Reputation: 63
I am trying to get a wallet balance using BitcoinJ, this is the code i am trying but it always returns 0
BriefLogFormatter.init();
NetworkParameters params ;
String net = "testnet"; //choosing network
if (net.equals("testnet")) {params = TestNet3Params.get();
} else if (net.equals("regtest")) {params = RegTestParams.get();
} else {params = MainNetParams.get();}
String privKey = "key-here";
BigInteger test = new BigInteger(privKey);
ECKey key = ECKey.fromPrivate(test);//initializing key
Wallet wallet = new Wallet(params);
wallet.importKey(key); //puting key in wallet
BlockStore blockStore = new MemoryBlockStore(params);
BlockChain chain = new BlockChain(params, wallet, blockStore);
PeerGroup peerGroup = new PeerGroup(params, chain);
peerGroup.addWallet(wallet);
peerGroup.startAsync(); //syncing with the blockchain
System.out.println( wallet.getBalance().toString());//getting balance
Upvotes: 1
Views: 864
Reputation: 139
Use the WalletAppKit
class to handle all the boiler plate:
WalletAppKit walletAppKit = WalletAppKit(params, ScriptType, FileDirectory)
walletAppKit.startAsync()
walletAppKit.awaitRunning()
walletAppKit.wallet().getBalance().toPlainString()
Upvotes: 0
Reputation: 33
You should downloadBlockChain after startAsync
peerGroup.startAsync();
peerGroup.downloadBlockChain();
Upvotes: 1