org.bitcoinj.core.TransactionConfidence Java Examples

The following examples show how to use org.bitcoinj.core.TransactionConfidence. 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: 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 #2
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 #3
Source File: WalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @param serializedTransaction The serialized transaction to be added to the wallet
 * @return The transaction we added to the wallet, which is different as the one we passed as argument!
 * @throws VerificationException
 */
public static Transaction maybeAddTxToWallet(byte[] serializedTransaction,
                                             Wallet wallet,
                                             TransactionConfidence.Source source) throws VerificationException {
    Transaction tx = new Transaction(wallet.getParams(), serializedTransaction);
    Transaction walletTransaction = wallet.getTransaction(tx.getHash());

    if (walletTransaction == null) {
        // We need to recreate the transaction otherwise we get a null pointer...
        tx.getConfidence(Context.get()).setSource(source);
        //wallet.maybeCommitTx(tx);
        wallet.receivePending(tx, null, true);
        return tx;
    } else {
        return walletTransaction;
    }
}
 
Example #4
Source File: WalletService.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
@Nullable
protected TransactionConfidence getMostRecentConfidence(List<TransactionConfidence> transactionConfidenceList) {
    TransactionConfidence transactionConfidence = null;
    for (TransactionConfidence confidence : transactionConfidenceList) {
        if (confidence != null) {
            if (transactionConfidence == null ||
                    confidence.getConfidenceType().equals(TransactionConfidence.ConfidenceType.PENDING) ||
                    (confidence.getConfidenceType().equals(TransactionConfidence.ConfidenceType.BUILDING) &&
                            transactionConfidence.getConfidenceType().equals(
                                    TransactionConfidence.ConfidenceType.BUILDING) &&
                            confidence.getDepthInBlocks() < transactionConfidence.getDepthInBlocks())) {
                transactionConfidence = confidence;
            }
        }
    }
    return transactionConfidence;
}
 
Example #5
Source File: WalletService.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void onTransactionConfidenceChanged(Wallet wallet, Transaction tx) {
    for (AddressConfidenceListener addressConfidenceListener : addressConfidenceListeners) {
        List<TransactionConfidence> transactionConfidenceList = new ArrayList<>();
        transactionConfidenceList.add(getTransactionConfidence(tx, addressConfidenceListener.getAddress()));

        TransactionConfidence transactionConfidence = getMostRecentConfidence(transactionConfidenceList);
        addressConfidenceListener.onTransactionConfidenceChanged(transactionConfidence);
    }
    txConfidenceListeners.stream()
            .filter(txConfidenceListener -> tx != null &&
                    tx.getHashAsString() != null &&
                    txConfidenceListener != null &&
                    tx.getHashAsString().equals(txConfidenceListener.getTxID()))
            .forEach(txConfidenceListener ->
                    txConfidenceListener.onTransactionConfidenceChanged(tx.getConfidence()));
}
 
Example #6
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 #7
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 #8
Source File: TxConfidenceListItem.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
protected TxConfidenceListItem(Transaction transaction,
                               BsqWalletService bsqWalletService) {
    this.bsqWalletService = bsqWalletService;

    txId = transaction.getHashAsString();
    txConfidenceIndicator = new TxConfidenceIndicator();
    txConfidenceIndicator.setId("funds-confidence");
    Tooltip tooltip = new Tooltip();
    txConfidenceIndicator.setProgress(0);
    txConfidenceIndicator.setPrefSize(24, 24);
    txConfidenceIndicator.setTooltip(tooltip);

    txConfidenceListener = new TxConfidenceListener(txId) {
        @Override
        public void onTransactionConfidenceChanged(TransactionConfidence confidence) {
            updateConfidence(confidence, tooltip);
        }
    };
    bsqWalletService.addTxConfidenceListener(txConfidenceListener);
    updateConfidence(bsqWalletService.getConfidenceForTxId(txId), tooltip);
}
 
