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

The following examples show how to use org.bitcoinj.core.Coin#isLessThan() . 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: GATx.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
public static Coin getTxFee(final GaService service, final Transaction tx, final Coin feeRate) {
    final Coin minRate = service.getMinFeeRate();
    final Coin rate = feeRate.isLessThan(minRate) ? minRate : feeRate;
    Log.d(TAG, "getTxFee(rates): " + rate.value + '/' + feeRate.value + '/' + minRate.value);

    final int vSize = getTxVSize(tx, service.getNetwork());
    final double fee = (double) vSize * rate.value / 1000.0;
    final long roundedFee = (long) Math.ceil(fee); // Round up
    Log.d(TAG, "getTxFee: fee is " + roundedFee);
    return Coin.valueOf(roundedFee);
}
 
Example 2
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 3
Source File: Verifier.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
static Coin verify(final GaService service,
                   final Map<TransactionOutPoint, Coin> countedUtxoValues, final PreparedTransaction ptx,
                   final Address recipient, final Coin amount, final List<Boolean> input) {
    final int changeIdx;
    if (input == null)
        changeIdx = -1;
    else if (input.get(0))
        changeIdx = 0;
    else if (input.get(1))
        changeIdx = 1;
    else
        throw new IllegalArgumentException("Verification: Change output missing.");

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

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

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

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

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

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

    return amount == null ? output.getValue() : fee;
}
 
Example 4
Source File: TransactionActivity.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
private static Pair<Integer, JSONMap>
createRawTransaction(final GaService service,
                     final Transaction tx, final List<JSONMap> usedUtxos,
                     final List<JSONMap> utxos, final int subAccount,
                     GATx.ChangeOutput changeOutput,
                     final Coin amount, final Coin oldFee,
                     final Coin feeRate,
                     final JSONMap privateData, final boolean sendAll) {

    final boolean isRBF = usedUtxos != null;
    final boolean haveExistingChange = changeOutput != null;
    Coin total =  isRBF ? getUtxoSum(usedUtxos) : Coin.ZERO;
    Coin fee;

    // First add inputs until we cover the amount to send
    while ((sendAll || total.isLessThan(amount)) && !utxos.isEmpty())
        total = total.add(GATx.addUtxo(service, tx, utxos, usedUtxos));

    // Then add inputs until we cover amount + fee/change
    while (true) {
        fee = GATx.getTxFee(service, tx, feeRate);
        if (isRBF) {
            final Coin bandwidthFee = GATx.getTxFee(service, tx, service.getMinFeeRate());
            fee = (fee.isLessThan(oldFee) ? oldFee : fee).add(bandwidthFee);
        }

        final Coin minChange = changeOutput == null ? Coin.ZERO : service.getDustThreshold();
        final int cmp = sendAll ? 0 : total.compareTo(amount.add(fee).add(minChange));
        if (cmp < 0) {
            // Need more inputs to cover amount + fee/change
            if (utxos.isEmpty())
                return createFailed(R.string.insufficientFundsText); // None left, fail

            total = total.add(GATx.addUtxo(service, tx, utxos, usedUtxos));
            continue;
        }

        if (cmp == 0 || changeOutput != null) {
            // Inputs exactly match amount + fee/change, or are greater
            // and we have a change output for the excess
            break;
        }

        // Inputs greater than amount + fee, add a change output and try again
        changeOutput = GATx.addChangeOutput(service, tx, subAccount);
        if (changeOutput == null)
            return createFailed(R.string.unable_to_create_change);
    }

    boolean randomizedChange = false;
    if (changeOutput != null) {
        // Set the value of the change output
        if (tx.getOutputs().size() == 1)
            changeOutput.mOutput.setValue(total.subtract(fee)); // Redeposit
        else
            changeOutput.mOutput.setValue(total.subtract(amount).subtract(fee));
        if (haveExistingChange)
            randomizedChange = changeOutput.mOutput == tx.getOutput(0);
        else
            randomizedChange = GATx.randomizeChangeOutput(tx);
    }

    if (sendAll) {
        final Coin actualAmount = total.subtract(fee);
        if (!actualAmount.isGreaterThan(Coin.ZERO))
            return createFailed(R.string.insufficientFundsText);
        final int amtIndex = tx.getOutputs().size() == 1 ? 0 : (randomizedChange ? 1 : 0);
        tx.getOutput(amtIndex).setValue(actualAmount);
    }

    tx.setLockTime(service.getCurrentBlock()); // Prevent fee sniping

    int changeIndex = -1;
    if (changeOutput != null && tx.getOutputs().size() != 1)
        changeIndex = randomizedChange ? 0 : 1;
    return new Pair<>(0,
                      GATx.makeLimitsData(fee.subtract(oldFee), fee, changeIndex));
}
 
