org.bitcoinj.wallet.SendRequest Java Examples

The following examples show how to use org.bitcoinj.wallet.SendRequest. 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: TransactionOutputTest.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testMultiSigOutputToString() throws Exception {
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, Coin.COIN);
    ECKey myKey = new ECKey();
    this.wallet.importKey(myKey);

    // Simulate another signatory
    ECKey otherKey = new ECKey();

    // Create multi-sig transaction
    Transaction multiSigTransaction = new Transaction(PARAMS);
    ImmutableList<ECKey> keys = ImmutableList.of(myKey, otherKey);

    Script scriptPubKey = ScriptBuilder.createMultiSigOutputScript(2, keys);
    multiSigTransaction.addOutput(Coin.COIN, scriptPubKey);

    SendRequest req = SendRequest.forTx(multiSigTransaction);
    this.wallet.completeTx(req);
    TransactionOutput multiSigTransactionOutput = multiSigTransaction.getOutput(0);

    assertThat(multiSigTransactionOutput.toString(), CoreMatchers.containsString("CHECKMULTISIG"));
}
 
Example #2
Source File: BtcWalletService.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
public String sendFundsForMultipleAddresses(Set<String> fromAddresses,
                                            String toAddress,
                                            Coin receiverAmount,
                                            Coin fee,
                                            @Nullable String changeAddress,
                                            @Nullable KeyParameter aesKey,
                                            FutureCallback<Transaction> callback) throws AddressFormatException,
        AddressEntryException, InsufficientMoneyException {

    SendRequest request = getSendRequestForMultipleAddresses(fromAddresses, toAddress, receiverAmount, fee, changeAddress, aesKey);
    Wallet.SendResult sendResult = wallet.sendCoins(request);
    Futures.addCallback(sendResult.broadcastComplete, callback);

    printTx("sendFunds", sendResult.tx);
    return sendResult.tx.getHashAsString();
}
 
Example #3
Source File: BtcWalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public int getEstimatedFeeTxSize(List<Coin> outputValues, Coin txFee)
        throws InsufficientMoneyException, AddressFormatException {
    Transaction transaction = new Transaction(params);
    Address dummyAddress = wallet.currentReceiveKey().toAddress(params);
    outputValues.forEach(outputValue -> transaction.addOutput(outputValue, dummyAddress));

    SendRequest sendRequest = SendRequest.forTx(transaction);
    sendRequest.shuffleOutputs = false;
    sendRequest.aesKey = aesKey;
    sendRequest.coinSelector = new BtcCoinSelector(walletsSetup.getAddressesByContext(AddressEntry.Context.AVAILABLE),
            preferences.getIgnoreDustThreshold());
    sendRequest.fee = txFee;
    sendRequest.feePerKb = Coin.ZERO;
    sendRequest.ensureMinRequiredFee = false;
    sendRequest.changeAddress = dummyAddress;
    wallet.completeTx(sendRequest);
    return transaction.bitcoinSerialize().length;
}
 
Example #4
Source File: WalletService.java    From bisq 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 #5
Source File: BtcWalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public String sendFundsForMultipleAddresses(Set<String> fromAddresses,
                                            String toAddress,
                                            Coin receiverAmount,
                                            Coin fee,
                                            @Nullable String changeAddress,
                                            @Nullable KeyParameter aesKey,
                                            FutureCallback<Transaction> callback) throws AddressFormatException,
        AddressEntryException, InsufficientMoneyException {

    SendRequest request = getSendRequestForMultipleAddresses(fromAddresses, toAddress, receiverAmount, fee, changeAddress, aesKey);
    Wallet.SendResult sendResult = wallet.sendCoins(request);
    Futures.addCallback(sendResult.broadcastComplete, callback);

    printTx("sendFunds", sendResult.tx);
    return sendResult.tx.getHashAsString();
}
 
