diff --git a/src/hashtree.py b/src/hashtree.py --- a/src/hashtree.py +++ b/src/hashtree.py @@ -5,6 +5,10 @@ from datetime import datetime from util import Progress +def hashBlock(data): + return hashlib.sha256(data).digest()[-HashTree.HASH_LEN:] + + class HashTree: HASH_LEN=16 # bytes BLOCK_SIZE=4096 # bytes @@ -28,7 +32,7 @@ class HashTree: progress=Progress(leafCount) for i in range(leafCount): data=f.read(HashTree.BLOCK_SIZE) - res.insertLeaf(hashlib.sha256(data).digest()[-HashTree.HASH_LEN:]) + res.insertLeaf(hashBlock(data)) progress.p(i) progress.done() @@ -70,7 +74,7 @@ class HashTree: ## Updates the node at index and all its ancestors. def updateNode(self,index): while index>=0: - self.store[index]=hashlib.sha256(self.store[index*2+1]+self.store[index*2+2]).digest()[-HashTree.HASH_LEN:] + self.store[index]=hashBlock(self.store[index*2+1]+self.store[index*2+2]) index=(index-1)//2 ## Fast construction of the tree over the leaves. O(n). @@ -78,14 +82,6 @@ class HashTree: print(datetime.now(), "building tree:") progress=Progress(-1, self.leafStart-1) for i in range(self.leafStart-1,-1,-1): - self.store[i]=hashlib.sha256(self.store[i*2+1]+self.store[i*2+2]).digest()[-HashTree.HASH_LEN:] + self.store[i]=hashBlock(self.store[i*2+1]+self.store[i*2+2]) progress.p(i) progress.done() - - -if __name__=="__main__": - f1=HashTree.fromFile(open("serverFile.txt",mode='rb')) - f2=HashTree.fromFile(open("clientFile.txt",mode='rb')) - - for i,(h1,h2) in enumerate(zip(f1.store,f2.store)): - print("{0:2}".format(i),h1.hex(),h2.hex(),h1==h2)