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.
- multisig-0.1.0.dist-info/METADATA +188 -0
- multisig-0.1.0.dist-info/RECORD +70 -0
- multisig-0.1.0.dist-info/WHEEL +4 -0
- multisig-0.1.0.dist-info/licenses/LICENSE +21 -0
- multisig_escrow/__init__.py +152 -0
- multisig_escrow/authenticity.py +45 -0
- multisig_escrow/bitcoin/__init__.py +124 -0
- multisig_escrow/bitcoin/addresses.py +103 -0
- multisig_escrow/bitcoin/assets.py +29 -0
- multisig_escrow/bitcoin/descriptor.py +211 -0
- multisig_escrow/bitcoin/fees.py +282 -0
- multisig_escrow/bitcoin/finalize.py +271 -0
- multisig_escrow/bitcoin/funding.py +153 -0
- multisig_escrow/bitcoin/keys.py +209 -0
- multisig_escrow/bitcoin/params.py +66 -0
- multisig_escrow/bitcoin/policy.py +158 -0
- multisig_escrow/bitcoin/psbt.py +241 -0
- multisig_escrow/bitcoin/timelock.py +166 -0
- multisig_escrow/bitcoin/verify.py +709 -0
- multisig_escrow/core/__init__.py +134 -0
- multisig_escrow/core/amounts.py +24 -0
- multisig_escrow/core/capabilities.py +273 -0
- multisig_escrow/core/codec.py +122 -0
- multisig_escrow/core/errors.py +104 -0
- multisig_escrow/core/ids.py +56 -0
- multisig_escrow/core/protocol.py +46 -0
- multisig_escrow/core/roles.py +196 -0
- multisig_escrow/core/terms.py +437 -0
- multisig_escrow/core/time.py +73 -0
- multisig_escrow/core/validation.py +127 -0
- multisig_escrow/evm/__init__.py +97 -0
- multisig_escrow/evm/addresses.py +72 -0
- multisig_escrow/evm/assets.py +76 -0
- multisig_escrow/evm/calldata.py +142 -0
- multisig_escrow/evm/deployment.py +201 -0
- multisig_escrow/evm/eip712.py +138 -0
- multisig_escrow/evm/funding.py +89 -0
- multisig_escrow/evm/params.py +38 -0
- multisig_escrow/evm/payouts.py +66 -0
- multisig_escrow/evm/plan.py +63 -0
- multisig_escrow/evm/safe.py +236 -0
- multisig_escrow/evm/signatures.py +181 -0
- multisig_escrow/evm/verify.py +732 -0
- multisig_escrow/facade.py +2532 -0
- multisig_escrow/fsm/__init__.py +95 -0
- multisig_escrow/fsm/events.py +95 -0
- multisig_escrow/fsm/invariants.py +287 -0
- multisig_escrow/fsm/machine.py +547 -0
- multisig_escrow/fsm/plan.py +24 -0
- multisig_escrow/fsm/record.py +271 -0
- multisig_escrow/fsm/serialize.py +453 -0
- multisig_escrow/fsm/states.py +86 -0
- multisig_escrow/fsm/tokens.py +466 -0
- multisig_escrow/monero/__init__.py +86 -0
- multisig_escrow/monero/adapter.py +741 -0
- multisig_escrow/monero/addresses.py +144 -0
- multisig_escrow/monero/approval.py +149 -0
- multisig_escrow/monero/crypto.py +234 -0
- multisig_escrow/monero/facade.py +610 -0
- multisig_escrow/monero/funding.py +217 -0
- multisig_escrow/monero/key_images.py +49 -0
- multisig_escrow/monero/keys.py +53 -0
- multisig_escrow/monero/manifest.py +103 -0
- multisig_escrow/monero/multisig.py +55 -0
- multisig_escrow/monero/params.py +76 -0
- multisig_escrow/monero/refund.py +119 -0
- multisig_escrow/monero/settlement.py +299 -0
- multisig_escrow/monero/terms.py +216 -0
- multisig_escrow/py.typed +0 -0
- multisig_escrow/store.py +115 -0
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
from ..core.errors import NetworkMismatchError, PolicyError, ValidationError
|
|
6
|
+
from ..core.terms import FeePolicy
|
|
7
|
+
from ..core.validation import require_bool, require_int, require_sequence
|
|
8
|
+
from .descriptor import (
|
|
9
|
+
build_multisig_descriptor,
|
|
10
|
+
descriptor_address,
|
|
11
|
+
descriptor_checksum,
|
|
12
|
+
descriptor_redeem_script,
|
|
13
|
+
descriptor_script_pubkey,
|
|
14
|
+
descriptor_witness_script,
|
|
15
|
+
witness_script_address,
|
|
16
|
+
witness_script_redeem_script,
|
|
17
|
+
witness_script_script_pubkey,
|
|
18
|
+
)
|
|
19
|
+
from .keys import BitcoinChain, BitcoinNetwork, BtcSigner, network_data
|
|
20
|
+
from .timelock import TimelockRefund, build_timelock_script
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True, slots=True)
|
|
24
|
+
class BitcoinPolicy:
|
|
25
|
+
threshold: int
|
|
26
|
+
signers: tuple[BtcSigner, ...]
|
|
27
|
+
network: BitcoinNetwork
|
|
28
|
+
wrapped: bool = False
|
|
29
|
+
timelock: TimelockRefund | None = None
|
|
30
|
+
fee_policy: FeePolicy | None = None
|
|
31
|
+
|
|
32
|
+
def __post_init__(self) -> None:
|
|
33
|
+
network_data(self.network)
|
|
34
|
+
signers = require_sequence(self.signers, "signers", 2, 15)
|
|
35
|
+
out: list[BtcSigner] = []
|
|
36
|
+
keys: set[bytes] = set()
|
|
37
|
+
ids: set[str] = set()
|
|
38
|
+
for signer in signers:
|
|
39
|
+
if not isinstance(signer, BtcSigner):
|
|
40
|
+
raise ValidationError("signer type")
|
|
41
|
+
if signer.network != self.network:
|
|
42
|
+
raise NetworkMismatchError("signer network")
|
|
43
|
+
public = signer.public_key()
|
|
44
|
+
if public in keys:
|
|
45
|
+
raise PolicyError("key duplicate")
|
|
46
|
+
keys.add(public)
|
|
47
|
+
if signer.signer_id is not None:
|
|
48
|
+
if signer.signer_id.value in ids:
|
|
49
|
+
raise PolicyError("signer id duplicate")
|
|
50
|
+
ids.add(signer.signer_id.value)
|
|
51
|
+
out.append(signer)
|
|
52
|
+
try:
|
|
53
|
+
threshold = require_int(self.threshold, "threshold", 2, 15)
|
|
54
|
+
except ValidationError as exc:
|
|
55
|
+
raise PolicyError("threshold") from exc
|
|
56
|
+
if threshold > len(out):
|
|
57
|
+
raise PolicyError("threshold size")
|
|
58
|
+
wrapped = require_bool(self.wrapped, "wrapped")
|
|
59
|
+
timelock = self.timelock
|
|
60
|
+
if timelock is not None:
|
|
61
|
+
if not isinstance(timelock, TimelockRefund):
|
|
62
|
+
raise ValidationError("timelock type")
|
|
63
|
+
matches = [signer for signer in out if signer.signer_id == timelock.refund_signer_id]
|
|
64
|
+
if len(matches) != 1:
|
|
65
|
+
raise PolicyError("refund signer")
|
|
66
|
+
fee_policy = self.fee_policy
|
|
67
|
+
if fee_policy is not None and not isinstance(fee_policy, FeePolicy):
|
|
68
|
+
raise ValidationError("fee policy")
|
|
69
|
+
object.__setattr__(self, "signers", tuple(out))
|
|
70
|
+
object.__setattr__(self, "threshold", threshold)
|
|
71
|
+
object.__setattr__(self, "wrapped", wrapped)
|
|
72
|
+
object.__setattr__(self, "timelock", timelock)
|
|
73
|
+
object.__setattr__(self, "fee_policy", fee_policy)
|
|
74
|
+
|
|
75
|
+
@property
|
|
76
|
+
def chain(self) -> BitcoinChain:
|
|
77
|
+
return BitcoinChain(self.network)
|
|
78
|
+
|
|
79
|
+
def descriptor_body(self) -> str | None:
|
|
80
|
+
if self.timelock is not None:
|
|
81
|
+
return None
|
|
82
|
+
return build_multisig_descriptor(self.threshold, self.signers, self.wrapped)
|
|
83
|
+
|
|
84
|
+
def descriptor(self) -> str | None:
|
|
85
|
+
body = self.descriptor_body()
|
|
86
|
+
if body is None:
|
|
87
|
+
return None
|
|
88
|
+
return f"{body}#{descriptor_checksum(body)}"
|
|
89
|
+
|
|
90
|
+
def descriptor_checksum(self) -> str | None:
|
|
91
|
+
body = self.descriptor_body()
|
|
92
|
+
if body is None:
|
|
93
|
+
return None
|
|
94
|
+
return descriptor_checksum(body)
|
|
95
|
+
|
|
96
|
+
def timelock_signer(self) -> BtcSigner:
|
|
97
|
+
timelock = self.timelock
|
|
98
|
+
if timelock is None:
|
|
99
|
+
raise PolicyError("timelock missing")
|
|
100
|
+
matches = [
|
|
101
|
+
signer for signer in self.signers if signer.signer_id == timelock.refund_signer_id
|
|
102
|
+
]
|
|
103
|
+
if len(matches) != 1:
|
|
104
|
+
raise PolicyError("refund signer")
|
|
105
|
+
return matches[0]
|
|
106
|
+
|
|
107
|
+
def witness_script(self) -> bytes:
|
|
108
|
+
if self.timelock is not None:
|
|
109
|
+
return build_timelock_script(
|
|
110
|
+
self.threshold,
|
|
111
|
+
tuple(signer.public_key() for signer in self.signers),
|
|
112
|
+
self.timelock.sequence(),
|
|
113
|
+
self.timelock_signer().public_key(),
|
|
114
|
+
)
|
|
115
|
+
descriptor = self.descriptor()
|
|
116
|
+
if descriptor is None:
|
|
117
|
+
raise PolicyError("descriptor")
|
|
118
|
+
return descriptor_witness_script(descriptor)
|
|
119
|
+
|
|
120
|
+
def redeem_script(self) -> bytes | None:
|
|
121
|
+
if self.timelock is not None:
|
|
122
|
+
return witness_script_redeem_script(self.witness_script(), self.wrapped)
|
|
123
|
+
descriptor = self.descriptor()
|
|
124
|
+
if descriptor is None:
|
|
125
|
+
raise PolicyError("descriptor")
|
|
126
|
+
return descriptor_redeem_script(descriptor)
|
|
127
|
+
|
|
128
|
+
def script_pubkey(self) -> bytes:
|
|
129
|
+
if self.timelock is not None:
|
|
130
|
+
return witness_script_script_pubkey(self.witness_script(), self.wrapped)
|
|
131
|
+
descriptor = self.descriptor()
|
|
132
|
+
if descriptor is None:
|
|
133
|
+
raise PolicyError("descriptor")
|
|
134
|
+
return descriptor_script_pubkey(descriptor)
|
|
135
|
+
|
|
136
|
+
def address(self) -> str:
|
|
137
|
+
if self.timelock is not None:
|
|
138
|
+
return witness_script_address(self.witness_script(), self.network, self.wrapped)
|
|
139
|
+
descriptor = self.descriptor()
|
|
140
|
+
if descriptor is None:
|
|
141
|
+
raise PolicyError("descriptor")
|
|
142
|
+
return descriptor_address(descriptor, self.network)
|
|
143
|
+
|
|
144
|
+
def summary(self) -> str:
|
|
145
|
+
return f"{self.threshold} of {len(self.signers)} {self.address()}"
|
|
146
|
+
|
|
147
|
+
def to_canonical(self) -> dict[str, object]:
|
|
148
|
+
return {
|
|
149
|
+
"threshold": self.threshold,
|
|
150
|
+
"signers": [signer.to_canonical() for signer in self.signers],
|
|
151
|
+
"network": self.network.value,
|
|
152
|
+
"wrapped": self.wrapped,
|
|
153
|
+
"timelock": self.timelock.to_canonical() if self.timelock is not None else None,
|
|
154
|
+
"fee_policy": self.fee_policy.to_canonical() if self.fee_policy is not None else None,
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
__all__ = ["BitcoinPolicy"]
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import cast
|
|
6
|
+
|
|
7
|
+
from ..core.errors import (
|
|
8
|
+
DependencyError,
|
|
9
|
+
NetworkMismatchError,
|
|
10
|
+
SettlementError,
|
|
11
|
+
TimelockError,
|
|
12
|
+
ValidationError,
|
|
13
|
+
)
|
|
14
|
+
from ..core.ids import SignerId
|
|
15
|
+
from ..core.terms import FeePolicy
|
|
16
|
+
from ..core.validation import require_int
|
|
17
|
+
from ..fsm.states import SettlementAction, SettlementPath
|
|
18
|
+
from .addresses import BtcPayout
|
|
19
|
+
from .fees import dust_rate, dust_threshold, estimate_vsize, output_dust, validate_fee, vsize_bounds
|
|
20
|
+
from .funding import BtcUtxo
|
|
21
|
+
from .policy import BitcoinPolicy
|
|
22
|
+
from .timelock import TimelockMaturity, validate_maturity
|
|
23
|
+
|
|
24
|
+
try:
|
|
25
|
+
from embit import ec
|
|
26
|
+
from embit.psbt import PSBT, DerivationPath
|
|
27
|
+
from embit.script import Script
|
|
28
|
+
from embit.transaction import (
|
|
29
|
+
SIGHASH,
|
|
30
|
+
Transaction,
|
|
31
|
+
TransactionInput,
|
|
32
|
+
TransactionOutput,
|
|
33
|
+
)
|
|
34
|
+
except ImportError as exc:
|
|
35
|
+
raise DependencyError("embit") from exc
|
|
36
|
+
|
|
37
|
+
_NON_RBF = 0xFFFFFFFE
|
|
38
|
+
_MAX_INPUTS = 100
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True, slots=True)
|
|
42
|
+
class BitcoinSettlementPlan:
|
|
43
|
+
action: SettlementAction
|
|
44
|
+
policy: BitcoinPolicy
|
|
45
|
+
payout: BtcPayout
|
|
46
|
+
amount: int
|
|
47
|
+
fee: int
|
|
48
|
+
change: int
|
|
49
|
+
utxos: tuple[BtcUtxo, ...]
|
|
50
|
+
tx: Transaction
|
|
51
|
+
psbt: PSBT
|
|
52
|
+
path: SettlementPath = SettlementPath.PRIMARY
|
|
53
|
+
maturity: TimelockMaturity | None = None
|
|
54
|
+
fee_policy: FeePolicy | None = None
|
|
55
|
+
required_approvers: frozenset[SignerId] | None = None
|
|
56
|
+
approver_threshold: int | None = None
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def psbt_base64(self) -> str:
|
|
60
|
+
return cast(str, self.psbt.to_base64())
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def unsigned_tx_hex(self) -> str:
|
|
64
|
+
return cast(bytes, self.tx.serialize()).hex()
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def unsigned_txid(self) -> bytes:
|
|
68
|
+
return cast(bytes, self.tx.txid())[::-1]
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def payload_hash(self) -> bytes:
|
|
72
|
+
return hashlib.sha256(cast(bytes, self.tx.serialize())).digest()
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def sequence(self) -> int:
|
|
76
|
+
return cast(int, self.tx.vin[0].sequence)
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def fee_rate_sat_vb(self) -> int:
|
|
80
|
+
scripts = tuple(output.script_pubkey.data for output in self.tx.vout)
|
|
81
|
+
estimate = estimate_vsize(self.policy, len(self.utxos), scripts, self.path)
|
|
82
|
+
return self.fee // max(1, estimate)
|
|
83
|
+
|
|
84
|
+
def summary(self) -> str:
|
|
85
|
+
return (
|
|
86
|
+
f"{self.action.value} {self.path.value} {self.amount} "
|
|
87
|
+
f"{self.payout.address} fee {self.fee} change {self.change} "
|
|
88
|
+
f"rate {self.fee_rate_sat_vb} seq {self.sequence}"
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
def to_canonical(self) -> dict[str, object]:
|
|
92
|
+
return {
|
|
93
|
+
"kind": "bitcoin",
|
|
94
|
+
"action": self.action.value,
|
|
95
|
+
"policy": self.policy.to_canonical(),
|
|
96
|
+
"payout": self.payout.to_canonical(),
|
|
97
|
+
"amount": self.amount,
|
|
98
|
+
"fee": self.fee,
|
|
99
|
+
"change": self.change,
|
|
100
|
+
"utxos": [utxo.to_canonical() for utxo in self.utxos],
|
|
101
|
+
"tx": cast(bytes, self.tx.serialize()).hex(),
|
|
102
|
+
"psbt": self.psbt_base64,
|
|
103
|
+
"path": self.path.value,
|
|
104
|
+
"maturity": None if self.maturity is None else self.maturity.to_canonical(),
|
|
105
|
+
"fee_policy": None
|
|
106
|
+
if self.fee_policy is None
|
|
107
|
+
else self.fee_policy.to_canonical(),
|
|
108
|
+
"required_approvers": None
|
|
109
|
+
if self.required_approvers is None
|
|
110
|
+
else [item.value for item in sorted(self.required_approvers, key=lambda x: x.value)],
|
|
111
|
+
"approver_threshold": self.approver_threshold,
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _build_derivations(policy: BitcoinPolicy) -> list[tuple[object, DerivationPath]]:
|
|
116
|
+
out: list[tuple[object, DerivationPath]] = []
|
|
117
|
+
for signer in policy.signers:
|
|
118
|
+
key = ec.PublicKey.parse(signer.public_key())
|
|
119
|
+
path = DerivationPath(signer.fingerprint, list(signer.derivation_path()))
|
|
120
|
+
out.append((key, path))
|
|
121
|
+
return out
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def build_settlement_psbt(
|
|
125
|
+
policy: BitcoinPolicy,
|
|
126
|
+
payout: BtcPayout,
|
|
127
|
+
amount: int,
|
|
128
|
+
utxos: tuple[BtcUtxo, ...],
|
|
129
|
+
fee: int,
|
|
130
|
+
action: SettlementAction = SettlementAction.RELEASE,
|
|
131
|
+
path: SettlementPath = SettlementPath.PRIMARY,
|
|
132
|
+
maturity: TimelockMaturity | None = None,
|
|
133
|
+
fee_policy: FeePolicy | None = None,
|
|
134
|
+
) -> BitcoinSettlementPlan:
|
|
135
|
+
if not isinstance(policy, BitcoinPolicy):
|
|
136
|
+
raise ValidationError("policy")
|
|
137
|
+
if not isinstance(payout, BtcPayout):
|
|
138
|
+
raise ValidationError("payout")
|
|
139
|
+
if not isinstance(action, SettlementAction):
|
|
140
|
+
raise ValidationError("action")
|
|
141
|
+
if not isinstance(path, SettlementPath):
|
|
142
|
+
raise ValidationError("path")
|
|
143
|
+
if payout.network != policy.network:
|
|
144
|
+
raise NetworkMismatchError("payout network")
|
|
145
|
+
if fee_policy is not None and not isinstance(fee_policy, FeePolicy):
|
|
146
|
+
raise ValidationError("fee policy")
|
|
147
|
+
active_fee_policy = fee_policy if fee_policy is not None else policy.fee_policy
|
|
148
|
+
value = require_int(amount, "amount", 1, (1 << 64) - 1)
|
|
149
|
+
fee_sats = require_int(fee, "fee", 0, (1 << 64) - 1)
|
|
150
|
+
items = tuple(utxos)
|
|
151
|
+
if not 1 <= len(items) <= _MAX_INPUTS:
|
|
152
|
+
raise ValidationError("utxo count")
|
|
153
|
+
seen: set[tuple[bytes, int]] = set()
|
|
154
|
+
total = 0
|
|
155
|
+
escrow_script = policy.script_pubkey()
|
|
156
|
+
for utxo in items:
|
|
157
|
+
if not isinstance(utxo, BtcUtxo):
|
|
158
|
+
raise ValidationError("utxo type")
|
|
159
|
+
if utxo.script_pubkey != escrow_script:
|
|
160
|
+
raise SettlementError("utxo script")
|
|
161
|
+
outpoint = (utxo.txid, utxo.output_index)
|
|
162
|
+
if outpoint in seen:
|
|
163
|
+
raise SettlementError("utxo duplicate")
|
|
164
|
+
seen.add(outpoint)
|
|
165
|
+
total += utxo.amount
|
|
166
|
+
if output_dust(value, payout.script_pubkey, active_fee_policy):
|
|
167
|
+
raise SettlementError("dust output")
|
|
168
|
+
if total < value + fee_sats:
|
|
169
|
+
raise SettlementError("insufficient funds")
|
|
170
|
+
sequence = _NON_RBF
|
|
171
|
+
if path is SettlementPath.TIMELOCK:
|
|
172
|
+
timelock = policy.timelock
|
|
173
|
+
if timelock is None:
|
|
174
|
+
raise TimelockError("timelock missing")
|
|
175
|
+
if action is not SettlementAction.REFUND:
|
|
176
|
+
raise TimelockError("timelock action")
|
|
177
|
+
if maturity is None:
|
|
178
|
+
raise TimelockError("maturity missing")
|
|
179
|
+
validate_maturity(
|
|
180
|
+
timelock,
|
|
181
|
+
maturity,
|
|
182
|
+
tuple(utxo.confirmations for utxo in items),
|
|
183
|
+
)
|
|
184
|
+
sequence = timelock.sequence()
|
|
185
|
+
elif maturity is not None:
|
|
186
|
+
raise TimelockError("maturity path")
|
|
187
|
+
rate = dust_rate(active_fee_policy)
|
|
188
|
+
raw_change = total - value - fee_sats
|
|
189
|
+
output_scripts: tuple[bytes, ...]
|
|
190
|
+
if 0 < raw_change < dust_threshold(escrow_script, rate):
|
|
191
|
+
effective_fee = fee_sats + raw_change
|
|
192
|
+
change = 0
|
|
193
|
+
output_scripts = (payout.script_pubkey,)
|
|
194
|
+
else:
|
|
195
|
+
effective_fee = fee_sats
|
|
196
|
+
change = raw_change
|
|
197
|
+
output_scripts = (
|
|
198
|
+
(payout.script_pubkey, escrow_script) if change else (payout.script_pubkey,)
|
|
199
|
+
)
|
|
200
|
+
if active_fee_policy is not None:
|
|
201
|
+
bounds = vsize_bounds(policy, len(items), output_scripts, path)
|
|
202
|
+
validate_fee(active_fee_policy, effective_fee, bounds)
|
|
203
|
+
vout = [TransactionOutput(value, Script(payout.script_pubkey))]
|
|
204
|
+
if change:
|
|
205
|
+
vout.append(TransactionOutput(change, Script(escrow_script)))
|
|
206
|
+
vin = [
|
|
207
|
+
TransactionInput(utxo.txid[::-1], utxo.output_index, sequence=sequence) for utxo in items
|
|
208
|
+
]
|
|
209
|
+
tx = Transaction(version=2, vin=vin, vout=vout)
|
|
210
|
+
psbt = PSBT(tx)
|
|
211
|
+
if psbt.version is not None:
|
|
212
|
+
raise SettlementError("psbt version")
|
|
213
|
+
witness_script = Script(policy.witness_script())
|
|
214
|
+
redeem = policy.redeem_script()
|
|
215
|
+
redeem_script = None if redeem is None else Script(redeem)
|
|
216
|
+
derivations = _build_derivations(policy)
|
|
217
|
+
for i, utxo in enumerate(items):
|
|
218
|
+
inp = psbt.inputs[i]
|
|
219
|
+
inp.witness_utxo = TransactionOutput(utxo.amount, Script(utxo.script_pubkey))
|
|
220
|
+
inp.witness_script = witness_script
|
|
221
|
+
inp.redeem_script = redeem_script
|
|
222
|
+
inp.sighash_type = int(SIGHASH.ALL)
|
|
223
|
+
for key, path_item in derivations:
|
|
224
|
+
inp.bip32_derivations[key] = path_item
|
|
225
|
+
return BitcoinSettlementPlan(
|
|
226
|
+
action=action,
|
|
227
|
+
policy=policy,
|
|
228
|
+
payout=payout,
|
|
229
|
+
amount=value,
|
|
230
|
+
fee=effective_fee,
|
|
231
|
+
change=change,
|
|
232
|
+
utxos=items,
|
|
233
|
+
tx=tx,
|
|
234
|
+
psbt=psbt,
|
|
235
|
+
path=path,
|
|
236
|
+
maturity=maturity,
|
|
237
|
+
fee_policy=active_fee_policy,
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
__all__ = ["BitcoinSettlementPlan", "build_settlement_psbt"]
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from enum import StrEnum
|
|
5
|
+
|
|
6
|
+
from ..core.errors import PolicyError, TimelockError, ValidationError
|
|
7
|
+
from ..core.ids import SignerId
|
|
8
|
+
from ..core.roles import RecoveryPolicy
|
|
9
|
+
from ..core.validation import require_bytes, require_int
|
|
10
|
+
|
|
11
|
+
_BLOCKS_MAX = 0xFFFF
|
|
12
|
+
_CONFIRMATIONS_MAX = (1 << 32) - 1
|
|
13
|
+
_PUSH_MAX = 0xFFFF
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class CsvUnit(StrEnum):
|
|
17
|
+
BLOCKS = "blocks"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True, slots=True)
|
|
21
|
+
class CsvDelay:
|
|
22
|
+
value: int
|
|
23
|
+
unit: CsvUnit = CsvUnit.BLOCKS
|
|
24
|
+
|
|
25
|
+
def __post_init__(self) -> None:
|
|
26
|
+
value = require_int(self.value, "delay", 1, _BLOCKS_MAX)
|
|
27
|
+
if not isinstance(self.unit, CsvUnit) or self.unit is not CsvUnit.BLOCKS:
|
|
28
|
+
raise ValidationError("delay unit")
|
|
29
|
+
object.__setattr__(self, "value", value)
|
|
30
|
+
|
|
31
|
+
@classmethod
|
|
32
|
+
def blocks(cls, value: int) -> CsvDelay:
|
|
33
|
+
return cls(value, CsvUnit.BLOCKS)
|
|
34
|
+
|
|
35
|
+
def sequence(self) -> int:
|
|
36
|
+
return self.value
|
|
37
|
+
|
|
38
|
+
def to_canonical(self) -> dict[str, object]:
|
|
39
|
+
return {"value": self.value, "unit": self.unit.value}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True, slots=True)
|
|
43
|
+
class TimelockMaturity:
|
|
44
|
+
confirmations: int
|
|
45
|
+
|
|
46
|
+
def __post_init__(self) -> None:
|
|
47
|
+
require_int(self.confirmations, "maturity", 0, _CONFIRMATIONS_MAX)
|
|
48
|
+
|
|
49
|
+
def to_canonical(self) -> dict[str, object]:
|
|
50
|
+
return {"confirmations": self.confirmations}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True, slots=True)
|
|
54
|
+
class TimelockRefund:
|
|
55
|
+
delay: CsvDelay
|
|
56
|
+
refund_signer_id: SignerId
|
|
57
|
+
refund_policy: RecoveryPolicy
|
|
58
|
+
|
|
59
|
+
def __post_init__(self) -> None:
|
|
60
|
+
if not isinstance(self.delay, CsvDelay):
|
|
61
|
+
raise ValidationError("delay")
|
|
62
|
+
if not isinstance(self.refund_signer_id, SignerId):
|
|
63
|
+
raise ValidationError("refund signer")
|
|
64
|
+
if not isinstance(self.refund_policy, RecoveryPolicy):
|
|
65
|
+
raise ValidationError("refund policy")
|
|
66
|
+
if self.refund_policy.threshold != 1:
|
|
67
|
+
raise PolicyError("refund threshold")
|
|
68
|
+
if self.refund_policy.allowed != (self.refund_signer_id,):
|
|
69
|
+
raise PolicyError("refund allowed")
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def recovery_policy(self) -> RecoveryPolicy:
|
|
73
|
+
return self.refund_policy
|
|
74
|
+
|
|
75
|
+
def sequence(self) -> int:
|
|
76
|
+
return self.delay.sequence()
|
|
77
|
+
|
|
78
|
+
def to_canonical(self) -> dict[str, object]:
|
|
79
|
+
return {
|
|
80
|
+
"delay": self.delay.to_canonical(),
|
|
81
|
+
"refund_signer_id": self.refund_signer_id.value,
|
|
82
|
+
"refund_policy": self.refund_policy.to_canonical(),
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def validate_maturity(
|
|
87
|
+
timelock: TimelockRefund,
|
|
88
|
+
maturity: TimelockMaturity,
|
|
89
|
+
funding_confirmations: tuple[int, ...] = (),
|
|
90
|
+
) -> TimelockMaturity:
|
|
91
|
+
if not isinstance(timelock, TimelockRefund):
|
|
92
|
+
raise TimelockError("timelock")
|
|
93
|
+
if not isinstance(maturity, TimelockMaturity):
|
|
94
|
+
raise TimelockError("maturity")
|
|
95
|
+
required = timelock.delay.value
|
|
96
|
+
if maturity.confirmations < required:
|
|
97
|
+
raise TimelockError("immature")
|
|
98
|
+
for confirmations in funding_confirmations:
|
|
99
|
+
if not isinstance(confirmations, int) or isinstance(confirmations, bool):
|
|
100
|
+
raise TimelockError("confirmations")
|
|
101
|
+
if confirmations < required:
|
|
102
|
+
raise TimelockError("immature")
|
|
103
|
+
return maturity
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _push_int(value: int) -> bytes:
|
|
107
|
+
number = require_int(value, "script number", 0, _PUSH_MAX)
|
|
108
|
+
if number == 0:
|
|
109
|
+
return b"\x00"
|
|
110
|
+
if number <= 16:
|
|
111
|
+
return bytes([0x50 + number])
|
|
112
|
+
raw = number.to_bytes((number.bit_length() + 7) // 8, "little")
|
|
113
|
+
if raw[-1] & 0x80:
|
|
114
|
+
raw += b"\x00"
|
|
115
|
+
return bytes([len(raw)]) + raw
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _push_bytes(value: bytes) -> bytes:
|
|
119
|
+
raw = require_bytes(value, "push", minimum=1, maximum=75)
|
|
120
|
+
return bytes([len(raw)]) + raw
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _multisig(threshold: int, keys: tuple[bytes, ...]) -> bytes:
|
|
124
|
+
raw = bytes([0x50 + threshold])
|
|
125
|
+
raw += b"".join(_push_bytes(key) for key in keys)
|
|
126
|
+
raw += bytes([0x50 + len(keys), 0xAE])
|
|
127
|
+
return raw
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def build_timelock_script(
|
|
131
|
+
threshold: int,
|
|
132
|
+
public_keys: tuple[bytes, ...],
|
|
133
|
+
sequence: int,
|
|
134
|
+
refund_public_key: bytes,
|
|
135
|
+
) -> bytes:
|
|
136
|
+
count = require_int(threshold, "threshold", 2, 15)
|
|
137
|
+
try:
|
|
138
|
+
keys = tuple(sorted(public_keys))
|
|
139
|
+
except Exception as exc:
|
|
140
|
+
raise ValidationError("keys") from exc
|
|
141
|
+
if len(keys) < count or len(keys) > 15 or len(set(keys)) != len(keys):
|
|
142
|
+
raise ValidationError("keys")
|
|
143
|
+
for key in keys:
|
|
144
|
+
if not isinstance(key, bytes) or len(key) != 33 or key[0] not in (2, 3):
|
|
145
|
+
raise ValidationError("public key")
|
|
146
|
+
if (
|
|
147
|
+
not isinstance(refund_public_key, bytes)
|
|
148
|
+
or len(refund_public_key) != 33
|
|
149
|
+
or refund_public_key[0] not in (2, 3)
|
|
150
|
+
):
|
|
151
|
+
raise ValidationError("refund key")
|
|
152
|
+
value = require_int(sequence, "sequence", 1, _BLOCKS_MAX)
|
|
153
|
+
raw = b"\x63" + _multisig(count, keys)
|
|
154
|
+
raw += b"\x67" + _push_int(value) + b"\xb2\x75"
|
|
155
|
+
raw += _push_bytes(refund_public_key) + b"\xac\x68"
|
|
156
|
+
return raw
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
__all__ = [
|
|
160
|
+
"CsvDelay",
|
|
161
|
+
"CsvUnit",
|
|
162
|
+
"TimelockMaturity",
|
|
163
|
+
"TimelockRefund",
|
|
164
|
+
"build_timelock_script",
|
|
165
|
+
"validate_maturity",
|
|
166
|
+
]
|