forked from jimmysong/programmingbitcoin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelper.py
More file actions
220 lines (179 loc) · 7.11 KB
/
helper.py
File metadata and controls
220 lines (179 loc) · 7.11 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
from unittest import TestCase, TestSuite, TextTestRunner
import hashlib
SIGHASH_ALL = 1
SIGHASH_NONE = 2
SIGHASH_SINGLE = 3
BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
TWO_WEEKS = 60 * 60 * 24 * 14
MAX_TARGET = 0xffff * 256**(0x1d - 3)
def run(test):
suite = TestSuite()
suite.addTest(test)
TextTestRunner().run(suite)
def hash160(s):
'''sha256 followed by ripemd160'''
return hashlib.new('ripemd160', hashlib.sha256(s).digest()).digest()
def hash256(s):
'''two rounds of sha256'''
return hashlib.sha256(hashlib.sha256(s).digest()).digest()
def encode_base58(s):
# determine how many 0 bytes (b'\x00') s starts with
count = 0
for c in s:
if c == 0:
count += 1
else:
break
# convert to big endian integer
num = int.from_bytes(s, 'big')
prefix = '1' * count
result = ''
while num > 0:
num, mod = divmod(num, 58)
result = BASE58_ALPHABET[mod] + result
return prefix + result
def encode_base58_checksum(s):
return encode_base58(s + hash256(s)[:4])
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'''
return int.from_bytes(b, 'little')
def int_to_little_endian(n, length):
'''endian_to_little_endian takes an integer and returns the little-endian
byte sequence of length'''
return n.to_bytes(length, 'little')
def read_varint(s):
'''read_varint reads a variable integer from a stream'''
i = s.read(1)[0]
if i == 0xfd:
# 0xfd means the next two bytes are the number
return little_endian_to_int(s.read(2))
elif i == 0xfe:
# 0xfe means the next four bytes are the number
return little_endian_to_int(s.read(4))
elif i == 0xff:
# 0xff means the next eight bytes are the number
return little_endian_to_int(s.read(8))
else:
# anything else is just the integer
return i
def encode_varint(i):
'''encodes an integer as a varint'''
if i < 0xfd:
return bytes([i])
elif i < 0x10000:
return b'\xfd' + int_to_little_endian(i, 2)
elif i < 0x100000000:
return b'\xfe' + int_to_little_endian(i, 4)
elif i < 0x10000000000000000:
return b'\xff' + int_to_little_endian(i, 8)
else:
raise ValueError('integer too large: {}'.format(i))
def h160_to_p2pkh_address(h160, testnet=False):
'''Takes a byte sequence hash160 and returns a p2pkh address string'''
# p2pkh has a prefix of b'\x00' for mainnet, b'\x6f' for testnet
if testnet:
prefix = b'\x6f'
else:
prefix = b'\x00'
return encode_base58_checksum(prefix + h160)
def h160_to_p2sh_address(h160, testnet=False):
'''Takes a byte sequence hash160 and returns a p2sh address string'''
# p2sh has a prefix of b'\x05' for mainnet, b'\xc4' for testnet
if testnet:
prefix = b'\xc4'
else:
prefix = b'\x05'
return encode_base58_checksum(prefix + h160)
def bits_to_target(bits):
'''Turns bits into a target (large 256-bit integer)'''
# last byte is exponent
exponent = bits[-1]
# the first three bytes are the coefficient in little endian
coefficient = little_endian_to_int(bits[:-1])
# the formula is:
# coefficient * 256**(exponent-3)
return coefficient * 256**(exponent - 3)
def target_to_bits(target):
'''Turns a target integer back into bits, which is 4 bytes'''
raw_bytes = target.to_bytes(32, 'big')
# get rid of leading 0's
raw_bytes = raw_bytes.lstrip(b'\x00')
if raw_bytes[0] > 0x7f:
# if the first bit is 1, we have to start with 00
exponent = len(raw_bytes) + 1
coefficient = b'\x00' + raw_bytes[:2]
else:
# otherwise, we can show the first 3 bytes
# exponent is the number of digits in base-256
exponent = len(raw_bytes)
# coefficient is the first 3 digits of the base-256 number
coefficient = raw_bytes[:3]
# we've truncated the number after the first 3 digits of base-256
new_bits = coefficient[::-1] + bytes([exponent])
return new_bits
def calculate_new_bits(previous_bits, time_differential):
'''Calculates the new bits given
a 2016-block time differential and the previous bits'''
# if the time differential is greater than 8 weeks, set to 8 weeks
if time_differential > TWO_WEEKS * 4:
time_differential = TWO_WEEKS * 4
# if the time differential is less than half a week, set to half a week
if time_differential < TWO_WEEKS // 4:
time_differential = TWO_WEEKS // 4
# the new target is the previous target * time differential / two weeks
new_target = bits_to_target(previous_bits) * time_differential // TWO_WEEKS
# if the new target is bigger than MAX_TARGET, set to MAX_TARGET
if new_target > MAX_TARGET:
new_target = MAX_TARGET
# convert the new target to bits
return target_to_bits(new_target)
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)
def test_base58(self):
addr = 'mnrVtF8DWjMu839VW3rBfgYaAfKk8983Xf'
h160 = decode_base58(addr).hex()
want = '507b27411ccf7f16f10297de6cef3f291623eddf'
self.assertEqual(h160, want)
got = encode_base58_checksum(b'\x6f' + bytes.fromhex(h160))
self.assertEqual(got, addr)
def test_p2pkh_address(self):
h160 = bytes.fromhex('74d691da1574e6b3c192ecfb52cc8984ee7b6c56')
want = '1BenRpVUFK65JFWcQSuHnJKzc4M8ZP8Eqa'
self.assertEqual(h160_to_p2pkh_address(h160, testnet=False), want)
want = 'mrAjisaT4LXL5MzE81sfcDYKU3wqWSvf9q'
self.assertEqual(h160_to_p2pkh_address(h160, testnet=True), want)
def test_p2sh_address(self):
h160 = bytes.fromhex('74d691da1574e6b3c192ecfb52cc8984ee7b6c56')
want = '3CLoMMyuoDQTPRD3XYZtCvgvkadrAdvdXh'
self.assertEqual(h160_to_p2sh_address(h160, testnet=False), want)
want = '2N3u1R6uwQfuobCqbCgBkpsgBxvr1tZpe7B'
self.assertEqual(h160_to_p2sh_address(h160, testnet=True), want)
def test_calculate_new_bits(self):
prev_bits = bytes.fromhex('54d80118')
time_differential = 302400
want = bytes.fromhex('00157617')
self.assertEqual(calculate_new_bits(prev_bits, time_differential), want)