Repository Public
1# Copyright (c) 2017, 2020 Pieter Wuille2#3# Permission is hereby granted, free of charge, to any person obtaining a copy4# of this software and associated documentation files (the "Software"), to deal5# in the Software without restriction, including without limitation the rights6# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell7# copies of the Software, and to permit persons to whom the Software is8# furnished to do so, subject to the following conditions:9#10# The above copyright notice and this permission notice shall be included in11# all copies or substantial portions of the Software.12#13# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR14# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,15# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE16# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER17# 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 IN19# THE SOFTWARE.2021"""Reference implementation for Bech32/Bech32m and segwit addresses."""222324from enum import Enum2526class Encoding(Enum):27 """Enumeration type to list the various supported encodings."""28 BECH32 = 129 BECH32M = 23031CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"32BECH32M_CONST = 0x2bc830a33334def bech32_polymod(values):35 """Internal function that computes the Bech32 checksum."""36 generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]37 chk = 138 for value in values:39 top = chk >> 2540 chk = (chk & 0x1ffffff) << 5 ^ value41 for i in range(5):42 chk ^= generator[i] if ((top >> i) & 1) else 043 return chk444546def bech32_hrp_expand(hrp):47 """Expand the HRP into values for checksum computation."""48 return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp]495051def bech32_verify_checksum(hrp, data):52 """Verify a checksum given HRP and converted data characters."""53 const = bech32_polymod(bech32_hrp_expand(hrp) + data)54 if const == 1:55 return Encoding.BECH3256 if const == BECH32M_CONST:57 return Encoding.BECH32M58 return None5960def bech32_create_checksum(hrp, data, spec):61 """Compute the checksum values given HRP and data."""62 values = bech32_hrp_expand(hrp) + data63 const = BECH32M_CONST if spec == Encoding.BECH32M else 164 polymod = bech32_polymod(values + [0, 0, 0, 0, 0, 0]) ^ const65 return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)]666768def bech32_encode(hrp, data, spec):69 """Compute a Bech32 string given HRP and data values."""70 combined = data + bech32_create_checksum(hrp, data, spec)71 return hrp + '1' + ''.join([CHARSET[d] for d in combined])7273def bech32_decode(bech):74 """Validate a Bech32/Bech32m string, and determine HRP and data."""75 if ((any(ord(x) < 33 or ord(x) > 126 for x in bech)) or76 (bech.lower() != bech and bech.upper() != bech)):77 return (None, None, None)78 bech = bech.lower()79 pos = bech.rfind('1')80 if pos < 1 or pos + 7 > len(bech) or len(bech) > 90:81 return (None, None, None)82 if not all(x in CHARSET for x in bech[pos+1:]):83 return (None, None, None)84 hrp = bech[:pos]85 data = [CHARSET.find(x) for x in bech[pos+1:]]86 spec = bech32_verify_checksum(hrp, data)87 if spec is None:88 return (None, None, None)89 return (hrp, data[:-6], spec)9091def convertbits(data, frombits, tobits, pad=True):92 """General power-of-2 base conversion."""93 acc = 094 bits = 095 ret = []96 maxv = (1 << tobits) - 197 max_acc = (1 << (frombits + tobits - 1)) - 198 for value in data:99 if value < 0 or (value >> frombits):100 return None101 acc = ((acc << frombits) | value) & max_acc102 bits += frombits103 while bits >= tobits:104 bits -= tobits105 ret.append((acc >> bits) & maxv)106 if pad:107 if bits:108 ret.append((acc << (tobits - bits)) & maxv)109 elif bits >= frombits or ((acc << (tobits - bits)) & maxv):110 return None111 return ret112113114def decode(hrp, addr):115 """Decode a segwit address."""116 hrpgot, data, spec = bech32_decode(addr)117 if hrpgot != hrp:118 return (None, None)119 decoded = convertbits(data[1:], 5, 8, False)120 if decoded is None or len(decoded) < 2 or len(decoded) > 40:121 return (None, None)122 if data[0] > 16:123 return (None, None)124 if data[0] == 0 and len(decoded) != 20 and len(decoded) != 32:125 return (None, None)126 if data[0] == 0 and spec != Encoding.BECH32 or data[0] != 0 and spec != Encoding.BECH32M:127 return (None, None)128 return (data[0], decoded)129130131def encode(hrp, witver, witprog):132 """Encode a segwit address."""133 spec = Encoding.BECH32 if witver == 0 else Encoding.BECH32M134 ret = bech32_encode(hrp, [witver] + convertbits(witprog, 8, 5), spec)135 if decode(hrp, ret) == (None, None):136 return None137 return ret138