Example #6
Source File: TransactionOutputTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testMultiSigOutputToString() throws Exception {
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, Coin.COIN);
    ECKey myKey = new ECKey();
    this.wallet.importKey(myKey);

    // Simulate another signatory
    ECKey otherKey = new ECKey();

    // Create multi-sig transaction
    Transaction multiSigTransaction = new Transaction(PARAMS);
    ImmutableList<ECKey> keys = ImmutableList.of(myKey, otherKey);

    Script scriptPubKey = ScriptBuilder.createMultiSigOutputScript(2, keys);
    multiSigTransaction.addOutput(Coin.COIN, scriptPubKey);

    SendRequest req = SendRequest.forTx(multiSigTransaction);
    this.wallet.completeTx(req);
    TransactionOutput multiSigTransactionOutput = multiSigTransaction.getOutput(0);

    assertThat(multiSigTransactionOutput.toString(), CoreMatchers.containsString("CHECKMULTISIG"));
}
 
Example #7
Source File: BsqWalletService.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
public Transaction getPreparedSendTx(String receiverAddress, Coin receiverAmount)
        throws AddressFormatException, InsufficientBsqException, WalletException, TransactionVerificationException {
    Transaction tx = new Transaction(params);
    checkArgument(Restrictions.isAboveDust(receiverAmount),
            "The amount is too low (dust limit).");
    tx.addOutput(receiverAmount, Address.fromBase58(params, receiverAddress));

    SendRequest sendRequest = SendRequest.forTx(tx);
    sendRequest.fee = Coin.ZERO;
    sendRequest.feePerKb = Coin.ZERO;
    sendRequest.ensureMinRequiredFee = false;
    sendRequest.aesKey = aesKey;
    sendRequest.shuffleOutputs = false;
    sendRequest.signInputs = false;
    sendRequest.ensureMinRequiredFee = false;
    sendRequest.changeAddress = getUnusedAddress();
    try {
        wallet.completeTx(sendRequest);
    } catch (InsufficientMoneyException e) {
        throw new InsufficientBsqException(e.missing);
    }
    checkWalletConsistency(wallet);
    verifyTransaction(tx);
    // printTx("prepareSendTx", tx);
    return tx;
}
 
Example #8
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 #9
Source File: TransactionInputTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testStandardWalletDisconnect() throws Exception {
    NetworkParameters params = UnitTestParams.get();
    Wallet w = new Wallet(new Context(params));
    w.setCoinSelector(new AllowUnconfirmedCoinSelector());
    Address a = w.currentReceiveAddress();
    Transaction tx1 = FakeTxBuilder.createFakeTxWithoutChangeAddress(params, Coin.COIN, a);
    w.receivePending(tx1, null);
    Transaction tx2 = new Transaction(params);
    tx2.addOutput(Coin.valueOf(99000000), new ECKey());
    w.completeTx(SendRequest.forTx(tx2));

    TransactionInput txInToDisconnect = tx2.getInput(0);

    assertEquals(tx1, txInToDisconnect.getOutpoint().fromTx);
    assertNull(txInToDisconnect.getOutpoint().connectedOutput);

    txInToDisconnect.disconnect();

    assertNull(txInToDisconnect.getOutpoint().fromTx);
    assertNull(txInToDisconnect.getOutpoint().connectedOutput);
}
 
Example #10
Source File: TransactionInputTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testStandardWalletDisconnect() throws Exception {
    Wallet w = new Wallet(new Context(UNITTEST));
    w.setCoinSelector(new AllowUnconfirmedCoinSelector());
    Address a = w.currentReceiveAddress();
    Transaction tx1 = FakeTxBuilder.createFakeTxWithoutChangeAddress(UNITTEST, Coin.COIN, a);
    w.receivePending(tx1, null);
    Transaction tx2 = new Transaction(UNITTEST);
    tx2.addOutput(Coin.valueOf(99000000), new ECKey());
    w.completeTx(SendRequest.forTx(tx2));

    TransactionInput txInToDisconnect = tx2.getInput(0);

    assertEquals(tx1, txInToDisconnect.getOutpoint().fromTx);
    assertNull(txInToDisconnect.getOutpoint().connectedOutput);

    txInToDisconnect.disconnect();

    assertNull(txInToDisconnect.getOutpoint().fromTx);
    assertNull(txInToDisconnect.getOutpoint().connectedOutput);
}
 
