Skip to content

Instantly share code, notes, and snippets.

@braydonf
Last active February 6, 2019 00:49
Show Gist options
  • Save braydonf/e9572bb40c084691fa20 to your computer and use it in GitHub Desktop.
Save braydonf/e9572bb40c084691fa20 to your computer and use it in GitHub Desktop.
Read bitcoin blocks from disk with bitcore
// updated version with bcoin at https://gist.github.com/braydonf/528a51785f0f5641464d172696cd2112
var bitcore = require('bitcore');
var fs = require('fs');
var glob = require('glob');
var async = require('async');
var Block = bitcore.Block;
glob('./blk*.dat', null, function(err, files) {
async.eachSeries(files, function(filename, next) {
console.log('Loading Block File: ' + filename);
var file = fs.readFile(filename, function(err, data) {
var blocks = [];
var byteLength = data.length / 2;
var pos = 0;
while (true) {
var magic = data.readUInt32LE(pos);
if (magic != 0xD9B4BEF9) {
throw new Error('Incorrect Magic');
}
var size = data.readUInt32LE(pos + 4);
var chunk = data.slice(pos, 8 + pos + size);
var block = Block.fromRawBlock(chunk);
console.log('File: ' + filename + ' Block: ' + block.hash);
blocks.push(block);
pos += 8 + size;
if (pos > byteLength) {
break;
}
}
next();
});
}, function(err) {
if (err) {
throw err;
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment