libnexapy-test 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. libnexapy_test-0.1.0.dist-info/METADATA +104 -0
  2. libnexapy_test-0.1.0.dist-info/RECORD +56 -0
  3. libnexapy_test-0.1.0.dist-info/WHEEL +5 -0
  4. libnexapy_test-0.1.0.dist-info/licenses/LICENCE +22 -0
  5. libnexapy_test-0.1.0.dist-info/top_level.txt +1 -0
  6. src/__init__.py +0 -0
  7. src/common/__init__.py +2 -0
  8. src/common/class_types.py +60 -0
  9. src/common/types.py +351 -0
  10. src/core/address/address.py +380 -0
  11. src/core/address/address_formatter.py +293 -0
  12. src/core/block/block.py +158 -0
  13. src/core/block/block_header.py +257 -0
  14. src/core/grouptoken.py +363 -0
  15. src/core/message.py +131 -0
  16. src/core/network/network.py +118 -0
  17. src/core/network/network_manager.py +131 -0
  18. src/core/script/opcode.py +312 -0
  19. src/core/script/script.py +841 -0
  20. src/core/script/script_factory.py +385 -0
  21. src/core/transaction/input/input.py +134 -0
  22. src/core/transaction/input/public_key_hash.py +47 -0
  23. src/core/transaction/input/public_key_template.py +47 -0
  24. src/core/transaction/input/script_template.py +154 -0
  25. src/core/transaction/output.py +161 -0
  26. src/core/transaction/sighash_type.py +246 -0
  27. src/core/transaction/transaction.py +506 -0
  28. src/core/transaction/tx_builder.py +228 -0
  29. src/core/transaction/tx_signature.py +85 -0
  30. src/core/transaction/tx_signer.py +164 -0
  31. src/core/transaction/unspent_output.py +79 -0
  32. src/crypto/__init__.py +3 -0
  33. src/crypto/curve_utils.py +43 -0
  34. src/crypto/digital_signature.py +73 -0
  35. src/crypto/ecc_fast.py +175 -0
  36. src/crypto/ecdsa.py +310 -0
  37. src/crypto/hash.py +64 -0
  38. src/crypto/libsecp256k1.so.0 +0 -0
  39. src/crypto/ripemd160.py +408 -0
  40. src/crypto/schnorr.py +509 -0
  41. src/crypto/secp256k1.py +223 -0
  42. src/crypto/signature.py +244 -0
  43. src/encoding/base32.py +51 -0
  44. src/encoding/base58.py +165 -0
  45. src/encoding/base58_check.py +92 -0
  46. src/encoding/buffer_reader.py +159 -0
  47. src/encoding/buffer_writer.py +138 -0
  48. src/keys/hd_private_key.py +473 -0
  49. src/keys/hd_public_key.py +417 -0
  50. src/keys/hdkey_utils.py +139 -0
  51. src/keys/private_key.py +340 -0
  52. src/keys/public_key.py +394 -0
  53. src/utils/buffer_utils.py +47 -0
  54. src/utils/common_utils.py +4 -0
  55. src/utils/num_utils.py +81 -0
  56. src/utils/unit_utils.py +78 -0
