如何使用bitcoinj接收有关新块的通知

时间:2017-12-08 22:16:23

标签: bitcoinj

我正在尝试接收有关比特币区块链中块的通知。我正在使用这段代码,但是从2010年左右开始打印数百个块。

import org.bitcoinj.core.*;
import org.bitcoinj.net.discovery.DnsDiscovery;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.store.BlockStore;
import org.bitcoinj.store.MemoryBlockStore;


public class BlockChainMonitorTest {


    BlockChainMonitorTest() throws Exception {

        NetworkParameters params = MainNetParams.get();

        BlockStore bs = new MemoryBlockStore(params);
        BlockChain bc = new BlockChain(params, bs);

        PeerGroup peerGroup = new PeerGroup(params, bc);
        peerGroup.setUserAgent("PeerMonitor", "1.0");
        peerGroup.setMaxConnections(4);
        peerGroup.addPeerDiscovery(new DnsDiscovery(params));

        bc.addNewBestBlockListener((StoredBlock block) -> {
            System.out.println("addNewBestBlockListener");
            System.out.println(block);
        });

        //peerGroup.setFastCatchupTimeSecs(1483228800); // 2017-01-01

        peerGroup.start();
        peerGroup.waitForPeers(4).get();
        Thread.sleep(1000 * 60 * 30);
        peerGroup.stop();

    }

    public static void main(String[] args) throws Exception {
        new BlockChainMonitorTest();
    }
}

我想只听新块。任何想法?
我试过了setFastCatchupTimeSecs但是我似乎没有收到任何事件。

2 个答案:

答案 0 :(得分:0)

How about you use a collection to store the blocks already found and check if the block is already there and only execute the System.out.println call if it is not.

 echo '/gateway/success';

答案 1 :(得分:0)

所以我进入了源代码,显然接收块通知而不必下载完整的区块链的唯一方法是修改bitcoinj源代码。

在第352行的AbstractBlockChain.java中:

将方法public boolean add(Block block)的正文替换为:

informListenersForNewBlock(block, NewBlockType.BEST_CHAIN, null, null, new StoredBlock(block, BigInteger.ZERO, 0));
return true;