bech32.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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. # leading spaces converted to tabs
  12. #
  13. """Reference implementation for Bech32 and segwit addresses."""
  14. CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
  15. def bech32_polymod(values):
  16. """Internal function that computes the Bech32 checksum."""
  17. generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]
  18. chk = 1
  19. for value in values:
  20. top = chk >> 25
  21. chk = (chk & 0x1ffffff) << 5 ^ value
  22. for i in range(5):
  23. chk ^= generator[i] if ((top >> i) & 1) else 0
  24. return chk
  25. def bech32_hrp_expand(hrp):
  26. """Expand the HRP into values for checksum computation."""
  27. return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp]
  28. def bech32_verify_checksum(hrp, data):
  29. """Verify a checksum given HRP and converted data characters."""
  30. return bech32_polymod(bech32_hrp_expand(hrp) + data) == 1
  31. def bech32_create_checksum(hrp, data):
  32. """Compute the checksum values given HRP and data."""
  33. values = bech32_hrp_expand(hrp) + data
  34. polymod = bech32_polymod(values + [0, 0, 0, 0, 0, 0]) ^ 1
  35. return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)]
  36. def bech32_encode(hrp, data):
  37. """Compute a Bech32 string given HRP and data values."""
  38. combined = data + bech32_create_checksum(hrp, data)
  39. return hrp + '1' + ''.join([CHARSET[d] for d in combined])
  40. def bech32_decode(bech):
  41. """Validate a Bech32 string, and determine HRP and data."""
  42. if ((any(ord(x) < 33 or ord(x) > 126 for x in bech)) or
  43. (bech.lower() != bech and bech.upper() != bech)):
  44. return (None, None)
  45. bech = bech.lower()
  46. pos = bech.rfind('1')
  47. if pos < 1 or pos + 7 > len(bech) or len(bech) > 90:
  48. return (None, None)
  49. if not all(x in CHARSET for x in bech[pos+1:]):
  50. return (None, None)
  51. hrp = bech[:pos]
  52. data = [CHARSET.find(x) for x in bech[pos+1:]]
  53. if not bech32_verify_checksum(hrp, data):
  54. return (None, None)
  55. return (hrp, data[:-6])
  56. def convertbits(data, frombits, tobits, pad=True):
  57. """General power-of-2 base conversion."""
  58. acc = 0
  59. bits = 0
  60. ret = []
  61. maxv = (1 << tobits) - 1
  62. max_acc = (1 << (frombits + tobits - 1)) - 1
  63. for value in data:
  64. if value < 0 or (value >> frombits):
  65. return None
  66. acc = ((acc << frombits) | value) & max_acc
  67. bits += frombits
  68. while bits >= tobits:
  69. bits -= tobits
  70. ret.append((acc >> bits) & maxv)
  71. if pad:
  72. if bits:
  73. ret.append((acc << (tobits - bits)) & maxv)
  74. elif bits >= frombits or ((acc << (tobits - bits)) & maxv):
  75. return None
  76. return ret
  77. def decode(hrp, addr):
  78. """Decode a segwit address."""
  79. hrpgot, data = bech32_decode(addr)
  80. if hrpgot != hrp:
  81. return (None, None)
  82. decoded = convertbits(data[1:], 5, 8, False)
  83. if decoded is None or len(decoded) < 2 or len(decoded) > 40:
  84. return (None, None)
  85. if data[0] > 16:
  86. return (None, None)
  87. if data[0] == 0 and len(decoded) != 20 and len(decoded) != 32:
  88. return (None, None)
  89. return (data[0], decoded)
  90. def encode(hrp, witver, witprog):
  91. """Encode a segwit address."""
  92. ret = bech32_encode(hrp, [witver] + convertbits(witprog, 8, 5))
  93. if decode(hrp, ret) == (None, None):
  94. return None
  95. return ret