49 lines
1.0 KiB
Python
49 lines
1.0 KiB
Python
# base58
|
|
from hashlib import sha256
|
|
|
|
from util import *
|
|
|
|
B58_STR = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
|
|
|
|
# encode int as base58 string
|
|
def encodeInt( i ):
|
|
outstr = ''
|
|
while i > 0:
|
|
outstr += B58_STR[i % 58]
|
|
i = i // 58
|
|
return outstr[::-1]
|
|
|
|
# return base58 encoding of version + payload + checksum bytes, leading zeros are removed and
|
|
# reinserted as leading 1's in the final output
|
|
def encodeCheck( ver, payload ):
|
|
bs = ver + payload
|
|
cksha = sha256( sha256( bs ).digest() ).digest()
|
|
bs = bs + cksha[:4]
|
|
|
|
# strip and count leading zeros
|
|
lzc = 0
|
|
while bs[0] == 0: bs = bs[1:]; lzc += 1
|
|
|
|
b58str = encodeInt( int( bs.hex(), 16 ) )
|
|
|
|
# reinsert leading 1's
|
|
for z in range( lzc ): b58str = '1' + b58str
|
|
|
|
return b58str
|
|
|
|
# decode base58Check string to bytes
|
|
def decodeCheck( bstr ):
|
|
lzc = 0
|
|
while bstr[0] == '1': bstr = bstr[1:]; lzc += 1
|
|
|
|
outi = 0
|
|
for c in bstr:
|
|
outi = outi * 58 + B58_STR.index( c )
|
|
|
|
outb = intBytes( outi )
|
|
|
|
for z in range( lzc ): outb = (b'\x00' + outb)
|
|
|
|
return outb
|
|
|