Java Code Examples for org.bitcoinj.core.TransactionOutput#getValue()

The following examples show how to use org.bitcoinj.core.TransactionOutput#getValue() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DefaultCoinSelector.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@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);
}
 
Example 2
Source File: DefaultCoinSelector.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@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);
}
 
Example 3
Source File: UnconfirmedTxOutput.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public static UnconfirmedTxOutput fromTransactionOutput(TransactionOutput transactionOutput) {
    Transaction parentTransaction = transactionOutput.getParentTransaction();
    if (parentTransaction != null) {
        return new UnconfirmedTxOutput(transactionOutput.getIndex(),
                transactionOutput.getValue().value,
                parentTransaction.getHashAsString());
    } else {
        log.warn("parentTransaction of transactionOutput is null. " +
                        "This must not happen. " +
                        "We could throw an exception as well " +
                        "here but we prefer to be for now more tolerant and just " +
                        "assign the value 0 if that would be the case. transactionOutput={}",
                transactionOutput);
        return new UnconfirmedTxOutput(transactionOutput.getIndex(),
                0,
                "null");
    }
}
 
Example 4
Source File: BsqWalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public Transaction signTx(Transaction tx) throws WalletException, TransactionVerificationException {
    for (int i = 0; i < tx.getInputs().size(); i++) {
        TransactionInput txIn = tx.getInputs().get(i);
        TransactionOutput connectedOutput = txIn.getConnectedOutput();
        if (connectedOutput != null && connectedOutput.isMine(wallet)) {
            signTransactionInput(wallet, aesKey, tx, txIn, i);
            checkScriptSig(tx, txIn, i);
        }
    }

    for (TransactionOutput txo : tx.getOutputs()) {
        Coin value = txo.getValue();
        // OpReturn outputs have value 0
        if (value.isPositive()) {
            checkArgument(Restrictions.isAboveDust(txo.getValue()),
                    "An output value is below dust limit. Transaction=" + tx);
        }
    }

    checkWalletConsistency(wallet);
    verifyTransaction(tx);
    printTx("BSQ wallet: Signed Tx", tx);
    return tx;
}
 
Example 5
Source File: DefaultCoinSelector.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@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);
}
 
Example 6
Source File: MyceliumCoinSelector.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@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);
}
 
Example 7
Source File: BisqDefaultCoinSelector.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
@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 "coin days" spent.
    ArrayList<TransactionOutput> sortedOutputs = new ArrayList<>(candidates);
    // If we spend all we don't need to sort
    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;
    long targetValue = target.value;
    for (TransactionOutput output : sortedOutputs) {
        if (total >= targetValue) {
            long change = total - targetValue;
            if (change == 0 || change >= Restrictions.getMinNonDustOutput().value)
                break;
        }

        if (output.getParentTransaction() != null &&
                isTxSpendable(output.getParentTransaction()) &&
                isTxOutputSpendable(output)) {
            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);
}
 
Example 8
Source File: BsqWalletService.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Coin getValueSentToMeForTransaction(Transaction transaction) throws ScriptException {
    Coin result = Coin.ZERO;
    final String txId = transaction.getHashAsString();
    // We check if we have a matching BSQ tx. We do that call here to avoid repeated calls in the loop.
    Optional<Tx> txOptional = bsqStateService.getTx(txId);
    // We check all the outputs of our tx
    for (int i = 0; i < transaction.getOutputs().size(); i++) {
        TransactionOutput output = transaction.getOutputs().get(i);
        final boolean isConfirmed = output.getParentTransaction() != null &&
                output.getParentTransaction().getConfidence().getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING;
        if (output.isMineOrWatched(wallet)) {
            if (isConfirmed) {
                if (txOptional.isPresent()) {
                    // The index of the BSQ tx outputs are the same like the bitcoinj tx outputs
                    TxOutput txOutput = txOptional.get().getTxOutputs().get(i);
                    if (bsqStateService.isBsqTxOutputType(txOutput)) {
                        //TODO check why values are not the same
                        if (txOutput.getValue() != output.getValue().value) {
                            log.warn("getValueSentToMeForTransaction: Value of BSQ output do not match BitcoinJ tx output. " +
                                            "txOutput.getValue()={}, output.getValue().value={}, txId={}",
                                    txOutput.getValue(), output.getValue().value, txId);
                        }

                        // If it is a valid BSQ output we add it
                        result = result.add(Coin.valueOf(txOutput.getValue()));
                    }
                }
            } /*else {
                // TODO atm we don't display amounts of unconfirmed txs but that might change so we leave that code
                // if it will be required
                // If the tx is not confirmed yet we add the value and assume it is a valid BSQ output.
                result = result.add(output.getValue());
            }*/
        }
    }
    return result;
}
 
