-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelper.py
More file actions
97 lines (74 loc) · 2.4 KB
/
helper.py
File metadata and controls
97 lines (74 loc) · 2.4 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
from unittest import TestCase, TestSuite, TextTestRunner
import hashlib
# tag::source1[]
BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
# end::source1[]
def run(test):
suite = TestSuite()
suite.addTest(test)
TextTestRunner().run(suite)
# tag::source4[]
def hash160(s):
'''sha256 followed by ripemd160'''
return hashlib.new('ripemd160', hashlib.sha256(s).digest()).digest() # <1>
# end::source4[]
def hash256(s):
'''two rounds of sha256'''
return hashlib.sha256(hashlib.sha256(s).digest()).digest()
# tag::source2[]
def encode_base58(s):
count = 0
for c in s: # <1>
if c == 0:
count += 1
else:
break
num = int.from_bytes(s, 'big')
prefix = '1' * count
result = ''
while num > 0: # <2>
num, mod = divmod(num, 58)
result = BASE58_ALPHABET[mod] + result
return prefix + result # <3>
# end::source2[]
# tag::source3[]
def encode_base58_checksum(b):
return encode_base58(b + hash256(b)[:4])
# end::source3[]
def decode_base58(s):
num = 0
for c in s:
num *= 58
num += BASE58_ALPHABET.index(c)
combined = num.to_bytes(25, byteorder='big')
checksum = combined[-4:]
if hash256(combined[:-4])[:4] != checksum:
raise ValueError('bad address: {} {}'.format(checksum, hash256(combined[:-4])[:4]))
return combined[1:-4]
def little_endian_to_int(b):
'''little_endian_to_int takes byte sequence as a little-endian number.
Returns an integer'''
# use int.from_bytes()
num = int.from_bytes(b, 'little')
return num
def int_to_little_endian(n, length):
'''endian_to_little_endian takes an integer and returns the little-endian
byte sequence of length'''
# use n.to_bytes()
num = n.to_bytes(length, 'little')
return num
class HelperTest(TestCase):
def test_little_endian_to_int(self):
h = bytes.fromhex('99c3980000000000')
want = 10011545
self.assertEqual(little_endian_to_int(h), want)
h = bytes.fromhex('a135ef0100000000')
want = 32454049
self.assertEqual(little_endian_to_int(h), want)
def test_int_to_little_endian(self):
n = 1
want = b'\x01\x00\x00\x00'
self.assertEqual(int_to_little_endian(n, 4), want)
n = 10011545
want = b'\x99\xc3\x98\x00\x00\x00\x00\x00'
self.assertEqual(int_to_little_endian(n, 8), want)