Java Code Examples for org.bitcoinj.core.TransactionConfidence#getConfidenceType()

The following examples show how to use org.bitcoinj.core.TransactionConfidence#getConfidenceType() . 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: Trade.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
private void setupConfidenceListener() {
    if (getDepositTx() != null) {
        TransactionConfidence transactionConfidence = getDepositTx().getConfidence();
        if (transactionConfidence.getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING) {
            setConfirmedState();
        } else {
            ListenableFuture<TransactionConfidence> future = transactionConfidence.getDepthFuture(1);
            Futures.addCallback(future, new FutureCallback<TransactionConfidence>() {
                @Override
                public void onSuccess(TransactionConfidence result) {
                    setConfirmedState();
                }

                @Override
                public void onFailure(@NotNull Throwable t) {
                    t.printStackTrace();
                    log.error(t.getMessage());
                    throw new RuntimeException(t);
                }
            });
        }
    } else {
        log.error("depositTx == null. That must not happen.");
    }
}
 
Example 2
Source File: GUIUtil.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void updateConfidence(TransactionConfidence confidence,
                                    Tooltip tooltip,
                                    TxConfidenceIndicator txConfidenceIndicator) {
    if (confidence != null) {
        switch (confidence.getConfidenceType()) {
            case UNKNOWN:
                tooltip.setText(Res.get("confidence.unknown"));
                txConfidenceIndicator.setProgress(0);
                break;
            case PENDING:
                tooltip.setText(Res.get("confidence.seen", confidence.numBroadcastPeers()));
                txConfidenceIndicator.setProgress(-1.0);
                break;
            case BUILDING:
                tooltip.setText(Res.get("confidence.confirmed", confidence.getDepthInBlocks()));
                txConfidenceIndicator.setProgress(Math.min(1, (double) confidence.getDepthInBlocks() / 6.0));
                break;
            case DEAD:
                tooltip.setText(Res.get("confidence.invalid"));
                txConfidenceIndicator.setProgress(0);
                break;
        }

        txConfidenceIndicator.setPrefSize(24, 24);
    }
}
 
Example 3
Source File: Trade.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
private void setupConfidenceListener() {
    if (getDepositTx() != null) {
        TransactionConfidence transactionConfidence = getDepositTx().getConfidence();
        if (transactionConfidence.getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING) {
            setConfirmedState();
        } else {
            ListenableFuture<TransactionConfidence> future = transactionConfidence.getDepthFuture(1);
            Futures.addCallback(future, new FutureCallback<TransactionConfidence>() {
                @Override
                public void onSuccess(TransactionConfidence result) {
                    setConfirmedState();
                }

                @Override
                public void onFailure(@NotNull Throwable t) {
                    t.printStackTrace();
                    log.error(t.getMessage());
                    throw new RuntimeException(t);
                }
            });
        }
    } else {
        log.error("depositTx == null. That must not happen.");
    }
}
 
Example 4
Source File: DefaultCoinSelector.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public static boolean isSelectable(Transaction tx) {
    // Only pick chain-included transactions, or transactions that are ours and pending.
    TransactionConfidence confidence = tx.getConfidence();
    TransactionConfidence.ConfidenceType type = confidence.getConfidenceType();
    return type.equals(TransactionConfidence.ConfidenceType.BUILDING) ||

            type.equals(TransactionConfidence.ConfidenceType.PENDING) &&
                    confidence.getSource().equals(TransactionConfidence.Source.SELF) &&
                    // In regtest mode we expect to have only one peer, so we won't see transactions propagate.
                    // TODO: The value 1 below dates from a time when transactions we broadcast *to* were counted, set to 0
                    (confidence.numBroadcastPeers() > 1 || tx.getParams().getId().equals(NetworkParameters.ID_REGTEST));
}
 
Example 5
Source File: MyceliumCoinSelector.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public static boolean isSelectable(Transaction tx) {
    // Only pick chain-included transactions, or transactions that are ours and pending.
    TransactionConfidence confidence = tx.getConfidence();
    TransactionConfidence.ConfidenceType type = confidence.getConfidenceType();
    return type.equals(TransactionConfidence.ConfidenceType.BUILDING) ||
            type.equals(TransactionConfidence.ConfidenceType.PENDING);
}
 
