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,506 @@
1
+ from datetime import datetime, timezone
2
+ import math
3
+ from typing import Self
4
+
5
+ from src.common.class_types import TypedClass
6
+ from src.common.types import InputType
7
+ from src.core.script.opcode import Opcode
8
+ from src.core.script.script import Script
9
+ from src.core.script.script_factory import ScriptFactory
10
+ from src.core.transaction.input.input import Input
11
+ from src.core.transaction.input.public_key_hash import PublicKeyHashInput
12
+ from src.core.transaction.input.public_key_template import PublicKeyTemplateInput
13
+ from src.core.transaction.input.script_template import ScriptTemplateInput
14
+ from src.core.transaction.output import Output
15
+ from src.encoding.buffer_reader import BufferReader
16
+ from src.encoding.buffer_writer import BufferWriter
17
+ from src.crypto.hash import Hash
18
+ from src.utils.common_utils import *
19
+
20
+ """
21
+ Represents a Nexa transaction
22
+
23
+ """
24
+
25
+
26
+ class Transaction(TypedClass):
27
+ """
28
+ Version of this transaction
29
+ """
30
+
31
+ CURRENT_VERSION: int = 0
32
+
33
+ """
34
+ Fee per byte for estimating fees
35
+ """
36
+ FEE_PER_BYTE: int = 3
37
+
38
+ """
39
+ Minimum output amount to be considered not dust
40
+ """
41
+ DUST_AMOUNT: int = 546
42
+
43
+ """
44
+ Maximum amount of money in NEXA
45
+ """
46
+ MAX_MONEY: int = 21000000 * 10**8
47
+
48
+ """
49
+ NLocktime value at or below which, the value is the block height; above which, it is the UNIX timestamp
50
+ """
51
+ NLOCKTIME_BLOCKHEIGHT_LIMIT: int = 5 * 10**8
52
+
53
+ """
54
+ Maximum nLockTime value
55
+ """
56
+ NLOCKTIME_MAX_VALUE: int = 4294967295
57
+
58
+ version: int
59
+ inputs: list
60
+ outputs: list
61
+ n_lock_time: int
62
+ _fee_per_byte: int
63
+ _fee: int
64
+ _change_index: int
65
+ _change_script: Script
66
+
67
+ def __init__(self, serialised_tx=None):
68
+ super().__init__()
69
+ self.version = Transaction.CURRENT_VERSION
70
+ self.inputs = []
71
+ self.outputs = []
72
+ self.n_lock_time = 0 # nLockTime is 0 by default in the full node
73
+ self._fee_per_byte = None
74
+ self._fee = None
75
+ self._change_index = None
76
+ self._change_script = None
77
+ if serialised_tx is not None:
78
+ if isinstance(serialised_tx, (bytes, bytearray)):
79
+ self.from_buffer(serialised_tx)
80
+ elif isinstance(serialised_tx, str) and is_hex_string(serialised_tx):
81
+ self.from_string(serialised_tx)
82
+ elif isinstance(serialised_tx, (dict, Transaction)):
83
+ self.from_object(serialised_tx)
84
+ else:
85
+ raise TypeError("Must provide an object or string to deserialize a transaction")
86
+ self._enforce_attribute_types()
87
+
88
+ @property
89
+ def id(self):
90
+ writer = BufferWriter()
91
+ writer.write(self._get_tx_idem())
92
+ writer.write(self._get_tx_satisfier())
93
+ return bytearray(reversed(Hash.sha256sha256(writer.to_buffer()))).hex()
94
+
95
+ @property
96
+ def idem(self):
97
+ return bytearray(reversed(self._get_tx_idem())).hex()
98
+
99
+ @property
100
+ def input_amount(self):
101
+ return sum((input_.amount or 0) for input_ in self.inputs)
102
+
103
+ @property
104
+ def output_amount(self):
105
+ return sum((output.value for output in self.outputs))
106
+
107
+ def _get_tx_idem(self) -> bytearray:
108
+ return bytearray(Hash.sha256sha256(self._to_idem_buffer()))
109
+
110
+ def _get_tx_satisfier(self) -> bytearray:
111
+ return bytearray(Hash.sha256sha256(self._to_satisfier_buffer()))
112
+
113
+ @staticmethod
114
+ def shallow_copy(transaction) -> "Transaction":
115
+ return Transaction(transaction.to_buffer())
116
+
117
+ def is_coinbase(self):
118
+ return len(self.inputs) == 0
119
+
120
+ def get_serialization_error(self, opts=None):
121
+ if self._invalid_amount():
122
+ return ValueError("Output satoshis are invalid")
123
+ if len(self.outputs) > 256:
124
+ return ValueError("Too many outputs (> 256)")
125
+ if len(self.inputs) > 256:
126
+ return ValueError("Too many inputs (> 256)")
127
+ unspent = self.get_unspent_value()
128
+ unspent_error = None
129
+ if unspent < 0:
130
+ if not (opts and opts.get("disableMoreOutputThanInput")):
131
+ unspent_error = ValueError("Invalid outputs amount sum")
132
+ else:
133
+ unspent_error = self._has_fee_error(unspent)
134
+ return unspent_error or self._has_dust_outputs(opts) or self._is_missing_signatures(opts)
135
+
136
+ def _invalid_amount(self):
137
+ return any((output.invalid_value() for output in self.outputs))
138
+
139
+ def _has_dust_outputs(self, opts):
140
+ if opts and opts.get("disableDustOutputs"):
141
+ return None
142
+ has_dust = any(
143
+ (
144
+ output.value < Transaction.DUST_AMOUNT and not output.script_pubkey.is_data_out()
145
+ for output in self.outputs
146
+ )
147
+ )
148
+ return ValueError("Dust amount detected in one output") if has_dust else None
149
+
150
+ def _has_fee_error(self, unspent):
151
+ if self._fee is not None and self._fee != unspent:
152
+ return ValueError(f"Unspent value is {unspent} but specified fee is {self._fee}")
153
+ return None
154
+
155
+ def _estimate_fee(self):
156
+ estimated_size = self._estimate_size()
157
+ available = self.get_unspent_value()
158
+ fee_rate = (
159
+ self._fee_per_byte if self._fee_per_byte is not None else Transaction.FEE_PER_BYTE
160
+ )
161
+
162
+ def calc_fee(size):
163
+ return size * fee_rate
164
+
165
+ fee_with_change = math.ceil(
166
+ calc_fee(estimated_size) + calc_fee(self._estimate_size_of_change_output())
167
+ )
168
+ if (
169
+ self._change_script is None
170
+ or available <= fee_with_change
171
+ or available - fee_with_change < Transaction.DUST_AMOUNT
172
+ ):
173
+ return available
174
+ return fee_with_change
175
+
176
+ def _estimate_size_of_change_output(self):
177
+ if self._change_script is None:
178
+ return 0
179
+ script_len = len(self._change_script.to_buffer())
180
+ return 1 + 8 + len(BufferWriter.write_varint_buf(script_len)) + script_len
181
+
182
+ def _estimate_size(self):
183
+ result = 4 + 1
184
+ result += 1 if len(self.inputs) < 253 else 3
185
+ for input_ in self.inputs:
186
+ result += input_.estimate_size()
187
+ result += 1 if len(self.outputs) < 253 else 3
188
+ for output in self.outputs:
189
+ result += len(output.to_buffer_writer().to_buffer())
190
+ return result
191
+
192
+ def _is_missing_signatures(self, opts):
193
+ if opts and opts.get("disableIsFullySigned"):
194
+ return None
195
+ if not self.is_fully_signed():
196
+ return ValueError("Some inputs have not been fully signed")
197
+ return None
198
+
199
+ def is_fully_signed(self):
200
+ """
201
+ Returns true if all inputs in the transaction are fully signed,
202
+ ignoring read-only inputs without script sigs.
203
+ """
204
+ inputs = [
205
+ input_
206
+ for input_ in self.inputs
207
+ if not (input_.type == InputType.READ_ONLY and input_.script_sig.is_empty())
208
+ ]
209
+ if any((input_.is_fully_signed.__func__ is Input.is_fully_signed for input_ in inputs)):
210
+ raise ValueError(
211
+ "Unable to verify signature: Unrecognized script kind, or not enough information to execute script."
212
+ " This usually happens when creating a transaction from a serialized transaction"
213
+ )
214
+ return all((input_.is_fully_signed() for input_ in inputs))
215
+
216
+ def has_all_utxo_info(self):
217
+ return all(
218
+ (
219
+ getattr(input_, "output", None) is not None
220
+ and input_.output.script_pubkey is not None
221
+ for input_ in self.inputs
222
+ )
223
+ )
224
+
225
+ def get_unspent_value(self):
226
+ return self.input_amount - self.output_amount
227
+
228
+ def get_fee(self):
229
+ if self.is_coinbase():
230
+ return 0
231
+ if self._fee is not None:
232
+ return self._fee
233
+ if self._change_script is None:
234
+ return self.get_unspent_value()
235
+ return self._estimate_fee()
236
+
237
+ def estimate_required_fee(self):
238
+ fee_rate = (
239
+ self._fee_per_byte if self._fee_per_byte is not None else Transaction.FEE_PER_BYTE
240
+ )
241
+ return self._estimate_size() * fee_rate
242
+
243
+ def clear_signatures(self):
244
+ for input_ in self.inputs:
245
+ input_.clear_signatures()
246
+
247
+ def checked_serialize(self, opts=None):
248
+ error = self.get_serialization_error(opts)
249
+ if error:
250
+ raise error
251
+ return self.to_string()
252
+
253
+ def to_string(self):
254
+ return self.to_buffer().hex()
255
+
256
+ def __str__(self):
257
+ return f"<Transaction: {self.to_string()}>"
258
+
259
+ def from_string(self, string):
260
+ return self.from_buffer(bytes.fromhex(string))
261
+
262
+ def from_buffer(self, buffer):
263
+ br = BufferReader(bytearray(buffer))
264
+ self._from_buffer_reader(br)
265
+ return self
266
+
267
+ def from_buffer_reader(self, reader):
268
+ if reader is None:
269
+ raise Exception("reader is required")
270
+ self._from_buffer_reader(reader)
271
+ return self
272
+
273
+ def _from_buffer_reader(self, br):
274
+ self.version = br.read_uint8()
275
+ input_count = br.read_varint()
276
+ for _ in range(input_count):
277
+ self.inputs.append(Input.from_buffer_reader(br))
278
+ output_count = br.read_varint()
279
+ for _ in range(output_count):
280
+ self.outputs.append(Output.from_buffer_reader(br))
281
+ self.n_lock_time = br.read_uint32_le()
282
+ return self
283
+
284
+ def serialize(self, unsafe=None):
285
+ if unsafe is True or (isinstance(unsafe, dict) and unsafe.get("disableAll")):
286
+ return self.unchecked_serialize()
287
+ else:
288
+ return self.checked_serialize(unsafe if isinstance(unsafe, dict) else None)
289
+
290
+ def unchecked_serialize(self):
291
+ return self.to_string()
292
+
293
+ def set_fee(self, amount):
294
+ if not isinstance(amount, (int, float)) or isinstance(amount, bool):
295
+ raise ValueError("Invalid Argument: amount must be a number. ")
296
+ self._fee = amount
297
+ self._update_change_output()
298
+ return self
299
+
300
+ def set_fee_per_byte(self, amount):
301
+ if not isinstance(amount, (int, float)) or isinstance(amount, bool):
302
+ raise ValueError("Invalid Argument: amount must be a number. ")
303
+ self._fee_per_byte = amount
304
+ self._update_change_output()
305
+ return self
306
+
307
+ def add_output(self, output):
308
+ if not isinstance(output, Output):
309
+ raise TypeError(
310
+ f"Invalid Argument for output, expected Output but got {type(output).__name__}"
311
+ )
312
+ self.outputs.append(output)
313
+ self._update_change_output()
314
+ return self
315
+
316
+ def remove_output(self, index):
317
+ self._remove_output(index)
318
+ self._update_change_output()
319
+ return self
320
+
321
+ def _remove_output(self, index):
322
+ self.outputs = [output for i, output in enumerate(self.outputs) if i != index]
323
+
324
+ def clear_outputs(self):
325
+ self.outputs = []
326
+ self.clear_signatures()
327
+ self._update_change_output()
328
+ return self
329
+
330
+ def update_output_amount(self, index, sats):
331
+ self.outputs[index].value = int(sats)
332
+ self._update_change_output()
333
+ return self
334
+
335
+ def set_change_output(self, address):
336
+ if address is None:
337
+ raise ValueError("Invalid Argument: address is required. ")
338
+ self._change_script = ScriptFactory.build_out_from_address(address)
339
+ self._update_change_output()
340
+ return self
341
+
342
+ def get_change_output(self):
343
+ if self._change_index is not None:
344
+ return self.outputs[self._change_index]
345
+ return None
346
+
347
+ def _update_change_output(self):
348
+ if self._change_script is None:
349
+ return
350
+ self.clear_signatures()
351
+ if self._change_index is not None:
352
+ self._remove_output(self._change_index)
353
+ available = self.get_unspent_value()
354
+ fee = self.get_fee()
355
+ change_amount = available - fee
356
+ if change_amount >= Transaction.DUST_AMOUNT:
357
+ self._change_index = len(self.outputs)
358
+ self.outputs.append(Output(change_amount, self._change_script))
359
+ else:
360
+ self._change_index = None
361
+
362
+ def unchecked_add_input(self, input_):
363
+ if not isinstance(input_, Input):
364
+ raise TypeError(
365
+ f"Invalid Argument for input, expected Input but got {type(input_).__name__}"
366
+ )
367
+ self.inputs.append(input_)
368
+ self._update_change_output()
369
+ return self
370
+
371
+ def add_input(self, input_, output_script=None, amount=None):
372
+ if not isinstance(input_, Input):
373
+ raise TypeError(
374
+ f"Invalid Argument for input, expected Input but got {type(input_).__name__}"
375
+ )
376
+ if getattr(input_, "output", None) is None and (output_script is None or amount is None):
377
+ raise ValueError("Need information about the UTXO script and amount")
378
+ if (
379
+ getattr(input_, "output", None) is None
380
+ and output_script is not None
381
+ and amount is not None
382
+ ):
383
+ script_pubkey = (
384
+ output_script if isinstance(output_script, Script) else Script(output_script)
385
+ )
386
+ input_.output = Output(int(amount), script_pubkey)
387
+ return self.unchecked_add_input(input_)
388
+
389
+ def remove_input(self, outpoint):
390
+ self.inputs = [input_ for input_ in self.inputs if input_.outpoint.hex() != outpoint]
391
+ self._update_change_output()
392
+ return self
393
+
394
+ def set_lock_time(self, locktime):
395
+ if not isinstance(locktime, (int, float)) or isinstance(locktime, bool):
396
+ raise ValueError("Invalid Argument: locktime. must be a number")
397
+ for input_ in self.inputs:
398
+ if input_.sequence_number == Input.SEQUENCE_FINAL:
399
+ input_.sequence_number = Input.SEQUENCE_FINAL - 1
400
+ self.n_lock_time = locktime
401
+ return self
402
+
403
+ def get_lock_time(self):
404
+ if not self.n_lock_time:
405
+ return None
406
+ if self.n_lock_time < Transaction.NLOCKTIME_BLOCKHEIGHT_LIMIT:
407
+ return self.n_lock_time
408
+ return datetime.fromtimestamp(self.n_lock_time, tz=timezone.utc)
409
+
410
+ def to_buffer(self):
411
+ return self.to_buffer_writer().to_buffer()
412
+
413
+ def to_buffer_writer(self, writer=None, with_inputs_scripts=True):
414
+ if writer is None:
415
+ writer = BufferWriter()
416
+ writer.write_uint8(self.version)
417
+ writer.write_varint(len(self.inputs))
418
+ for input_ in self.inputs:
419
+ input_.to_buffer_writer(writer, with_inputs_scripts)
420
+ writer.write_varint(len(self.outputs))
421
+ for output in self.outputs:
422
+ output.to_buffer_writer(writer)
423
+ writer.write_uint32_le(self.n_lock_time)
424
+ return writer
425
+
426
+ def _to_idem_buffer(self):
427
+ return self.to_buffer_writer(None, False).to_buffer()
428
+
429
+ def _to_satisfier_buffer(self):
430
+ writer = BufferWriter()
431
+ writer.write_uint32_le(len(self.inputs))
432
+ for input_ in self.inputs:
433
+ writer.write(input_.script_sig.to_buffer())
434
+ writer.write_uint8(Opcode.OP_INVALIDOPCODE.value)
435
+ return writer.to_buffer()
436
+
437
+ def to_object(self):
438
+ obj = {
439
+ "id": self.id,
440
+ "idem": self.idem,
441
+ "version": self.version,
442
+ "inputs": [input_.to_object() for input_ in self.inputs],
443
+ "outputs": [output.to_object() for output in self.outputs],
444
+ "nLockTime": self.n_lock_time,
445
+ }
446
+ if self._change_script is not None:
447
+ obj["changeScript"] = self._change_script.to_hex()
448
+ if self._change_index is not None:
449
+ obj["changeIndex"] = self._change_index
450
+ if self._fee is not None:
451
+ obj["fee"] = self._fee
452
+ if self._fee_per_byte is not None:
453
+ obj["feePerByte"] = self._fee_per_byte
454
+ return obj
455
+
456
+ def from_object(self, transaction):
457
+ if not isinstance(transaction, (dict, Transaction)):
458
+ raise ValueError("Invalid Argument: transaction. ")
459
+ if isinstance(transaction, Transaction):
460
+ transaction = transaction.to_object()
461
+ self.n_lock_time = transaction.get("nLockTime", 0)
462
+ self.version = transaction.get("version", 0)
463
+ for input_data in transaction.get("inputs", []):
464
+ if input_data.get("output") is None or input_data["output"].get("scriptPubKey") is None:
465
+ self.unchecked_add_input(Input(input_data))
466
+ continue
467
+ script = Script(input_data["output"]["scriptPubKey"])
468
+ if script.is_public_key_hash_out():
469
+ txin = PublicKeyHashInput(input_data)
470
+ elif script.is_public_key_template_out():
471
+ txin = PublicKeyTemplateInput(input_data)
472
+ elif script.is_script_template_out():
473
+ if "templateData" in input_data:
474
+ txin = ScriptTemplateInput(input_data)
475
+ else:
476
+ txin = Input(input_data)
477
+ else:
478
+ raise ValueError(f"Unsupported input script type: {script.to_hex()}")
479
+ self.add_input(txin)
480
+ for output_data in transaction.get("outputs", []):
481
+ self.add_output(Output.from_object(output_data))
482
+ if transaction.get("changeIndex") is not None:
483
+ self._change_index = transaction["changeIndex"]
484
+ if transaction.get("changeScript") is not None:
485
+ self._change_script = Script(transaction["changeScript"])
486
+ if transaction.get("fee") is not None:
487
+ self._fee = transaction["fee"]
488
+ if transaction.get("feePerByte") is not None:
489
+ self._fee_per_byte = transaction["feePerByte"]
490
+ self._check_consistency(transaction)
491
+ return self
492
+
493
+ def _check_consistency(self, transaction):
494
+ if self._change_index is not None:
495
+ if self._change_script is None:
496
+ raise ValueError("Invalid State: Change script is expected.")
497
+ if self._change_index >= len(self.outputs) or self.outputs[self._change_index] is None:
498
+ raise ValueError("Invalid State: Change index points to undefined output.")
499
+ if (
500
+ self.outputs[self._change_index].script_pubkey.to_hex()
501
+ != self._change_script.to_hex()
502
+ ):
503
+ raise ValueError("Invalid State: Change output has an unexpected script.")
504
+ if transaction.get("id"):
505
+ if transaction["id"] != self.id:
506
+ raise ValueError("Invalid State: Id in object does not match transaction id.")