Example #9
Source File: BalanceWithConfirmationTextField.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public void setup(Address address, CoinFormatter formatter) {
    this.formatter = formatter;
    confidenceListener = new AddressConfidenceListener(address) {
        @Override
        public void onTransactionConfidenceChanged(TransactionConfidence confidence) {
            updateConfidence(confidence);
        }
    };
    walletService.addAddressConfidenceListener(confidenceListener);
    updateConfidence(walletService.getConfidenceForAddress(address));

    balanceListener = new BalanceListener(address) {
        @Override
        public void onBalanceChanged(Coin balance, Transaction tx) {
            updateBalance(balance);
        }
    };
    walletService.addBalanceListener(balanceListener);
    updateBalance(walletService.getBalanceForAddress(address));
}
 
Example #10
Source File: TxIdTextField.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public void setup(String txId) {
    if (txConfidenceListener != null)
        walletService.removeTxConfidenceListener(txConfidenceListener);

    txConfidenceListener = new TxConfidenceListener(txId) {
        @Override
        public void onTransactionConfidenceChanged(TransactionConfidence confidence) {
            updateConfidence(confidence);
        }
    };
    walletService.addTxConfidenceListener(txConfidenceListener);
    updateConfidence(walletService.getConfidenceForTxId(txId));

    textField.setText(txId);
    textField.setOnMouseClicked(mouseEvent -> openBlockExplorer(txId));
    blockExplorerIcon.setOnMouseClicked(mouseEvent -> openBlockExplorer(txId));
    copyIcon.setOnMouseClicked(e -> Utilities.copyToClipboard(txId));
}
 
Example #11
Source File: TxIdTextField.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
private void updateConfidence(TransactionConfidence confidence) {
    GUIUtil.updateConfidence(confidence, progressIndicatorTooltip, txConfidenceIndicator);
    if (confidence != null) {
        if (txConfidenceIndicator.getProgress() != 0) {
            txConfidenceIndicator.setVisible(true);
            AnchorPane.setRightAnchor(txConfidenceIndicator, 0.0);
        }
    } else {
        //TODO we should show some placeholder in case of a tx which we are not aware of but which can be
        // confirmed already. This is for instance the case of the other peers trade fee tx, as it is not related
        // to our wallet we don't have a confidence object but we should show that it is in an unknown state instead
        // of not showing anything which causes confusion that the tx was not broadcasted. Best would be to request
        // it from a block explorer service but that is a bit too heavy for that use case...
        // Maybe a question mark with a tooltip explaining why we don't know about the confidence might be ok...
    }
}
 
Example #12
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 #13
Source File: WalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void onTransactionConfidenceChanged(Wallet wallet, Transaction tx) {
    for (AddressConfidenceListener addressConfidenceListener : addressConfidenceListeners) {
        List<TransactionConfidence> transactionConfidenceList = new ArrayList<>();
        transactionConfidenceList.add(getTransactionConfidence(tx, addressConfidenceListener.getAddress()));

        TransactionConfidence transactionConfidence = getMostRecentConfidence(transactionConfidenceList);
        addressConfidenceListener.onTransactionConfidenceChanged(transactionConfidence);
    }
    txConfidenceListeners.stream()
            .filter(txConfidenceListener -> tx != null &&
                    tx.getHashAsString() != null &&
                    txConfidenceListener != null &&
                    tx.getHashAsString().equals(txConfidenceListener.getTxID()))
            .forEach(txConfidenceListener ->
                    txConfidenceListener.onTransactionConfidenceChanged(tx.getConfidence()));
}
 