Example #11
Source File: TransactionOutputTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testMultiSigOutputToString() throws Exception {
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, Coin.COIN);
    ECKey myKey = new ECKey();
    this.wallet.importKey(myKey);

    // Simulate another signatory
    ECKey otherKey = new ECKey();

    // Create multi-sig transaction
    Transaction multiSigTransaction = new Transaction(UNITTEST);
    ImmutableList<ECKey> keys = ImmutableList.of(myKey, otherKey);

    Script scriptPubKey = ScriptBuilder.createMultiSigOutputScript(2, keys);
    multiSigTransaction.addOutput(Coin.COIN, scriptPubKey);

    SendRequest req = SendRequest.forTx(multiSigTransaction);
    this.wallet.completeTx(req);
    TransactionOutput multiSigTransactionOutput = multiSigTransaction.getOutput(0);

    assertThat(multiSigTransactionOutput.toString(), CoreMatchers.containsString("CHECKMULTISIG"));
}
 
Example #12
Source File: TransactionInputTest.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testStandardWalletDisconnect() throws Exception {
    NetworkParameters params = UnitTestParams.get();
    Wallet w = new Wallet(new Context(params));
    w.setCoinSelector(new AllowUnconfirmedCoinSelector());
    Address a = w.currentReceiveAddress();
    Transaction tx1 = FakeTxBuilder.createFakeTxWithoutChangeAddress(params, Coin.COIN, a);
    w.receivePending(tx1, null);
    Transaction tx2 = new Transaction(params);
    tx2.addOutput(Coin.valueOf(99000000), new ECKey());
    w.completeTx(SendRequest.forTx(tx2));

    TransactionInput txInToDisconnect = tx2.getInput(0);

    assertEquals(tx1, txInToDisconnect.getOutpoint().fromTx);
    assertNull(txInToDisconnect.getOutpoint().connectedOutput);

    txInToDisconnect.disconnect();

    assertNull(txInToDisconnect.getOutpoint().fromTx);
    assertNull(txInToDisconnect.getOutpoint().connectedOutput);
}
 
Example #13
Source File: TransactionInputTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testUTXOWalletDisconnect() throws Exception {
    final NetworkParameters params = UnitTestParams.get();
    Wallet w = new Wallet(new Context(params));
    Address a = w.currentReceiveAddress();
    final UTXO utxo = new UTXO(Sha256Hash.of(new byte[] { 1, 2, 3 }), 1, Coin.COIN, 0, false,
            ScriptBuilder.createOutputScript(a));
    w.setUTXOProvider(new UTXOProvider() {
        @Override
        public NetworkParameters getParams() {
            return params;
        }

        @Override
        public List<UTXO> getOpenTransactionOutputs(List<Address> addresses) throws UTXOProviderException {
            return Lists.newArrayList(utxo);
        }

        @Override
        public int getChainHeadHeight() throws UTXOProviderException {
            return Integer.MAX_VALUE;
        }
    });

    Transaction tx2 = new Transaction(params);
    tx2.addOutput(Coin.valueOf(99000000), new ECKey());
    w.completeTx(SendRequest.forTx(tx2));

    TransactionInput txInToDisconnect = tx2.getInput(0);

    assertNull(txInToDisconnect.getOutpoint().fromTx);
    assertEquals(utxo.getHash(), txInToDisconnect.getOutpoint().connectedOutput.getParentTransactionHash());

    txInToDisconnect.disconnect();

    assertNull(txInToDisconnect.getOutpoint().fromTx);
    assertNull(txInToDisconnect.getOutpoint().connectedOutput);
}
 
Example #14
Source File: PaymentSession.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a {@link SendRequest} suitable for broadcasting to the network.
 */
public SendRequest getSendRequest() {
    Transaction tx = new Transaction(params);
    for (Protos.Output output : paymentDetails.getOutputsList())
        tx.addOutput(new TransactionOutput(params, tx, Coin.valueOf(output.getAmount()), output.getScript().toByteArray()));
    return SendRequest.forTx(tx).fromPaymentDetails(paymentDetails);
}
 
