bech32.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. #!/usr/bin/env python3
  2. #
  3. # Source URL:
  4. # https://github.com/bitcoin/bitcoin/blob/v0.16.0/test/functional/test_framework/segwit_addr.py
  5. #
  6. # Copyright (c) 2017 Pieter Wuille
  7. # Distributed under the MIT software license, see the accompanying
  8. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
  9. #
  10. # Unaltered except for the following changes by the MMGen Project:
  11. # 'python3' changed to 'python' in the hashbang
  12. # leading spaces converted to tabs
  13. #
  14. """Reference implementation for Bech32 and segwit addresses."""
  15. CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
  16. def bech32_polymod(values):
  17. """Internal function that computes the Bech32 checksum."""
  18. generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]
  19. chk = 1
  20. for value in values:
  21. top = chk >> 25
  22. chk = (chk & 0x1ffffff) << 5 ^ value
  23. for i in range(5):
  24. chk ^= generator[i] if ((top >> i) & 1) else 0
  25. return chk
  26. def bech32_hrp_expand(hrp):
  27. """Expand the HRP into values for checksum computation."""
  28. return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp]
  29. def bech32_verify_checksum(hrp, data):
  30. """Verify a checksum given HRP and converted data characters."""
  31. return bech32_polymod(bech32_hrp_expand(hrp) + data) == 1
  32. def bech32_create_checksum(hrp, data):
  33. """Compute the checksum values given HRP and data."""
  34. values = bech32_hrp_expand(hrp) + data
  35. polymod = bech32_polymod(values + [0, 0, 0, 0, 0, 0]) ^ 1
  36. return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)]
  37. def bech32_encode(hrp, data):
  38. """Compute a Bech32 string given HRP and data values."""
  39. combined = data + bech32_create_checksum(hrp, data)
  40. return hrp + '1' + ''.join([CHARSET[d] for d in combined])
  41. def bech32_decode(bech):
  42. """Validate a Bech32 string, and determine HRP and data."""
  43. if ((any(ord(x) < 33 or ord(x) > 126 for x in bech)) or
  44. (bech.lower() != bech and bech.upper() != bech)):
  45. return (None, None)
  46. bech = bech.lower()
  47. pos = bech.rfind('1')
  48. if pos < 1 or pos + 7 > len(bech) or len(bech) > 90:
  49. return (None, None)
  50. if not all(x in CHARSET for x in bech[pos+1:]):
  51. return (None, None)
  52. hrp = bech[:pos]
  53. data = [CHARSET.find(x) for x in bech[pos+1:]]
  54. if not bech32_verify_checksum(hrp, data):
  55. return (None, None)
  56. return (hrp, data[:-6])
  57. def convertbits(data, frombits, tobits, pad=True):
  58. """General power-of-2 base conversion."""
  59. acc = 0
  60. bits = 0
  61. ret = []
  62. maxv = (1 << tobits) - 1
  63. max_acc = (1 << (frombits + tobits - 1)) - 1
  64. for value in data:
  65. if value < 0 or (value >> frombits):
  66. return None
  67. acc = ((acc << frombits) | value) & max_acc
  68. bits += frombits
  69. while bits >= tobits:
  70. bits -= tobits
  71. ret.append((acc >> bits) & maxv)
  72. if pad:
  73. if bits:
  74. ret.append((acc << (tobits - bits)) & maxv)
  75. elif bits >= frombits or ((acc << (tobits - bits)) & maxv):
  76. return None
  77. return ret
  78. def decode(hrp, addr):
  79. """Decode a segwit address."""
  80. hrpgot, data = bech32_decode(addr)
  81. if hrpgot != hrp:
  82. return (None, None)
  83. decoded = convertbits(data[1:], 5, 8, False)
  84. if decoded is None or len(decoded) < 2 or len(decoded) > 40:
  85. return (None, None)
  86. if data[0] > 16:
  87. return (None, None)
  88. if data[0] == 0 and len(decoded) != 20 and len(decoded) != 32:
  89. return (None, None)
  90. return (data[0], decoded)
  91. def encode(hrp, witver, witprog):
  92. """Encode a segwit address."""
  93. ret = bech32_encode(hrp, [witver] + convertbits(witprog, 8, 5))
  94. if decode(hrp, ret) == (None, None):
  95. return None
  96. return ret