comparison src/block.py @ 0:2327b9eda10f

first commit
author Dennis Concepcion Martin <dennisconcepcionmartin@gmail.com>
date Thu, 14 Oct 2021 21:42:10 +0200
parents
children 5b16e6df6a59
comparison
equal deleted inserted replaced
-1:000000000000 0:2327b9eda10f
1 import hashlib
2 from src.helpers import read_bytes
3
4
5 class Block:
6 """
7 Block structure
8 """
9
10 block_hash = None
11 magic_number = None
12 size = None
13
14 def __init__(self):
15 # Init BlockHeader class
16 self.header = self.Header()
17
18 class Header:
19 version = None
20 previous_block_hash = None
21 merkle_root = None
22 timestamp = None
23 difficult_target = None
24 nonce = None
25
26
27 def read_block(file):
28 """
29 Deserialize block
30 :param file: <class '_io.BufferedReader'>, required
31 :return:
32 """
33
34 block = Block()
35 block.magic_number = int(read_bytes(file, 4), 16)
36 block.size = int(read_bytes(file, 4), 16)
37
38 # Compute block hash
39 header_bytes = file.read(80)
40 block_hash = hashlib.sha256(header_bytes).digest()
41 block_hash = hashlib.sha256(block_hash).digest()
42
43 # Read block header
44 header = block.Header()
45 header.block_hash = block_hash[::-1].hex()
46 header.version = int.from_bytes(header_bytes[:4], 'little')
47 header.previous_block_hash = header_bytes[4:32].hex()
48