Sending bitcoins from one wallet to another
Posted By : S. Ajit | 27-May-2016

Bitcoinj library is a Java implementation of the Bitcoin protocol. It can maintain a wallet, send/receive transactions.in order to perform transaction there are certian steps that need to be followed .Consider the below written program which depict a simple bitcoin transaction.
public class SendCoin {
public static void main(String[] args) {
File file = new File("/opt/wallet.dat");
NetworkParameters params=TestNet3Params.get();
try
{
Wallet wallet=Wallet.loadFromFile(file);
BlockStore block=new MemoryBlockStore(params);
BlockChain chain=new BlockChain(params,block);
chain.addWallet(wallet);
PeerGroup peer=new PeerGroup(params,chain);
peer.addAddress(new PeerAddress(InetAddress.getByName("127.0.0.1"),18333));
peer.startAsync();
peer.downloadBlockChain();
Coin btcCoin = Coin.parseCoin("0.0001");
Address receiverAddress=new Address(params, "mzD8ncNmbgBdrfJF5RfXkPAStKZS9TLMvj");
Wallet.SendRequest.DEFAULT_FEE_PER_KB = Coin.ZERO;
SendRequest request = SendRequest.to(receiverAddress, btcCoin);
request.ensureMinRequiredFee = false;
request.fee = Coin.valueOf(10000);
request.feePerKb = Coin.ZERO;
Transaction transaction = wallet.sendCoins(request);
wallet.completeTx(request);
wallet.commitTx(request.tx);
TransactionBroadcast future = peer.broadcastTransaction(request.tx);
future.broadcast();
String transactionHash = request.tx.getHashAsString();
System.out.println("transaction hash"+transactionHash)
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
S. Ajit
Ajit is a software developer who loves solving problems and programming in C, C++, Java. He also has a passion to learn new technologies.