|
January 16, 2015, 12:10:06 PM |
|
Big thank you to Mike and other devs. There's a lot of good work behind BitcoinJ. I've been using quite a few libraries, and few are as well documented as BitcoinJ.
I've experimented a bit, and wanted to provide the solutions if someone else comes across similar problems:
>Can it be done with BitcoinJ? Yes, but since BitcoinJ is very lightweight, it won't scan the blockchain from before the program was started. So you only get the updates that happens to your address when your program is live.
Here's how you do it: (I've borrowed a lot from the examples provided in BitcoinJ on github)
public static void main(String[] args) {
NetworkParameters params = MainNetParams.get();
WalletAppKit kit = new WalletAppKit(params, new File("."), "walletappkit-example");
kit.startAsync(); kit.awaitRunning();
WalletListener wListener = new WalletListener(); kit.wallet().addEventListener(wListener);
Address address = null; try { address = new Address(params, "1BitangoaBiPiX6dqcLCHZUjsvzsuauB2x"); } catch (AddressFormatException e) { e.printStackTrace(); } kit.wallet().addWatchedAddress(address); }
//Then you need a wallet listener class:
static class WalletListener extends AbstractWalletEventListener {
@Override public void onCoinsReceived(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) { System.out.println("-----> coins resceived: " + tx.getHashAsString()); System.out.println("received: " + tx.getValue(wallet)); System.out.println("wallet balance: " +wallet.getBalance()); System.out.println("prev bal: "+prevBalance.value); System.out.println("new bal " + newBalance.value); System.out.println(tx.getVersion()); }
@Override public void onTransactionConfidenceChanged(Wallet wallet, Transaction tx) { System.out.println("-----> confidence changed: " + tx.getHashAsString()); TransactionConfidence confidence = tx.getConfidence(); System.out.println("new block depth: " + confidence.getDepthInBlocks()); }
@Override public void onCoinsSent(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) { System.out.println("coins sent"); }
@Override public void onReorganize(Wallet wallet) { }
@Override public void onWalletChanged(Wallet wallet) { }
@Override public void onKeysAdded(List<ECKey> keys) { System.out.println("new key added"); }
// @Override public void onScriptsChanged(Wallet wallet, List<Script> scripts, boolean isAddingScripts) { System.out.println("new script added"); } } Creating unsigned transaction might not be the best way to do it. Pass instead the required information; address and amount, and have the program on the other side create a transaction from that information.
Sample: (assuming you got a class variable WalletAppKit kit)
public Transaction(NetworkParameters params, String addressTo, Coin value){ Transaction tx1 = kit.wallet().createSend(new Address(params, addressTo), value); }
|