Java Code Examples for org.bitcoinj.core.Coin#isPositive()

The following examples show how to use org.bitcoinj.core.Coin#isPositive() . 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: BsqWalletService.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
private void addInputsAndChangeOutputForTx(Transaction tx, Coin fee, BsqCoinSelector bsqCoinSelector)
        throws InsufficientBsqException {
    Coin requiredInput;
    // If our fee is less then dust limit we increase it so we are sure to not get any dust output.
    if (Restrictions.isDust(fee))
        requiredInput = Restrictions.getMinNonDustOutput().add(fee);
    else
        requiredInput = fee;

    CoinSelection coinSelection = bsqCoinSelector.select(requiredInput, wallet.calculateAllSpendCandidates());
    coinSelection.gathered.forEach(tx::addInput);
    try {
        // TODO why is fee passed to getChange ???
        Coin change = this.bsqCoinSelector.getChange(fee, coinSelection);
        if (change.isPositive()) {
            checkArgument(Restrictions.isAboveDust(change), "We must not get dust output here.");
            tx.addOutput(change, getUnusedAddress());
        }
    } catch (InsufficientMoneyException e) {
        throw new InsufficientBsqException(e.missing);
    }
}
 
Example 2
Source File: SupplyView.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
private void updateWithBsqBlockChainData() {
    Coin issuedAmountFromGenesis = daoFacade.getGenesisTotalSupply();
    genesisIssueAmountTextField.setText(bsqFormatter.formatAmountWithGroupSeparatorAndCode(issuedAmountFromGenesis));

    Coin issuedAmountFromCompRequests = Coin.valueOf(daoFacade.getTotalIssuedAmount(IssuanceType.COMPENSATION));
    compRequestIssueAmountTextField.setText(bsqFormatter.formatAmountWithGroupSeparatorAndCode(issuedAmountFromCompRequests));
    Coin issuedAmountFromReimbursementRequests = Coin.valueOf(daoFacade.getTotalIssuedAmount(IssuanceType.REIMBURSEMENT));
    reimbursementAmountTextField.setText(bsqFormatter.formatAmountWithGroupSeparatorAndCode(issuedAmountFromReimbursementRequests));

    Coin totalBurntFee = Coin.valueOf(daoFacade.getTotalBurntFee());
    Coin totalLockedUpAmount = Coin.valueOf(daoFacade.getTotalLockupAmount());
    Coin totalUnlockingAmount = Coin.valueOf(daoFacade.getTotalAmountOfUnLockingTxOutputs());
    Coin totalUnlockedAmount = Coin.valueOf(daoFacade.getTotalAmountOfUnLockedTxOutputs());
    Coin totalConfiscatedAmount = Coin.valueOf(daoFacade.getTotalAmountOfConfiscatedTxOutputs());
    Coin totalAmountOfInvalidatedBsq = Coin.valueOf(daoFacade.getTotalAmountOfInvalidatedBsq());

    totalBurntFeeAmountTextField.setText("-" + bsqFormatter.formatAmountWithGroupSeparatorAndCode(totalBurntFee));
    totalLockedUpAmountTextField.setText(bsqFormatter.formatAmountWithGroupSeparatorAndCode(totalLockedUpAmount));
    totalUnlockingAmountTextField.setText(bsqFormatter.formatAmountWithGroupSeparatorAndCode(totalUnlockingAmount));
    totalUnlockedAmountTextField.setText(bsqFormatter.formatAmountWithGroupSeparatorAndCode(totalUnlockedAmount));
    totalConfiscatedAmountTextField.setText(bsqFormatter.formatAmountWithGroupSeparatorAndCode(totalConfiscatedAmount));
    String minusSign = totalAmountOfInvalidatedBsq.isPositive() ? "-" : "";
    totalAmountOfInvalidatedBsqTextField.setText(minusSign + bsqFormatter.formatAmountWithGroupSeparatorAndCode(totalAmountOfInvalidatedBsq));

    updateChartSeries();
}
 