Example 6
Source File: BisqDefaultCoinSelector.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
protected boolean isTxSpendable(Transaction tx) {
    TransactionConfidence confidence = tx.getConfidence();
    TransactionConfidence.ConfidenceType type = confidence.getConfidenceType();
    boolean isConfirmed = type.equals(TransactionConfidence.ConfidenceType.BUILDING);
    boolean isPending = type.equals(TransactionConfidence.ConfidenceType.PENDING);
    boolean isOwnTx = confidence.getSource().equals(TransactionConfidence.Source.SELF);
    return isConfirmed || (isPending && (permitForeignPendingTx || isOwnTx));
}
 
Example 7
Source File: DefaultCoinSelector.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
public static boolean isSelectable(Transaction tx) {
    // Only pick chain-included transactions, or transactions that are ours and pending.
    TransactionConfidence confidence = tx.getConfidence();
    TransactionConfidence.ConfidenceType type = confidence.getConfidenceType();
    return type.equals(TransactionConfidence.ConfidenceType.BUILDING) ||

           type.equals(TransactionConfidence.ConfidenceType.PENDING) &&
           confidence.getSource().equals(TransactionConfidence.Source.SELF) &&
           // In regtest mode we expect to have only one peer, so we won't see transactions propagate.
           // TODO: The value 1 below dates from a time when transactions we broadcast *to* were counted, set to 0
           (confidence.numBroadcastPeers() > 1 || tx.getParams().getId().equals(NetworkParameters.ID_REGTEST));
}
 
Example 8
Source File: DefaultCoinSelector.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
public static boolean isSelectable(Transaction tx) {
    // Only pick chain-included transactions, or transactions that are ours and pending.
    TransactionConfidence confidence = tx.getConfidence();
    TransactionConfidence.ConfidenceType type = confidence.getConfidenceType();
    return type.equals(TransactionConfidence.ConfidenceType.BUILDING) ||

           type.equals(TransactionConfidence.ConfidenceType.PENDING) &&
           confidence.getSource().equals(TransactionConfidence.Source.SELF) &&
           // In regtest mode we expect to have only one peer, so we won't see transactions propagate.
           // TODO: The value 1 below dates from a time when transactions we broadcast *to* were counted, set to 0
           (confidence.numBroadcastPeers() > 1 || tx.getParams().getId().equals(NetworkParameters.ID_REGTEST));
}
 
Example 9
Source File: BisqDefaultCoinSelector.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
protected boolean isTxSpendable(Transaction tx) {
    TransactionConfidence confidence = tx.getConfidence();
    TransactionConfidence.ConfidenceType type = confidence.getConfidenceType();
    boolean isConfirmed = type.equals(TransactionConfidence.ConfidenceType.BUILDING);
    boolean isPending = type.equals(TransactionConfidence.ConfidenceType.PENDING);
    boolean isOwnTx = confidence.getSource().equals(TransactionConfidence.Source.SELF);
    return isConfirmed || (isPending && (permitForeignPendingTx || isOwnTx));
}
 
