22import struct
33import sys
44
5+ # Dynamically add the root path to sys.path
56root_path = os .path .abspath (os .path .join (os .path .dirname (__file__ ), '..' ))
67if root_path not in sys .path :
78 sys .path .append (root_path )
1011from bitcoinutils .constants import BLOCK_MAGIC_NUMBER
1112
1213def main ():
13- filename = '' # Give .dat file path to run example
14+ if len (sys .argv ) != 2 :
15+ print ("Usage: python script.py <path_to_blkNNNNN.dat>" )
16+ return
17+
18+ filename = sys .argv [1 ]
19+
1420 try :
1521 with open (filename , 'rb' ) as file :
22+ block_height = 0
1623 while True :
17- # Read the magic number and block size (first 8 bytes: 4 bytes magic, 4 bytes size)
24+ # Read 8 bytes: 4 for magic number and 4 for block size
1825 preamble = file .read (8 )
1926 if len (preamble ) < 8 :
20- # If less than 8 bytes were read, it's the end of the file
27+ print ( "End of file reached." )
2128 break
22-
23- # Unpack the header to get magic number and size
29+
2430 magic , size = struct .unpack ('<4sI' , preamble )
2531 magic_hex = magic .hex ()
2632
2733 if magic_hex not in BLOCK_MAGIC_NUMBER :
2834 raise ValueError (f"Unknown or unsupported network magic number: { magic_hex } " )
2935
30- print ( "Network:" , BLOCK_MAGIC_NUMBER [magic_hex ])
31-
32- # Read the block data based on the size specified
36+ network = BLOCK_MAGIC_NUMBER [magic_hex ]
37+ print ( f" \n [ { network } ] Block # { block_height } " )
38+
3339 block_data = file .read (size )
3440 if len (block_data ) < size :
35- # If the block data is less than the size specified, it means the file is truncated
36- print ("Truncated block data." )
41+ print ("Warning: Truncated block data." )
3742 break
38-
39- # Concatenate the header and block data to parse it as a raw block
43+
4044 raw_block = preamble + block_data
41-
42- # Use the from_raw method of the Block class to parse the block
4345 block = Block .from_raw (raw_block )
44-
45- # Output some information about the block (example: hash, number of transactions)
46+
47+ # Output block info
4648 print ("Block Hash:" , block .get_block_header ().get_block_hash ())
47- print ("Number of Transactions:" , block .get_transactions_count ())
48-
49+ print ("Transactions:" , block .get_transactions_count ())
50+
51+ block_height += 1
52+
4953 except FileNotFoundError :
50- print (f"Error: The file '{ filename } ' does not exist ." )
54+ print (f"Error: File '{ filename } ' not found ." )
5155 except Exception as e :
52- print (f"An unexpected error occurred: { e } " )
56+ print (f"An error occurred: { e } " )
5357
5458if __name__ == '__main__' :
55- main ()
59+ main ()
0 commit comments