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,841 @@
1
+ from typing import Self, TypeVar
2
+ import json
3
+ import math
4
+
5
+ from src.common.class_types import TypedClass
6
+ from src.core.script.opcode import ScriptOpcode, Opcode
7
+ from src.encoding.buffer_reader import BufferReader
8
+ from src.utils.buffer_utils import is_hash_buffer
9
+ from src.utils.common_utils import is_hex_string
10
+
11
+
12
+ class ScriptChunk(TypedClass):
13
+ def __init__(self, buf: bytearray = None, len: int = None, opcodenum: int = None):
14
+ super().__init__()
15
+ self.buf = buf
16
+ self.len = len
17
+ self.opcodenum = opcodenum
18
+ self._enforce_attribute_types()
19
+
20
+
21
+ ScriptElement = TypeVar(
22
+ "ScriptElement", str, int, bool, bytes, bytearray, ScriptOpcode, ScriptChunk
23
+ )
24
+
25
+
26
+ class Script(TypedClass):
27
+ """
28
+ A nexa transaction script. Each transaction's inputs and outputs
29
+ has a script that is evaluated to validate it's spending.
30
+
31
+ @see {@link https://spec.nexa.org/script/1script/}
32
+ """
33
+
34
+ def __init__(self, from_data: bytearray | str | ScriptChunk | Self = None):
35
+ super().__init__()
36
+ self.chunks = []
37
+ self._enforce_attribute_types()
38
+ if not from_data:
39
+ return
40
+ if isinstance(from_data, (bytes, bytearray)):
41
+ if isinstance(from_data, bytes):
42
+ from_data = bytearray(from_data)
43
+ other = Script.from_buffer(from_data)
44
+ self.chunks = other.chunks
45
+ elif isinstance(from_data, Script):
46
+ other = Script.from_buffer(from_data.to_buffer())
47
+ self.chunks = other.chunks
48
+ elif isinstance(from_data, str):
49
+ other = Script.from_string(from_data)
50
+ self.chunks = other.chunks
51
+ elif Script._is_script_object(from_data):
52
+ self.set(from_data)
53
+ else:
54
+ raise TypeError(
55
+ "from_data must be one of the following types: bytearray, str, ScriptChunk, Script."
56
+ )
57
+
58
+ @staticmethod
59
+ # needs chunks (list[ScriptChunk]) in the object
60
+ def _is_script_object(obj):
61
+ if isinstance(obj, Script):
62
+ return True
63
+ return False
64
+
65
+ @staticmethod
66
+ # needs opcodenum in the object
67
+ def _is_script_chunk(obj):
68
+ if isinstance(obj, ScriptChunk):
69
+ return True
70
+ return False
71
+
72
+ def set(self, obj: Self):
73
+ if Script._is_script_object(obj) == False:
74
+ raise TypeError("obj must be of type Script")
75
+ self.chunks = obj.chunks
76
+
77
+ @staticmethod
78
+ def empty():
79
+ return Script()
80
+
81
+ @staticmethod
82
+ def from_buffer(buffer: bytearray) -> Self:
83
+ if not isinstance(buffer, (bytearray, bytes)):
84
+ raise ValueError("Invalid Argument: Buffer must be a Buffer.")
85
+ if isinstance(buffer, bytes):
86
+ buffer = bytearray(buffer)
87
+
88
+ script = Script()
89
+ script.chunks = []
90
+
91
+ br = BufferReader(buffer)
92
+ while not br.finished():
93
+ try:
94
+ opcodenum = br.read_uint8()
95
+
96
+ len_val = None
97
+ buf = None
98
+ if opcodenum > 0 and opcodenum < Opcode.OP_PUSHDATA1.value:
99
+ len_val = opcodenum
100
+ buf = br.read(len_val)
101
+ script.chunks.append(ScriptChunk(buf, len_val, opcodenum))
102
+ elif opcodenum == Opcode.OP_PUSHDATA1.value:
103
+ len_val = br.read_uint8()
104
+ buf = br.read(len_val)
105
+ script.chunks.append(ScriptChunk(buf, len_val, opcodenum))
106
+ elif opcodenum == Opcode.OP_PUSHDATA2.value:
107
+ len_val = br.read_uint16_le()
108
+ buf = br.read(len_val)
109
+ script.chunks.append(ScriptChunk(buf, len_val, opcodenum))
110
+ elif opcodenum == Opcode.OP_PUSHDATA4.value:
111
+ len_val = br.read_uint32_le()
112
+ buf = br.read(len_val)
113
+ script.chunks.append(ScriptChunk(buf, len_val, opcodenum))
114
+ else:
115
+ script.chunks.append(ScriptChunk(None, None, opcodenum))
116
+ except IndexError:
117
+ raise ValueError(
118
+ "Invalid script buffer: can't parse valid script from given buffer: "
119
+ + buffer.hex()
120
+ )
121
+ return script
122
+
123
+ def to_buffer(self) -> bytearray:
124
+ res = bytearray()
125
+ for chunk in self.chunks:
126
+ res.append(chunk.opcodenum)
127
+ if chunk.buf is not None:
128
+ if chunk.opcodenum < Opcode.OP_PUSHDATA1.value:
129
+ res.extend(chunk.buf)
130
+ elif chunk.opcodenum == Opcode.OP_PUSHDATA1.value:
131
+ res.append(chunk.len)
132
+ res.extend(chunk.buf)
133
+ elif chunk.opcodenum == Opcode.OP_PUSHDATA2.value:
134
+ res.extend(bytearray(chunk.len.to_bytes(2, "little")))
135
+ res.extend(chunk.buf)
136
+ elif chunk.opcodenum == Opcode.OP_PUSHDATA4.value:
137
+ res.extend(bytearray(chunk.len.to_bytes(4, "little")))
138
+ res.extend(chunk.buf)
139
+ return res
140
+
141
+ @staticmethod
142
+ def from_hex(hex_str: str) -> Self:
143
+ if not isinstance(hex_str, str):
144
+ raise TypeError("hex_str must be of type str")
145
+ if len(hex_str) > 0 and len(hex_str) % 2 == 0 and is_hex_string(hex_str):
146
+ return Script.from_buffer(bytearray.fromhex(hex_str))
147
+ else:
148
+ raise ValueError("Argument must be hex string: " + hex_str)
149
+
150
+ @staticmethod
151
+ def from_string(input_str: str) -> Self:
152
+ if not isinstance(input_str, str):
153
+ raise TypeError("input_str must be of type str")
154
+ if len(input_str) == 0:
155
+ return Script.empty()
156
+ if is_hex_string(input_str):
157
+ return Script.from_hex(input_str)
158
+
159
+ script = Script()
160
+ script.chunks = []
161
+
162
+ tokens = input_str.split(" ")
163
+ i = 0
164
+ while i < len(tokens):
165
+ token = tokens[i]
166
+ try:
167
+ opcodenum = ScriptOpcode(token).to_number()
168
+ except (KeyError, ValueError):
169
+ opcodenum = None
170
+
171
+ if opcodenum is None:
172
+ try:
173
+ opcodenum = int(token)
174
+ except ValueError:
175
+ raise ValueError("Invalid script: " + input_str)
176
+ if opcodenum > 0 and opcodenum < Opcode.OP_PUSHDATA1.value:
177
+ script.chunks.append(
178
+ ScriptChunk(bytearray.fromhex(tokens[i + 1][2:]), opcodenum, opcodenum)
179
+ )
180
+ i = i + 2
181
+ else:
182
+ raise ValueError("Invalid script: " + input_str)
183
+ elif (
184
+ opcodenum == Opcode.OP_PUSHDATA1.value
185
+ or opcodenum == Opcode.OP_PUSHDATA2.value
186
+ or opcodenum == Opcode.OP_PUSHDATA4.value
187
+ ):
188
+ if tokens[i + 2][0:2] != "0x":
189
+ raise ValueError("Pushdata data must start with 0x")
190
+ try:
191
+ int_token = int(tokens[i + 1])
192
+ except ValueError:
193
+ raise ValueError("Invalid script: " + input_str)
194
+ script.chunks.append(
195
+ ScriptChunk(bytearray.fromhex(tokens[i + 2][2:]), int_token, opcodenum)
196
+ )
197
+ i = i + 3
198
+ else:
199
+ script.chunks.append(ScriptChunk(None, None, opcodenum))
200
+ i = i + 1
201
+ return script
202
+
203
+ @staticmethod
204
+ def from_asm(input_str: str) -> Self:
205
+ if not isinstance(input_str, str):
206
+ raise TypeError("input_str must be of type str")
207
+ script = Script()
208
+ script.chunks = []
209
+
210
+ tokens = input_str.split(" ")
211
+ i = 0
212
+ while i < len(tokens):
213
+ token = tokens[i]
214
+ opcode = ScriptOpcode(token)
215
+ opcodenum = opcode.to_number()
216
+
217
+ if opcodenum is None:
218
+ buf = bytearray.fromhex(token)
219
+ buf_len = len(buf)
220
+ if buf_len >= 0 and buf_len < Opcode.OP_PUSHDATA1.value:
221
+ opcodenum = buf_len
222
+ elif buf_len < math.pow(2, 8):
223
+ opcodenum = Opcode.OP_PUSHDATA1.value
224
+ elif buf_len < math.pow(2, 16):
225
+ opcodenum = Opcode.OP_PUSHDATA2.value
226
+ elif buf_len < math.pow(2, 32):
227
+ opcodenum = Opcode.OP_PUSHDATA4.value
228
+ script.chunks.append(ScriptChunk(buf, buf_len, opcodenum))
229
+ i = i + 1
230
+ else:
231
+ script.chunks.append(ScriptChunk(None, None, opcodenum))
232
+ i = i + 1
233
+ return script
234
+
235
+ @staticmethod
236
+ def _chunk_to_string(chunk: ScriptChunk, to_asm=False) -> str:
237
+ if not isinstance(chunk, ScriptChunk):
238
+ raise TypeError("chunk must be of type ScriptChunk")
239
+ opcodenum = chunk.opcodenum
240
+ res_str = ""
241
+ if chunk.buf is None:
242
+ # no data chunk
243
+ if Opcode(opcodenum) is not None:
244
+ if to_asm == True:
245
+ if opcodenum == 0:
246
+ res_str = res_str + " 0"
247
+ elif opcodenum == 79:
248
+ res_str = res_str + " -1"
249
+ else:
250
+ res_str = res_str + " " + ScriptOpcode(opcodenum).to_string()
251
+ else:
252
+ res_str = res_str + " " + ScriptOpcode(opcodenum).to_string()
253
+ else:
254
+ numstr = format(opcodenum, "x")
255
+ if len(numstr) % 2 != 0:
256
+ numstr = "0" + numstr
257
+ if to_asm == True:
258
+ res_str = res_str + " " + numstr
259
+ else:
260
+ res_str = res_str + " " + "0x" + numstr
261
+ else:
262
+ # data chunk
263
+ if to_asm == False and (
264
+ opcodenum == Opcode.OP_PUSHDATA1.value
265
+ or opcodenum == Opcode.OP_PUSHDATA2.value
266
+ or opcodenum == Opcode.OP_PUSHDATA4.value
267
+ ):
268
+ res_str = res_str + " " + ScriptOpcode(opcodenum).to_string()
269
+ if chunk.len > 0:
270
+ if to_asm:
271
+ res_str = res_str + " " + chunk.buf.hex()
272
+ else:
273
+ res_str = res_str + " " + str(chunk.len) + " " + "0x" + chunk.buf.hex()
274
+ return res_str
275
+
276
+ def to_asm(self) -> str:
277
+ res_str = "".join(Script._chunk_to_string(chunk, True) for chunk in self.chunks)
278
+ return res_str[1:]
279
+
280
+ def to_string(self) -> str:
281
+ res_str = "".join(Script._chunk_to_string(chunk) for chunk in self.chunks)
282
+ return res_str[1:]
283
+
284
+ def __str__(self):
285
+ return self.to_string()
286
+
287
+ def to_hex(self) -> str:
288
+ return self.to_buffer().hex()
289
+
290
+ def add(self, param: ScriptElement | Self) -> Self:
291
+ """
292
+ Adds a script element to the end of the script.
293
+
294
+ Args:
295
+ param: a ScriptElement to add
296
+
297
+ Returns:
298
+ this script instance (self)
299
+ """
300
+ if (
301
+ not isinstance(param, str)
302
+ and not isinstance(param, int)
303
+ and not isinstance(param, bool)
304
+ and not isinstance(param, (bytes, bytearray))
305
+ and not isinstance(param, ScriptOpcode)
306
+ and not isinstance(param, Opcode)
307
+ and not isinstance(param, ScriptChunk)
308
+ and not isinstance(param, Script)
309
+ ):
310
+ raise TypeError("param must be of type ScriptElement")
311
+ self._add_by_type(param, False)
312
+ return self
313
+
314
+ def append(self, param: ScriptElement | Self) -> Self:
315
+ return self.add(param)
316
+
317
+ def prepend(self, param: ScriptElement | Self) -> Self:
318
+ """
319
+ Adds a script element at the start of the script.
320
+
321
+ Args:
322
+ param: a ScriptElement to add
323
+
324
+ Returns:
325
+ this script instance (self)
326
+ """
327
+ if (
328
+ not isinstance(param, str)
329
+ and not isinstance(param, int)
330
+ and not isinstance(param, bool)
331
+ and not isinstance(param, (bytes, bytearray))
332
+ and not isinstance(param, ScriptOpcode)
333
+ and not isinstance(param, Opcode)
334
+ and not isinstance(param, ScriptChunk)
335
+ and not isinstance(param, Script)
336
+ ):
337
+ raise TypeError("param must be of type ScriptElement")
338
+ self._add_by_type(param, True)
339
+ return self
340
+
341
+ @staticmethod
342
+ def int_to_script_num_bytes(value: int) -> bytearray:
343
+ if not isinstance(value, int):
344
+ raise TypeError("value must be of type int")
345
+
346
+ value_as_hex_str = format((value), "x")
347
+ if len(value_as_hex_str) % 2 != 0:
348
+ value_as_hex_str = "0" + value_as_hex_str
349
+ buf = bytearray.fromhex(value_as_hex_str)
350
+ # reverse buf to make it little endian
351
+ buf.reverse()
352
+ if value < 0:
353
+ if buf[0] & 0x80:
354
+ buf = bytearray([0x80]) + buf
355
+ else:
356
+ buf[0] = buf[0] | 0x80
357
+ else:
358
+ if buf[0] & 0x80:
359
+ buf = bytearray([0x00]) + buf
360
+ if len(buf) == 1 and buf[0] == 0:
361
+ buf = bytearray()
362
+ return buf
363
+
364
+ def _add_by_type(self, obj: ScriptElement | Self, prepend: bool):
365
+ if isinstance(obj, str):
366
+ self._add_opcode(obj, prepend)
367
+ elif isinstance(obj, bool):
368
+ if obj:
369
+ self._add_opcode(Opcode.OP_TRUE, prepend)
370
+ else:
371
+ self._add_opcode(Opcode.OP_FALSE, prepend)
372
+ elif isinstance(obj, int):
373
+ self._add_opcode(obj, prepend)
374
+ elif isinstance(obj, ScriptOpcode):
375
+ self._add_opcode(obj, prepend)
376
+ elif isinstance(obj, Opcode):
377
+ self._add_opcode(obj, prepend)
378
+ elif isinstance(obj, (bytes, bytearray)):
379
+ if isinstance(obj, bytes):
380
+ obj = bytearray(obj)
381
+ self._add_buffer(obj, prepend)
382
+ elif isinstance(obj, Script):
383
+ self.chunks.extend(obj.chunks)
384
+ elif Script._is_script_chunk(obj):
385
+ self._insert_at_position(obj, prepend)
386
+ else:
387
+ raise ValueError("Invalid script chunk")
388
+
389
+ def _insert_at_position(self, chunk: ScriptChunk, prepend: bool):
390
+ if prepend:
391
+ self.chunks = [chunk] + self.chunks
392
+ else:
393
+ self.chunks.append(chunk)
394
+
395
+ def _add_opcode(self, opcode: str | int | ScriptOpcode | Opcode, prepend: bool) -> Self:
396
+ if isinstance(opcode, int):
397
+ op = opcode
398
+ elif isinstance(opcode, ScriptOpcode):
399
+ op = opcode.to_number()
400
+ elif isinstance(opcode, Opcode):
401
+ op = opcode.value
402
+ else:
403
+ op = ScriptOpcode(opcode).to_number()
404
+ self._insert_at_position(ScriptChunk(None, None, op), prepend)
405
+ return self
406
+
407
+ def _add_buffer(self, buf: bytearray, prepend: bool) -> Self:
408
+ buf_len = len(buf)
409
+ if buf_len >= 0 and buf_len < Opcode.OP_PUSHDATA1.value:
410
+ opcodenum = buf_len
411
+ elif buf_len < math.pow(2, 8):
412
+ opcodenum = Opcode.OP_PUSHDATA1.value
413
+ elif buf_len < math.pow(2, 16):
414
+ opcodenum = Opcode.OP_PUSHDATA2.value
415
+ elif buf_len < math.pow(2, 32):
416
+ opcodenum = Opcode.OP_PUSHDATA4.value
417
+ else:
418
+ raise ValueError("You can't push that much data")
419
+ self._insert_at_position(ScriptChunk(buf, buf_len, opcodenum), prepend)
420
+ return self
421
+
422
+ def equals(self, script: Self) -> bool:
423
+ if not isinstance(script, Script):
424
+ raise TypeError("script must be of type Script")
425
+
426
+ if len(self.chunks) != len(script.chunks):
427
+ return False
428
+
429
+ for i in range(len(self.chunks)):
430
+ if self.chunks[i].buf != script.chunks[i].buf:
431
+ return False
432
+ elif self.chunks[i].opcodenum != script.chunks[i].opcodenum:
433
+ return False
434
+ return True
435
+
436
+ def find_and_delete(self, script: Self) -> Self:
437
+ """
438
+ Analogous to nexad's FindAndDelete. Find and delete equivalent chunks,
439
+ typically used with push data chunks. Note that this will find and delete
440
+ not just the same data, but the same data with the same push data op as
441
+ produced by default. i.e., if a pushdata in a tx does not use the minimal
442
+ pushdata op, then when you try to remove the data it is pushing, it will not
443
+ be removed, because they do not use the same pushdata op.
444
+ """
445
+ buf = script.to_buffer()
446
+ hex = buf.hex()
447
+ for i in range(len(self.chunks)):
448
+ script2 = Script()
449
+ script2.chunks = [self.chunks[i]]
450
+ buf2 = script2.to_buffer()
451
+ hex2 = buf2.hex()
452
+ if hex == hex2:
453
+ self.chunks.pop(i)
454
+ return self
455
+
456
+ def replace_chunk(self, index: int, replacement: Self) -> bool:
457
+ """
458
+ Replace the chunk at the given index with the chunks of `replacement`.
459
+
460
+ Args:
461
+ index: Zero-based index of the chunk to replace.
462
+ replacement: Script whose chunks will be spliced in at `index`.
463
+
464
+ Returns:
465
+ true if a replacement was made, otherwise false.
466
+ """
467
+ if index < 0 or index >= len(self.chunks):
468
+ return False
469
+ self.chunks[index : index + 1] = replacement.chunks
470
+ return True
471
+
472
+ def check_minimal_push(self, i: int) -> bool:
473
+ """
474
+ Comes from nexad's script interpreter CheckMinimalPush function
475
+
476
+ Returns:
477
+ true if the chunk {i} is the smallest way to push that particular data.
478
+ """
479
+ chunk = self.chunks[i]
480
+ buf = chunk.buf
481
+ opcodenum = chunk.opcodenum
482
+ if buf is None:
483
+ return True
484
+ len = len(buf)
485
+ if len == 0:
486
+ # could have used OP_0
487
+ return opcodenum == Opcode.OP_0.value
488
+ elif len == 1 and buf[0] >= 1 and buf[0] <= 16:
489
+ # could have used OP_1 ... OP_16
490
+ return False
491
+ elif len == 1 and buf[0] == 0x81:
492
+ # could have used OP_1NEGATE
493
+ return False
494
+ elif len <= 75:
495
+ # could have used a direct push (opcode iindicating number of bytes pushed + those bytes)
496
+ return opcodenum == len
497
+ elif len <= 255:
498
+ # could have used OP_PUSHDATA
499
+ return opcodenum == Opcode.OP_PUSHDATA1.value
500
+ elif len <= 65535:
501
+ # could have used OP_PUSHDATA2
502
+ return opcodenum == Opcode.OP_PUSHDATA2.value
503
+ return True
504
+
505
+ def get_signature_operations_count(self, accurate: bool = True) -> int:
506
+ """
507
+ Comes from bitcoind's script GetSigOpCount(boolean) function
508
+
509
+ Args:
510
+ accurate default true
511
+
512
+ Returns:
513
+ number of signature operations required by this script
514
+ """
515
+ n = 0
516
+ lastOpcode = Opcode.OP_INVALIDOPCODE.value
517
+ for i in range(len(self.chunks)):
518
+ opcode = self.chunks[i].opcodenum
519
+ if opcode == Opcode.OP_CHECKSIG.value or opcode == Opcode.OP_CHECKSIGVERIFY.value:
520
+ n = n + 1
521
+ elif (
522
+ opcode == Opcode.OP_CHECKMULTISIG.value
523
+ or opcode == Opcode.OP_CHECKMULTISIGVERIFY.value
524
+ ):
525
+ if (
526
+ accurate
527
+ and lastOpcode >= Opcode.OP_1.value
528
+ and lastOpcode <= Opcode.OP_16.value
529
+ ):
530
+ n = n + ScriptOpcode.decodeOP_N(lastOpcode)
531
+ else:
532
+ n = n + 20
533
+ lastOpcode = opcode
534
+ return n
535
+
536
+ def is_push_only(self) -> bool:
537
+ """
538
+ Returns:
539
+ true if the script is only composed of data pushing opcodes or small int opcodes (OP_0, OP_1, ..., OP_16)
540
+ """
541
+ for i in range(len(self.chunks)):
542
+ opcode = self.chunks[i].opcodenum
543
+ # if opcode == Opcode.OP_RESERVED:
544
+ # return False
545
+ # elif opcode == Opcode.OP_RETURN:
546
+ if opcode == Opcode.OP_RETURN.value:
547
+ return True
548
+ elif opcode > Opcode.OP_16.value:
549
+ return False
550
+ return True
551
+
552
+ def find_placeholder(self) -> int:
553
+ """
554
+ Find the index of the first placeholder chunk.
555
+
556
+ A placeholder is defined as:
557
+ - pushdata present (buf exists)
558
+ - length between 64 and 68 bytes
559
+ - first 64 bytes are all zero
560
+ - The optional trailing 0–4 bytes (positions 65–68) may be any value, ususally the sighash type bytes.
561
+
562
+ Returns:
563
+ The zero-based index of the first placeholder, or -1 if not found.
564
+ """
565
+ for i, chunk in enumerate(self.chunks):
566
+ if self._is_placeholder_chunk(chunk):
567
+ return i
568
+ return -1
569
+
570
+ def _is_placeholder_chunk(self, chunk: ScriptChunk) -> bool:
571
+ if (
572
+ not isinstance(chunk.buf, (bytes, bytearray))
573
+ or len(chunk.buf) < 64
574
+ or len(chunk.buf) > 68
575
+ ):
576
+ return False
577
+
578
+ return chunk.buf[:64] == bytearray(64)
579
+
580
+ def is_script_template_out(self) -> bool:
581
+ """
582
+ @remarks for well-known-1 template use {@link isPublicKeyTemplateOut}
583
+
584
+ Returns:
585
+ true if this is a pay to script template output script
586
+ """
587
+ len_chunks = len(self.chunks)
588
+ if len_chunks < 3:
589
+ return False
590
+
591
+ has_group = self.chunks[0].opcodenum != Opcode.OP_0.value
592
+ min_length = 3
593
+ template_index = 1
594
+ constraint_index = 2
595
+ if has_group:
596
+ min_length = 4
597
+ template_index = 2
598
+ constraint_index = 3
599
+
600
+ is_template = (
601
+ len_chunks >= min_length
602
+ and is_hash_buffer(self.chunks[template_index].buf)
603
+ and (
604
+ is_hash_buffer(self.chunks[constraint_index].buf)
605
+ or self.chunks[constraint_index].opcodenum == Opcode.OP_FALSE.value
606
+ )
607
+ )
608
+
609
+ if has_group:
610
+ valid_group_id = self.chunks[0].buf is not None and len(self.chunks[0].buf) >= 32
611
+ len_group_amount = len(self.chunks[1].buf) if self.chunks[1].buf is not None else 0
612
+ valid_group_amount = len_group_amount >= 2 and len_group_amount <= 8
613
+ is_template = is_template and valid_group_id and valid_group_amount
614
+
615
+ if is_template and len(self.chunks) > min_length:
616
+ visible_args = Script()
617
+ visible_args.chunks = self.chunks[min_length:]
618
+ is_template = visible_args.is_push_only()
619
+
620
+ return is_template
621
+
622
+ def is_empty(self) -> bool:
623
+ """
624
+ @returns `true` if the script is empty (has no chunks).
625
+ """
626
+ return len(self.chunks) == 0
627
+
628
+ def is_script_template_in(self) -> bool:
629
+ """
630
+ * Checks if this script is a valid pay to script template input script
631
+ *
632
+ * @returns true if this is a pay to script template form input script
633
+ * @remarks for well-known-1 template use {@link isPublicKeyTemplateIn}
634
+ """
635
+ # we do not know the length or content of satisfier / template / costraint scripts,
636
+ # only that must be push-only and template must exist
637
+ return len(self.chunks) > 1 and len(self.chunks[0].buf) > 0 and self.is_push_only()
638
+
639
+ def is_public_key_template_out(self) -> bool:
640
+ """
641
+ Returns:
642
+ returns true if this is a pay to pubkey template output script (well-known-1, p2pkt)
643
+ """
644
+ len_chunks = len(self.chunks)
645
+ if len_chunks < 3:
646
+ return False
647
+
648
+ has_group = self.chunks[0].opcodenum != Opcode.OP_0.value
649
+ min_length = 3
650
+ template_index = 1
651
+ constraint_index = 2
652
+ if has_group:
653
+ min_length = 4
654
+ template_index = 2
655
+ constraint_index = 3
656
+
657
+ is_template = (
658
+ len_chunks == min_length
659
+ and self.chunks[template_index].opcodenum == Opcode.OP_1.value
660
+ and is_hash_buffer(self.chunks[constraint_index].buf)
661
+ )
662
+
663
+ if has_group:
664
+ valid_group_id = self.chunks[0].buf is not None and len(self.chunks[0].buf) >= 32
665
+ len_group_amount = len(self.chunks[1].buf) if self.chunks[1].buf is not None else 0
666
+ valid_group_amount = len_group_amount >= 2 and len_group_amount <= 8
667
+ is_template = is_template and valid_group_id and valid_group_amount
668
+
669
+ return is_template
670
+
671
+ def is_public_key_template_in(self) -> bool:
672
+ """
673
+ Returns:
674
+ returns true if this is a pay to public key template input script
675
+ """
676
+ len_chunks = len(self.chunks)
677
+ if len_chunks != 2:
678
+ return False
679
+
680
+ pubkey_push_buf = self.chunks[0].buf
681
+ len_signature_buf = len(self.chunks[1].buf)
682
+ if len_signature_buf >= 64 and len_signature_buf <= 68 and len(pubkey_push_buf) == 34:
683
+ pubkey_buf = Script.from_buffer(pubkey_push_buf).chunks[0].buf
684
+ return len(pubkey_buf) == 33 and (pubkey_buf[0] == 0x03 or pubkey_buf[0] == 0x02)
685
+
686
+ return False
687
+
688
+ def is_public_key_hash_out(self) -> bool:
689
+ """
690
+ Returns:
691
+ returns true if this is a pay to pubkey hash output script
692
+ """
693
+ return (
694
+ len(self.chunks) == 5
695
+ and self.chunks[0].opcodenum == Opcode.OP_DUP.value
696
+ and self.chunks[1].opcodenum == Opcode.OP_HASH160.value
697
+ and len(self.chunks[2].buf) == 20
698
+ and self.chunks[3].opcodenum == Opcode.OP_EQUALVERIFY.value
699
+ and self.chunks[4].opcodenum == Opcode.OP_CHECKSIG.value
700
+ )
701
+
702
+ def is_public_key_hash_in(self) -> bool:
703
+ """
704
+ Returns:
705
+ returns {boolean} if this is a pay to public key hash input script
706
+ """
707
+ if len(self.chunks) != 2:
708
+ return False
709
+
710
+ signature_buf = self.chunks[0].buf
711
+ pubkey_buf = self.chunks[1].buf
712
+ if len(signature_buf) > 0 and len(pubkey_buf) > 0:
713
+ version = pubkey_buf[0]
714
+ if (version == 0x04 or version == 0x06 or version == 0x07) and len(pubkey_buf) == 65:
715
+ return True
716
+ elif (version == 0x03 or version == 0x02) and len(pubkey_buf) == 33:
717
+ return True
718
+ return False
719
+
720
+ def is_data_out(self) -> bool:
721
+ """
722
+ Returns:
723
+ returns true if this is a valid standard OP_RETURN output
724
+ """
725
+ step1 = (
726
+ len(self.chunks) >= 1
727
+ and self.chunks[0].opcodenum == Opcode.OP_RETURN.value
728
+ and len(self.to_buffer()) <= 233
729
+ )
730
+ if step1 == False:
731
+ return False
732
+ script2 = Script()
733
+ script2.chunks = self.chunks[1:]
734
+ return script2.is_push_only()
735
+
736
+ def is_token_description_out(self) -> bool:
737
+ """
738
+ Returns:
739
+ returns true if this is a valid Token Description OP_RETURN output
740
+ """
741
+ len_chunks = len(self.chunks)
742
+ step1 = (
743
+ len_chunks >= 2
744
+ and len_chunks < 8
745
+ and self.chunks[0].opcodenum == Opcode.OP_RETURN.value
746
+ and self.chunks[1].len == 4
747
+ )
748
+ script2 = Script()
749
+ script2.chunks = self.chunks[1:]
750
+ return step1 and script2.is_push_only()
751
+
752
+ def get_public_key(self) -> bytearray:
753
+ """
754
+ Will retrieve the Public Key buffer from p2pkt/p2pkh input scriptSig
755
+ """
756
+ is_pkh = self.is_public_key_hash_in()
757
+ is_pkt = self.is_public_key_template_in()
758
+ if is_pkh == False and is_pkt == False:
759
+ raise Exception("Can't retrieve PublicKey from a non-PKT or non-PKH input")
760
+ if is_pkh:
761
+ return self.chunks[1].buf
762
+ # if is_pkt:
763
+ return Script.from_buffer(self.chunks[0].buf).chunks[0].buf
764
+
765
+ def get_public_key_hash(self) -> bytearray:
766
+ """
767
+ Will retrieve the Public Key Hash buffer from p2pkh output scriptPubKey
768
+ """
769
+ if self.is_public_key_hash_out() == False:
770
+ raise Exception("Can't retrieve PublicKeyHash from a non-PKH output")
771
+ return self.chunks[2].buf
772
+
773
+ def get_template_hash(self) -> bytearray | Opcode:
774
+ """
775
+ Will retrieve the Template Hash from p2pkt/p2st output scriptPubKey
776
+
777
+ Returns:
778
+ returns OP_1 if its p2pkt, otherwise the template hash buffer
779
+ """
780
+ is_p2pkt = self.is_public_key_template_out()
781
+ is_p2st = self.is_script_template_out()
782
+ if is_p2pkt == False and is_p2st == False:
783
+ raise Exception("Can't retrieve TemplateHash from a non-PST output")
784
+ if is_p2pkt:
785
+ return Opcode.OP_1
786
+ has_group = self.chunks[0].opcodenum != Opcode.OP_0.value
787
+ if has_group:
788
+ return self.chunks[2].buf
789
+ return self.chunks[1].buf
790
+
791
+ def get_constraint_hash(self) -> bytearray | Opcode:
792
+ """
793
+ Will retrieve the Constraint Hash from p2pkt/p2st output scriptPubKey
794
+
795
+ Returns:
796
+ returns The constraint hash buffer, or OP_FALSE if not included
797
+ """
798
+ is_p2pkt = self.is_public_key_template_out()
799
+ is_p2st = self.is_script_template_out()
800
+ if is_p2pkt == False and is_p2st == False:
801
+ raise Exception("Can't retrieve ConstraintHash from a non-PST output")
802
+ has_group = self.chunks[0].opcodenum != Opcode.OP_0.value
803
+ constraint_index = 2
804
+ if has_group:
805
+ constraint_index = 3
806
+ if is_p2pkt:
807
+ return self.chunks[constraint_index].buf
808
+ # else is_p2st
809
+ if self.chunks[constraint_index].opcodenum == Opcode.OP_FALSE.value:
810
+ return Opcode.OP_FALSE
811
+ return self.chunks[constraint_index].buf
812
+
813
+ def get_visible_args(self) -> Self:
814
+ if not self.is_script_template_out():
815
+ raise ValueError("Invalid State: Can't retrieve Visible Args from a non-PST output")
816
+ script = Script()
817
+ if self.chunks[0].opcodenum != Opcode.OP_0.value:
818
+ script.chunks = list(self.chunks[4:])
819
+ else:
820
+ script.chunks = list(self.chunks[3:])
821
+ return script
822
+
823
+ def get_group_id_type(self) -> int:
824
+ """
825
+ Will retrieve the Group Identifier number from Token Description OP_RETURN output
826
+
827
+ This method doesn't check if the group id number is fit to NRC1/NRC2 etc.
828
+ """
829
+ if self.is_token_description_out() == False:
830
+ raise Exception("Can't retrieve GroupIdType from a non Token Description output")
831
+ # Note = this might not be right....
832
+ return int.from_bytes(self.chunks[1].buf, "little")
833
+
834
+ def get_group_data(self):
835
+ if not self.is_public_key_template_out() and not self.is_script_template_out():
836
+ raise Exception("Can't retrieve GroupData from a non-PST output")
837
+ if self.chunks[0].opcodenum != Opcode.OP_0.value:
838
+ id = self.chunks[0].buf
839
+ amount = self.chunks[1].buf
840
+ return id, amount
841
+ return None, None