Example 10
Source File: WalletProtobufSerializer.java    From bcm-android with GNU General Public License v3.0 4 votes vote down vote up
private static void writeConfidence(Protos.Transaction.Builder txBuilder,
                                    TransactionConfidence confidence,
                                    Protos.TransactionConfidence.Builder confidenceBuilder) {
    synchronized (confidence) {
        confidenceBuilder.setType(Protos.TransactionConfidence.Type.valueOf(confidence.getConfidenceType().getValue()));
        if (confidence.getConfidenceType() == ConfidenceType.BUILDING) {
            confidenceBuilder.setAppearedAtHeight(confidence.getAppearedAtChainHeight());
            confidenceBuilder.setDepth(confidence.getDepthInBlocks());
        }
        if (confidence.getConfidenceType() == ConfidenceType.DEAD) {
            // Copy in the overriding transaction, if available.
            // (A dead coinbase transaction has no overriding transaction).
            if (confidence.getOverridingTransaction() != null) {
                Sha256Hash overridingHash = confidence.getOverridingTransaction().getHash();
                confidenceBuilder.setOverridingTransaction(hashToByteString(overridingHash));
            }
        }
        TransactionConfidence.Source source = confidence.getSource();
        switch (source) {
            case SELF:
                confidenceBuilder.setSource(Protos.TransactionConfidence.Source.SOURCE_SELF);
                break;
            case NETWORK:
                confidenceBuilder.setSource(Protos.TransactionConfidence.Source.SOURCE_NETWORK);
                break;
            case UNKNOWN:
                // Fall through.
            default:
                confidenceBuilder.setSource(Protos.TransactionConfidence.Source.SOURCE_UNKNOWN);
                break;
        }
    }

    for (PeerAddress address : confidence.getBroadcastBy()) {
        Protos.PeerAddress proto = Protos.PeerAddress.newBuilder()
                .setIpAddress(ByteString.copyFrom(address.getAddr().getAddress()))
                .setPort(address.getPort())
                .setServices(address.getServices().longValue())
                .build();
        confidenceBuilder.addBroadcastBy(proto);
    }
    Date lastBroadcastedAt = confidence.getLastBroadcastedAt();
    if (lastBroadcastedAt != null)
        confidenceBuilder.setLastBroadcastedAt(lastBroadcastedAt.getTime());
    txBuilder.setConfidence(confidenceBuilder);
}
 
Example 11
Source File: WalletProtobufSerializer.java    From bcm-android with GNU General Public License v3.0 4 votes vote down vote up
private void readConfidence(final NetworkParameters params, final Transaction tx,
                            final Protos.TransactionConfidence confidenceProto,
                            final TransactionConfidence confidence) throws UnreadableWalletException {
    // We are lenient here because tx confidence is not an essential part of the wallet.
    // If the tx has an unknown type of confidence, ignore.
    if (!confidenceProto.hasType()) {
        log.warn("Unknown confidence type for tx {}", tx.getHashAsString());
        return;
    }
    ConfidenceType confidenceType;
    switch (confidenceProto.getType()) {
        case BUILDING:
            confidenceType = ConfidenceType.BUILDING;
            break;
        case DEAD:
            confidenceType = ConfidenceType.DEAD;
            break;
        // These two are equivalent (must be able to read old wallets).
        case NOT_IN_BEST_CHAIN:
            confidenceType = ConfidenceType.PENDING;
            break;
        case PENDING:
            confidenceType = ConfidenceType.PENDING;
            break;
        case IN_CONFLICT:
            confidenceType = ConfidenceType.IN_CONFLICT;
            break;
        case UNKNOWN:
            // Fall through.
        default:
            confidenceType = ConfidenceType.UNKNOWN;
            break;
    }
    confidence.setConfidenceType(confidenceType);
    if (confidenceProto.hasAppearedAtHeight()) {
        if (confidence.getConfidenceType() != ConfidenceType.BUILDING) {
            log.warn("Have appearedAtHeight but not BUILDING for tx {}", tx.getHashAsString());
            return;
        }
        confidence.setAppearedAtChainHeight(confidenceProto.getAppearedAtHeight());
    }
    if (confidenceProto.hasDepth()) {
        if (confidence.getConfidenceType() != ConfidenceType.BUILDING) {
            log.warn("Have depth but not BUILDING for tx {}", tx.getHashAsString());
            return;
        }
        confidence.setDepthInBlocks(confidenceProto.getDepth());
    }
    if (confidenceProto.hasOverridingTransaction()) {
        if (confidence.getConfidenceType() != ConfidenceType.DEAD) {
            log.warn("Have overridingTransaction but not OVERRIDDEN for tx {}", tx.getHashAsString());
            return;
        }
        Transaction overridingTransaction =
                txMap.get(confidenceProto.getOverridingTransaction());
        if (overridingTransaction == null) {
            log.warn("Have overridingTransaction that is not in wallet for tx {}", tx.getHashAsString());
            return;
        }
        confidence.setOverridingTransaction(overridingTransaction);
    }
    for (Protos.PeerAddress proto : confidenceProto.getBroadcastByList()) {
        InetAddress ip;
        try {
            ip = InetAddress.getByAddress(proto.getIpAddress().toByteArray());
        } catch (UnknownHostException e) {
            throw new UnreadableWalletException("Peer IP address does not have the right length", e);
        }
        int port = proto.getPort();
        int protocolVersion = params.getProtocolVersionNum(NetworkParameters.ProtocolVersion.CURRENT);
        BigInteger services = BigInteger.valueOf(proto.getServices());
        PeerAddress address = new PeerAddress(params, ip, port, protocolVersion, services);
        confidence.markBroadcastBy(address);
    }
    if (confidenceProto.hasLastBroadcastedAt())
        confidence.setLastBroadcastedAt(new Date(confidenceProto.getLastBroadcastedAt()));
    switch (confidenceProto.getSource()) {
        case SOURCE_SELF:
            confidence.setSource(TransactionConfidence.Source.SELF);
            break;
        case SOURCE_NETWORK:
            confidence.setSource(TransactionConfidence.Source.NETWORK);
            break;
        case SOURCE_UNKNOWN:
            // Fall through.
        default:
            confidence.setSource(TransactionConfidence.Source.UNKNOWN);
            break;
    }
}
 
