How do I concatenate two hashes in Python?

2

Concatenating and double SHA-256 hashing

"a751efbeabe73bdf9d08df5760104feff915d9d807d4c62178cdeb98d8c25f43"

with itself

"a751efbeabe73bdf9d08df5760104feff915d9d807d4c62178cdeb98d8c25f43"

should output 15eca0aa3e2cc2b9b4fbe0629f1dda87f329500fcdcd6ef546d163211266b3b3

import hashlib header_hex = "a751efbeabe73bdf9d08df5760104feff915d9d807d4c62178cdeb98d8c25f43a751efbeabe73bdf9d08df5760104feff915d9d807d4c62178cdeb98d8c25f43"

header_bin = header_hex.decode('hex')

hash = hashlib.sha256(hashlib.sha256(header_bin).digest()).digest()

hash.encode('hex_codec') '2b4a9fdb97e89e73c4647791e476090eaad04f43c93a3de21a95d2c4fc8e8e0c'

I'm getting the wrong answer :/?

Ben Stolman

Posted 2018-07-08T01:13:11.367

Reputation: 55

Your code looks correct. Where do you read that the double-SHA256 hash of a751... input concatenated with itself should have 15eca... as output?Pieter Wuille 2018-07-08T01:20:30.870

https://bitcointalk.org/index.php?topic=44707.msg534605#msg534605 the bottom of the last pageBen Stolman 2018-07-08T01:29:17.993

https://www.blockchain.com/en/btc/block-index/120872 the Merkle Root in the example on the forum is the same as the one on Blockchain.infoBen Stolman 2018-07-08T01:35:20.987

Block hashes are often displayed in byte-reversed order. Try reversing the bytes before hashing, and again on the computed hash.Pieter Wuille 2018-07-08T01:37:36.267

>>> import hashlib >>> header_hex = "435fc2d898ebcd7821c6d407d8d915f9ef4f106057df089ddf3be7abbeef51a7435fc2d898ebcd7821c6d407d8d915f9ef4f106057df089ddf3be7abbeef51a7" >>> header_bin = header_hex.decode('hex') >>> hash = hashlib.sha256(hashlib.sha256(header_bin).digest()).digest() >>> hash.encode('hex_codec') 'b3b366122163d146f56ecdcd0f5029f387da1d9f62e0fbb4b9c22c3eaaa0ec15' >>> hash[::-1].encode('hex_codec') '15eca0aa3e2cc2b9b4fbe0629f1dda87f329500fcdcd6ef546d163211266b3b3' YIPEE THANK YOU PIETER!Ben Stolman 2018-07-08T01:46:26.633

Don't forget to write an answer yourself if you fixed the issue.Pieter Wuille 2018-07-08T03:28:24.127

Answers

2

You have to byte-swap the hex values BEFORE concatenating them. You also have to byte-swap the double hashed hex string!

import hashlib header_hex = "435fc2d898ebcd7821c6d407d8d915f9ef4f106057df089ddf3be7abbeef51a7435fc2d898ebcd7821c6d407d8d915f9ef4f106057df089ddf3be7abbeef51a7"

header_bin = header_hex.decode('hex') hash = hashlib.sha256(hashlib.sha256(header_bin).digest()).digest() hash.encode('hex_codec') 'b3b366122163d146f56ecdcd0f5029f387da1d9f62e0fbb4b9c22c3eaaa0ec15' >>>

hash[::-1].encode('hex_codec') '15eca0aa3e2cc2b9b4fbe0629f1dda87f329500fcdcd6ef546d163211266b3b3'

Ben Stolman

Posted 2018-07-08T01:13:11.367

Reputation: 55