Example #15
Source File: TransactionInputTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testUTXOWalletDisconnect() throws Exception {
    final NetworkParameters params = UnitTestParams.get();
    Wallet w = new Wallet(new Context(params));
    Address a = w.currentReceiveAddress();
    final UTXO utxo = new UTXO(Sha256Hash.of(new byte[] { 1, 2, 3 }), 1, Coin.COIN, 0, false,
            ScriptBuilder.createOutputScript(a));
    w.setUTXOProvider(new UTXOProvider() {
        @Override
        public NetworkParameters getParams() {
            return params;
        }

        @Override
        public List<UTXO> getOpenTransactionOutputs(List<Address> addresses) throws UTXOProviderException {
            return Lists.newArrayList(utxo);
        }

        @Override
        public int getChainHeadHeight() throws UTXOProviderException {
            return Integer.MAX_VALUE;
        }
    });

    Transaction tx2 = new Transaction(params);
    tx2.addOutput(Coin.valueOf(99000000), new ECKey());
    w.completeTx(SendRequest.forTx(tx2));

    TransactionInput txInToDisconnect = tx2.getInput(0);

    assertNull(txInToDisconnect.getOutpoint().fromTx);
    assertEquals(utxo.getHash(), txInToDisconnect.getOutpoint().connectedOutput.getParentTransactionHash());

    txInToDisconnect.disconnect();

    assertNull(txInToDisconnect.getOutpoint().fromTx);
    assertNull(txInToDisconnect.getOutpoint().connectedOutput);
}
 
Example #16
Source File: PaymentChannelServerState.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
protected synchronized SendRequest makeUnsignedChannelContract(Coin valueToMe) {
    Transaction tx = new Transaction(wallet.getParams());
    if (!getTotalValue().subtract(valueToMe).equals(Coin.ZERO)) {
        tx.addOutput(getTotalValue().subtract(valueToMe), getClientKey().toAddress(wallet.getParams()));
    }
    tx.addInput(contract.getOutput(0));
    return SendRequest.forTx(tx);
}
 
Example #17
Source File: PaymentSession.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a {@link SendRequest} suitable for broadcasting to the network.
 */
public SendRequest getSendRequest() {
    Transaction tx = new Transaction(params);
    for (Protos.Output output : paymentDetails.getOutputsList())
        tx.addOutput(new TransactionOutput(params, tx, Coin.valueOf(output.getAmount()), output.getScript().toByteArray()));
    return SendRequest.forTx(tx).fromPaymentDetails(paymentDetails);
}
 
Example #18
Source File: BsqWalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private Transaction getPreparedSendTx(String receiverAddress, Coin receiverAmount, CoinSelector coinSelector)
        throws AddressFormatException, InsufficientBsqException, WalletException, TransactionVerificationException, BsqChangeBelowDustException {
    daoKillSwitch.assertDaoIsNotDisabled();
    Transaction tx = new Transaction(params);
    checkArgument(Restrictions.isAboveDust(receiverAmount),
            "The amount is too low (dust limit).");
    tx.addOutput(receiverAmount, Address.fromBase58(params, receiverAddress));

    SendRequest sendRequest = SendRequest.forTx(tx);
    sendRequest.fee = Coin.ZERO;
    sendRequest.feePerKb = Coin.ZERO;
    sendRequest.ensureMinRequiredFee = false;
    sendRequest.aesKey = aesKey;
    sendRequest.shuffleOutputs = false;
    sendRequest.signInputs = false;
    sendRequest.changeAddress = getChangeAddress();
    sendRequest.coinSelector = coinSelector;
    try {
        wallet.completeTx(sendRequest);
        checkWalletConsistency(wallet);
        verifyTransaction(tx);
        // printTx("prepareSendTx", tx);

        // Tx has as first output BSQ and an optional second BSQ change output.
        // At that stage we do not have added the BTC inputs so there is no BTC change output here.
        if (tx.getOutputs().size() == 2) {
            Coin bsqChangeOutputValue = tx.getOutputs().get(1).getValue();
            if (!Restrictions.isAboveDust(bsqChangeOutputValue)) {
                String msg = "BSQ change output is below dust limit. outputValue=" + bsqChangeOutputValue.value / 100 + " BSQ";
                log.warn(msg);
                throw new BsqChangeBelowDustException(msg, bsqChangeOutputValue);
            }
        }

        return tx;
    } catch (InsufficientMoneyException e) {
        log.error(e.toString());
        throw new InsufficientBsqException(e.missing);
    }
}
 
