# -*- coding: utf-8 -*-
"""
Created on Tue Aug 29 14:42:07 2017
@author: Sean Chang
"""
import hashlib
#the node class of binary merkle hash tree
class MerkleNode(object):
def __init__(self,left=None,right=None,data=None):
self.left = left
self.right = right
#data stores the hash value
self.data = data
#build the tree recursively
def createTree(nodes):
list_len = len(nodes)
if list_len == 0:
return 0
else:
while list_len %2 != 0:
nodes.extend(nodes[-1:])
list_len = len(nodes)
secondary = []
#combine two nodes in pair
for k in [nodes[x:x+2] for x in range(0,list_len,2)]:
d1 = k[0].data.encode()
d2 = k[1].data.encode()
md5 = hashlib.md5()
md5.update(d1+d2)
newdata = md5.hexdigest()
#print("nodehash:",newdata)
node = MerkleNode(left=k[0],right=k[1],data=newdata)
secondary.append(node)
if len(secondary) == 1:
return secondary[0]
else:
return createTree(secondary)
#dfs traverse the whole tree with In-Order Traverse
def dfs(root):
if root != None:
print("data:",root.data)
dfs(root.left)
dfs(root.right)
#BFS the whole tree by using a queue
def bfs(root):
print('start bfs')
queue = []
queue.append(root)
while(len(queue)>0):
e = queue.pop(0)
print(e.data)
if e.left != None:
queue.append(e.left)
if e.right != None:
queue.append(e.right)
if __name__ == "__main__":
blocks = ['A','B','C','D','E']
nodes = []
print("leaf hash")
for e in blocks:
md5 = hashlib.md5()
md5.update(e.encode())
d=md5.hexdigest()
nodes.append(MerkleNode(data=d))
print(d)
root = createTree(nodes)
bfs(root)
Merkle Hash Binary Tree
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Given inorder and postorder traversal of a tree, construc...
- 思路1 利用map存储对应的节点, 算法2 先了解几个特性1 二叉搜索树左(右)子树的值小于等于(大于等于)...
- Given a binary tree, find its maximum depth.The maximum d...