org.bitcoinj.core.TransactionOutput Java Examples

The following examples show how to use org.bitcoinj.core.TransactionOutput. 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: BisqDefaultCoinSelector.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
protected void sortOutputs(ArrayList<TransactionOutput> outputs) {
    Collections.sort(outputs, (a, 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() != null ?
                a.getParentTransactionHash().toBigInteger() : BigInteger.ZERO;
        BigInteger bHash = b.getParentTransactionHash() != null ?
                b.getParentTransactionHash().toBigInteger() : BigInteger.ZERO;
        return aHash.compareTo(bHash);
    });
}
 
Example #2
Source File: DefaultCoinSelector.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@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);
        }
    });
}
 
Example #3
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void transactions() throws Exception {
    // This test covers a bug in which Transaction.getValueSentFromMe was calculating incorrectly.
    Transaction tx = createFakeTx(PARAMS, COIN, myAddress);
    // Now add another output (ie, change) that goes to some other address.
    TransactionOutput output = new TransactionOutput(PARAMS, tx, valueOf(0, 5), OTHER_ADDRESS);
    tx.addOutput(output);
    // Note that tx is no longer valid: it spends more than it imports. However checking transactions balance
    // correctly isn't possible in SPV mode because value is a property of outputs not inputs. Without all
    // transactions you can't check they add up.
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, tx);
    // Now the other guy creates a transaction which spends that change.
    Transaction tx2 = new Transaction(PARAMS);
    tx2.addInput(output);
    tx2.addOutput(new TransactionOutput(PARAMS, tx2, valueOf(0, 5), myAddress));
    // tx2 doesn't send any coins from us, even though the output is in the wallet.
    assertEquals(ZERO, tx2.getValueSentFromMe(wallet));
}
 
Example #4
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void transactions() throws Exception {
    // This test covers a bug in which Transaction.getValueSentFromMe was calculating incorrectly.
    Transaction tx = createFakeTx(UNITTEST, COIN, myAddress);
    // Now add another output (ie, change) that goes to some other address.
    TransactionOutput output = new TransactionOutput(UNITTEST, tx, valueOf(0, 5), OTHER_ADDRESS);
    tx.addOutput(output);
    // Note that tx is no longer valid: it spends more than it imports. However checking transactions balance
    // correctly isn't possible in SPV mode because value is a property of outputs not inputs. Without all
    // transactions you can't check they add up.
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, tx);
    // Now the other guy creates a transaction which spends that change.
    Transaction tx2 = new Transaction(UNITTEST);
    tx2.addInput(output);
    tx2.addOutput(new TransactionOutput(UNITTEST, tx2, valueOf(0, 5), myAddress));
    // tx2 doesn't send any coins from us, even though the output is in the wallet.
    assertEquals(ZERO, tx2.getValueSentFromMe(wallet));
}
 
Example #5
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 #6
Source File: BsqCoinSelector.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected boolean isTxOutputSpendable(TransactionOutput output) {
    // output.getParentTransaction() cannot be null as it is checked in calling method
    Transaction parentTransaction = output.getParentTransaction();
    if (parentTransaction == null)
        return false;

    // If it is a normal confirmed BSQ output we use the default lookup at the daoState
    if (daoStateService.isTxOutputSpendable(new TxOutputKey(parentTransaction.getHashAsString(), output.getIndex())))
        return true;

    // It might be that it is an unconfirmed change output which we allow to be used for spending without requiring a confirmation.
    // We check if we have the output in the dao state, if so we have a confirmed but unspendable output (e.g. confiscated).
    if (daoStateService.getTxOutput(new TxOutputKey(parentTransaction.getHashAsString(), output.getIndex())).isPresent())
        return false;

    // Only if it's not existing yet in the dao state (unconfirmed) we use our unconfirmedBsqChangeOutputList to
    // check if it is an own change output.
    return unconfirmedBsqChangeOutputListService.hasTransactionOutput(output);
}
 
Example #7
Source File: ToolsTest.java    From thunder with GNU Affero General Public License v3.0 6 votes vote down vote up
private static Transaction shuffleTransaction (Transaction transaction) {
    Transaction shuffledTransaction = new Transaction(Constants.getNetwork());

    List<TransactionInput> shuffledInputs = new ArrayList<>(transaction.getInputs());
    List<TransactionOutput> shuffledOutputs = new ArrayList<>(transaction.getOutputs());

    Collections.shuffle(shuffledInputs);
    Collections.shuffle(shuffledOutputs);
    for (TransactionInput input : shuffledInputs) {
        shuffledTransaction.addInput(input);
    }
    for (TransactionOutput output : shuffledOutputs) {
        shuffledTransaction.addOutput(output);
    }
    return shuffledTransaction;
}
 