Example #19
Source File: BtcWalletService.java    From bisq-core 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());
    sendRequest.changeAddress = addressEntry.get().getAddress();
    return sendRequest;
}
 
Example #20
Source File: PaymentChannelServerState.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
protected synchronized SendRequest makeUnsignedChannelContract(Coin valueToMe) {
    Transaction tx = new Transaction(wallet.getParams());
    if (!getTotalValue().subtract(valueToMe).equals(Coin.ZERO)) {
        tx.addOutput(getTotalValue().subtract(valueToMe), getClientKey().toAddress(wallet.getParams()));
    }
    tx.addInput(contract.getOutput(0));
    return SendRequest.forTx(tx);
}
 
Example #21
Source File: PaymentSession.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a {@link SendRequest} suitable for broadcasting to the network.
 */
public SendRequest getSendRequest() {
    Transaction tx = new Transaction(params);
    for (Protos.Output output : paymentDetails.getOutputsList())
        tx.addOutput(new TransactionOutput(params, tx, Coin.valueOf(output.getAmount()), output.getScript().toByteArray()));
    return SendRequest.forTx(tx).fromPaymentDetails(paymentDetails);
}
 
Example #22
Source File: TradeWalletService.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
private void addAvailableInputsAndChangeOutputs(Transaction transaction, Address address, Address changeAddress, Coin txFee) throws WalletException {
    SendRequest sendRequest = null;
    try {
        // Lets let the framework do the work to find the right inputs
        sendRequest = SendRequest.forTx(transaction);
        sendRequest.shuffleOutputs = false;
        sendRequest.aesKey = aesKey;
        // We use a fixed fee
        sendRequest.fee = txFee;
        sendRequest.feePerKb = Coin.ZERO;
        sendRequest.ensureMinRequiredFee = false;
        // we allow spending of unconfirmed tx (double spend risk is low and usability would suffer if we need to wait for 1 confirmation)
        sendRequest.coinSelector = new BtcCoinSelector(address);
        // We use always the same address in a trade for all transactions
        sendRequest.changeAddress = changeAddress;
        // With the usage of completeTx() we get all the work done with fee calculation, validation and coin selection.
        // We don't commit that tx to the wallet as it will be changed later and it's not signed yet.
        // So it will not change the wallet balance.
        checkNotNull(wallet, "wallet must not be null");
        wallet.completeTx(sendRequest);
    } catch (Throwable t) {
        if (sendRequest != null && sendRequest.tx != null)
            log.warn("addAvailableInputsAndChangeOutputs: sendRequest.tx={}, sendRequest.tx.getOutputs()={}", sendRequest.tx, sendRequest.tx.getOutputs());

        throw new WalletException(t);
    }
}
 
Example #23
Source File: BtcWalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public String sendFunds(String fromAddress,
                        String toAddress,
                        Coin receiverAmount,
                        Coin fee,
                        @Nullable KeyParameter aesKey,
                        @SuppressWarnings("SameParameterValue") AddressEntry.Context context,
                        FutureCallback<Transaction> callback) throws AddressFormatException,
        AddressEntryException, InsufficientMoneyException {
    SendRequest sendRequest = getSendRequest(fromAddress, toAddress, receiverAmount, fee, aesKey, context);
    Wallet.SendResult sendResult = wallet.sendCoins(sendRequest);
    Futures.addCallback(sendResult.broadcastComplete, callback);

    printTx("sendFunds", sendResult.tx);
    return sendResult.tx.getHashAsString();
}
 
