Example usage for java.math BigInteger subtract

List of usage examples for java.math BigInteger subtract

Introduction

In this page you can find the example usage for java.math BigInteger subtract.

Prototype

public BigInteger subtract(BigInteger val) 

Source Link

Document

Returns a BigInteger whose value is (this - val) .

Usage

From source file:de.schildbach.litecoinwallet.ui.SendCoinsFragment.java

private void validateAmounts(final boolean popups) {
    isValidAmounts = false;// w w  w .  jav  a  2  s .co  m

    final BigInteger amount = amountCalculatorLink.getAmount();

    if (amount == null) {
        // empty amount
        if (popups)
            popupMessage(amountCalculatorLink.activeView(),
                    getString(R.string.send_coins_fragment_amount_empty));
    } else if (amount.signum() > 0) {
        final BigInteger estimated = wallet.getBalance(BalanceType.ESTIMATED);
        final BigInteger available = wallet.getBalance(BalanceType.AVAILABLE);
        final BigInteger pending = estimated.subtract(available);
        // TODO subscribe to litecoinwallet changes

        final BigInteger availableAfterAmount = available.subtract(amount);
        final boolean enoughFundsForAmount = availableAfterAmount.signum() >= 0;

        if (enoughFundsForAmount) {
            // everything fine
            isValidAmounts = true;
        } else {
            // not enough funds for amount
            if (popups)
                popupAvailable(amountCalculatorLink.activeView(), available, pending);
        }
    } else {
        // invalid amount
        if (popups)
            popupMessage(amountCalculatorLink.activeView(),
                    getString(R.string.send_coins_fragment_amount_error));
    }

    updateView();
}

From source file:org.apache.hadoop.hbase.util.Bytes.java

/**
 * Iterate over keys within the passed range.
 *//*from w ww.  java  2 s .  c om*/
public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, boolean inclusive,
        final int num) {
    byte[] aPadded;
    byte[] bPadded;
    if (a.length < b.length) {
        aPadded = padTail(a, b.length - a.length);
        bPadded = b;
    } else if (b.length < a.length) {
        aPadded = a;
        bPadded = padTail(b, a.length - b.length);
    } else {
        aPadded = a;
        bPadded = b;
    }
    if (compareTo(aPadded, bPadded) >= 0) {
        throw new IllegalArgumentException("b <= a");
    }
    if (num <= 0) {
        throw new IllegalArgumentException("num cannot be <= 0");
    }
    byte[] prependHeader = { 1, 0 };
    final BigInteger startBI = new BigInteger(add(prependHeader, aPadded));
    final BigInteger stopBI = new BigInteger(add(prependHeader, bPadded));
    BigInteger diffBI = stopBI.subtract(startBI);
    if (inclusive) {
        diffBI = diffBI.add(BigInteger.ONE);
    }
    final BigInteger splitsBI = BigInteger.valueOf(num + 1);
    if (diffBI.compareTo(splitsBI) < 0) {
        return null;
    }
    final BigInteger intervalBI;
    try {
        intervalBI = diffBI.divide(splitsBI);
    } catch (Exception e) {
        LOG.error("Exception caught during division", e);
        return null;
    }

    final Iterator<byte[]> iterator = new Iterator<byte[]>() {
        private int i = -1;

        @Override
        public boolean hasNext() {
            return i < num + 1;
        }

        @Override
        public byte[] next() {
            i++;
            if (i == 0)
                return a;
            if (i == num + 1)
                return b;

            BigInteger curBI = startBI.add(intervalBI.multiply(BigInteger.valueOf(i)));
            byte[] padded = curBI.toByteArray();
            if (padded[1] == 0)
                padded = tail(padded, padded.length - 2);
            else
                padded = tail(padded, padded.length - 1);
            return padded;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }

    };

    return new Iterable<byte[]>() {
        @Override
        public Iterator<byte[]> iterator() {
            return iterator;
        }
    };
}

From source file:com.mastercard.mcbp.utils.crypto.CryptoServiceImpl.java

/**
 * {@inheritDoc}//from   w  w  w. j a  va  2 s . c o  m
 */