Example #8
Source File: TransactionAwareTrade.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
boolean isDelayedPayoutTx(String txId) {
    Transaction transaction = btcWalletService.getTransaction(txId);
    if (transaction == null)
        return false;

    if (transaction.getLockTime() == 0)
        return false;

    if (transaction.getInputs() == null)
        return false;

    return transaction.getInputs().stream()
            .anyMatch(input -> {
                TransactionOutput connectedOutput = input.getConnectedOutput();
                if (connectedOutput == null) {
                    return false;
                }
                Transaction parentTransaction = connectedOutput.getParentTransaction();
                if (parentTransaction == null) {
                    return false;
                }
                return isDepositTx(parentTransaction.getHashAsString());
            });
}
 
Example #9
Source File: FakeTxBuilder.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Create a fake TX of sufficient realism to exercise the unit tests. Two outputs, one to us, one to somewhere
 * else to simulate change. There is one random input.
 */
public static Transaction createFakeTxWithChangeAddress(NetworkParameters params, Coin value, Address to, Address changeOutput) {
    Transaction t = new Transaction(params);
    TransactionOutput outputToMe = new TransactionOutput(params, t, value, to);
    t.addOutput(outputToMe);
    TransactionOutput change = new TransactionOutput(params, t, valueOf(1, 11), changeOutput);
    t.addOutput(change);
    // Make a previous tx simply to send us sufficient coins. This prev tx is not really valid but it doesn't
    // matter for our purposes.
    Transaction prevTx = new Transaction(params);
    TransactionOutput prevOut = new TransactionOutput(params, prevTx, value, to);
    prevTx.addOutput(prevOut);
    // Connect it.
    t.addInput(prevOut).setScriptSig(ScriptBuilder.createInputScript(TransactionSignature.dummy()));
    // Fake signature.
    // Serialize/deserialize to ensure internal state is stripped, as if it had been read from the wire.
    return roundTripTransaction(params, t);
}
 
Example #10
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void bounce() throws Exception {
    // This test covers bug 64 (False double spends). Check that if we create a spend and it's immediately sent
    // back to us, this isn't considered as a double spend.
    Coin coin1 = COIN;
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, coin1);
    // Send half to some other guy. Sending only half then waiting for a confirm is important to ensure the tx is
    // in the unspent pool, not pending or spent.
    Coin coinHalf = valueOf(0, 50);
    assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.UNSPENT));
    assertEquals(1, wallet.getTransactions(true).size());
    Transaction outbound1 = wallet.createSend(OTHER_ADDRESS, coinHalf);
    wallet.commitTx(outbound1);
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, outbound1);
    assertTrue(outbound1.getWalletOutputs(wallet).size() <= 1); //the change address at most
    // That other guy gives us the coins right back.
    Transaction inbound2 = new Transaction(UNITTEST);
    inbound2.addOutput(new TransactionOutput(UNITTEST, inbound2, coinHalf, myAddress));
    assertTrue(outbound1.getWalletOutputs(wallet).size() >= 1);
    inbound2.addInput(outbound1.getOutputs().get(0));
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, inbound2);
    assertEquals(coin1, wallet.getBalance());
}
 
Example #11
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void isConsistent_duplicates() throws Exception {
    // This test ensures that isConsistent catches duplicate transactions, eg, because we submitted the same block
    // twice (this is not allowed).
    Transaction tx = createFakeTx(PARAMS, COIN, myAddress);
    TransactionOutput output = new TransactionOutput(PARAMS, tx, valueOf(0, 5), OTHER_ADDRESS);
    tx.addOutput(output);
    wallet.receiveFromBlock(tx, null, BlockChain.NewBlockType.BEST_CHAIN, 0);

    assertTrue(wallet.isConsistent());

    Transaction txClone = PARAMS.getDefaultSerializer().makeTransaction(tx.bitcoinSerialize());
    try {
        wallet.receiveFromBlock(txClone, null, BlockChain.NewBlockType.BEST_CHAIN, 0);
        fail("Illegal argument not thrown when it should have been.");
    } catch (IllegalStateException ex) {
        // expected
    }
}
 
Example #12
Source File: DefaultCoinSelector.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@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);
        }
    });
}
 
Example #13
Source File: DefaultCoinSelector.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@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);
        }
    });
}
 
