Bitcoin is an experimental new digital currency that enables instant payments to anyone, anywhere in the world. Bitcoin uses peer-to-peer technology to operate with no central authority: managing transactions and issuing money are carried out collectively by the network.
File walletFile = new File("coins.dat");
try {
wallet = Wallet.loadFromFile(walletFile);
} catch (IOException e) {
wallet = new Wallet(params);
wallet.addKey(new ECKey());
wallet.saveToFile(walletFile);
}
NetworkParameters params =
NetworkParameters.testNet()
For production:
NetworkParameters params =
NetworkParameters.prodNet();
Address a1 =
new Address(params, "1HaSchNbFfLF8MJw41QNie7RPePPqdTozb");
→ 1HaSchNbFfLF8MJw41QNie7RPePPqdTozb
ECKey key = new ECKey();
byte[] publicKey = key.getPubKey();
Gets the address corresponding to the public key.
Address addr = key.toAddress(params);
System.out.println(addr.toString());
1HwBZk111V4eEEC4BcN8fZd3RVifig2WjY
final PeerGroup peerGroup =
new PeerGroup(blockStore, params, chain);
peerGroup.setUserAgent("MyApp", "1.2");
peerGroup.addWallet(wallet);
peerGroup.addAddress(
new PeerAddress(InetAddress.getLocalHost()));
peerGroup.start();
wallet.addEventListener(
new AbstractWalletEventListener() {
public void onCoinsReceived(
Wallet w,
Transaction tx,
BigInteger prevBalance,
BigInteger newBalance) {
// Running on a peer thread.
}
});
// Wallet w, Transaction tx;
TransactionInput input = tx.getInputs().get(0);
Address from = input.getFromAddress();
BigInteger value = tx.getValueSentToMe(w);
println(Utils.bitcoinValueToFriendlyString(value));
Note: For each payment request, generate a new address.
// Address to; Wallet w
Wallet.SendResult sendResult =
w.sendCoins(peerGroup, to, value);
println("Sent coins! TX=" +
sendResult.tx.getHashAsString());
Note: sendResult could be null
.
Talk |
|
Bitcoin |
|
BitcoinJ |
Based on work by Hakim El Hattab
Details: git blame
;-)