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.
- libnexapy_test-0.1.0.dist-info/METADATA +104 -0
- libnexapy_test-0.1.0.dist-info/RECORD +56 -0
- libnexapy_test-0.1.0.dist-info/WHEEL +5 -0
- libnexapy_test-0.1.0.dist-info/licenses/LICENCE +22 -0
- libnexapy_test-0.1.0.dist-info/top_level.txt +1 -0
- src/__init__.py +0 -0
- src/common/__init__.py +2 -0
- src/common/class_types.py +60 -0
- src/common/types.py +351 -0
- src/core/address/address.py +380 -0
- src/core/address/address_formatter.py +293 -0
- src/core/block/block.py +158 -0
- src/core/block/block_header.py +257 -0
- src/core/grouptoken.py +363 -0
- src/core/message.py +131 -0
- src/core/network/network.py +118 -0
- src/core/network/network_manager.py +131 -0
- src/core/script/opcode.py +312 -0
- src/core/script/script.py +841 -0
- src/core/script/script_factory.py +385 -0
- src/core/transaction/input/input.py +134 -0
- src/core/transaction/input/public_key_hash.py +47 -0
- src/core/transaction/input/public_key_template.py +47 -0
- src/core/transaction/input/script_template.py +154 -0
- src/core/transaction/output.py +161 -0
- src/core/transaction/sighash_type.py +246 -0
- src/core/transaction/transaction.py +506 -0
- src/core/transaction/tx_builder.py +228 -0
- src/core/transaction/tx_signature.py +85 -0
- src/core/transaction/tx_signer.py +164 -0
- src/core/transaction/unspent_output.py +79 -0
- src/crypto/__init__.py +3 -0
- src/crypto/curve_utils.py +43 -0
- src/crypto/digital_signature.py +73 -0
- src/crypto/ecc_fast.py +175 -0
- src/crypto/ecdsa.py +310 -0
- src/crypto/hash.py +64 -0
- src/crypto/libsecp256k1.so.0 +0 -0
- src/crypto/ripemd160.py +408 -0
- src/crypto/schnorr.py +509 -0
- src/crypto/secp256k1.py +223 -0
- src/crypto/signature.py +244 -0
- src/encoding/base32.py +51 -0
- src/encoding/base58.py +165 -0
- src/encoding/base58_check.py +92 -0
- src/encoding/buffer_reader.py +159 -0
- src/encoding/buffer_writer.py +138 -0
- src/keys/hd_private_key.py +473 -0
- src/keys/hd_public_key.py +417 -0
- src/keys/hdkey_utils.py +139 -0
- src/keys/private_key.py +340 -0
- src/keys/public_key.py +394 -0
- src/utils/buffer_utils.py +47 -0
- src/utils/common_utils.py +4 -0
- src/utils/num_utils.py +81 -0
- src/utils/unit_utils.py +78 -0
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
from urllib.parse import urlparse
|
|
2
|
+
|
|
3
|
+
from src.common.class_types import FrozenClass
|
|
4
|
+
from src.core.address.address import Address
|
|
5
|
+
from src.core.address.address_formatter import AddressType
|
|
6
|
+
from src.core.grouptoken import GroupToken, GroupIdType
|
|
7
|
+
from src.core.script.opcode import ScriptOpcode, Opcode
|
|
8
|
+
from src.core.script.script import Script
|
|
9
|
+
from src.crypto.signature import Signature
|
|
10
|
+
from src.encoding.buffer_reader import BufferReader
|
|
11
|
+
from src.keys.public_key import PublicKey
|
|
12
|
+
from src.utils.common_utils import is_hex_string
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ScriptFactory(FrozenClass):
|
|
16
|
+
"""
|
|
17
|
+
A factory class for creating scripts with predefined configurations and flags.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def __init__(self):
|
|
21
|
+
super().__init__()
|
|
22
|
+
self._freeze_attributes()
|
|
23
|
+
|
|
24
|
+
@staticmethod
|
|
25
|
+
def build_script_template_out(
|
|
26
|
+
to: str | Address | PublicKey,
|
|
27
|
+
group_id: str | Address | bytearray = None,
|
|
28
|
+
group_amount: bytearray | int = None,
|
|
29
|
+
) -> Script:
|
|
30
|
+
"""
|
|
31
|
+
Args:
|
|
32
|
+
to: destination address or public key
|
|
33
|
+
group_id: group id buffer or group address or hex id - only if its token output script
|
|
34
|
+
group_amount: optional. quantity amount buffer or int - only if its token output script
|
|
35
|
+
|
|
36
|
+
Returns:
|
|
37
|
+
a new pay to public key / script template output for the given address or public key
|
|
38
|
+
"""
|
|
39
|
+
if to is None:
|
|
40
|
+
raise ValueError("Invalid Argument: to. must provide an argument")
|
|
41
|
+
if not isinstance(to, (str, Address, PublicKey)):
|
|
42
|
+
raise TypeError("Invalid Argument: to. must be address or pubkey")
|
|
43
|
+
if (group_id is None) != (group_amount is None):
|
|
44
|
+
raise ValueError("Invalid Argument: group data. both must present or both not present")
|
|
45
|
+
|
|
46
|
+
to = ScriptFactory._parse_address(to)
|
|
47
|
+
if not to.is_pay_to_script_template():
|
|
48
|
+
raise ValueError(
|
|
49
|
+
"Invalid Argument: Invalid destination address (not a script template)."
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
if isinstance(group_id, str):
|
|
53
|
+
if is_hex_string(group_id):
|
|
54
|
+
group_id = bytearray.fromhex(group_id)
|
|
55
|
+
else:
|
|
56
|
+
group_id_address = Address.from_string(group_id)
|
|
57
|
+
if not group_id_address.is_group_identifier_address():
|
|
58
|
+
raise ValueError("Invalid Argument: Invalid group id address (not a group).")
|
|
59
|
+
group_id = group_id_address.data
|
|
60
|
+
elif isinstance(group_id, Address):
|
|
61
|
+
if not group_id.is_group_identifier_address():
|
|
62
|
+
raise ValueError("Invalid Argument: Invalid group id address (not a group).")
|
|
63
|
+
group_id = group_id.data
|
|
64
|
+
|
|
65
|
+
if isinstance(group_amount, int):
|
|
66
|
+
group_amount = GroupToken.get_amount_buffer(group_amount)
|
|
67
|
+
|
|
68
|
+
bfr = BufferReader(to.data).read_var_length_buffer()
|
|
69
|
+
s = Script.from_buffer(bfr)
|
|
70
|
+
|
|
71
|
+
if group_id is not None and group_amount is not None:
|
|
72
|
+
if not isinstance(group_id, (bytearray, bytes)):
|
|
73
|
+
raise ValueError("Invalid Argument: groupId.")
|
|
74
|
+
if not isinstance(group_amount, (bytearray, bytes)):
|
|
75
|
+
raise ValueError("Invalid Argument: groupAmount.")
|
|
76
|
+
# replace OP_0 with group data
|
|
77
|
+
s.chunks = s.chunks[1:]
|
|
78
|
+
s.prepend(group_amount).prepend(group_id)
|
|
79
|
+
|
|
80
|
+
return s
|
|
81
|
+
|
|
82
|
+
@staticmethod
|
|
83
|
+
def build_data_out(data: str | bytearray | Script = None, encoding: str = None) -> Script:
|
|
84
|
+
"""
|
|
85
|
+
Args:
|
|
86
|
+
data: the data to embed in the output
|
|
87
|
+
encoding: the type of encoding of the string
|
|
88
|
+
|
|
89
|
+
Returns:
|
|
90
|
+
a new OP_RETURN script with data
|
|
91
|
+
"""
|
|
92
|
+
if data is not None and not isinstance(data, (str, bytearray, bytes, Script)):
|
|
93
|
+
raise TypeError("Invalid Argument: data.")
|
|
94
|
+
if isinstance(data, str):
|
|
95
|
+
if encoding == "hex":
|
|
96
|
+
data = bytearray.fromhex(data)
|
|
97
|
+
else:
|
|
98
|
+
data = bytearray(data.encode("utf-8"))
|
|
99
|
+
elif isinstance(data, bytes):
|
|
100
|
+
data = bytearray(data)
|
|
101
|
+
|
|
102
|
+
s = Script.empty().add(Opcode.OP_RETURN)
|
|
103
|
+
if data is not None:
|
|
104
|
+
s.add(data)
|
|
105
|
+
return s
|
|
106
|
+
|
|
107
|
+
@staticmethod
|
|
108
|
+
def build_out_from_address(
|
|
109
|
+
address: str | Address,
|
|
110
|
+
group_id: str | Address | bytearray = None,
|
|
111
|
+
group_amount: bytearray | int = None,
|
|
112
|
+
) -> Script:
|
|
113
|
+
"""
|
|
114
|
+
Args:
|
|
115
|
+
address: the pay to address
|
|
116
|
+
group_id: optional. only for p2st addresses
|
|
117
|
+
group_amount: optional. only for p2st addresses
|
|
118
|
+
|
|
119
|
+
Returns:
|
|
120
|
+
an output script built from the address
|
|
121
|
+
"""
|
|
122
|
+
if isinstance(address, str):
|
|
123
|
+
address = Address.from_string(address)
|
|
124
|
+
if not isinstance(address, Address):
|
|
125
|
+
raise TypeError("Invalid Argument: address. must be address or address string")
|
|
126
|
+
|
|
127
|
+
if address.is_pay_to_public_key_hash():
|
|
128
|
+
return ScriptFactory.build_public_key_hash_out(address)
|
|
129
|
+
elif address.is_pay_to_script_template():
|
|
130
|
+
return ScriptFactory.build_script_template_out(address, group_id, group_amount)
|
|
131
|
+
raise ValueError(f"Invalid address type: {address.type}")
|
|
132
|
+
|
|
133
|
+
@staticmethod
|
|
134
|
+
def build_script_template_in(
|
|
135
|
+
template: Script = None, constraint: Script = None, satisfier: bytearray | Script = None
|
|
136
|
+
) -> Script:
|
|
137
|
+
"""
|
|
138
|
+
Builds a scriptSig (a script for an input) that signs a script template
|
|
139
|
+
output script.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
template: the template script or None for well-known
|
|
143
|
+
constraint: the constraint script or None for no constraint script
|
|
144
|
+
satisfier: the satisfier script or buffer or None for no satisfier
|
|
145
|
+
"""
|
|
146
|
+
if template is not None and not isinstance(template, Script):
|
|
147
|
+
raise TypeError("Invalid Argument: template.")
|
|
148
|
+
if constraint is not None and not isinstance(constraint, Script):
|
|
149
|
+
raise TypeError("Invalid Argument: constraint.")
|
|
150
|
+
if satisfier is not None and not isinstance(satisfier, (bytearray, bytes, Script)):
|
|
151
|
+
raise TypeError("Invalid Argument: satisfier.")
|
|
152
|
+
|
|
153
|
+
script = Script.empty()
|
|
154
|
+
if isinstance(template, Script):
|
|
155
|
+
script.add(template.to_buffer())
|
|
156
|
+
if isinstance(constraint, Script):
|
|
157
|
+
script.add(constraint.to_buffer())
|
|
158
|
+
if isinstance(satisfier, (bytearray, bytes)):
|
|
159
|
+
satisfier = Script.from_buffer(bytearray(satisfier))
|
|
160
|
+
if isinstance(satisfier, Script):
|
|
161
|
+
script.add(satisfier)
|
|
162
|
+
|
|
163
|
+
return script
|
|
164
|
+
|
|
165
|
+
@staticmethod
|
|
166
|
+
def _parse_address(address: str | Address | PublicKey, type: AddressType = None) -> Address:
|
|
167
|
+
if isinstance(address, str):
|
|
168
|
+
return Address.from_string(address)
|
|
169
|
+
elif isinstance(address, PublicKey):
|
|
170
|
+
return Address.from_public_key(address, address.network, type)
|
|
171
|
+
return address
|
|
172
|
+
|
|
173
|
+
@staticmethod
|
|
174
|
+
def build_public_key_hash_out(to: str | Address | PublicKey) -> Script:
|
|
175
|
+
"""
|
|
176
|
+
Args:
|
|
177
|
+
to: destination address or public key
|
|
178
|
+
|
|
179
|
+
Returns:
|
|
180
|
+
a new pay to public key hash output for the given
|
|
181
|
+
address or public key
|
|
182
|
+
"""
|
|
183
|
+
if to is None:
|
|
184
|
+
raise ValueError("Invalid Argument: to. must provide an argument")
|
|
185
|
+
if not isinstance(to, (str, Address, PublicKey)):
|
|
186
|
+
raise TypeError("Invalid Argument: to. must be address or pubkey")
|
|
187
|
+
|
|
188
|
+
to = ScriptFactory._parse_address(to, AddressType.PAY_TO_PUBLIC_KEY_HASH)
|
|
189
|
+
return (
|
|
190
|
+
Script.empty()
|
|
191
|
+
.add(Opcode.OP_DUP)
|
|
192
|
+
.add(Opcode.OP_HASH160)
|
|
193
|
+
.add(to.data)
|
|
194
|
+
.add(Opcode.OP_EQUALVERIFY)
|
|
195
|
+
.add(Opcode.OP_CHECKSIG)
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
@staticmethod
|
|
199
|
+
def build_public_key_hash_in(public_key: PublicKey, signature: Signature | bytearray) -> Script:
|
|
200
|
+
"""
|
|
201
|
+
Builds a scriptSig (a script for an input) that signs a public key hash
|
|
202
|
+
output script. (SIGHASH_ALL only)
|
|
203
|
+
|
|
204
|
+
Args:
|
|
205
|
+
public_key: the public key
|
|
206
|
+
signature: a Signature object, or the signature in DER canonical encoding
|
|
207
|
+
"""
|
|
208
|
+
if not isinstance(public_key, PublicKey):
|
|
209
|
+
raise TypeError("Invalid Argument: publicKey.")
|
|
210
|
+
if not isinstance(signature, (Signature, bytearray, bytes)):
|
|
211
|
+
raise TypeError("Invalid Argument: signature.")
|
|
212
|
+
|
|
213
|
+
if isinstance(signature, Signature):
|
|
214
|
+
signature = signature.to_buffer()
|
|
215
|
+
elif isinstance(signature, bytes):
|
|
216
|
+
signature = bytearray(signature)
|
|
217
|
+
|
|
218
|
+
return Script.empty().add(signature).add(public_key.to_buffer())
|
|
219
|
+
|
|
220
|
+
@staticmethod
|
|
221
|
+
def build_token_description_legacy(
|
|
222
|
+
ticker: str, name: str, doc_url: str = None, doc_hash: str = None, decimals: int = None
|
|
223
|
+
) -> Script:
|
|
224
|
+
"""
|
|
225
|
+
Build OP_RETURN output script for Legacy Token Description
|
|
226
|
+
|
|
227
|
+
Args:
|
|
228
|
+
ticker: the ticker as utf8.
|
|
229
|
+
name: the ticker as utf8.
|
|
230
|
+
doc_url: optional. the description document url
|
|
231
|
+
doc_hash: optional. the document hash hex.
|
|
232
|
+
decimals: optional. the decimals for the token amount.
|
|
233
|
+
|
|
234
|
+
Returns:
|
|
235
|
+
the output OP_RETURN script
|
|
236
|
+
"""
|
|
237
|
+
if not isinstance(ticker, str) or not 1 <= len(ticker) <= 8:
|
|
238
|
+
raise ValueError("Invalid Argument: Ticker must be between 1-8 chars.")
|
|
239
|
+
if not isinstance(name, str) or name.strip() == "":
|
|
240
|
+
raise ValueError("Invalid Argument: Name is missing.")
|
|
241
|
+
if decimals is not None:
|
|
242
|
+
if not isinstance(decimals, int) or not 0 <= decimals <= 18:
|
|
243
|
+
raise ValueError("Invalid Argument: decimals must be between 0 and 18.")
|
|
244
|
+
|
|
245
|
+
s = (
|
|
246
|
+
Script.empty()
|
|
247
|
+
.add(Opcode.OP_RETURN)
|
|
248
|
+
.add(Script.int_to_script_num_bytes(GroupIdType.LEGACY.value))
|
|
249
|
+
.add(bytearray(ticker.encode("utf-8")))
|
|
250
|
+
.add(bytearray(name.encode("utf-8")))
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
if doc_url and len(doc_url) > 0:
|
|
254
|
+
ScriptFactory._validate_url(doc_url)
|
|
255
|
+
if not isinstance(doc_hash, str) or doc_hash.strip() == "":
|
|
256
|
+
raise ValueError(
|
|
257
|
+
"Invalid Argument: You must include document hash if you set document url."
|
|
258
|
+
)
|
|
259
|
+
s.add(bytearray(doc_url.encode("utf-8"))).add(bytearray.fromhex(doc_hash)[::-1])
|
|
260
|
+
else:
|
|
261
|
+
s.add(Opcode.OP_FALSE).add(Opcode.OP_FALSE)
|
|
262
|
+
|
|
263
|
+
if decimals is not None:
|
|
264
|
+
if decimals <= 16:
|
|
265
|
+
s.add(ScriptOpcode.small_int(decimals))
|
|
266
|
+
else:
|
|
267
|
+
s.add(Script.int_to_script_num_bytes(decimals))
|
|
268
|
+
|
|
269
|
+
return s
|
|
270
|
+
|
|
271
|
+
@staticmethod
|
|
272
|
+
def build_token_description(
|
|
273
|
+
ticker: str, name: str, zip_url: str, zip_hash: str, decimals: int
|
|
274
|
+
) -> Script:
|
|
275
|
+
"""
|
|
276
|
+
Build OP_RETURN output script for NRC1 Token Description
|
|
277
|
+
|
|
278
|
+
Args:
|
|
279
|
+
ticker: the ticker as utf8.
|
|
280
|
+
name: the ticker as utf8.
|
|
281
|
+
zip_url: the zip file url.
|
|
282
|
+
zip_hash: the zip file hash hex.
|
|
283
|
+
decimals: the decimals for the token amount.
|
|
284
|
+
|
|
285
|
+
Returns:
|
|
286
|
+
the output OP_RETURN script
|
|
287
|
+
"""
|
|
288
|
+
if not isinstance(ticker, str) or not 2 <= len(ticker) <= 8:
|
|
289
|
+
raise ValueError("Invalid Argument: Ticker must be 2-8 chars.")
|
|
290
|
+
if not isinstance(name, str) or not 2 <= len(name) <= 25:
|
|
291
|
+
raise ValueError("Invalid Argument: Name must be 2-25 chars.")
|
|
292
|
+
if not isinstance(zip_url, str) or zip_url.strip() == "":
|
|
293
|
+
raise ValueError("Invalid Argument: Zip URL is missing.")
|
|
294
|
+
if not isinstance(zip_hash, str) or zip_hash.strip() == "":
|
|
295
|
+
raise ValueError("Invalid Argument: Zip hash is missing.")
|
|
296
|
+
if not isinstance(decimals, int) or not 0 <= decimals <= 18:
|
|
297
|
+
raise ValueError("Invalid Argument: Decimals must be a number 0-18.")
|
|
298
|
+
ScriptFactory._validate_url(zip_url)
|
|
299
|
+
|
|
300
|
+
return (
|
|
301
|
+
Script.empty()
|
|
302
|
+
.add(Opcode.OP_RETURN)
|
|
303
|
+
.add(Script.int_to_script_num_bytes(GroupIdType.NRC1.value))
|
|
304
|
+
.add(bytearray(ticker.encode("utf-8")))
|
|
305
|
+
.add(bytearray(name.encode("utf-8")))
|
|
306
|
+
.add(bytearray(zip_url.encode("utf-8")))
|
|
307
|
+
.add(bytearray.fromhex(zip_hash)[::-1])
|
|
308
|
+
.add(
|
|
309
|
+
ScriptOpcode.small_int(decimals)
|
|
310
|
+
if decimals <= 16
|
|
311
|
+
else Script.int_to_script_num_bytes(decimals)
|
|
312
|
+
)
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
@staticmethod
|
|
316
|
+
def build_nft_collection_description(
|
|
317
|
+
ticker: str, name: str, zip_url: str, zip_hash: str
|
|
318
|
+
) -> Script:
|
|
319
|
+
"""
|
|
320
|
+
Build OP_RETURN output script for an NFT Collection Description (NRC2)
|
|
321
|
+
|
|
322
|
+
Args:
|
|
323
|
+
ticker: the ticker as utf8.
|
|
324
|
+
name: the ticker as utf8.
|
|
325
|
+
zip_url: the zip file url.
|
|
326
|
+
zip_hash: the zip file hash hex.
|
|
327
|
+
|
|
328
|
+
Returns:
|
|
329
|
+
the output OP_RETURN script
|
|
330
|
+
"""
|
|
331
|
+
if not isinstance(ticker, str) or not 2 <= len(ticker) <= 8:
|
|
332
|
+
raise ValueError("Invalid Argument: Ticker must be 2-8 chars.")
|
|
333
|
+
if not isinstance(name, str) or not 2 <= len(name) <= 25:
|
|
334
|
+
raise ValueError("Invalid Argument: Name must be 2-25 chars.")
|
|
335
|
+
if not isinstance(zip_url, str) or zip_url.strip() == "":
|
|
336
|
+
raise ValueError("Invalid Argument: Zip URL is missing.")
|
|
337
|
+
if not isinstance(zip_hash, str) or zip_hash.strip() == "":
|
|
338
|
+
raise ValueError("Invalid Argument: Zip hash is missing.")
|
|
339
|
+
ScriptFactory._validate_url(zip_url)
|
|
340
|
+
|
|
341
|
+
return (
|
|
342
|
+
Script.empty()
|
|
343
|
+
.add(Opcode.OP_RETURN)
|
|
344
|
+
.add(Script.int_to_script_num_bytes(GroupIdType.NRC2.value))
|
|
345
|
+
.add(bytearray(ticker.encode("utf-8")))
|
|
346
|
+
.add(bytearray(name.encode("utf-8")))
|
|
347
|
+
.add(bytearray(zip_url.encode("utf-8")))
|
|
348
|
+
.add(bytearray.fromhex(zip_hash)[::-1])
|
|
349
|
+
.add(ScriptOpcode.small_int(0))
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
@staticmethod
|
|
353
|
+
def build_nft_description(zip_url: str, zip_hash: str) -> Script:
|
|
354
|
+
"""
|
|
355
|
+
Build OP_RETURN output script for an NFT that belongs to an NFT Collection (NRC3)
|
|
356
|
+
|
|
357
|
+
Args:
|
|
358
|
+
zip_url: the zip file url.
|
|
359
|
+
zip_hash: the zip file hash hex.
|
|
360
|
+
|
|
361
|
+
Returns:
|
|
362
|
+
the output OP_RETURN script
|
|
363
|
+
"""
|
|
364
|
+
if not isinstance(zip_url, str) or zip_url.strip() == "":
|
|
365
|
+
raise ValueError("Invalid Argument: Zip URL is missing.")
|
|
366
|
+
if not isinstance(zip_hash, str) or zip_hash.strip() == "":
|
|
367
|
+
raise ValueError("Invalid Argument: Zip hash is missing.")
|
|
368
|
+
ScriptFactory._validate_url(zip_url)
|
|
369
|
+
|
|
370
|
+
return (
|
|
371
|
+
Script.empty()
|
|
372
|
+
.add(Opcode.OP_RETURN)
|
|
373
|
+
.add(Script.int_to_script_num_bytes(GroupIdType.NRC3.value))
|
|
374
|
+
.add(bytearray(zip_url.encode("utf-8")))
|
|
375
|
+
.add(bytearray.fromhex(zip_hash)[::-1])
|
|
376
|
+
)
|
|
377
|
+
|
|
378
|
+
@staticmethod
|
|
379
|
+
def _validate_url(url: str) -> None:
|
|
380
|
+
"""
|
|
381
|
+
Will raise an exception if the given string is not a valid url.
|
|
382
|
+
"""
|
|
383
|
+
parsed = urlparse(url)
|
|
384
|
+
if not parsed.scheme or (parsed.scheme in ("http", "https") and not parsed.netloc):
|
|
385
|
+
raise ValueError(f"Invalid URL: {url}")
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
from typing import Self
|
|
2
|
+
|
|
3
|
+
from src.common.class_types import TypedClass
|
|
4
|
+
from src.common.types import InputType
|
|
5
|
+
from src.core.script.script import Script
|
|
6
|
+
from src.core.transaction.output import Output
|
|
7
|
+
from src.encoding.buffer_reader import BufferReader
|
|
8
|
+
from src.encoding.buffer_writer import BufferWriter
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Input(TypedClass):
|
|
12
|
+
SEQUENCE_FINAL: int = 0xFFFFFFFF
|
|
13
|
+
|
|
14
|
+
type: InputType | int
|
|
15
|
+
outpoint: bytearray | bytes
|
|
16
|
+
amount: int
|
|
17
|
+
sequence_number: int
|
|
18
|
+
output: Output | None
|
|
19
|
+
script_sig: Script | str
|
|
20
|
+
_script_sig: Script
|
|
21
|
+
|
|
22
|
+
def __init__(self, params: dict | None = None):
|
|
23
|
+
super().__init__()
|
|
24
|
+
self.type = None
|
|
25
|
+
self.outpoint = None
|
|
26
|
+
self.amount = None
|
|
27
|
+
self.sequence_number = None
|
|
28
|
+
self.output = None
|
|
29
|
+
self._script_sig = None
|
|
30
|
+
self._enforce_attribute_types()
|
|
31
|
+
if params is not None:
|
|
32
|
+
self._set(params)
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def script_sig(self) -> Script:
|
|
36
|
+
return self._script_sig
|
|
37
|
+
|
|
38
|
+
@script_sig.setter
|
|
39
|
+
def script_sig(self, script: str | Script):
|
|
40
|
+
if isinstance(script, Script):
|
|
41
|
+
self._script_sig = script
|
|
42
|
+
elif isinstance(script, str):
|
|
43
|
+
self._script_sig = Script.from_string(script)
|
|
44
|
+
else:
|
|
45
|
+
raise TypeError("Invalid argument type: script")
|
|
46
|
+
|
|
47
|
+
def _set(self, params: dict) -> None:
|
|
48
|
+
self.type = params.get("type") if params.get("type") is not None else InputType.UTXO
|
|
49
|
+
if params.get("scriptSig") is None:
|
|
50
|
+
raise TypeError("Need a script to create an input")
|
|
51
|
+
self.script_sig = params["scriptSig"]
|
|
52
|
+
self.outpoint = (
|
|
53
|
+
params["outpoint"]
|
|
54
|
+
if isinstance(params["outpoint"], (bytearray, bytes))
|
|
55
|
+
else bytearray.fromhex(params["outpoint"])
|
|
56
|
+
)
|
|
57
|
+
self.amount = int(params["amount"]) if params.get("amount") is not None else None
|
|
58
|
+
self.sequence_number = (
|
|
59
|
+
Input.SEQUENCE_FINAL
|
|
60
|
+
if params.get("sequenceNumber") is None
|
|
61
|
+
else params["sequenceNumber"]
|
|
62
|
+
)
|
|
63
|
+
if params.get("output"):
|
|
64
|
+
self.output = (
|
|
65
|
+
params["output"]
|
|
66
|
+
if isinstance(params["output"], Output)
|
|
67
|
+
else Output.from_object(params["output"])
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
@staticmethod
|
|
71
|
+
def from_object(obj: dict) -> Self:
|
|
72
|
+
if not isinstance(obj, dict):
|
|
73
|
+
raise ValueError("Invalid Argument: obj. ")
|
|
74
|
+
return Input(obj)
|
|
75
|
+
|
|
76
|
+
def to_object(self):
|
|
77
|
+
return {
|
|
78
|
+
"type": self.type,
|
|
79
|
+
"outpoint": self.outpoint.hex(),
|
|
80
|
+
"amount": str(self.amount),
|
|
81
|
+
"sequenceNumber": self.sequence_number,
|
|
82
|
+
"scriptSig": self.script_sig.to_hex(),
|
|
83
|
+
"output": self.output.to_object()
|
|
84
|
+
if getattr(self, "output", None) is not None
|
|
85
|
+
else None,
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
@staticmethod
|
|
89
|
+
def from_buffer_reader(br: BufferReader) -> Self:
|
|
90
|
+
input_ = Input()
|
|
91
|
+
input_.type = br.read_uint8()
|
|
92
|
+
input_.outpoint = br.read_reverse(32)
|
|
93
|
+
input_.script_sig = Script.from_buffer(br.read_var_length_buffer())
|
|
94
|
+
input_.sequence_number = br.read_uint32_le()
|
|
95
|
+
input_.amount = br.read_uint64_le()
|
|
96
|
+
return input_
|
|
97
|
+
|
|
98
|
+
def to_buffer_writer(
|
|
99
|
+
self, writer: BufferWriter | None = None, include_script=True
|
|
100
|
+
) -> BufferWriter:
|
|
101
|
+
if writer is None:
|
|
102
|
+
writer = BufferWriter()
|
|
103
|
+
writer.write_uint8(int(self.type))
|
|
104
|
+
writer.write_reverse(self.outpoint)
|
|
105
|
+
if include_script:
|
|
106
|
+
writer.write_var_length_buf(self.script_sig.to_buffer())
|
|
107
|
+
writer.write_uint32_le(self.sequence_number)
|
|
108
|
+
writer.write_uint64_le(self.amount)
|
|
109
|
+
return writer
|
|
110
|
+
|
|
111
|
+
def estimate_size(self) -> int:
|
|
112
|
+
return len(self.to_buffer_writer().to_buffer())
|
|
113
|
+
|
|
114
|
+
def is_final(self) -> bool:
|
|
115
|
+
return self.sequence_number != Input.SEQUENCE_FINAL
|
|
116
|
+
|
|
117
|
+
def clear_signatures(self) -> Self:
|
|
118
|
+
self.script_sig = Script.empty()
|
|
119
|
+
return self
|
|
120
|
+
|
|
121
|
+
def get_subscript(self) -> Script:
|
|
122
|
+
raise Exception("Abstract Method Invocation: Input#getSubscript")
|
|
123
|
+
|
|
124
|
+
def can_sign(self, private_key) -> bool:
|
|
125
|
+
"""
|
|
126
|
+
@returns true if the provided private key can sign this input
|
|
127
|
+
"""
|
|
128
|
+
raise Exception("Abstract Method Invocation: Input#canSign")
|
|
129
|
+
|
|
130
|
+
def is_fully_signed(self) -> bool:
|
|
131
|
+
raise Exception("Abstract Method Invocation: Input#isFullySigned")
|
|
132
|
+
|
|
133
|
+
def add_signature(self, signature) -> Self:
|
|
134
|
+
raise Exception("Abstract Method Invocation: Input#addSignature")
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
from typing import Self
|
|
2
|
+
|
|
3
|
+
from src.core.script.script import Script
|
|
4
|
+
from src.core.script.script_factory import ScriptFactory
|
|
5
|
+
from src.core.transaction.input.input import Input
|
|
6
|
+
from src.core.transaction.output import Output
|
|
7
|
+
from src.crypto.hash import Hash
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class PublicKeyHashInput(Input):
|
|
11
|
+
"""
|
|
12
|
+
Represents a special kind of input of PayToPublicKeyHash kind.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
SCRIPT_SIZE: int = 99
|
|
16
|
+
|
|
17
|
+
def __init__(self, params: dict | None = None):
|
|
18
|
+
super().__init__(params)
|
|
19
|
+
self._enforce_attribute_types()
|
|
20
|
+
|
|
21
|
+
def get_subscript(self) -> Script:
|
|
22
|
+
output = getattr(self, "output", None)
|
|
23
|
+
if not isinstance(output, Output):
|
|
24
|
+
raise ValueError("Invalid State: missing associated output")
|
|
25
|
+
return output.script_pubkey
|
|
26
|
+
|
|
27
|
+
def can_sign(self, private_key) -> bool:
|
|
28
|
+
output = getattr(self, "output", None)
|
|
29
|
+
if not isinstance(output, Output):
|
|
30
|
+
return False
|
|
31
|
+
pkh = Hash.sha256ripemd160(private_key.pubkey.to_buffer())
|
|
32
|
+
return pkh == output.script_pubkey.get_public_key_hash()
|
|
33
|
+
|
|
34
|
+
def is_fully_signed(self) -> bool:
|
|
35
|
+
return self.script_sig.is_public_key_hash_in()
|
|
36
|
+
|
|
37
|
+
def add_signature(self, signature) -> Self:
|
|
38
|
+
self.script_sig = ScriptFactory.build_public_key_hash_in(
|
|
39
|
+
signature.public_key, signature.signature
|
|
40
|
+
)
|
|
41
|
+
return self
|
|
42
|
+
|
|
43
|
+
def estimate_size(self) -> int:
|
|
44
|
+
if self.is_fully_signed():
|
|
45
|
+
return super().estimate_size()
|
|
46
|
+
# type + outpoint + scriptlen + script + sequence + amount
|
|
47
|
+
return 1 + 32 + 1 + PublicKeyHashInput.SCRIPT_SIZE + 4 + 8
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
from typing import Self
|
|
2
|
+
|
|
3
|
+
from src.core.script.opcode import Opcode
|
|
4
|
+
from src.core.script.script import Script
|
|
5
|
+
from src.core.script.script_factory import ScriptFactory
|
|
6
|
+
from src.core.transaction.input.input import Input
|
|
7
|
+
from src.core.transaction.output import Output
|
|
8
|
+
from src.crypto.hash import Hash
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class PublicKeyTemplateInput(Input):
|
|
12
|
+
"""
|
|
13
|
+
Represents a special kind of input of PayToPublicKeyTemplate kind.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
SCRIPT_SIZE: int = 100
|
|
17
|
+
|
|
18
|
+
def __init__(self, params: dict | None = None):
|
|
19
|
+
super().__init__(params)
|
|
20
|
+
self._enforce_attribute_types()
|
|
21
|
+
|
|
22
|
+
def get_subscript(self) -> Script:
|
|
23
|
+
return Script.empty().add(Opcode.OP_FROMALTSTACK).add(Opcode.OP_CHECKSIGVERIFY)
|
|
24
|
+
|
|
25
|
+
def can_sign(self, private_key) -> bool:
|
|
26
|
+
output = getattr(self, "output", None)
|
|
27
|
+
if not isinstance(output, Output):
|
|
28
|
+
return False
|
|
29
|
+
constraint_hash = Hash.sha256ripemd160(
|
|
30
|
+
Script.empty().add(private_key.pubkey.to_buffer()).to_buffer()
|
|
31
|
+
)
|
|
32
|
+
return constraint_hash == output.script_pubkey.get_constraint_hash()
|
|
33
|
+
|
|
34
|
+
def is_fully_signed(self) -> bool:
|
|
35
|
+
return self.script_sig.is_public_key_template_in()
|
|
36
|
+
|
|
37
|
+
def add_signature(self, signature) -> Self:
|
|
38
|
+
constraint = Script.empty().add(signature.public_key.to_buffer())
|
|
39
|
+
satisfier = Script.empty().add(signature.to_tx_satisfier())
|
|
40
|
+
self.script_sig = ScriptFactory.build_script_template_in(None, constraint, satisfier)
|
|
41
|
+
return self
|
|
42
|
+
|
|
43
|
+
def estimate_size(self) -> int:
|
|
44
|
+
if self.is_fully_signed():
|
|
45
|
+
return super().estimate_size()
|
|
46
|
+
# type + outpoint + scriptlen + script + sequence + amount
|
|
47
|
+
return 1 + 32 + 1 + PublicKeyTemplateInput.SCRIPT_SIZE + 4 + 8
|