| •1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
from hashlib import sha256 |
| 8 |
|
| 9 |
__base58_alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' |
| 10 |
__base58_alphabet_bytes = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' |
| 11 |
__base58_radix = len(__base58_alphabet) |
| 12 |
|
| 13 |
|
| 14 |
def __string_to_int(data): |
| 15 |
"Convert string of bytes Python integer, MSB" |
| 16 |
val = 0 |
| 17 |
|
| 18 |
|
| 19 |
if type(data) == str: |
| 20 |
data = bytearray(data) |
| 21 |
|
| 22 |
for (i, c) in enumerate(data[::-1]): |
| 23 |
val += (256**i)*c |
| 24 |
return val |
| 25 |
|
| 26 |
|
| 27 |
def encode(data): |
| 28 |
"Encode bytes into Bitcoin base58 string" |
| 29 |
enc = '' |
| 30 |
val = __string_to_int(data) |
| 31 |
while val >= __base58_radix: |
| 32 |
val, mod = divmod(val, __base58_radix) |
| 33 |
enc = __base58_alphabet[mod] + enc |
| 34 |
if val: |
| 35 |
enc = __base58_alphabet[val] + enc |
| 36 |
|
| 37 |
|
| 38 |
n = len(data)-len(data.lstrip(b'\0')) |
| 39 |
return __base58_alphabet[0]*n + enc |
| 40 |
|
| 41 |
|
| 42 |
def check_encode(raw): |
| 43 |
"Encode raw bytes into Bitcoin base58 string with checksum" |
| 44 |
chk = sha256(sha256(raw).digest()).digest()[:4] |
| 45 |
return encode(raw+chk) |
| 46 |
|
| 47 |
|
| 48 |
def decode(data): |
| 49 |
"Decode Bitcoin base58 format string to bytes" |
| 50 |
|
| 51 |
if bytes != str: |
| 52 |
data = bytes(data, 'ascii') |
| 53 |
|
| 54 |
val = 0 |
| 55 |
for (i, c) in enumerate(data[::-1]): |
| 56 |
val += __base58_alphabet_bytes.find(c) * (__base58_radix**i) |
| 57 |
|
| 58 |
dec = bytearray() |
| 59 |
while val >= 256: |
| 60 |
val, mod = divmod(val, 256) |
| 61 |
dec.append(mod) |
| 62 |
if val: |
| 63 |
dec.append(val) |
| 64 |
|
| 65 |
return bytes(dec[::-1]) |
| 66 |
|
| 67 |
|
| 68 |
def check_decode(enc): |
| 69 |
"Decode bytes from Bitcoin base58 string and test checksum" |
| 70 |
dec = decode(enc) |
| 71 |
raw, chk = dec[:-4], dec[-4:] |
| 72 |
if chk != sha256(sha256(raw).digest()).digest()[:4]: |
| 73 |
raise ValueError("base58 decoding checksum error") |
| 74 |
else: |
| 75 |
return raw |
| 76 |
|
| 77 |
|
| 78 |
if __name__ == '__main__': |
| 79 |
assert(__base58_radix == 58) |
| 80 |
data = b'now is the time for all good men to come to the aid of their country' |
| 81 |
enc = check_encode(data) |
| 82 |
assert(check_decode(enc) == data) |