@Override
public final int initRsaPrivateKey(final ByteArray primeP, final ByteArray primeQ,
        final ByteArray primeExponentP, final ByteArray primeExponentQ, final ByteArray crtCoefficient)
        throws McbpCryptoException {
    try {
        final BigInteger p = new BigInteger(primeP.toHexString(), 16);
        final BigInteger q = new BigInteger(primeQ.toHexString(), 16);
        final BigInteger dp = new BigInteger(primeExponentP.toHexString(), 16);
        final BigInteger dq = new BigInteger(primeExponentQ.toHexString(), 16);
        final BigInteger a = new BigInteger(crtCoefficient.toHexString(), 16);

        final BigInteger n = p.multiply(q);
        final BigInteger e = dp.modInverse(p.subtract(BigInteger.ONE));

        final BigInteger d = e.modInverse(p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE))
                .divide((p.subtract(BigInteger.ONE)).gcd(q.subtract(BigInteger.ONE))));

        final RSAPrivateKey rsaKey = (RSAPrivateKey) KeyFactory.getInstance("RSA")
                .generatePrivate(new RSAPrivateCrtKeySpec(n, e, d, p, q, dp, dq, a));

        initRsaPrivate(rsaKey);

        return n.bitLength() / 8;

    } catch (final NoSuchAlgorithmException | InvalidKeySpecException e) {
        throw new McbpCryptoException(e.toString());
    }
}

From source file:org.owasp.webscarab.plugin.sessionid.swing.SessionIDPanel.java

private void updateStats() {
    if (_key == null) {
        maxTextField.setText("");
        minTextField.setText("");
        rangeTextField.setText("");
        return;//  w ww .  j  a v  a 2 s .  c o m
    }
    BigInteger min = _model.getMinimumValue(_key);
    BigInteger max = _model.getMaximumValue(_key);
    if (min != null) {
        minTextField.setText(min.toString());
    } else {
        minTextField.setText("");
    }
    if (max != null) {
        maxTextField.setText(max.toString());
    } else {
        maxTextField.setText("");
    }
    if (min != null && max != null) {
        BigInteger range = max.subtract(min);
        rangeTextField.setText(Float.toString(range.floatValue()));
    } else {
        rangeTextField.setText("");
    }
}

From source file:com.jkoolcloud.jesl.simulator.TNT4JSimulatorParserHandler.java

protected String processVarValue(String value) throws SAXParseException {
    double valueNext = 0;
    double totalValue = 0;
    String symbol = null;/*  w  w  w. j a v a2  s.c o m*/

    // If addition or multiplication are specified, then do the math.
    // For now, only one or the other is permitted.
    if (value.indexOf("+") > 0 && (value.indexOf("*") > 0))
        throw new SAXParseException("Either multiplicaton or addition but not both are allowed", saxLocator);
    else if (value.indexOf("bet") > 0) {
        if ((value.substring(value.indexOf("bet") + 4, value.length()).length() > 9)) {
            BigInteger min = new BigInteger(value.substring(0, value.indexOf("bet") - 1));
            BigInteger max = new BigInteger(value.substring(value.indexOf("bet") + 4, value.length()));
            BigInteger diff = max.subtract(min);
            diff = diff.add(new BigInteger("1"));
            BigInteger rnd = new BigInteger(diff.bitLength(), random);
            BigInteger finalVal = rnd.add(min);
            value = "" + finalVal;
        } else {
            int min = Integer.parseInt(value.substring(0, value.indexOf("bet") - 1));
            int max = Integer.parseInt(value.substring(value.indexOf("bet") + 4, value.length()));
            value = "" + (random.nextInt(max - min + 1) + min);
        }
    } else if ((value.indexOf("+") > 0 && (value.indexOf("*") < 0))
            || (value.indexOf("*") > 0 && (value.indexOf("+") < 0))) {
        symbol = (value.indexOf("+") > 0) ? "+" : "*";
        totalValue = symbol.equals("*") ? 1 : 0;
        while (value.indexOf(symbol) > 0) {
            valueNext = Double.parseDouble(vars.get(value.substring(0, value.indexOf(symbol) - 1)));
            if (symbol.equals("+"))
                totalValue = totalValue + valueNext;
            else
                totalValue = totalValue * valueNext;
            value = value.substring(value.indexOf(symbol) + 2, value.length());
        }
        totalValue = symbol.equals("*") ? totalValue * Double.parseDouble(value)
                : totalValue + Double.parseDouble(vars.get(value.substring(0, value.length())));
        value = "" + totalValue;
    }
    return value;
}

