1# Copyright (c) 2017 Pieter Wuille 2# 3# Permission is hereby granted, free of charge, to any person obtaining a copy 4# of this software and associated documentation files (the "Software"), to deal 5# in the Software without restriction, including without limitation the rights 6# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7# copies of the Software, and to permit persons to whom the Software is 8# furnished to do so, subject to the following conditions: 9# 10# The above copyright notice and this permission notice shall be included in 11# all copies or substantial portions of the Software. 12# 13# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19# THE SOFTWARE. 20 21"""Reference implementation for Bech32 and segwit addresses.""" 22 23 24CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l" 25 26 27def bech32_polymod(values): 28 """Internal function that computes the Bech32 checksum.""" 29 generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3] 30 chk = 1 31 for value in values: 32 top = chk >> 25 33 chk = (chk & 0x1ffffff) << 5 ^ value 34 for i in range(5): 35 chk ^= generator[i] if ((top >> i) & 1) else 0 36 return chk 37 38 39def bech32_hrp_expand(hrp): 40 """Expand the HRP into values for checksum computation.""" 41 return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp] 42 43 44def bech32_verify_checksum(hrp, data): 45 """Verify a checksum given HRP and converted data characters.""" 46 return bech32_polymod(bech32_hrp_expand(hrp) + data) == 1 47 48 49def bech32_create_checksum(hrp, data): 50 """Compute the checksum values given HRP and data.""" 51 values = bech32_hrp_expand(hrp) + data 52 polymod = bech32_polymod(values + [0, 0, 0, 0, 0, 0]) ^ 1 53 return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)] 54 55 56def bech32_encode(hrp, data): 57 """Compute a Bech32 string given HRP and data values.""" 58 combined = data + bech32_create_checksum(hrp, data) 59 return hrp + '1' + ''.join([CHARSET[d] for d in combined]) 60 61 62def bech32_decode(bech): 63 """Validate a Bech32 string, and determine HRP and data.""" 64 if ((any(ord(x) < 33 or ord(x) > 126 for x in bech)) or 65 (bech.lower() != bech and bech.upper() != bech)): 66 return (None, None) 67 bech = bech.lower() 68 pos = bech.rfind('1') 69 if pos < 1 or pos + 7 > len(bech) or len(bech) > 90: 70 return (None, None) 71 if not all(x in CHARSET for x in bech[pos+1:]): 72 return (None, None) 73 hrp = bech[:pos] 74 data = [CHARSET.find(x) for x in bech[pos+1:]] 75 if not bech32_verify_checksum(hrp, data): 76 return (None, None) 77 return (hrp, data[:-6]) 78 79 80def convertbits(data, frombits, tobits, pad=True): 81 """General power-of-2 base conversion.""" 82 acc = 0 83 bits = 0 84 ret = [] 85 maxv = (1 << tobits) - 1 86 max_acc = (1 << (frombits + tobits - 1)) - 1 87 for value in data: 88 if value < 0 or (value >> frombits): 89 return None 90 acc = ((acc << frombits) | value) & max_acc 91 bits += frombits 92 while bits >= tobits: 93 bits -= tobits 94 ret.append((acc >> bits) & maxv) 95 if pad: 96 if bits: 97 ret.append((acc << (tobits - bits)) & maxv) 98 elif bits >= frombits or ((acc << (tobits - bits)) & maxv): 99 return None 100 return ret 101 102 103def decode(hrp, addr): 104 """Decode a segwit address.""" 105 hrpgot, data = bech32_decode(addr) 106 if hrpgot != hrp: 107 return (None, None) 108 decoded = convertbits(data[1:], 5, 8, False) 109 if decoded is None or len(decoded) < 2 or len(decoded) > 40: 110 return (None, None) 111 if data[0] > 16: 112 return (None, None) 113 if data[0] == 0 and len(decoded) != 20 and len(decoded) != 32: 114 return (None, None) 115 return (data[0], decoded) 116 117 118def encode(hrp, witver, witprog): 119 """Encode a segwit address.""" 120 ret = bech32_encode(hrp, [witver] + convertbits(witprog, 8, 5)) 121 assert decode(hrp, ret) != (None, None) 122 return ret 123