2

I'm working on some code that reads the DAT files in the Blockchain, and I was trying to use bitcoinj because it seemed fairly straightforward. However, I can't seem to get it to actually read the blocks within the DAT file. I've tried many different versions and have made no significant progress.

I'm feeling like this should be fairly straightforward, and I'm just missing something simple here. To be clear, I'm not trying to write to the Blockchain, just read the DAT files.
Thanks!

Here is a code snippet.

NetworkParameters np = new MainNetParams();
Context c = new Context( np );
Context.getOrCreate(MainNetParams.get());
List<File> blockChainFiles = new ArrayList<>();
blockChainFiles.add( new File( "blk00000.dat" ) );
BlockFileLoader bfl = new BlockFileLoader(np, blockChainFiles);

int blockNum = 0;
// Iterate over the blocks in the dataset.
for (Block block : bfl) {
...

This code produces the following error:

Exception in thread "main" java.lang.IllegalStateException: Context does not match implicit network params: org.bitcoinj.params.MainNetParams@9d1d82f2 vs org.bitcoinj.params.MainNetParams@9d1d82f2
at org.bitcoinj.core.Context.getOrCreate(Context.java:147)
at testBitcoin.main(testBitcoin.java:20)
cgivre
  • 513
  • 4
  • 21

3 Answers3

0

The block .dat files contain multiple blocks in one file, including orphans, separated by magic numbers.

Please refer https://en.bitcoin.it/wiki/Protocol_documentation#Message_structure

Your code doesn't seem to be looking for magic numbers or jumping lengths as specified by message structure.

Kang
  • 545
  • 1
  • 7
  • 15
0

Just get rid of the complaining line, Context.getOrCreate(MainNetParams.get());, it's not needed.

The following slightly altered version of your code worked for me:

List<File> blockChainFiles = new ArrayList<>();
blockChainFiles.add(new File("blk00000.dat"));
MainNetParams params = MainNetParams.get();
Context context = new Context(params);
BlockFileLoader bfl = new BlockFileLoader(params, blockChainFiles);

// Iterate over the blocks in the dataset.
for (Block block : bfl) {
    System.out.println(block.getHashAsString());
}
Clay H
  • 651
  • 9
  • 21
0

You can use my blockchain parser. It writtens on Python and can parse all the data from blk*.dat files to the simple text view.

Denis Leonov
  • 171
  • 1
  • 11