-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase58.py
executable file
·73 lines (62 loc) · 1.67 KB
/
base58.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import hashlib
def dhash(s):
return hashlib.sha256(hashlib.sha256(s).digest()).digest()
def rhash(s):
h1 = hashlib.new('ripemd160')
h1.update(hashlib.sha256(s).digest())
return h1.digest()
b58_digits = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
def base58_encode(n):
l = []
while n > 0:
n, r = divmod(n, 58)
l.insert(0,(b58_digits[r]))
return ''.join(l)
def base58_decode(s):
n = 0
for ch in s:
n *= 58
digit = b58_digits.index(ch)
n += digit
return n
def base58_encode_padded(s):
res = base58_encode(int('0x' + s.encode('hex'), 16))
pad = 0
for c in s:
if c == chr(0):
pad += 1
else:
break
return b58_digits[0] * pad + res
def base58_decode_padded(s):
pad = 0
for c in s:
if c == b58_digits[0]:
pad += 1
else:
break
h = '%x' % base58_decode(s)
if len(h) % 2:
h = '0' + h
res = h.decode('hex')
return chr(0) * pad + res
def base58_check_encode(s, version=0):
vs = chr(version) + s
check = dhash(vs)[:4]
return base58_encode_padded(vs + check)
def base58_check_decode(s, version=0):
k = base58_decode_padded(s)
v0, data, check0 = k[0], k[1:-4], k[-4:]
check1 = dhash(v0 + data)[:4]
if check0 != check1:
raise BaseException('checksum error')
if version != ord(v0):
raise BaseException('version mismatch')
return data
def base58_get_version(s):
k = base58_decode_padded(s)
v0, data, check0 = k[0], k[1:-4], k[-4:]
check1 = dhash(v0 + data)[:4]
if check0 != check1:
return None
return ord(v0)