From source file:de.schildbach.wallet.ui.SendCoinsFragment.java

private void handleGo() {
    state = State.PREPARATION;/*from   w  w  w  .  j av a  2s  . c o  m*/
    updateView();

    // final payment intent
    final PaymentIntent finalPaymentIntent = paymentIntent.mergeWithEditedValues(
            amountCalculatorLink.getAmount(), validatedAddress != null ? validatedAddress.address : null);
    final BigInteger finalAmount = finalPaymentIntent.getAmount();

    // prepare send request
    final SendRequest sendRequest = finalPaymentIntent.toSendRequest();
    final Address returnAddress = WalletUtils.pickOldestKey(wallet).toAddress(Constants.NETWORK_PARAMETERS);
    sendRequest.changeAddress = returnAddress;
    sendRequest.emptyWallet = paymentIntent.mayEditAmount()
            && finalAmount.equals(wallet.getBalance(BalanceType.AVAILABLE));

    new SendCoinsOfflineTask(wallet, backgroundHandler) {
        @Override
        protected void onSuccess(final Transaction transaction) {
            sentTransaction = transaction;

            state = State.SENDING;
            updateView();

            sentTransaction.getConfidence().addEventListener(sentTransactionConfidenceListener);

            directPay(sentTransaction);

            application.broadcastTransaction(sentTransaction);

            final Intent result = new Intent();
            BitcoinIntegration.transactionHashToResult(result, sentTransaction.getHashAsString());
            activity.setResult(Activity.RESULT_OK, result);
        }

        private void directPay(final Transaction transaction) {
            if (directPaymentEnableView.isChecked()) {
                final DirectPaymentTask.ResultCallback callback = new DirectPaymentTask.ResultCallback() {
                    @Override
                    public void onResult(final boolean ack) {
                        directPaymentAck = ack;

                        if (state == State.SENDING)
                            state = State.SENT;

                        updateView();
                    }

                    @Override
                    public void onFail(final String message) {
                        final DialogBuilder dialog = new DialogBuilder(activity);
                        dialog.setIcon(R.drawable.ic_menu_warning);
                        dialog.setTitle(R.string.send_coins_fragment_direct_payment_failed_title);
                        dialog.setMessage(paymentIntent.paymentUrl + "\n" + message + "\n\n"
                                + getString(R.string.send_coins_fragment_direct_payment_failed_msg));
                        dialog.setPositiveButton(R.string.button_retry, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialog, final int which) {
                                directPay(transaction);
                            }
                        });
                        dialog.setNegativeButton(R.string.button_dismiss, null);
                        dialog.show();
                    }
                };

                if (paymentIntent.isHttpPaymentUrl()) {
                    new DirectPaymentTask.HttpPaymentTask(backgroundHandler, callback, paymentIntent.paymentUrl)
                            .send(paymentIntent.standard, transaction, returnAddress, finalAmount,
                                    paymentIntent.payeeData);
                } else if (paymentIntent.isBluetoothPaymentUrl() && bluetoothAdapter != null
                        && bluetoothAdapter.isEnabled()) {
                    new DirectPaymentTask.BluetoothPaymentTask(backgroundHandler, callback, bluetoothAdapter,
                            paymentIntent.getBluetoothMac()).send(paymentIntent.standard, transaction,
                                    returnAddress, finalAmount, paymentIntent.payeeData);
                }
            }
        }

        @Override
        protected void onInsufficientMoney(final BigInteger missing) {
            state = State.INPUT;
            updateView();

            final BigInteger estimated = wallet.getBalance(BalanceType.ESTIMATED);
            final BigInteger available = wallet.getBalance(BalanceType.AVAILABLE);
            final BigInteger pending = estimated.subtract(available);

            final int btcShift = config.getBtcShift();
            final int btcPrecision = config.getBtcMaxPrecision();
            final String btcPrefix = config.getBtcPrefix();

            final DialogBuilder dialog = new DialogBuilder(activity);
            dialog.setIcon(R.drawable.ic_menu_warning);
            dialog.setTitle(R.string.send_coins_fragment_insufficient_money_title);
            final StringBuilder msg = new StringBuilder(
                    String.format(getString(R.string.send_coins_fragment_insufficient_money_msg1),
                            btcPrefix + ' ' + GenericUtils.formatValue(missing, btcPrecision, btcShift)));
            if (pending.signum() > 0)
                msg.append("\n\n").append(getString(R.string.send_coins_fragment_pending,
                        GenericUtils.formatValue(pending, btcPrecision, btcShift)));
            msg.append("\n\n").append(getString(R.string.send_coins_fragment_insufficient_money_msg2));
            dialog.setMessage(msg);
            dialog.setPositiveButton(R.string.send_coins_options_empty, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    handleEmpty();
                }
            });
            dialog.setNegativeButton(R.string.button_cancel, null);
            dialog.show();
        }

        @Override
        protected void onFailure() {
            state = State.FAILED;
            updateView();

            activity.longToast(R.string.send_coins_error_msg);
        }
    }.sendCoinsOffline(sendRequest); // send asynchronously
}

