I’m trying to follow the steps here https://en.bitcoin.it/wiki/Bech32 to generate a valid bech32 address. I am getting stuck on the first step:
- Having a compressed public key (0x02 or 0x03 followed by 32 byte X coordinate): 0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798
- Perform SHA-256 hashing on the public key: 0f715baf5d4c2ed329785cef29e562f73488c8a2bb9dbc5700b361d54b9b0554
Here is one of the things I tried:
>>> import hashlib >>> m = hashlib.sha256() >>> m.update('0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798') >>> m.hexdigest() 'd13c888cfd35d6ab67dc3f67edcc401833e6ae4eec20b254b1981b187946ed91'
Note:
- I’m limited to python 2.7.18
- I’m making these addresses for testing purposes, they are not needed for real use but should be valid
- If you know how to do steps 3+, please share them as well :)
- There is a putative reference implementation of this here: https://github.com/fiatjaf/bech32/blob/master/bech32/__init__.py, but I can’t make heads or tails of it… it seems to be completely different from the process described.
Advertisement
Answer
It seems that you’re hashing the string representation of the binary, instead of binary stream itself. Not sure what’s the most pythonic way to do that in Python 2.7, but you’d get what you need with something like the following:
import hashlib str_of_key = '0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798' hashlib.new('sha256', str_of_key.decode('hex')).hexdigest()
For the reference, related question about .decode('hex')
:
https://stackoverflow.com/a/5682984/1150918