Cot*_*oty 4 java bitcoin bitcoinj
我的目标是监视公共比特币地址,并在资金发送到该地址时打印到控制台。就这样。我现在使用的是之前在 Bitcoin Core 中生成的地址。
我正在执行以下操作:
NetworkParameters params = MainNetParams.get();
Wallet wallet = Wallet.loadFromFile(file);
BlockStore blockStore = new MemoryBlockStore(params);
BlockChain chain = new BlockChain(params, wallet, blockStore);
PeerGroup peerGroup = new PeerGroup(params, chain);
peerGroup.addPeerDiscovery(new DnsDiscovery(params));
peerGroup.setUseLocalhostPeerWhenPossible(true);
peerGroup.startAsync();
Address add = new Address(params, "1NpxxxxxxxxxxxxxxxaSC4");
wallet.addWatchedAddress(add);
wallet.addEventListener(new AbstractWalletEventListener() {
@Override
public synchronized void onCoinsReceived(Wallet w, Transaction tx, Coin prevBalance, Coin newBalance) {
System.out.println("[main]: COINS RECIEVED!");
System.out.println("\nReceived tx " + tx.getHashAsString());
System.out.println(tx.toString());
}
});
System.out.println("\nDone!\n");
System.out.println(wallet.toString());
Run Code Online (Sandbox Code Playgroud)
我有一种感觉,我没有正确处理 AbstractWalletEventListener。当我向该地址汇款时,我没有收到预期在控制台中看到的文本。相反,我只是从peerGroup.startAsync()方法的[NioClientManager]中看到“对等宣布的新交易”的连续流。
我做错了什么以及如何纠正?我在看似简单的任务上花费了比应有的时间更多的时间。
附言。我调用的“loadFromFile”文件只是一个由bitcoinj 生成的空白默认钱包文件。没什么特别的。
编辑:另外,我不想看到钱包的总余额。我只想知道新交易何时进入。旧交易在我的程序中无关紧要。
我终于弄明白了。花了我足够长的时间。我决定只使用钱包应用程序套件,而不是手动执行此操作。这是我想做的事情的最终代码(删除了公钥和文件)。
final NetworkParameters params = MainNetParams.get();
try{
//initialize files and stuff here
WalletAppKit kit = new WalletAppKit(params, wakfile, "_wak");
kit.setAutoSave(true);
kit.connectToLocalHost();
kit.startAsync();
kit.awaitRunning();
kit.peerGroup().addPeerDiscovery(new DnsDiscovery(params));
kit.wallet().addWatchedAddress(new Address(params, "1NxxxxxxxxxxxxxxxxC4"));
kit.wallet().addEventListener(new AbstractWalletEventListener() {
@Override
public synchronized void onCoinsReceived(Wallet w, Transaction tx, Coin prevBalance, Coin newBalance) {
System.out.println("[main]: COINS RECIEVED!");
System.out.println("\nReceived tx " + tx.getHashAsString());
System.out.println(tx.toString());
}
});
} catch (IOException e) {
e.printStackTrace();
} catch (AddressFormatException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
为什么这有效而我发布的内容无效,我仍然不完全确定。我肯定错过了什么。如果你看到这篇文章并知道我在上面做错了什么;请告诉我。对以后的参考还是很有用的。
| 归档时间: |
|
| 查看次数: |
2462 次 |
| 最近记录: |