You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

address.py 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2016 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 BASE58, P2PKH and P2SH addresses."""
  6. from .script import hash256, hash160, sha256, CScript, OP_0
  7. from .util import bytes_to_hex_str, hex_str_to_bytes
  8. chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
  9. def byte_to_base58(b, version):
  10. result = ''
  11. str = bytes_to_hex_str(b)
  12. str = bytes_to_hex_str(chr(version).encode('latin-1')) + str
  13. checksum = bytes_to_hex_str(hash256(hex_str_to_bytes(str)))
  14. str += checksum[:8]
  15. value = int('0x'+str,0)
  16. while value > 0:
  17. result = chars[value % 58] + result
  18. value //= 58
  19. while (str[:2] == '00'):
  20. result = chars[0] + result
  21. str = str[2:]
  22. return result
  23. # TODO: def base58_decode
  24. def keyhash_to_p2pkh(hash, main = False):
  25. assert (len(hash) == 20)
  26. version = 0 if main else 111
  27. return byte_to_base58(hash, version)
  28. def scripthash_to_p2sh(hash, main = False):
  29. assert (len(hash) == 20)
  30. version = 5 if main else 196
  31. return byte_to_base58(hash, version)
  32. def key_to_p2pkh(key, main = False):
  33. key = check_key(key)
  34. return keyhash_to_p2pkh(hash160(key), main)
  35. def script_to_p2sh(script, main = False):
  36. script = check_script(script)
  37. return scripthash_to_p2sh(hash160(script), main)
  38. def key_to_p2sh_p2wpkh(key, main = False):
  39. key = check_key(key)
  40. p2shscript = CScript([OP_0, hash160(key)])
  41. return script_to_p2sh(p2shscript, main)
  42. def script_to_p2sh_p2wsh(script, main = False):
  43. script = check_script(script)
  44. p2shscript = CScript([OP_0, sha256(script)])
  45. return script_to_p2sh(p2shscript, main)
  46. def check_key(key):
  47. if (type(key) is str):
  48. key = hex_str_to_bytes(key) # Assuming this is hex string
  49. if (type(key) is bytes and (len(key) == 33 or len(key) == 65)):
  50. return key
  51. assert(False)
  52. def check_script(script):
  53. if (type(script) is str):
  54. script = hex_str_to_bytes(script) # Assuming this is hex string
  55. if (type(script) is bytes or type(script) is CScript):
  56. return script
  57. assert(False)