def __init__(self, block: Block, flags: bitarray): hashes = [t.hash() for t in block.transactions] tree = crypto.MerkleTree(hashes) self.flags = flags.tobytes() self.tx_count = len(hashes) self.hashes = tree.to_hash_array() self.header = block.header
def test_merkle_node_methods(self): hash1 = types.UInt256(data=binascii.unhexlify(b'aa' * 32)) hash2 = types.UInt256(data=binascii.unhexlify(b'bb' * 32)) hashes = [hash1, hash2] m = crypto.MerkleTree(hashes) self.assertEqual(True, m.root.is_root()) self.assertEqual(False, m.root.is_leaf()) self.assertEqual(False, m.root.left_child.is_root()) self.assertEqual(True, m.root.left_child.is_leaf())
def __init__(self, block: Block, flags: bitarray): super(MerkleBlockPayload, self).__init__(block.version, block.prev_hash, block.timestamp, block.index, block.next_consensus, block.witness, block.merkle_root) hashes = [block.consensus_data.hash() ] + [t.hash() for t in block.transactions] tree = crypto.MerkleTree(hashes) self.flags = flags.tobytes() self.content_count = len(hashes) self.hashes = tree.to_hash_array()
def test_to_hash_array(self): hash1 = types.UInt256(data=binascii.unhexlify(b'aa' * 32)) hash2 = types.UInt256(data=binascii.unhexlify(b'bb' * 32)) hash3 = types.UInt256(data=binascii.unhexlify(b'cc' * 32)) hash4 = types.UInt256(data=binascii.unhexlify(b'dd' * 32)) hash5 = types.UInt256(data=binascii.unhexlify(b'ee' * 32)) hashes = [hash1, hash2, hash3, hash4, hash5] m = crypto.MerkleTree(hashes) hash_array = m.to_hash_array() # sort the array hash_array = sorted(hash_array) for i, h in enumerate(hashes): self.assertEqual(h, hash_array[i])
def create(cls, block: Block, flags: bitarray) -> MerkleBlockPayload: """ Create payload. Should be used instead of directly calling the initializer. Args: block: flags: """ hashes = [block.consensus_data.hash()] + [t.hash() for t in block.transactions] tree = crypto.MerkleTree(hashes) flag_bytes = flags.tobytes() return cls(version=block.version, prev_hash=block.prev_hash, merkle_root=block.merkle_root, timestamp=block.timestamp, index=block.index, next_consensus=block.next_consensus, witness=block.witness, content_count=len(hashes), hashes=tree.to_hash_array(), flags=flag_bytes)