From source file:libra.preprocess.common.kmerhistogram.KmerRangePartitioner.java

public KmerRangePartition[] getEqualAreaPartitions() {
    KmerRangePartition[] partitions = new KmerRangePartition[this.numPartitions];

    // calc 4^kmerSize
    BigInteger kmerend = BigInteger.valueOf(4).pow(this.kmerSize);
    BigDecimal bdkmerend = new BigDecimal(kmerend);
    // moves between x (0~1) y (0~1)
    // sum of area (0.5)
    double kmerArea = 0.5;
    double sliceArea = kmerArea / this.numPartitions;

    // we think triangle is horizontally flipped so calc get easier.
    double x1 = 0;

    List<BigInteger> widths = new ArrayList<BigInteger>();
    BigInteger widthSum = BigInteger.ZERO;
    for (int i = 0; i < this.numPartitions; i++) {
        // x2*x2 = 2*sliceArea + x1*x1
        double temp = (2 * sliceArea) + (x1 * x1);
        double x2 = Math.sqrt(temp);

        BigDecimal bdx1 = BigDecimal.valueOf(x1);
        BigDecimal bdx2 = BigDecimal.valueOf(x2);

        // if i increases, bdw will be decreased
        BigDecimal bdw = bdx2.subtract(bdx1);

        BigInteger bw = bdw.multiply(bdkmerend).toBigInteger();
        if (bw.compareTo(BigInteger.ZERO) <= 0) {
            bw = BigInteger.ONE;//ww  w  . java 2 s. co m
        }

        if (widthSum.add(bw).compareTo(kmerend) > 0) {
            bw = kmerend.subtract(widthSum);
        }

        if (i == this.numPartitions - 1) {
            // last case
            if (widthSum.add(bw).compareTo(kmerend) < 0) {
                bw = kmerend.subtract(widthSum);
            }
        }

        // save it
        widths.add(bw);
        widthSum = widthSum.add(bw);

        x1 = x2;
    }

    BigInteger cur_begin = BigInteger.ZERO;
    for (int i = 0; i < this.numPartitions; i++) {
        BigInteger slice_width = widths.get(this.numPartitions - 1 - i);

        BigInteger slice_begin = cur_begin;

        if (slice_begin.add(slice_width).compareTo(kmerend) > 0) {
            slice_width = kmerend.subtract(slice_begin);
        }

        BigInteger slice_end = cur_begin.add(slice_width).subtract(BigInteger.ONE);

        KmerRangePartition slice = new KmerRangePartition(this.kmerSize, this.numPartitions, i, slice_width,
                slice_begin, slice_end);
        partitions[i] = slice;

        cur_begin = cur_begin.add(slice_width);
    }

    return partitions;
}

