本文整理汇总了Java中org.bitcoinj.core.TransactionOutput.isAvailableForSpending方法的典型用法代码示例。如果您正苦于以下问题:Java TransactionOutput.isAvailableForSpending方法的具体用法?Java TransactionOutput.isAvailableForSpending怎么用?Java TransactionOutput.isAvailableForSpending使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.bitcoinj.core.TransactionOutput
的用法示例。
在下文中一共展示了TransactionOutput.isAvailableForSpending方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: isTxConsistent
import org.bitcoinj.core.TransactionOutput; //导入方法依赖的package包/类
@VisibleForTesting
boolean isTxConsistent(final Transaction tx, final boolean isSpent) {
boolean isActuallySpent = true;
for (TransactionOutput o : tx.getOutputs()) {
if (o.isAvailableForSpending()) {
if (o.isMineOrWatched(this)) isActuallySpent = false;
if (o.getSpentBy() != null) {
log.error("isAvailableForSpending != spentBy");
return false;
}
} else {
if (o.getSpentBy() == null) {
log.error("isAvailableForSpending != spentBy");
return false;
}
}
}
return isActuallySpent == isSpent;
}
示例2: getWatchedOutputs
import org.bitcoinj.core.TransactionOutput; //导入方法依赖的package包/类
/**
* Returns all the outputs that match addresses or scripts added via {@link #addWatchedAddress(Address)} or
* {@link #addWatchedScripts(java.util.List)}.
* @param excludeImmatureCoinbases Whether to ignore outputs that are unspendable due to being immature.
*/
public List<TransactionOutput> getWatchedOutputs(boolean excludeImmatureCoinbases) {
lock.lock();
keyChainGroupLock.lock();
try {
LinkedList<TransactionOutput> candidates = Lists.newLinkedList();
for (Transaction tx : Iterables.concat(unspent.values(), pending.values())) {
if (excludeImmatureCoinbases && !tx.isMature()) continue;
for (TransactionOutput output : tx.getOutputs()) {
if (!output.isAvailableForSpending()) continue;
try {
Script scriptPubKey = output.getScriptPubKey();
if (!watchedScripts.contains(scriptPubKey)) continue;
candidates.add(output);
} catch (ScriptException e) {
// Ignore
}
}
}
return candidates;
} finally {
keyChainGroupLock.unlock();
lock.unlock();
}
}
示例3: childPaysForParent
import org.bitcoinj.core.TransactionOutput; //导入方法依赖的package包/类
/**
* Construct a SendRequest for a CPFP (child-pays-for-parent) transaction. The resulting transaction is already
* completed, so you should directly proceed to signing and broadcasting/committing the transaction. CPFP is
* currently only supported by a few miners, so use with care.
*/
public static SendRequest childPaysForParent(Wallet wallet, Transaction parentTransaction, Coin feeRaise) {
TransactionOutput outputToSpend = null;
for (final TransactionOutput output : parentTransaction.getOutputs()) {
if (output.isMine(wallet) && output.isAvailableForSpending()
&& output.getValue().isGreaterThan(feeRaise)) {
outputToSpend = output;
break;
}
}
// TODO spend another confirmed output of own wallet if needed
checkNotNull(outputToSpend, "Can't find adequately sized output that spends to us");
final Transaction tx = new Transaction(parentTransaction.getParams());
tx.addInput(outputToSpend);
tx.addOutput(outputToSpend.getValue().subtract(feeRaise), wallet.freshAddress(KeyPurpose.CHANGE));
tx.setPurpose(Transaction.Purpose.RAISE_FEE);
final SendRequest req = forTx(tx);
req.completed = true;
return req;
}
示例4: getMines
import org.bitcoinj.core.TransactionOutput; //导入方法依赖的package包/类
private List<TransactionOutput> getMines(Address address) {
Map<Sha256Hash, Transaction> unspent = wallet.getTransactionPool(WalletTransaction.Pool.UNSPENT);
List<TransactionOutput> transactionOutputList= new ArrayList<>();
for (Map.Entry<Sha256Hash, Transaction> entry : unspent.entrySet()) {
Transaction current = entry.getValue();
List<TransactionOutput> outputs = current.getOutputs();
for (TransactionOutput o : outputs) {
if(o.isAvailableForSpending()) {
Address a = o.getAddressFromP2PKHScript(PARAMS);
if(address.equals(a)) {
transactionOutputList.add(o);
}
}
}
}
return transactionOutputList;
}
示例5: addWalletTransaction
import org.bitcoinj.core.TransactionOutput; //导入方法依赖的package包/类
/**
* Adds the given transaction to the given pools and registers a confidence change listener on it.
*/
private void addWalletTransaction(Pool pool, Transaction tx) {
checkState(lock.isHeldByCurrentThread());
transactions.put(tx.getHash(), tx);
switch (pool) {
case UNSPENT:
checkState(unspent.put(tx.getHash(), tx) == null);
break;
case SPENT:
checkState(spent.put(tx.getHash(), tx) == null);
break;
case PENDING:
checkState(pending.put(tx.getHash(), tx) == null);
break;
case DEAD:
checkState(dead.put(tx.getHash(), tx) == null);
break;
default:
throw new RuntimeException("Unknown wallet transaction type " + pool);
}
if (pool == Pool.UNSPENT || pool == Pool.PENDING) {
for (TransactionOutput output : tx.getOutputs()) {
if (output.isAvailableForSpending() && output.isMineOrWatched(this))
myUnspents.add(output);
}
}
// This is safe even if the listener has been added before, as TransactionConfidence ignores duplicate
// registration requests. That makes the code in the wallet simpler.
tx.getConfidence().addEventListener(Threading.SAME_THREAD, txConfidenceListener);
}
示例6: findSpendableOutput
import org.bitcoinj.core.TransactionOutput; //导入方法依赖的package包/类
private static @Nullable TransactionOutput findSpendableOutput(final Wallet wallet, final Transaction transaction,
final Coin minimumOutputValue) {
for (final TransactionOutput output : transaction.getOutputs()) {
if (output.isMine(wallet) && output.isAvailableForSpending()
&& output.getValue().isGreaterThan(minimumOutputValue))
return output;
}
return null;
}
示例7: updateV1toV2
import org.bitcoinj.core.TransactionOutput; //导入方法依赖的package包/类
private static void updateV1toV2(Wallet wallet) {
checkState(wallet.getVersion() < 2, "Can update only from version < 2");
wallet.setVersion(2);
for (WalletAccount walletAccount : wallet.getAllAccounts()) {
if (walletAccount instanceof WalletPocketHD) {
WalletPocketHD account = (WalletPocketHD) walletAccount;
// Force resync
account.addressesStatus.clear();
// Gather hashes to trim them later
Set<Sha256Hash> txHashes = new HashSet<>(account.rawTransactions.size());
// Reconstruct UTXO set
for (BitTransaction tx : account.rawTransactions.values()) {
txHashes.add(tx.getHash());
for (TransactionOutput txo : tx.getOutputs()) {
if (txo.isAvailableForSpending() && txo.isMineOrWatched(account)) {
OutPointOutput utxo = new OutPointOutput(tx, txo.getIndex());
if (tx.getConfidenceType() == BUILDING) {
utxo.setAppearedAtChainHeight(tx.getAppearedAtChainHeight());
utxo.setDepthInBlocks(tx.getDepthInBlocks());
}
account.unspentOutputs.put(utxo.getOutPoint(), utxo);
}
}
}
// Trim transactions
for (Sha256Hash txHash : txHashes) {
account.trimTransactionIfNeeded(txHash);
}
}
}
}
示例8: findSpendableOutput
import org.bitcoinj.core.TransactionOutput; //导入方法依赖的package包/类
private static @Nullable TransactionOutput findSpendableOutput(final Wallet wallet, final Transaction transaction)
{
for (final TransactionOutput output : transaction.getOutputs())
{
if (output.isMine(wallet) && output.isAvailableForSpending() && output.getValue().isGreaterThan(FEE_RAISE))
return output;
}
return null;
}
示例9: getUnspentOutputsOfAddress
import org.bitcoinj.core.TransactionOutput; //导入方法依赖的package包/类
@RequestMapping(value = "/payment/utxo", method = GET, produces = APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public List<UnspentTransactionOutputDTO> getUnspentOutputsOfAddress(@NotNull @Valid @RequestParam("address") String addressString) throws BusinessException {
UserAccount user = getAuthenticatedUser();
if(user.getAccount() == null || user.getAccount().getTimeLockedAddresses().size() == 0) {
throw new AccountNotFoundException();
}
TimeLockedAddressEntity foundTLA = null;
for(TimeLockedAddressEntity tla : user.getAccount().getTimeLockedAddresses()) {
if (addressString.equals(tla.toAddress(appConfig.getNetworkParameters()).toString())) {
foundTLA = tla;
}
}
if(foundTLA == null) {
throw new InvalidAddressException();
}
List<TransactionOutput> UTXOs = walletService.getUTXOByAddress(foundTLA.toAddress(appConfig.getNetworkParameters()));
List<UnspentTransactionOutputDTO> unspentOutputs = new ArrayList<>();
for(TransactionOutput utxo : UTXOs) {
if(!utxo.isAvailableForSpending()) {
throw new CoinbleskInternalError("The unspent transaction output is not available for spending -> walletService returns wrong transaction outputs.");
}
UnspentTransactionOutputDTO utxoDTO = new UnspentTransactionOutputDTO();
utxoDTO.setValue(utxo.getValue().longValue());
utxoDTO.setIndex(utxo.getIndex());
utxoDTO.setTransaction(SerializeUtils.bytesToHex(utxo.getParentTransaction().bitcoinSerialize()));
unspentOutputs.add(utxoDTO);
}
return unspentOutputs;
}
示例10: appendApplicationInfo
import org.bitcoinj.core.TransactionOutput; //导入方法依赖的package包/类
public static void appendApplicationInfo(final Appendable report, final WalletApplication application)
throws IOException {
final PackageInfo pi = application.packageInfo();
final Configuration configuration = application.getConfiguration();
final Calendar calendar = new GregorianCalendar(UTC);
report.append("Version: " + pi.versionName + " (" + pi.versionCode + ")\n");
report.append("Package: " + pi.packageName + "\n");
report.append("Installer: " + application.getPackageManager().getInstallerPackageName(pi.packageName) + "\n");
report.append("Test/Prod: " + (Constants.TEST ? "test" : "prod") + "\n");
report.append("Timezone: " + TimeZone.getDefault().getID() + "\n");
calendar.setTimeInMillis(System.currentTimeMillis());
report.append("Time: " + String.format(Locale.US, "%tF %tT %tZ", calendar, calendar, calendar) + "\n");
calendar.setTimeInMillis(WalletApplication.TIME_CREATE_APPLICATION);
report.append(
"Time of launch: " + String.format(Locale.US, "%tF %tT %tZ", calendar, calendar, calendar) + "\n");
calendar.setTimeInMillis(pi.lastUpdateTime);
report.append(
"Time of last update: " + String.format(Locale.US, "%tF %tT %tZ", calendar, calendar, calendar) + "\n");
calendar.setTimeInMillis(pi.firstInstallTime);
report.append("Time of first install: " + String.format(Locale.US, "%tF %tT %tZ", calendar, calendar, calendar)
+ "\n");
final long lastBackupTime = configuration.getLastBackupTime();
calendar.setTimeInMillis(lastBackupTime);
report.append("Time of backup: "
+ (lastBackupTime > 0 ? String.format(Locale.US, "%tF %tT %tZ", calendar, calendar, calendar) : "none")
+ "\n");
report.append("Network: " + Constants.NETWORK_PARAMETERS.getId() + "\n");
final Wallet wallet = application.getWallet();
report.append("Encrypted: " + wallet.isEncrypted() + "\n");
report.append("Keychain size: " + wallet.getKeyChainGroupSize() + "\n");
final Set<Transaction> transactions = wallet.getTransactions(true);
int numInputs = 0;
int numOutputs = 0;
int numSpentOutputs = 0;
for (final Transaction tx : transactions) {
numInputs += tx.getInputs().size();
final List<TransactionOutput> outputs = tx.getOutputs();
numOutputs += outputs.size();
for (final TransactionOutput txout : outputs) {
if (!txout.isAvailableForSpending())
numSpentOutputs++;
}
}
report.append("Transactions: " + transactions.size() + "\n");
report.append("Inputs: " + numInputs + "\n");
report.append("Outputs: " + numOutputs + " (spent: " + numSpentOutputs + ")\n");
report.append(
"Last block seen: " + wallet.getLastBlockSeenHeight() + " (" + wallet.getLastBlockSeenHash() + ")\n");
report.append("Databases:");
for (final String db : application.databaseList())
report.append(" " + db);
report.append("\n");
final File filesDir = application.getFilesDir();
report.append("\nContents of FilesDir " + filesDir + ":\n");
appendDir(report, filesDir, 0);
}
示例11: connectTransactionOutputs
import org.bitcoinj.core.TransactionOutput; //导入方法依赖的package包/类
private BitWalletTransaction connectTransactionOutputs(Protos.Transaction txProto) throws UnreadableWalletException {
BitTransaction tx = txMap.get(txProto.getHash());
final WalletTransaction.Pool pool;
switch (txProto.getPool()) {
case PENDING: pool = WalletTransaction.Pool.PENDING; break;
case SPENT:
case UNSPENT: pool = WalletTransaction.Pool.CONFIRMED; break;
case DEAD:
default:
throw new UnreadableWalletException("Unknown transaction pool: " + txProto.getPool());
}
for (int i = 0 ; i < tx.getOutputs(false).size() ; i++) {
TransactionOutput output = tx.getOutputs().get(i);
final Protos.TransactionOutput transactionOutput = txProto.getTransactionOutput(i);
if (tx.isTrimmed()) {
if (transactionOutput.getIsSpent() && output.isAvailableForSpending()) {
output.markAsSpent(null);
}
} else {
if (transactionOutput.hasSpentByTransactionHash()) {
final ByteString spentByTransactionHash = transactionOutput.getSpentByTransactionHash();
BitTransaction spendingTx = txMap.get(spentByTransactionHash);
if (spendingTx == null || spendingTx.isTrimmed()) {
throw new UnreadableWalletException(String.format("Could not connect %s to %s",
tx.getHashAsString(), byteStringToHash(spentByTransactionHash)));
}
final int spendingIndex = transactionOutput.getSpentByTransactionIndex();
TransactionInput input = checkNotNull(spendingTx.getRawTransaction().getInput(spendingIndex), "A spending index does not exist");
input.connect(output);
}
}
}
if (txProto.hasConfidence()) {
Protos.TransactionConfidence confidenceProto = txProto.getConfidence();
Transaction rawTx = tx.getRawTransaction();
TransactionConfidence confidence = rawTx.getConfidence();
readConfidence(rawTx, confidenceProto, confidence);
}
return new BitWalletTransaction(pool, tx);
}
示例12: appendApplicationInfo
import org.bitcoinj.core.TransactionOutput; //导入方法依赖的package包/类
public static void appendApplicationInfo(final Appendable report, final WalletApplication application) throws IOException
{
final PackageInfo pi = application.packageInfo();
final Configuration configuration = application.getConfiguration();
final long now = System.currentTimeMillis();
report.append("Version: " + pi.versionName + " (" + pi.versionCode + ")\n");
report.append("Package: " + pi.packageName + "\n");
report.append("Test/Prod: " + (Constants.TEST ? "test" : "prod") + "\n");
report.append("Time: " + String.format(Locale.US, "%tF %tT %tz", now, now, now) + "\n");
report.append("Time of launch: "
+ String.format(Locale.US, "%tF %tT %tz", TIME_CREATE_APPLICATION, TIME_CREATE_APPLICATION, TIME_CREATE_APPLICATION) + "\n");
report.append("Time of last update: " + String.format(Locale.US, "%tF %tT %tz", pi.lastUpdateTime, pi.lastUpdateTime, pi.lastUpdateTime)
+ "\n");
report.append("Time of first install: "
+ String.format(Locale.US, "%tF %tT %tz", pi.firstInstallTime, pi.firstInstallTime, pi.firstInstallTime) + "\n");
final long lastBackupTime = configuration.getLastBackupTime();
report.append("Time of backup: "
+ (lastBackupTime > 0 ? String.format(Locale.US, "%tF %tT %tz", lastBackupTime, lastBackupTime, lastBackupTime) : "none") + "\n");
report.append("Network: " + Constants.NETWORK_PARAMETERS.getId() + "\n");
final Wallet wallet = application.getWallet();
report.append("Encrypted: " + wallet.isEncrypted() + "\n");
report.append("Keychain size: " + wallet.getKeychainSize() + "\n");
final DevicePolicyManager devicePolicyManager = (DevicePolicyManager) application.getSystemService(Context.DEVICE_POLICY_SERVICE);
report.append("Storage Encryption Status: " + devicePolicyManager.getStorageEncryptionStatus() + "\n");
final Set<Transaction> transactions = wallet.getTransactions(true);
int numInputs = 0;
int numOutputs = 0;
int numSpentOutputs = 0;
for (final Transaction tx : transactions)
{
numInputs += tx.getInputs().size();
final List<TransactionOutput> outputs = tx.getOutputs();
numOutputs += outputs.size();
for (final TransactionOutput txout : outputs)
{
if (!txout.isAvailableForSpending())
numSpentOutputs++;
}
}
report.append("Transactions: " + transactions.size() + "\n");
report.append("Inputs: " + numInputs + "\n");
report.append("Outputs: " + numOutputs + " (spent: " + numSpentOutputs + ")\n");
report.append("Last block seen: " + wallet.getLastBlockSeenHeight() + " (" + wallet.getLastBlockSeenHash() + ")\n");
report.append("Databases:");
for (final String db : application.databaseList())
report.append(" " + db);
report.append("\n");
final File filesDir = application.getFilesDir();
report.append("\nContents of FilesDir " + filesDir + ":\n");
appendDir(report, filesDir, 0);
final File logDir = application.getDir("log", Context.MODE_PRIVATE);
report.append("\nContents of LogDir " + logDir + ":\n");
appendDir(report, logDir, 0);
}
示例13: checkInputs
import org.bitcoinj.core.TransactionOutput; //导入方法依赖的package包/类
/***
* Checks all inputs for validity.
*
* @param tx The transaction to check
* @param accountSender Every input must be from an address from this account
* @param neededFeeInSatoshi Fee in Satoshi/Byte that the given transaction should have
* @return long (UNIX timestamp) that indicates then when the first address used is unlocked
*/
private long checkInputs(Transaction tx, Account accountSender, int neededFeeInSatoshi) {
Coin valueOfInputs = Coin.ZERO;
long earliestLockTime = Long.MAX_VALUE;
for (int i=0; i<tx.getInputs().size(); i++) {
TransactionInput input = tx.getInput(i);
TransactionOutput out = walletService.findOutputFor(input);
if (out == null) {
throw new RuntimeException("Transaction spends unknown UTXOs");
}
valueOfInputs = valueOfInputs.add(out.getValue());
if (!out.isAvailableForSpending()) {
throw new RuntimeException("Input is already spent");
}
if (out.getParentTransactionDepthInBlocks() < 1) {
throw new RuntimeException("UTXO must be mined");
}
Address fromAddress = out.getAddressFromP2SH(appConfig.getNetworkParameters());
if (fromAddress == null) {
throw new RuntimeException("Transaction must spent P2SH addresses");
}
TimeLockedAddressEntity tlaEntity = timeLockedAddressRepository.findByAddressHash(fromAddress.getHash160());
if (tlaEntity == null) {
throw new RuntimeException("Used TLA inputs are not known to server");
}
if (!tlaEntity.getAccount().equals(accountSender)) {
throw new RuntimeException("Inputs must be from sender account");
}
final Instant minimumLockedUntil = Instant.now()
.plus(Duration.ofSeconds(appConfig.getMinimumLockTimeSeconds()));
if (Instant.ofEpochSecond(tlaEntity.getLockTime()).isBefore(minimumLockedUntil)) {
throw new RuntimeException("Inputs must be locked at least until " + minimumLockedUntil);
}
earliestLockTime = Math.min(earliestLockTime, tlaEntity.getLockTime());
Script spendingScript = input.getScriptSig();
if (spendingScript.getChunks().size() == 0) {
throw new RuntimeException("Input was not signed");
}
if (spendingScript.getChunks().size() != 1 || !spendingScript.getChunks().get(0).isPushData()) {
throw new RuntimeException("Signature for input had wrong format");
}
byte[] redeemScript = tlaEntity.getRedeemScript();
final ECKey serverPrivateKey = ECKey.fromPrivateAndPrecalculatedPublic(accountSender.serverPrivateKey(),
accountSender.serverPublicKey());
TransactionSignature serverSig = tx.calculateSignature(i, serverPrivateKey, redeemScript, SigHash.ALL,
false);
Script finalSig = new ScriptBuilder(spendingScript).data(serverSig.encodeToBitcoin()).smallNum(1).data
(redeemScript).build();
input.setScriptSig(finalSig);
finalSig.correctlySpends(tx, i, out.getScriptPubKey(), Script.ALL_VERIFY_FLAGS);
}
// Check fee
Coin givenFee = valueOfInputs.minus(tx.getOutputSum());
Coin neededFee = Coin.valueOf(neededFeeInSatoshi * tx.bitcoinSerialize().length);
if (givenFee.isLessThan(neededFee)) {
throw new RuntimeException("Insufficient transaction fee. Given: " + givenFee.divide(tx.bitcoinSerialize()
.length) + " satoshi per byte. Needed: " + neededFee.divide(tx.bitcoinSerialize().length));
}
return earliestLockTime;
}