Example 3
Source File: DisputeSummaryWindow.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
private boolean isPayoutAmountValid() {
    Coin buyerAmount = ParsingUtils.parseToCoin(buyerPayoutAmountInputTextField.getText(), formatter);
    Coin sellerAmount = ParsingUtils.parseToCoin(sellerPayoutAmountInputTextField.getText(), formatter);
    Contract contract = dispute.getContract();
    Coin tradeAmount = contract.getTradeAmount();
    Offer offer = new Offer(contract.getOfferPayload());
    Coin available = tradeAmount
            .add(offer.getBuyerSecurityDeposit())
            .add(offer.getSellerSecurityDeposit());
    Coin totalAmount = buyerAmount.add(sellerAmount);

    if (!totalAmount.isPositive()) {
        return false;
    }

    if (getDisputeManager(dispute) instanceof RefundManager) {
        // We allow to spend less in case of RefundAgent
        return totalAmount.compareTo(available) <= 0;
    } else {
        return totalAmount.compareTo(available) == 0;
    }
}
 
Example 4
Source File: BsqWalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public Transaction signTx(Transaction tx) throws WalletException, TransactionVerificationException {
    for (int i = 0; i < tx.getInputs().size(); i++) {
        TransactionInput txIn = tx.getInputs().get(i);
        TransactionOutput connectedOutput = txIn.getConnectedOutput();
        if (connectedOutput != null && connectedOutput.isMine(wallet)) {
            signTransactionInput(wallet, aesKey, tx, txIn, i);
            checkScriptSig(tx, txIn, i);
        }
    }

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

    checkWalletConsistency(wallet);
    verifyTransaction(tx);
    printTx("BSQ wallet: Signed Tx", tx);
    return tx;
}
 
Example 5
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
private Transaction createPayoutTx(Transaction depositTx,
                                   Coin buyerPayoutAmount,
                                   Coin sellerPayoutAmount,
                                   String buyerAddressString,
                                   String sellerAddressString) throws AddressFormatException {
    TransactionOutput p2SHMultiSigOutput = depositTx.getOutput(0);
    Transaction transaction = new Transaction(params);
    transaction.addInput(p2SHMultiSigOutput);
    if (buyerPayoutAmount.isPositive()) {
        transaction.addOutput(buyerPayoutAmount, Address.fromBase58(params, buyerAddressString));
    }
    if (sellerPayoutAmount.isPositive()) {
        transaction.addOutput(sellerPayoutAmount, Address.fromBase58(params, sellerAddressString));
    }
    checkArgument(transaction.getOutputs().size() >= 1, "We need at least one output.");
    return transaction;
}
 
Example 6
Source File: TakeOfferView.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public void onClose() {
    Coin balance = model.dataModel.getBalance().get();
    if (balance != null && balance.isPositive() && !model.takeOfferCompleted.get() && !DevEnv.isDevMode()) {
        model.dataModel.swapTradeToSavings();
        new Popup().information(Res.get("takeOffer.alreadyFunded.movedFunds"))
                .actionButtonTextWithGoTo("navigation.funds.availableForWithdrawal")
                .onAction(() -> navigation.navigateTo(MainView.class, FundsView.class, WithdrawalView.class))
                .show();
    }

    // TODO need other implementation as it is displayed also if there are old funds in the wallet
    /*
    if (model.dataModel.getIsWalletFunded().get())
        new Popup<>().warning("You have already funds paid in.\nIn the <Funds/Open for withdrawal> section you can withdraw those funds.").show();*/
}
 
Example 7
Source File: TakeOfferDataModel.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
boolean wouldCreateDustForMaker() {
    //noinspection SimplifiableIfStatement
    boolean result;
    if (amount.get() != null && offer != null) {
        Coin customAmount = offer.getAmount().subtract(amount.get());
        result = customAmount.isPositive() && customAmount.isLessThan(Restrictions.getMinNonDustOutput());

        if (result)
            log.info("would create dust for maker, customAmount={},  Restrictions.getMinNonDustOutput()={}", customAmount, Restrictions.getMinNonDustOutput());
    } else {
        result = true;
    }
    return result;
}
 
Example 8
Source File: BalanceWithConfirmationTextField.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private void updateBalance(Coin balance) {
    textField.setText(formatter.formatCoinWithCode(balance));
    if (balance.isPositive())
        textField.setEffect(fundedEffect);
    else
        textField.setEffect(notFundedEffect);
}
 