Example #14
Source File: DefaultRiskAnalysis.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
private Result analyzeIsFinal() {
    // Transactions we create ourselves are, by definition, not at risk of double spending against us.
    if (tx.getConfidence().getSource() == TransactionConfidence.Source.SELF)
        return Result.OK;

    // We consider transactions that opt into replace-by-fee at risk of double spending.
    if (tx.isOptInFullRBF()) {
        nonFinal = tx;
        return Result.NON_FINAL;
    }

    if (wallet == null)
        return null;

    final int height = wallet.getLastBlockSeenHeight();
    final long time = wallet.getLastBlockSeenTimeSecs();
    // If the transaction has a lock time specified in blocks, we consider that if the tx would become final in the
    // next block it is not risky (as it would confirm normally).
    final int adjustedHeight = height + 1;

    if (!tx.isFinal(adjustedHeight, time)) {
        nonFinal = tx;
        return Result.NON_FINAL;
    }
    for (Transaction dep : dependencies) {
        if (!dep.isFinal(adjustedHeight, time)) {
            nonFinal = dep;
            return Result.NON_FINAL;
        }
    }

    return Result.OK;
}
 
Example #15
Source File: TradeWalletService.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @param transaction The transaction to be added to the wallet
 * @return The transaction we added to the wallet, which is different as the one we passed as argument!
 * @throws VerificationException
 */
public Transaction addTxToWallet(Transaction transaction) throws VerificationException {
    Log.traceCall("transaction " + transaction.toString());

    // We need to recreate the transaction otherwise we get a null pointer...
    Transaction result = new Transaction(params, transaction.bitcoinSerialize());
    result.getConfidence(Context.get()).setSource(TransactionConfidence.Source.SELF);

    if (wallet != null)
        wallet.receivePending(result, null, true);
    return result;
}
 
Example #16
Source File: UnconfirmedBsqChangeOutputListService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public void onTransactionConfidenceChanged(Transaction tx) {
    if (tx != null &&
            tx.getConfidence().getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING) {
        removeConnectedOutputsOfInputsOfTx(tx);

        tx.getOutputs().forEach(transactionOutput -> {
            UnconfirmedTxOutput txOutput = UnconfirmedTxOutput.fromTransactionOutput(transactionOutput);
            if (unconfirmedBsqChangeOutputList.containsTxOutput(txOutput)) {
                unconfirmedBsqChangeOutputList.remove(txOutput);
            }
        });
    }
}
 
Example #17
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 #18
Source File: TradeManager.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public Set<String> getSetOfFailedOrClosedTradeIdsFromLockedInFunds() throws TradeTxException {
    AtomicReference<TradeTxException> tradeTxException = new AtomicReference<>();
    Set<String> tradesIdSet = getTradesStreamWithFundsLockedIn()
            .filter(Trade::hasFailed)
            .map(Trade::getId)
            .collect(Collectors.toSet());
    tradesIdSet.addAll(failedTradesManager.getTradesStreamWithFundsLockedIn()
            .filter(trade -> trade.getDepositTx() != null)
            .map(trade -> {
                log.warn("We found a failed trade with locked up funds. " +
                        "That should never happen. trade ID=" + trade.getId());
                return trade.getId();
            })
            .collect(Collectors.toSet()));
    tradesIdSet.addAll(closedTradableManager.getTradesStreamWithFundsLockedIn()
            .map(trade -> {
                Transaction depositTx = trade.getDepositTx();
                if (depositTx != null) {
                    TransactionConfidence confidence = btcWalletService.getConfidenceForTxId(depositTx.getHashAsString());
                    if (confidence != null && confidence.getConfidenceType() != TransactionConfidence.ConfidenceType.BUILDING) {
                        tradeTxException.set(new TradeTxException(Res.get("error.closedTradeWithUnconfirmedDepositTx", trade.getShortId())));
                    } else {
                        log.warn("We found a closed trade with locked up funds. " +
                                "That should never happen. trade ID=" + trade.getId());
                    }
                } else {
                    tradeTxException.set(new TradeTxException(Res.get("error.closedTradeWithNoDepositTx", trade.getShortId())));
                }
                return trade.getId();
            })
            .collect(Collectors.toSet()));

    if (tradeTxException.get() != null)
        throw tradeTxException.get();

    return tradesIdSet;
}
 
