Created
January 26, 2022 22:38
-
-
Save humbdrag/dd00da59d4ccf4ee207371a73a3706ff to your computer and use it in GitHub Desktop.
Calculate merkle root for pyminer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def calc_merkle_root(transactions: List[str]) -> str: | |
# Convert transactions into big-endian bytes. | |
be_hashes = [ | |
bytes.fromhex(transaction)[::-1] | |
for transaction in transactions | |
] | |
# We combine the hashes pairwise until there is only 1 left. | |
while len(be_hashes) > 1: | |
# Duplicate the last hash if the list size is odd. | |
if len(be_hashes) % 2 != 0: | |
be_hashes.append(be_hashes[-1]) | |
# Combine the hashes pairwise. | |
for i in range(len(be_hashes) // 2): | |
concat_hash = be_hashes[i * 2] + be_hashes[i * 2 + 1] | |
be_hash = hashlib.sha256(hashlib.sha256(concat_hash).digest()).digest() | |
be_hashes[i] = be_hash | |
be_hashes = be_hashes[:len(be_hashes) // 2] | |
return be_hashes[0][::-1].hex() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment