-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhelper.py
339 lines (275 loc) · 8.03 KB
/
helper.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
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
"""
Helper functions for ecc.py
"""
import hashlib
from typing import List
BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
SIGHASH_ALL = 1
TWO_WEEKS = 60 * 60 * 24 * 14
def hash256(s) -> bytes:
"""
Performs two rounds of sha256
"""
return hashlib.sha256(hashlib.sha256(s).digest()).digest()
def hash160(s) -> bytes:
"""
SHA256 followed by RIPEMD160
"""
return hashlib.new("ripemd160", hashlib.sha256(2).digest()).digest()
def encode_base58(s) -> bytes:
"""
Encodes/converts any bytes to Base58 to transmit public key
"""
count = 0
for c in s:
if c == 0:
count += 1
else:
break
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(b) -> bytes:
"""
Returns a Base58 encoding with checksum
"""
return encode_base58(b + hash256(b)[:4])
def little_endian_to_int(b) -> int:
"""
Takes a byte sequence as a little-endian number and returns an integer
"""
return int.from_bytes(b, 'little')
def int_to_little_endian(n: int, length) -> bytes:
"""
Takes an integer and returns the little-endian byte sequence
"""
return n.to_bytes(length, 'little')
def read_varint(s):
"""
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:
# oxff 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(1, 2)
elif i < 0x100000000:
return b'\xfe' + int_to_little_endian(1, 4)
elif i < 0x10000000000000000:
return b'\xff' + int_to_little_endian(1, 8)
else:
raise ValueError('integer too large: {}'.format(i))
def encode_num(num) -> bytes:
"""
Encode an integer number to bytes equivalent
"""
if num == 0:
return b''
abs_num = abs(num)
negative = num < 0
result = bytearray()
while abs_num:
result.append(abs_num & 0xff)
abs_num >>= 8
if result[-1] & 0x80:
if negative:
result.append(0x80)
else:
result.append(0)
elif negative:
result[-1] |= 0x80
return bytes(result)
def decode_num(element) -> int:
"""
Decode an integer from its byte equivalent
"""
if element == b'':
return 0
big_endian = element[::-1]
if big_endian[0] & 0x80:
negative = True
result = big_endian[0] & 0x7f
else:
negative = False
result = big_endian[0]
for c in big_endian[1:]:
result <<= 8
result += c
if negative:
return -result
else:
return result
def decode_base58(s):
"""
Decodes a base58 encoded address to extract the hash of address
"""
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(f"bad address: {checksum} {hash256(combined[:-4])[:4]}")
return combined[1:-4]
def h160_to_p2pkh_address(h160: bytes, testnet=False):
"""
Encodes a 20-byte H160 to P2PKH address
"""
if testnet:
prefix = b'\x6f'
else:
prefix = b'\x00'
return encode_base58_checksum(prefix + h160)
def h160_to_p2sh_address(h160: bytes, testnet=False):
"""
Encodes a 20-byte H160 to P2PKH address
"""
if testnet:
prefix = b'\xc4'
else:
prefix = b'\x05'
return encode_base58_checksum(prefix + h160)
def bits_to_target(bits):
"""
Turns bits into target
"""
exponent = bits[-1]
coefficient = little_endian_to_int(bits[:-1])
return coefficient * 256 ** (exponent - 3)
def target_to_bits(target: int):
"""
Turns a target integer back into bits
"""
raw_bytes = target.to_bytes(32, "big")
raw_bytes = raw_bytes.lstrip(b'\x00')
if raw_bytes[0] > 0x7f:
exponent = len(raw_bytes) + 1
coefficient = b'\x00' + raw_bytes[:2]
else:
exponent = len(raw_bytes)
coefficient = raw_bytes[:3]
new_bits = coefficient[::-1] + bytes([exponent])
return new_bits
def calculate_new_bits(previous_bits, time_differential):
"""
"""
if time_differential > TWO_WEEKS * 4:
time_differential = TWO_WEEKS * 4
if time_differential < TWO_WEEKS // 4:
time_differential = TWO_WEEKS // 4
new_target = bits_to_target(previous_bits) * time_differential // TWO_WEEKS
return target_to_bits(new_target)
def merkle_parent(hash1: bytes, hash2: bytes) -> bytes:
"""
Takes the binary hashes and calculates the hash256
"""
return hash256(hash1 + hash2)
def merkle_parent_level(hashes: List) -> List[bytes]:
"""
Takes a list of binary hashes and returns a list that is half
the length
"""
if len(hashes) == 1:
raise RuntimeError('Cannot take a parent level with only 1 item')
if len(hashes) % 2 == 1:
hashes.append(hashes[-1])
parent_level = []
for i in range(0, len(hashes), 2):
parent = merkle_parent(hashes[i], hashes[i+1])
parent_level.append(parent)
return parent_level
def merkle_root(hashes: List[bytes]) -> bytes:
"""
Takes a list of binary hashes and returns the merkle root
"""
current_level = hashes
while len(current_level) > 1:
current_level = merkle_parent_level(current_level)
return current_level[0]
def bytes_to_bit_field(some_bytes: bytes) -> List:
"""
Converts bytes to a list of bits
"""
flag_bits = []
for byte in some_bytes:
for _ in range(8):
flag_bits.append(byte & 1)
byte >>= 1
return flag_bits
def bit_field_to_bytes(bitfield: List[int]):
"""
Converts a bitfield to bytes
"""
if len(bitfield) % 8 != 0:
raise RuntimeError('bit field does not have a length that is divisible by 8')
result = bytearray(len(bitfield) // 8)
for i, bit in enumerate(bitfield):
byte_index, bit_index = divmod(i, 8)
if bit:
result[byte_index] |= 1 << bit_index
return bytes(result)
def murmur3(data, seed=0):
"""
murmur hash
http://stackoverflow.com/questions/13305290/is-there-a-pure-python-implementation-of-murmurhash
"""
c1 = 0xcc9e2d51
c2 = 0x1b873593
length = len(data)
h1 = seed
roundedEnd = (length & 0xfffffffc) # round down to 4 byte block
for i in range(0, roundedEnd, 4):
# little endian load order
k1 = (data[i] & 0xff) | ((data[i + 1] & 0xff) << 8) | \
((data[i + 2] & 0xff) << 16) | (data[i + 3] << 24)
k1 *= c1
k1 = (k1 << 15) | ((k1 & 0xffffffff) >> 17) # ROTL32(k1,15)
k1 *= c2
h1 ^= k1
h1 = (h1 << 13) | ((h1 & 0xffffffff) >> 19) # ROTL32(h1,13)
h1 = h1 * 5 + 0xe6546b64
# tail
k1 = 0
val = length & 0x03
if val == 3:
k1 = (data[roundedEnd + 2] & 0xff) << 16
# fallthrough
if val in [2, 3]:
k1 |= (data[roundedEnd + 1] & 0xff) << 8
# fallthrough
if val in [1, 2, 3]:
k1 |= data[roundedEnd] & 0xff
k1 *= c1
k1 = (k1 << 15) | ((k1 & 0xffffffff) >> 17) # ROTL32(k1,15)
k1 *= c2
h1 ^= k1
# finalization
h1 ^= length
# fmix(h1)
h1 ^= ((h1 & 0xffffffff) >> 16)
h1 *= 0x85ebca6b
h1 ^= ((h1 & 0xffffffff) >> 13)
h1 *= 0xc2b2ae35
h1 ^= ((h1 & 0xffffffff) >> 16)
return h1 & 0xffffffff