Example #19
Source File: BuyerSetupDepositTxListener.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private void applyConfidence(TransactionConfidence confidence) {
    if (trade.getDepositTx() == null) {
        Transaction walletTx = processModel.getTradeWalletService().getWalletTx(confidence.getTransactionHash());
        trade.applyDepositTx(walletTx);
        BtcWalletService.printTx("depositTx received from network", walletTx);
        trade.setState(Trade.State.BUYER_SAW_DEPOSIT_TX_IN_NETWORK);
    } else {
        log.info("We got the deposit tx already set from MakerProcessDepositTxPublishedMessage.  tradeId={}, state={}", trade.getId(), trade.getState());
    }

    swapReservedForTradeEntry();

    // need delay as it can be called inside the listener handler before listener and tradeStateSubscription are actually set.
    UserThread.execute(this::unSubscribe);
}
 
Example #20
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 #21
Source File: SetupPayoutTxListener.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected void run() {
    try {
        runInterceptHook();
        if (!trade.isPayoutPublished()) {
            BtcWalletService walletService = processModel.getBtcWalletService();
            String id = processModel.getOffer().getId();
            Address address = walletService.getOrCreateAddressEntry(id, AddressEntry.Context.TRADE_PAYOUT).getAddress();

            TransactionConfidence confidence = walletService.getConfidenceForAddress(address);
            if (isInNetwork(confidence)) {
                applyConfidence(confidence);
            } else {
                confidenceListener = new AddressConfidenceListener(address) {
                    @Override
                    public void onTransactionConfidenceChanged(TransactionConfidence confidence) {
                        if (isInNetwork(confidence))
                            applyConfidence(confidence);
                    }
                };
                walletService.addAddressConfidenceListener(confidenceListener);

                tradeStateSubscription = EasyBind.subscribe(trade.stateProperty(), newValue -> {
                    if (trade.isPayoutPublished()) {
                        swapMultiSigEntry();

                        // hack to remove tradeStateSubscription at callback
                        UserThread.execute(this::unSubscribe);
                    }
                });
            }
        }

        // we complete immediately, our object stays alive because the balanceListener is stored in the WalletService
        complete();
    } catch (Throwable t) {
        failed(t);
    }
}
 
Example #22
Source File: SetupPayoutTxListener.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private void applyConfidence(TransactionConfidence confidence) {
    if (trade.getPayoutTx() == null) {
        Transaction walletTx = processModel.getTradeWalletService().getWalletTx(confidence.getTransactionHash());
        trade.setPayoutTx(walletTx);
        BtcWalletService.printTx("payoutTx received from network", walletTx);
        setState();
    } else {
        log.info("We had the payout tx already set. tradeId={}, state={}", trade.getId(), trade.getState());
    }

    swapMultiSigEntry();

    // need delay as it can be called inside the handler before the listener and tradeStateSubscription are actually set.
    UserThread.execute(this::unSubscribe);
}
 
Example #23
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
// Having a test for deprecated method getFromAddress() is no evil so we suppress the warning here.
public void customTransactionSpending() throws Exception {
    // We'll set up a wallet that receives a coin, then sends a coin of lesser value and keeps the change.
    Coin v1 = valueOf(3, 0);
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, v1);
    assertEquals(v1, wallet.getBalance());
    assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.UNSPENT));
    assertEquals(1, wallet.getTransactions(true).size());

    Coin v2 = valueOf(0, 50);
    Coin v3 = valueOf(0, 75);
    Coin v4 = valueOf(1, 25);

    Transaction t2 = new Transaction(PARAMS);
    t2.addOutput(v2, OTHER_ADDRESS);
    t2.addOutput(v3, OTHER_ADDRESS);
    t2.addOutput(v4, OTHER_ADDRESS);
    SendRequest req = SendRequest.forTx(t2);
    wallet.completeTx(req);

    // Do some basic sanity checks.
    assertEquals(1, t2.getInputs().size());
    assertEquals(myAddress, t2.getInput(0).getScriptSig().getFromAddress(PARAMS));
    assertEquals(TransactionConfidence.ConfidenceType.UNKNOWN, t2.getConfidence().getConfidenceType());

    // We have NOT proven that the signature is correct!
    wallet.commitTx(t2);
    assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.PENDING));
    assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.SPENT));
    assertEquals(2, wallet.getTransactions(true).size());
}
 
