tpy2specials.py - electrum-personal-server - Maximally lightweight electrum server for a single user
HTML git clone https://git.parazyd.org/electrum-personal-server
DIR Log
DIR Files
DIR Refs
DIR README
---
tpy2specials.py (2425B)
---
1 import sys, re
2 import binascii
3 import os
4 import hashlib
5
6 if sys.version_info.major == 2:
7 string_types = (str, unicode)
8 string_or_bytes_types = string_types
9 int_types = (int, float, long)
10
11 # Base switching
12 code_strings = {
13 2: '01',
14 10: '0123456789',
15 16: '0123456789abcdef',
16 32: 'abcdefghijklmnopqrstuvwxyz234567',
17 58: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz',
18 256: ''.join([chr(x) for x in range(256)])
19 }
20
21 def bin_dbl_sha256(s):
22 bytes_to_hash = from_string_to_bytes(s)
23 return hashlib.sha256(hashlib.sha256(bytes_to_hash).digest()).digest()
24
25 def lpad(msg, symbol, length):
26 if len(msg) >= length:
27 return msg
28 return symbol * (length - len(msg)) + msg
29
30 def get_code_string(base):
31 if base in code_strings:
32 return code_strings[base]
33 else:
34 raise ValueError("Invalid base!")
35
36 def changebase(string, frm, to, minlen=0):
37 if frm == to:
38 return lpad(string, get_code_string(frm)[0], minlen)
39 return encode(decode(string, frm), to, minlen)
40
41 def bin_to_b58check(inp, magicbyte=0):
42 inp_fmtd = chr(int(magicbyte)) + inp
43 leadingzbytes = len(re.match('^\x00*', inp_fmtd).group(0))
44 checksum = bin_dbl_sha256(inp_fmtd)[:4]
45 return '1' * leadingzbytes + changebase(inp_fmtd + checksum, 256, 58)
46
47 def bytes_to_hex_string(b):
48 return b.encode('hex')
49
50 def safe_from_hex(s):
51 return s.decode('hex')
52
53 def from_int_to_byte(a):
54 return chr(a)
55
56 def from_byte_to_int(a):
57 return ord(a)
58
59 def from_string_to_bytes(a):
60 return a
61
62 def safe_hexlify(a):
63 return binascii.hexlify(a)
64
65 def encode(val, base, minlen=0):
66 base, minlen = int(base), int(minlen)
67 code_string = get_code_string(base)
68 result = ""
69 while val > 0:
70 result = code_string[val % base] + result
71 val //= base
72 return code_string[0] * max(minlen - len(result), 0) + result
73
74 def decode(string, base):
75 base = int(base)
76 code_string = get_code_string(base)
77 result = 0
78 if base == 16:
79 string = string.lower()
80 while len(string) > 0:
81 result *= base
82 result += code_string.find(string[0])
83 string = string[1:]
84 return result
85