From source file:com.guldencoin.androidwallet.nlg.ui.SendCoinsFragment.java

private void handleGo() {
    state = State.PREPARATION;// w  w w  . jav  a  2 s  .  com
    updateView();

    // final payment intent
    final PaymentIntent finalPaymentIntent = paymentIntent.mergeWithEditedValues(
            amountCalculatorLink.getAmount(), validatedAddress != null ? validatedAddress.address : null);
    final BigInteger finalAmount = finalPaymentIntent.getAmount();

    // prepare send request
    final SendRequest sendRequest = finalPaymentIntent.toSendRequest();
    final Address returnAddress = WalletUtils.pickOldestKey(wallet).toAddress(Constants.NETWORK_PARAMETERS);
    sendRequest.changeAddress = returnAddress;
    sendRequest.emptyWallet = paymentIntent.mayEditAmount()
            && finalAmount.equals(wallet.getBalance(BalanceType.AVAILABLE));

    new SendCoinsOfflineTask(wallet, backgroundHandler) {
        @Override
        protected void onSuccess(final Transaction transaction) {
            sentTransaction = transaction;

            state = State.SENDING;
            updateView();

            sentTransaction.getConfidence().addEventListener(sentTransactionConfidenceListener);

            directPay(sentTransaction);

            application.broadcastTransaction(sentTransaction);

            final Intent result = new Intent();
            BitcoinIntegration.transactionHashToResult(result, sentTransaction.getHashAsString());
            activity.setResult(Activity.RESULT_OK, result);
        }

        private void directPay(final Transaction transaction) {
            if (directPaymentEnableView.isChecked()) {
                final DirectPaymentTask.ResultCallback callback = new DirectPaymentTask.ResultCallback() {
                    @Override
                    public void onResult(final boolean ack) {
                        directPaymentAck = ack;

                        if (state == State.SENDING)
                            state = State.SENT;

                        updateView();
                    }

                    @Override
                    public void onFail(final int messageResId, final Object... messageArgs) {
                        final DialogBuilder dialog = DialogBuilder.warn(activity,
                                R.string.send_coins_fragment_direct_payment_failed_title);
                        dialog.setMessage(paymentIntent.paymentUrl + "\n" + getString(messageResId, messageArgs)
                                + "\n\n" + getString(R.string.send_coins_fragment_direct_payment_failed_msg));
                        dialog.setPositiveButton(R.string.button_retry, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialog, final int which) {
                                directPay(transaction);
                            }
                        });
                        dialog.setNegativeButton(R.string.button_dismiss, null);
                        dialog.show();
                    }
                };

                if (paymentIntent.isHttpPaymentUrl()) {
                    new DirectPaymentTask.HttpPaymentTask(backgroundHandler, callback, paymentIntent.paymentUrl)
                            .send(paymentIntent.standard, transaction, returnAddress, finalAmount,
                                    paymentIntent.payeeData);
                } else if (paymentIntent.isBluetoothPaymentUrl() && bluetoothAdapter != null
                        && bluetoothAdapter.isEnabled()) {
                    new DirectPaymentTask.BluetoothPaymentTask(backgroundHandler, callback, bluetoothAdapter,
                            paymentIntent.getBluetoothMac()).send(paymentIntent.standard, transaction,
                                    returnAddress, finalAmount, paymentIntent.payeeData);
                }
            }
        }

        @Override
        protected void onInsufficientMoney(final BigInteger missing) {
            state = State.INPUT;
            updateView();

            final BigInteger estimated = wallet.getBalance(BalanceType.ESTIMATED);
            final BigInteger available = wallet.getBalance(BalanceType.AVAILABLE);
            final BigInteger pending = estimated.subtract(available);

            final int btcShift = config.getBtcShift();
            final int btcPrecision = config.getBtcMaxPrecision();
            final String btcPrefix = config.getBtcPrefix();

            final DialogBuilder dialog = DialogBuilder.warn(activity,
                    R.string.send_coins_fragment_insufficient_money_title);
            final StringBuilder msg = new StringBuilder(
                    String.format(getString(R.string.send_coins_fragment_insufficient_money_msg1),
                            btcPrefix + ' ' + GenericUtils.formatValue(missing, btcPrecision, btcShift)));
            if (pending.signum() > 0)
                msg.append("\n\n").append(getString(R.string.send_coins_fragment_pending,
                        GenericUtils.formatValue(pending, btcPrecision, btcShift)));
            msg.append("\n\n").append(getString(R.string.send_coins_fragment_insufficient_money_msg2));
            dialog.setMessage(msg);
            dialog.setPositiveButton(R.string.send_coins_options_empty, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    handleEmpty();
                }
            });
            dialog.setNegativeButton(R.string.button_cancel, null);
            dialog.show();
        }

        @Override
        protected void onFailure() {
            state = State.FAILED;
            updateView();

            activity.longToast(R.string.send_coins_error_msg);
        }
    }.sendCoinsOffline(sendRequest); // send asynchronously
}

