multisig 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 (70) hide show
  1. multisig-0.1.0.dist-info/METADATA +188 -0
  2. multisig-0.1.0.dist-info/RECORD +70 -0
  3. multisig-0.1.0.dist-info/WHEEL +4 -0
  4. multisig-0.1.0.dist-info/licenses/LICENSE +21 -0
  5. multisig_escrow/__init__.py +152 -0
  6. multisig_escrow/authenticity.py +45 -0
  7. multisig_escrow/bitcoin/__init__.py +124 -0
  8. multisig_escrow/bitcoin/addresses.py +103 -0
  9. multisig_escrow/bitcoin/assets.py +29 -0
  10. multisig_escrow/bitcoin/descriptor.py +211 -0
  11. multisig_escrow/bitcoin/fees.py +282 -0
  12. multisig_escrow/bitcoin/finalize.py +271 -0
  13. multisig_escrow/bitcoin/funding.py +153 -0
  14. multisig_escrow/bitcoin/keys.py +209 -0
  15. multisig_escrow/bitcoin/params.py +66 -0
  16. multisig_escrow/bitcoin/policy.py +158 -0
  17. multisig_escrow/bitcoin/psbt.py +241 -0
  18. multisig_escrow/bitcoin/timelock.py +166 -0
  19. multisig_escrow/bitcoin/verify.py +709 -0
  20. multisig_escrow/core/__init__.py +134 -0
  21. multisig_escrow/core/amounts.py +24 -0
  22. multisig_escrow/core/capabilities.py +273 -0
  23. multisig_escrow/core/codec.py +122 -0
  24. multisig_escrow/core/errors.py +104 -0
  25. multisig_escrow/core/ids.py +56 -0
  26. multisig_escrow/core/protocol.py +46 -0
  27. multisig_escrow/core/roles.py +196 -0
  28. multisig_escrow/core/terms.py +437 -0
  29. multisig_escrow/core/time.py +73 -0
  30. multisig_escrow/core/validation.py +127 -0
  31. multisig_escrow/evm/__init__.py +97 -0
  32. multisig_escrow/evm/addresses.py +72 -0
  33. multisig_escrow/evm/assets.py +76 -0
  34. multisig_escrow/evm/calldata.py +142 -0
  35. multisig_escrow/evm/deployment.py +201 -0
  36. multisig_escrow/evm/eip712.py +138 -0
  37. multisig_escrow/evm/funding.py +89 -0
  38. multisig_escrow/evm/params.py +38 -0
  39. multisig_escrow/evm/payouts.py +66 -0
  40. multisig_escrow/evm/plan.py +63 -0
  41. multisig_escrow/evm/safe.py +236 -0
  42. multisig_escrow/evm/signatures.py +181 -0
  43. multisig_escrow/evm/verify.py +732 -0
  44. multisig_escrow/facade.py +2532 -0
  45. multisig_escrow/fsm/__init__.py +95 -0
  46. multisig_escrow/fsm/events.py +95 -0
  47. multisig_escrow/fsm/invariants.py +287 -0
  48. multisig_escrow/fsm/machine.py +547 -0
  49. multisig_escrow/fsm/plan.py +24 -0
  50. multisig_escrow/fsm/record.py +271 -0
  51. multisig_escrow/fsm/serialize.py +453 -0
  52. multisig_escrow/fsm/states.py +86 -0
  53. multisig_escrow/fsm/tokens.py +466 -0
  54. multisig_escrow/monero/__init__.py +86 -0
  55. multisig_escrow/monero/adapter.py +741 -0
  56. multisig_escrow/monero/addresses.py +144 -0
  57. multisig_escrow/monero/approval.py +149 -0
  58. multisig_escrow/monero/crypto.py +234 -0
  59. multisig_escrow/monero/facade.py +610 -0
  60. multisig_escrow/monero/funding.py +217 -0
  61. multisig_escrow/monero/key_images.py +49 -0
  62. multisig_escrow/monero/keys.py +53 -0
  63. multisig_escrow/monero/manifest.py +103 -0
  64. multisig_escrow/monero/multisig.py +55 -0
  65. multisig_escrow/monero/params.py +76 -0
  66. multisig_escrow/monero/refund.py +119 -0
  67. multisig_escrow/monero/settlement.py +299 -0
  68. multisig_escrow/monero/terms.py +216 -0
  69. multisig_escrow/py.typed +0 -0
  70. multisig_escrow/store.py +115 -0