Example #24
Source File: ProposalListPresentation.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private void updateLists() {
    List<Proposal> tempProposals = proposalService.getTempProposals();
    Set<Proposal> verifiedProposals = proposalService.getProposalPayloads().stream()
            .map(ProposalPayload::getProposal)
            .filter(proposal -> !daoStateService.isParseBlockChainComplete() ||
                    validatorProvider.getValidator(proposal).isValidAndConfirmed(proposal))
            .collect(Collectors.toSet());
    Set<Proposal> set = new HashSet<>(tempProposals);
    set.addAll(verifiedProposals);

    // We want to show our own unconfirmed proposals. Unconfirmed proposals from other users are not included
    // in the list.
    // If a tx is not found in the daoStateService it can be that it is either unconfirmed or invalid.
    // To avoid inclusion of invalid txs we add a check for the confidence type PENDING from the bsqWalletService.
    // So we only add proposals if they are unconfirmed and therefore not yet parsed. Once confirmed they have to be
    // found in the daoStateService.
    List<Proposal> myUnconfirmedProposals = myProposalListService.getList().stream()
            .filter(p -> !daoStateService.getTx(p.getTxId()).isPresent()) // Tx is still not in our bsq blocks
            .filter(p -> {
                TransactionConfidence confidenceForTxId = bsqWalletService.getConfidenceForTxId(p.getTxId());
                return confidenceForTxId != null &&
                        confidenceForTxId.getConfidenceType() == TransactionConfidence.ConfidenceType.PENDING;
            })
            .collect(Collectors.toList());
    set.addAll(myUnconfirmedProposals);

    allProposals.clear();
    allProposals.addAll(set);

    activeOrMyUnconfirmedProposals.setPredicate(proposal -> validatorProvider.getValidator(proposal).isValidAndConfirmed(proposal) ||
            myUnconfirmedProposals.contains(proposal));
}
 
Example #25
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
// Having a test for deprecated method getFromAddress() is no evil so we suppress the warning here.
public void customTransactionSpending() throws Exception {
    // We'll set up a wallet that receives a coin, then sends a coin of lesser value and keeps the change.
    Coin v1 = valueOf(3, 0);
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, v1);
    assertEquals(v1, wallet.getBalance());
    assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.UNSPENT));
    assertEquals(1, wallet.getTransactions(true).size());

    Coin v2 = valueOf(0, 50);
    Coin v3 = valueOf(0, 75);
    Coin v4 = valueOf(1, 25);

    Transaction t2 = new Transaction(PARAMS);
    t2.addOutput(v2, OTHER_ADDRESS);
    t2.addOutput(v3, OTHER_ADDRESS);
    t2.addOutput(v4, OTHER_ADDRESS);
    SendRequest req = SendRequest.forTx(t2);
    wallet.completeTx(req);

    // Do some basic sanity checks.
    assertEquals(1, t2.getInputs().size());
    assertEquals(myAddress, t2.getInput(0).getScriptSig().getFromAddress(PARAMS));
    assertEquals(TransactionConfidence.ConfidenceType.UNKNOWN, t2.getConfidence().getConfidenceType());

    // We have NOT proven that the signature is correct!
    wallet.commitTx(t2);
    assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.PENDING));
    assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.SPENT));
    assertEquals(2, wallet.getTransactions(true).size());
}
 
