-
Notifications
You must be signed in to change notification settings - Fork 172
Expand file tree
/
Copy pathbitcoincash.py
More file actions
185 lines (151 loc) · 6.22 KB
/
Copy pathbitcoincash.py
File metadata and controls
185 lines (151 loc) · 6.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
#!/usr/bin/env python3
# Copyright © 2020-2026, Meheret Tesfaye Batu <meherett.batu@gmail.com>
# Distributed under the MIT software license, see the accompanying
# file COPYING or https://opensource.org/license/mit
from typing import (
Any, Union
)
from ..libs.base58 import ensure_string
from ..libs.bech32 import (
CHARSET, convertbits
)
from ..consts import PUBLIC_KEY_TYPES
from ..eccs import (
IPublicKey, SLIP10Secp256k1PublicKey, validate_and_get_public_key
)
from ..cryptocurrencies import BitcoinCash
from ..crypto import hash160
from ..utils import bytes_to_string
from .iaddress import IAddress
from enum import IntEnum
class BitcoinCashAddressType(IntEnum):
P2PKH = 0b0000
P2SH = 0b0001
P2PKH_WITH_TOKENS = 0b0010
P2SH_WITH_TOKENS = 0b0011
@property
def label(self):
mapping = {
BitcoinCashAddressType.P2PKH: "P2PKH",
BitcoinCashAddressType.P2SH: "P2SH",
BitcoinCashAddressType.P2PKH_WITH_TOKENS: "P2PKH_WITH_TOKENS",
BitcoinCashAddressType.P2SH_WITH_TOKENS: "P2SH_WITH_TOKENS"
}
return mapping.get(self, "Unknown Type")
class BitcoinCashAddress(IAddress):
hrp: str = BitcoinCash.NETWORKS.MAINNET.HRP
public_key_address_prefix: int = BitcoinCash.NETWORKS.MAINNET.STD_PUBLIC_KEY_ADDRESS_PREFIX
script_address_prefix: int = BitcoinCash.NETWORKS.MAINNET.STD_SCRIPT_ADDRESS_PREFIX
@staticmethod
def name() -> str:
"""
Returns the name of the cryptocurrency.
:return: The name of the address type.
:rtype: str
"""
return "BitcoinCash"
@classmethod
def encode(cls, public_key: Union[bytes, str, IPublicKey], **kwargs: Any) -> str:
"""
Encode a public key into a Bitcoin Cash CashAddr address.
:param public_key: The public key to encode.
:type public_key: Union[bytes, str, IPublicKey]
:param kwargs: Additional keyword arguments.
- hrp: Human-readable part (optional).
- public_key_type: Type of the public key (optional).
- public_key_address_prefix: Address prefix for P2PKH (optional).
- script_address_prefix: Address prefix for P2SH (optional).
:type kwargs: Any
:return: The encoded CashAddr address.
:rtype: str
"""
hrp = kwargs.get("prefix") or kwargs.get("hrp", cls.hrp)
public_key_address_prefix = kwargs.get("public_key_address_prefix", cls.public_key_address_prefix)
public_key: IPublicKey = validate_and_get_public_key(
public_key=public_key, public_key_cls=SLIP10Secp256k1PublicKey
)
public_key_hash: bytes = hash160(
public_key.raw_compressed()
if kwargs.get("public_key_type", PUBLIC_KEY_TYPES.COMPRESSED) == PUBLIC_KEY_TYPES.COMPRESSED else
public_key.raw_uncompressed()
)
# CashAddr version byte: 0 for P2PKH, 1 for P2SH
version_byte = 0x00 # P2PKH with 160-bit hash
if kwargs.get('token_support'):
version_byte = 0x10
# Pack version and hash
payload = bytes([version_byte]) + public_key_hash
# Convert to 5-bit groups
data = convertbits(payload, 8, 5)
# CashAddr polymod for checksum
generator = [0x98f2bc8e61, 0x79b76d99e2, 0xf33e5fb3c4, 0xae2eabe2a8, 0x1e4f43e470]
hrp_expand = [ord(x) & 0x1f for x in hrp] + [0]
values = hrp_expand + data + [0, 0, 0, 0, 0, 0, 0, 0]
chk = 1
for value in values:
top = chk >> 35
chk = ((chk & 0x07ffffffff) << 5) ^ value
for i in range(5):
chk ^= generator[i] if ((top >> i) & 1) else 0
polymod = chk ^ 1
# Create checksum
checksum = [(polymod >> (5 * (7 - i))) & 0x1f for i in range(8)]
# Encode as CashAddr
combined = data + checksum
return ensure_string(hrp + ':' + ''.join([CHARSET[d] for d in combined]))
@classmethod
def decode(cls, address: str, **kwargs: Any) -> str or dict:
"""
Decode a Bitcoin Cash CashAddr address.
:param address: The CashAddr address to decode.
:type address: str
:param kwargs: Additional keyword arguments.
- hrp: Human-readable part (optional).
:type kwargs: Any
:return: The decoded address as a string.
:rtype: str
"""
hrp_expected = [BitcoinCash.NETWORKS.MAINNET.HRP, BitcoinCash.NETWORKS.TESTNET.HRP, BitcoinCash.NETWORKS.REGTEST.HRP]
# Parse address
if ':' in address:
hrp, addr = address.split(':', 1)
else:
hrp = None
addr = address
if not all(x in CHARSET for x in addr.lower()):
raise ValueError("Invalid CashAddr characters")
addr = addr.lower()
data = [CHARSET.find(x) for x in addr]
# Verify checksum
if hrp:
generator = [0x98f2bc8e61, 0x79b76d99e2, 0xf33e5fb3c4, 0xae2eabe2a8, 0x1e4f43e470]
hrp_expand = [ord(x) & 0x1f for x in hrp.lower()] + [0]
values = hrp_expand + data
chk = 1
for value in values:
top = chk >> 35
chk = ((chk & 0x07ffffffff) << 5) ^ value
for i in range(5):
chk ^= generator[i] if ((top >> i) & 1) else 0
polymod = chk ^ 1
if polymod != 0:
raise ValueError("Invalid CashAddr checksum")
if hrp and hrp not in hrp_expected:
raise ValueError(f"Invalid HRP (expected: {hrp_expected}, got: {hrp})")
# Remove 8-byte checksum
data = data[:-8]
# Convert from 5-bit to 8-bit
decoded = convertbits(data, 5, 8, False)
if decoded is None or len(decoded) < 21:
raise ValueError("Invalid CashAddr data")
# First byte is version, rest is hash
version = decoded[0]
address_hash = bytes(decoded[1:])
if kwargs.get('decode_type'):
type_bits = (version & 0b01111000) >> 3
address_type = BitcoinCashAddressType(type_bits)
return {
'payload': bytes_to_string(address_hash),
'type': address_type.label
}
return bytes_to_string(address_hash)