javabitcoinbitcoinj

Checking wallet balance with bitcoinj


I'm attempting to learn the bitcoinj API and I've written the test code below. I created an account on:

http://tpfaucet.appspot.com/

so I can use fake coins and test sending/receiving. My account has 14 fake BTC's shown when I log in to the URL. However, my code below indicates I have 0 coins. Can someone help me understand what I missed? I used both getBalance and getWatchedBalance with no luck.

public class CheckBalance {

    public static void main(String[] args) throws Exception {
        // This line makes the log output more compact and easily read, especially when using the JDK log adapter.
        BriefLogFormatter.init();
        // Figure out which network we should connect to. Each one gets its own set of files.
        final NetworkParameters params = TestNet3Params.get();
        final String filePrefix = "forwarding-service-testnet";
        // Parse the address given as the first parameter.
        final Address forwardingAddress = new Address(params, "bogusHash"); //note, I replace bogusHash when I really run
        // Start up a basic app using a class that automates some boilerplate.
        final WalletAppKit kit = new WalletAppKit(params, new File("."), filePrefix);
        // Download the block chain and wait until it's done.
        kit.startAndWait();
        System.out.println("You have : " +kit.wallet().getWatchedBalance() + " bitcoins");
        System.exit(0);
    }

}

Solution

  • You are not using forwardingAdress after assigning it. I guess this is not the adress of a pubkey in that wallet?

    To get the balance for an Adress that is not (yet) in the Wallet you can do the following:

    1. Find the PublicKey to the adress. For example with this service for MainNet adresses: https://www.biteasy.com/blockchain/addresses/1CjgioGLRpLyEiFSsLpYdEKfaFjWg3ZWSS
    2. Add this public key to the wallet: kit.wallet().addKey(new ECKey(null, Hex.decode("0210fdade86b268597e9aa4f2adc314fe459837be831aeb532f04b32c160b4e50a")));
    3. Put the wallet in autosave mode kit.setAutoSave(true);
    4. Run this

    Now you have the pubkey for which you want to know the balance in the wallet. Remove the Blockchain file: forwarding-service-testnet.spvchain

    You have a public key without a creation date in your wallet and the Blockchain download will take much longer. But in the end you should see a proper balance.

    WalletAppKit is not meant to check the balance for keypairs it did not generate or add later. So thats why this is more complicated as it should be.

    You can create a normal Wallet, add keys, add it to a PeerGroup and a SPVBlockschain and then start downloading blocks to get the information necessary to calculate the balance. Whenever you add keys to a wallet you have to redownload the SPVBlockchain if the key is older than the last Block.