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