Java Code Examples for org.bitcoinj.wallet.Wallet#SendResult

The following examples show how to use org.bitcoinj.wallet.Wallet#SendResult . 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: 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: ForwardingService.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
private static void forwardCoins(Transaction tx) {
    try {
        Coin value = tx.getValueSentToMe(kit.wallet());
        System.out.println("Forwarding " + value.toFriendlyString());
        // Now send the coins back! Send with a small fee attached to ensure rapid confirmation.
        final Coin amountToSend = value.subtract(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
        final Wallet.SendResult sendResult = kit.wallet().sendCoins(kit.peerGroup(), forwardingAddress, amountToSend);
        checkNotNull(sendResult);  // We should never try to send more coins than we have!
        System.out.println("Sending ...");
        // Register a callback that is invoked when the transaction has propagated across the network.
        // This shows a second style of registering ListenableFuture callbacks, it works when you don't
        // need access to the object the future returns.
        sendResult.broadcastComplete.addListener(new Runnable() {
            @Override
            public void run() {
                // The wallet has changed now, it'll get auto saved shortly or when the app shuts down.
                System.out.println("Sent coins onwards! Transaction hash is " + sendResult.tx.getHashAsString());
            }
        }, MoreExecutors.sameThreadExecutor());
    } catch (KeyCrypterException | InsufficientMoneyException e) {
        // We don't use encrypted wallets in this example - can never happen.
        throw new RuntimeException(e);
    }
}
 
Example 4
Source File: BlockChain.java    From polling-station-app with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Broadcasts the list of signed transactions.
 * @param transactionsRaw transactions in raw byte[] format
 */
public ArrayList<Transaction> broadcastTransactions(ArrayList<byte[]> transactionsRaw) {
    ArrayList<Transaction> transactions = new ArrayList<>();
    for (byte[] transactionRaw : transactionsRaw) {
        final Wallet.SendResult result = new Wallet.SendResult();
        result.tx = new Transaction(params, transactionRaw);

        result.broadcast = kit.peerGroup().broadcastTransaction(result.tx);
        result.broadcastComplete = result.broadcast.future();

        result.broadcastComplete.addListener(new Runnable() {
            @Override
            public void run() {
                System.out.println("Asset spent! txid: " + result.tx.getHashAsString());
            }
        }, MoreExecutors.directExecutor());

        transactions.add(result.tx);
    }
    return transactions;
}
 
Example 5
Source File: ForwardingService.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
private static void forwardCoins(Transaction tx) {
    try {
        Coin value = tx.getValueSentToMe(kit.wallet());
        System.out.println("Forwarding " + value.toFriendlyString());
        // Now send the coins back! Send with a small fee attached to ensure rapid confirmation.
        final Coin amountToSend = value.subtract(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
        final Wallet.SendResult sendResult = kit.wallet().sendCoins(kit.peerGroup(), forwardingAddress, amountToSend);
        checkNotNull(sendResult);  // We should never try to send more coins than we have!
        System.out.println("Sending ...");
        // Register a callback that is invoked when the transaction has propagated across the network.
        // This shows a second style of registering ListenableFuture callbacks, it works when you don't
        // need access to the object the future returns.
        sendResult.broadcastComplete.addListener(new Runnable() {
            @Override
            public void run() {
                // The wallet has changed now, it'll get auto saved shortly or when the app shuts down.
                System.out.println("Sent coins onwards! Transaction hash is " + sendResult.tx.getHashAsString());
            }
        }, MoreExecutors.sameThreadExecutor());
    } catch (KeyCrypterException | InsufficientMoneyException e) {
        // We don't use encrypted wallets in this example - can never happen.
        throw new RuntimeException(e);
    }
}
 
Example 6
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 7
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 8
Source File: TransactionBroadcastTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void retryFailedBroadcast() throws Exception {
    // If we create a spend, it's sent to a peer that swallows it, and the peergroup is removed/re-added then
    // the tx should be broadcast again.
    InboundMessageQueuer p1 = connectPeer(1);
    connectPeer(2);

    // Send ourselves a bit of money.
    Block b1 = FakeTxBuilder.makeSolvedTestBlock(blockStore, address);
    inbound(p1, b1);
    assertNull(outbound(p1));
    assertEquals(FIFTY_COINS, wallet.getBalance());

    // Now create a spend, and expect the announcement on p1.
    Address dest = LegacyAddress.fromKey(UNITTEST, new ECKey());
    Wallet.SendResult sendResult = wallet.sendCoins(peerGroup, dest, COIN);
    assertFalse(sendResult.broadcastComplete.isDone());
    Transaction t1;
    {
        Message m;
        while (!((m = outbound(p1)) instanceof Transaction))
            ;
        t1 = (Transaction) m;
    }
    assertFalse(sendResult.broadcastComplete.isDone());

    // p1 eats it :( A bit later the PeerGroup is taken down.
    peerGroup.removeWallet(wallet);
    peerGroup.addWallet(wallet);

    // We want to hear about it again. Now, because we've disabled the randomness for the unit tests it will
    // re-appear on p1 again. Of course in the real world it would end up with a different set of peers and
    // select randomly so we get a second chance.
    Transaction t2 = (Transaction) outbound(p1);
    assertEquals(t1, t2);
}
 
Example 9
Source File: BtcWalletService.java    From bisq-core 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 10
Source File: TransactionBroadcastTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void retryFailedBroadcast() throws Exception {
    // If we create a spend, it's sent to a peer that swallows it, and the peergroup is removed/re-added then
    // the tx should be broadcast again.
    InboundMessageQueuer p1 = connectPeer(1);
    connectPeer(2);

    // Send ourselves a bit of money.
    Block b1 = FakeTxBuilder.makeSolvedTestBlock(blockStore, address);
    inbound(p1, b1);
    assertNull(outbound(p1));
    assertEquals(FIFTY_COINS, wallet.getBalance());

    // Now create a spend, and expect the announcement on p1.
    Address dest = new ECKey().toAddress(PARAMS);
    Wallet.SendResult sendResult = wallet.sendCoins(peerGroup, dest, COIN);
    assertFalse(sendResult.broadcastComplete.isDone());
    Transaction t1;
    {
        Message m;
        while (!((m = outbound(p1)) instanceof Transaction));
        t1 = (Transaction) m;
    }
    assertFalse(sendResult.broadcastComplete.isDone());

    // p1 eats it :( A bit later the PeerGroup is taken down.
    peerGroup.removeWallet(wallet);
    peerGroup.addWallet(wallet);

    // We want to hear about it again. Now, because we've disabled the randomness for the unit tests it will
    // re-appear on p1 again. Of course in the real world it would end up with a different set of peers and
    // select randomly so we get a second chance.
    Transaction t2 = (Transaction) outbound(p1);
    assertEquals(t1, t2);
}
 
Example 11
Source File: TransactionBroadcastTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void retryFailedBroadcast() throws Exception {
    // If we create a spend, it's sent to a peer that swallows it, and the peergroup is removed/re-added then
    // the tx should be broadcast again.
    InboundMessageQueuer p1 = connectPeer(1);
    connectPeer(2);

    // Send ourselves a bit of money.
    Block b1 = FakeTxBuilder.makeSolvedTestBlock(blockStore, address);
    inbound(p1, b1);
    assertNull(outbound(p1));
    assertEquals(FIFTY_COINS, wallet.getBalance());

    // Now create a spend, and expect the announcement on p1.
    Address dest = new ECKey().toAddress(PARAMS);
    Wallet.SendResult sendResult = wallet.sendCoins(peerGroup, dest, COIN);
    assertFalse(sendResult.broadcastComplete.isDone());
    Transaction t1;
    {
        Message m;
        while (!((m = outbound(p1)) instanceof Transaction));
        t1 = (Transaction) m;
    }
    assertFalse(sendResult.broadcastComplete.isDone());

    // p1 eats it :( A bit later the PeerGroup is taken down.
    peerGroup.removeWallet(wallet);
    peerGroup.addWallet(wallet);

    // We want to hear about it again. Now, because we've disabled the randomness for the unit tests it will
    // re-appear on p1 again. Of course in the real world it would end up with a different set of peers and
    // select randomly so we get a second chance.
    Transaction t2 = (Transaction) outbound(p1);
    assertEquals(t1, t2);
}
 
Example 12
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 13
Source File: SendRequest.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        // We use the WalletAppKit that handles all the boilerplate for us. Have a look at the Kit.java example for more details.
        NetworkParameters params = TestNet3Params.get();
        WalletAppKit kit = new WalletAppKit(params, new File("."), "sendrequest-example");
        kit.startAsync();
        kit.awaitRunning();

        System.out.println("Send money to: " + kit.wallet().currentReceiveAddress().toString());

        // How much coins do we want to send?
        // The Coin class represents a monetary Bitcoin value.
        // We use the parseCoin function to simply get a Coin instance from a simple String.
        Coin value = Coin.parseCoin("0.09");

        // To which address you want to send the coins?
        // The Address class represents a Bitcoin address.
        Address to = Address.fromBase58(params, "mupBAFeT63hXfeeT4rnAUcpKHDkz1n4fdw");

        // There are different ways to create and publish a SendRequest. This is probably the easiest one.
        // Have a look at the code of the SendRequest class to see what's happening and what other options you have: https://bitcoinj.github.io/javadoc/0.11/com/google/bitcoin/core/Wallet.SendRequest.html
        // 
        // Please note that this might raise a InsufficientMoneyException if your wallet has not enough coins to spend.
        // When using the testnet you can use a faucet (like the http://faucet.xeno-genesis.com/) to get testnet coins.
        // In this example we catch the InsufficientMoneyException and register a BalanceFuture callback that runs once the wallet has enough balance.
        try {
            Wallet.SendResult result = kit.wallet().sendCoins(kit.peerGroup(), to, value);
            System.out.println("coins sent. transaction hash: " + result.tx.getHashAsString());
            // you can use a block explorer like https://www.biteasy.com/ to inspect the transaction with the printed transaction hash. 
        } catch (InsufficientMoneyException e) {
            System.out.println("Not enough coins in your wallet. Missing " + e.missing.getValue() + " satoshis are missing (including fees)");
            System.out.println("Send money to: " + kit.wallet().currentReceiveAddress().toString());

            // Bitcoinj allows you to define a BalanceFuture to execute a callback once your wallet has a certain balance.
            // Here we wait until the we have enough balance and display a notice.
            // Bitcoinj is using the ListenableFutures of the Guava library. Have a look here for more information: https://github.com/google/guava/wiki/ListenableFutureExplained
            ListenableFuture<Coin> balanceFuture = kit.wallet().getBalanceFuture(value, BalanceType.AVAILABLE);
            FutureCallback<Coin> callback = new FutureCallback<Coin>() {
                @Override
                public void onSuccess(Coin balance) {
                    System.out.println("coins arrived and the wallet now has enough balance");
                }

                @Override
                public void onFailure(Throwable t) {
                    System.out.println("something went wrong");
                }
            };
            Futures.addCallback(balanceFuture, callback);
        }

        // shutting down 
        //kit.stopAsync();
        //kit.awaitTerminated();
    }
 
Example 14
Source File: SendRequest.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        // We use the WalletAppKit that handles all the boilerplate for us. Have a look at the Kit.java example for more details.
        NetworkParameters params = TestNet3Params.get();
        WalletAppKit kit = new WalletAppKit(params, new File("."), "sendrequest-example");
        kit.startAsync();
        kit.awaitRunning();

        System.out.println("Send money to: " + kit.wallet().currentReceiveAddress().toString());

        // How much coins do we want to send?
        // The Coin class represents a monetary Bitcoin value.
        // We use the parseCoin function to simply get a Coin instance from a simple String.
        Coin value = Coin.parseCoin("0.09");

        // To which address you want to send the coins?
        // The Address class represents a Bitcoin address.
        Address to = Address.fromBase58(params, "mupBAFeT63hXfeeT4rnAUcpKHDkz1n4fdw");

        // There are different ways to create and publish a SendRequest. This is probably the easiest one.
        // Have a look at the code of the SendRequest class to see what's happening and what other options you have: https://bitcoinj.github.io/javadoc/0.11/com/google/bitcoin/core/Wallet.SendRequest.html
        // 
        // Please note that this might raise a InsufficientMoneyException if your wallet has not enough coins to spend.
        // When using the testnet you can use a faucet (like the http://faucet.xeno-genesis.com/) to get testnet coins.
        // In this example we catch the InsufficientMoneyException and register a BalanceFuture callback that runs once the wallet has enough balance.
        try {
            Wallet.SendResult result = kit.wallet().sendCoins(kit.peerGroup(), to, value);
            System.out.println("coins sent. transaction hash: " + result.tx.getHashAsString());
            // you can use a block explorer like https://www.biteasy.com/ to inspect the transaction with the printed transaction hash. 
        } catch (InsufficientMoneyException e) {
            System.out.println("Not enough coins in your wallet. Missing " + e.missing.getValue() + " satoshis are missing (including fees)");
            System.out.println("Send money to: " + kit.wallet().currentReceiveAddress().toString());

            // Bitcoinj allows you to define a BalanceFuture to execute a callback once your wallet has a certain balance.
            // Here we wait until the we have enough balance and display a notice.
            // Bitcoinj is using the ListenableFutures of the Guava library. Have a look here for more information: https://github.com/google/guava/wiki/ListenableFutureExplained
            ListenableFuture<Coin> balanceFuture = kit.wallet().getBalanceFuture(value, BalanceType.AVAILABLE);
            FutureCallback<Coin> callback = new FutureCallback<Coin>() {
                @Override
                public void onSuccess(Coin balance) {
                    System.out.println("coins arrived and the wallet now has enough balance");
                }

                @Override
                public void onFailure(Throwable t) {
                    System.out.println("something went wrong");
                }
            };
            Futures.addCallback(balanceFuture, callback);
        }

        // shutting down 
        //kit.stopAsync();
        //kit.awaitTerminated();
    }