PageRenderTime 1333ms CodeModel.GetById 41ms RepoModel.GetById 1ms app.codeStats 0ms

/test/functional/test_framework/address.py

https://github.com/bitcoin/bitcoin
Python | 175 lines | 147 code | 11 blank | 17 comment | 0 complexity | 2c2cf043d01f95dbf09428cf89451f54 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. b = bytes([version]) + b # prepend version
  46. b += hash256(b)[:4] # append checksum
  47. value = int.from_bytes(b, 'big')
  48. while value > 0:
  49. result = chars[value % 58] + result
  50. value //= 58
  51. while b[0] == 0:
  52. result = chars[0] + result
  53. b = b[1:]
  54. return result
  55. def base58_to_byte(s):
  56. """Converts a base58-encoded string to its data and version.
  57. Throws if the base58 checksum is invalid."""
  58. if not s:
  59. return b''
  60. n = 0
  61. for c in s:
  62. n *= 58
  63. assert c in chars
  64. digit = chars.index(c)
  65. n += digit
  66. h = '%x' % n
  67. if len(h) % 2:
  68. h = '0' + h
  69. res = n.to_bytes((n.bit_length() + 7) // 8, 'big')
  70. pad = 0
  71. for c in s:
  72. if c == chars[0]:
  73. pad += 1
  74. else:
  75. break
  76. res = b'\x00' * pad + res
  77. # Assert if the checksum is invalid
  78. assert_equal(hash256(res[:-4])[:4], res[-4:])
  79. return res[1:-4], int(res[0])
  80. def keyhash_to_p2pkh(hash, main=False):
  81. assert len(hash) == 20
  82. version = 0 if main else 111
  83. return byte_to_base58(hash, version)
  84. def scripthash_to_p2sh(hash, main=False):
  85. assert len(hash) == 20
  86. version = 5 if main else 196
  87. return byte_to_base58(hash, version)
  88. def key_to_p2pkh(key, main=False):
  89. key = check_key(key)
  90. return keyhash_to_p2pkh(hash160(key), main)
  91. def script_to_p2sh(script, main=False):
  92. script = check_script(script)
  93. return scripthash_to_p2sh(hash160(script), main)
  94. def key_to_p2sh_p2wpkh(key, main=False):
  95. key = check_key(key)
  96. p2shscript = CScript([OP_0, hash160(key)])
  97. return script_to_p2sh(p2shscript, main)
  98. def program_to_witness(version, program, main=False):
  99. if (type(program) is str):
  100. program = bytes.fromhex(program)
  101. assert 0 <= version <= 16
  102. assert 2 <= len(program) <= 40
  103. assert version > 0 or len(program) in [20, 32]
  104. return encode_segwit_address("bc" if main else "bcrt", version, program)
  105. def script_to_p2wsh(script, main=False):
  106. script = check_script(script)
  107. return program_to_witness(0, sha256(script), main)
  108. def key_to_p2wpkh(key, main=False):
  109. key = check_key(key)
  110. return program_to_witness(0, hash160(key), main)
  111. def script_to_p2sh_p2wsh(script, main=False):
  112. script = check_script(script)
  113. p2shscript = CScript([OP_0, sha256(script)])
  114. return script_to_p2sh(p2shscript, main)
  115. def check_key(key):
  116. if (type(key) is str):
  117. key = bytes.fromhex(key) # Assuming this is hex string
  118. if (type(key) is bytes and (len(key) == 33 or len(key) == 65)):
  119. return key
  120. assert False
  121. def check_script(script):
  122. if (type(script) is str):
  123. script = bytes.fromhex(script) # Assuming this is hex string
  124. if (type(script) is bytes or type(script) is CScript):
  125. return script
  126. assert False
  127. class TestFrameworkScript(unittest.TestCase):
  128. def test_base58encodedecode(self):
  129. def check_base58(data, version):
  130. self.assertEqual(base58_to_byte(byte_to_base58(data, version)), (data, version))
  131. check_base58(bytes.fromhex('1f8ea1702a7bd4941bca0941b852c4bbfedb2e05'), 111)
  132. check_base58(bytes.fromhex('3a0b05f4d7f66c3ba7009f453530296c845cc9cf'), 111)
  133. check_base58(bytes.fromhex('41c1eaf111802559bad61b60d62b1f897c63928a'), 111)
  134. check_base58(bytes.fromhex('0041c1eaf111802559bad61b60d62b1f897c63928a'), 111)
  135. check_base58(bytes.fromhex('000041c1eaf111802559bad61b60d62b1f897c63928a'), 111)
  136. check_base58(bytes.fromhex('00000041c1eaf111802559bad61b60d62b1f897c63928a'), 111)
  137. check_base58(bytes.fromhex('1f8ea1702a7bd4941bca0941b852c4bbfedb2e05'), 0)
  138. check_base58(bytes.fromhex('3a0b05f4d7f66c3ba7009f453530296c845cc9cf'), 0)
  139. check_base58(bytes.fromhex('41c1eaf111802559bad61b60d62b1f897c63928a'), 0)
  140. check_base58(bytes.fromhex('0041c1eaf111802559bad61b60d62b1f897c63928a'), 0)
  141. check_base58(bytes.fromhex('000041c1eaf111802559bad61b60d62b1f897c63928a'), 0)
  142. check_base58(bytes.fromhex('00000041c1eaf111802559bad61b60d62b1f897c63928a'), 0)