Example 9
Source File: BsqWalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private void addInputsAndChangeOutputForTx(Transaction tx,
                                           Coin fee,
                                           BsqCoinSelector bsqCoinSelector)
        throws InsufficientBsqException {
    Coin requiredInput;
    // If our fee is less then dust limit we increase it so we are sure to not get any dust output.
    if (Restrictions.isDust(fee)) {
        requiredInput = fee.add(Restrictions.getMinNonDustOutput());
    } else {
        requiredInput = fee;
    }

    CoinSelection coinSelection = bsqCoinSelector.select(requiredInput, wallet.calculateAllSpendCandidates());
    coinSelection.gathered.forEach(tx::addInput);
    try {
        Coin change = bsqCoinSelector.getChange(fee, coinSelection);
        if (change.isPositive()) {
            checkArgument(Restrictions.isAboveDust(change),
                    "The change output of " + change.value / 100d + " BSQ is below the min. dust value of "
                            + Restrictions.getMinNonDustOutput().value / 100d +
                            ". At least " + Restrictions.getMinNonDustOutput().add(fee).value / 100d +
                            " BSQ is needed for this transaction");
            tx.addOutput(change, getChangeAddress());
        }
    } catch (InsufficientMoneyException e) {
        log.error(tx.toString());
        throw new InsufficientBsqException(e.missing);
    }
}
 
Example 10
Source File: DisputeSummaryWindow.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
private void showPayoutTxConfirmation(Contract contract, DisputeResult disputeResult, ResultHandler resultHandler) {
    Coin buyerPayoutAmount = disputeResult.getBuyerPayoutAmount();
    String buyerPayoutAddressString = contract.getBuyerPayoutAddressString();
    Coin sellerPayoutAmount = disputeResult.getSellerPayoutAmount();
    String sellerPayoutAddressString = contract.getSellerPayoutAddressString();
    Coin outputAmount = buyerPayoutAmount.add(sellerPayoutAmount);
    Tuple2<Coin, Integer> feeTuple = txFeeEstimationService.getEstimatedFeeAndTxSize(outputAmount, feeService, btcWalletService);
    Coin fee = feeTuple.first;
    Integer txSize = feeTuple.second;
    double feePerByte = CoinUtil.getFeePerByte(fee, txSize);
    double kb = txSize / 1000d;
    Coin inputAmount = outputAmount.add(fee);
    String buyerDetails = "";
    if (buyerPayoutAmount.isPositive()) {
        buyerDetails = Res.get("disputeSummaryWindow.close.txDetails.buyer",
                formatter.formatCoinWithCode(buyerPayoutAmount),
                buyerPayoutAddressString);
    }
    String sellerDetails = "";
    if (sellerPayoutAmount.isPositive()) {
        sellerDetails = Res.get("disputeSummaryWindow.close.txDetails.seller",
                formatter.formatCoinWithCode(sellerPayoutAmount),
                sellerPayoutAddressString);
    }
    new Popup().width(900)
            .headLine(Res.get("disputeSummaryWindow.close.txDetails.headline"))
            .confirmation(Res.get("disputeSummaryWindow.close.txDetails",
                    formatter.formatCoinWithCode(inputAmount),
                    buyerDetails,
                    sellerDetails,
                    formatter.formatCoinWithCode(fee),
                    feePerByte,
                    kb))
            .actionButtonText(Res.get("shared.yes"))
            .onAction(() -> {
                doPayout(buyerPayoutAmount,
                        sellerPayoutAmount,
                        fee,
                        buyerPayoutAddressString,
                        sellerPayoutAddressString,
                        resultHandler);
            })
            .closeButtonText(Res.get("shared.cancel"))
            .onClose(() -> {
            })
            .show();
}
 
