Bitcoin Price = 575.0 USD
Namecheap.com
Home / Bitcoin Programming / Bitcoin Programming With BitcoinJ – Part 2 (Bye-Bye Money)
bitcoin programming, BitcoinJ programming

Bitcoin Programming With BitcoinJ – Part 2 (Bye-Bye Money)

Bye-bye Money

Now, let’s write a program that can send money from an arbitrary Bitcoin address. To create a new bye-bye-money program, run the following from your top-level program directory:

mvn archetype:generate -DgroupId=byebyemoney -DartifactId=bye-bye-money
   -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Then, make the exact additions to the pom.xml file as we did in the hello-money example in Part 1 of this series, except for the line that reads <mainClass>hellomoney.App</mainClass>. Change that line to <mainClass>byebyemoney.App</mainClass>.

(These steps are analogous to those we followed for our hello-money program in our article “Introduction to bitcoin programming“).

Just as before, open the file src/main/java/byebyemoney/App.java and replace its contents with the following program:

package byebyemoney;

import com.google.bitcoin.core.;
import com.google.bitcoin.store.;
import com.google.bitcoin.discovery.DnsDiscovery;
import java.util.concurrent.ExecutionException;
import java.io.File;
import java.math.BigInteger;

public class App
{
   public static void main( String[] args )
       throws BlockStoreException, AddressFormatException,
                   InterruptedException, ExecutionException
   {
       NetworkParameters params = NetworkParameters.prodNet();
       Wallet wallet = new Wallet(params);
       DumpedPrivateKey key = new DumpedPrivateKey(params,
               “L1vJHdDqQ5kcY5q4QoY124zD21UVgFe6NL2835mp8UgG2FNU94Sy”);
       wallet.addKey(key.getKey());
       BlockChain chain = new BlockChain(params, wallet,
               new MemoryBlockStore(params));
     PeerGroup peerGroup = new PeerGroup(params, chain);
     peerGroup.addPeerDiscovery(new DnsDiscovery(params));
     peerGroup.addWallet(wallet);
     peerGroup.start();
     peerGroup.downloadBlockChain();
     BigInteger balance = wallet.getBalance();
     System.out.println(“Wallet balance: ” + balance);
     Address destinationAddress = new Address(params,
              “1BTCorgHwCg6u2YSAWKgS17qUad6kHmtQW”);
     BigInteger fee=BigInteger.valueOf(10000);
     Wallet.SendRequest req = Wallet.SendRequest.to(
             destinationAddress,balance.subtract(fee));
     req.fee = fee;
     Wallet.SendResult result = wallet.sendCoins(peerGroup, req);
     if(result != null)
         {
             result.broadcastComplete.get();
             System.out.println(“The money was sent!”);
         }
     else
         {
             System.out.println(“Something went wrong sending the money.”);
         }
   }
}

Many of the lines in this new program are shared with our previous hello-money program, but let’s look carefully at the new parts.

Importing a Private Key:

To send money from our program, we need to import the private key of the Bitcoin address from the previous example. Here is the code that does this:

DumpedPrivateKey key = new DumpedPrivateKey(params,
         “L1vJHdDqQ5kcY5q4QoY124zD21UVgFe6NL2835mp8UgG2FNU94Sy“);
wallet.addKey(key.getKey());
BlockChain chain = new BlockChain(params, wallet,
         new MemoryBlockStore(params));

