Search code examples
bitcoinbitcoindbitcoinj

Is there a way to get block through the block number(height) using bitcoinj?


I looked up the api document, and I can only find a way to get the block by a block hash.

Is there a way to get block through the block number(height) using bitcoinj?


Solution

  • The block height (number) is not recorded on each blockchain node. bitcoinj is not meant to be a full-node, so I think they seems not to provide an API or function to get a block by height.

    However, if you want the height by bitconj anyway, you can firstly download and install BitCoin Core and wait for all blocks in the blockchain downloaded, then iterate the block files(blk00001.dat, blk00002.dat, ... blkxxxxx.dat) that Bitcoin Core save their blocks (defaults in ~/.bitcoin/blocks/) by the BlockFileLoader class that bitcoinj provided.

    As I have tested, the iteration process by BlockFileLoader is disk-and-time- consuming, and you should ensure the block in proper order in the blockchain, so I suggest to reserve blockchain with the height information to some better index storage or devices, such as MySQL or MongoDB.