bitcoinj

How can I receive notifications about new blocks using bitcoinj


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.


Solution

  • 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;