@@ -0,0 +1,271 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import TYPE_CHECKING, cast
5
+
6
+ from ..core.errors import DependencyError, SignatureError, VerificationError
7
+ from ..core.ids import SignerId
8
+ from ..fsm.states import SettlementPath
9
+ from .verify import (
10
+ _check_dust_outputs,
11
+ _check_fee_policy,
12
+ _check_path,
13
+ _check_signature,
14
+ _check_timelock_maturity,
15
+ _expected_sequence,
16
+ _signature_requirements,
17
+ _strict_der,
18
+ expected_outputs,
19
+ reconstruct_redeem_script,
20
+ reconstruct_witness_script,
21
+ verify_psbt,
22
+ )
23
+
24
+ if TYPE_CHECKING:
25
+ from .psbt import BitcoinSettlementPlan
26
+
27
+ try:
28
+ from embit.psbt import PSBT
29
+ from embit.script import Script, Witness
30
+ from embit.transaction import Transaction, TransactionInput
31
+ except ImportError as exc:
32
+ raise DependencyError("embit") from exc
33
+
34
+
35
+ @dataclass(frozen=True, slots=True)
36
+ class FinalizedBitcoinSettlement:
37
+ raw_tx: bytes
38
+ txid: bytes
39
+ weight: int
40
+ vsize: int
41
+ fee: int
42
+ signer_pubkeys: tuple[bytes, ...]
43
+
44
+ @property
45
+ def tx_hex(self) -> str:
46
+ return self.raw_tx.hex()
47
+
48
+ @property
49
+ def fee_rate_sat_vb(self) -> int:
50
+ return self.fee // max(1, self.vsize)
51
+
52
+
53
+ def _push_redeem(redeem: bytes) -> Script:
54
+ script = Script(b"")
55
+ script.push(redeem)
56
+ return script
57
+
58
+
59
+ def _weight(tx: Transaction) -> tuple[int, int]:
60
+ base = Transaction(
61
+ version=tx.version,
62
+ vin=[
63
+ TransactionInput(
64
+ item.txid,
65
+ item.vout,
66
+ script_sig=item.script_sig,
67
+ sequence=item.sequence,
68
+ )
69
+ for item in tx.vin
70
+ ],
71
+ vout=tx.vout,
72
+ locktime=tx.locktime,
73
+ )
74
+ base_size = len(cast(bytes, base.serialize()))
75
+ total = len(cast(bytes, tx.serialize()))
76
+ weight = base_size * 4 + (total - base_size)
77
+ return weight, (weight + 3) // 4
78
+
79
+
80
+ def finalize_psbt(
81
+ plan: BitcoinSettlementPlan,
82
+ psbt_base64: str,
83
+ *,
84
+ required_approvers: frozenset[SignerId] | None = None,
85
+ approver_threshold: int | None = None,
86
+ arbiter_required: bool = False,
87
+ arbiter_ids: frozenset[SignerId] | None = None,
88
+ ) -> FinalizedBitcoinSettlement:
89
+ verification = verify_psbt(
90
+ psbt_base64,
91
+ plan,
92
+ required_approvers=required_approvers,
93
+ approver_threshold=approver_threshold,
94
+ arbiter_required=arbiter_required,
95
+ arbiter_ids=frozenset() if arbiter_ids is None else arbiter_ids,
96
+ )
97
+ if not verification.quorum:
98
+ raise SignatureError("quorum")
99
+ try:
100
+ psbt = PSBT.from_base64(psbt_base64)
101
+ except Exception as exc:
102
+ raise VerificationError("psbt parse") from exc
103
+ tx = Transaction.parse(psbt.tx.serialize())
104
+ _, threshold = _signature_requirements(plan)
105
+ for index, inp in enumerate(psbt.inputs):
106
+ items = sorted(inp.partial_sigs.items(), key=lambda item: item[0].sec())
107
+ chosen = items[:threshold]
108
+ signatures = [sig for _, sig in chosen]
109
+ if plan.path is SettlementPath.TIMELOCK:
110
+ if len(signatures) != 1:
111
+ raise SignatureError("refund signature")
112
+ tx.vin[index].witness = Witness([signatures[0], b"", verification.witness_script])
113
+ else:
114
+ tx.vin[index].witness = Witness(
115
+ [b"", *signatures, b"\x01", verification.witness_script]
116
+ )
117
+ if verification.redeem_script is None:
118
+ tx.vin[index].script_sig = Script(b"")
119
+ else:
120
+ tx.vin[index].script_sig = _push_redeem(verification.redeem_script)
121
+ raw = cast(bytes, tx.serialize())
122
+ return verify_final_transaction(raw, plan)
123
+
124
+
125
+ def verify_final_transaction(
126
+ raw_tx: bytes,
127
+ plan: BitcoinSettlementPlan,
128
+ *,
129
+ required_approvers: frozenset[SignerId] | None = None,
130
+ approver_threshold: int | None = None,
131
+ arbiter_required: bool = False,
132
+ arbiter_ids: frozenset[SignerId] | None = None,
133
+ ) -> FinalizedBitcoinSettlement:
134
+ _check_path(plan)
135
+ _check_timelock_maturity(plan)
136
+ try:
137
+ tx = cast(Transaction, Transaction.parse(raw_tx))
138
+ except Exception as exc:
139
+ raise VerificationError("tx parse") from exc
140
+ if tx.version != 2 or tx.locktime != 0:
141
+ raise VerificationError("tx header")
142
+ outputs = expected_outputs(plan)
143
+ _check_dust_outputs(plan, outputs)
144
+ if len(tx.vout) != len(outputs):
145
+ raise VerificationError("output count")
146
+ for output, (amount, script, _) in zip(tx.vout, outputs, strict=True):
147
+ if output.value != amount or output.script_pubkey.data != script:
148
+ raise VerificationError("output")
149
+ if len(tx.vin) != len(plan.utxos):
150
+ raise VerificationError("input count")
151
+ witness_script = reconstruct_witness_script(plan.policy)
152
+ redeem_script = reconstruct_redeem_script(plan.policy)
153
+ sequence = _expected_sequence(plan)
154
+ timelock = plan.path is SettlementPath.TIMELOCK
155
+ if timelock:
156
+ keys, threshold = _signature_requirements(plan)
157
+ refund_key = next(iter(keys))
158
+ expected_keys: list[bytes] = []
159
+ else:
160
+ expected_keys = sorted(signer.public_key() for signer in plan.policy.signers)
161
+ threshold = plan.policy.threshold
162
+ refund_key = b""
163
+ if threshold > len(expected_keys) and not timelock:
164
+ raise VerificationError("threshold")
165
+ selected: list[bytes] = []
166
+ for index, (vin, utxo) in enumerate(zip(tx.vin, plan.utxos, strict=True)):
167
+ if vin.txid != utxo.txid[::-1] or vin.vout != utxo.output_index:
168
+ raise VerificationError("outpoint")
169
+ if vin.sequence != sequence:
170
+ raise VerificationError("sequence")
171
+ if redeem_script is None:
172
+ if vin.script_sig.data != b"":
173
+ raise VerificationError("script sig")
174
+ elif vin.script_sig.data != _push_redeem(redeem_script).data:
175
+ raise VerificationError("script sig")
176
+ items = vin.witness.items
177
+ if timelock:
178
+ if len(items) != 3:
179
+ raise VerificationError("witness count")
180
+ if items[1] != b"" or items[2] != witness_script:
181
+ raise VerificationError("witness shape")
182
+ signature = items[0]
183
+ digest = cast(
184
+ bytes,
185
+ tx.sighash_segwit(
186
+ index,
187
+ Script(witness_script),
188
+ utxo.amount,
189
+ 1,
190
+ ),
191
+ )
192
+ try:
193
+ _strict_der(signature[:-1])
194
+ except SignatureError:
195
+ raise
196
+ _check_signature(refund_key, signature, digest)
197
+ selected.append(refund_key)
198
+ continue
199
+ if len(items) != threshold + 3:
200
+ raise VerificationError("witness count")
201
+ if items[0] != b"" or items[-2] != b"\x01" or items[-1] != witness_script:
202
+ raise VerificationError("witness shape")
203
+ signatures = items[1:-2]
204
+ digest = cast(
205
+ bytes,
206
+ tx.sighash_segwit(
207
+ index,
208
+ Script(witness_script),
209
+ utxo.amount,
210
+ 1,
211
+ ),
212
+ )
213
+ cursor = 0
214
+ for signature in signatures:
215
+ try:
216
+ _strict_der(signature[:-1])
217
+ except SignatureError:
218
+ raise
219
+ while cursor < len(expected_keys):
220
+ key = expected_keys[cursor]
221
+ cursor += 1
222
+ try:
223
+ _check_signature(key, signature, digest)
224
+ except SignatureError:
225
+ continue
226
+ selected.append(key)
227
+ break
228
+ else:
229
+ raise SignatureError("witness signer")
230
+ if required_approvers is not None:
231
+ threshold_active = (
232
+ len(required_approvers) if approver_threshold is None else approver_threshold
233
+ )
234
+ if not 1 <= threshold_active <= len(required_approvers):
235
+ raise VerificationError("approvers")
236
+ by_key = {
237
+ signer.public_key(): signer.signer_id
238
+ for signer in plan.policy.signers
239
+ if signer.signer_id is not None
240
+ }
241
+ selected_ids = {
242
+ by_key[key] for key in selected if key in by_key and by_key[key] in required_approvers
243
+ }
244
+ if len(selected_ids) < threshold_active:
245
+ raise SignatureError("quorum")
246
+ if arbiter_required:
247
+ required_arbiters = arbiter_ids or frozenset()
248
+ if not selected_ids.intersection(required_arbiters):
249
+ raise SignatureError("arbiter")
250
+ total_in = sum(utxo.amount for utxo in plan.utxos)
251
+ total_out = sum(output.value for output in tx.vout)
252
+ fee = total_in - total_out
253
+ if fee < 0 or fee != plan.fee:
254
+ raise VerificationError("fee")
255
+ weight, vsize = _weight(tx)
256
+ _check_fee_policy(plan, fee, vsize, vsize)
257
+ return FinalizedBitcoinSettlement(
258
+ raw_tx=raw_tx,
259
+ txid=cast(bytes, tx.txid())[::-1],
260
+ weight=weight,
261
+ vsize=vsize,
262
+ fee=fee,
263
+ signer_pubkeys=tuple(dict.fromkeys(selected)),
264
+ )
265
+
266
+
267
+ __all__ = [
268
+ "FinalizedBitcoinSettlement",
269
+ "finalize_psbt",
270
+ "verify_final_transaction",
271
+ ]
@@ -0,0 +1,153 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import cast
5
+
6
+ from ..core.errors import DependencyError, FundingError, ValidationError
7
+ from ..core.validation import require_bytes, require_hash, require_int, require_str
8
+ from .policy import BitcoinPolicy
9
+
10
+ try:
11
+ from embit.transaction import Transaction
12
+ except ImportError as exc:
13
+ raise DependencyError("embit") from exc
14
+
15
+
16
+ @dataclass(frozen=True, slots=True)
17
+ class BitcoinFundingTarget:
18
+ policy: BitcoinPolicy
19
+ address: str
20
+ script_pubkey: bytes
21
+ descriptor: str | None
22
+ amount: int
23
+ confirmations: int
24
+ tolerance: int = 0
25
+
26
+ def __post_init__(self) -> None:
27
+ if not isinstance(self.policy, BitcoinPolicy):
28
+ raise ValidationError("policy")
29
+ require_str(self.address, "address", 14, 128, True)
30
+ require_bytes(self.script_pubkey, "script pubkey", minimum=1, maximum=10000)
31
+ if self.descriptor is not None:
32
+ require_str(self.descriptor, "descriptor", 1, 100000, True)
33
+ require_int(self.amount, "amount", 1, (1 << 64) - 1)
34
+ require_int(self.confirmations, "confirmations", 1, (1 << 32) - 1)
35
+ require_int(self.tolerance, "tolerance", 0, (1 << 64) - 1)
36
+ if self.address != self.policy.address():
37
+ raise ValidationError("funding address")
38
+ if self.script_pubkey != self.policy.script_pubkey():
39
+ raise ValidationError("funding script")
40
+ if self.descriptor != self.policy.descriptor():
41
+ raise ValidationError("funding descriptor")
42
+
43
+ @classmethod
44
+ def from_policy(
45
+ cls,
46
+ policy: BitcoinPolicy,
47
+ amount: int,
48
+ confirmations: int,
49
+ tolerance: int = 0,
50
+ ) -> BitcoinFundingTarget:
51
+ return cls(
52
+ policy=policy,
53
+ address=policy.address(),
54
+ script_pubkey=policy.script_pubkey(),
55
+ descriptor=policy.descriptor(),
56
+ amount=amount,
57
+ confirmations=confirmations,
58
+ tolerance=tolerance,
59
+ )
60
+
61
+
62
+ @dataclass(frozen=True, slots=True)
63
+ class BitcoinFundingEvidence:
64
+ raw_tx: bytes
65
+ txid: bytes
66
+ output_index: int
67
+ amount: int
68
+ confirmations: int
69
+ block_height: int | None = None
70
+
71
+ def __post_init__(self) -> None:
72
+ require_bytes(self.raw_tx, "raw tx", minimum=1, maximum=4 * 1024 * 1024)
73
+ require_hash(self.txid, "txid")
74
+ require_int(self.output_index, "output index", 0, (1 << 32) - 1)
75
+ require_int(self.amount, "amount", 1, (1 << 64) - 1)
76
+ require_int(self.confirmations, "confirmations", 0, (1 << 32) - 1)
77
+ if self.block_height is not None:
78
+ require_int(self.block_height, "block height", 0, (1 << 32) - 1)
79
+
80
+
81
+ @dataclass(frozen=True, slots=True)
82
+ class BtcUtxo:
83
+ txid: bytes
84
+ output_index: int
85
+ amount: int
86
+ script_pubkey: bytes
87
+ confirmations: int
88
+ block_height: int | None = None
89
+
90
+ def __post_init__(self) -> None:
91
+ require_hash(self.txid, "txid")
92
+ require_int(self.output_index, "output index", 0, (1 << 32) - 1)
93
+ require_int(self.amount, "amount", 1, (1 << 64) - 1)
94
+ require_bytes(self.script_pubkey, "script pubkey", minimum=1, maximum=10000)
95
+ require_int(self.confirmations, "confirmations", 0, (1 << 32) - 1)
96
+ if self.block_height is not None:
97
+ require_int(self.block_height, "block height", 0, (1 << 32) - 1)
98
+
99
+ def to_canonical(self) -> dict[str, object]:
100
+ return {
101
+ "txid": self.txid.hex(),
102
+ "output_index": self.output_index,
103
+ "amount": self.amount,
104
+ "script_pubkey": self.script_pubkey,
105
+ "confirmations": self.confirmations,
106
+ "block_height": self.block_height,
107
+ }
108
+
109
+
110
+ def validate_funding(
111
+ target: BitcoinFundingTarget,
112
+ evidence: BitcoinFundingEvidence,
113
+ ) -> BtcUtxo:
114
+ if not isinstance(target, BitcoinFundingTarget):
115
+ raise FundingError("target type")
116
+ if not isinstance(evidence, BitcoinFundingEvidence):
117
+ raise FundingError("evidence type")
118
+ try:
119
+ tx = cast(Transaction, Transaction.parse(evidence.raw_tx))
120
+ except Exception as exc:
121
+ raise FundingError("raw tx parse") from exc
122
+ if tx.txid()[::-1] != evidence.txid:
123
+ raise FundingError("txid")
124
+ if evidence.output_index >= len(tx.vout):
125
+ raise FundingError("output index")
126
+ output = tx.vout[evidence.output_index]
127
+ script = cast(bytes, output.script_pubkey.data)
128
+ if script != target.script_pubkey:
129
+ raise FundingError("funding script")
130
+ if output.value != evidence.amount:
131
+ raise FundingError("evidence amount")
132
+ if output.value < target.amount:
133
+ raise FundingError("amount low")
134
+ if output.value > target.amount + target.tolerance:
135
+ raise FundingError("amount high")
136
+ if evidence.confirmations < target.confirmations:
137
+ raise FundingError("confirmations")
138
+ return BtcUtxo(
139
+ txid=evidence.txid,
140
+ output_index=evidence.output_index,
141
+ amount=output.value,
142
+ script_pubkey=script,
143
+ confirmations=evidence.confirmations,
144
+ block_height=evidence.block_height,
145
+ )
146
+
147
+
148
+ __all__ = [
149
+ "BitcoinFundingEvidence",
150
+ "BitcoinFundingTarget",
151
+ "BtcUtxo",
152
+ "validate_funding",
153
+ ]
@@ -0,0 +1,209 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from enum import StrEnum
5
+ from typing import Any, cast
6
+
7
+ from ..core.capabilities import ChainFamily
8
+ from ..core.errors import DependencyError, NetworkMismatchError, ValidationError
9
+ from ..core.ids import SignerId
10
+ from ..core.validation import require_bytes, require_str
11
+
12
+ try:
13
+ from embit import bip32
14
+ from embit.networks import NETWORKS
15
+ except ImportError as exc:
16
+ raise DependencyError("embit") from exc
17
+
18
+ _HARDENED = 1 << 31
19
+ _MAX_DEPTH = 255
20
+
21
+
22
+ class BitcoinNetwork(StrEnum):
23
+ MAINNET = "mainnet"
24
+ TESTNET = "testnet"
25
+ SIGNET = "signet"
26
+ REGTEST = "regtest"
27
+
28
+
29
+ _NETWORKS = {
30
+ BitcoinNetwork.MAINNET: NETWORKS["main"],
31
+ BitcoinNetwork.TESTNET: NETWORKS["test"],
32
+ BitcoinNetwork.SIGNET: NETWORKS["signet"],
33
+ BitcoinNetwork.REGTEST: NETWORKS["regtest"],
34
+ }
35
+
36
+
37
+ def network_data(network: BitcoinNetwork) -> dict[str, object]:
38
+ if not isinstance(network, BitcoinNetwork):
39
+ raise ValidationError("network")
40
+ return cast(dict[str, object], _NETWORKS[network])
41
+
42
+
43
+ @dataclass(frozen=True, slots=True)
44
+ class BitcoinChain:
45
+ network: BitcoinNetwork
46
+
47
+ def __post_init__(self) -> None:
48
+ network_data(self.network)
49
+
50
+ @classmethod
51
+ def mainnet(cls) -> BitcoinChain:
52
+ return cls(BitcoinNetwork.MAINNET)
53
+
54
+ @classmethod
55
+ def testnet(cls) -> BitcoinChain:
56
+ return cls(BitcoinNetwork.TESTNET)
57
+
58
+ @classmethod
59
+ def signet(cls) -> BitcoinChain:
60
+ return cls(BitcoinNetwork.SIGNET)
61
+
62
+ @classmethod
63
+ def regtest(cls) -> BitcoinChain:
64
+ return cls(BitcoinNetwork.REGTEST)
65
+
66
+ @property
67
+ def kind(self) -> str:
68
+ return "bitcoin"
69
+
70
+ @property
71
+ def family(self) -> ChainFamily:
72
+ return ChainFamily.BITCOIN
73
+
74
+ def to_canonical(self) -> dict[str, object]:
75
+ return {"kind": self.kind, "network": self.network.value}
76
+
77
+
78
+ def _parse_path(value: str, field: str, allow_hardened: bool) -> tuple[int, ...]:
79
+ text = require_str(value, field, 0, 512)
80
+ if text in ("", "m"):
81
+ return ()
82
+ if text.startswith("m/"):
83
+ text = text[2:]
84
+ if not text or text.endswith("/") or "//" in text:
85
+ raise ValidationError(f"{field} format")
86
+ out: list[int] = []
87
+ for part in text.split("/"):
88
+ if not part:
89
+ raise ValidationError(f"{field} format")
90
+ hardened = part.endswith("'") or part.endswith("h")
91
+ if hardened:
92
+ part = part[:-1]
93
+ if not part.isdigit():
94
+ raise ValidationError(f"{field} format")
95
+ index = int(part)
96
+ if index >= _HARDENED:
97
+ raise ValidationError(f"{field} range")
98
+ if hardened:
99
+ if not allow_hardened:
100
+ raise ValidationError(f"{field} hardened")
101
+ index += _HARDENED
102
+ out.append(index)
103
+ if len(out) > _MAX_DEPTH:
104
+ raise ValidationError(f"{field} depth")
105
+ return tuple(out)
106
+
107
+
108
+ def _format_path(path: tuple[int, ...]) -> str:
109
+ parts = []
110
+ for index in path:
111
+ if index >= _HARDENED:
112
+ parts.append(f"{index - _HARDENED}'")
113
+ else:
114
+ parts.append(str(index))
115
+ return "/".join(parts)
116
+
117
+
118
+ def _parse_xpub(xpub: str, network: BitcoinNetwork) -> Any:
119
+ text = require_str(xpub, "xpub", 100, 120, True)
120
+ try:
121
+ key = bip32.HDKey.from_base58(text)
122
+ except Exception as exc:
123
+ raise ValidationError("xpub format") from exc
124
+ if key.is_private:
125
+ raise ValidationError("xpub private")
126
+ data = network_data(network)
127
+ if key.version != data["xpub"]:
128
+ raise NetworkMismatchError("xpub network")
129
+ return key
130
+
131
+
132
+ @dataclass(frozen=True, slots=True)
133
+ class BtcSigner:
134
+ xpub: str
135
+ fingerprint: bytes
136
+ origin_path: str
137
+ derive_path: str
138
+ network: BitcoinNetwork
139
+ signer_id: SignerId | None = None
140
+
141
+ def __post_init__(self) -> None:
142
+ network_data(self.network)
143
+ if self.signer_id is not None and not isinstance(self.signer_id, SignerId):
144
+ raise ValidationError("signer id")
145
+ require_bytes(self.fingerprint, "fingerprint", 4)
146
+ origin = _parse_path(self.origin_path, "origin path", True)
147
+ derive = _parse_path(self.derive_path, "derive path", False)
148
+ if len(origin) + len(derive) > _MAX_DEPTH:
149
+ raise ValidationError("path depth")
150
+ key = _parse_xpub(self.xpub, self.network)
151
+ if key.depth + len(derive) > _MAX_DEPTH:
152
+ raise ValidationError("path depth")
153
+ if not origin and self.fingerprint != key.my_fingerprint:
154
+ raise ValidationError("fingerprint")
155
+
156
+ @classmethod
157
+ def from_xpub(
158
+ cls,
159
+ xpub: str,
160
+ fingerprint: bytes,
161
+ origin_path: str,
162
+ derive_path: str,
163
+ network: BitcoinNetwork,
164
+ signer_id: SignerId | None = None,
165
+ ) -> BtcSigner:
166
+ return cls(xpub, fingerprint, origin_path, derive_path, network, signer_id)
167
+
168
+ def public_key(self) -> bytes:
169
+ key = _parse_xpub(self.xpub, self.network)
170
+ derive = _parse_path(self.derive_path, "derive path", False)
171
+ child = key.derive(derive)
172
+ return cast(bytes, child.get_public_key().sec())
173
+
174
+ def descriptor_key(self) -> str:
175
+ origin = _parse_path(self.origin_path, "origin path", True)
176
+ derive = _parse_path(self.derive_path, "derive path", False)
177
+ prefix = f"[{self.fingerprint.hex()}"
178
+ if origin:
179
+ prefix += f"/{_format_path(origin)}"
180
+ prefix += "]"
181
+ suffix = f"/{_format_path(derive)}" if derive else ""
182
+ return f"{prefix}{self.xpub}{suffix}"
183
+
184
+ def derivation_path(self) -> tuple[int, ...]:
185
+ origin = _parse_path(self.origin_path, "origin path", True)
186
+ derive = _parse_path(self.derive_path, "derive path", False)
187
+ return origin + derive
188
+
189
+ def to_canonical(self) -> dict[str, object]:
190
+ origin = _parse_path(self.origin_path, "origin path", True)
191
+ derive = _parse_path(self.derive_path, "derive path", False)
192
+ data: dict[str, object] = {
193
+ "xpub": self.xpub,
194
+ "fingerprint": self.fingerprint.hex(),
195
+ "origin_path": _format_path(origin),
196
+ "derive_path": _format_path(derive),
197
+ "network": self.network.value,
198
+ }
199
+ if self.signer_id is not None:
200
+ data["signer_id"] = self.signer_id.value
201
+ return data
202
+
203
+
204
+ __all__ = [
205
+ "BitcoinChain",
206
+ "BitcoinNetwork",
207
+ "BtcSigner",
208
+ "network_data",
209
+ ]
@@ -0,0 +1,66 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Protocol
5
+
6
+ from ..core.errors import ValidationError
7
+ from ..core.validation import require_int, require_sequence, require_str
8
+ from ..fsm.states import SettlementPath
9
+ from .funding import BtcUtxo
10
+ from .timelock import TimelockMaturity
11
+
12
+
13
+ class PsbtSigner(Protocol):
14
+ def sign_psbt(self, psbt_base64: str) -> str: ...
15
+
16
+
17
+ @dataclass(frozen=True, slots=True)
18
+ class PsbtApproval:
19
+ psbt_base64: str
20
+
21
+ def __post_init__(self) -> None:
22
+ object.__setattr__(
23
+ self,
24
+ "psbt_base64",
25
+ require_str(self.psbt_base64, "psbt", 1, 1024 * 1024),
26
+ )
27
+
28
+
29
+ @dataclass(frozen=True, slots=True)
30
+ class BtcReleaseParams:
31
+ utxos: tuple[BtcUtxo, ...]
32
+ fee: int
33
+
34
+ def __post_init__(self) -> None:
35
+ items = require_sequence(self.utxos, "utxos", 1, 100)
36
+ if any(not isinstance(item, BtcUtxo) for item in items):
37
+ raise ValidationError("utxo")
38
+ require_int(self.fee, "fee", 0, (1 << 64) - 1)
39
+ object.__setattr__(self, "utxos", tuple(items))
40
+
41
+
42
+ @dataclass(frozen=True, slots=True)
43
+ class BtcRefundParams:
44
+ utxos: tuple[BtcUtxo, ...]
45
+ fee: int
46
+ path: SettlementPath = SettlementPath.PRIMARY
47
+ maturity: TimelockMaturity | None = None
48
+
49
+ def __post_init__(self) -> None:
50
+ items = require_sequence(self.utxos, "utxos", 1, 100)
51
+ if any(not isinstance(item, BtcUtxo) for item in items):
52
+ raise ValidationError("utxo")
53
+ require_int(self.fee, "fee", 0, (1 << 64) - 1)
54
+ if not isinstance(self.path, SettlementPath):
55
+ raise ValidationError("path")
56
+ if self.maturity is not None and not isinstance(self.maturity, TimelockMaturity):
57
+ raise ValidationError("maturity")
58
+ object.__setattr__(self, "utxos", tuple(items))
59
+
60
+
61
+ __all__ = [
62
+ "BtcRefundParams",
63
+ "BtcReleaseParams",
64
+ "PsbtApproval",
65
+ "PsbtSigner",
66
+ ]