Example 11
Source File: BtcWalletService.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
public Transaction createRefundPayoutTx(Coin buyerAmount,
                                        Coin sellerAmount,
                                        Coin fee,
                                        String buyerAddressString,
                                        String sellerAddressString)
        throws AddressFormatException, InsufficientMoneyException, WalletException, TransactionVerificationException {
    Transaction tx = new Transaction(params);
    Preconditions.checkArgument(buyerAmount.add(sellerAmount).isPositive(),
            "The sellerAmount + buyerAmount must be positive.");
    // buyerAmount can be 0
    if (buyerAmount.isPositive()) {
        Preconditions.checkArgument(Restrictions.isAboveDust(buyerAmount),
                "The buyerAmount is too low (dust limit).");

        tx.addOutput(buyerAmount, Address.fromBase58(params, buyerAddressString));
    }
    // sellerAmount can be 0
    if (sellerAmount.isPositive()) {
        Preconditions.checkArgument(Restrictions.isAboveDust(sellerAmount),
                "The sellerAmount is too low (dust limit).");

        tx.addOutput(sellerAmount, Address.fromBase58(params, sellerAddressString));
    }

    SendRequest sendRequest = SendRequest.forTx(tx);
    sendRequest.fee = fee;
    sendRequest.feePerKb = Coin.ZERO;
    sendRequest.ensureMinRequiredFee = false;
    sendRequest.aesKey = aesKey;
    sendRequest.shuffleOutputs = false;
    sendRequest.coinSelector = new BtcCoinSelector(walletsSetup.getAddressesByContext(AddressEntry.Context.AVAILABLE),
            preferences.getIgnoreDustThreshold());
    sendRequest.changeAddress = getFreshAddressEntry().getAddress();

    checkNotNull(wallet);
    wallet.completeTx(sendRequest);

    Transaction resultTx = sendRequest.tx;
    checkWalletConsistency(wallet);
    verifyTransaction(resultTx);

    WalletService.printTx("createRefundPayoutTx", resultTx);

    return resultTx;
}
 
Example 12
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * A trader who got the signed tx from the arbitrator finalizes the payout tx.
 *
 * @param depositTxSerialized    serialized deposit tx
 * @param arbitratorSignature    DER encoded canonical signature of arbitrator
 * @param buyerPayoutAmount      payout amount of the buyer
 * @param sellerPayoutAmount     payout amount of the seller
 * @param buyerAddressString     the address of the buyer
 * @param sellerAddressString    the address of the seller
 * @param tradersMultiSigKeyPair the key pair for the MultiSig of the trader who calls that method
 * @param buyerPubKey            the public key of the buyer
 * @param sellerPubKey           the public key of the seller
 * @param arbitratorPubKey       the public key of the arbitrator
 * @return the completed payout tx
 * @throws AddressFormatException if the buyer or seller base58 address doesn't parse or its checksum is invalid
 * @throws TransactionVerificationException if there was an unexpected problem with the payout tx or its signature
 * @throws WalletException if the trade wallet is null or structurally inconsistent
 */
public Transaction traderSignAndFinalizeDisputedPayoutTx(byte[] depositTxSerialized,
                                                         byte[] arbitratorSignature,
                                                         Coin buyerPayoutAmount,
                                                         Coin sellerPayoutAmount,
                                                         String buyerAddressString,
                                                         String sellerAddressString,
                                                         DeterministicKey tradersMultiSigKeyPair,
                                                         byte[] buyerPubKey,
                                                         byte[] sellerPubKey,
                                                         byte[] arbitratorPubKey)
        throws AddressFormatException, TransactionVerificationException, WalletException {
    Transaction depositTx = new Transaction(params, depositTxSerialized);
    TransactionOutput p2SHMultiSigOutput = depositTx.getOutput(0);
    Transaction payoutTx = new Transaction(params);
    payoutTx.addInput(p2SHMultiSigOutput);
    if (buyerPayoutAmount.isPositive()) {
        payoutTx.addOutput(buyerPayoutAmount, Address.fromBase58(params, buyerAddressString));
    }
    if (sellerPayoutAmount.isPositive()) {
        payoutTx.addOutput(sellerPayoutAmount, Address.fromBase58(params, sellerAddressString));
    }

    // take care of sorting!
    Script redeemScript = get2of3MultiSigRedeemScript(buyerPubKey, sellerPubKey, arbitratorPubKey);
    Sha256Hash sigHash = payoutTx.hashForSignature(0, redeemScript, Transaction.SigHash.ALL, false);
    checkNotNull(tradersMultiSigKeyPair, "tradersMultiSigKeyPair must not be null");
    if (tradersMultiSigKeyPair.isEncrypted()) {
        checkNotNull(aesKey);
    }
    ECKey.ECDSASignature tradersSignature = tradersMultiSigKeyPair.sign(sigHash, aesKey).toCanonicalised();
    TransactionSignature tradersTxSig = new TransactionSignature(tradersSignature, Transaction.SigHash.ALL, false);
    TransactionSignature arbitratorTxSig = new TransactionSignature(ECKey.ECDSASignature.decodeFromDER(arbitratorSignature),
            Transaction.SigHash.ALL, false);
    // Take care of order of signatures. See comment below at getMultiSigRedeemScript (sort order needed here: arbitrator, seller, buyer)
    Script inputScript = ScriptBuilder.createP2SHMultiSigInputScript(ImmutableList.of(arbitratorTxSig, tradersTxSig),
            redeemScript);
    TransactionInput input = payoutTx.getInput(0);
    input.setScriptSig(inputScript);
    WalletService.printTx("disputed payoutTx", payoutTx);
    WalletService.verifyTransaction(payoutTx);
    WalletService.checkWalletConsistency(wallet);
    WalletService.checkScriptSig(payoutTx, input, 0);
    checkNotNull(input.getConnectedOutput(), "input.getConnectedOutput() must not be null");
    input.verify(input.getConnectedOutput());
    return payoutTx;
}
 
