forked from tonkeeper/ton-assets
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutlis.py
More file actions
46 lines (41 loc) · 1.13 KB
/
utlis.py
File metadata and controls
46 lines (41 loc) · 1.13 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
import base64
def normalize_address(a, to_raw):
if len(a) == 48:
raw = base64.urlsafe_b64decode(a)
workchain = raw[1]
if workchain == 255:
workchain = -1
addr = raw[2:34]
elif ":" in a:
parts = a.split(":")
if len(parts) != 2:
raise Exception("invalid address %s" % a)
workchain = int(parts[0])
addr = bytearray.fromhex(parts[1])
else:
raise Exception("invalid address %s" % a)
if to_raw:
return "%d:%s" % (workchain, addr.hex())
if workchain == -1:
workchain = 255
human = bytearray(36)
human[0] = 0x11
human[1] = workchain
human[2:34] = addr
human[34:] = crc16(human[:34])
return base64.urlsafe_b64encode(human).decode()
def crc16(data):
POLY = 0x1021
reg = 0
message = bytes(data) + bytes(2)
for byte in message:
mask = 0x80
while mask > 0:
reg <<= 1
if byte & mask:
reg += 1
mask >>= 1
if reg > 0xffff:
reg &= 0xffff
reg ^= POLY
return reg // 256, reg % 256