Example #14
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 #15
Source File: SendRequest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #16
Source File: NonBsqCoinSelector.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected boolean isTxOutputSpendable(TransactionOutput output) {
    // output.getParentTransaction() cannot be null as it is checked in calling method
    Transaction parentTransaction = output.getParentTransaction();
    if (parentTransaction == null)
        return false;

    if (parentTransaction.getConfidence().getConfidenceType() != TransactionConfidence.ConfidenceType.BUILDING)
        return false;

    TxOutputKey key = new TxOutputKey(parentTransaction.getHashAsString(), output.getIndex());
    // It might be that we received BTC in a non-BSQ tx so that will not be stored in out state and not found.
    // So we consider any txOutput which is not in the state as BTC output.
    boolean outputIsNotInBsqState = !bsqStateService.existsTxOutput(key);
    return outputIsNotInBsqState || bsqStateService.getBtcTxOutput(key).isPresent();
}
 
Example #17
Source File: MyceliumCoinSelector.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@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);
        }
    });
}
 
Example #18
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 #19
Source File: RawTransactionInfo.java    From consensusj with Apache License 2.0 6 votes vote down vote up
/**
 * Construct from a bitcoinj transaction
 * @param transaction A bitcoinj confirmed or unconfirmed transaction
 */
public RawTransactionInfo(Transaction transaction) {
    this.hex = HexUtil.bytesToHexString(transaction.bitcoinSerialize());
    this.txid = transaction.getTxId();
    this.version = transaction.getVersion();
    this.locktime = transaction.getLockTime();
    this.blockhash = null;  // For now
    this.confirmations = transaction.getConfidence().getDepthInBlocks();
    this.time = 0; // TODO: block header time of block including transaction
    this.blocktime = this.time; // same as time (see API doc)
    vin = new VinList();
    for (TransactionInput input : transaction.getInputs()) {
        vin.add(new Vin(txid,
                        input.getOutpoint().getIndex(),
                        input.getScriptSig().toString(),
                        input.getSequenceNumber()));
    }
    vout = new VoutList();
    for (TransactionOutput output : transaction.getOutputs()) {
        vout.add(new Vout(output.getValue(),
                            output.getIndex(),
                            output.getScriptPubKey().toString()));
    }
}
 
Example #20
Source File: NonBsqCoinSelector.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected boolean isTxOutputSpendable(TransactionOutput output) {
    // output.getParentTransaction() cannot be null as it is checked in calling method
    Transaction parentTransaction = output.getParentTransaction();
    if (parentTransaction == null)
        return false;

    // It is important to not allow pending txs as otherwise unconfirmed BSQ txs would be considered nonBSQ as
    // below outputIsNotInBsqState would be true.
    if (parentTransaction.getConfidence().getConfidenceType() != TransactionConfidence.ConfidenceType.BUILDING)
        return false;

    TxOutputKey key = new TxOutputKey(parentTransaction.getHashAsString(), output.getIndex());
    // It might be that we received BTC in a non-BSQ tx so that will not be stored in out state and not found.
    // So we consider any txOutput which is not in the state as BTC output.
    return !daoStateService.existsTxOutput(key) || daoStateService.isRejectedIssuanceOutput(key);
}
 
Example #21
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void bounce() throws Exception {
    // This test covers bug 64 (False double spends). Check that if we create a spend and it's immediately sent
    // back to us, this isn't considered as a double spend.
    Coin coin1 = COIN;
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, coin1);
    // Send half to some other guy. Sending only half then waiting for a confirm is important to ensure the tx is
    // in the unspent pool, not pending or spent.
    Coin coinHalf = valueOf(0, 50);
    assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.UNSPENT));
    assertEquals(1, wallet.getTransactions(true).size());
    Transaction outbound1 = wallet.createSend(OTHER_ADDRESS, coinHalf);
    wallet.commitTx(outbound1);
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, outbound1);
    assertTrue(outbound1.getWalletOutputs(wallet).size() <= 1); //the change address at most
    // That other guy gives us the coins right back.
    Transaction inbound2 = new Transaction(PARAMS);
    inbound2.addOutput(new TransactionOutput(PARAMS, inbound2, coinHalf, myAddress));
    assertTrue(outbound1.getWalletOutputs(wallet).size() >= 1);
    inbound2.addInput(outbound1.getOutputs().get(0));
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, inbound2);
    assertEquals(coin1, wallet.getBalance());
}
 
