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,103 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, cast
5
+
6
+ from ..core.errors import DependencyError, NetworkMismatchError, ValidationError
7
+ from ..core.validation import require_bytes, require_str
8
+ from .keys import BitcoinChain, BitcoinNetwork, network_data
9
+
10
+ try:
11
+ from embit.script import Script
12
+ except ImportError as exc:
13
+ raise DependencyError("embit") from exc
14
+
15
+ _ADDRESS_TYPES = frozenset({"p2pkh", "p2sh", "p2wpkh", "p2wsh", "p2tr"})
16
+ _SEGWIT_TYPES = frozenset({"p2wpkh", "p2wsh", "p2tr"})
17
+
18
+
19
+ def _script(address: str) -> Any:
20
+ text = require_str(address, "address", 14, 128, True)
21
+ if text != text.strip():
22
+ raise ValidationError("address space")
23
+ lower = text.lower()
24
+ bech32 = lower.startswith(("bc1", "tb1", "bcrt1"))
25
+ if bech32:
26
+ if text != text.lower() and text != text.upper():
27
+ raise ValidationError("address case")
28
+ text = lower
29
+ try:
30
+ return Script.from_address(text)
31
+ except Exception as exc:
32
+ raise ValidationError("address format") from exc
33
+
34
+
35
+ def address_to_script(address: str, network: BitcoinNetwork) -> bytes:
36
+ data = network_data(network)
37
+ script = _script(address)
38
+ kind = script.script_type()
39
+ if kind not in _ADDRESS_TYPES:
40
+ raise ValidationError("address type")
41
+ canonical = script.address(data)
42
+ if kind in _SEGWIT_TYPES:
43
+ if address.lower() != canonical:
44
+ raise NetworkMismatchError("address network")
45
+ elif address != canonical:
46
+ raise NetworkMismatchError("address network")
47
+ return cast(bytes, script.data)
48
+
49
+
50
+ def script_to_address(script_pubkey: bytes, network: BitcoinNetwork) -> str:
51
+ data = network_data(network)
52
+ raw = require_bytes(script_pubkey, "script pubkey", minimum=1, maximum=10000)
53
+ script = Script(raw)
54
+ kind = script.script_type()
55
+ if kind not in _ADDRESS_TYPES:
56
+ raise ValidationError("script type")
57
+ address = cast(str, script.address(data))
58
+ if address_to_script(address, network) != raw:
59
+ raise ValidationError("script round trip")
60
+ return address
61
+
62
+
63
+ @dataclass(frozen=True, slots=True)
64
+ class BtcPayout:
65
+ address: str
66
+ network: BitcoinNetwork
67
+ script_pubkey: bytes
68
+
69
+ def __post_init__(self) -> None:
70
+ network_data(self.network)
71
+ require_bytes(self.script_pubkey, "script pubkey", minimum=1, maximum=10000)
72
+ require_str(self.address, "address", 14, 128, True)
73
+ script = address_to_script(self.address, self.network)
74
+ if script != self.script_pubkey:
75
+ raise ValidationError("payout script")
76
+ canonical = script_to_address(script, self.network)
77
+ object.__setattr__(self, "address", canonical)
78
+
79
+ @classmethod
80
+ def from_address(cls, address: str, network: BitcoinNetwork) -> BtcPayout:
81
+ return cls(address, network, address_to_script(address, network))
82
+
83
+ @property
84
+ def chain(self) -> BitcoinChain:
85
+ return BitcoinChain(self.network)
86
+
87
+ def display(self) -> str:
88
+ return self.address
89
+
90
+ def validate(self) -> None:
91
+ script = address_to_script(self.address, self.network)
92
+ if script != self.script_pubkey:
93
+ raise ValidationError("payout script")
94
+
95
+ def to_canonical(self) -> dict[str, object]:
96
+ return {
97
+ "address": self.address,
98
+ "network": self.network.value,
99
+ "script_pubkey": self.script_pubkey,
100
+ }
101
+
102
+
103
+ __all__ = ["BtcPayout", "address_to_script", "script_to_address"]
@@ -0,0 +1,29 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+
5
+ from ..core.amounts import MAX_BTC_SATS
6
+ from ..core.errors import ValidationError
7
+ from ..core.validation import require_int, require_str
8
+
9
+
10
+ @dataclass(frozen=True, slots=True)
11
+ class BtcAsset:
12
+ symbol: str = "BTC"
13
+ decimals: int = 8
14
+
15
+ def __post_init__(self) -> None:
16
+ symbol = require_str(self.symbol, "symbol", 1, 16, True)
17
+ if symbol != "BTC":
18
+ raise ValidationError("symbol")
19
+ require_int(self.decimals, "decimals", 8, 8)
20
+ object.__setattr__(self, "symbol", symbol)
21
+
22
+ def validate_amount(self, amount: int) -> None:
23
+ require_int(amount, "amount", 1, MAX_BTC_SATS)
24
+
25
+ def to_canonical(self) -> dict[str, object]:
26
+ return {"symbol": self.symbol, "decimals": self.decimals}
27
+
28
+
29
+ __all__ = ["BtcAsset"]
@@ -0,0 +1,211 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Sequence
4
+ from typing import cast
5
+
6
+ from ..core.errors import DependencyError, ParserError, ValidationError
7
+ from ..core.validation import require_bool, require_int, require_str
8
+ from .keys import BitcoinNetwork, BtcSigner, network_data
9
+
10
+ try:
11
+ from embit import ec
12
+ from embit import script as _script
13
+ from embit.descriptor import Descriptor
14
+ from embit.descriptor import checksum as _checksum
15
+ except ImportError as exc:
16
+ raise DependencyError("embit") from exc
17
+
18
+
19
+ def sort_public_keys(keys: Sequence[bytes]) -> tuple[bytes, ...]:
20
+ out: list[bytes] = []
21
+ seen: set[bytes] = set()
22
+ for key in keys:
23
+ if type(key) is not bytes or len(key) != 33 or key[0] not in (2, 3):
24
+ raise ValidationError("public key")
25
+ try:
26
+ ec.PublicKey.parse(key)
27
+ except Exception as exc:
28
+ raise ValidationError("public key") from exc
29
+ if key in seen:
30
+ raise ValidationError("public key duplicate")
31
+ seen.add(key)
32
+ out.append(key)
33
+ if not out:
34
+ raise ValidationError("public keys")
35
+ return tuple(sorted(out))
36
+
37
+
38
+ def build_multisig_descriptor(
39
+ threshold: int,
40
+ signers: tuple[BtcSigner, ...],
41
+ wrapped: bool = False,
42
+ ) -> str:
43
+ count = require_int(threshold, "threshold", 2, 15)
44
+ if len(signers) < count or len(signers) > 15:
45
+ raise ValidationError("signer count")
46
+ keys = []
47
+ for signer in signers:
48
+ if not isinstance(signer, BtcSigner):
49
+ raise ValidationError("signer type")
50
+ keys.append(signer.descriptor_key())
51
+ body = f"wsh(sortedmulti({count},{','.join(keys)}))"
52
+ if require_bool(wrapped, "wrapped"):
53
+ body = f"sh({body})"
54
+ try:
55
+ Descriptor.from_string(body)
56
+ except Exception as exc:
57
+ raise ValidationError("descriptor") from exc
58
+ return body
59
+
60
+
61
+ def _body(descriptor: str) -> str:
62
+ text = require_str(descriptor, "descriptor", 1, 100000, True)
63
+ body, marker, tail = text.partition("#")
64
+ if marker and len(tail) != 8:
65
+ raise ValidationError("checksum length")
66
+ return body
67
+
68
+
69
+ def descriptor_checksum(descriptor: str) -> str:
70
+ body = _body(descriptor)
71
+ try:
72
+ return cast(str, _checksum.checksum(body))
73
+ except Exception as exc:
74
+ raise ValidationError("descriptor checksum") from exc
75
+
76
+
77
+ def with_checksum(descriptor: str) -> str:
78
+ body = _body(descriptor)
79
+ try:
80
+ return cast(str, _checksum.add_checksum(body))
81
+ except Exception as exc:
82
+ raise ValidationError("descriptor checksum") from exc
83
+
84
+
85
+ def validate_descriptor_checksum(descriptor: str) -> str:
86
+ text = require_str(descriptor, "descriptor", 1, 100000, True)
87
+ body, marker, tail = text.partition("#")
88
+ if marker != "#":
89
+ raise ValidationError("checksum missing")
90
+ if len(tail) != 8:
91
+ raise ValidationError("checksum length")
92
+ expected = descriptor_checksum(body)
93
+ if tail != expected:
94
+ raise ValidationError("checksum mismatch")
95
+ return body
96
+
97
+
98
+ def parse_descriptor(descriptor: str, require_checksum: bool = True) -> Descriptor:
99
+ body = validate_descriptor_checksum(descriptor) if require_checksum else _body(descriptor)
100
+ try:
101
+ return cast(Descriptor, Descriptor.from_string(body))
102
+ except Exception as exc:
103
+ raise ParserError("descriptor parse") from exc
104
+
105
+
106
+ def _derived_public_keys(desc: Descriptor) -> tuple[bytes, ...]:
107
+ if not desc.is_basic_multisig or not desc.wsh:
108
+ raise ValidationError("descriptor policy")
109
+ keys: list[bytes] = []
110
+ seen: set[bytes] = set()
111
+ for key in desc.keys:
112
+ if not key.is_extended:
113
+ public = cast(bytes, key.key.sec())
114
+ elif key.allowed_derivation is None:
115
+ public = cast(bytes, key.key.get_public_key().sec())
116
+ else:
117
+ indexes = key.allowed_derivation.indexes
118
+ if any(isinstance(index, list) or index is None for index in indexes):
119
+ raise ValidationError("descriptor wildcard")
120
+ if any(index >= (1 << 31) for index in indexes):
121
+ raise ValidationError("descriptor hardened")
122
+ public = cast(bytes, key.key.derive(indexes).get_public_key().sec())
123
+ if len(public) != 33 or public[0] not in (2, 3):
124
+ raise ValidationError("public key")
125
+ if public in seen:
126
+ raise ValidationError("public key duplicate")
127
+ seen.add(public)
128
+ keys.append(public)
129
+ return tuple(keys)
130
+
131
+
132
+ def _witness_script(desc: Descriptor) -> bytes:
133
+ keys = _derived_public_keys(desc)
134
+ if desc.is_sorted:
135
+ keys = sort_public_keys(keys)
136
+ threshold = int(desc.miniscript.args[0].num)
137
+ if threshold < 1 or threshold > len(keys):
138
+ raise ValidationError("threshold")
139
+ raw = bytes([0x50 + threshold])
140
+ raw += b"".join(bytes([len(key)]) + key for key in keys)
141
+ raw += bytes([0x50 + len(keys), 0xAE])
142
+ return raw
143
+
144
+
145
+ def _script_pubkey(desc: Descriptor) -> bytes:
146
+ witness = _witness_script(desc)
147
+ redeem = _script.p2wsh(_script.Script(witness))
148
+ return cast(bytes, (_script.p2sh(redeem) if desc.sh else redeem).data)
149
+
150
+
151
+ def descriptor_script_pubkey(descriptor: str, require_checksum: bool = True) -> bytes:
152
+ return _script_pubkey(parse_descriptor(descriptor, require_checksum))
153
+
154
+
155
+ def descriptor_address(
156
+ descriptor: str,
157
+ network: BitcoinNetwork,
158
+ require_checksum: bool = True,
159
+ ) -> str:
160
+ raw = descriptor_script_pubkey(descriptor, require_checksum)
161
+ return cast(str, _script.Script(raw).address(network_data(network)))
162
+
163
+
164
+ def descriptor_witness_script(descriptor: str, require_checksum: bool = True) -> bytes:
165
+ return _witness_script(parse_descriptor(descriptor, require_checksum))
166
+
167
+
168
+ def descriptor_redeem_script(descriptor: str, require_checksum: bool = True) -> bytes | None:
169
+ desc = parse_descriptor(descriptor, require_checksum)
170
+ if not desc.sh:
171
+ return None
172
+ return cast(bytes, _script.p2wsh(_script.Script(_witness_script(desc))).data)
173
+
174
+
175
+ def witness_script_script_pubkey(witness_script: bytes, wrapped: bool = False) -> bytes:
176
+ if not isinstance(witness_script, bytes) or not 1 <= len(witness_script) <= 10000:
177
+ raise ValidationError("witness script")
178
+ wsh = _script.p2wsh(_script.Script(witness_script))
179
+ return cast(bytes, (_script.p2sh(wsh) if wrapped else wsh).data)
180
+
181
+
182
+ def witness_script_redeem_script(witness_script: bytes, wrapped: bool = False) -> bytes | None:
183
+ if not wrapped:
184
+ return None
185
+ return cast(bytes, _script.p2wsh(_script.Script(witness_script)).data)
186
+
187
+
188
+ def witness_script_address(
189
+ witness_script: bytes,
190
+ network: BitcoinNetwork,
191
+ wrapped: bool = False,
192
+ ) -> str:
193
+ raw = witness_script_script_pubkey(witness_script, wrapped)
194
+ return cast(str, _script.Script(raw).address(network_data(network)))
195
+
196
+
197
+ __all__ = [
198
+ "build_multisig_descriptor",
199
+ "descriptor_address",
200
+ "descriptor_checksum",
201
+ "descriptor_redeem_script",
202
+ "descriptor_script_pubkey",
203
+ "descriptor_witness_script",
204
+ "parse_descriptor",
205
+ "sort_public_keys",
206
+ "validate_descriptor_checksum",
207
+ "with_checksum",
208
+ "witness_script_address",
209
+ "witness_script_redeem_script",
210
+ "witness_script_script_pubkey",
211
+ ]
@@ -0,0 +1,282 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Sequence
4
+ from dataclasses import dataclass
5
+ from typing import TYPE_CHECKING, Any, cast
6
+
7
+ from ..core.amounts import MAX_BTC_SATS
8
+ from ..core.errors import SettlementError, ValidationError
9
+ from ..core.terms import FeePolicy
10
+ from ..core.validation import require_bytes, require_int
11
+ from ..fsm.states import SettlementPath
12
+
13
+ if TYPE_CHECKING:
14
+ from .policy import BitcoinPolicy
15
+
16
+ _DUST_RELAY_RATE = 3
17
+ _WITNESS_SPEND_SIZE = 67
18
+ _LEGACY_SPEND_SIZE = 148
19
+ _MIN_SIGNATURE_SIZE = 69
20
+ _MAX_SIGNATURE_SIZE = 73
21
+
22
+
23
+ class BitcoinFeePolicy(FeePolicy):
24
+ __slots__ = ()
25
+
26
+ def __init__(
27
+ self,
28
+ min_fee: int | None = None,
29
+ max_fee: int | None = None,
30
+ max_fee_rate_sat_vb: int | None = None,
31
+ min_fee_rate_sat_vb: int = 1,
32
+ *,
33
+ min_fee_sats: int | None = None,
34
+ max_fee_sats: int | None = None,
35
+ ) -> None:
36
+ if min_fee is not None and min_fee_sats is not None and min_fee != min_fee_sats:
37
+ raise ValidationError("min fee alias")
38
+ if max_fee is not None and max_fee_sats is not None and max_fee != max_fee_sats:
39
+ raise ValidationError("max fee alias")
40
+ minimum = min_fee if min_fee is not None else min_fee_sats
41
+ maximum = max_fee if max_fee is not None else max_fee_sats
42
+ if minimum is None or maximum is None:
43
+ raise ValidationError("fee missing")
44
+ FeePolicy.__init__(
45
+ self,
46
+ minimum,
47
+ maximum,
48
+ max_fee_rate_sat_vb,
49
+ min_fee_rate_sat_vb,
50
+ )
51
+
52
+ def __post_init__(self) -> None:
53
+ FeePolicy.__post_init__(self)
54
+ if self.min_fee > MAX_BTC_SATS or self.max_fee > MAX_BTC_SATS:
55
+ raise ValidationError("fee high")
56
+
57
+ @property
58
+ def min_fee_sats(self) -> int:
59
+ return self.min_fee
60
+
61
+ @property
62
+ def max_fee_sats(self) -> int:
63
+ return self.max_fee
64
+
65
+ @classmethod
66
+ def from_sats(
67
+ cls,
68
+ min_fee_sats: int,
69
+ max_fee_sats: int,
70
+ max_fee_rate_sat_vb: int | None = None,
71
+ min_fee_rate_sat_vb: int = 1,
72
+ ) -> BitcoinFeePolicy:
73
+ return cls(
74
+ min_fee_sats=min_fee_sats,
75
+ max_fee_sats=max_fee_sats,
76
+ max_fee_rate_sat_vb=max_fee_rate_sat_vb,
77
+ min_fee_rate_sat_vb=min_fee_rate_sat_vb,
78
+ )
79
+
80
+
81
+ @dataclass(frozen=True, slots=True)
82
+ class VsizeEstimate:
83
+ minimum: int
84
+ maximum: int
85
+
86
+ def __post_init__(self) -> None:
87
+ minimum = require_int(self.minimum, "vsize", 1, (1 << 63) - 1)
88
+ maximum = require_int(self.maximum, "vsize", 1, (1 << 63) - 1)
89
+ if minimum > maximum:
90
+ raise ValidationError("vsize order")
91
+ object.__setattr__(self, "minimum", minimum)
92
+ object.__setattr__(self, "maximum", maximum)
93
+
94
+
95
+ @dataclass(frozen=True, slots=True)
96
+ class FeeBounds:
97
+ minimum: int
98
+ maximum: int
99
+
100
+ def __post_init__(self) -> None:
101
+ minimum = require_int(self.minimum, "min fee", 0, MAX_BTC_SATS)
102
+ maximum = require_int(self.maximum, "max fee", 0, MAX_BTC_SATS)
103
+ if minimum > maximum:
104
+ raise ValidationError("fee order")
105
+ object.__setattr__(self, "minimum", minimum)
106
+ object.__setattr__(self, "maximum", maximum)
107
+
108
+
109
+ def _varint_size(value: int) -> int:
110
+ if value < 0xFD:
111
+ return 1
112
+ if value <= 0xFFFF:
113
+ return 3
114
+ if value <= 0xFFFFFFFF:
115
+ return 5
116
+ return 9
117
+
118
+
119
+ def _push_size(length: int) -> int:
120
+ if length < 0x4C:
121
+ return 1 + length
122
+ if length <= 0xFF:
123
+ return 2 + length
124
+ if length <= 0xFFFF:
125
+ return 3 + length
126
+ return 5 + length
127
+
128
+
129
+ def _witness_program(script_pubkey: bytes) -> bool:
130
+ if len(script_pubkey) < 4 or len(script_pubkey) > 42:
131
+ return False
132
+ version = script_pubkey[0]
133
+ if version != 0 and not 0x51 <= version <= 0x60:
134
+ return False
135
+ length = script_pubkey[1]
136
+ return 2 <= length <= 40 and length + 2 == len(script_pubkey)
137
+
138
+
139
+ def dust_threshold(script_pubkey: bytes, fee_rate_sat_vb: int = _DUST_RELAY_RATE) -> int:
140
+ script = require_bytes(script_pubkey, "script pubkey", minimum=1, maximum=10000)
141
+ rate = require_int(fee_rate_sat_vb, "dust rate", 0, MAX_BTC_SATS)
142
+ if script[0] == 0x6A:
143
+ return 0
144
+ output_size = 8 + _varint_size(len(script)) + len(script)
145
+ spend_size = _WITNESS_SPEND_SIZE if _witness_program(script) else _LEGACY_SPEND_SIZE
146
+ return (output_size + spend_size) * max(rate, _DUST_RELAY_RATE)
147
+
148
+
149
+ def is_dust(amount: int, script_pubkey: bytes, fee_rate_sat_vb: int = _DUST_RELAY_RATE) -> bool:
150
+ value = require_int(amount, "dust amount", 0, MAX_BTC_SATS)
151
+ return value < dust_threshold(script_pubkey, fee_rate_sat_vb)
152
+
153
+
154
+ def vsize_bounds(
155
+ policy: BitcoinPolicy,
156
+ input_count: int,
157
+ output_scripts: Sequence[bytes] | int,
158
+ path: SettlementPath = SettlementPath.PRIMARY,
159
+ ) -> VsizeEstimate:
160
+ from .policy import BitcoinPolicy as Policy
161
+
162
+ if not isinstance(policy, Policy):
163
+ raise ValidationError("policy")
164
+ if not isinstance(path, SettlementPath):
165
+ raise ValidationError("path")
166
+ count = require_int(input_count, "input count", 1, 100)
167
+ if isinstance(output_scripts, int) and not isinstance(output_scripts, bool):
168
+ outputs = require_int(output_scripts, "output count", 1, 100)
169
+ scripts = (b"\x00\x20" + b"\x00" * 32,) * outputs
170
+ else:
171
+ try:
172
+ scripts = tuple(cast(Any, output_scripts))
173
+ except Exception as exc:
174
+ raise ValidationError("output scripts") from exc
175
+ if not 1 <= len(scripts) <= 100:
176
+ raise ValidationError("output count")
177
+ for script in scripts:
178
+ require_bytes(script, "output script", minimum=1, maximum=10000)
179
+ if path is SettlementPath.TIMELOCK:
180
+ if policy.timelock is None:
181
+ raise ValidationError("timelock missing")
182
+ signatures = 1
183
+ else:
184
+ signatures = policy.threshold
185
+ witness_script = policy.witness_script()
186
+ redeem_script = policy.redeem_script()
187
+ script_sig = 0 if redeem_script is None else _push_size(len(redeem_script))
188
+ input_base = 36 + _varint_size(script_sig) + script_sig + 4
189
+ output_base = sum(8 + _varint_size(len(script)) + len(script) for script in scripts)
190
+ base = 4 + _varint_size(count) + _varint_size(len(scripts))
191
+ base += count * input_base + output_base + 4
192
+
193
+ def witness(signature_size: int) -> int:
194
+ stack = 1
195
+ if path is SettlementPath.TIMELOCK:
196
+ stack += 1 + signature_size
197
+ stack += 1
198
+ else:
199
+ stack += 1
200
+ stack += signatures * (1 + signature_size)
201
+ stack += 2
202
+ stack += _varint_size(len(witness_script)) + len(witness_script)
203
+ return 2 + count * stack
204
+
205
+ def vsize(signature_size: int) -> int:
206
+ return base + (witness(signature_size) + 3) // 4
207
+
208
+ return VsizeEstimate(vsize(_MIN_SIGNATURE_SIZE), vsize(_MAX_SIGNATURE_SIZE))
209
+
210
+
211
+ def estimate_vsize(
212
+ policy: BitcoinPolicy,
213
+ input_count: int,
214
+ output_scripts: Sequence[bytes] | int,
215
+ path: SettlementPath = SettlementPath.PRIMARY,
216
+ ) -> int:
217
+ return vsize_bounds(policy, input_count, output_scripts, path).maximum
218
+
219
+
220
+ def fee_bounds(policy: FeePolicy, estimate: VsizeEstimate | int) -> FeeBounds:
221
+ if not isinstance(policy, FeePolicy):
222
+ raise ValidationError("fee policy")
223
+ if isinstance(estimate, int) and not isinstance(estimate, bool):
224
+ estimate = VsizeEstimate(estimate, estimate)
225
+ if not isinstance(estimate, VsizeEstimate):
226
+ raise ValidationError("vsize")
227
+ minimum = max(
228
+ policy.min_fee,
229
+ policy.min_fee_rate_sat_vb * estimate.maximum,
230
+ )
231
+ maximum = policy.max_fee
232
+ if policy.max_fee_rate_sat_vb is not None:
233
+ maximum = min(
234
+ maximum,
235
+ policy.max_fee_rate_sat_vb * estimate.minimum,
236
+ )
237
+ return FeeBounds(minimum, maximum)
238
+
239
+
240
+ def validate_fee(policy: FeePolicy, fee: int, estimate: VsizeEstimate | int) -> FeeBounds:
241
+ if not isinstance(policy, FeePolicy):
242
+ raise ValidationError("fee policy")
243
+ if isinstance(estimate, int) and not isinstance(estimate, bool):
244
+ estimate = VsizeEstimate(estimate, estimate)
245
+ if not isinstance(estimate, VsizeEstimate):
246
+ raise ValidationError("vsize")
247
+ value = require_int(fee, "fee", 0, (1 << 64) - 1)
248
+ try:
249
+ bounds = fee_bounds(policy, estimate)
250
+ except ValidationError as exc:
251
+ raise SettlementError("fee bounds") from exc
252
+ if value < bounds.minimum:
253
+ raise SettlementError("fee low")
254
+ if value > bounds.maximum:
255
+ raise SettlementError("fee high")
256
+ return bounds
257
+
258
+
259
+ def dust_rate(policy: FeePolicy | None) -> int:
260
+ if policy is None:
261
+ return _DUST_RELAY_RATE
262
+ rate = require_int(policy.min_fee_rate_sat_vb, "min rate", 0, MAX_BTC_SATS)
263
+ return max(rate, _DUST_RELAY_RATE)
264
+
265
+
266
+ def output_dust(amount: int, script_pubkey: bytes, policy: FeePolicy | None) -> bool:
267
+ return is_dust(amount, script_pubkey, dust_rate(policy))
268
+
269
+
270
+ __all__ = [
271
+ "BitcoinFeePolicy",
272
+ "FeeBounds",
273
+ "VsizeEstimate",
274
+ "dust_rate",
275
+ "dust_threshold",
276
+ "estimate_vsize",
277
+ "fee_bounds",
278
+ "is_dust",
279
+ "output_dust",
280
+ "validate_fee",
281
+ "vsize_bounds",
282
+ ]