Example 12
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void doubleSpends() throws Exception {
    // Test the case where two semantically identical but bitwise different transactions double spend each other.
    // We call the second transaction a "mutant" of the first.
    //
    // This can (and has!) happened when a wallet is cloned between devices, and both devices decide to make the
    // same spend simultaneously - for example due a re-keying operation. It can also happen if there are malicious
    // nodes in the P2P network that are mutating transactions on the fly as occurred during Feb 2014.
    final Coin value = COIN;
    final Coin value2 = valueOf(2, 0);
    // Give us three coins and make sure we have some change.
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, value.add(value2));
    Transaction send1 = checkNotNull(wallet.createSend(OTHER_ADDRESS, value2));
    Transaction send2 = checkNotNull(wallet.createSend(OTHER_ADDRESS, value2));
    byte[] buf = send1.bitcoinSerialize();
    buf[43] = 0;  // Break the signature: bitcoinj won't check in SPV mode and this is easier than other mutations.
    send1 = UNITTEST.getDefaultSerializer().makeTransaction(buf);
    wallet.commitTx(send2);
    wallet.allowSpendingUnconfirmedTransactions();
    assertEquals(value, wallet.getBalance(Wallet.BalanceType.ESTIMATED));
    // Now spend the change. This transaction should die permanently when the mutant appears in the chain.
    Transaction send3 = checkNotNull(wallet.createSend(OTHER_ADDRESS, value));
    wallet.commitTx(send3);
    assertEquals(ZERO, wallet.getBalance());
    final LinkedList<TransactionConfidence> dead = new LinkedList<>();
    final TransactionConfidence.Listener listener = new TransactionConfidence.Listener() {
        @Override
        public void onConfidenceChanged(TransactionConfidence confidence, ChangeReason reason) {
            final TransactionConfidence.ConfidenceType type = confidence.getConfidenceType();
            if (reason == ChangeReason.TYPE && type == TransactionConfidence.ConfidenceType.DEAD)
                dead.add(confidence);
        }
    };
    send2.getConfidence().addEventListener(Threading.SAME_THREAD, listener);
    send3.getConfidence().addEventListener(Threading.SAME_THREAD, listener);
    // Double spend!
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, send1);
    // Back to having one coin.
    assertEquals(value, wallet.getBalance());
    assertEquals(send2.getHash(), dead.poll().getTransactionHash());
    assertEquals(send3.getHash(), dead.poll().getTransactionHash());
}
 
