Java Code Examples for org.bitcoinj.core.Coin#ZERO

The following examples show how to use org.bitcoinj.core.Coin#ZERO . 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: WalletService.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
public void emptyWallet(String toAddress, KeyParameter aesKey, ResultHandler resultHandler, ErrorMessageHandler errorMessageHandler)
        throws InsufficientMoneyException, AddressFormatException {
    SendRequest sendRequest = SendRequest.emptyWallet(Address.fromBase58(params, toAddress));
    sendRequest.fee = Coin.ZERO;
    sendRequest.feePerKb = getTxFeeForWithdrawalPerByte().multiply(1000);
    sendRequest.aesKey = aesKey;
    Wallet.SendResult sendResult = wallet.sendCoins(sendRequest);
    printTx("empty wallet", sendResult.tx);
    Futures.addCallback(sendResult.broadcastComplete, new FutureCallback<Transaction>() {
        @Override
        public void onSuccess(Transaction result) {
            log.info("emptyWallet onSuccess Transaction=" + result);
            resultHandler.handleResult();
        }

        @Override
        public void onFailure(@NotNull Throwable t) {
            log.error("emptyWallet onFailure " + t.toString());
            errorMessageHandler.handleErrorMessage(t.getMessage());
        }
    });
}
 
Example 2
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void opReturnOneOutputTest() throws Exception {
    // Tests basic send of transaction with one output that doesn't transfer any value but just writes OP_RETURN.
    receiveATransaction(wallet, myAddress);
    Transaction tx = new Transaction(UNITTEST);
    Coin messagePrice = Coin.ZERO;
    Script script = ScriptBuilder.createOpReturnScript("hello world!".getBytes());
    tx.addOutput(messagePrice, script);
    SendRequest request = SendRequest.forTx(tx);
    request.ensureMinRequiredFee = true;
    wallet.completeTx(request);
}
 
Example 3
Source File: CreateOfferService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private Coin getSellerSecurityDeposit(Coin amount, double sellerSecurityDeposit) {
    Coin amountAsCoin = amount;
    if (amountAsCoin == null)
        amountAsCoin = Coin.ZERO;

    Coin percentOfAmountAsCoin = CoinUtil.getPercentOfAmountAsCoin(sellerSecurityDeposit, amountAsCoin);
    return getBoundedSellerSecurityDeposit(percentOfAmountAsCoin);
}
 
Example 4
Source File: WalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
protected Coin getBalance(List<TransactionOutput> transactionOutputs, Address address) {
    Coin balance = Coin.ZERO;
    for (TransactionOutput output : transactionOutputs) {
        if (!isDustAttackUtxo(output)) {
            if (isOutputScriptConvertibleToAddress(output) &&
                    address != null &&
                    address.equals(getAddressFromOutput(output)))
                balance = balance.add(output.getValue());
        }
    }
    return balance;
}
 
Example 5
Source File: Price.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
public Coin getAmountByVolume(Volume volume) {
    Monetary monetary = volume.getMonetary();
    if (monetary instanceof Fiat && this.monetary instanceof Fiat)
        return new ExchangeRate((Fiat) this.monetary).fiatToCoin((Fiat) monetary);
    else if (monetary instanceof Altcoin && this.monetary instanceof Altcoin)
        return new AltcoinExchangeRate((Altcoin) this.monetary).altcoinToCoin((Altcoin) monetary);
    else
        return Coin.ZERO;
}
 
Example 6
Source File: TradeWalletService.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
public Transaction estimateBtcTradingFeeTxSize(Address fundingAddress,
                                               Address reservedForTradeAddress,
                                               Address changeAddress,
                                               Coin reservedFundsForOffer,
                                               boolean useSavingsWallet,
                                               Coin tradingFee,
                                               Coin txFee,
                                               String feeReceiverAddresses)
        throws InsufficientMoneyException, AddressFormatException {
    Transaction tradingFeeTx = new Transaction(params);
    tradingFeeTx.addOutput(tradingFee, Address.fromBase58(params, feeReceiverAddresses));
    tradingFeeTx.addOutput(reservedFundsForOffer, reservedForTradeAddress);

    SendRequest sendRequest = SendRequest.forTx(tradingFeeTx);
    sendRequest.shuffleOutputs = false;
    sendRequest.aesKey = aesKey;
    if (useSavingsWallet)
        sendRequest.coinSelector = new BtcCoinSelector(walletsSetup.getAddressesByContext(AddressEntry.Context.AVAILABLE));
    else
        sendRequest.coinSelector = new BtcCoinSelector(fundingAddress);

    sendRequest.fee = txFee;
    sendRequest.feePerKb = Coin.ZERO;
    sendRequest.ensureMinRequiredFee = false;
    sendRequest.changeAddress = changeAddress;
    checkNotNull(wallet, "Wallet must not be null");
    log.info("estimateBtcTradingFeeTxSize");
    wallet.completeTx(sendRequest);
    return tradingFeeTx;
}
 
Example 7
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void clearWallet() {
    wallet = null;
    walletFriendlyAddress = null;
    mnemonicKey = "";
    myBalance = Coin.ZERO;
    xprvKey = "";
    wifKey = "";
    restFromWif = false;
}
 
