Python中的可变哈希

时间:2018-07-28 08:08:39

标签: python hash merkle-tree

我正在尝试在python中实现默克尔树。 这是我当前的代码(不完整)

代码:

from random import randint
import math
import sys


#First create a leaf node with some data
#Creates the Hash of L1
class Leaf():
    def __init__(self,x):
        self.data = x
        self.recompute()

    def write(self,new_data):
        self.data = new_data

    def recompute(self):
        self.hash = str(abs(hash(self.data)))
        return self.hash



#Node will have a left and right leaf
class Node():
    def __init__(self,left_node,right_node):
        self.hash = None
        self.left = left_node
        self.right = right_node

    def recompute(self):
        #Hash the left and right first, recursively
        #l = self.left.recompute()
        #Hash the left and right first, recursively
        #r = self.right.recompute()
        print(self.left)
        print(self.right)
        self.hash = str(abs(hash(self.left.recompute()+self.right.recompute())))
        return self.hash






#Add some data to one of the leaf node
l1 = Leaf("left")
l2 = Leaf("right")
print(l1)
print(l2)
#Generates the Hash 
#print(leaf.recompute())
node = Node(l1,l2)
print(node.recompute())

输出:

mohit@mohit-LIFEBOOK-UH552:~/Documents/python/merkeltree$ python3 main.py 
<__main__.Leaf object at 0x7fe80bc21748>
<__main__.Leaf object at 0x7fe80bc21780>
<__main__.Leaf object at 0x7fe80bc21748>
<__main__.Leaf object at 0x7fe80bc21780>
7573330512381989326
mohit@mohit-LIFEBOOK-UH552:~/Documents/python/merkeltree$ python3 main.py 
<__main__.Leaf object at 0x7f11938bf780>
<__main__.Leaf object at 0x7f11938bf7b8>
<__main__.Leaf object at 0x7f11938bf780>
<__main__.Leaf object at 0x7f11938bf7b8>
6285654789845752725

我面临的问题是在为节点生成哈希值时,每次执行代码时哈希值都在变化。从理论上讲,如果我的输入是静态的,则输出应该是相同的哈希值。

0 个答案:

没有答案