Java Code Examples for org.bitcoinj.kits.WalletAppKit#startAsync()
The following examples show how to use
org.bitcoinj.kits.WalletAppKit#startAsync() .
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: BlockChain.java From polling-station-app with GNU Lesser General Public License v3.0 | 7 votes |
public void startDownload() { BriefLogFormatter.init(); String filePrefix = "voting-wallet"; File walletFile = new File(Environment.getExternalStorageDirectory() + "/" + Util.FOLDER_DIGITAL_VOTING_PASS); if (!walletFile.exists()) { walletFile.mkdirs(); } kit = new WalletAppKit(params, walletFile, filePrefix); //set the observer kit.setDownloadListener(progressTracker); kit.setBlockingStartup(false); PeerAddress peer = new PeerAddress(params, peeraddr); kit.setPeerNodes(peer); kit.startAsync(); }
Example 2
Source File: TestFeeLevel.java From green_android with GNU General Public License v3.0 | 6 votes |
public static void main(String[] args) throws Exception { BriefLogFormatter.initWithSilentBitcoinJ(); if (args.length == 0) { System.err.println("Specify the fee rate to test in satoshis/kB as the first argument."); return; } Coin feeRateToTest = Coin.valueOf(Long.parseLong(args[0])); System.out.println("Fee rate to test is " + feeRateToTest.toFriendlyString() + "/kB"); kit = new WalletAppKit(PARAMS, new File("."), "testfeelevel"); kit.startAsync(); kit.awaitRunning(); try { go(feeRateToTest, NUM_OUTPUTS); } finally { kit.stopAsync(); kit.awaitTerminated(); } }
Example 3
Source File: TestFeeLevel.java From GreenBits with GNU General Public License v3.0 | 6 votes |
public static void main(String[] args) throws Exception { BriefLogFormatter.initWithSilentBitcoinJ(); if (args.length == 0) { System.err.println("Specify the fee rate to test in satoshis/kB as the first argument."); return; } Coin feeRateToTest = Coin.valueOf(Long.parseLong(args[0])); System.out.println("Fee rate to test is " + feeRateToTest.toFriendlyString() + "/kB"); kit = new WalletAppKit(PARAMS, new File("."), "testfeelevel"); kit.startAsync(); kit.awaitRunning(); try { go(feeRateToTest, NUM_OUTPUTS); } finally { kit.stopAsync(); kit.awaitTerminated(); } }
Example 4
Source File: ExamplePaymentChannelServer.java From green_android with GNU General Public License v3.0 | 5 votes |
public void run(NetworkParameters params) throws Exception { // Bring up all the objects we need, create/load a wallet, sync the chain, etc. We override WalletAppKit so we // can customize it by adding the extension objects - we have to do this before the wallet file is loaded so // the plugin that knows how to parse all the additional data is present during the load. appKit = new WalletAppKit(params, new File("."), "payment_channel_example_server") { @Override protected List<WalletExtension> provideWalletExtensions() { // The StoredPaymentChannelClientStates object is responsible for, amongst other things, broadcasting // the refund transaction if its lock time has expired. It also persists channels so we can resume them // after a restart. return ImmutableList.<WalletExtension>of(new StoredPaymentChannelServerStates(null)); } }; // Broadcasting can take a bit of time so we up the timeout for "real" networks final int timeoutSeconds = params.getId().equals(NetworkParameters.ID_REGTEST) ? 15 : 150; if (params == RegTestParams.get()) { appKit.connectToLocalHost(); } appKit.startAsync(); appKit.awaitRunning(); System.out.println(appKit.wallet()); // We provide a peer group, a wallet, a timeout in seconds, the amount we require to start a channel and // an implementation of HandlerFactory, which we just implement ourselves. new PaymentChannelServerListener(appKit.peerGroup(), appKit.wallet(), timeoutSeconds, Coin.valueOf(100000), this).bindAndStart(4242); }
Example 5
Source File: ExamplePaymentChannelServer.java From GreenBits with GNU General Public License v3.0 | 5 votes |
public void run(NetworkParameters params) throws Exception { // Bring up all the objects we need, create/load a wallet, sync the chain, etc. We override WalletAppKit so we // can customize it by adding the extension objects - we have to do this before the wallet file is loaded so // the plugin that knows how to parse all the additional data is present during the load. appKit = new WalletAppKit(params, new File("."), "payment_channel_example_server") { @Override protected List<WalletExtension> provideWalletExtensions() { // The StoredPaymentChannelClientStates object is responsible for, amongst other things, broadcasting // the refund transaction if its lock time has expired. It also persists channels so we can resume them // after a restart. return ImmutableList.<WalletExtension>of(new StoredPaymentChannelServerStates(null)); } }; // Broadcasting can take a bit of time so we up the timeout for "real" networks final int timeoutSeconds = params.getId().equals(NetworkParameters.ID_REGTEST) ? 15 : 150; if (params == RegTestParams.get()) { appKit.connectToLocalHost(); } appKit.startAsync(); appKit.awaitRunning(); System.out.println(appKit.wallet()); // We provide a peer group, a wallet, a timeout in seconds, the amount we require to start a channel and // an implementation of HandlerFactory, which we just implement ourselves. new PaymentChannelServerListener(appKit.peerGroup(), appKit.wallet(), timeoutSeconds, Coin.valueOf(100000), this).bindAndStart(4242); }
Example 6
Source File: SendRequest.java From green_android with GNU General Public License v3.0 | 4 votes |
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 7
Source File: ForwardingService.java From green_android with GNU General Public License v3.0 | 4 votes |
public static void main(String[] args) throws Exception { // This line makes the log output more compact and easily read, especially when using the JDK log adapter. BriefLogFormatter.init(); if (args.length < 1) { System.err.println("Usage: address-to-send-back-to [regtest|testnet]"); return; } // Figure out which network we should connect to. Each one gets its own set of files. NetworkParameters params; String filePrefix; if (args.length > 1 && args[1].equals("testnet")) { params = TestNet3Params.get(); filePrefix = "forwarding-service-testnet"; } else if (args.length > 1 && args[1].equals("regtest")) { params = RegTestParams.get(); filePrefix = "forwarding-service-regtest"; } else { params = MainNetParams.get(); filePrefix = "forwarding-service"; } // Parse the address given as the first parameter. forwardingAddress = Address.fromBase58(params, args[0]); // Start up a basic app using a class that automates some boilerplate. kit = new WalletAppKit(params, new File("."), filePrefix); if (params == RegTestParams.get()) { // Regression test mode is designed for testing and development only, so there's no public network for it. // If you pick this mode, you're expected to be running a local "bitcoind -regtest" instance. kit.connectToLocalHost(); } // Download the block chain and wait until it's done. kit.startAsync(); kit.awaitRunning(); // We want to know when we receive money. kit.wallet().addCoinsReceivedEventListener(new WalletCoinsReceivedEventListener() { @Override public void onCoinsReceived(Wallet w, Transaction tx, Coin prevBalance, Coin newBalance) { // Runs in the dedicated "user thread" (see bitcoinj docs for more info on this). // // The transaction "tx" can either be pending, or included into a block (we didn't see the broadcast). Coin value = tx.getValueSentToMe(w); System.out.println("Received tx for " + value.toFriendlyString() + ": " + tx); System.out.println("Transaction will be forwarded after it confirms."); // Wait until it's made it into the block chain (may run immediately if it's already there). // // For this dummy app of course, we could just forward the unconfirmed transaction. If it were // to be double spent, no harm done. Wallet.allowSpendingUnconfirmedTransactions() would have to // be called in onSetupCompleted() above. But we don't do that here to demonstrate the more common // case of waiting for a block. Futures.addCallback(tx.getConfidence().getDepthFuture(1), new FutureCallback<TransactionConfidence>() { @Override public void onSuccess(TransactionConfidence result) { forwardCoins(tx); } @Override public void onFailure(Throwable t) { // This kind of future can't fail, just rethrow in case something weird happens. throw new RuntimeException(t); } }); } }); Address sendToAddress = kit.wallet().currentReceiveKey().toAddress(params); System.out.println("Send coins to: " + sendToAddress); System.out.println("Waiting for coins to arrive. Press Ctrl-C to quit."); try { Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException ignored) {} }
Example 8
Source File: ExamplePaymentChannelClient.java From green_android with GNU General Public License v3.0 | 4 votes |
public void run(final String host, IPaymentChannelClient.ClientChannelProperties clientChannelProperties, final NetworkParameters params) throws Exception { // Bring up all the objects we need, create/load a wallet, sync the chain, etc. We override WalletAppKit so we // can customize it by adding the extension objects - we have to do this before the wallet file is loaded so // the plugin that knows how to parse all the additional data is present during the load. appKit = new WalletAppKit(params, new File("."), "payment_channel_example_client") { @Override protected List<WalletExtension> provideWalletExtensions() { // The StoredPaymentChannelClientStates object is responsible for, amongst other things, broadcasting // the refund transaction if its lock time has expired. It also persists channels so we can resume them // after a restart. // We should not send a PeerGroup in the StoredPaymentChannelClientStates constructor // since WalletAppKit will find it for us. return ImmutableList.<WalletExtension>of(new StoredPaymentChannelClientStates(null)); } }; // Broadcasting can take a bit of time so we up the timeout for "real" networks final int timeoutSeconds = params.getId().equals(NetworkParameters.ID_REGTEST) ? 15 : 150; if (params == RegTestParams.get()) { appKit.connectToLocalHost(); } appKit.startAsync(); appKit.awaitRunning(); // We now have active network connections and a fully synced wallet. // Add a new key which will be used for the multisig contract. appKit.wallet().importKey(myKey); appKit.wallet().allowSpendingUnconfirmedTransactions(); System.out.println(appKit.wallet()); // Create the object which manages the payment channels protocol, client side. Tell it where the server to // connect to is, along with some reasonable network timeouts, the wallet and our temporary key. We also have // to pick an amount of value to lock up for the duration of the channel. // // Note that this may or may not actually construct a new channel. If an existing unclosed channel is found in // the wallet, then it'll re-use that one instead. final InetSocketAddress server = new InetSocketAddress(host, 4242); waitForSufficientBalance(channelSize); final String channelID = host; // Do this twice as each one sends 1/10th of a bitcent 5 times, so to send a bitcent, we do it twice. This // demonstrates resuming a channel that wasn't closed yet. It should close automatically once we run out // of money on the channel. log.info("Round one ..."); openAndSend(timeoutSeconds, server, channelID, 5, clientChannelProperties); log.info("Round two ..."); log.info(appKit.wallet().toString()); openAndSend(timeoutSeconds, server, channelID, 4, clientChannelProperties); // 4 times because the opening of the channel made a payment. log.info("Stopping ..."); appKit.stopAsync(); appKit.awaitTerminated(); }
Example 9
Source File: SendRequest.java From GreenBits with GNU General Public License v3.0 | 4 votes |
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 10
Source File: ForwardingService.java From GreenBits with GNU General Public License v3.0 | 4 votes |
public static void main(String[] args) throws Exception { // This line makes the log output more compact and easily read, especially when using the JDK log adapter. BriefLogFormatter.init(); if (args.length < 1) { System.err.println("Usage: address-to-send-back-to [regtest|testnet]"); return; } // Figure out which network we should connect to. Each one gets its own set of files. NetworkParameters params; String filePrefix; if (args.length > 1 && args[1].equals("testnet")) { params = TestNet3Params.get(); filePrefix = "forwarding-service-testnet"; } else if (args.length > 1 && args[1].equals("regtest")) { params = RegTestParams.get(); filePrefix = "forwarding-service-regtest"; } else { params = MainNetParams.get(); filePrefix = "forwarding-service"; } // Parse the address given as the first parameter. forwardingAddress = Address.fromBase58(params, args[0]); // Start up a basic app using a class that automates some boilerplate. kit = new WalletAppKit(params, new File("."), filePrefix); if (params == RegTestParams.get()) { // Regression test mode is designed for testing and development only, so there's no public network for it. // If you pick this mode, you're expected to be running a local "bitcoind -regtest" instance. kit.connectToLocalHost(); } // Download the block chain and wait until it's done. kit.startAsync(); kit.awaitRunning(); // We want to know when we receive money. kit.wallet().addCoinsReceivedEventListener(new WalletCoinsReceivedEventListener() { @Override public void onCoinsReceived(Wallet w, Transaction tx, Coin prevBalance, Coin newBalance) { // Runs in the dedicated "user thread" (see bitcoinj docs for more info on this). // // The transaction "tx" can either be pending, or included into a block (we didn't see the broadcast). Coin value = tx.getValueSentToMe(w); System.out.println("Received tx for " + value.toFriendlyString() + ": " + tx); System.out.println("Transaction will be forwarded after it confirms."); // Wait until it's made it into the block chain (may run immediately if it's already there). // // For this dummy app of course, we could just forward the unconfirmed transaction. If it were // to be double spent, no harm done. Wallet.allowSpendingUnconfirmedTransactions() would have to // be called in onSetupCompleted() above. But we don't do that here to demonstrate the more common // case of waiting for a block. Futures.addCallback(tx.getConfidence().getDepthFuture(1), new FutureCallback<TransactionConfidence>() { @Override public void onSuccess(TransactionConfidence result) { forwardCoins(tx); } @Override public void onFailure(Throwable t) { // This kind of future can't fail, just rethrow in case something weird happens. throw new RuntimeException(t); } }); } }); Address sendToAddress = kit.wallet().currentReceiveKey().toAddress(params); System.out.println("Send coins to: " + sendToAddress); System.out.println("Waiting for coins to arrive. Press Ctrl-C to quit."); try { Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException ignored) {} }
Example 11
Source File: ExamplePaymentChannelClient.java From GreenBits with GNU General Public License v3.0 | 4 votes |
public void run(final String host, IPaymentChannelClient.ClientChannelProperties clientChannelProperties, final NetworkParameters params) throws Exception { // Bring up all the objects we need, create/load a wallet, sync the chain, etc. We override WalletAppKit so we // can customize it by adding the extension objects - we have to do this before the wallet file is loaded so // the plugin that knows how to parse all the additional data is present during the load. appKit = new WalletAppKit(params, new File("."), "payment_channel_example_client") { @Override protected List<WalletExtension> provideWalletExtensions() { // The StoredPaymentChannelClientStates object is responsible for, amongst other things, broadcasting // the refund transaction if its lock time has expired. It also persists channels so we can resume them // after a restart. // We should not send a PeerGroup in the StoredPaymentChannelClientStates constructor // since WalletAppKit will find it for us. return ImmutableList.<WalletExtension>of(new StoredPaymentChannelClientStates(null)); } }; // Broadcasting can take a bit of time so we up the timeout for "real" networks final int timeoutSeconds = params.getId().equals(NetworkParameters.ID_REGTEST) ? 15 : 150; if (params == RegTestParams.get()) { appKit.connectToLocalHost(); } appKit.startAsync(); appKit.awaitRunning(); // We now have active network connections and a fully synced wallet. // Add a new key which will be used for the multisig contract. appKit.wallet().importKey(myKey); appKit.wallet().allowSpendingUnconfirmedTransactions(); System.out.println(appKit.wallet()); // Create the object which manages the payment channels protocol, client side. Tell it where the server to // connect to is, along with some reasonable network timeouts, the wallet and our temporary key. We also have // to pick an amount of value to lock up for the duration of the channel. // // Note that this may or may not actually construct a new channel. If an existing unclosed channel is found in // the wallet, then it'll re-use that one instead. final InetSocketAddress server = new InetSocketAddress(host, 4242); waitForSufficientBalance(channelSize); final String channelID = host; // Do this twice as each one sends 1/10th of a bitcent 5 times, so to send a bitcent, we do it twice. This // demonstrates resuming a channel that wasn't closed yet. It should close automatically once we run out // of money on the channel. log.info("Round one ..."); openAndSend(timeoutSeconds, server, channelID, 5, clientChannelProperties); log.info("Round two ..."); log.info(appKit.wallet().toString()); openAndSend(timeoutSeconds, server, channelID, 4, clientChannelProperties); // 4 times because the opening of the channel made a payment. log.info("Stopping ..."); appKit.stopAsync(); appKit.awaitTerminated(); }