How can I receive notifications about new blocks using bitcoinj

507 views Asked by At

I am trying to receive notifications about new blocks in the Bitcoin blockchain. I am using this code, but this prints hundreds of blocks from 2010 or so upwards.

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

I would like to listen to new blocks only. Any ideas ?
I tried setFastCatchupTimeSecs but then I don't receive any events it seems.

2

There are 2 answers

0
Ray Hulha On BEST ANSWER

So I went into the source code and apparently the only way to receive block notifications without having to download the complete blockchain is to modify the bitcoinj source code.

In AbstractBlockChain.java around line 352:

replace the body of method public boolean add(Block block) with:

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

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.

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