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();
            }
            

    }

 

About Author

Author Image
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.

Request for Proposal

Name is required

Comment is required

Sending message..