#!/usr/bin/python3 -I
"""Independent OPG_TREE_HASH_V2, written only from docs/pilot07/TREE_HASH_V2_SPEC.md
(no OPG code imported), to cross-check OPG's implementation and its golden vectors."""
import hashlib, os, sys
def spec_v2(root):
    files = []
    for base, dirs, names in os.walk(root):
        for n in names:
            p = os.path.join(base, n)
            files.append(os.fsencode(os.path.relpath(p, root)))
    h = hashlib.sha256(b"OPG_TREE_HASH_V2\x00")
    for rel in sorted(files):                       # raw-byte sort == LC_ALL=C
        data = open(os.path.join(root, os.fsdecode(rel)), "rb").read()
        h.update(b"F\x00" + str(len(data)).encode() + b"\x00" +
                 hashlib.sha256(data).hexdigest().encode() + b"\x00" +
                 str(len(rel)).encode() + b"\x00" + rel)
    return h.hexdigest()
print(spec_v2(sys.argv[1]))
