-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtraverse_block_indexes.py
54 lines (42 loc) · 2.22 KB
/
traverse_block_indexes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from block_parser import getBlock
from leveldb_parser import getBlockIndex, getRecentBlockHash
import os
import mmap
import binascii
import json
from utility_adapters.graph_adapter import GraphAdapter
import argparse
host = "localhost"
port = 7687
user = "neo4j"
password = "test"
snap_bitcoin_path = os.path.join(os.getenv('HOME'), 'snap', 'bitcoin-core', 'common')
bitcoin_path = os.path.join(snap_bitcoin_path, '.bitcoin')
blocks_path = os.path.join(bitcoin_path, 'blocks')
graph_adapter = GraphAdapter(host=host, port=port, user=user, password=password)
def traverse_blockchain_in_reverse(block_count: int):
global graph_adapter
prev_block_hash_bigendian_b = getRecentBlockHash()
# print('next block hash = %s' % bytes.decode(binascii.hexlify(next_block_hash_bigendian_b[::-1])))
for _ in range(block_count):
jsonobj = getBlockIndex(prev_block_hash_bigendian_b)
if 'data_pos' in jsonobj:
block_filepath = os.path.join(blocks_path, 'blk%05d.dat' % jsonobj['n_file'])
start = jsonobj['data_pos']
print('height = %d' % jsonobj['height'])
elif 'undo_pos' in jsonobj:
block_filepath = os.path.join(blocks_path, 'rev%05d.dat' % jsonobj['n_file'])
start = jsonobj['undo_pos']
with open(block_filepath, 'rb') as block_file:
# load file to memory
mptr = mmap.mmap(block_file.fileno(), 0, prot=mmap.PROT_READ) #File is open read-only
prev_block_hash_bigendian_b, block = getBlock(mptr, start)
graph_adapter.createTxnGraph(block)
if jsonobj['height'] == 1:
break
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Process Blocks in reverse to generate graph of given number of blocks')
parser.add_argument("-c", "--block_count", type=int, default=5, help="Retrieve recent number of blocks. Default: 5")
args = parser.parse_args()
print('block_count = %d' % args.block_count)
traverse_blockchain_in_reverse(args.block_count)