Example 5
Source File: SendFragment.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
private int createRawTransaction(final List<JSONMap> utxos, final String recipient,
                                 final Coin amount, final JSONMap privateData,
                                 final boolean sendAll, final Coin feeRate) {
    final GaService service = getGAService();

    if (service.isElements())
        return createRawElementsTransaction(utxos, recipient, amount, privateData, sendAll, feeRate);

    final GaActivity gaActivity = getGaActivity();

    final List<JSONMap> usedUtxos = new ArrayList<>();

    final Transaction tx = new Transaction(service.getNetworkParameters());

    if (!GATx.addTxOutput(service, tx, amount, recipient))
        return R.string.invalidAddress;

    Coin total = Coin.ZERO;
    Coin fee;
    boolean randomizedChange = false;
    GATx.ChangeOutput changeOutput = null;

    // First add inputs until we cover the amount to send
    while ((sendAll || total.isLessThan(amount)) && !utxos.isEmpty())
        total = total.add(GATx.addUtxo(service, tx, utxos, usedUtxos));

    // Then add inputs until we cover amount + fee/change
    while (true) {
        fee = GATx.getTxFee(service, tx, feeRate);

        final Coin minChange = changeOutput == null ? Coin.ZERO : service.getDustThreshold();
        final int cmp = sendAll ? 0 : total.compareTo(amount.add(fee).add(minChange));
        if (cmp < 0) {
            // Need more inputs to cover amount + fee/change
            if (utxos.isEmpty())
                return R.string.insufficientFundsText; // None left, fail

            total = total.add(GATx.addUtxo(service, tx, utxos, usedUtxos));
            continue;
        }

        if (cmp == 0 || changeOutput != null) {
            // Inputs exactly match amount + fee/change, or are greater
            // and we have a change output for the excess
            break;
        }

        // Inputs greater than amount + fee, add a change output and try again
        changeOutput = GATx.addChangeOutput(service, tx, mSubaccount);
        if (changeOutput == null)
            return R.string.unable_to_create_change;
    }

    if (changeOutput != null) {
        // Set the value of the change output
        changeOutput.mOutput.setValue(total.subtract(amount).subtract(fee));
        randomizedChange = GATx.randomizeChangeOutput(tx);
    }

    final Coin actualAmount;
    if (!sendAll)
        actualAmount = amount;
    else {
        actualAmount = total.subtract(fee);
        if (!actualAmount.isGreaterThan(Coin.ZERO))
            return R.string.insufficientFundsText;
        tx.getOutput(randomizedChange ? 1 : 0).setValue(actualAmount);
    }

    tx.setLockTime(service.getCurrentBlock()); // Prevent fee sniping

    final PreparedTransaction ptx;
    ptx = GATx.signTransaction(service, tx, usedUtxos, mSubaccount, changeOutput);

    final int changeIndex = changeOutput == null ? -1 : (randomizedChange ? 0 : 1);
    final JSONMap underLimits = GATx.makeLimitsData(actualAmount.add(fee), fee, changeIndex);

    final boolean skipChoice = service.isUnderLimit(underLimits.getCoin("amount"));
    final Coin sendFee = fee;
    gaActivity.runOnUiThread(new Runnable() {
        public void run() {
            mSendButton.setEnabled(true);
            mTwoFactor = UI.popupTwoFactorChoice(gaActivity, service, skipChoice,
                                                 new CB.Runnable1T<String>() {
                public void run(String method) {
                    if (skipChoice && service.hasAnyTwoFactor())
                        method = "limit";
                    onTransactionValidated(null, tx, recipient, actualAmount,
                                           method, sendFee, privateData, underLimits);
                }
            });
            if (mTwoFactor != null)
                mTwoFactor.show();
        }
    });
    return 0;
}
 
Example 6
Source File: SignedWitnessService.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
public boolean isSufficientTradeAmountForSigning(Coin tradeAmount) {
    return !tradeAmount.isLessThan(MINIMUM_TRADE_AMOUNT_FOR_SIGNING);
}