qa: Only allow disconnecting all NodeConns
[bitcoinplatinum.git] / test / functional / test_framework / address.py
blob2e2db5ffb21a06aec9556ed7f942972d9e0bc371
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."""
7 from .script import hash256, hash160, sha256, CScript, OP_0
8 from .util import bytes_to_hex_str, hex_str_to_bytes
10 from . import segwit_addr
12 chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
14 def byte_to_base58(b, version):
15 result = ''
16 str = bytes_to_hex_str(b)
17 str = bytes_to_hex_str(chr(version).encode('latin-1')) + str
18 checksum = bytes_to_hex_str(hash256(hex_str_to_bytes(str)))
19 str += checksum[:8]
20 value = int('0x'+str,0)
21 while value > 0:
22 result = chars[value % 58] + result
23 value //= 58
24 while (str[:2] == '00'):
25 result = chars[0] + result
26 str = str[2:]
27 return result
29 # TODO: def base58_decode
31 def keyhash_to_p2pkh(hash, main = False):
32 assert (len(hash) == 20)
33 version = 0 if main else 111
34 return byte_to_base58(hash, version)
36 def scripthash_to_p2sh(hash, main = False):
37 assert (len(hash) == 20)
38 version = 5 if main else 196
39 return byte_to_base58(hash, version)
41 def key_to_p2pkh(key, main = False):
42 key = check_key(key)
43 return keyhash_to_p2pkh(hash160(key), main)
45 def script_to_p2sh(script, main = False):
46 script = check_script(script)
47 return scripthash_to_p2sh(hash160(script), main)
49 def key_to_p2sh_p2wpkh(key, main = False):
50 key = check_key(key)
51 p2shscript = CScript([OP_0, hash160(key)])
52 return script_to_p2sh(p2shscript, main)
54 def program_to_witness(version, program, main = False):
55 if (type(program) is str):
56 program = hex_str_to_bytes(program)
57 assert 0 <= version <= 16
58 assert 2 <= len(program) <= 40
59 assert version > 0 or len(program) in [20, 32]
60 return segwit_addr.encode("bc" if main else "bcrt", version, program)
62 def script_to_p2wsh(script, main = False):
63 script = check_script(script)
64 return program_to_witness(0, sha256(script), main)
66 def key_to_p2wpkh(key, main = False):
67 key = check_key(key)
68 return program_to_witness(0, hash160(key), main)
70 def script_to_p2sh_p2wsh(script, main = False):
71 script = check_script(script)
72 p2shscript = CScript([OP_0, sha256(script)])
73 return script_to_p2sh(p2shscript, main)
75 def check_key(key):
76 if (type(key) is str):
77 key = hex_str_to_bytes(key) # Assuming this is hex string
78 if (type(key) is bytes and (len(key) == 33 or len(key) == 65)):
79 return key
80 assert(False)
82 def check_script(script):
83 if (type(script) is str):
84 script = hex_str_to_bytes(script) # Assuming this is hex string
85 if (type(script) is bytes or type(script) is CScript):
86 return script
87 assert(False)