-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMerkleTrees.py
66 lines (50 loc) · 2.27 KB
/
MerkleTrees.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
55
56
57
58
59
60
61
62
63
64
65
66
# coding:utf-8
import hashlib
from collections import OrderedDict
from transaction import Transaction
class MerkleTrees(object):
def __init__(self, transaction_list=None):
self.transaction_list = transaction_list
self.transactions = transaction_list
self.transaction_tree = OrderedDict()
self.create_tree()
def create_tree(self):
transaction_list = self.transaction_list
transaction_tree = self.transaction_tree
temp_transaction = []
if len(transaction_list) != 1:
# print transaction_list
for index in range(0, len(transaction_list), 2):
left_leaf = transaction_list[index]
if index + 1 != len(transaction_list):
right_leaf = transaction_list[index + 1]
else:
right_leaf = transaction_list[index]
if isinstance(left_leaf, Transaction):
left_leaf = left_leaf.txid
if isinstance(right_leaf, Transaction):
right_leaf = right_leaf.txid
left_leaf_hash = hashlib.sha256(left_leaf).hexdigest() # 左边叶子节点的哈希值
right_leaf_hash = hashlib.sha256(right_leaf).hexdigest() # 右边叶子节点的哈希值
transaction_tree[left_leaf] = left_leaf_hash
transaction_tree[right_leaf] = right_leaf_hash
temp_transaction.append(left_leaf_hash + right_leaf_hash)
self.transaction_list = temp_transaction
self.transaction_tree = transaction_tree
self.create_tree()
else:
root_leaf = transaction_list[0]
if isinstance(root_leaf, Transaction):
root_leaf = root_leaf.txid
else:
root_leaf = root_leaf
root_leaf_hash = hashlib.sha256(root_leaf.encode('utf-8')).hexdigest()
transaction_tree[root_leaf] = root_leaf_hash
self.transaction_tree = transaction_tree
def get_transaction_tree(self):
return self.transaction_tree
def get_transaction_list(self):
return self.transactions
def get_root_leaf(self):
last_key = list(self.transaction_tree.keys())[-1]
return self.transaction_tree[last_key]