Example 9
Source File: BisqDefaultCoinSelector.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@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 "coin days" spent.
    ArrayList<TransactionOutput> sortedOutputs = new ArrayList<>(candidates);
    // If we spend all we don't need to sort
    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;
    long targetValue = target.value;
    for (TransactionOutput output : sortedOutputs) {
        if (!isDustAttackUtxo(output)) {
            if (total >= targetValue) {
                long change = total - targetValue;
                if (change == 0 || change >= Restrictions.getMinNonDustOutput().value)
                    break;
            }

            if (output.getParentTransaction() != null &&
                    isTxSpendable(output.getParentTransaction()) &&
                    isTxOutputSpendable(output)) {
                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);
}
 
Example 10
Source File: BsqWalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Coin getValueSentToMeForTransaction(Transaction transaction) throws ScriptException {
    Coin result = Coin.ZERO;
    final String txId = transaction.getHashAsString();
    // We check if we have a matching BSQ tx. We do that call here to avoid repeated calls in the loop.
    Optional<Tx> txOptional = daoStateService.getTx(txId);
    // We check all the outputs of our tx
    for (int i = 0; i < transaction.getOutputs().size(); i++) {
        TransactionOutput output = transaction.getOutputs().get(i);
        final boolean isConfirmed = output.getParentTransaction() != null &&
                output.getParentTransaction().getConfidence().getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING;
        if (output.isMineOrWatched(wallet)) {
            if (isConfirmed) {
                if (txOptional.isPresent()) {
                    // The index of the BSQ tx outputs are the same like the bitcoinj tx outputs
                    TxOutput txOutput = txOptional.get().getTxOutputs().get(i);
                    if (daoStateService.isBsqTxOutputType(txOutput)) {
                        //TODO check why values are not the same
                        if (txOutput.getValue() != output.getValue().value) {
                            log.warn("getValueSentToMeForTransaction: Value of BSQ output do not match BitcoinJ tx output. " +
                                            "txOutput.getValue()={}, output.getValue().value={}, txId={}",
                                    txOutput.getValue(), output.getValue().value, txId);
                        }

                        // If it is a valid BSQ output we add it
                        result = result.add(Coin.valueOf(txOutput.getValue()));
                    }
                }
            } /*else {
                // TODO atm we don't display amounts of unconfirmed txs but that might change so we leave that code
                // if it will be required
                // If the tx is not confirmed yet we add the value and assume it is a valid BSQ output.
                result = result.add(output.getValue());
            }*/
        }
    }
    return result;
}
 
Example 11
Source File: BsqWalletService.java    From bisq-core with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Coin getValueSentFromMeForTransaction(Transaction transaction) throws ScriptException {
    Coin result = Coin.ZERO;
    // We check all our inputs and get the connected outputs.
    for (int i = 0; i < transaction.getInputs().size(); i++) {
        TransactionInput input = transaction.getInputs().get(i);
        // We grab the connected output for that input
        TransactionOutput connectedOutput = input.getConnectedOutput();
        if (connectedOutput != null) {
            // We grab the parent tx of the connected output
            final Transaction parentTransaction = connectedOutput.getParentTransaction();
            final boolean isConfirmed = parentTransaction != null &&
                    parentTransaction.getConfidence().getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING;
            if (connectedOutput.isMineOrWatched(wallet)) {
                if (isConfirmed) {
                    // We lookup if we have a BSQ tx matching the parent tx
                    // We cannot make that findTx call outside of the loop as the parent tx can change at each iteration
                    Optional<Tx> txOptional = bsqStateService.getTx(parentTransaction.getHash().toString());
                    if (txOptional.isPresent()) {
                        TxOutput txOutput = txOptional.get().getTxOutputs().get(connectedOutput.getIndex());
                        if (bsqStateService.isBsqTxOutputType(txOutput)) {
                            //TODO check why values are not the same
                            if (txOutput.getValue() != connectedOutput.getValue().value)
                                log.warn("getValueSentToMeForTransaction: Value of BSQ output do not match BitcoinJ tx output. " +
                                                "txOutput.getValue()={}, output.getValue().value={}, txId={}",
                                        txOutput.getValue(), connectedOutput.getValue().value, txOptional.get().getId());

                            // If it is a valid BSQ output we add it
                            result = result.add(Coin.valueOf(txOutput.getValue()));
                        }
                    }
                } /*else {
                    // TODO atm we don't display amounts of unconfirmed txs but that might change so we leave that code
                    // if it will be required
                    // If the tx is not confirmed yet we add the value and assume it is a valid BSQ output.
                    result = result.add(connectedOutput.getValue());
                }*/
            }
        }
    }
    return result;
}
 
Example 12
Source File: Verifier.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
static Coin verify(final GaService service,
                   final Map<TransactionOutPoint, Coin> countedUtxoValues, final PreparedTransaction ptx,
                   final Address recipient, final Coin amount, final List<Boolean> input) {
    final int changeIdx;
    if (input == null)
        changeIdx = -1;
    else if (input.get(0))
        changeIdx = 0;
    else if (input.get(1))
        changeIdx = 1;
    else
        throw new IllegalArgumentException("Verification: Change output missing.");

    if (input != null && input.get(0) && input.get(1)) {
        // Shouldn't happen really. In theory user can send money to a new change address
        // of themselves which they've generated manually, but it's unlikely, so for
        // simplicity we don't handle it.
        throw new IllegalArgumentException("Verification: Cannot send to a change address.");
    }
    final TransactionOutput output = ptx.mDecoded.getOutputs().get(1 - Math.abs(changeIdx));
    if (recipient != null) {
        final Address gotAddress = output.getScriptPubKey().getToAddress(service.getNetworkParameters());
        if (!gotAddress.equals(recipient))
            throw new IllegalArgumentException("Verification: Invalid recipient address.");
    }
    if (amount != null && !output.getValue().equals(amount))
        throw new IllegalArgumentException("Verification: Invalid output amount.");

    // 3. Verify fee value
    Coin fee = Coin.ZERO;
    for (final TransactionInput in : ptx.mDecoded.getInputs()) {
        if (countedUtxoValues.get(in.getOutpoint()) != null) {
            fee = fee.add(countedUtxoValues.get(in.getOutpoint()));
            continue;
        }

        final Transaction prevTx = ptx.mPrevoutRawTxs.get(in.getOutpoint().getHash().toString());
        if (!prevTx.getHash().equals(in.getOutpoint().getHash()))
            throw new IllegalArgumentException("Verification: Prev tx hash invalid");
        fee = fee.add(prevTx.getOutput((int) in.getOutpoint().getIndex()).getValue());
    }
    for (final TransactionOutput out : ptx.mDecoded.getOutputs())
        fee = fee.subtract(out.getValue());

    final double messageSize = ptx.mDecoded.getMessageSize();
    final double satoshiPerByte = fee.value / messageSize;
    final double satoshiPerKiloByte = satoshiPerByte * 1000.0;
    final Coin feeRate = Coin.valueOf((int) satoshiPerKiloByte);

    final Coin minFeeRate = service.getMinFeeRate();
    if (feeRate.isLessThan(minFeeRate) && service.getNetworkParameters() != RegTestParams.get())
        feeError("small", feeRate, minFeeRate);

    final Coin maxFeeRate = Coin.valueOf(15000 * 1000); // FIXME: Get max fee rate from server
    if (feeRate.isGreaterThan(maxFeeRate))
        feeError("large", feeRate, maxFeeRate);

    return amount == null ? output.getValue() : fee;
}
 
Example 13
Source File: BtcCoinSelector.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
protected boolean isDustAttackUtxo(TransactionOutput output) {
    return output.getValue().value < ignoreDustThreshold;
}
 
Example 14
Source File: BsqWalletService.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Coin getValueSentFromMeForTransaction(Transaction transaction) throws ScriptException {
    Coin result = Coin.ZERO;
    // We check all our inputs and get the connected outputs.
    for (int i = 0; i < transaction.getInputs().size(); i++) {
        TransactionInput input = transaction.getInputs().get(i);
        // We grab the connected output for that input
        TransactionOutput connectedOutput = input.getConnectedOutput();
        if (connectedOutput != null) {
            // We grab the parent tx of the connected output
            final Transaction parentTransaction = connectedOutput.getParentTransaction();
            final boolean isConfirmed = parentTransaction != null &&
                    parentTransaction.getConfidence().getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING;
            if (connectedOutput.isMineOrWatched(wallet)) {
                if (isConfirmed) {
                    // We lookup if we have a BSQ tx matching the parent tx
                    // We cannot make that findTx call outside of the loop as the parent tx can change at each iteration
                    Optional<Tx> txOptional = daoStateService.getTx(parentTransaction.getHash().toString());
                    if (txOptional.isPresent()) {
                        TxOutput txOutput = txOptional.get().getTxOutputs().get(connectedOutput.getIndex());
                        if (daoStateService.isBsqTxOutputType(txOutput)) {
                            //TODO check why values are not the same
                            if (txOutput.getValue() != connectedOutput.getValue().value)
                                log.warn("getValueSentToMeForTransaction: Value of BSQ output do not match BitcoinJ tx output. " +
                                                "txOutput.getValue()={}, output.getValue().value={}, txId={}",
                                        txOutput.getValue(), connectedOutput.getValue().value, txOptional.get().getId());

                            // If it is a valid BSQ output we add it
                            result = result.add(Coin.valueOf(txOutput.getValue()));
                        }
                    }
                } /*else {
                    // TODO atm we don't display amounts of unconfirmed txs but that might change so we leave that code
                    // if it will be required
                    // If the tx is not confirmed yet we add the value and assume it is a valid BSQ output.
                    result = result.add(connectedOutput.getValue());
                }*/
            }
        }
    }
    return result;
}
 
Example 15
Source File: BtcWalletService.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
protected boolean isDustAttackUtxo(TransactionOutput output) {
    return output.getValue().value < preferences.getIgnoreDustThreshold();
}