1+ import os
2+ import struct
3+ import sys
4+
5+ root_path = os .path .abspath (os .path .join (os .path .dirname (__file__ ), '..' ))
6+ if root_path not in sys .path :
7+ sys .path .append (root_path )
8+
9+ from bitcoinutils .block import Block
10+ from bitcoinutils .constants import BLOCK_MAGIC_NUMBER
11+
12+ def main ():
13+ filename = '' # Give .dat file path to run example
14+ try :
15+ with open (filename , 'rb' ) as file :
16+ while True :
17+ # Read the magic number and block size (first 8 bytes: 4 bytes magic, 4 bytes size)
18+ preamble = file .read (8 )
19+ if len (preamble ) < 8 :
20+ # If less than 8 bytes were read, it's the end of the file
21+ break
22+
23+ # Unpack the header to get magic number and size
24+ magic , size = struct .unpack ('<4sI' , preamble )
25+ magic_hex = magic .hex ()
26+
27+ if magic_hex not in BLOCK_MAGIC_NUMBER :
28+ raise ValueError (f"Unknown or unsupported network magic number: { magic_hex } " )
29+
30+ print ("Network:" , BLOCK_MAGIC_NUMBER [magic_hex ])
31+
32+ # Read the block data based on the size specified
33+ block_data = file .read (size )
34+ 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." )
37+ break
38+
39+ # Concatenate the header and block data to parse it as a raw block
40+ raw_block = preamble + block_data
41+
42+ # Use the from_raw method of the Block class to parse the block
43+ block = Block .from_raw (raw_block )
44+
45+ # Output some information about the block (example: hash, number of transactions)
46+ print ("Block Hash:" , block .get_block_header ().get_block_hash ())
47+ print ("Number of Transactions:" , block .get_transactions_count ())
48+
49+ except FileNotFoundError :
50+ print (f"Error: The file '{ filename } ' does not exist." )
51+ except Exception as e :
52+ print (f"An unexpected error occurred: { e } " )
53+
54+ if __name__ == '__main__' :
55+ main ()
0 commit comments