Example 13
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
public void emergencySignAndPublishPayoutTxFrom2of2MultiSig(String depositTxHex,
                                                            Coin buyerPayoutAmount,
                                                            Coin sellerPayoutAmount,
                                                            Coin txFee,
                                                            String buyerAddressString,
                                                            String sellerAddressString,
                                                            String buyerPrivateKeyAsHex,
                                                            String sellerPrivateKeyAsHex,
                                                            String buyerPubKeyAsHex,
                                                            String sellerPubKeyAsHex,
                                                            TxBroadcaster.Callback callback)
        throws AddressFormatException, TransactionVerificationException, WalletException {
    byte[] buyerPubKey = ECKey.fromPublicOnly(Utils.HEX.decode(buyerPubKeyAsHex)).getPubKey();
    byte[] sellerPubKey = ECKey.fromPublicOnly(Utils.HEX.decode(sellerPubKeyAsHex)).getPubKey();

    Script p2SHMultiSigOutputScript = get2of2MultiSigOutputScript(buyerPubKey, sellerPubKey);

    Coin msOutput = buyerPayoutAmount.add(sellerPayoutAmount).add(txFee);
    TransactionOutput p2SHMultiSigOutput = new TransactionOutput(params, null, msOutput, p2SHMultiSigOutputScript.getProgram());
    Transaction depositTx = new Transaction(params);
    depositTx.addOutput(p2SHMultiSigOutput);

    Transaction payoutTx = new Transaction(params);
    Sha256Hash spendTxHash = Sha256Hash.wrap(depositTxHex);
    payoutTx.addInput(new TransactionInput(params, depositTx, p2SHMultiSigOutputScript.getProgram(), new TransactionOutPoint(params, 0, spendTxHash), msOutput));

    if (buyerPayoutAmount.isPositive()) {
        payoutTx.addOutput(buyerPayoutAmount, Address.fromBase58(params, buyerAddressString));
    }
    if (sellerPayoutAmount.isPositive()) {
        payoutTx.addOutput(sellerPayoutAmount, Address.fromBase58(params, sellerAddressString));
    }

    // take care of sorting!
    Script redeemScript = get2of2MultiSigRedeemScript(buyerPubKey, sellerPubKey);
    Sha256Hash sigHash = payoutTx.hashForSignature(0, redeemScript, Transaction.SigHash.ALL, false);

    ECKey buyerPrivateKey = ECKey.fromPrivate(Utils.HEX.decode(buyerPrivateKeyAsHex));
    checkNotNull(buyerPrivateKey, "key must not be null");
    ECKey.ECDSASignature buyerECDSASignature = buyerPrivateKey.sign(sigHash, aesKey).toCanonicalised();

    ECKey sellerPrivateKey = ECKey.fromPrivate(Utils.HEX.decode(sellerPrivateKeyAsHex));
    checkNotNull(sellerPrivateKey, "key must not be null");
    ECKey.ECDSASignature sellerECDSASignature = sellerPrivateKey.sign(sigHash, aesKey).toCanonicalised();

    TransactionSignature buyerTxSig = new TransactionSignature(buyerECDSASignature, Transaction.SigHash.ALL, false);
    TransactionSignature sellerTxSig = new TransactionSignature(sellerECDSASignature, Transaction.SigHash.ALL, false);
    Script inputScript = ScriptBuilder.createP2SHMultiSigInputScript(ImmutableList.of(sellerTxSig, buyerTxSig), redeemScript);

    TransactionInput input = payoutTx.getInput(0);
    input.setScriptSig(inputScript);
    WalletService.printTx("payoutTx", payoutTx);
    WalletService.verifyTransaction(payoutTx);
    WalletService.checkWalletConsistency(wallet);
    broadcastTx(payoutTx, callback, 20);
}