Example #22
Source File: BisqDefaultCoinSelector.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
protected void sortOutputs(ArrayList<TransactionOutput> outputs) {
    Collections.sort(outputs, (a, 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() != null ?
                a.getParentTransactionHash().toBigInteger() : BigInteger.ZERO;
        BigInteger bHash = b.getParentTransactionHash() != null ?
                b.getParentTransactionHash().toBigInteger() : BigInteger.ZERO;
        return aHash.compareTo(bHash);
    });
}
 
Example #23
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void isTxConsistentReturnsFalseAsExpected() {
    Wallet wallet = new Wallet(PARAMS);
    TransactionOutput to = createMock(TransactionOutput.class);
    EasyMock.expect(to.isAvailableForSpending()).andReturn(true);
    EasyMock.expect(to.isMineOrWatched(wallet)).andReturn(true);
    EasyMock.expect(to.getSpentBy()).andReturn(new TransactionInput(PARAMS, null, new byte[0]));

    Transaction tx = FakeTxBuilder.createFakeTxWithoutChange(PARAMS, to);

    replay(to);

    boolean isConsistent = wallet.isTxConsistent(tx, false);
    assertFalse(isConsistent);
}
 
Example #24
Source File: BitcoinExtendedClient.java    From consensusj with Apache License 2.0 5 votes vote down vote up
/**
 * Build a list of bitcoinj <code>TransactionOutput</code>s using <code>listUnspent</code>
 * and <code>getRawTransaction</code> RPCs
 *
 * @param fromAddress Address to get UTXOs for
 * @return All unspent TransactionOutputs for fromAddress
 */
public List<TransactionOutput> listUnspentJ(Address fromAddress) throws JsonRpcStatusException, IOException {
    List<Address> addresses = Collections.singletonList(fromAddress);
    List<UnspentOutput> unspentOutputsRPC = listUnspent(0, defaultMaxConf, addresses); // RPC UnspentOutput objects
    List<TransactionOutput> unspentOutputsJ = new ArrayList<TransactionOutput>();
    for (UnspentOutput it : unspentOutputsRPC) {
        unspentOutputsJ.add(getRawTransaction(it.getTxid()).getOutput(it.getVout()));
    }
    return unspentOutputsJ;
}
 
Example #25
Source File: BsqWalletService.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
public Transaction getPreparedLockupTx(Coin lockupAmount) throws AddressFormatException, InsufficientBsqException {
    Transaction tx = new Transaction(params);
    checkArgument(Restrictions.isAboveDust(lockupAmount), "The amount is too low (dust limit).");
    tx.addOutput(new TransactionOutput(params, tx, lockupAmount, getUnusedAddress()));
    addInputsAndChangeOutputForTx(tx, lockupAmount, bsqCoinSelector);
    printTx("prepareLockupTx", tx);
    return tx;
}
 
Example #26
Source File: BsqWalletService.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
public Transaction getPreparedBlindVoteTx(Coin fee, Coin stake) throws InsufficientBsqException {
    Transaction tx = new Transaction(params);
    tx.addOutput(new TransactionOutput(params, tx, stake, getUnusedAddress()));
    addInputsAndChangeOutputForTx(tx, fee.add(stake), bsqCoinSelector);
    //printTx("getPreparedBlindVoteTx", tx);
    return tx;
}
 
Example #27
Source File: BsqWalletService.java    From bisq-core with GNU Affero General Public License v3.0 5 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);
        }
    }

    checkWalletConsistency(wallet);
    verifyTransaction(tx);
    printTx("BSQ wallet: Signed Tx", tx);
    return tx;
}
 
Example #28
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 #29
Source File: BlockChain.java    From polling-station-app with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Spends all outputs in this balance to the master address.
 * @param balance
 * @param pcon
 */

public ArrayList<byte[]> getSpendUtxoTransactions(PublicKey pubKey, AssetBalance balance, PassportConnection pcon) throws Exception {
    ArrayList<byte[]> transactions = new ArrayList<>();
    for (TransactionOutput utxo : balance) {
        transactions.add(utxoToSignedTransaction(pubKey, utxo, masterAddress, pcon));
    }
    return transactions;
}
 
Example #30
Source File: Trezor.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
private TxOutputBinType.Builder createBinOutput(final TxRequestDetailsType txRequest) {
    final int index = txRequest.getRequestIndex();

    final TransactionOutput out = getPreviousTx(txRequest).getOutput(index);
    return TxOutputBinType.newBuilder()
                          .setAmount(out.getValue().longValue())
                          .setScriptPubkey(ByteString.copyFrom(out.getScriptBytes()));
}