Example #26
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
private void receiveATransactionAmount(Wallet wallet, Address toAddress, Coin amount) {
    final ListenableFuture<Coin> availFuture = wallet.getBalanceFuture(amount, Wallet.BalanceType.AVAILABLE);
    final ListenableFuture<Coin> estimatedFuture = wallet.getBalanceFuture(amount, Wallet.BalanceType.ESTIMATED);
    assertFalse(availFuture.isDone());
    assertFalse(estimatedFuture.isDone());
    // Send some pending coins to the wallet.
    Transaction t1 = sendMoneyToWallet(wallet, null, amount, toAddress);
    Threading.waitForUserCode();
    final ListenableFuture<TransactionConfidence> depthFuture = t1.getConfidence().getDepthFuture(1);
    assertFalse(depthFuture.isDone());
    assertEquals(ZERO, wallet.getBalance());
    assertEquals(amount, wallet.getBalance(Wallet.BalanceType.ESTIMATED));
    assertFalse(availFuture.isDone());
    // Our estimated balance has reached the requested level.
    assertTrue(estimatedFuture.isDone());
    assertEquals(1, wallet.getPoolSize(Pool.PENDING));
    assertEquals(0, wallet.getPoolSize(Pool.UNSPENT));
    // Confirm the coins.
    sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, t1);
    assertEquals("Incorrect confirmed tx balance", amount, wallet.getBalance());
    assertEquals("Incorrect confirmed tx PENDING pool size", 0, wallet.getPoolSize(Pool.PENDING));
    assertEquals("Incorrect confirmed tx UNSPENT pool size", 1, wallet.getPoolSize(Pool.UNSPENT));
    assertEquals("Incorrect confirmed tx ALL pool size", 1, wallet.getTransactions(true).size());
    Threading.waitForUserCode();
    assertTrue(availFuture.isDone());
    assertTrue(estimatedFuture.isDone());
    assertTrue(depthFuture.isDone());
}
 
Example #27
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 #28
Source File: WalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@Nullable
public TransactionConfidence getConfidenceForTxId(String txId) {
    if (wallet != null) {
        Set<Transaction> transactions = wallet.getTransactions(false);
        for (Transaction tx : transactions) {
            if (tx.getHashAsString().equals(txId))
                return tx.getConfidence();
        }
    }
    return null;
}
 
Example #29
Source File: DefaultRiskAnalysis.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
private Result analyzeIsFinal() {
    // Transactions we create ourselves are, by definition, not at risk of double spending against us.
    if (tx.getConfidence().getSource() == TransactionConfidence.Source.SELF)
        return Result.OK;

    // We consider transactions that opt into replace-by-fee at risk of double spending.
    if (tx.isOptInFullRBF()) {
        nonFinal = tx;
        return Result.NON_FINAL;
    }

    if (wallet == null)
        return null;

    final int height = wallet.getLastBlockSeenHeight();
    final long time = wallet.getLastBlockSeenTimeSecs();
    // If the transaction has a lock time specified in blocks, we consider that if the tx would become final in the
    // next block it is not risky (as it would confirm normally).
    final int adjustedHeight = height + 1;

    if (!tx.isFinal(adjustedHeight, time)) {
        nonFinal = tx;
        return Result.NON_FINAL;
    }
    for (Transaction dep : dependencies) {
        if (!dep.isFinal(adjustedHeight, time)) {
            nonFinal = dep;
            return Result.NON_FINAL;
        }
    }

    return Result.OK;
}
 
Example #30
Source File: WalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@Nullable
public TransactionConfidence getConfidenceForAddress(Address address) {
    List<TransactionConfidence> transactionConfidenceList = new ArrayList<>();
    if (wallet != null) {
        Set<Transaction> transactions = wallet.getTransactions(false);
        if (transactions != null) {
            transactionConfidenceList.addAll(transactions.stream().map(tx ->
                    getTransactionConfidence(tx, address)).collect(Collectors.toList()));
        }
    }
    return getMostRecentConfidence(transactionConfidenceList);
}