I am trying to write a Bitcoin address validator, and I am trying to make it work with Python 2 and 3.
import codecs
from hashlib import sha256
digits58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
def to_bytes(n, length):
s = '%x' % n
s = s.rjust(length*2, '0')
s = codecs.decode(bytes(s, 'UTF-8'), 'hex_codec')
return s
def decode_base58(bc, length):
n = 0
for char in bc:
n = n * 58 + digits58.index(char)
return to_bytes(n, length)
def check_bc(bc):
bcbytes = decode_base58(bc, 25)
return bcbytes[-4:] == sha256(sha256(bcbytes[:-4]).digest()).digest()[:4]
if __name__ == '__main__':
print(check_bc('1111111111111111111114oLvT2'))
This code should run and print True. Instead, it errors on this line in Python 2:
s = codecs.decode(bytes(s, 'UTF-8'), 'hex_codec')
Error:
TypeError: str() takes at most 1 argument (2 given)
If I remove the 'UTF-8' part, it breaks in Python 3 instead. If I remove the call to bytes altogether, it breaks in Python 3.