本文整理汇总了Java中org.bitcoinj.kits.WalletAppKit.startAsync方法的典型用法代码示例。如果您正苦于以下问题:Java WalletAppKit.startAsync方法的具体用法?Java WalletAppKit.startAsync怎么用?Java WalletAppKit.startAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.bitcoinj.kits.WalletAppKit
的用法示例。
在下文中一共展示了WalletAppKit.startAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: startDownload
import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
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();
}
示例2: run
import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
public void run() throws Exception {
NetworkParameters params = RegTestParams.get();
// 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));
}
};
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(), 15, Coin.valueOf(100000), this).bindAndStart(4242);
}
示例3: main
import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
BriefLogFormatter.init();
if (args.length == 0) {
System.err.println("Specify the fee level to test in satoshis as the first argument.");
return;
}
Coin feeToTest = Coin.valueOf(Long.parseLong(args[0]));
kit = new WalletAppKit(PARAMS, new File("."), "testfeelevel");
kit.startAsync();
kit.awaitRunning();
try {
go(feeToTest);
} finally {
kit.stopAsync();
kit.awaitTerminated();
}
}
示例4: main
import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
BriefLogFormatter.initWithSilentBitcoinJ();
if (args.length == 0) {
System.err.println("Specify the fee level to test in satoshis as the first argument.");
return;
}
Coin feeToTest = Coin.valueOf(Long.parseLong(args[0]));
System.out.println("Fee to test is " + feeToTest.toFriendlyString());
kit = new WalletAppKit(PARAMS, new File("."), "testfeelevel");
kit.startAsync();
kit.awaitRunning();
try {
go(feeToTest, NUM_OUTPUTS);
} finally {
kit.stopAsync();
kit.awaitTerminated();
}
}
示例5: main
import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
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();
}
}
示例6: main
import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
public static void main(String[] args) {
// First we configure the network we want to use.
// The available options are:
// - MainNetParams
// - TestNet3Params
// - RegTestParams
// While developing your application you probably want to use the Regtest mode and run your local bitcoin network. Run bitcoind with the -regtest flag
// To test you app with a real network you can use the testnet. The testnet is an alternative bitcoin network that follows the same rules as main network. Coins are worth nothing and you can get coins for example from http://faucet.xeno-genesis.com/
//
// For more information have a look at: https://bitcoinj.github.io/testing and https://bitcoin.org/en/developer-examples#testing-applications
NetworkParameters params = TestNet3Params.get();
// Now we initialize a new WalletAppKit. The kit handles all the boilerplate for us and is the easiest way to get everything up and running.
// Have a look at the WalletAppKit documentation and its source to understand what's happening behind the scenes: https://github.com/bitcoinj/bitcoinj/blob/master/core/src/main/java/org/bitcoinj/kits/WalletAppKit.java
WalletAppKit kit = new WalletAppKit(params, new File("."), "walletappkit-example");
// In case you want to connect with your local bitcoind tell the kit to connect to localhost.
// You must do that in reg test mode.
//kit.connectToLocalHost();
// Now we start the kit and sync the blockchain.
// bitcoinj is working a lot with the Google Guava libraries. The WalletAppKit extends the AbstractIdleService. Have a look at the introduction to Guava services: https://code.google.com/p/guava-libraries/wiki/ServiceExplained
kit.startAsync();
kit.awaitRunning();
// To observe wallet events (like coins received) we implement a EventListener class that extends the AbstractWalletEventListener bitcoinj then calls the different functions from the EventListener class
WalletListener wListener = new WalletListener();
kit.wallet().addEventListener(wListener);
// Ready to run. The kit syncs the blockchain and our wallet event listener gets notified when something happens.
// To test everything we create and print a fresh receiving address. Send some coins to that address and see if everything works.
System.out.println("send money to: " + kit.wallet().freshReceiveAddress().toString());
// Make sure to properly shut down all the running services when you manually want to stop the kit. The WalletAppKit registers a runtime ShutdownHook so we actually do not need to worry about that when our application is stopping.
//System.out.println("shutting down again");
//kit.stopAsync();
//kit.awaitTerminated();
}
示例7: setUp
import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
@Before
public void setUp() throws Exception
{
appKit = new WalletAppKit(TestNet3Params.get(), walletLocation, TransactionServletTest.class.getName().toString());
appKit.setAutoSave(true);
appKit.startAsync();
appKit.awaitRunning();
appKit.setBlockingStartup(true);
wallet = appKit.wallet();
log.info("Wallet Address " + wallet.currentReceiveAddress());
}
示例8: run
import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
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);
}
示例9: initWalletService
import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
private void initWalletService() {
Log.d(TAG, "initWalletService with app config: " + getAppConfig());
ClientUtils.fixECKeyComparator();
initLogging();
bitcoinjContext = new Context(getNetworkParameters());
Context.propagate(bitcoinjContext);
walletFile = walletFile();
Log.d(TAG, "Wallet file: " + walletFile + ", already exists: " + walletFile.exists());
kit = new WalletAppKit(bitcoinjContext, getFilesDir(), getAppConfig().getWalletFilesPrefix()) {
@Override
protected void onSetupCompleted() {
final long startTime = System.currentTimeMillis();
try {
wallet = kit.wallet();
peerGroup = kit.peerGroup();
blockChain = kit.chain();
blockStore = kit.store();
initWalletEventListener();
/*
* Check that we already have keys.
* - if yes: check whether current address is still locked. if no: create new one.
* - if no: (1) create client key, (2) execute key-exchange and store server key (3) init address
*/
boolean keysAlreadyExist = loadKeysIfExist();
if (!keysAlreadyExist) {
keyExchange();
loadKeysIfExist();
}
initAddresses();
initFiatCurrency();
// broadcast current wallet balance (not using serviceBinder!)
Coin coinBalance = wallet.getBalance();
broadcastBalanceChanged(coinBalance, exchangeRate.coinToFiat(coinBalance));
if(walletLRunnable!=null) {
walletLRunnable.run();
}
appKitInitDone = true;
broadcastBalanceChanged();
} catch (Exception e) {
String errorMessage = "Error during wallet initialization: " + e.getMessage();
Log.e(TAG, errorMessage, e);
broadcastWalletError(errorMessage);
} finally {
long duration = System.currentTimeMillis() - startTime;
Log.d(TAG, "WalletService - onSetupCompleted finished in "+duration+" ms");
}
}
};
setChainCheckpoints();
kit.setDownloadListener(new DownloadListener());
kit.setBlockingStartup(false);
kit.startAsync();
Log.d(TAG, "Wallet started");
}
示例10: main
import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
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 = new Address(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://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained
ListenableFuture<Coin> balanceFuture = kit.wallet().getBalanceFuture(value, BalanceType.AVAILABLE);
FutureCallback<Coin> callback = new FutureCallback<Coin>() {
public void onSuccess(Coin balance) {
System.out.println("coins arrived and the wallet now has enough balance");
}
public void onFailure(Throwable t) {
System.out.println("something went wrong");
}
};
Futures.addCallback(balanceFuture, callback);
}
// shutting down
//kit.stopAsync();
//kit.awaitTerminated();
}
示例11: main
import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
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 = new Address(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().addEventListener(new AbstractWalletEventListener() {
@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<Transaction>() {
@Override
public void onSuccess(Transaction result) {
// "result" here is the same as "tx" above, but we use it anyway for clarity.
forwardCoins(result);
}
@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) {}
}
示例12: run
import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
public void run(final String host) 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.
return ImmutableList.<WalletExtension>of(new StoredPaymentChannelClientStates(null, peerGroup()));
}
};
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 int timeoutSecs = 15;
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(timeoutSecs, server, channelID, 5);
log.info("Round two ...");
log.info(appKit.wallet().toString());
openAndSend(timeoutSecs, server, channelID, 4); // 4 times because the opening of the channel made a payment.
log.info("Stopping ...");
appKit.stopAsync();
appKit.awaitTerminated();
}
示例13: testWalletApp
import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
@Test
public void testWalletApp() throws UnknownHostException {
WalletAppKit kit = new WalletAppKit(MainNetParams.get(), new File("/tmp"), "" + System.currentTimeMillis()) {
@Override
protected void onSetupCompleted() {
// This is called in a background thread after startAndWait is called, as setting up various objects
// can do disk and network IO that may cause UI jank/stuttering in wallet apps if it were to be done
// on the main thread.
System.out.println("keyChainSize=" + wallet().getKeychainSize());
if (wallet().getKeychainSize() < 1) {
System.out.println("<1");
wallet().importKey(new ECKey());
} else {
System.out.println(">1");
}
}
};
kit.setPeerNodes(new PeerAddress(InetAddress.getByName("10.106.137.73")));
Service service = kit.startAsync();
service.awaitRunning();
//kit.peerGroup().addPeerFilterProvider(new EWFilterProvider());
EWChainListener listener = new EWChainListener();
kit.chain().addListener(listener);
Address address = kit.wallet().freshReceiveAddress();
kit.wallet().addEventListener(new AbstractWalletEventListener() {
@Override
public void onCoinsReceived(Wallet w, Transaction tx, Coin prevBalance, Coin newBalance) {
System.out.println("onCoinsReceived");
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<Transaction>() {
@Override
public void onSuccess(Transaction result) {
// "result" here is the same as "tx" above, but we use it anyway for clarity.
//forwardCoins(result);
}
@Override
public void onFailure(Throwable t) {
}
});
*/
}
});
System.out.println("address= " + address.toString());
System.out.println("counter=" + listener.counter);
service.awaitTerminated();
}
示例14: run
import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
public void run(final String host) 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));
}
};
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 int timeoutSecs = 15;
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(timeoutSecs, server, channelID, 5);
log.info("Round two ...");
log.info(appKit.wallet().toString());
openAndSend(timeoutSecs, server, channelID, 4); // 4 times because the opening of the channel made a payment.
log.info("Stopping ...");
appKit.stopAsync();
appKit.awaitTerminated();
}
示例15: main
import org.bitcoinj.kits.WalletAppKit; //导入方法依赖的package包/类
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();
}