PageRenderTime 156ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/test/functional/test_framework/address.py

https://github.com/martindale/bitcoin
Python | 177 lines | 149 code | 11 blank | 17 comment | 0 complexity | e21c70cccb419f6f5dec761b0fc12cc5 MD5 | raw file
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2016-2021 The Bitcoin Core developers
  3. # Distributed under the MIT software license, see the accompanying
  4. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. """Encode and decode Bitcoin addresses.
  6. - base58 P2PKH and P2SH addresses.
  7. - bech32 segwit v0 P2WPKH and P2WSH addresses.
  8. - bech32m segwit v1 P2TR addresses."""
  9. import enum
  10. import unittest
  11. from .script import (
  12. CScript,
  13. OP_0,
  14. OP_TRUE,
  15. hash160,
  16. hash256,
  17. sha256,
  18. taproot_construct,
  19. )
  20. from .segwit_addr import encode_segwit_address
  21. from .util import assert_equal
  22. ADDRESS_BCRT1_UNSPENDABLE = 'bcrt1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3xueyj'
  23. ADDRESS_BCRT1_UNSPENDABLE_DESCRIPTOR = 'addr(bcrt1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3xueyj)#juyq9d97'
  24. # Coins sent to this address can be spent with a witness stack of just OP_TRUE
  25. ADDRESS_BCRT1_P2WSH_OP_TRUE = 'bcrt1qft5p2uhsdcdc3l2ua4ap5qqfg4pjaqlp250x7us7a8qqhrxrxfsqseac85'
  26. class AddressType(enum.Enum):
  27. bech32 = 'bech32'
  28. p2sh_segwit = 'p2sh-segwit'
  29. legacy = 'legacy' # P2PKH
  30. chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
  31. def create_deterministic_address_bcrt1_p2tr_op_true():
  32. """
  33. Generates a deterministic bech32m address (segwit v1 output) that
  34. can be spent with a witness stack of OP_TRUE and the control block
  35. with internal public key (script-path spending).
  36. Returns a tuple with the generated address and the internal key.
  37. """
  38. internal_key = (1).to_bytes(32, 'big')
  39. scriptPubKey = taproot_construct(internal_key, [(None, CScript([OP_TRUE]))]).scriptPubKey
  40. address = encode_segwit_address("bcrt", 1, scriptPubKey[2:])
  41. assert_equal(address, 'bcrt1p9yfmy5h72durp7zrhlw9lf7jpwjgvwdg0jr0lqmmjtgg83266lqsekaqka')
  42. return (address, internal_key)
  43. def byte_to_base58(b, version):
  44. result = ''
  45. str = b.hex()
  46. str = chr(version).encode('latin-1').hex() + str
  47. checksum = hash256(bytes.fromhex(str)).hex()
  48. str += checksum[:8]
  49. value = int('0x' + str, 0)
  50. while value > 0:
  51. result = chars[value % 58] + result
  52. value //= 58
  53. while (str[:2] == '00'):
  54. result = chars[0] + result
  55. str = str[2:]
  56. return result
  57. def base58_to_byte(s):
  58. """Converts a base58-encoded string to its data and version.
  59. Throws if the base58 checksum is invalid."""
  60. if not s:
  61. return b''
  62. n = 0
  63. for c in s:
  64. n *= 58
  65. assert c in chars
  66. digit = chars.index(c)
  67. n += digit
  68. h = '%x' % n
  69. if len(h) % 2:
  70. h = '0' + h
  71. res = n.to_bytes((n.bit_length() + 7) // 8, 'big')
  72. pad = 0
  73. for c in s:
  74. if c == chars[0]:
  75. pad += 1
  76. else:
  77. break
  78. res = b'\x00' * pad + res
  79. # Assert if the checksum is invalid
  80. assert_equal(hash256(res[:-4])[:4], res[-4:])
  81. return res[1:-4], int(res[0])
  82. def keyhash_to_p2pkh(hash, main=False):
  83. assert len(hash) == 20
  84. version = 0 if main else 111
  85. return byte_to_base58(hash, version)
  86. def scripthash_to_p2sh(hash, main=False):
  87. assert len(hash) == 20
  88. version = 5 if main else 196
  89. return byte_to_base58(hash, version)
  90. def key_to_p2pkh(key, main=False):
  91. key = check_key(key)
  92. return keyhash_to_p2pkh(hash160(key), main)
  93. def script_to_p2sh(script, main=False):
  94. script = check_script(script)
  95. return scripthash_to_p2sh(hash160(script), main)
  96. def key_to_p2sh_p2wpkh(key, main=False):
  97. key = check_key(key)
  98. p2shscript = CScript([OP_0, hash160(key)])
  99. return script_to_p2sh(p2shscript, main)
  100. def program_to_witness(version, program, main=False):
  101. if (type(program) is str):
  102. program = bytes.fromhex(program)
  103. assert 0 <= version <= 16
  104. assert 2 <= len(program) <= 40
  105. assert version > 0 or len(program) in [20, 32]
  106. return encode_segwit_address("bc" if main else "bcrt", version, program)
  107. def script_to_p2wsh(script, main=False):
  108. script = check_script(script)
  109. return program_to_witness(0, sha256(script), main)
  110. def key_to_p2wpkh(key, main=False):
  111. key = check_key(key)
  112. return program_to_witness(0, hash160(key), main)
  113. def script_to_p2sh_p2wsh(script, main=False):
  114. script = check_script(script)
  115. p2shscript = CScript([OP_0, sha256(script)])
  116. return script_to_p2sh(p2shscript, main)
  117. def check_key(key):
  118. if (type(key) is str):
  119. key = bytes.fromhex(key) # Assuming this is hex string
  120. if (type(key) is bytes and (len(key) == 33 or len(key) == 65)):
  121. return key
  122. assert False
  123. def check_script(script):
  124. if (type(script) is str):
  125. script = bytes.fromhex(script) # Assuming this is hex string
  126. if (type(script) is bytes or type(script) is CScript):
  127. return script
  128. assert False
  129. class TestFrameworkScript(unittest.TestCase):
  130. def test_base58encodedecode(self):
  131. def check_base58(data, version):
  132. self.assertEqual(base58_to_byte(byte_to_base58(data, version)), (data, version))
  133. check_base58(bytes.fromhex('1f8ea1702a7bd4941bca0941b852c4bbfedb2e05'), 111)
  134. check_base58(bytes.fromhex('3a0b05f4d7f66c3ba7009f453530296c845cc9cf'), 111)
  135. check_base58(bytes.fromhex('41c1eaf111802559bad61b60d62b1f897c63928a'), 111)
  136. check_base58(bytes.fromhex('0041c1eaf111802559bad61b60d62b1f897c63928a'), 111)
  137. check_base58(bytes.fromhex('000041c1eaf111802559bad61b60d62b1f897c63928a'), 111)
  138. check_base58(bytes.fromhex('00000041c1eaf111802559bad61b60d62b1f897c63928a'), 111)
  139. check_base58(bytes.fromhex('1f8ea1702a7bd4941bca0941b852c4bbfedb2e05'), 0)
  140. check_base58(bytes.fromhex('3a0b05f4d7f66c3ba7009f453530296c845cc9cf'), 0)
  141. check_base58(bytes.fromhex('41c1eaf111802559bad61b60d62b1f897c63928a'), 0)
  142. check_base58(bytes.fromhex('0041c1eaf111802559bad61b60d62b1f897c63928a'), 0)
  143. check_base58(bytes.fromhex('000041c1eaf111802559bad61b60d62b1f897c63928a'), 0)
  144. check_base58(bytes.fromhex('00000041c1eaf111802559bad61b60d62b1f897c63928a'), 0)