From source file:de.schildbach.wallet.ui.SendCoinsFragmentBackup.java

private void handleGo() {
    state = State.PREPARATION;/*from   ww  w. j ava  2  s.c o  m*/
    updateView();

    // final payment intent
    final PaymentIntent finalPaymentIntent = paymentIntent.mergeWithEditedValues(
            amountCalculatorLink.getAmount(), validatedAddress != null ? validatedAddress.address : null);
    final BigInteger finalAmount = finalPaymentIntent.getAmount();

    // prepare send request
    final SendRequest sendRequest = finalPaymentIntent.toSendRequest();
    final Address returnAddress = WalletUtils.pickOldestKey(wallet).toAddress(Constants.NETWORK_PARAMETERS);
    sendRequest.changeAddress = returnAddress;
    sendRequest.emptyWallet = paymentIntent.mayEditAmount()
            && finalAmount.equals(wallet.getBalance(BalanceType.AVAILABLE));

    new SendCoinsOfflineTask(wallet, backgroundHandler) {
        @Override
        protected void onSuccess(final Transaction transaction) {
            sentTransaction = transaction;

            state = State.SENDING;
            updateView();

            sentTransaction.getConfidence().addEventListener(sentTransactionConfidenceListener);

            final Payment payment = PaymentProtocol.createPaymentMessage(sentTransaction, returnAddress,
                    finalAmount, null, paymentIntent.payeeData);

            directPay(payment);

            application.broadcastTransaction(sentTransaction);

            final ComponentName callingActivity = activity.getCallingActivity();
            if (callingActivity != null) {
                log.info("returning result to calling activity: {}", callingActivity.flattenToString());

                final Intent result = new Intent();
                BitcoinIntegration.transactionHashToResult(result, sentTransaction.getHashAsString());
                if (paymentIntent.standard == Standard.BIP70)
                    BitcoinIntegration.paymentToResult(result, payment.toByteArray());
                activity.setResult(Activity.RESULT_OK, result);
            }
        }

        private void directPay(final Payment payment) {
            if (directPaymentEnableView.isChecked()) {
                final DirectPaymentTask.ResultCallback callback = new DirectPaymentTask.ResultCallback() {
                    @Override
                    public void onResult(final boolean ack) {
                        directPaymentAck = ack;

                        if (state == State.SENDING)
                            state = State.SENT;

                        updateView();
                    }

                    @Override
                    public void onFail(final int messageResId, final Object... messageArgs) {
                        final DialogBuilder dialog = DialogBuilder.warn(activity,
                                R.string.send_coins_fragment_direct_payment_failed_title);
                        dialog.setMessage(paymentIntent.paymentUrl + "\n" + getString(messageResId, messageArgs)
                                + "\n\n" + getString(R.string.send_coins_fragment_direct_payment_failed_msg));
                        dialog.setPositiveButton(R.string.button_retry, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialog, final int which) {
                                directPay(payment);
                            }
                        });
                        dialog.setNegativeButton(R.string.button_dismiss, null);
                        dialog.show();
                    }
                };

                if (paymentIntent.isHttpPaymentUrl()) {
                    new DirectPaymentTask.HttpPaymentTask(backgroundHandler, callback, paymentIntent.paymentUrl,
                            application.httpUserAgent()).send(paymentIntent.standard, payment);
                } else if (paymentIntent.isBluetoothPaymentUrl() && bluetoothAdapter != null
                        && bluetoothAdapter.isEnabled()) {
                    new DirectPaymentTask.BluetoothPaymentTask(backgroundHandler, callback, bluetoothAdapter,
                            paymentIntent.getBluetoothMac()).send(paymentIntent.standard, payment);
                }
            }
        }

        @Override
        protected void onInsufficientMoney(@Nullable final BigInteger missing) {
            state = State.INPUT;
            updateView();

            final BigInteger estimated = wallet.getBalance(BalanceType.ESTIMATED);
            final BigInteger available = wallet.getBalance(BalanceType.AVAILABLE);
            final BigInteger pending = estimated.subtract(available);

            final int btcShift = config.getBtcShift();
            final int btcPrecision = config.getBtcMaxPrecision();
            final String btcPrefix = config.getBtcPrefix();

            final DialogBuilder dialog = DialogBuilder.warn(activity,
                    R.string.send_coins_fragment_insufficient_money_title);
            final StringBuilder msg = new StringBuilder();
            if (missing != null)
                msg.append(String.format(getString(R.string.send_coins_fragment_insufficient_money_msg1),
                        btcPrefix + ' ' + GenericUtils.formatValue(missing, btcPrecision, btcShift)))
                        .append("\n\n");
            if (pending.signum() > 0)
                msg.append(getString(R.string.send_coins_fragment_pending,
                        GenericUtils.formatValue(pending, btcPrecision, btcShift))).append("\n\n");
            msg.append(getString(R.string.send_coins_fragment_insufficient_money_msg2));
            dialog.setMessage(msg);
            dialog.setPositiveButton(R.string.send_coins_options_empty, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    handleEmpty();
                }
            });
            dialog.setNegativeButton(R.string.button_cancel, null);
            dialog.show();
        }

        @Override
        protected void onFailure() {
            state = State.FAILED;
            updateView();

            activity.longToast(R.string.send_coins_error_msg);
        }
    }.sendCoinsOffline(sendRequest); // send asynchronously
}

