SHA-256 Merkle tree: Difference between revisions

→‎{{header|Python}}: Add implementation.
(→‎{{header|Python}}: Add implementation.)
Line 113:
a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c
</pre>
 
=={{header|Python}}==
This version attempts to combine blocks as soon as possible to minimize the memory footprint.
 
<lang Python>#!/usr/bin/env python
import argh, hashlib, sys
 
@argh.arg('filename', nargs='?', default=None)
def main(filename, block_size=1024*1024, ):
if filename:
fin = open(filename, 'rb')
else:
fin = sys.stdin
 
stack = [ ]
block = fin.read(block_size)
while block:
# a node is a pair: (tree-level, hash)
node = ( 0, hashlib.sha256(block).digest() )
stack.append(node)
 
# concatenate adjacent pairs at the same level
while len(stack) >= 2 and stack[-2][0] == stack[-1][0]:
a = stack[-2]
b = stack[-1]
l = a[0]
stack[-2:] = [ (l+1, hashlib.sha256(a[1] + b[1]).digest()) ]
 
block = fin.read(block_size)
 
# at the end we have to concatenate across levels
while len(stack) > 1:
a = stack[-2]
b = stack[-1]
al = a[0]
bl = b[0]
stack[-2:] = [ (max(al,bl)+1, hashlib.sha256(a[1] + b[1]).digest()) ]
 
print(stack[0][1].hex())
 
argh.dispatch_command(main)</lang>
 
{{Out}}
<pre>$ sha256tree.py -b=1024 title.png
a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c</pre>
 
=={{header|Raku}}==
1,480

edits