Gotchas When Using Wallets in BitcoinJ

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 earlier, 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.


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!