Question

I'm trying to create a Bitcoin address with Python. I got the hashing part right, but I have some trouble with the Base58Check encoding. I use this package:

https://pypi.python.org/pypi/base58

Here is an example:

import base58

unencoded_string = "00010966776006953D5567439E5E39F86A0D273BEED61967F6"
encoded_string = base58.b58encode(unencoded_string)
print(encoded_string)

The output is:

bSLesHPiFV9jKNeNbUiMyZGJm45zVSB8bSdogLWCmvs88wxHjEQituLz5daEGCrHE7R7

According to the technical background for creating Bitcoin addresses the RIPEMD-160 hash above should be "16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM". That said, my output is wrong and obviously too long. Does anyone know what I did wrong?

EDIT:

I added a decoding to hex (.decode("hex")):

import base58

unencoded_string = "00010966776006953D5567439E5E39F86A0D273BEED61967F6"
encoded_string = base58.b58encode(unencoded_string.decode("hex"))
print(encoded_string)

The output looks better now:

1csU3KSAQMEYLPudM8UWJVxFfptcZSDvaYY477

Yet, it is still wrong. Does it have to be a byte encoding? How do you do that in Python?

EDIT2:

Fixed it now (thanks to Arpegius). Added str(bytearray.fromhex( hexstring )) to my code (in Python 2.7):

import base58

hexstring= "00010966776006953D5567439E5E39F86A0D273BEED61967F6"
unencoded_string = str(bytearray.fromhex( hexstring ))
encoded_string= base58.b58encode(unencoded_string)
print(encoded_string)

Output:

16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM
Was it helpful?

Solution

In base58.b58encode need a bytes (python2 str) not a hex. You need to decode it first:

In [1]: import base58
In [2]: hexstring= "00010966776006953D5567439E5E39F86A0D273BEED61967F6"
In [3]: unencoded_string = bytes.fromhex(hexstring)
In [4]: encoded_string= base58.b58encode(unencoded_string)
In [5]: print(encoded_string)
16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM

In python 2.7 you can use str(bytearray.fromhex( hexstring )).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top