Example 8
Source File: BtcWalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private SendRequest getSendRequest(String fromAddress,
                                   String toAddress,
                                   Coin amount,
                                   Coin fee,
                                   @Nullable KeyParameter aesKey,
                                   AddressEntry.Context context) throws AddressFormatException,
        AddressEntryException {
    Transaction tx = new Transaction(params);
    final Coin receiverAmount = amount.subtract(fee);
    Preconditions.checkArgument(Restrictions.isAboveDust(receiverAmount),
            "The amount is too low (dust limit).");
    tx.addOutput(receiverAmount, Address.fromBase58(params, toAddress));

    SendRequest sendRequest = SendRequest.forTx(tx);
    sendRequest.fee = fee;
    sendRequest.feePerKb = Coin.ZERO;
    sendRequest.ensureMinRequiredFee = false;
    sendRequest.aesKey = aesKey;
    sendRequest.shuffleOutputs = false;
    Optional<AddressEntry> addressEntry = findAddressEntry(fromAddress, context);
    if (!addressEntry.isPresent())
        throw new AddressEntryException("WithdrawFromAddress is not found in our wallet.");

    checkNotNull(addressEntry.get(), "addressEntry.get() must not be null");
    checkNotNull(addressEntry.get().getAddress(), "addressEntry.get().getAddress() must not be null");
    sendRequest.coinSelector = new BtcCoinSelector(addressEntry.get().getAddress(), preferences.getIgnoreDustThreshold());
    sendRequest.changeAddress = addressEntry.get().getAddress();
    return sendRequest;
}
 
Example 9
Source File: WalletService.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
protected Coin getBalance(List<TransactionOutput> transactionOutputs, Address address) {
    Coin balance = Coin.ZERO;
    for (TransactionOutput output : transactionOutputs) {
        if (isOutputScriptConvertibleToAddress(output) &&
                address != null &&
                address.equals(getAddressFromOutput(output)))
            balance = balance.add(output.getValue());
    }
    return balance;
}
 
Example 10
Source File: BuyerAsTakerCreatesDepositTxInputs.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected void run() {
    try {
        runInterceptHook();

        // In case we pay the taker fee in bsq we reduce tx fee by that as the burned bsq satoshis goes to miners.
        Coin bsqTakerFee = trade.isCurrencyForTakerFeeBtc() ? Coin.ZERO : trade.getTakerFee();

        Coin txFee = trade.getTxFee();
        Coin takerInputAmount = checkNotNull(trade.getOffer()).getBuyerSecurityDeposit()
                .add(txFee)
                .add(txFee)
                .subtract(bsqTakerFee);
        Coin fee = txFee.subtract(bsqTakerFee);
        InputsAndChangeOutput result = processModel.getTradeWalletService().takerCreatesDepositTxInputs(
                processModel.getTakeOfferFeeTx(),
                takerInputAmount,
                fee);
        processModel.setRawTransactionInputs(result.rawTransactionInputs);
        processModel.setChangeOutputValue(result.changeOutputValue);
        processModel.setChangeOutputAddress(result.changeOutputAddress);

        complete();
    } catch (Throwable t) {
        failed(t);
    }
}
 
Example 11
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void opReturnTwoOutputsTest() throws Exception {
    // Tests sending transaction where one output transfers BTC, the other one writes OP_RETURN.
    receiveATransaction(wallet, myAddress);
    Transaction tx = new Transaction(PARAMS);
    Coin messagePrice = Coin.ZERO;
    Script script = ScriptBuilder.createOpReturnScript("hello world!".getBytes());
    tx.addOutput(CENT, OTHER_ADDRESS);
    tx.addOutput(messagePrice, script);
    SendRequest request = SendRequest.forTx(tx);
    wallet.completeTx(request);
}
 
Example 12
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void opReturnTwoOutputsTest() throws Exception {
    // Tests sending transaction where one output transfers BTC, the other one writes OP_RETURN.
    receiveATransaction(wallet, myAddress);
    Transaction tx = new Transaction(PARAMS);
    Coin messagePrice = Coin.ZERO;
    Script script = ScriptBuilder.createOpReturnScript("hello world!".getBytes());
    tx.addOutput(CENT, OTHER_ADDRESS);
    tx.addOutput(messagePrice, script);
    SendRequest request = SendRequest.forTx(tx);
    wallet.completeTx(request);
}
 
Example 13
Source File: ParsingUtils.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Coin parseToCoin(String input, MonetaryFormat coinFormat) {
    if (input != null && input.length() > 0) {
        try {
            return coinFormat.parse(cleanDoubleInput(input));
        } catch (Throwable t) {
            log.warn("Exception at parseToBtc: " + t.toString());
            return Coin.ZERO;
        }
    } else {
        return Coin.ZERO;
    }
}
 
Example 14
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 4 votes vote down vote up
public void setBalance(long balance) {
    Coin coin = balance != 0 ? Coin.valueOf(balance) : Coin.ZERO;
    this.balance = new BigDecimal(coin.toPlainString());
}
 
Example 15
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 4 votes vote down vote up
public Coin getMyBalance() {
    return myBalance != null ? myBalance : Coin.ZERO;
}
 
Example 16
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 4 votes vote down vote up
public Coin getMyBalance() {
    return myBalance != null ? myBalance : Coin.ZERO;
}
 
Example 17
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 4 votes vote down vote up
public Coin getMyBalance() {
    return myBalance != null ? myBalance : Coin.ZERO;
}
 
Example 18
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 4 votes vote down vote up
public void setMyBalance(Long satoshi) {
    myBalance = satoshi != null ? Coin.valueOf(satoshi) : Coin.ZERO;
}
 
Example 19
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 4 votes vote down vote up
public void setMyBalance(Long satoshi) {
    myBalance = satoshi != 0 ? Coin.valueOf(satoshi) : Coin.ZERO;
}
 
Example 20
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;
}