PageRenderTime 1091ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/test/functional/test_framework/segwit_addr.py

https://github.com/bitcoin/bitcoin
Python | 141 lines | 119 code | 11 blank | 11 comment | 12 complexity | 323e51c04b57270f2d2cbf81948aed6f MD5 | raw file
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2017 Pieter Wuille
  3. # Distributed under the MIT software license, see the accompanying
  4. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. """Reference implementation for Bech32/Bech32m and segwit addresses."""
  6. import unittest
  7. from enum import Enum
  8. CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
  9. BECH32_CONST = 1
  10. BECH32M_CONST = 0x2bc830a3
  11. class Encoding(Enum):
  12. """Enumeration type to list the various supported encodings."""
  13. BECH32 = 1
  14. BECH32M = 2
  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. check = bech32_polymod(bech32_hrp_expand(hrp) + data)
  31. if check == BECH32_CONST:
  32. return Encoding.BECH32
  33. elif check == BECH32M_CONST:
  34. return Encoding.BECH32M
  35. else:
  36. return None
  37. def bech32_create_checksum(encoding, hrp, data):
  38. """Compute the checksum values given HRP and data."""
  39. values = bech32_hrp_expand(hrp) + data
  40. const = BECH32M_CONST if encoding == Encoding.BECH32M else BECH32_CONST
  41. polymod = bech32_polymod(values + [0, 0, 0, 0, 0, 0]) ^ const
  42. return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)]
  43. def bech32_encode(encoding, hrp, data):
  44. """Compute a Bech32 or Bech32m string given HRP and data values."""
  45. combined = data + bech32_create_checksum(encoding, hrp, data)
  46. return hrp + '1' + ''.join([CHARSET[d] for d in combined])
  47. def bech32_decode(bech):
  48. """Validate a Bech32/Bech32m string, and determine HRP and data."""
  49. if ((any(ord(x) < 33 or ord(x) > 126 for x in bech)) or
  50. (bech.lower() != bech and bech.upper() != bech)):
  51. return (None, None, None)
  52. bech = bech.lower()
  53. pos = bech.rfind('1')
  54. if pos < 1 or pos + 7 > len(bech) or len(bech) > 90:
  55. return (None, None, None)
  56. if not all(x in CHARSET for x in bech[pos+1:]):
  57. return (None, None, None)
  58. hrp = bech[:pos]
  59. data = [CHARSET.find(x) for x in bech[pos+1:]]
  60. encoding = bech32_verify_checksum(hrp, data)
  61. if encoding is None:
  62. return (None, None, None)
  63. return (encoding, hrp, data[:-6])
  64. def convertbits(data, frombits, tobits, pad=True):
  65. """General power-of-2 base conversion."""
  66. acc = 0
  67. bits = 0
  68. ret = []
  69. maxv = (1 << tobits) - 1
  70. max_acc = (1 << (frombits + tobits - 1)) - 1
  71. for value in data:
  72. if value < 0 or (value >> frombits):
  73. return None
  74. acc = ((acc << frombits) | value) & max_acc
  75. bits += frombits
  76. while bits >= tobits:
  77. bits -= tobits
  78. ret.append((acc >> bits) & maxv)
  79. if pad:
  80. if bits:
  81. ret.append((acc << (tobits - bits)) & maxv)
  82. elif bits >= frombits or ((acc << (tobits - bits)) & maxv):
  83. return None
  84. return ret
  85. def decode_segwit_address(hrp, addr):
  86. """Decode a segwit address."""
  87. encoding, hrpgot, data = bech32_decode(addr)
  88. if hrpgot != hrp:
  89. return (None, None)
  90. decoded = convertbits(data[1:], 5, 8, False)
  91. if decoded is None or len(decoded) < 2 or len(decoded) > 40:
  92. return (None, None)
  93. if data[0] > 16:
  94. return (None, None)
  95. if data[0] == 0 and len(decoded) != 20 and len(decoded) != 32:
  96. return (None, None)
  97. if (data[0] == 0 and encoding != Encoding.BECH32) or (data[0] != 0 and encoding != Encoding.BECH32M):
  98. return (None, None)
  99. return (data[0], decoded)
  100. def encode_segwit_address(hrp, witver, witprog):
  101. """Encode a segwit address."""
  102. encoding = Encoding.BECH32 if witver == 0 else Encoding.BECH32M
  103. ret = bech32_encode(encoding, hrp, [witver] + convertbits(witprog, 8, 5))
  104. if decode_segwit_address(hrp, ret) == (None, None):
  105. return None
  106. return ret
  107. class TestFrameworkScript(unittest.TestCase):
  108. def test_segwit_encode_decode(self):
  109. def test_python_bech32(addr):
  110. hrp = addr[:4]
  111. self.assertEqual(hrp, "bcrt")
  112. (witver, witprog) = decode_segwit_address(hrp, addr)
  113. self.assertEqual(encode_segwit_address(hrp, witver, witprog), addr)
  114. # P2WPKH
  115. test_python_bech32('bcrt1qthmht0k2qnh3wy7336z05lu2km7emzfpm3wg46')
  116. # P2WSH
  117. test_python_bech32('bcrt1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3xueyj')
  118. test_python_bech32('bcrt1qft5p2uhsdcdc3l2ua4ap5qqfg4pjaqlp250x7us7a8qqhrxrxfsqseac85')
  119. # P2TR
  120. test_python_bech32('bcrt1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqc8gma6')