Example #24
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private void addAvailableInputsAndChangeOutputs(Transaction transaction,
                                                Address address,
                                                Address changeAddress) throws WalletException {
    SendRequest sendRequest = null;
    try {
        // Let the framework do the work to find the right inputs
        sendRequest = SendRequest.forTx(transaction);
        sendRequest.shuffleOutputs = false;
        sendRequest.aesKey = aesKey;
        // We use a fixed fee
        sendRequest.fee = Coin.ZERO;
        sendRequest.feePerKb = Coin.ZERO;
        sendRequest.ensureMinRequiredFee = false;
        // we allow spending of unconfirmed tx (double spend risk is low and usability would suffer if we need to wait for 1 confirmation)
        sendRequest.coinSelector = new BtcCoinSelector(address, preferences.getIgnoreDustThreshold());
        // We use always the same address in a trade for all transactions
        sendRequest.changeAddress = changeAddress;
        // With the usage of completeTx() we get all the work done with fee calculation, validation and coin selection.
        // We don't commit that tx to the wallet as it will be changed later and it's not signed yet.
        // So it will not change the wallet balance.
        checkNotNull(wallet, "wallet must not be null");
        wallet.completeTx(sendRequest);
    } catch (Throwable t) {
        if (sendRequest != null && sendRequest.tx != null) {
            log.warn("addAvailableInputsAndChangeOutputs: sendRequest.tx={}, sendRequest.tx.getOutputs()={}",
                    sendRequest.tx, sendRequest.tx.getOutputs());
        }

        throw new WalletException(t);
    }
}
 
Example #25
Source File: PaymentChannelServerState.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
protected synchronized SendRequest makeUnsignedChannelContract(Coin valueToMe) {
    Transaction tx = new Transaction(wallet.getParams());
    if (!getTotalValue().subtract(valueToMe).equals(Coin.ZERO)) {
        tx.addOutput(getTotalValue().subtract(valueToMe), LegacyAddress.fromKey(wallet.getParams(), getClientKey()));
    }
    tx.addInput(contract.getOutput(0));
    return SendRequest.forTx(tx);
}
 
Example #26
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 #27
Source File: TransactionInputTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testUTXOWalletDisconnect() throws Exception {
    Wallet w = new Wallet(new Context(UNITTEST));
    Address a = w.currentReceiveAddress();
    final UTXO utxo = new UTXO(Sha256Hash.of(new byte[]{1, 2, 3}), 1, Coin.COIN, 0, false,
            ScriptBuilder.createOutputScript(a));
    w.setUTXOProvider(new UTXOProvider() {
        @Override
        public NetworkParameters getParams() {
            return UNITTEST;
        }

        @Override
        public List<UTXO> getOpenTransactionOutputs(List<ECKey> addresses) throws UTXOProviderException {
            return Lists.newArrayList(utxo);
        }

        @Override
        public int getChainHeadHeight() throws UTXOProviderException {
            return Integer.MAX_VALUE;
        }
    });

    Transaction tx2 = new Transaction(UNITTEST);
    tx2.addOutput(Coin.valueOf(99000000), new ECKey());
    w.completeTx(SendRequest.forTx(tx2));

    TransactionInput txInToDisconnect = tx2.getInput(0);

    assertNull(txInToDisconnect.getOutpoint().fromTx);
    assertEquals(utxo.getHash(), txInToDisconnect.getOutpoint().connectedOutput.getParentTransactionHash());

    txInToDisconnect.disconnect();

    assertNull(txInToDisconnect.getOutpoint().fromTx);
    assertNull(txInToDisconnect.getOutpoint().connectedOutput);
}
 
