1

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.

1
  • @MarkRansom See tag wiki. Commented May 28, 2023 at 4:28

1 Answer 1

5

IIUC, instead of calling bytes, you can encode directly:

s = codecs.decode(s.encode("UTF-8"), 'hex_codec')

which gives

dsm@notebook:~/coding$ python2.7 bitcoin.py
True
dsm@notebook:~/coding$ python3.4 bitcoin.py
True
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.