本文整理汇总了Java中org.bitcoinj.core.TransactionOutput类的典型用法代码示例。如果您正苦于以下问题:Java TransactionOutput类的具体用法?Java TransactionOutput怎么用?Java TransactionOutput使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
TransactionOutput类属于org.bitcoinj.core包,在下文中一共展示了TransactionOutput类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getWalletAddressOfReceived
import org.bitcoinj.core.TransactionOutput; //导入依赖的package包/类
@Nullable
public static Address getWalletAddressOfReceived(final Transaction tx, final Wallet wallet) {
for (final TransactionOutput output : tx.getOutputs()) {
try {
if (output.isMine(wallet)) {
final Script script = output.getScriptPubKey();
return script.getToAddress(Constants.NETWORK_PARAMETERS, true);
}
} catch (final ScriptException x) {
// swallow
}
}
return null;
}
示例2: isValidImprintingTransaction
import org.bitcoinj.core.TransactionOutput; //导入依赖的package包/类
/**
* Return true if the transaction in input is a valid imprinting transaction and contains the specified address in
* one of its output, otherwise false.
* @param tx the transaction to check if is valid imprinting
* @param networkParameters the {@link NetworkParameters}
* @param imprintingAddress the address to check for
* @return true if it's an imprinting transaction otherwise false
*/
public static boolean isValidImprintingTransaction(Transaction tx, NetworkParameters networkParameters, Address imprintingAddress) {
// Retrieve sender
String sender = tx.getInput(0).getFromAddress().toBase58();
// Check output
List<TransactionOutput> transactionOutputs = tx.getOutputs();
for (TransactionOutput to : transactionOutputs) {
Address address = to.getAddressFromP2PKHScript(networkParameters);
if (address != null && address.equals(imprintingAddress)) {
return true;
}
}
return false;
}
示例3: markKeysAsUsed
import org.bitcoinj.core.TransactionOutput; //导入依赖的package包/类
/**
* Marks all keys used in the transaction output as used in the wallet.
* See {@link org.bitcoinj.wallet.DeterministicKeyChain#markKeyAsUsed(DeterministicKey)} for more info on this.
*/
private void markKeysAsUsed(Transaction tx) {
keyChainGroupLock.lock();
try {
for (TransactionOutput o : tx.getOutputs()) {
try {
Script script = o.getScriptPubKey();
if (script.isSentToRawPubKey()) {
byte[] pubkey = script.getPubKey();
keyChainGroup.markPubKeyAsUsed(pubkey);
} else if (script.isSentToAddress()) {
byte[] pubkeyHash = script.getPubKeyHash();
keyChainGroup.markPubKeyHashAsUsed(pubkeyHash);
} else if (script.isPayToScriptHash()) {
Address a = Address.fromP2SHScript(tx.getParams(), script);
keyChainGroup.markP2SHAddressAsUsed(a);
}
} catch (ScriptException e) {
// Just means we didn't understand the output of this transaction: ignore it.
log.warn("Could not parse tx output script: {}", e.toString());
}
}
} finally {
keyChainGroupLock.unlock();
}
}
示例4: 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;
}
示例5: 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();
}
}
示例6: getBalance
import org.bitcoinj.core.TransactionOutput; //导入依赖的package包/类
/**
* Returns the balance of this wallet as calculated by the provided balanceType.
*/
public Coin getBalance(BalanceType balanceType) {
lock.lock();
try {
if (balanceType == BalanceType.AVAILABLE || balanceType == BalanceType.AVAILABLE_SPENDABLE) {
List<TransactionOutput> candidates = calculateAllSpendCandidates(true, balanceType == BalanceType.AVAILABLE_SPENDABLE);
CoinSelection selection = coinSelector.select(NetworkParameters.MAX_MONEY, candidates);
return selection.valueGathered;
} else if (balanceType == BalanceType.ESTIMATED || balanceType == BalanceType.ESTIMATED_SPENDABLE) {
List<TransactionOutput> all = calculateAllSpendCandidates(false, balanceType == BalanceType.ESTIMATED_SPENDABLE);
Coin value = Coin.ZERO;
for (TransactionOutput out : all) value = value.add(out.getValue());
return value;
} else {
throw new AssertionError("Unknown balance type"); // Unreachable.
}
} finally {
lock.unlock();
}
}
示例7: getTotalReceived
import org.bitcoinj.core.TransactionOutput; //导入依赖的package包/类
/**
* Returns the amount of bitcoin ever received via output. <b>This is not the balance!</b> If an output spends from a
* transaction whose inputs are also to our wallet, the input amounts are deducted from the outputs contribution, with a minimum of zero
* contribution. The idea behind this is we avoid double counting money sent to us.
* @return the total amount of satoshis received, regardless of whether it was spent or not.
*/
public Coin getTotalReceived() {
Coin total = Coin.ZERO;
// Include outputs to us if they were not just change outputs, ie the inputs to us summed to less
// than the outputs to us.
for (Transaction tx: transactions.values()) {
Coin txTotal = Coin.ZERO;
for (TransactionOutput output : tx.getOutputs()) {
if (output.isMine(this)) {
txTotal = txTotal.add(output.getValue());
}
}
for (TransactionInput in : tx.getInputs()) {
TransactionOutput prevOut = in.getConnectedOutput();
if (prevOut != null && prevOut.isMine(this)) {
txTotal = txTotal.subtract(prevOut.getValue());
}
}
if (txTotal.isPositive()) {
total = total.add(txTotal);
}
}
return total;
}
示例8: calculateAllSpendCandidates
import org.bitcoinj.core.TransactionOutput; //导入依赖的package包/类
/**
* Returns a list of all outputs that are being tracked by this wallet either from the {@link UTXOProvider}
* (in this case the existence or not of private keys is ignored), or the wallets internal storage (the default)
* taking into account the flags.
*
* @param excludeImmatureCoinbases Whether to ignore coinbase outputs that we will be able to spend in future once they mature.
* @param excludeUnsignable Whether to ignore outputs that we are tracking but don't have the keys to sign for.
*/
public List<TransactionOutput> calculateAllSpendCandidates(boolean excludeImmatureCoinbases, boolean excludeUnsignable) {
lock.lock();
try {
List<TransactionOutput> candidates;
if (vUTXOProvider == null) {
candidates = new ArrayList<>(myUnspents.size());
for (TransactionOutput output : myUnspents) {
if (excludeUnsignable && !canSignFor(output.getScriptPubKey())) continue;
Transaction transaction = checkNotNull(output.getParentTransaction());
if (excludeImmatureCoinbases && !transaction.isMature())
continue;
candidates.add(output);
}
} else {
candidates = calculateAllSpendCandidatesFromUTXOProvider(excludeImmatureCoinbases);
}
return candidates;
} finally {
lock.unlock();
}
}
示例9: calcBloomOutPointsLocked
import org.bitcoinj.core.TransactionOutput; //导入依赖的package包/类
private void calcBloomOutPointsLocked() {
// TODO: This could be done once and then kept up to date.
bloomOutPoints.clear();
Set<Transaction> all = new HashSet<>();
all.addAll(unspent.values());
all.addAll(spent.values());
all.addAll(pending.values());
for (Transaction tx : all) {
for (TransactionOutput out : tx.getOutputs()) {
try {
if (isTxOutputBloomFilterable(out))
bloomOutPoints.add(out.getOutPointFor());
} catch (ScriptException e) {
// If it is ours, we parsed the script correctly, so this shouldn't happen.
throw new RuntimeException(e);
}
}
}
}
示例10: estimateBytesForSigning
import org.bitcoinj.core.TransactionOutput; //导入依赖的package包/类
private int estimateBytesForSigning(CoinSelection selection) {
int size = 0;
for (TransactionOutput output : selection.gathered) {
try {
Script script = output.getScriptPubKey();
ECKey key = null;
Script redeemScript = null;
if (script.isSentToAddress()) {
key = findKeyFromPubHash(script.getPubKeyHash());
checkNotNull(key, "Coin selection includes unspendable outputs");
} else if (script.isPayToScriptHash()) {
redeemScript = findRedeemDataFromScriptHash(script.getPubKeyHash()).redeemScript;
checkNotNull(redeemScript, "Coin selection includes unspendable outputs");
}
size += script.getNumberOfBytesRequiredToSpend(key, redeemScript);
} catch (ScriptException e) {
// If this happens it means an output script in a wallet tx could not be understood. That should never
// happen, if it does it means the wallet has got into an inconsistent state.
throw new IllegalStateException(e);
}
}
return size;
}
示例11: 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;
}
示例12: select
import org.bitcoinj.core.TransactionOutput; //导入依赖的package包/类
@Override
public CoinSelection select(Coin target, List<TransactionOutput> candidates) {
ArrayList<TransactionOutput> selected = new ArrayList<>();
// Sort the inputs by age*value so we get the highest "coindays" spent.
// TODO: Consider changing the wallets internal format to track just outputs and keep them ordered.
ArrayList<TransactionOutput> sortedOutputs = new ArrayList<>(candidates);
// When calculating the wallet balance, we may be asked to select all possible coins, if so, avoid sorting
// them in order to improve performance.
// TODO: Take in network parameters when instanatiated, and then test against the current network. Or just have a boolean parameter for "give me everything"
if (!target.equals(NetworkParameters.MAX_MONEY)) {
sortOutputs(sortedOutputs);
}
// Now iterate over the sorted outputs until we have got as close to the target as possible or a little
// bit over (excessive value will be change).
long total = 0;
for (TransactionOutput output : sortedOutputs) {
if (total >= target.value) break;
// Only pick chain-included transactions, or transactions that are ours and pending.
if (!shouldSelect(output.getParentTransaction())) continue;
selected.add(output);
total += output.getValue().value;
}
// Total may be lower than target here, if the given candidates were insufficient to create to requested
// transaction.
return new CoinSelection(Coin.valueOf(total), selected);
}
示例13: sortOutputs
import org.bitcoinj.core.TransactionOutput; //导入依赖的package包/类
@VisibleForTesting static void sortOutputs(ArrayList<TransactionOutput> outputs) {
Collections.sort(outputs, new Comparator<TransactionOutput>() {
@Override
public int compare(TransactionOutput a, TransactionOutput b) {
int depth1 = a.getParentTransactionDepthInBlocks();
int depth2 = b.getParentTransactionDepthInBlocks();
Coin aValue = a.getValue();
Coin bValue = b.getValue();
BigInteger aCoinDepth = BigInteger.valueOf(aValue.value).multiply(BigInteger.valueOf(depth1));
BigInteger bCoinDepth = BigInteger.valueOf(bValue.value).multiply(BigInteger.valueOf(depth2));
int c1 = bCoinDepth.compareTo(aCoinDepth);
if (c1 != 0) return c1;
// The "coin*days" destroyed are equal, sort by value alone to get the lowest transaction size.
int c2 = bValue.compareTo(aValue);
if (c2 != 0) return c2;
// They are entirely equivalent (possibly pending) so sort by hash to ensure a total ordering.
BigInteger aHash = a.getParentTransactionHash().toBigInteger();
BigInteger bHash = b.getParentTransactionHash().toBigInteger();
return aHash.compareTo(bHash);
}
});
}
示例14: getUnlockedUnspentOutputs
import org.bitcoinj.core.TransactionOutput; //导入依赖的package包/类
private List<TransactionOutput> getUnlockedUnspentOutputs() {
final List<TransactionOutput> outputs = new ArrayList<>();
final List<TransactionOutput> candidates = wallet.calculateAllSpendCandidates(false, false);
final long currentTimeSec = org.bitcoinj.core.Utils.currentTimeSeconds();
for (TransactionOutput txOut : candidates) {
byte[] addressHash = txOut.getScriptPubKey().getPubKeyHash();
TimeLockedAddress tla = findTimeLockedAddressByHash(addressHash);
if (tla != null) {
long lockTime = tla.getLockTime();
if (BitcoinUtils.isAfterLockTime(currentTimeSec, lockTime)) {
outputs.add(txOut);
Log.d(TAG, "getUnlockedUnspentOutputs - unlocked output: " + txOut);
}
}
}
return outputs;
}
示例15: signTransaction
import org.bitcoinj.core.TransactionOutput; //导入依赖的package包/类
private List<TransactionSignature> signTransaction(Transaction tx) throws CoinbleskException {
final List<TransactionInput> inputs = tx.getInputs();
final List<TransactionSignature> signatures = new ArrayList<>(inputs.size());
for (int i = 0; i < inputs.size(); ++i) {
TransactionInput txIn = inputs.get(i);
TransactionOutput prevTxOut = txIn.getConnectedOutput();
byte[] sentToHash = prevTxOut.getScriptPubKey().getPubKeyHash();
TimeLockedAddress tla = findTimeLockedAddressByHash(sentToHash);
if (tla == null) {
throw new CoinbleskException(String.format(Locale.US,
"Could not sign input (index=%d, pubKeyHash=%s)",
i, org.bitcoinj.core.Utils.HEX.encode(sentToHash)));
}
byte[] redeemScript = tla.createRedeemScript().getProgram();
TransactionSignature signature = tx.calculateSignature(
i, multisigClientKey, redeemScript, Transaction.SigHash.ALL, false);
signatures.add(signature);
}
return signatures;
}