使用bitcoinj检查钱包余额



我正在尝试学习bitcoinj API,我已经编写了下面的测试代码。我在上创建了一个帐户

http://tpfaucet.appspot.com/

所以我可以使用假硬币并测试发送/接收。当我登录URL时,我的帐户显示了14个假的BTC。但是,我下面的代码表示我有0个硬币。有人能帮我理解我错过了什么吗?我同时使用了getBalancegetWatchedBalance,但运气不佳。

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

分配后没有使用forwardingAdress。我想这不是钱包中公钥的地址?

要获得钱包中未包含的地址的余额,您可以执行以下操作:

  1. 查找地址的公钥。例如,使用MainNet地址的此服务:https://www.biteasy.com/blockchain/addresses/1CjgioGLRpLyEiFSsLpYdEKfaFjWg3ZWSS
  2. 将此公钥添加到钱包:kit.wallet().addKey(new ECKey(null, Hex.decode("0210fdade86b268597e9aa4f2adc314fe459837be831aeb532f04b32c160b4e50a")));
  3. 将钱包置于自动保存模式kit.setAutoSave(true);
  4. 运行此

现在您有了要知道钱包余额的公钥。删除区块链文件:forwarding-service-testnet.spvchain

你的钱包里有一个没有创建日期的公钥,区块链下载需要更长的时间。但最终你应该看到一个适当的平衡。

WalletAppKit并不意味着要检查它以后没有生成或添加的密钥对的余额。所以这就是为什么它应该更复杂的原因

你可以创建一个普通的钱包,添加密钥,将其添加到PeerGroup和SPVBlockschain,然后开始下载区块,以获得计算余额所需的信息。每当你向钱包添加密钥时,如果密钥比上一个区块旧,你必须重新下载SPVBlockchain。

在您的代码中,您检查的是钱包的余额(尚未包含任何地址),而不是您创建的地址的余额。在该地址的余额出现在您的钱包中之前,您应该尝试将您从网络创建的地址的密钥导入到您在本地创建的钱包中。

您可以使用检查您的比特币余额

WalletAppKit kit = new WalletAppKit(params, new File("."), "walletappkit2");
System.out.println("you have got :" + MonetaryFormat.BTC.noCode().format(kit.wallet().getBalance()).toString());

最新更新