How can I receive notifications of new blocks using bitcoinj

I am trying to receive notifications of new blocks in the blockchain of bitcoins. I use this code, but it has been printing hundreds of blocks since 2010 or so up.

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 only to new blocks. Any ideas?
I tried setFastCatchupTimeSecs , but then I do not receive any events.

+7
bitcoinj
source share
2 answers

So, I went into the source code and apparently the only way to get block notifications without having to download the full blockchain is to change the source code of bitcoinj.

In AbstractBlockChain.java line 352:

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

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

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

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

All Articles