Example 13
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void doubleSpends() throws Exception {
    // Test the case where two semantically identical but bitwise different transactions double spend each other.
    // We call the second transaction a "mutant" of the first.
    //
    // This can (and has!) happened when a wallet is cloned between devices, and both devices decide to make the
    // same spend simultaneously - for example due a re-keying operation. It can also happen if there are malicious
    // nodes in the P2P network that are mutating transactions on the fly as occurred during Feb 2014.
    final Coin value = COIN;
    final Coin value2 = valueOf(2, 0);
    // Give us three coins and make sure we have some change.
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, value.add(value2));
    Transaction send1 = checkNotNull(wallet.createSend(OTHER_ADDRESS, value2));
    Transaction send2 = checkNotNull(wallet.createSend(OTHER_ADDRESS, value2));
    byte[] buf = send1.bitcoinSerialize();
    buf[43] = 0;  // Break the signature: bitcoinj won't check in SPV mode and this is easier than other mutations.
    send1 = PARAMS.getDefaultSerializer().makeTransaction(buf);
    wallet.commitTx(send2);
    wallet.allowSpendingUnconfirmedTransactions();
    assertEquals(value, wallet.getBalance(Wallet.BalanceType.ESTIMATED));
    // Now spend the change. This transaction should die permanently when the mutant appears in the chain.
    Transaction send3 = checkNotNull(wallet.createSend(OTHER_ADDRESS, value));
    wallet.commitTx(send3);
    assertEquals(ZERO, wallet.getBalance());
    final LinkedList<TransactionConfidence> dead = new LinkedList<>();
    final TransactionConfidence.Listener listener = new TransactionConfidence.Listener() {
        @Override
        public void onConfidenceChanged(TransactionConfidence confidence, ChangeReason reason) {
            final TransactionConfidence.ConfidenceType type = confidence.getConfidenceType();
            if (reason == ChangeReason.TYPE && type == TransactionConfidence.ConfidenceType.DEAD)
                dead.add(confidence);
        }
    };
    send2.getConfidence().addEventListener(Threading.SAME_THREAD, listener);
    send3.getConfidence().addEventListener(Threading.SAME_THREAD, listener);
    // Double spend!
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, send1);
    // Back to having one coin.
    assertEquals(value, wallet.getBalance());
    assertEquals(send2.getHash(), dead.poll().getTransactionHash());
    assertEquals(send3.getHash(), dead.poll().getTransactionHash());
}
 
Example 14
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void doubleSpends() throws Exception {
    // Test the case where two semantically identical but bitwise different transactions double spend each other.
    // We call the second transaction a "mutant" of the first.
    //
    // This can (and has!) happened when a wallet is cloned between devices, and both devices decide to make the
    // same spend simultaneously - for example due a re-keying operation. It can also happen if there are malicious
    // nodes in the P2P network that are mutating transactions on the fly as occurred during Feb 2014.
    final Coin value = COIN;
    final Coin value2 = valueOf(2, 0);
    // Give us three coins and make sure we have some change.
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, value.add(value2));
    Transaction send1 = checkNotNull(wallet.createSend(OTHER_ADDRESS, value2));
    Transaction send2 = checkNotNull(wallet.createSend(OTHER_ADDRESS, value2));
    byte[] buf = send1.bitcoinSerialize();
    buf[43] = 0;  // Break the signature: bitcoinj won't check in SPV mode and this is easier than other mutations.
    send1 = PARAMS.getDefaultSerializer().makeTransaction(buf);
    wallet.commitTx(send2);
    wallet.allowSpendingUnconfirmedTransactions();
    assertEquals(value, wallet.getBalance(Wallet.BalanceType.ESTIMATED));
    // Now spend the change. This transaction should die permanently when the mutant appears in the chain.
    Transaction send3 = checkNotNull(wallet.createSend(OTHER_ADDRESS, value));
    wallet.commitTx(send3);
    assertEquals(ZERO, wallet.getBalance());
    final LinkedList<TransactionConfidence> dead = new LinkedList<>();
    final TransactionConfidence.Listener listener = new TransactionConfidence.Listener() {
        @Override
        public void onConfidenceChanged(TransactionConfidence confidence, ChangeReason reason) {
            final TransactionConfidence.ConfidenceType type = confidence.getConfidenceType();
            if (reason == ChangeReason.TYPE && type == TransactionConfidence.ConfidenceType.DEAD)
                dead.add(confidence);
        }
    };
    send2.getConfidence().addEventListener(Threading.SAME_THREAD, listener);
    send3.getConfidence().addEventListener(Threading.SAME_THREAD, listener);
    // Double spend!
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, send1);
    // Back to having one coin.
    assertEquals(value, wallet.getBalance());
    assertEquals(send2.getHash(), dead.poll().getTransactionHash());
    assertEquals(send3.getHash(), dead.poll().getTransactionHash());
}