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,154 @@
|
|
|
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
|
+
from src.keys.public_key import PublicKey
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ScriptTemplateInput(Input):
|
|
13
|
+
"""
|
|
14
|
+
Represents a special kind of input of generic ScriptTemplate kind.
|
|
15
|
+
|
|
16
|
+
WARNING: this is a general case where the signature is similar to p2pkt and added to scriptSig as push signature data.
|
|
17
|
+
If you have complex smart contract, consider extending this class (or Input class) and implement the necessary logic,
|
|
18
|
+
or sign it manually.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
template_script: Script
|
|
22
|
+
constraint_script: Script | None
|
|
23
|
+
public_key: PublicKey | None
|
|
24
|
+
|
|
25
|
+
def __init__(self, arg: dict):
|
|
26
|
+
if not isinstance(arg.get("templateData"), dict):
|
|
27
|
+
raise ValueError("Invalid Argument: Missing template object. ")
|
|
28
|
+
if not isinstance(arg.get("output"), (dict, Output)):
|
|
29
|
+
raise ValueError("Invalid Argument: Missing associated utxo. ")
|
|
30
|
+
|
|
31
|
+
td = arg["templateData"]
|
|
32
|
+
if not (
|
|
33
|
+
isinstance(td.get("templateScript"), Script)
|
|
34
|
+
or isinstance(td.get("templateScript"), str)
|
|
35
|
+
):
|
|
36
|
+
raise ValueError("Invalid Argument: Invalid template. ")
|
|
37
|
+
if not (
|
|
38
|
+
isinstance(td.get("constraintScript"), Script)
|
|
39
|
+
or isinstance(td.get("constraintScript"), str)
|
|
40
|
+
or td.get("constraintScript") is None
|
|
41
|
+
):
|
|
42
|
+
raise ValueError("Invalid Argument: Invalid constraint. ")
|
|
43
|
+
if not (
|
|
44
|
+
isinstance(td.get("publicKey"), PublicKey)
|
|
45
|
+
or isinstance(td.get("publicKey"), str)
|
|
46
|
+
or td.get("publicKey") is None
|
|
47
|
+
):
|
|
48
|
+
raise ValueError("Invalid Argument: Invalid pubkey. ")
|
|
49
|
+
|
|
50
|
+
super().__init__(arg)
|
|
51
|
+
self.template_script = (
|
|
52
|
+
Script.from_string(td["templateScript"])
|
|
53
|
+
if isinstance(td["templateScript"], str)
|
|
54
|
+
else td["templateScript"]
|
|
55
|
+
)
|
|
56
|
+
constraint_script = td.get("constraintScript")
|
|
57
|
+
self.constraint_script = (
|
|
58
|
+
Script.from_string(constraint_script)
|
|
59
|
+
if isinstance(constraint_script, str)
|
|
60
|
+
else constraint_script
|
|
61
|
+
)
|
|
62
|
+
public_key = td.get("publicKey")
|
|
63
|
+
self.public_key = (
|
|
64
|
+
PublicKey.from_string(public_key) if isinstance(public_key, str) else public_key
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
template_hash = self.output.script_pubkey.get_template_hash()
|
|
68
|
+
if not (
|
|
69
|
+
isinstance(template_hash, (bytearray, bytes))
|
|
70
|
+
and template_hash == Hash.sha256ripemd160(self.template_script.to_buffer())
|
|
71
|
+
):
|
|
72
|
+
raise ValueError(
|
|
73
|
+
"Invalid State: Provided template doesn't match to the provided output"
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
constraint_hash = self.output.script_pubkey.get_constraint_hash()
|
|
77
|
+
if isinstance(constraint_hash, (bytearray, bytes)):
|
|
78
|
+
if not (self.constraint_script is not None and not self.constraint_script.is_empty()):
|
|
79
|
+
raise ValueError(
|
|
80
|
+
"Invalid State: Provided constraint must not be undefined or empty if constraint hash is provided in output"
|
|
81
|
+
)
|
|
82
|
+
if not constraint_hash == Hash.sha256ripemd160(self.constraint_script.to_buffer()):
|
|
83
|
+
raise ValueError(
|
|
84
|
+
"Invalid State: Provided constraint doesn't match to the provided output"
|
|
85
|
+
)
|
|
86
|
+
else:
|
|
87
|
+
if constraint_hash != Opcode.OP_FALSE:
|
|
88
|
+
raise ValueError(
|
|
89
|
+
"Invalid State: Provided output has invalid constraint hash, must be a hash or OP_FALSE"
|
|
90
|
+
)
|
|
91
|
+
if self.constraint_script is not None:
|
|
92
|
+
raise ValueError(
|
|
93
|
+
"Invalid State: Provided constraint must be undefined if constraint hash is OP_FALSE"
|
|
94
|
+
)
|
|
95
|
+
self._enforce_attribute_types()
|
|
96
|
+
|
|
97
|
+
def to_object(self):
|
|
98
|
+
input_obj = super().to_object()
|
|
99
|
+
return {
|
|
100
|
+
**input_obj,
|
|
101
|
+
"templateData": {
|
|
102
|
+
"templateScript": self.template_script.to_hex(),
|
|
103
|
+
"constraintScript": self.constraint_script.to_hex()
|
|
104
|
+
if self.constraint_script is not None
|
|
105
|
+
else None,
|
|
106
|
+
"publicKey": self.public_key.to_string() if self.public_key is not None else None,
|
|
107
|
+
},
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
@staticmethod
|
|
111
|
+
def from_object(obj) -> Self:
|
|
112
|
+
if not isinstance(obj, dict):
|
|
113
|
+
raise ValueError("Invalid Argument: obj. ")
|
|
114
|
+
return ScriptTemplateInput(obj)
|
|
115
|
+
|
|
116
|
+
def get_subscript(self) -> Script:
|
|
117
|
+
return self.template_script
|
|
118
|
+
|
|
119
|
+
def can_sign(self, private_key) -> bool:
|
|
120
|
+
return (
|
|
121
|
+
self.public_key.to_string() if self.public_key is not None else None
|
|
122
|
+
) == private_key.pubkey.to_string()
|
|
123
|
+
|
|
124
|
+
def is_fully_signed(self) -> bool:
|
|
125
|
+
return (
|
|
126
|
+
self.script_sig.is_script_template_in()
|
|
127
|
+
and self.template_script.equals(Script.from_buffer(self.script_sig.chunks[0].buf))
|
|
128
|
+
and (
|
|
129
|
+
not isinstance(self.constraint_script, Script)
|
|
130
|
+
or self.constraint_script.equals(Script.from_buffer(self.script_sig.chunks[1].buf))
|
|
131
|
+
)
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
def add_signature(self, signature) -> Self:
|
|
135
|
+
satisfier = Script.empty().add(signature.to_tx_satisfier())
|
|
136
|
+
self.script_sig = ScriptFactory.build_script_template_in(
|
|
137
|
+
self.template_script, self.constraint_script, satisfier
|
|
138
|
+
)
|
|
139
|
+
return self
|
|
140
|
+
|
|
141
|
+
def estimate_size(self) -> int:
|
|
142
|
+
if self.is_fully_signed():
|
|
143
|
+
return super().estimate_size()
|
|
144
|
+
script_size = self._estimate_script_size()
|
|
145
|
+
|
|
146
|
+
# type + outpoint + scriptlen + script + sequence + amount
|
|
147
|
+
return 1 + 32 + (1 if script_size < 253 else 3) + script_size + 4 + 8
|
|
148
|
+
|
|
149
|
+
def _estimate_script_size(self) -> int:
|
|
150
|
+
# here we calculate by template size, constraint size if not op_false, and satisfier size as sigsize (1 + 64)
|
|
151
|
+
s = Script.empty().add(self.template_script.to_buffer())
|
|
152
|
+
if isinstance(self.constraint_script, Script):
|
|
153
|
+
s.add(self.constraint_script.to_buffer())
|
|
154
|
+
return len(s.to_buffer()) + 1 + 64
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
from typing import Self
|
|
2
|
+
|
|
3
|
+
from src.common.class_types import TypedClass
|
|
4
|
+
from src.common.types import OutputType
|
|
5
|
+
from src.core.address.address import Address
|
|
6
|
+
from src.core.address.address_formatter import AddressType
|
|
7
|
+
from src.core.grouptoken import GroupToken
|
|
8
|
+
from src.core.network.network_manager import networks
|
|
9
|
+
from src.core.script.script import Script
|
|
10
|
+
from src.encoding.buffer_reader import BufferReader
|
|
11
|
+
from src.encoding.buffer_writer import BufferWriter
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Output(TypedClass):
|
|
15
|
+
type: OutputType
|
|
16
|
+
_value: int
|
|
17
|
+
_script_pubkey: Script
|
|
18
|
+
value: int | float | str
|
|
19
|
+
script_pubkey: Script | str | int
|
|
20
|
+
|
|
21
|
+
def __init__(self, value, script_pubkey: Script | str, type: OutputType = OutputType.INFER):
|
|
22
|
+
super().__init__()
|
|
23
|
+
self.type = type
|
|
24
|
+
self._value = 0
|
|
25
|
+
self._script_pubkey = None
|
|
26
|
+
self._enforce_attribute_types()
|
|
27
|
+
self.value = value
|
|
28
|
+
self.script_pubkey = script_pubkey
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def value(self) -> int:
|
|
32
|
+
return self._value
|
|
33
|
+
|
|
34
|
+
@value.setter
|
|
35
|
+
def value(self, sats):
|
|
36
|
+
if isinstance(sats, float):
|
|
37
|
+
raise ValueError(f"Cannot convert {sats} to a BigInt")
|
|
38
|
+
if isinstance(sats, str):
|
|
39
|
+
try:
|
|
40
|
+
sats = int(sats)
|
|
41
|
+
except ValueError:
|
|
42
|
+
raise ValueError(f"Cannot convert {sats} to a BigInt")
|
|
43
|
+
else:
|
|
44
|
+
sats = int(sats)
|
|
45
|
+
if not sats >= 0:
|
|
46
|
+
raise ValueError("Invalid Argument: Output value is not a natural bigint. ")
|
|
47
|
+
self._value = sats
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def script_pubkey(self) -> Script:
|
|
51
|
+
return self._script_pubkey
|
|
52
|
+
|
|
53
|
+
@script_pubkey.setter
|
|
54
|
+
def script_pubkey(self, script: Script | str):
|
|
55
|
+
if self._script_pubkey is not None:
|
|
56
|
+
self.type = OutputType.INFER
|
|
57
|
+
|
|
58
|
+
if isinstance(script, Script):
|
|
59
|
+
self._script_pubkey = script
|
|
60
|
+
elif isinstance(script, str):
|
|
61
|
+
self._script_pubkey = Script.from_string(script)
|
|
62
|
+
else:
|
|
63
|
+
raise TypeError("Invalid argument type: script")
|
|
64
|
+
|
|
65
|
+
# in case we replace script or type wasn't passed in c'tor, we need to define the output type
|
|
66
|
+
if self.type == OutputType.INFER:
|
|
67
|
+
self.type = (
|
|
68
|
+
OutputType.TEMPLATE
|
|
69
|
+
if (
|
|
70
|
+
self._script_pubkey.is_public_key_template_out()
|
|
71
|
+
or self._script_pubkey.is_script_template_out()
|
|
72
|
+
)
|
|
73
|
+
else OutputType.SATOSCRIPT
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def address(self) -> str | None:
|
|
78
|
+
if self._script_pubkey.is_public_key_template_out():
|
|
79
|
+
return Address.from_script_template(
|
|
80
|
+
self._script_pubkey.get_template_hash(), self._script_pubkey.get_constraint_hash()
|
|
81
|
+
).to_string()
|
|
82
|
+
elif self._script_pubkey.is_public_key_hash_out():
|
|
83
|
+
return Address(
|
|
84
|
+
self._script_pubkey.get_public_key_hash(),
|
|
85
|
+
networks.default_network,
|
|
86
|
+
AddressType.PAY_TO_PUBLIC_KEY_HASH,
|
|
87
|
+
).to_string()
|
|
88
|
+
elif self._script_pubkey.is_script_template_out():
|
|
89
|
+
return Address.from_script_template(
|
|
90
|
+
self._script_pubkey.get_template_hash(),
|
|
91
|
+
self._script_pubkey.get_constraint_hash(),
|
|
92
|
+
self._script_pubkey.get_visible_args(),
|
|
93
|
+
).to_string()
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def group_data(self):
|
|
98
|
+
try:
|
|
99
|
+
group_data = self._script_pubkey.get_group_data()
|
|
100
|
+
if group_data:
|
|
101
|
+
group_id, group_amount = group_data
|
|
102
|
+
return {
|
|
103
|
+
"groupId": Address(
|
|
104
|
+
group_id, networks.default_network, AddressType.GROUP_ID_ADDRESS
|
|
105
|
+
).to_string(),
|
|
106
|
+
"groupAmount": str(GroupToken.get_amount_value(group_amount)),
|
|
107
|
+
}
|
|
108
|
+
except Exception:
|
|
109
|
+
return None
|
|
110
|
+
return None
|
|
111
|
+
|
|
112
|
+
def invalid_value(self):
|
|
113
|
+
if self.value > 2**53 - 1:
|
|
114
|
+
return "transaction txout value greater than max safe integer"
|
|
115
|
+
if self.value < 0:
|
|
116
|
+
return "transaction txout negative"
|
|
117
|
+
return False
|
|
118
|
+
|
|
119
|
+
def to_object(self):
|
|
120
|
+
group = self.group_data
|
|
121
|
+
return {
|
|
122
|
+
"type": self.type,
|
|
123
|
+
"value": str(self.value),
|
|
124
|
+
"scriptPubKey": self.script_pubkey.to_hex(),
|
|
125
|
+
"address": self.address,
|
|
126
|
+
"groupId": group["groupId"] if group else None,
|
|
127
|
+
"groupAmount": group["groupAmount"] if group else None,
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
def to_json(self):
|
|
131
|
+
return self.to_object()
|
|
132
|
+
|
|
133
|
+
@staticmethod
|
|
134
|
+
def from_object(data) -> Self:
|
|
135
|
+
if not isinstance(data, dict):
|
|
136
|
+
raise ValueError("Invalid Argument: data. Unrecognized argument for Output")
|
|
137
|
+
return Output(data["value"], data["scriptPubKey"], data.get("type", OutputType.INFER))
|
|
138
|
+
|
|
139
|
+
def __str__(self) -> str:
|
|
140
|
+
return (
|
|
141
|
+
f"<Output (type: {int(self.type)}) ({self.value} sats) (script: {self.script_pubkey})>"
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
@staticmethod
|
|
145
|
+
def from_buffer_reader(br: BufferReader) -> Self:
|
|
146
|
+
type_ = br.read_varint()
|
|
147
|
+
value = br.read_uint64_le()
|
|
148
|
+
|
|
149
|
+
size = br.read_varint()
|
|
150
|
+
script_buf = br.read(size) if size != 0 else bytearray()
|
|
151
|
+
|
|
152
|
+
return Output(value, Script.from_buffer(script_buf), type_)
|
|
153
|
+
|
|
154
|
+
def to_buffer_writer(self, writer: BufferWriter | None = None) -> BufferWriter:
|
|
155
|
+
if writer is None:
|
|
156
|
+
writer = BufferWriter()
|
|
157
|
+
writer.write_uint8(int(self.type))
|
|
158
|
+
writer.write_uint64_le(self.value)
|
|
159
|
+
writer.write_var_length_buf(self.script_pubkey.to_buffer())
|
|
160
|
+
|
|
161
|
+
return writer
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
from typing import Self
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
from src.common.class_types import TypedClass
|
|
6
|
+
from src.common.types import InputSighashType, OutputSighashType
|
|
7
|
+
from src.encoding.buffer_reader import BufferReader
|
|
8
|
+
from src.encoding.buffer_writer import BufferWriter
|
|
9
|
+
from src.utils.common_utils import is_hex_string
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class SighashType(TypedClass):
|
|
13
|
+
"""
|
|
14
|
+
the longest sighashtype in bytes
|
|
15
|
+
(for use in calculating tx fees by tx length estimation)
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
MAX_SIZE: int = 4
|
|
19
|
+
|
|
20
|
+
in_type: InputSighashType | int
|
|
21
|
+
out_type: OutputSighashType | int
|
|
22
|
+
in_data: list
|
|
23
|
+
out_data: list
|
|
24
|
+
|
|
25
|
+
def __init__(self):
|
|
26
|
+
super().__init__()
|
|
27
|
+
self.in_type = InputSighashType.ALL
|
|
28
|
+
self.out_type = OutputSighashType.ALL
|
|
29
|
+
self.in_data = []
|
|
30
|
+
self.out_data = []
|
|
31
|
+
self._enforce_attribute_types()
|
|
32
|
+
|
|
33
|
+
@staticmethod
|
|
34
|
+
def ALL() -> Self:
|
|
35
|
+
"""
|
|
36
|
+
creates a sighash that is the most restrictive -- it signs all inputs and outputs
|
|
37
|
+
"""
|
|
38
|
+
return SighashType()
|
|
39
|
+
|
|
40
|
+
def has_all(self) -> bool:
|
|
41
|
+
return self.in_type == InputSighashType.ALL and self.out_type == OutputSighashType.ALL
|
|
42
|
+
|
|
43
|
+
def is_invalid(self) -> bool:
|
|
44
|
+
return (
|
|
45
|
+
self.in_type > InputSighashType.LAST_VALID
|
|
46
|
+
or self.out_type > OutputSighashType.LAST_VALID
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
def set_anyone_can_pay(self) -> Self:
|
|
50
|
+
"""
|
|
51
|
+
Anyone can pay signs only the current input, so other entities can add addtl inputs to complete the partial tx
|
|
52
|
+
"""
|
|
53
|
+
self.in_type = InputSighashType.THISIN
|
|
54
|
+
self.in_data = []
|
|
55
|
+
return self
|
|
56
|
+
|
|
57
|
+
def set_first_n_in(self, n: int) -> Self:
|
|
58
|
+
"""
|
|
59
|
+
Include only the n first inputs in the preimage sighash
|
|
60
|
+
|
|
61
|
+
@param n The first inputs to include
|
|
62
|
+
"""
|
|
63
|
+
if not (n >= 0 and n < 256):
|
|
64
|
+
raise ValueError("Invalid Argument: n. out of range (0-255).")
|
|
65
|
+
self.in_type = InputSighashType.FIRSTN
|
|
66
|
+
self.in_data = [n]
|
|
67
|
+
return self
|
|
68
|
+
|
|
69
|
+
def set_first_n_out(self, n: int) -> Self:
|
|
70
|
+
"""
|
|
71
|
+
Include only the n first outputs in the preimage sighash
|
|
72
|
+
|
|
73
|
+
@param n The first outputs to include
|
|
74
|
+
"""
|
|
75
|
+
if not (n >= 0 and n < 256):
|
|
76
|
+
raise ValueError("Invalid Argument: n. out of range (0-255).")
|
|
77
|
+
self.out_type = OutputSighashType.FIRSTN
|
|
78
|
+
self.out_data = [n]
|
|
79
|
+
return self
|
|
80
|
+
|
|
81
|
+
def set_2_out(self, a: int, b: int) -> Self:
|
|
82
|
+
"""
|
|
83
|
+
Include specific 2 outputs in the preimage sighash
|
|
84
|
+
|
|
85
|
+
@param a The 1st output to include
|
|
86
|
+
@param b The 2nd output to include
|
|
87
|
+
"""
|
|
88
|
+
if not (a >= 0 and a < 256):
|
|
89
|
+
raise ValueError("Invalid Argument: a. out of range (0-255).")
|
|
90
|
+
if not (b >= 0 and b < 256):
|
|
91
|
+
raise ValueError("Invalid Argument: b. out of range (0-255).")
|
|
92
|
+
self.out_type = OutputSighashType.TWO
|
|
93
|
+
self.out_data = [a, b]
|
|
94
|
+
return self
|
|
95
|
+
|
|
96
|
+
def to_buffer(self) -> bytearray:
|
|
97
|
+
if self.has_all():
|
|
98
|
+
return bytearray()
|
|
99
|
+
|
|
100
|
+
bw = BufferWriter()
|
|
101
|
+
sigtype = (int(self.in_type) << 4) | int(self.out_type)
|
|
102
|
+
bw.write_uint8(sigtype)
|
|
103
|
+
|
|
104
|
+
if self.in_type == InputSighashType.FIRSTN:
|
|
105
|
+
if not (self.in_data and len(self.in_data) > 0):
|
|
106
|
+
raise ValueError("Invalid State: Missing input data")
|
|
107
|
+
bw.write_uint8(self.in_data[0])
|
|
108
|
+
elif self.in_type not in (InputSighashType.THISIN, InputSighashType.ALL):
|
|
109
|
+
raise Exception("Malformed sighash type")
|
|
110
|
+
|
|
111
|
+
if self.out_type == OutputSighashType.TWO:
|
|
112
|
+
if not (self.out_data and len(self.out_data) > 1):
|
|
113
|
+
raise ValueError("Invalid State: Missing output data")
|
|
114
|
+
bw.write_uint8(self.out_data[0])
|
|
115
|
+
bw.write_uint8(self.out_data[1])
|
|
116
|
+
elif self.out_type == OutputSighashType.FIRSTN:
|
|
117
|
+
if not (self.out_data and len(self.out_data) > 0):
|
|
118
|
+
raise ValueError("Invalid State: Missing output data")
|
|
119
|
+
bw.write_uint8(self.out_data[0])
|
|
120
|
+
elif self.out_type not in (OutputSighashType.ALL,):
|
|
121
|
+
raise Exception("Malformed sighash type")
|
|
122
|
+
|
|
123
|
+
return bw.to_buffer()
|
|
124
|
+
|
|
125
|
+
@staticmethod
|
|
126
|
+
def from_buffer(buf: bytearray) -> Self:
|
|
127
|
+
if not isinstance(buf, (bytearray, bytes)):
|
|
128
|
+
raise ValueError("Invalid Argument: buf. ")
|
|
129
|
+
if len(buf) == 0:
|
|
130
|
+
return SighashType.ALL()
|
|
131
|
+
|
|
132
|
+
sighash = SighashType()
|
|
133
|
+
br = BufferReader(buf)
|
|
134
|
+
type_ = br.read_uint8()
|
|
135
|
+
|
|
136
|
+
sighash.out_type = type_ & 0x0F
|
|
137
|
+
sighash.in_type = type_ >> 4
|
|
138
|
+
|
|
139
|
+
if sighash.is_invalid():
|
|
140
|
+
raise Exception("Invalid sighash buffer")
|
|
141
|
+
|
|
142
|
+
def safe_read(br: BufferReader) -> int:
|
|
143
|
+
if br.finished():
|
|
144
|
+
raise Exception("Invalid sighash buffer")
|
|
145
|
+
return br.read_uint8()
|
|
146
|
+
|
|
147
|
+
if sighash.in_type == InputSighashType.FIRSTN:
|
|
148
|
+
sighash.in_data.append(safe_read(br))
|
|
149
|
+
|
|
150
|
+
if sighash.out_type == OutputSighashType.FIRSTN:
|
|
151
|
+
sighash.out_data.append(safe_read(br))
|
|
152
|
+
elif sighash.out_type == OutputSighashType.TWO:
|
|
153
|
+
sighash.out_data.append(safe_read(br))
|
|
154
|
+
sighash.out_data.append(safe_read(br))
|
|
155
|
+
|
|
156
|
+
if not br.finished():
|
|
157
|
+
raise Exception("Invalid sighash buffer")
|
|
158
|
+
|
|
159
|
+
return sighash
|
|
160
|
+
|
|
161
|
+
def to_hex(self) -> str:
|
|
162
|
+
"""
|
|
163
|
+
Convert to a hex representation of the sighash
|
|
164
|
+
"""
|
|
165
|
+
return self.to_buffer().hex()
|
|
166
|
+
|
|
167
|
+
@staticmethod
|
|
168
|
+
def from_hex(hex: str) -> Self:
|
|
169
|
+
"""
|
|
170
|
+
Create sighash for hex represantation
|
|
171
|
+
@see to_hex
|
|
172
|
+
"""
|
|
173
|
+
if isinstance(hex, str) and len(hex) == 0:
|
|
174
|
+
return SighashType.ALL()
|
|
175
|
+
if not isinstance(hex, str) or not is_hex_string(hex):
|
|
176
|
+
raise ValueError("Invalid Argument: Not a hex string. ")
|
|
177
|
+
return SighashType.from_buffer(bytearray.fromhex(hex))
|
|
178
|
+
|
|
179
|
+
def to_string(self) -> str:
|
|
180
|
+
"""
|
|
181
|
+
Convert to a human readable representation of the sighash
|
|
182
|
+
"""
|
|
183
|
+
if self.has_all():
|
|
184
|
+
return "ALL"
|
|
185
|
+
|
|
186
|
+
ret = ""
|
|
187
|
+
|
|
188
|
+
if self.in_type == InputSighashType.ALL:
|
|
189
|
+
ret += "ALL_IN"
|
|
190
|
+
elif self.in_type == InputSighashType.THISIN:
|
|
191
|
+
ret += "THIS_IN"
|
|
192
|
+
elif self.in_type == InputSighashType.FIRSTN:
|
|
193
|
+
ret += f"FIRST_{self.in_data[0]}_IN"
|
|
194
|
+
else:
|
|
195
|
+
return "INVALID"
|
|
196
|
+
|
|
197
|
+
ret += "|"
|
|
198
|
+
|
|
199
|
+
if self.out_type == OutputSighashType.ALL:
|
|
200
|
+
ret += "ALL_OUT"
|
|
201
|
+
elif self.out_type == OutputSighashType.TWO:
|
|
202
|
+
ret += f"{self.out_data[0]}_{self.out_data[1]}_OUT"
|
|
203
|
+
elif self.out_type == OutputSighashType.FIRSTN:
|
|
204
|
+
ret += f"FIRST_{self.out_data[0]}_OUT"
|
|
205
|
+
else:
|
|
206
|
+
return "INVALID"
|
|
207
|
+
|
|
208
|
+
return ret
|
|
209
|
+
|
|
210
|
+
@staticmethod
|
|
211
|
+
def from_string(input: str) -> Self:
|
|
212
|
+
"""
|
|
213
|
+
Create sighash from human readable represantation
|
|
214
|
+
@see to_string
|
|
215
|
+
"""
|
|
216
|
+
if not isinstance(input, str):
|
|
217
|
+
raise ValueError("Invalid Argument: Not a string. ")
|
|
218
|
+
if input == "ALL":
|
|
219
|
+
return SighashType.ALL()
|
|
220
|
+
|
|
221
|
+
if "|" not in input:
|
|
222
|
+
raise ValueError("Invalid Argument: Not a sighash string. ")
|
|
223
|
+
parts = input.split("|")
|
|
224
|
+
in_str = parts[0]
|
|
225
|
+
out_str = parts[1]
|
|
226
|
+
sighash = SighashType()
|
|
227
|
+
|
|
228
|
+
if in_str == "THIS_IN":
|
|
229
|
+
sighash.in_type = InputSighashType.THISIN
|
|
230
|
+
elif in_str != "ALL_IN":
|
|
231
|
+
match = re.match(r"^FIRST_(\d+)_IN$", in_str)
|
|
232
|
+
if match is None:
|
|
233
|
+
raise ValueError("Invalid State: Not a sighash string")
|
|
234
|
+
sighash.set_first_n_in(int(match.group(1)))
|
|
235
|
+
|
|
236
|
+
if out_str != "ALL_OUT":
|
|
237
|
+
fn_match = re.match(r"^FIRST_(\d+)_OUT$", out_str)
|
|
238
|
+
tw_match = re.match(r"^(\d+)_(\d+)_OUT$", out_str)
|
|
239
|
+
if fn_match:
|
|
240
|
+
sighash.set_first_n_out(int(fn_match.group(1)))
|
|
241
|
+
elif tw_match:
|
|
242
|
+
sighash.set_2_out(int(tw_match.group(1)), int(tw_match.group(2)))
|
|
243
|
+
else:
|
|
244
|
+
raise Exception("Not a sighash string")
|
|
245
|
+
|
|
246
|
+
return sighash
|