import hashlib # Hash pairs of items recursively until a single value is obtained def merkle(hashList): if len(hashList) == 1: return hashList[0] newHashList = [] # Process pairs. For odd length, the last is skipped for i in range(0, len(hashList)-1, 2): newHashList.append(hash2(hashList[i], hashList[i+1])) if len(hashList) % 2 == 1: # odd, hash last item twice newHashList.append(hash2(hashList[-1], hashList[-1])) return merkle(newHashList) def hash2(a, b): # Reverse inputs before and after hashing # due to big-endian / little-endian nonsense a1 = a.decode('hex') a11 = a1[::-1] # print a11.encode('hex') b1 = b.decode('hex')[::-1] #print b1.encode('hex') concat = a11+b1 #print concat.encode('hex') concat2 = hashlib.sha256(concat).digest() print "hash1:" + concat2.encode('hex') h = hashlib.sha256(concat2).digest() print "hash2:" + h[::-1].encode('hex') print '' return h[::-1].encode('hex') # https://blockexplorer.com/rawblock/000000000000030de89e7729d5785c4730839b6e16ea9fb686a54818d3860a8d txHashes = [ "338bbd00b893c384eb2b11e70f3875447297c5f20815499e787867df4538e48d", "1ad1138c6064dd17d0a4d12016d629c18f15fc9d1472412945f9c91a696689c7", "c77834d14d66729014b06fcf45c5f82af4bdd9d816e787f01bfa525cfa147014", "bb3d83398d7517fe643b2421d795e73c342b6a478ef53acdaab35dbdffbbcdb5", "38d563caf0e9ed103515cab09e40e49da0ccb8c0765ce304f9556e5bc62e8ff5", "8fc0507359d0122fa14b5887034d857bd69c8bc0e74c8dd428c2fc098595c285", "9db9fe6d011c1c7e997418aeec78ccb659648cfc915b2ff1154cabb41359ac70", "3c72fdb7e38e4437faa9e5789df6b51505de014b062361ef47578244d5025628" ] print merkle(txHashes)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question