@@ -0,0 +1,380 @@
1
+ import json
2
+ from typing import Self
3
+
4
+ from src.core.address.address_formatter import *
5
+ from src.core.network.network_manager import networks
6
+ from src.core.script.opcode import Opcode
7
+ from src.core.script.script import Script, ScriptElement
8
+ from src.common.class_types import FrozenClass
9
+ from src.common.types import Networkish, AddressDto
10
+ from src.crypto.hash import Hash
11
+ from src.encoding.buffer_writer import BufferWriter
12
+ from src.keys.public_key import PublicKey
13
+ from src.utils.buffer_utils import is_hash_buffer
14
+ from src.utils.common_utils import is_hex_string
15
+
16
+
17
+ class AddressError(Exception):
18
+ """Exception used for Address errors."""
19
+
20
+
21
+ class Address(FrozenClass):
22
+ def __new__(
23
+ cls,
24
+ data: Self | str | bytearray | bytes,
25
+ network: Networkish = None,
26
+ type: AddressType = None,
27
+ ):
28
+ # if the data being passed in is an Address instance, the same instance is returned
29
+ if isinstance(data, Address):
30
+ return data
31
+ return super().__new__(cls)
32
+
33
+ def __init__(
34
+ self,
35
+ data: Self | str | bytearray | bytes,
36
+ network: Networkish = None,
37
+ type: AddressType = None,
38
+ ):
39
+ """
40
+ Instantiate an address from an address String or Buffer, a public key or script hash Buffer,
41
+ or an instance of {@link PublicKey} or {@link Script}.
42
+
43
+ This is an immutable class, and if the first parameter provided to this constructor is an
44
+ `Address` instance, the same argument will be returned.
45
+
46
+ An address has two key properties: `network` and `type`. The type is either
47
+ `AddressType.PayToPublicKeyHash` (value is the `'P2PKH'` string)
48
+ or `AddressType.PayToScriptTemplate` (the string `'P2ST'`). The network is an instance of {@link Network} or network name.
49
+ You can quickly check whether an address is of a given kind by using the methods
50
+ `isPayToPublicKeyHash` and `isPayToScriptTemplate`
51
+
52
+ Args:
53
+ data: The encoded data in various formats
54
+ network: The network: 'mainnet' (default) or 'testnet'
55
+ type: The type of address: 'P2ST' (default) or 'P2PKH' or 'GROUP'
56
+
57
+ Returns:
58
+ A new valid and frozen instance of an Address
59
+ """
60
+ if isinstance(data, Address):
61
+ return
62
+
63
+ super().__init__()
64
+ self.data: bytearray = None
65
+ self.network = None
66
+ self.type = None
67
+
68
+ # there are two options. if the data is a str and it is passed alone, it is an address string
69
+ # otherwise all fields are passed in and its the parts of an address
70
+
71
+ if isinstance(data, str):
72
+ if network is not None and type is not None:
73
+ raise AddressError(
74
+ "If the data being passed in is a string, it must be a full address string"
75
+ "and can not be passed in with a network and type"
76
+ )
77
+ parts = AddressFormatter.decode(data)
78
+ self.data = parts.data
79
+ self.type = parts.type
80
+ self.network = networks.get(parts.prefix, "prefix")
81
+ self._freeze_attributes()
82
+ return
83
+
84
+ if isinstance(data, bytes):
85
+ data = bytearray(data)
86
+
87
+ if not isinstance(data, bytearray):
88
+ raise TypeError(
89
+ "First argument is required to be of type Address, bytes, or bytearray if it is not passed alone."
90
+ )
91
+
92
+ Address.validate_params(network, type)
93
+ self.data = data
94
+ self.type = type if type is not None else AddressType.PAY_TO_SCRIPT_TEMPLATE
95
+ self.network = networks.get(network)
96
+ if self.network is None:
97
+ self.network = networks.default_network
98
+ self._freeze_attributes() # attribute values can not be changed after this point
99
+
100
+ @staticmethod
101
+ def validate_params(network: Networkish, type: AddressType) -> None:
102
+ if network is not None and networks.get(network) is None:
103
+ raise AddressError('Second argument must be "mainnet" or "testnet".')
104
+
105
+ if (
106
+ type is not None
107
+ and type != AddressType.PAY_TO_SCRIPT_TEMPLATE
108
+ and type != AddressType.GROUP_ID_ADDRESS
109
+ and type != AddressType.PAY_TO_PUBLIC_KEY_HASH
110
+ ):
111
+ raise AddressError('Third argument must be "P2ST", "P2PKH" or "GROUP".')
112
+
113
+ @staticmethod
114
+ def from_string(address: str) -> Self:
115
+ """
116
+ Args:
117
+ address: an address string
118
+
119
+ Returns:
120
+ A new valid and frozen instance of an Address
121
+ """
122
+ if not isinstance(address, str):
123
+ raise TypeError("address must be of type str")
124
+
125
+ parts = AddressFormatter.decode(address)
126
+ network = networks.get(parts.prefix, "prefix")
127
+ return Address(parts.data, network, parts.type)
128
+
129
+ def to_string(self) -> str:
130
+ """
131
+ Will return a cashaddr representation of the address. Always returns lower case.
132
+ Can be converted by the called to uppercase as needed (still valid).
133
+
134
+ Returns:
135
+ address as a string
136
+ """
137
+ return AddressFormatter.encode(self.network.prefix, self.type, self.data)
138
+
139
+ def __str__(self):
140
+ return f"<Address: {self.to_string()}, type: {self.type.value}, network: {self.network}>"
141
+
142
+ @staticmethod
143
+ def from_object(obj: AddressDto) -> Self:
144
+ """
145
+ Instantiate an address from an JSON object
146
+
147
+ Args:
148
+ obj: A JSON object with keys: data, network, and type
149
+
150
+ Returns:
151
+ A new valid instance of an Address
152
+ """
153
+ if not isinstance(obj, AddressDto):
154
+ raise TypeError("obj must be of type AddressDto")
155
+
156
+ return Address(obj.data, obj.network, AddressType(obj.type))
157
+
158
+ @staticmethod
159
+ def from_json(obj: AddressDto) -> Self:
160
+ return Address.from_object(obj)
161
+
162
+ def to_json(self) -> AddressDto:
163
+ """
164
+ Get a JSON object representation of this address
165
+
166
+ Returns:
167
+ A JSON object with the address information
168
+ """
169
+ return AddressDto(self.data, self.network.to_string(), self.type.value)
170
+
171
+ def to_object(self) -> AddressDto:
172
+ return self.to_json()
173
+
174
+ def is_pay_to_public_key_hash(self) -> bool:
175
+ """
176
+ Returns:
177
+ true if an address is of pay to public key hash type
178
+ """
179
+ return self.type == AddressType.PAY_TO_PUBLIC_KEY_HASH
180
+
181
+ def is_pay_to_script_template(self) -> bool:
182
+ """
183
+ Returns:
184
+ true if an address is of pay to script template type
185
+ """
186
+ return self.type == AddressType.PAY_TO_SCRIPT_TEMPLATE
187
+
188
+ def is_group_identifier_address(self) -> bool:
189
+ """
190
+ Returns:
191
+ true if an address is a group token address
192
+ """
193
+ return self.type == AddressType.GROUP_ID_ADDRESS
194
+
195
+ @staticmethod
196
+ def get_validation_error(
197
+ data: str | bytearray, network: Networkish = None, type: AddressType = None
198
+ ) -> None | AddressError:
199
+ """
200
+ Will return a validation error if exists
201
+
202
+ Args:
203
+ data: The encoded data as either a string or bytearray
204
+ network: either a Network instance, 'mainnet', or 'testnet'
205
+ type: the type of address: 'P2ST' or 'GROUP' or 'P2PKH'
206
+
207
+ Returns:
208
+ the corresponding error message if one exists
209
+ """
210
+ try:
211
+ if isinstance(data, bytes):
212
+ data = bytearray(data)
213
+
214
+ if isinstance(data, str):
215
+ addr = Address.from_string(data)
216
+ data = addr.data
217
+
218
+ if network is not None:
219
+ found_net = networks.get(network)
220
+ if found_net is not None and found_net.prefix != addr.network.prefix:
221
+ raise AddressError("Address has mismatched network type.")
222
+ network = addr.network
223
+
224
+ if type is not None and type != addr.type:
225
+ raise AddressError("Address has mismatched type.")
226
+ type = addr.type
227
+
228
+ Address.validate_params(network, type)
229
+
230
+ encode_network = networks.get(network)
231
+ encode_prefix = (
232
+ encode_network.prefix
233
+ if encode_network is not None
234
+ else networks.default_network.prefix
235
+ )
236
+
237
+ AddressFormatter.encode(
238
+ encode_prefix,
239
+ type if type is not None else AddressType.PAY_TO_SCRIPT_TEMPLATE,
240
+ data,
241
+ )
242
+
243
+ return None
244
+
245
+ except Exception as e:
246
+ return e
247
+
248
+ @staticmethod
249
+ def is_valid(data: str | bytearray, network: Networkish = None, type: AddressType = None):
250
+ """
251
+ Will return a boolean describing if an address is valid
252
+
253
+ Args:
254
+ data: The encoded data as either a string or bytearray
255
+ network: either a Network instance, 'mainnet', or 'testnet'
256
+ type: the type of address: 'P2ST' or 'GROUP' or 'P2PKH'
257
+
258
+ Returns:
259
+ the corresponding error message if one exists
260
+ """
261
+ return Address.get_validation_error(data, network, type) == None
262
+
263
+ @staticmethod
264
+ def from_public_key(
265
+ pubkey: PublicKey, network: Networkish = None, type: AddressType = None
266
+ ) -> Self:
267
+ """
268
+ Instantiate an address from a PublicKey instance
269
+
270
+ Args:
271
+ pubkey: the public key instance
272
+ network: either a network instance, 'mainnet' or 'testnet'
273
+ type: address encoding type
274
+
275
+ Returns:
276
+ A new valid and frozen instance of an Address
277
+ """
278
+ data = Address._transform_public_key(pubkey, type)
279
+ return Address(data, network, type)
280
+
281
+ @staticmethod
282
+ def from_script_template(
283
+ template_hash: bytearray | Opcode,
284
+ constraint_hash: bytearray | Opcode,
285
+ visible_args: str | Script | list[ScriptElement] = None,
286
+ network: Networkish = None,
287
+ ) -> Self:
288
+ """
289
+ Instantiate an address from a non grouped script template
290
+
291
+ Args:
292
+ template_hash: An instance of a template hash Buffer
293
+ constraint_hash: An instance of a constraint hash Buffer
294
+ visible_args: An array of push-only args, or hex string represent script buffer, or Script with push args
295
+ network: either a Network instance, mainnet or testnet
296
+
297
+ Returns:
298
+ A new valid and frozen instance of an Address
299
+ """
300
+ data = Address._transform_script_template(template_hash, constraint_hash, visible_args)
301
+ return Address(data, network, AddressType.PAY_TO_SCRIPT_TEMPLATE)
302
+
303
+ @staticmethod
304
+ def _transform_public_key(
305
+ pubkey: PublicKey, type: AddressType = AddressType.PAY_TO_SCRIPT_TEMPLATE
306
+ ) -> bytearray:
307
+ """
308
+ Internal function to transform a {@link PublicKey}
309
+ """
310
+ if not isinstance(pubkey, PublicKey):
311
+ raise TypeError("pubkey must be of type PublicKey.")
312
+
313
+ if type is None:
314
+ type = AddressType.PAY_TO_SCRIPT_TEMPLATE
315
+
316
+ if type == AddressType.PAY_TO_PUBLIC_KEY_HASH:
317
+ return Hash.sha256ripemd160(pubkey.to_buffer())
318
+ elif type == AddressType.PAY_TO_SCRIPT_TEMPLATE:
319
+ constraint = Script.empty().add(pubkey.to_buffer())
320
+ constraint_hash = Hash.sha256ripemd160(constraint.to_buffer())
321
+ return Address._transform_script_template(Opcode.OP_1, constraint_hash)
322
+ else:
323
+ raise AddressError("type must be P2ST or P2PKH")
324
+
325
+ @staticmethod
326
+ def _transform_script_template(
327
+ template_hash: bytearray | Opcode,
328
+ constraint_hash: bytearray | Opcode,
329
+ visible_args: str | Script | list[ScriptElement] = None,
330
+ ) -> bytearray:
331
+ """
332
+ Internal function to transform a Script Template params
333
+ """
334
+ if template_hash != Opcode.OP_1 and not is_hash_buffer(template_hash):
335
+ raise AddressError("template_hash supplied is not a hash buffer or well-known OP_1.")
336
+
337
+ if constraint_hash != Opcode.OP_FALSE and not is_hash_buffer(constraint_hash):
338
+ raise AddressError("constraint_hash supplied is not a hash buffer or OP_FALSE.")
339
+
340
+ script_template = (
341
+ Script.empty().add(Opcode.OP_FALSE).add(template_hash).add(constraint_hash)
342
+ )
343
+ if visible_args:
344
+ if isinstance(visible_args, list):
345
+ for arg in visible_args:
346
+ script_template.add(arg)
347
+ elif isinstance(visible_args, Script):
348
+ script_template.add(visible_args)
349
+ elif is_hex_string(visible_args):
350
+ script_template.add(Script.from_hex(visible_args))
351
+
352
+ return BufferWriter().write_var_length_buf(script_template.to_buffer()).to_buffer()
353
+
354
+ @staticmethod
355
+ def get_output_type(address: str = None) -> int:
356
+ """
357
+ Will return the transaction output type by the address type
358
+
359
+ Args:
360
+ address: address as a string (optional)
361
+
362
+ Returns:
363
+ 1 - Template, 0 - otherwise
364
+ """
365
+ if not isinstance(address, str):
366
+ raise TypeError("address must be a string")
367
+ if Address.from_string(address).is_pay_to_script_template():
368
+ return 1
369
+ return 0
370
+
371
+ def get_self_output_type(self) -> int:
372
+ """
373
+ Will return the transaction output type by the address type
374
+
375
+ Returns:
376
+ 1 - Template, 0 - otherwise
377
+ """
378
+ if self.is_pay_to_script_template():
379
+ return 1
380
+ return 0
@@ -0,0 +1,293 @@
1
+ from enum import Enum, unique
2
+
3
+ from src.common.class_types import *
4
+ from src.encoding.base32 import Base32
5
+
6
+
7
+ @unique
8
+ class AddressType(Enum):
9
+ PAY_TO_PUBLIC_KEY_HASH = "P2PKH"
10
+ PAY_TO_SCRIPT_TEMPLATE = "P2ST"
11
+ GROUP_ID_ADDRESS = "GROUP"
12
+
13
+ @classmethod
14
+ def _missing_(cls, value):
15
+ for member in cls:
16
+ if member.value == value:
17
+ return member
18
+ return None
19
+
20
+
21
+ class AddressParts:
22
+ prefix: str
23
+ type: AddressType
24
+ data: bytearray | bytes
25
+
26
+ def __init__(
27
+ self, prefix: str = None, address_type: AddressType = None, data: bytearray = None
28
+ ):
29
+ self.prefix = prefix
30
+ self.type = address_type
31
+ self.data = data
32
+
33
+
34
+ class AddressFormatter(FrozenClass):
35
+ VALID_PREFIXES = ["nexa", "nexatest"]
36
+
37
+ def __init__(self):
38
+ super().__init__()
39
+ self._freeze_attributes()
40
+
41
+ @staticmethod
42
+ def encode(prefix: str, type: AddressType, data: bytearray) -> str:
43
+ """
44
+ @see encode_address
45
+ """
46
+ return AddressFormatter.encode_address(AddressParts(prefix, type, data))
47
+
48
+ @staticmethod
49
+ def encode_address(address: AddressParts) -> str:
50
+ """
51
+ Encodes a hash from a given type into a Nexa address with the given prefix.
52
+
53
+ Args:
54
+ address: AddressParts object that contains Network prefix (E.g.: 'nexa'), Type of address to generate and data to encode.
55
+ """
56
+ if not isinstance(address, AddressParts):
57
+ raise TypeError("address must be of type AddressParts")
58
+
59
+ if address.prefix not in AddressFormatter.VALID_PREFIXES:
60
+ raise ValueError("Invalid prefix: " + address.prefix + ".")
61
+
62
+ version_byte = AddressFormatter._get_type_int(address.type)
63
+
64
+ if address.type == AddressType.PAY_TO_PUBLIC_KEY_HASH:
65
+ offset = 1
66
+ encoded_size = 0
67
+ if len(address.data) >= 40:
68
+ offset = 2
69
+ encoded_size |= 0x04
70
+ encoded_size |= (len(address.data) - 20 * offset) // (4 * offset)
71
+ version_byte |= encoded_size
72
+ # invalid size?
73
+ if (len(address.data) - 20 * offset) % (4 * offset) != 0 or not 0 <= encoded_size <= 7:
74
+ raise ValueError(f"invalid address hash size {address.data}")
75
+
76
+ data = bytearray([version_byte]) + address.data
77
+ payload = AddressFormatter._convert_bits(data, 8, 5, True)
78
+ checksum = AddressFormatter._create_checksum(address.prefix, payload)
79
+ addr_str = address.prefix + ":" + Base32.encode(payload + checksum)
80
+ return addr_str
81
+
82
+ @staticmethod
83
+ def decode(address: str) -> AddressParts:
84
+ """
85
+ Decodes the given address into its constituting prefix, type and data. See {@link encodeAddress}.
86
+
87
+ Args:
88
+ address: string - Address to decode. E.g.: 'nexa:qpm2qsznhks23z7629mms6s4cwef74vcwvgpsey0xy'.
89
+ """
90
+ if not isinstance(address, str):
91
+ raise TypeError("address must be of type str")
92
+
93
+ if not AddressFormatter._has_single_case(address):
94
+ raise Exception(f"Invalid address: {address}.")
95
+
96
+ pieces = address.lower().split(":")
97
+ if len(pieces) != 2:
98
+ raise ValueError("Missing prefix: " + address + ".")
99
+
100
+ prefix = pieces[0]
101
+ payload = pieces[1]
102
+
103
+ if not prefix:
104
+ raise ValueError(f"address prefix is missing: {address}")
105
+ if not all(33 <= ord(x) <= 126 for x in prefix):
106
+ raise ValueError(f"invalid address prefix: {prefix}")
107
+ if 8 > len(payload):
108
+ raise ValueError(f"address payload has invalid length of {len(payload)}")
109
+
110
+ payload = Base32.decode(payload)
111
+
112
+ if AddressFormatter._valid_checksum(prefix, payload) == False:
113
+ raise Exception(f"Invalid checksum: {address}.")
114
+
115
+ # drop the 40 bit checksum
116
+ payload = payload[:-8]
117
+
118
+ # Ensure there isn't extra padding
119
+ extra_bits = len(payload) * 5 % 8
120
+ if extra_bits >= 5:
121
+ raise ValueError("excess padding in address {}".format(address))
122
+
123
+ # Ensure extra_bits are zeros
124
+ if payload[-1] & ((1 << extra_bits) - 1):
125
+ raise ValueError("non-zero padding in address {}".format(address))
126
+
127
+ converted_bits = AddressFormatter._convert_bits(payload, 5, 8, False)
128
+ version_byte = converted_bits[0]
129
+ data = converted_bits[1:]
130
+ addr_type = AddressFormatter._get_type(version_byte)
131
+ # only run size checks on p2pkh addrs
132
+ if addr_type == AddressType.PAY_TO_PUBLIC_KEY_HASH and len(data) == 20:
133
+ size = (version_byte & 0x03) * 4 + 20
134
+ if version_byte & 0x04:
135
+ size <<= 1
136
+ if size != len(data):
137
+ raise ValueError(f"address data has length {len(data)} but expected {size}")
138
+
139
+ return AddressParts(prefix, addr_type, data)
140
+
141
+ @staticmethod
142
+ def _is_valid_prefix(prefix: str) -> bool:
143
+ """
144
+ Checks whether a string is a valid prefix; ie., it has a single letter case.
145
+ and is only letters.
146
+
147
+ @param prefix
148
+ """
149
+ return AddressFormatter._has_single_case(prefix) and prefix.isalpha()
150
+
151
+ @staticmethod
152
+ def _prefix_to_bytearray(prefix: str) -> bytearray:
153
+ """
154
+ Derives an array from the given prefix to be used in the computation
155
+ of the address' checksum.
156
+
157
+ @param prefix Network prefix. E.g.: 'nexa'.
158
+ """
159
+ res = bytearray(ord(x) & 0x1F for x in prefix)
160
+ # Append null separator
161
+ res.append(0)
162
+ return res
163
+
164
+ @staticmethod
165
+ def _create_checksum(prefix: str, data: bytearray) -> bytearray:
166
+ """
167
+ Compute the checksum values given prefix and data.
168
+ """
169
+ values = AddressFormatter._prefix_to_bytearray(prefix) + data + bytes(8)
170
+ polymod = AddressFormatter._polymod(values)
171
+ # Return the polymod expanded into eight 5-bit elements
172
+ return bytearray((polymod >> 5 * (7 - i)) & 31 for i in range(8))
173
+
174
+ @staticmethod
175
+ def _checksum_to_bytearray(checksum: int) -> bytearray:
176
+ """
177
+ Returns an array representation of the given checksum to be encoded
178
+ within the address' payload.
179
+
180
+ @param checksum Computed checksum.
181
+ """
182
+ res = bytearray()
183
+ for i in range(8):
184
+ res.append(checksum & 31)
185
+ checksum = int(checksum / 32)
186
+ res.reverse()
187
+ return res
188
+
189
+ @staticmethod
190
+ def _get_type_int(type: AddressType) -> int:
191
+ """
192
+ Returns the bit representation of the given type within the version byte.
193
+
194
+ @param type Address type. Either 'P2PKH' or 'P2SH'.
195
+ """
196
+ if type == AddressType.PAY_TO_PUBLIC_KEY_HASH:
197
+ return 0
198
+ elif type == AddressType.PAY_TO_SCRIPT_TEMPLATE:
199
+ return 19 << 3
200
+ elif type == AddressType.GROUP_ID_ADDRESS:
201
+ return 11 << 3
202
+ else:
203
+ raise TypeError(f"Invalid type: {type}.")
204
+
205
+ @staticmethod
206
+ def _get_type(version_byte: int) -> AddressType:
207
+ """
208
+ Retrieves the address type from its bit representation within the
209
+ version byte.
210
+
211
+ @param versionByte
212
+ """
213
+ type_byte = version_byte & 248
214
+ if type_byte == 0:
215
+ return AddressType.PAY_TO_PUBLIC_KEY_HASH
216
+ elif type_byte == 19 << 3:
217
+ return AddressType.PAY_TO_SCRIPT_TEMPLATE
218
+ elif type_byte == 11 << 3:
219
+ return AddressType.GROUP_ID_ADDRESS
220
+ else:
221
+ raise Exception(f"Invalid address type in version byte: {version_byte}.")
222
+
223
+ @staticmethod
224
+ def _has_single_case(string: str) -> bool:
225
+ """
226
+ Returns true if, and only if, the given string contains either uppercase
227
+ or lowercase letters, but not both.
228
+
229
+ @param string Input string.
230
+ """
231
+ return string.islower() or string.isupper()
232
+
233
+ @staticmethod
234
+ def _valid_checksum(prefix: str, payload: bytearray) -> bool:
235
+ """
236
+ Verify that the payload has not been corrupted by checking that the
237
+ checksum is valid.
238
+
239
+ @param prefix Network prefix. E.g.: 'nexa'.
240
+ @param payload Array of 5-bit integers containing the address' payload.
241
+ """
242
+ prefix_data = AddressFormatter._prefix_to_bytearray(prefix)
243
+ prefix_data = prefix_data + payload
244
+ return AddressFormatter._polymod(prefix_data) == 0
245
+
246
+ @staticmethod
247
+ def _polymod(data: list[int]) -> int:
248
+ """
249
+ Computes a checksum from the given input data as specified for the CashAddr
250
+ format: https://github.com/Bitcoin-UAHF/spec/blob/master/cashaddr.md.
251
+
252
+ @param data Array of 5-bit integers over which the checksum is to be computed.
253
+ """
254
+ c = 1
255
+ for d in data:
256
+ c0 = c >> 35
257
+ c = ((c & 0x07FFFFFFFF) << 5) ^ d
258
+ if c0 & 0x01:
259
+ c ^= 0x98F2BC8E61
260
+ if c0 & 0x02:
261
+ c ^= 0x79B76D99E2
262
+ if c0 & 0x04:
263
+ c ^= 0xF33E5FB3C4
264
+ if c0 & 0x08:
265
+ c ^= 0xAE2EABE2A8
266
+ if c0 & 0x10:
267
+ c ^= 0x1E4F43E470
268
+ retval = c ^ 1
269
+ return retval
270
+
271
+ @staticmethod
272
+ def _convert_bits(
273
+ data: bytearray | bytes, from_bits: int, to_bits: int, pad: bool
274
+ ) -> bytearray:
275
+ """
276
+ General power-of-2 base conversion.
277
+ """
278
+ acc = 0
279
+ bits = 0
280
+ ret = bytearray()
281
+ maxv = (1 << to_bits) - 1
282
+ max_acc = (1 << (from_bits + to_bits - 1)) - 1
283
+ for value in data:
284
+ acc = ((acc << from_bits) | value) & max_acc
285
+ bits += from_bits
286
+ while bits >= to_bits:
287
+ bits -= to_bits
288
+ ret.append((acc >> bits) & maxv)
289
+
290
+ if pad and bits:
291
+ ret.append((acc << (to_bits - bits)) & maxv)
292
+
293
+ return ret