Example #28
Source File: BsqWalletService.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
public Transaction getPreparedSendBtcTx(String receiverAddress, Coin receiverAmount)
        throws AddressFormatException, InsufficientBsqException, WalletException, TransactionVerificationException {
    Transaction tx = new Transaction(params);
    checkArgument(Restrictions.isAboveDust(receiverAmount),
            "The amount is too low (dust limit).");
    tx.addOutput(receiverAmount, Address.fromBase58(params, receiverAddress));

    SendRequest sendRequest = SendRequest.forTx(tx);
    sendRequest.fee = Coin.ZERO;
    sendRequest.feePerKb = Coin.ZERO;
    sendRequest.ensureMinRequiredFee = false;
    sendRequest.aesKey = aesKey;
    sendRequest.shuffleOutputs = false;
    sendRequest.signInputs = false;
    sendRequest.ensureMinRequiredFee = false;
    sendRequest.changeAddress = getUnusedAddress();
    sendRequest.coinSelector = nonBsqCoinSelector;
    try {
        wallet.completeTx(sendRequest);
    } catch (InsufficientMoneyException e) {
        throw new InsufficientBsqException(e.missing);
    }
    checkWalletConsistency(wallet);
    verifyTransaction(tx);
    // printTx("prepareSendTx", tx);
    return tx;
}
 
Example #29
Source File: BtcWalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public Transaction getFeeEstimationTransaction(String fromAddress,
                                               String toAddress,
                                               Coin amount,
                                               AddressEntry.Context context)
        throws AddressFormatException, AddressEntryException, InsufficientFundsException {

    Optional<AddressEntry> addressEntry = findAddressEntry(fromAddress, context);
    if (!addressEntry.isPresent())
        throw new AddressEntryException("WithdrawFromAddress is not found in our wallet.");

    checkNotNull(addressEntry.get().getAddress(), "addressEntry.get().getAddress() must nto be null");

    try {
        Coin fee;
        int counter = 0;
        int txSize = 0;
        Transaction tx;
        Coin txFeeForWithdrawalPerByte = getTxFeeForWithdrawalPerByte();
        do {
            counter++;
            fee = txFeeForWithdrawalPerByte.multiply(txSize);
            SendRequest sendRequest = getSendRequest(fromAddress, toAddress, amount, fee, aesKey, context);
            wallet.completeTx(sendRequest);
            tx = sendRequest.tx;
            txSize = tx.bitcoinSerialize().length;
            printTx("FeeEstimationTransaction", tx);
        }
        while (feeEstimationNotSatisfied(counter, tx));
        if (counter == 10)
            log.error("Could not calculate the fee. Tx=" + tx);

        return tx;
    } catch (InsufficientMoneyException e) {
        throw new InsufficientFundsException("The fees for that transaction exceed the available funds " +
                "or the resulting output value is below the min. dust value:\n" +
                "Missing " + (e.missing != null ? e.missing.toFriendlyString() : "null"));
    }
}
 
Example #30
Source File: BtcWalletService.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
public Transaction getFeeEstimationTransaction(String fromAddress,
                                               String toAddress,
                                               Coin amount,
                                               AddressEntry.Context context)
        throws AddressFormatException, AddressEntryException, InsufficientFundsException {

    Optional<AddressEntry> addressEntry = findAddressEntry(fromAddress, context);
    if (!addressEntry.isPresent())
        throw new AddressEntryException("WithdrawFromAddress is not found in our wallet.");

    checkNotNull(addressEntry.get().getAddress(), "addressEntry.get().getAddress() must nto be null");

    try {
        Coin fee;
        int counter = 0;
        int txSize = 0;
        Transaction tx;
        Coin txFeeForWithdrawalPerByte = getTxFeeForWithdrawalPerByte();
        do {
            counter++;
            fee = txFeeForWithdrawalPerByte.multiply(txSize);
            SendRequest sendRequest = getSendRequest(fromAddress, toAddress, amount, fee, aesKey, context);
            wallet.completeTx(sendRequest);
            tx = sendRequest.tx;
            txSize = tx.bitcoinSerialize().length;
            printTx("FeeEstimationTransaction", tx);
        }
        while (feeEstimationNotSatisfied(counter, tx));
        if (counter == 10)
            log.error("Could not calculate the fee. Tx=" + tx);

        return tx;
    } catch (InsufficientMoneyException e) {
        throw new InsufficientFundsException("The fees for that transaction exceed the available funds " +
                "or the resulting output value is below the min. dust value:\n" +
                "Missing " + (e.missing != null ? e.missing.toFriendlyString() : "null"));
    }
}