In the first lines, we’re explicitly adding a new, preexisting private key to our wallet. This is the key associated with the Bitcoin address that received the money in the hello-money program. You need to replace the private key shown on this line with the private key you wrote down when running the previous example. Also, in this new program we’re not using the SPVBlockStore function; instead, we’re using bitcoinJ’s MemoryBlockStore function for variety. This block store won’t create a file, but by using it, our program will need to re-download the blockchain every time the program runs. (This also guarantees that bitcoinJ will assign the correct balance to the wallet. We’ll discuss why in later part of this tutorial.

Sending the Money:

Now let’s look at the code that actually sends the money:

BigInteger balance = wallet.getBalance();
System.out.println(“Wallet balance: ” + balance);
Address destinationAddress = new Address(params,
     “1S4gFerHwCg6u2YSAWKgS17qUae5lHmtQW“);
BigInteger fee = BigInteger.valueOf(10000);
Wallet.SendRequest req = Wallet.SendRequest.to(
     destinationAddress,balance.subtract(fee));
req.fee = fee;
Wallet.SendResult result = wallet.sendCoins(peerGroup, req);

First, we get the balance contained in the wallet and display it. Next, we declare the destination address the money should be sent to. In this example, we input a non-sense address; feel free to substitute a public address of one of your own wallets.

Nowadays, it’s best to include a transaction fee when sending bitcoins, which we declare to be 10,000 satoshis. Next, we create a SendRequest object, which is a structure to hold the basic information about what we’re sending and includes the destination address and the amount to be sent (which is the balance minus the fee). Then, we set the fee on this object and send our money!

 

Ensuring the Money Transmission:

If we try to send more money than we have, if the fee is inadequate, or if the Internet connection drops out at the wrong moment, the money might never be accepted by the network. Therefore, we need to write code that waits and ensures that the money we sent is transmitted to the network. Here’s what we’ll add to do this:

result.broadcastComplete.get();
System.out.println(“The money was sent!”);

The first line of code retrieves a Java future object, which indicates that the send transaction has been properly broadcast to the network. (A standard in Java, futures retrieve information about a separate execution thread in this case the thread that monitors communication with the Bitcoin network.) If this line completes without throwing an exception, we display a message indicating that the money was sent.

Running bye-bye-money:

We can run bye-bye-money in the usual way (remember to input your own private key):

> mvn install
> mvn exec:java

  EXCEPTION TYPES IN BITCOINJ 
One feature we skimped on in this example is error handling: The main function simply rethrows a variety of different exceptions for operations that can go wrong as we attempt to send our money. These include the following exceptions:
BlockStoreException: This is thrown when the block store cannot be created (most commonly, this happens with block store types that write to a file when something corrupts the file).
AddressFormatException: This is thrown when the format of the address is incorrect.
InterruptedException: This is thrown when network connection problems occur.
ExecutionException: This is thrown when we’re using a future object and an exception occurs in the other thread (as happens when we check for completion of the transaction broadcast).
In a more sophisticated Bitcoin app, you should catch all of these exception types separately and add more descriptive error messages for your app’s users.

 

Because this program churns through the blockchain in memory, you’ll need to wait a few minutes or more for it to complete (even when you rerun it). If the program is successful, you’ll see the message The money was sent!, and the money should arrive at the destination wallet. You can also access a blockchain information site (such as http://blockchain.info/), enter the source or destination address, and see that the details of the transaction are part of the public record.

Congratulations! You now understand the basics of writing a Bitcoin application!

 

To the novice, the way wallets and the BlockChain object work in bitcoinJ can be very confusing. If you don’t fully understand bitcoinJ’s behavior, bitcoinJ can also report incorrect wallet balances.

This happens because bitcoinJ is optimized around the concept of an SPV blockchain. The performance benefits of SPV blockchains were discussed in Part 1 of this series, but because they contain only limited blockchain data, you need to follow a few basic rules to ensure they work properly for you in bitcoinJ:

  1. If your app’s wallet already has money in it, bitcoinJ needs to know the amount before the blockchain is downloaded from the network.
  2. After the blockchain is loaded, bitcoinJ will perform the necessary tasks to ensure the wallet’s accuracy as new transactions appear on the network.
  3. If you use a block store type that supports saving to a disk file, your app is responsible for saving the wallet to a file, as well (it is also responsible for loading the block store and wallet data).

As you saw when we constructed a BlockChain object, bitcoinJ expects the app to pass in a wallet object. This allows the wallet to be updated when relevant historical transactions are found in downloaded blocks and allows rule #1 to be enforced: Be sure not to add additional keys to your wallet after the fact and expect your wallet to work without redownloading the blockchain.

Similarly, when we initialized the PeerGroup object, we called addWallet() to add our wallet to the peer group. By doing so, bitcoinJ keeps the wallet balance in sync with any new transactions that appear in the Bitcoin network as the program is running, enforcing rule #2.

To make sure rule #3 is adhered to, you can use the Wallet.loadFromFile() and Wallet.saveToFile()functions. A Wallet.autoSaveToFile() function is also available that can help with loading and saving the block store and wallet data. To learn how to use these functions properly, look at the example programs in the bitcoinJ repository.

If you keep the previously listed three basic tenets in mind, you’ll avoid most of the pitfalls that accompany mastering bitcoinJ.

Conclusion:

We hope you’ve enjoyed this tour of bitcoinJ programming, and we look forward to seeing any awesome new apps that you build. After all, the app you build just might completely reinvent how people interact with their money in the Internet age!

About Haruaki Osamu

Haruaki Osamu is a software developer who earned his degree in Computer Sciences (CS) from Temple University, Tokyo in 2005. He specializes in C++, Python and blockchain coding. He helped in developing a few bitcoin exchanges back in 2010. Since then, he has been helping many businesses build their websites and utilize bitcoin's blockchain technology. Haruaki is now working with multiple clients on the development of bitcoin apps, virtual exchanges and cryptocurrency mining software.

Check Also

blockchain coding, bitcoin software development

An Introduction To Developing Bitcoin Software

One of the most interesting things about bitcoin is that it is easy to code ...

  • Neil B

    My god…. That font. Worst choice of code font ever.

  • EXPmarygarcia

    Bye Bye Money! Hello Digital Currency!

  • rashidmdk

    These are well described examples. Can you provide examples of Repair Wallet and Restore Wallet using Bitcoinj