From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1DecryptionAttackExecutor.java

private void stepThree(final int i) throws Exception {
    BigInteger n = this.pubKey.getModulus();
    BigInteger r;//from  w  w w. ja  v  a  2 s  .  c o m
    BigInteger upperBound;
    BigInteger lowerBound;
    BigInteger max;
    BigInteger min;
    BigInteger[] tmp;
    ArrayList<Interval> ms = new ArrayList<>(15);

    for (Interval interval : this.m) {
        upperBound = step3ComputeUpperBound(this.si, n, interval.upper);
        lowerBound = step3ComputeLowerBound(this.si, n, interval.lower);

        r = lowerBound;
        // lowerBound <= r <= upperBound
        while (r.compareTo(upperBound) < 1) {
            // ceil((2*B+r*n)/si)
            max = (BigInteger.valueOf(2).multiply(this.bigB)).add(r.multiply(n));
            tmp = max.divideAndRemainder(this.si);
            if (BigInteger.ZERO.compareTo(tmp[1]) != 0) {
                max = tmp[0].add(BigInteger.ONE);
            } else {
                max = tmp[0];
            }

            // floor((3*B-1+r*n)/si
            min = BigInteger.valueOf(3).multiply(this.bigB);
            min = min.subtract(BigInteger.ONE);
            min = min.add(r.multiply(n));
            min = min.divide(this.si);

            // build new interval
            if (interval.lower.compareTo(max) > 0) {
                max = interval.lower;
            }
            if (interval.upper.compareTo(min) < 0) {
                min = interval.upper;
            }
            if (max.compareTo(min) <= 0) {
                ms.add(new Interval(max, min));
            }
            // one further....
            r = r.add(BigInteger.ONE);
        }
    }

    loggerInstance.log(getClass(), " # of intervals for M" + i + ": " + ms.size(), Logger.LogLevel.INFO);

    if (ms.size() == 0) {
        throw new Exception("Zero intervals left, validity oracle seems to be wrong!");
    }

    this.m = ms.toArray(new Interval[ms.size()]);
}