@babylonlabs-io/ledger-vault-signer 0.9.14 → 0.10.0
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.
- package/dist/delegatedClaimPsbt.d.ts +156 -0
- package/dist/delegatedClaimPsbt.d.ts.map +1 -0
- package/dist/expectedSignatures.d.ts.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +877 -762
- package/dist/index.js.map +1 -1
- package/dist/policyPsbt.d.ts.map +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the host takes from a payout leaf: the signer key D. The CSV timelock
|
|
3
|
+
* t2 decides whether the leaf is one at all, so it is read and range-checked,
|
|
4
|
+
* but nothing acts on its value, so it is not returned.
|
|
5
|
+
*
|
|
6
|
+
* @experimental
|
|
7
|
+
*/
|
|
8
|
+
export interface PayoutLeafTerms {
|
|
9
|
+
/** UNTWEAKED x-only key at leaf[1..33] (lowercase hex). */
|
|
10
|
+
readonly leafKeyHex: string;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Byte-for-byte mirror of the firmware's payout-leaf parser
|
|
14
|
+
* (`fw:sign_psbt_validate_helpers.c:158-219`, `parse_payout_leaf_script`),
|
|
15
|
+
* used by the PayoutFinalize validator on input 1: longer than the 68-byte
|
|
16
|
+
* NoPayout leaf, `<D> OP_CHECKSIGVERIFY`, a first challenger group opening
|
|
17
|
+
* with a 32-byte push at [34] and closing with OP_CHECKSIG at [67] (what
|
|
18
|
+
* separates it from the Vault-UTXO leaf), and a `<t2> OP_CSV` tail where t2
|
|
19
|
+
* is a 2-byte LE push with the sign bit clear or a 1-byte push, in
|
|
20
|
+
* `[90, 4032]`. Returns `undefined` where the firmware returns false.
|
|
21
|
+
*
|
|
22
|
+
* Firmware quirk mirrored on purpose (raised with Ledger as KB Q22; never
|
|
23
|
+
* code around it): the 2-byte branch is tried first and an out-of-band
|
|
24
|
+
* 2-byte value falls through to the 1-byte branch, so a tail `02 01 5a b2`
|
|
25
|
+
* (t2 = 23041) parses as t2 = 90 (`helpers.c:200-217`). Harmless for honest
|
|
26
|
+
* builders: nSequence 90 can never satisfy that CSV.
|
|
27
|
+
*
|
|
28
|
+
* @experimental
|
|
29
|
+
*/
|
|
30
|
+
export declare function parsePayoutLeafScript(script: Uint8Array): PayoutLeafTerms | undefined;
|
|
31
|
+
/**
|
|
32
|
+
* The five delegated-claim shapes the host must tell apart: three standalone
|
|
33
|
+
* (`claim`, `wronglyChallenged`, `payoutFinalize`), one intent-bound but
|
|
34
|
+
* relabelled here (`assert`), one recognised only to be routed back to the
|
|
35
|
+
* intent path (`payoutDepositor`).
|
|
36
|
+
*
|
|
37
|
+
* @experimental
|
|
38
|
+
*/
|
|
39
|
+
export type DelegatedClaimPsbtKind = "claim" | "wronglyChallenged" | "payoutFinalize" | "assert" | "payoutDepositor";
|
|
40
|
+
/**
|
|
41
|
+
* The one input each validator signs — a literal per firmware branch, never
|
|
42
|
+
* inferred from the PSBT (`fw:sign_custom_inputs.c:536-547` PayoutFinalize
|
|
43
|
+
* signs 1; `:692-703` Claim/WC/Assert sign 0; `:403-405` the intent-bound
|
|
44
|
+
* Payout signs 0).
|
|
45
|
+
*
|
|
46
|
+
* @experimental
|
|
47
|
+
*/
|
|
48
|
+
export declare const DELEGATED_CLAIM_SIGN_INPUT_INDEX: Readonly<Record<DelegatedClaimPsbtKind, number>>;
|
|
49
|
+
/** What the host needs from a recognised shape: where to sign, and whose key the leaf names. */
|
|
50
|
+
interface DelegatedClaimPsbtTerms {
|
|
51
|
+
readonly signInputIndex: number;
|
|
52
|
+
/** UNTWEAKED x-only key at leaf[1..33] of the signed input (lowercase hex). */
|
|
53
|
+
readonly leafKeyHex: string;
|
|
54
|
+
}
|
|
55
|
+
/** @experimental */
|
|
56
|
+
export type DelegatedClaimPsbtClassification = (DelegatedClaimPsbtTerms & {
|
|
57
|
+
readonly kind: "claim";
|
|
58
|
+
}) | (DelegatedClaimPsbtTerms & {
|
|
59
|
+
readonly kind: "wronglyChallenged";
|
|
60
|
+
}) | (DelegatedClaimPsbtTerms & {
|
|
61
|
+
readonly kind: "payoutFinalize";
|
|
62
|
+
}) | (DelegatedClaimPsbtTerms & {
|
|
63
|
+
readonly kind: "assert";
|
|
64
|
+
}) | (DelegatedClaimPsbtTerms & {
|
|
65
|
+
readonly kind: "payoutDepositor";
|
|
66
|
+
});
|
|
67
|
+
/**
|
|
68
|
+
* Classify a PSBT as one of the five delegated-claim shapes from the
|
|
69
|
+
* PROVIDER'S OWN PARSE plus the caller's requested input index —
|
|
70
|
+
* never from a caller flag. Anything else, including hex that does not
|
|
71
|
+
* parse, returns `undefined`, so the caller's ordinary gates keep their
|
|
72
|
+
* error precedence (the fail-safe direction: an unrecognised PSBT falls back
|
|
73
|
+
* to requiring an approved intent).
|
|
74
|
+
*
|
|
75
|
+
* Shapes, all v2/locktime-0 (`fw:sign_psbt_validate.c:2374`, `:2731`, `:3191`):
|
|
76
|
+
* - `claim`: 1 input, 2 outputs (`:2370`), input 0 leaf `<D> OP_CHECKSIG`
|
|
77
|
+
* of exactly 34 bytes (dispatch `:3677-3678`), requested index 0.
|
|
78
|
+
* - `wronglyChallenged`: exactly 1 input, 1 output, input 0 leaf of exactly
|
|
79
|
+
* 73 bytes with OP_SIZE at [34] (dispatch `:3681-3684`, layout
|
|
80
|
+
* `:2744-2755`), requested index 0. The validator itself admits more
|
|
81
|
+
* inputs (`:2727`, the wallet-policy route), but the dispatcher pre-routes
|
|
82
|
+
* 3-in/1-out to NoPayout in any state (`:3592`) and, under an intent,
|
|
83
|
+
* 2-in/non-2-out to Payout (`:3608-3610`) before the leaf dispatch, and
|
|
84
|
+
* btc-vault's WronglyChallenged is single-input (`wrongly_challenged.rs`),
|
|
85
|
+
* so only the one-input shape is the standalone WC this host signs.
|
|
86
|
+
* - `payoutFinalize`: 2 inputs, 2 outputs (dispatch `:3659-3660`), input 1
|
|
87
|
+
* leaf parsed by {@link parsePayoutLeafScript}, requested index 1, AND
|
|
88
|
+
* input 0 carrying no leaf and no derivation entry for D — the shape the
|
|
89
|
+
* claimer builder emits: btc-vault `ac4954e7` (the rev the facade bundles,
|
|
90
|
+
* `build-wasm.js:19-24`) populates taproot metadata on `ASSERT_PAYOUT_INPUT`
|
|
91
|
+
* only (`transactions/payout.rs:449-466`; `psbt.rs:125-144` sets
|
|
92
|
+
* `witness_utxo` on every input, leaf and key origins on listed ones).
|
|
93
|
+
* The depositor Payout is the same unsigned transaction with a leaf on
|
|
94
|
+
* input 0 and the caller asking for index 0; the device separates the two
|
|
95
|
+
* by session state alone (`:3600-3644`), so without both host conditions
|
|
96
|
+
* the DEPOSITOR-shaped Payout could be waived here; under a loaded intent
|
|
97
|
+
* the device would then sign it at input 0 as the intent-bound Payout
|
|
98
|
+
* whatever index the caller asked for (`fw:sign_custom_inputs.c:403-405`)
|
|
99
|
+
* — a valid signature nobody requested. (The claimer-shaped one is never
|
|
100
|
+
* signed under an intent: the device refuses it and wipes the intent,
|
|
101
|
+
* `:1765-1775`.) A future builder that adds input-0 metadata makes this return
|
|
102
|
+
* `undefined`: fail-closed, but the standalone claimer Payout is then
|
|
103
|
+
* unavailable on Ledger — a red run to fix, not a compatible state.
|
|
104
|
+
* - `payoutDepositor`: the same 2-in/2-out transaction with a leaf on input 0
|
|
105
|
+
* and requested index 0 — recognised so the provider can send it down the
|
|
106
|
+
* ordinary intent path unchanged, never relabelled here. Both leaves are
|
|
107
|
+
* required: btc-vault's depositor builder populates input 0 only
|
|
108
|
+
* (`payout.rs:268-273`, `psbt.rs:125-128` @ ac4954e7); input 1's payout
|
|
109
|
+
* leaf is there because the SDK copies it across (`payoutInputLeaf.ts`).
|
|
110
|
+
* A builder or SDK change that drops it makes this return `undefined` and
|
|
111
|
+
* the provider fail closed — look here first.
|
|
112
|
+
* - `assert`: 1 input (`:2569`), requested index 0, input 0 leaf matching
|
|
113
|
+
* {@link isAssertLeaf}. No output count: the validator enforces none
|
|
114
|
+
* (`:2568-2714`). Intent-bound on the device (`assert_prefix_ok`), so the
|
|
115
|
+
* provider must gate it on a loaded intent; it comes through here only for
|
|
116
|
+
* the derivation entry the standalone signing section reads
|
|
117
|
+
* (`fw:sign_custom_inputs.c:624-661`).
|
|
118
|
+
*
|
|
119
|
+
* @experimental
|
|
120
|
+
*/
|
|
121
|
+
export declare function classifyDelegatedClaimPsbt(psbtHex: string, requestedInputIndex: number): DelegatedClaimPsbtClassification | undefined;
|
|
122
|
+
/** @experimental */
|
|
123
|
+
export interface AugmentPsbtForDelegatedClaimParams {
|
|
124
|
+
/** The kind the caller classified; re-classified here and must agree. */
|
|
125
|
+
readonly kind: DelegatedClaimPsbtKind;
|
|
126
|
+
readonly psbtHex: string;
|
|
127
|
+
/** The connected device's depositor x-only key (64 lowercase hex). */
|
|
128
|
+
readonly depositorXOnlyHex: string;
|
|
129
|
+
/** The device's master fingerprint (8 lowercase hex). */
|
|
130
|
+
readonly masterFingerprintHex: string;
|
|
131
|
+
/** The depositor's 5-level BIP-86 path. */
|
|
132
|
+
readonly depositorPath: readonly number[];
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Put the one TAP_BIP32_DERIVATION entry the device requires on the SIGNED
|
|
136
|
+
* input: keyed by the untweaked D, carrying the master fingerprint and the
|
|
137
|
+
* BIP-86 path (`fw:sign_psbt_validate.c:2440-2486`, `:2658-2680`, `:2778-2818`,
|
|
138
|
+
* `:3291-3336`). The WASM builders already emit an entry for D with a zero
|
|
139
|
+
* fingerprint and an empty path (`btc-vault crates/vault/src/psbt.rs:65-75`),
|
|
140
|
+
* which the device would read and reject, and which bip174 refuses to add a
|
|
141
|
+
* second entry beside (`bip174@2.1.1 src/lib/converter/shared/bip32Derivation.js:70-75`),
|
|
142
|
+
* so the signed input's whole derivation set is REPLACED by D's one entry
|
|
143
|
+
* (the builder's entries for other signing keys are dropped too). No
|
|
144
|
+
* output entry is written — these validators derive P2TR(D) themselves
|
|
145
|
+
* (`:2481-2485`, `:2813-2817`, `:3331-3335`). `leafHashes: []` is fine: the
|
|
146
|
+
* device's value parser skips the hashes (`fw:sign_psbt_validate_helpers.c:59-60`).
|
|
147
|
+
* Re-classifies internally; augmenting anything that is not this device's
|
|
148
|
+
* PSBT of the stated kind is a caller bug. Every other term is the device's
|
|
149
|
+
* to validate (module doc). Never touches the
|
|
150
|
+
* unsigned transaction.
|
|
151
|
+
*
|
|
152
|
+
* @experimental
|
|
153
|
+
*/
|
|
154
|
+
export declare function augmentPsbtForDelegatedClaim(params: AugmentPsbtForDelegatedClaimParams): string;
|
|
155
|
+
export {};
|
|
156
|
+
//# sourceMappingURL=delegatedClaimPsbt.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"delegatedClaimPsbt.d.ts","sourceRoot":"","sources":["../src/delegatedClaimPsbt.ts"],"names":[],"mappings":"AAwFA;;;;;;GAMG;AACH,MAAM,WAAW,eAAe;IAC9B,2DAA2D;IAC3D,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;CAC7B;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,UAAU,GAAG,eAAe,GAAG,SAAS,CAwBrF;AAED;;;;;;;GAOG;AACH,MAAM,MAAM,sBAAsB,GAAG,OAAO,GAAG,mBAAmB,GAAG,gBAAgB,GAAG,QAAQ,GAAG,iBAAiB,CAAC;AAErH;;;;;;;GAOG;AACH,eAAO,MAAM,gCAAgC,EAAE,QAAQ,CAAC,MAAM,CAAC,sBAAsB,EAAE,MAAM,CAAC,CAM7F,CAAC;AAEF,gGAAgG;AAChG,UAAU,uBAAuB;IAC/B,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,+EAA+E;IAC/E,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;CAC7B;AAED,oBAAoB;AACpB,MAAM,MAAM,gCAAgC,GACxC,CAAC,uBAAuB,GAAG;IAAE,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAA;CAAE,CAAC,GACtD,CAAC,uBAAuB,GAAG;IAAE,QAAQ,CAAC,IAAI,EAAE,mBAAmB,CAAA;CAAE,CAAC,GAClE,CAAC,uBAAuB,GAAG;IAAE,QAAQ,CAAC,IAAI,EAAE,gBAAgB,CAAA;CAAE,CAAC,GAC/D,CAAC,uBAAuB,GAAG;IAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAA;CAAE,CAAC,GACvD,CAAC,uBAAuB,GAAG;IAAE,QAAQ,CAAC,IAAI,EAAE,iBAAiB,CAAA;CAAE,CAAC,CAAC;AAyErE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqDG;AACH,wBAAgB,0BAA0B,CACxC,OAAO,EAAE,MAAM,EACf,mBAAmB,EAAE,MAAM,GAC1B,gCAAgC,GAAG,SAAS,CAgE9C;AAED,oBAAoB;AACpB,MAAM,WAAW,kCAAkC;IACjD,yEAAyE;IACzE,QAAQ,CAAC,IAAI,EAAE,sBAAsB,CAAC;IACtC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,sEAAsE;IACtE,QAAQ,CAAC,iBAAiB,EAAE,MAAM,CAAC;IACnC,yDAAyD;IACzD,QAAQ,CAAC,oBAAoB,EAAE,MAAM,CAAC;IACtC,2CAA2C;IAC3C,QAAQ,CAAC,aAAa,EAAE,SAAS,MAAM,EAAE,CAAC;CAC3C;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,4BAA4B,CAAC,MAAM,EAAE,kCAAkC,GAAG,MAAM,CAwC/F"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"expectedSignatures.d.ts","sourceRoot":"","sources":["../src/expectedSignatures.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAIH,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAuChC,MAAM,MAAM,mBAAmB,GAC3B;IACE,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC;IAC3B,8EAA8E;IAC9E,QAAQ,CAAC,qBAAqB,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IACpD;8FAC0F;IAC1F,QAAQ,CAAC,sBAAsB,EAAE,MAAM,CAAC;CACzC,GACD;IACE,QAAQ,CAAC,IAAI,EAAE,iBAAiB,CAAC;IACjC,qFAAqF;IACrF,QAAQ,CAAC,oBAAoB,EAAE,MAAM,CAAC;CACvC,CAAC;AAEN,MAAM,WAAW,sBAAsB;IACrC,iFAAiF;IACjF,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAC;IAC3D;;;;;OAKG;IACH,QAAQ,CAAC,iBAAiB,EAAE,WAAW,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAC;IACrE,uEAAuE;IACvE,QAAQ,CAAC,kBAAkB,EAAE,MAAM,CAAC;CACrC;AAED,MAAM,MAAM,cAAc,GACtB;IACE,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC;IAC3B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,6DAA6D;IAC7D,QAAQ,CAAC,SAAS,EAAE,UAAU,CAAC;CAChC,GACD;IACE,QAAQ,CAAC,IAAI,EAAE,iBAAiB,CAAC;IACjC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,SAAS,EAAE,UAAU,CAAC;CAChC,CAAC;AAEN;;;;GAIG;AACH,MAAM,WAAW,qBAAqB;IACpC,mBAAmB,IAAI,MAAM,CAAC;IAC9B,qBAAqB,CACnB,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,MAAM,GACd,SAAS;QAAE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IACnE,mBAAmB,CAAC,UAAU,EAAE,MAAM,GAAG;QAAE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAAC;CACjH;AAED,MAAM,WAAW,iCAAiC;IAChD;;;OAGG;IACH,QAAQ,CAAC,IAAI,EAAE,qBAAqB,CAAC;IACrC,0EAA0E;IAC1E,QAAQ,CAAC,iBAAiB,EAAE,MAAM,CAAC;IACnC;;;;;;OAMG;IACH,QAAQ,CAAC,gBAAgB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC/C;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAU7D;AA2ED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,2BAA2B,CAAC,MAAM,EAAE,iCAAiC,GAAG,sBAAsB,
|
|
1
|
+
{"version":3,"file":"expectedSignatures.d.ts","sourceRoot":"","sources":["../src/expectedSignatures.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAIH,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAuChC,MAAM,MAAM,mBAAmB,GAC3B;IACE,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC;IAC3B,8EAA8E;IAC9E,QAAQ,CAAC,qBAAqB,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IACpD;8FAC0F;IAC1F,QAAQ,CAAC,sBAAsB,EAAE,MAAM,CAAC;CACzC,GACD;IACE,QAAQ,CAAC,IAAI,EAAE,iBAAiB,CAAC;IACjC,qFAAqF;IACrF,QAAQ,CAAC,oBAAoB,EAAE,MAAM,CAAC;CACvC,CAAC;AAEN,MAAM,WAAW,sBAAsB;IACrC,iFAAiF;IACjF,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAC;IAC3D;;;;;OAKG;IACH,QAAQ,CAAC,iBAAiB,EAAE,WAAW,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAC;IACrE,uEAAuE;IACvE,QAAQ,CAAC,kBAAkB,EAAE,MAAM,CAAC;CACrC;AAED,MAAM,MAAM,cAAc,GACtB;IACE,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC;IAC3B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,6DAA6D;IAC7D,QAAQ,CAAC,SAAS,EAAE,UAAU,CAAC;CAChC,GACD;IACE,QAAQ,CAAC,IAAI,EAAE,iBAAiB,CAAC;IACjC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,SAAS,EAAE,UAAU,CAAC;CAChC,CAAC;AAEN;;;;GAIG;AACH,MAAM,WAAW,qBAAqB;IACpC,mBAAmB,IAAI,MAAM,CAAC;IAC9B,qBAAqB,CACnB,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,MAAM,GACd,SAAS;QAAE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IACnE,mBAAmB,CAAC,UAAU,EAAE,MAAM,GAAG;QAAE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAAC;CACjH;AAED,MAAM,WAAW,iCAAiC;IAChD;;;OAGG;IACH,QAAQ,CAAC,IAAI,EAAE,qBAAqB,CAAC;IACrC,0EAA0E;IAC1E,QAAQ,CAAC,iBAAiB,EAAE,MAAM,CAAC;IACnC;;;;;;OAMG;IACH,QAAQ,CAAC,gBAAgB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC/C;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAU7D;AA2ED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,2BAA2B,CAAC,MAAM,EAAE,iCAAiC,GAAG,sBAAsB,CA6J7G;AAED,MAAM,WAAW,cAAc;IAC7B;;;;;OAKG;IACH,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvC,QAAQ,CAAC,MAAM,EAAE,SAAS,cAAc,EAAE,CAAC;IAC3C,qCAAqC;IACrC,QAAQ,CAAC,SAAS,EAAE,cAAc,GAAG,SAAS,CAAC;IAC/C;;;OAGG;IACH,cAAc,IAAI,IAAI,CAAC;CACxB;AAsBD,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,sBAAsB,GAAG,cAAc,CAwHlF"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var hn=Object.defineProperty;var fn=(e,t,n)=>t in e?hn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var p=(e,t,n)=>fn(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const at=require("@scure/bip32"),q=require("./testing-DjacXOYK.cjs"),_=require("bitcoinjs-lib"),u=require("buffer"),pn=require("@bitcoin-js/tiny-secp256k1-asmjs");function dn(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const wt=dn(pn),gn=1,En=1,wn=1,_n=2,Tn=33,mn=256,Sn=257,In=258,Pn=39,yn=259,bn=105,Rn=260,An=261,xn=262,On=271,Bn=265,vn=266,Cn=267,Ln=268,Nn=269,Mn=270,Dn=263,$n=264,nt=32,kn=32,F=255,Un=3+nt,Vt=Math.floor(F/Un);function x(e,t){if(t.length>F)throw new Error(`TLV value for tag 0x${e.toString(16)} exceeds 255 bytes`);const n=new Uint8Array(3+t.length);return n[0]=e>>8&255,n[1]=e&255,n[2]=t.length,n.set(t,3),n}function ut(e,t,n){if(e<0n||e>=1n<<BigInt(8*t))throw new Error(`${n} ${e} does not fit in ${t} bytes`);const r=new Uint8Array(t);let o=e;for(let s=t-1;s>=0;s--)r[s]=Number(o&0xffn),o>>=8n;return r}function L(e,t,n){return x(e,ut(BigInt(t),1,n))}function j(e,t,n){return x(e,ut(BigInt(t),4,n))}function N(e,t,n){return x(e,ut(t,8,n))}function rt(e){const t=e.reduce((o,s)=>o+s.length,0),n=new Uint8Array(t);let r=0;for(const o of e)n.set(o,r),r+=o.length;return n}function Rt(e,t,n){if(e.length!==t)throw new Error(`${n} must be ${t} bytes, got ${e.length}`);return e}const Gt=5;function Se(e){if(e.depositorPath.length!==Gt)throw new Error(`depositorPath must have exactly ${Gt} levels, got ${e.depositorPath.length}`);const t=rt(e.depositorPath.map(n=>ut(BigInt(n>>>0),4,"path level")));return rt([L(wn,gn,"structureType"),L(_n,En,"version"),j(Tn,e.coinType,"coinType"),N(mn,e.baseFeeRate,"baseFeeRate"),j(Sn,e.peginCsvTimelock,"peginCsvTimelock"),j(In,e.payoutTimelock,"payoutTimelock"),x(Pn,Rt(e.prepeginTxidInternal,kn,"prepeginTxid")),j(yn,e.htlcRefundTimelock,"htlcRefundTimelock"),x(bn,t),L(Rn,e.keeperCount,"keeperCount"),L(An,e.challengerCount,"challengerCount"),L(xn,e.vaultCount,"vaultCount"),N(On,e.prepeginMaxFee,"prepeginMaxFee")])}function Ie(e){return rt([L(Bn,e.htlcVout,"htlcVout"),x(vn,Rt(e.vaultProviderPubkey,nt,"vaultProviderPubkey")),N(Cn,e.vaultAmount,"vaultAmount"),N(Ln,e.commissionFee,"commissionFee"),N(Nn,e.depositorClaimValue,"depositorClaimValue"),N(Mn,e.peginMaxFee,"peginMaxFee")])}function Pe(e,t){const n=(s,i)=>s.map((a,c)=>Rt(a,nt,`${i}[${c}]`)).sort((a,c)=>{for(let l=0;l<nt;l++)if(a[l]!==c[l])return a[l]-c[l];return 0}),r=[...n(e,"keeper").map(s=>x(Dn,s)),...n(t,"challenger").map(s=>x($n,s))],o=[];for(let s=0;s<r.length;s+=Vt)o.push(rt(r.slice(s,s+Vt)));return o}const A=225,ht=128,Kt=129,Hn=0,Vn=1,Gn=0,Kn=1,Fn=2,Y=0,Ft=64,Yt=1024,Xt=10,qt=32;function Yn(e){return new Uint8Array([e>>8&255,e&255])}function Xn(e){const t=e>>>0;return new Uint8Array([t>>>24&255,t>>>16&255,t>>>8&255,t&255])}function ft(e){const t=new Uint8Array(e.reduce((r,o)=>r+o.length,0));let n=0;for(const r of e)t.set(r,n),n+=r.length;return t}const Wt=/^[a-z0-9-]+$/;async function qn(e,{appName:t,derivationPath:n,context:r}){const o=new TextEncoder().encode(t);if(o.length<1||o.length>Ft)throw new Error(`appName must be 1..${Ft} bytes, got ${o.length}`);if(!Wt.test(t))throw new Error(`appName must match ${Wt} — the device rejects other characters`);if(n.length<1||n.length>Xt)throw new Error(`derivationPath must have 1..${Xt} levels`);if(r.length<1||r.length>Yt)throw new Error(`context must be 1..${Yt} bytes, got ${r.length}`);const s=ft([new Uint8Array([o.length]),o,new Uint8Array([n.length]),ft(n.map(Xn)),Yn(r.length)]),i=Math.min(r.length,F-s.length);if(i<0)throw new Error("appName and derivationPath leave no room for context in the first APDU");let a=await e({cla:A,ins:Kt,p1:Hn,p2:Y,data:ft([s,r.subarray(0,i)])});for(let c=i;c<r.length;c+=F)a=await e({cla:A,ins:Kt,p1:Vn,p2:Y,data:r.subarray(c,c+F)});if(a.length!==qt)throw new Error(`Expected a ${qt}-byte context root, got ${a.length} bytes`);return a}async function Wn(e,{scalars:t,groups:n,keeperPubkeys:r,challengerPubkeys:o}){if(n.length!==t.vaultCount)throw new Error(`vaultCount ${t.vaultCount} does not match ${n.length} group(s)`);if(r.length!==t.keeperCount)throw new Error(`keeperCount ${t.keeperCount} does not match ${r.length} key(s)`);if(t.keeperCount<1||t.challengerCount<1)throw new Error(`Both rosters must be non-empty: keeperCount=${t.keeperCount}, challengerCount=${t.challengerCount}`);if(o.length!==t.challengerCount)throw new Error(`challengerCount ${t.challengerCount} does not match ${o.length} key(s)`);await e({cla:A,ins:ht,p1:Gn,p2:Y,data:Se(t)});for(const s of n)await e({cla:A,ins:ht,p1:Kn,p2:Y,data:Ie(s)});for(const s of Pe(r,o))await e({cla:A,ins:ht,p1:Fn,p2:Y,data:s})}const zn=0,ye=0,be=1,jn=0,zt=33,jt=10,Qn=5,Zn=4;async function Jn(e){const t=await e({cla:A,ins:Qn,p1:ye,p2:be,data:new Uint8Array(0)});if(t.length!==Zn)throw new Error(`Ledger returned a ${t.length}-byte response instead of the 4-byte master fingerprint`);return Ae(t)}async function Re(e,t,n){if(t.length<1||t.length>jt)throw new Error(`BIP-32 path must have 1..${jt} levels, got ${t.length}`);const r=await e({cla:A,ins:zn,p1:ye,p2:be,data:er(t)}),o=new TextDecoder().decode(r);if(o.length===0)throw new Error("Ledger returned an empty extended key");return at.HDKey.fromExtendedKey(o,n),o}async function tr(e,t,n){const r=await Re(e,t,n),o=at.HDKey.fromExtendedKey(r,n);if(!o.publicKey||o.publicKey.length!==zt)throw new Error(`Ledger returned an extended key without a ${zt}-byte public key`);return Ae(o.publicKey.subarray(1))}function Ae(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function er(e){const t=new Uint8Array(2+e.length*4);return t[0]=jn,t[1]=e.length,e.forEach((n,r)=>{const o=2+r*4;t[o]=n>>>24&255,t[o+1]=n>>>16&255,t[o+2]=n>>>8&255,t[o+3]=n&255}),t}const At="LedgerUserRefusedError",xt="LedgerDeviceLockedError",Ot="LedgerDeviceError",Bt="LedgerYieldMismatchError",vt="LedgerSignPsbtIncompleteError",Ct="LedgerSignPsbtProtocolError",Lt="LedgerSignPsbtAbortedError";function xe(e){return e.toString(16).padStart(4,"0")}class Oe extends Error{constructor(n){super(`User rejected the request on the Ledger device (0x${xe(n)})`);p(this,"statusWord");this.name=At,this.statusWord=n}}class Be extends Error{constructor(n,r){super(`The Ledger device is locked — unlock it and retry (0x${xe(n)})`);p(this,"statusWord");p(this,"preDispatch");this.name=xt,this.statusWord=n,this.preDispatch=(r==null?void 0:r.preDispatch)??!1}}class ve extends Error{constructor(n,r){super(r);p(this,"statusWord");this.name=Ot,this.statusWord=n}}class I extends Error{constructor(n,r){super(`The device yielded a signature that fails the expected-signature table (${n}${r===void 0?"":` on input ${r}`})`);p(this,"kind");p(this,"inputIndex");this.name=Bt,this.kind=n,this.inputIndex=r}}class Ce extends Error{constructor(n){super(`The device completed SIGN_PSBT without yielding every expected signature (missing ${n.length}: ${n.join(", ")})`);p(this,"missing");this.name=vt,this.missing=n}}function et(e){return e.map(({inputIndex:t,leafHashHex:n})=>n===void 0?{inputIndex:t}:{inputIndex:t,leafHashHex:n})}class d extends Error{constructor(n,r=[]){super(`SIGN_PSBT protocol failure: ${n}`);p(this,"detail");p(this,"collectedYields");this.name=Ct,this.detail=n,this.collectedYields=r}}class _t extends Error{constructor(n){super("SIGN_PSBT was abandoned host-side before completion");p(this,"yieldedCount");this.name=Lt,this.yieldedCount=n}}function nr(e){return e instanceof Error&&e.name===At}function rr(e){return e instanceof Error&&e.name===Ot}function or(e){return e instanceof Error&&e.name===xt}function Le(e){return e instanceof Error&&e.name===Bt}function sr(e){return e instanceof Error&&e.name===vt}function Ne(e){return e instanceof Error&&e.name===Ct}function ir(e){return e instanceof Error&&e.name===Lt}const ar=36864,ur=new Set([21761,27013]),cr=new Set([21781,27010,21251]),Nt=28160,Mt=27904,Me=45063,De=45066,lr={27264:"The device rejected the data as invalid",27266:"The device does not support this request — check that the app build matches the selected network",27270:"The device rejected the instruction parameters",27271:"The device rejected the payload length",[Mt]:"The running app does not support this instruction",26881:"The device was still busy with the previous request",[Nt]:"The running app does not handle vault instructions — open the Babylon Vault app for this network",45056:"The device reported a wrong response length",[Me]:"The device is not in the expected state for this step",45064:"The device rejected a signature or HMAC as invalid",45065:"The device rejected the CPFP anchor",[De]:"The device has already signed the maximum number of these transactions",28416:"The device could not derive the key at the requested path"};function M(e){return e.toString(16).padStart(2,"0")}function $e(e){return e.toString(16).padStart(4,"0")}function ke(e,t){if(e===ar)return;if(ur.has(e))return new Oe(e);if(cr.has(e))return new Be(e,{preDispatch:t.preDispatch===!0});const n=lr[e],r=(e===Nt||e===Mt)&&t.appName?` (app at connect time: "${t.appName}"${t.appVersion?` v${t.appVersion}`:""})`:"";return new ve(e,`${n??"The device rejected the request"} (ins 0x${M(t.ins)} p1 0x${M(t.p1)}, sw 0x${$e(e)})${r}`)}function hr(e,t){return async n=>{const{sw:r,data:o}=await e(n),s=ke(r,{...t,ins:n.ins,p1:n.p1});if(s)throw s;return o}}const Qt=2;function fr(e){if(e.statusCode.length!==Qt)throw new Error(`The device returned a ${e.statusCode.length}-byte status word; expected ${Qt}.`);return e.statusCode[0]<<8|e.statusCode[1]}function Q(e,t){if(!Number.isInteger(e)||e<0||e>255)throw new Error(`APDU ${t} ${e} is not a single byte (0..255)`)}function pr(e){if(Q(e.cla,"cla"),Q(e.ins,"ins"),Q(e.p1,"p1"),Q(e.p2,"p2"),e.data.length>255)throw new Error(`APDU data is ${e.data.length} bytes; Lc is a single byte (max 255)`);const t=new Uint8Array(5+e.data.length);return t[0]=e.cla,t[1]=e.ins,t[2]=e.p1,t[3]=e.p2,t[4]=e.data.length,t.set(e.data,5),t}function Zt(){return globalThis.__LEDGER_VAULT_APDU_TRACE__===!0}function Ue(e){return async t=>{const n=`${M(t.cla)} ${M(t.ins)} ${M(t.p1)} ${M(t.p2)} Lc=${t.data.length}`;let r;try{r=await e.dmk.sendApdu({sessionId:e.sessionId,apdu:pr(t)})}catch(s){throw Zt()&&console.debug(`[ledger-vault] APDU ${n} -> transport error`,s),s}const o=fr(r);return Zt()&&console.debug(`[ledger-vault] APDU ${n} -> sw=0x${$e(o)} len=${r.data.length}`),{sw:o,data:r.data}}}function dr(e){return hr(Ue(e),{appName:e.appName,appVersion:e.appVersion})}const gr=2,Er=3,Jt=32,wr=10,te=10000n,ee=100000000n,ot=72,_r=1008,Tr=4320,mr=91,Sr=4031,He=546n,ne=He,Ir=2n,Ve="DepositTermsRejectedError";class m extends Error{constructor(n,r="device-envelope"){super(n);p(this,"reason");this.name=Ve,this.reason=r}}const P="Deposit terms outside the device-supported range";function O(e,t,n,r){if(!Number.isInteger(t)||t<n||t>r)throw new m(`${P}: ${e} ${t} not in [${n}, ${r}]`)}function Pr(e){if(O("vaultCoreVersion",e.vaultCoreVersion,gr,Er),e.protocolFeeRate<1n||e.protocolFeeRate>te)throw new m(`${P}: protocolFeeRate ${e.protocolFeeRate} not in [1, ${te}]`);if(O("timelockPegin",e.timelockPegin,ot,_r),O("timelockAssert",e.timelockAssert,mr,Sr),O("timelockRefund",e.timelockRefund,ot,Tr),O("keeper count",e.vaultKeeperBtcPubkeys.length,1,Jt),O("challenger count",e.universalChallengerBtcPubkeys.length,1,Jt),O("vault count",e.vaults.length,1,wr),K("prepeginMaxFee",e.prepeginMaxFee),e.prepeginMaxFee<1n||e.prepeginMaxFee>ee)throw new m(`${P}: prepeginMaxFee ${e.prepeginMaxFee} not in [1, ${ee}]`);let t=-1;for(const a of e.vaults){if(!Number.isInteger(a.htlcVout)||a.htlcVout<0||a.htlcVout>255)throw new m(`${P}: htlcVout ${a.htlcVout} not in [0, 255]`);if(a.htlcVout<=t)throw new m(`${P}: vault groups must be in strictly ascending htlcVout order; got ${a.htlcVout} after ${t}`);t=a.htlcVout}const n=a=>a.replace(/^0x/,"").toLowerCase(),r=new Set(e.vaults.map(a=>n(a.vaultProviderBtcPubkey))),o=new Set;for(const[a,c]of[["vaultKeeperBtcPubkeys",e.vaultKeeperBtcPubkeys],["universalChallengerBtcPubkeys",e.universalChallengerBtcPubkeys]])for(const l of c){const f=n(l);if(r.has(f))throw new m(`${P}: ${a} contains the vault provider's own key (${f.slice(0,16)}…)`);if(o.has(f))throw new m(`${P}: duplicate participant key in ${a} (${f.slice(0,16)}…)`);o.add(f)}const s=He,i=Ir*s;for(const a of e.vaults){if(K(`vault ${a.htlcVout} peginAmount`,a.peginAmount),K(`vault ${a.htlcVout} commissionFee`,a.commissionFee),K(`vault ${a.htlcVout} depositorClaimValue`,a.depositorClaimValue),K(`vault ${a.htlcVout} peginMaxFee`,a.peginMaxFee),a.commissionFee<s)throw new m(`${P}: vault ${a.htlcVout} commissionFee ${a.commissionFee} below the ${s}-sat dust limit`);if(a.depositorClaimValue<ne)throw new m(`${P}: vault ${a.htlcVout} depositorClaimValue ${a.depositorClaimValue} below the ${ne}-sat device floor`);if(a.peginAmount<=a.commissionFee+i)throw new m(`${P}: vault ${a.htlcVout} peginAmount ${a.peginAmount} must exceed commissionFee + ${i} (${a.commissionFee+i})`)}}const yr=(1n<<64n)-1n;function K(e,t){if(t<0n||t>yr)throw new m(`${P}: ${e} ${t} does not fit in an unsigned 64-bit field`)}const b=2147483648,br=4294967295,st=86,Ge=0,Ke=1,re=5,Dt=3,Rr=3,Ar=4;function $t(e,t){if(t.length!==re)throw new Error(`${e} must have exactly ${re} levels, got ${t.length}`);for(const r of t)if(!Number.isInteger(r)||r<0||r>br)throw new Error(`${e} levels must be integers in 0..0xffffffff`);if(!t.slice(0,Dt).every(r=>(r&b)!==0)||(t[Ar]&b)!==0)throw new Error(`${e} must harden purpose'/coin'/account' and leave the address index unhardened`);if(t[0]!==(b|st)>>>0)throw new Error(`${e} must use BIP-86 purpose ${st}'`)}function $(e){return"m/"+e.map(t=>(t&b)!==0?`${(t&~b)>>>0}'`:`${t>>>0}`).join("/")}const oe=253,xr=254,Or=65535,Br=4294967295;function vr(e){if(e<oe)return u.Buffer.from([e]);if(e<=Or){const t=u.Buffer.alloc(2);return t.writeUInt16LE(e),u.Buffer.concat([u.Buffer.from([oe]),t])}if(e<=Br){const t=u.Buffer.alloc(4);return t.writeUInt32LE(e),u.Buffer.concat([u.Buffer.from([xr]),t])}throw new Error(`Script too large to encode as CompactSize: ${e} bytes`)}const Cr="TapLeaf";function Lr(e,t){const n=u.Buffer.concat([u.Buffer.from([e]),vr(t.length),u.Buffer.from(t)]);return _.crypto.taggedHash(Cr,n)}function Nr(e,t,n,r){for(let o=0;o<t;o++){if(n[o+r]===void 0)throw Error("Buffer too small");n[o+r]=Number(e%BigInt(256)),e=e>>BigInt(8)}}function Mr(e,t,n){let r=BigInt(0);for(let o=0;o<n;o++){const s=e[o+t];if(s===void 0)throw Error("Buffer too small");r+=BigInt(s)<<BigInt(o*8)}return r}function R(e){if(e<0)throw RangeError("Negative bigint is not a valid varint");if(e>Number.MAX_SAFE_INTEGER)throw RangeError("Too large for a Number");return Number(e)}function Dr(e){if(typeof e=="number"&&(e=R(e)),e<BigInt(0))throw new RangeError("Negative numbers are not supported");if(e>=BigInt(1)<<BigInt(64))throw new RangeError("Too large for a Bitcoin-style varint");return e<BigInt(253)?1:e<=BigInt(65535)?3:e<=BigInt(4294967295)?5:9}const $r=BigInt(253),kr=BigInt(65535)+BigInt(1),Ur=BigInt(4294967295)+BigInt(1);function Fe(e,t){if(t<0)throw RangeError("Negative offset is invalid");const n=e[t];if(n===void 0)throw Error("Buffer too small");if(n<253)return[BigInt(n),1];{let r,o;n===253?(r=2,o=$r):n===254?(r=4,o=kr):(r=8,o=Ur);const s=Mr(e,t+1,r);if(s<o)throw RangeError(`Non-minimal varint at offset ${t}: a ${r+1}-byte CompactSize must encode a value of at least ${o}; re-encode it in its canonical (shorter) form`);return[s,r+1]}}function k(e){typeof e=="number"&&(e=R(e));const t=Dr(e);e=BigInt(e);const n=u.Buffer.alloc(t);return t==1?n[0]=Number(e):(t==3?n[0]=253:t===5?n[0]=254:n[0]=255,Nr(e,t-1,n,1)),n}const Hr=31;function Ye(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Can't convert a number that is not a non-negative safe integer to 64-bit LE");const t=u.Buffer.alloc(8,0);for(let n=0;n<t.length;n++){const r=e&255;t[n]=r,e=(e-r)/256}return t}function Tt(e){let t=0;if(e.length!==8)throw new Error("Expected Buffer of length 8");if(e[7]!==0)throw new Error("Can't encode numbers > MAX_SAFE_INT");const n=e[6];if(n===void 0||n>Hr)throw new Error("Can't encode numbers > MAX_SAFE_INT");for(let r=e.length-1;r>=0;r--){const o=e[r];if(o===void 0)throw new Error("Buffer too small");t=t*256+o}return t}class B{constructor(){p(this,"bufs",[])}write(t,n){const r=u.Buffer.alloc(t);n(r),this.bufs.push(r)}writeUInt8(t){this.write(1,n=>n.writeUInt8(t,0))}writeInt32(t){this.write(4,n=>n.writeInt32LE(t,0))}writeUInt32(t){this.write(4,n=>n.writeUInt32LE(t,0))}writeUInt64(t){const n=Ye(t);this.writeSlice(n)}writeVarInt(t){this.bufs.push(k(t))}writeSlice(t){this.bufs.push(u.Buffer.from(t))}writeVarSlice(t){this.writeVarInt(t.length),this.writeSlice(t)}buffer(){return u.Buffer.concat(this.bufs)}}class D{constructor(t,n=0){this.buffer=t,this.offset=n}available(){return this.buffer.length-this.offset}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=this.readSlice(8);return Tt(t)}readVarInt(){const[t,n]=Fe(this.buffer,this.offset);return this.offset+=n,t}readSlice(t){if(this.buffer.length<this.offset+t)throw new Error("Cannot read slice out of bounds");const n=this.buffer.subarray(this.offset,this.offset+t);return this.offset+=t,n}readVarSlice(){const t=R(this.readVarInt());return this.readSlice(t)}readVector(){const t=this.readVarInt(),n=[];for(let r=0;r<t;r++)n.push(this.readVarSlice());return n}}var mt=(e=>(e[e.NON_WITNESS_UTXO=0]="NON_WITNESS_UTXO",e[e.WITNESS_UTXO=1]="WITNESS_UTXO",e[e.PARTIAL_SIG=2]="PARTIAL_SIG",e[e.SIGHASH_TYPE=3]="SIGHASH_TYPE",e[e.REDEEM_SCRIPT=4]="REDEEM_SCRIPT",e[e.WITNESS_SCRIPT=5]="WITNESS_SCRIPT",e[e.BIP32_DERIVATION=6]="BIP32_DERIVATION",e[e.FINAL_SCRIPTSIG=7]="FINAL_SCRIPTSIG",e[e.FINAL_SCRIPTWITNESS=8]="FINAL_SCRIPTWITNESS",e[e.PREVIOUS_TXID=14]="PREVIOUS_TXID",e[e.OUTPUT_INDEX=15]="OUTPUT_INDEX",e[e.SEQUENCE=16]="SEQUENCE",e[e.TAP_KEY_SIG=19]="TAP_KEY_SIG",e[e.TAP_LEAF_SCRIPT=21]="TAP_LEAF_SCRIPT",e[e.TAP_BIP32_DERIVATION=22]="TAP_BIP32_DERIVATION",e[e.TAP_INTERNAL_KEY=23]="TAP_INTERNAL_KEY",e))(mt||{});const se=u.Buffer.from([112,115,98,116,255]),Vr=4294967295;class Xe extends Error{}class qe{constructor(){p(this,"globalMap",new Map);p(this,"inputMaps",[]);p(this,"outputMaps",[])}setGlobalTxVersion(t){this.setGlobal(2,C(t))}getGlobalTxVersion(){return this.getGlobal(2).readUInt32LE(0)}setGlobalFallbackLocktime(t){this.setGlobal(3,C(t))}getGlobalFallbackLocktime(){var t;return(t=this.getGlobalOptional(3))==null?void 0:t.readUInt32LE(0)}setGlobalInputCount(t){this.setGlobal(4,ue(t))}getGlobalInputCount(){return ce(this.getGlobal(4))}setGlobalOutputCount(t){this.setGlobal(5,ue(t))}getGlobalOutputCount(){return ce(this.getGlobal(5))}setGlobalTxModifiable(t){this.setGlobal(6,t)}getGlobalTxModifiable(){return this.getGlobalOptional(6)}setGlobalPsbtVersion(t){this.setGlobal(251,C(t))}getGlobalPsbtVersion(){return this.getGlobal(251).readUInt32LE(0)}setInputNonWitnessUtxo(t,n){this.setInput(t,0,w(),n)}getInputNonWitnessUtxo(t){return this.getInputOptional(t,0,w())}setInputWitnessUtxo(t,n,r){const o=new B;o.writeSlice(ae(n)),o.writeVarSlice(r),this.setInput(t,1,w(),o.buffer())}getInputWitnessUtxo(t){const n=this.getInputOptional(t,1,w());if(!n)return;const r=new D(n);return{amount:Tt(r.readSlice(8)),scriptPubKey:r.readVarSlice()}}setInputPartialSig(t,n,r){this.setInput(t,2,n,r)}getInputPartialSig(t,n){return this.getInputOptional(t,2,n)}setInputSighashType(t,n){this.setInput(t,3,w(),C(n))}getInputSighashType(t){const n=this.getInputOptional(t,3,w());if(n)return n.readUInt32LE(0)}setInputRedeemScript(t,n){this.setInput(t,4,w(),n)}getInputRedeemScript(t){return this.getInputOptional(t,4,w())}setInputWitnessScript(t,n){this.setInput(t,5,w(),n)}getInputWitnessScript(t){return this.getInputOptional(t,5,w())}setInputBip32Derivation(t,n,r,o){if(n.length!==33)throw new Error("Invalid pubkey length: "+n.length);this.setInput(t,6,n,this.encodeBip32Derivation(r,o))}getInputBip32Derivation(t,n){const r=this.getInputOptional(t,6,n);if(r)return this.decodeBip32Derivation(r)}setInputFinalScriptsig(t,n){this.setInput(t,7,w(),n)}getInputFinalScriptsig(t){return this.getInputOptional(t,7,w())}setInputFinalScriptwitness(t,n){this.setInput(t,8,w(),n)}getInputFinalScriptwitness(t){return this.getInput(t,8,w())}setInputPreviousTxId(t,n){this.setInput(t,14,w(),n)}getInputPreviousTxid(t){return this.getInput(t,14,w())}setInputOutputIndex(t,n){this.setInput(t,15,w(),C(n))}getInputOutputIndex(t){return this.getInput(t,15,w()).readUInt32LE(0)}setInputSequence(t,n){this.setInput(t,16,w(),C(n))}getInputSequence(t){var n;return((n=this.getInputOptional(t,16,w()))==null?void 0:n.readUInt32LE(0))??Vr}setInputTapKeySig(t,n){this.setInput(t,19,w(),n)}getInputTapKeySig(t){return this.getInputOptional(t,19,w())}setInputTapBip32Derivation(t,n,r,o,s){if(n.length!==32)throw new Error("Invalid pubkey length: "+n.length);const i=this.encodeTapBip32Derivation(r,o,s);this.setInput(t,22,n,i)}getInputTapBip32Derivation(t,n){const r=this.getInput(t,22,n);return this.decodeTapBip32Derivation(r)}getInputKeyDatas(t,n){return this.getKeyDatas(this.inputMaps[t],n)}getInputEntriesOfType(t,n){const r=this.inputMaps[t];if(!r)throw new Error("No such map");const o=[];return r.forEach((s,i)=>{this.isKeyType(i,[n])&&o.push({keyData:u.Buffer.from(i.substring(2),"hex"),value:u.Buffer.from(s)})}),o}setOutputRedeemScript(t,n){this.setOutput(t,0,w(),n)}getOutputRedeemScript(t){return this.getOutput(t,0,w())}setOutputBip32Derivation(t,n,r,o){this.setOutput(t,2,n,this.encodeBip32Derivation(r,o))}getOutputBip32Derivation(t,n){const r=this.getOutput(t,2,n);return this.decodeBip32Derivation(r)}setOutputAmount(t,n){this.setOutput(t,3,w(),ae(n))}getOutputAmount(t){const n=this.getOutput(t,3,w());return Tt(n)}setOutputScript(t,n){this.setOutput(t,4,w(),n)}getOutputScript(t){return this.getOutput(t,4,w())}setOutputTapBip32Derivation(t,n,r,o,s){const i=this.encodeTapBip32Derivation(r,o,s);this.setOutput(t,7,n,i)}getOutputTapBip32Derivation(t,n){const r=this.getOutput(t,7,n);return this.decodeTapBip32Derivation(r)}deleteInputEntries(t,n){const r=this.inputMaps[t];if(!r)throw new Error("No such map");r.forEach((o,s,i)=>{this.isKeyType(s,n)&&i.delete(s)})}copy(t){this.copyMap(this.globalMap,t.globalMap),this.copyMaps(this.inputMaps,t.inputMaps),this.copyMaps(this.outputMaps,t.outputMaps)}copyMaps(t,n){t.forEach((r,o)=>{const s=new Map;this.copyMap(r,s),n[o]=s})}copyMap(t,n){t.forEach((r,o)=>n.set(o,u.Buffer.from(r)))}serialize(){const t=new B;return t.writeSlice(se),dt(t,this.globalMap),this.inputMaps.forEach(n=>{dt(t,n)}),this.outputMaps.forEach(n=>{dt(t,n)}),t.buffer()}deserialize(t){const n=new D(t);if(!n.readSlice(5).equals(se))throw new Error("Invalid magic bytes");for(;this.readKeyPair(this.globalMap,n););let r;try{r=this.getGlobalPsbtVersion()}catch(i){if(!(i instanceof Xe))throw i;r=0}if(r!==0&&r!==2)throw new Error("Only PSBTs of version 0 or 2 are supported");let o,s;if(r===0){const i=this.getGlobal(0),a=_.Transaction.fromBuffer(i);o=a.ins.length,s=a.outs.length}else o=this.getGlobalInputCount(),s=this.getGlobalOutputCount();for(let i=0;i<o;i++){const a=new Map;for(this.inputMaps[i]=a;this.readKeyPair(a,n););}for(let i=0;i<s;i++){const a=new Map;for(this.outputMaps[i]=a;this.readKeyPair(a,n););}if(n.available()!==0)throw new Error("Trailing bytes after PSBT output maps");this.normalizeToV2()}normalizeToV2(){var o;const t=(o=this.getGlobalOptional(251))==null?void 0:o.readUInt32LE(0);if(t===2)return;if(t!==void 0)throw new Error("Invalid or unsupported value for PSBT_GLOBAL_VERSION");const n=this.getGlobal(0),r=_.Transaction.fromBuffer(n);this.setGlobalPsbtVersion(2),this.setGlobalTxVersion(r.version),this.setGlobalFallbackLocktime(r.locktime),this.setGlobalInputCount(r.ins.length),this.setGlobalOutputCount(r.outs.length),r.ins.forEach((s,i)=>{this.setInputPreviousTxId(i,s.hash),this.setInputOutputIndex(i,s.index),this.setInputSequence(i,s.sequence)}),r.outs.forEach((s,i)=>{this.setOutputAmount(i,s.value),this.setOutputScript(i,s.script)}),this.globalMap.delete("0".padStart(2,"0"))}readKeyPair(t,n){const r=R(n.readVarInt());if(r===0)return!1;const o=n.readUInt8(),s=n.readSlice(r-1),i=n.readVarSlice(),a=new U(o,s).toString();if(t.has(a))throw new Error("Repeated keypair in PSBT map");return t.set(a,i),!0}getKeyDatas(t,n){if(!t)throw new Error("No such map");const r=[];return t.forEach((o,s)=>{this.isKeyType(s,[n])&&r.push(u.Buffer.from(s.substring(2),"hex"))}),r}isKeyType(t,n){const r=u.Buffer.from(t.substring(0,2),"hex").readUInt8(0);return n.some(o=>o===r)}setGlobal(t,n){const r=new U(t,u.Buffer.from([]));this.globalMap.set(r.toString(),n)}getGlobal(t){return pt(this.globalMap,t,w())}getGlobalOptional(t){return St(this.globalMap,t,w())}setInput(t,n,r,o){ie(this.getMap(t,this.inputMaps),n,r,o)}getInput(t,n,r){return pt(this.inputMaps[t],n,r)}getInputOptional(t,n,r){return St(this.inputMaps[t],n,r)}setOutput(t,n,r,o){ie(this.getMap(t,this.outputMaps),n,r,o)}getOutput(t,n,r){return pt(this.outputMaps[t],n,r)}getMap(t,n){const r=n[t];if(r)return r;const o=new Map;return n[t]=o,o}encodeBip32Derivation(t,n){const r=new B;return this.writeBip32Derivation(r,t,n),r.buffer()}decodeBip32Derivation(t){const n=new D(t);return this.readBip32Derivation(n)}writeBip32Derivation(t,n,r){t.writeSlice(n),r.forEach(o=>{t.writeUInt32(o)})}readBip32Derivation(t){const n=t.readSlice(4),r=[];for(;t.offset<t.buffer.length;)r.push(t.readUInt32());return{masterFingerprint:n,path:r}}encodeTapBip32Derivation(t,n,r){const o=new B;return o.writeVarInt(t.length),t.forEach(s=>{o.writeSlice(s)}),this.writeBip32Derivation(o,n,r),o.buffer()}decodeTapBip32Derivation(t){const n=new D(t),r=R(n.readVarInt()),o=[];for(let i=0;i<r;i++)o.push(n.readSlice(32));const s=this.readBip32Derivation(n);return{hashes:o,...s}}}function pt(e,t,n){const r=St(e,t,n);if(r===void 0)throw new Xe(new U(t,n).toString());return r}function St(e,t,n){if(!e)throw new Error("No such map");const r=new U(t,n),o=e.get(r.toString());if(o!==void 0)return u.Buffer.from(o)}class U{constructor(t,n){p(this,"keyType");p(this,"keyData");this.keyType=t,this.keyData=n}toString(){const t=new B;return this.toBuffer(t),t.buffer().toString("hex")}serialize(t){t.writeVarInt(1+this.keyData.length),this.toBuffer(t)}toBuffer(t){t.writeUInt8(this.keyType),t.writeSlice(this.keyData)}}class Gr{constructor(t,n){p(this,"key");p(this,"value");this.key=t,this.value=n}serialize(t){this.key.serialize(t),t.writeVarSlice(this.value)}}function Kr(e){return new U(e.readUInt8(0),e.subarray(1))}function dt(e,t){const n=[...t].sort(([r],[o])=>r<o?-1:r>o?1:0);for(const[r,o]of n)new Gr(Kr(u.Buffer.from(r,"hex")),o).serialize(e);e.writeUInt8(0)}function w(){return u.Buffer.from([])}function ie(e,t,n,r){const o=new U(t,n);e.set(o.toString(),r)}function C(e){const t=u.Buffer.alloc(4);return t.writeUInt32LE(e,0),t}function ae(e){return Ye(e)}function ue(e){const t=new B;return t.writeVarInt(e),t.buffer()}function ce(e){return R(new D(e).readVarInt())}const le=192,It=32,he=2,Z=33,J=32,Fr=1,Yr="TapBranch",Xr="TapTweak",fe=64,pe=32,gt=64,qr=34,it=u.Buffer.from([81,32]),Wr=u.Buffer.from([0,20]),zr=2,jr=3;function ct(e){_.initEccLib(wt);const t=_.payments.p2tr({internalPubkey:u.Buffer.from(e,"hex")}).output;if(!t)throw new d("p2tr produced no output script for the depositor key");return t}function de(e,t){const n=u.Buffer.concat([u.Buffer.from([t]),u.Buffer.from(e,"hex")]);return u.Buffer.concat([Wr,_.crypto.hash160(n)])}function We(e){return e.length===qr&&e.subarray(0,it.length).equals(it)}function Qr(e,t,n,r){if(!We(r))throw new d(`input ${e} is tapscript but its witnessUtxo script is not P2TR`);const o=t.length-Z;if(o<0||o%J!==0)throw new d(`input ${e} control block length ${t.length} is not ${Z} plus a multiple of ${J}`);const s=t.subarray(1,Z);if(!wt.isXOnlyPoint(s))throw new d(`input ${e} control block internal key is not an x-only point`);let i=n;for(let f=Z;f<t.length;f+=J){const g=t.subarray(f,f+J),h=u.Buffer.compare(i,g)<0?[i,g]:[g,i];i=_.crypto.taggedHash(Yr,u.Buffer.concat(h))}const a=_.crypto.taggedHash(Xr,u.Buffer.concat([s,i])),c=wt.xOnlyPointAddTweak(s,a);if(!c)throw new d(`input ${e} control block internal key has no taproot output key`);if(!r.subarray(it.length).equals(u.Buffer.from(c.xOnlyPubkey)))throw new d(`input ${e} control block does not commit to its TAP_LEAF_SCRIPT (recomputed taproot output key differs from the witnessUtxo witness program)`);if(c.parity!==(t[0]&Fr))throw new d(`input ${e} control block parity bit disagrees with the recomputed taproot output key`)}function Zr(e){const{psbt:t,depositorXOnlyHex:n,signInputIndexes:r}=e,o=new Map,s=new Map,i=t.getGlobalInputCount(),a=r===void 0?void 0:new Set(r),c=h=>a===void 0||a.has(h);if((a==null?void 0:a.size)===0)throw new d("signInputIndexes is empty — pass the indices to sign, or omit it to sign every device-signable input");for(const h of a??[])if(!Number.isInteger(h)||h<0||h>=i)throw new d(`input ${h} was requested for signing but this PSBT has ${i} input(s)`);const l=ct(n),f=[de(n,zr),de(n,jr)];for(let h=0;h<i;h++){const E=t.getInputEntriesOfType(h,mt.TAP_LEAF_SCRIPT);if(E.length>0){if(E.length>1)throw new d(`input ${h} carries an ambiguous leaf set (${E.length} TAP_LEAF_SCRIPT entries)`);const T=E[0].value;if(T.length<he)throw new d(`input ${h} TAP_LEAF_SCRIPT value length ${T.length} is below the ${he}-byte minimum (script byte plus the leaf-version byte)`);const G=T[T.length-1];if(G!==le)throw new d(`input ${h} leaf version 0x${G.toString(16)} is not tapscript (0xc0)`);const v=t.getInputWitnessUtxo(h);if(!v)throw new d(`input ${h} is tapscript but has no witnessUtxo`);const z=T.subarray(0,T.length-1),Ut=Lr(le,z);Qr(h,E[0].keyData,Ut,v.scriptPubKey);const Ht={kind:"tapscript",expectedLeafHashHexes:new Set([Ut.toString("hex")]),expectedSignerXOnlyHex:n};s.set(h,Ht),c(h)&&o.set(h,Ht);continue}const y=t.getInputEntriesOfType(h,mt.TAP_INTERNAL_KEY);if(y.length>0){const T=y[0];if(y.length>1||T.keyData.length!==0||T.value.length!==It)throw new d(`input ${h} carries a malformed TAP_INTERNAL_KEY entry`);if(T.value.toString("hex")!==n)throw new d(`input ${h} internal key is not the connected depositor key`);const G=t.getInputWitnessUtxo(h);if(!G)throw new d(`input ${h} is keypath but has no witnessUtxo`);const v=G.scriptPubKey;if(!We(v))throw new d(`input ${h} witnessUtxo script is not P2TR`);if(!v.equals(l))throw new d(`input ${h} witnessUtxo is not the BIP-86 P2TR of the depositor key`);const z={kind:"taproot-keypath",expectedOutputKeyHex:v.subarray(it.length).toString("hex")};s.set(h,z),o.set(h,z);continue}const lt=t.getInputWitnessUtxo(h);if(lt&&(lt.scriptPubKey.equals(l)||f.some(T=>lt.scriptPubKey.equals(T))))throw new d(`input ${h} spends a depositor-owned UTXO but carries no signing metadata`)}for(const h of a??[])if(!o.has(h))throw new d(`input ${h} was requested for signing but carries no signing metadata`);if(o.size===0)throw new d("PSBT contains no depositor-signable input");let g=0;for(const h of o.values())g+=h.kind==="tapscript"?h.expectedLeafHashHexes.size:1;return{byInput:o,classifiedByInput:s,expectedYieldCount:g}}function tt(e){return e.kind==="tapscript"?`${e.inputIndex}:${e.leafHashHex}`:`${e.inputIndex}`}function ge(e,t){if(e<gt)throw new d(`YIELD payload truncated inside the signature (${e} of ${gt} bytes on input ${t})`);if(e!==gt)throw new I("non-default-sighash",t)}function Jr(e){const t=[],n=new Set;return{assertAndRecord:s=>{let i,a;try{const[f,g]=Fe(s,0);i=R(f),a=g}catch(f){throw new d(`unparseable YIELD payload: ${f instanceof Error?f.message:String(f)}`)}const c=s[a];if(c===void 0)throw new d("YIELD payload truncated before the augmented-pubkey length");const l=e.byInput.get(i);if(l===void 0)throw new I("unexpected-input",i);if(c===fe){if(l.kind!=="tapscript")throw new I("wrong-spend-type",i);const f=a+1+fe;if(s.length<f)throw new d("YIELD payload truncated inside the augmented pubkey");const g=s.subarray(a+1,a+1+It).toString("hex"),h=s.subarray(a+1+It,f).toString("hex"),E=s.subarray(f);if(g!==l.expectedSignerXOnlyHex)throw new I("wrong-signer-key",i);if(!l.expectedLeafHashHexes.has(h))throw new I("unknown-leaf-hash",i);ge(E.length,i);const y={kind:"tapscript",inputIndex:i,signerXOnlyHex:g,leafHashHex:h,signature:Uint8Array.from(E)};if(n.has(tt(y)))throw new I("duplicate-yield",i);n.add(tt(y)),t.push(y);return}if(c===pe){if(l.kind!=="taproot-keypath")throw new I("wrong-spend-type",i);const f=a+1+pe;if(s.length<f)throw new d("YIELD payload truncated inside the augmented pubkey");const g=s.subarray(a+1,f).toString("hex"),h=s.subarray(f);if(g!==l.expectedOutputKeyHex)throw new I("wrong-signer-key",i);ge(h.length,i);const E={kind:"taproot-keypath",inputIndex:i,outputKeyHex:g,signature:Uint8Array.from(h)};if(n.has(tt(E)))throw new I("duplicate-yield",i);n.add(tt(E)),t.push(E);return}throw new I("unexpected-encoding",i)},get yields(){return t},get lastYield(){return t[t.length-1]},assertComplete:()=>{const s=new Set;for(const[c,l]of e.byInput)if(l.kind==="tapscript")for(const f of l.expectedLeafHashHexes)s.add(`${c}:${f}`);else s.add(`${c}`);const i=[...s].filter(c=>!n.has(c)),a=[...n].some(c=>!s.has(c));if(i.length>0||a||n.size!==e.expectedYieldCount)throw new Ce(i)}}}const ze=/^[0-9a-f]{64}$/;function to(e,t){if($t("depositorPath",e),e[Rr]!==Ge)throw new Error("depositorPath must use BIP-86 receive branch 0");for(let n=0;n<Dt;n++)if(e[n]!==t[n])throw new Error(`depositorPath ${$(e)} is not under the wallet policy's key origin ${$(t)} — the device could never mark the input internal`)}function je(e,t,n,r){if(!Number.isInteger(r)||r<0||r>=b)throw new Error("addressIndex must be a non-hardened integer in 0..2^31-1");const o=at.HDKey.fromExtendedKey(e,t).deriveChild(n).deriveChild(r);if(!o.publicKey)throw new Error(`account xpub derived no public key at ${n}/${r}`);return u.Buffer.from(o.publicKey.subarray(1)).toString("hex")}function Qe(e,t,n){return je(e,t,Ke,n)}function eo(e,t,n){return je(e,t,Ge,n)}function Ze(e,t){const n=ct(t);return e.txOutputs.flatMap((r,o)=>u.Buffer.from(r.script).equals(n)?[o]:[])}function no(e,t){if(!ze.test(t))throw new Error("changeXOnlyHex must be 64 lowercase hex characters");return Ze(_.Psbt.fromHex(e),t).length>0}function ro(e){const{psbtHex:t,depositorXOnlyHex:n,walletPolicy:r,depositorPath:o,change:s}=e;if(!ze.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");to(o,r.keyOriginPath);const i=_.Psbt.fromHex(t),a=u.Buffer.from(r.masterFingerprintHex,"hex"),c=u.Buffer.from(n,"hex");let l=0;if(i.data.inputs.forEach((f,g)=>{f.tapInternalKey&&u.Buffer.from(f.tapInternalKey).equals(c)&&(l++,i.updateInput(g,{tapBip32Derivation:[{masterFingerprint:a,pubkey:c,path:$(o),leafHashes:[]}]}))}),l!==i.data.inputs.length)throw new Error(`${i.data.inputs.length-l} of ${i.data.inputs.length} inputs do not carry the depositor key as TAP_INTERNAL_KEY — every Pre-PegIn input must be internal`);if(s){const f=Qe(r.accountXpub,r.bip32Versions,s.addressIndex),g=[...o.slice(0,Dt),Ke,s.addressIndex],h=u.Buffer.from(f,"hex"),E=Ze(i,f);if(E.length===0)throw new Error("change script matches no output — the PSBT does not pay the wallet's change address");for(const y of E)i.updateOutput(y,{tapInternalKey:h,tapBip32Derivation:[{masterFingerprint:a,pubkey:h,path:$(g),leafHashes:[]}]})}return i.toHex()}const oo="BIP0322-signed-message",so=new Uint8Array([252,6,98,118,97,117,108,116,0]),Je=0,tn=0,en=0,io=0,Pt=0,ao=u.Buffer.from([106]),uo=/^[0-9a-f]{64}$/,co=/^[0-9a-f]{8}$/,lo=u.Buffer.alloc(32,0),ho=4294967295,fo=u.Buffer.from([0,32]),po=u.Buffer.from([81,32]),go=2;function Eo(e,t){const n=_.crypto.sha256(u.Buffer.from(e,"utf8"));return _.crypto.sha256(u.Buffer.concat([n,n,u.Buffer.from(t)]))}function wo(e,t){const n=new _.Transaction;n.version=Je,n.locktime=tn;const r=u.Buffer.concat([fo,Eo(oo,e)]);return n.addInput(lo,ho,en,r),n.addOutput(u.Buffer.concat([po,u.Buffer.from(t)]),Pt),Uint8Array.from(n.getHash(!1))}function _o(e){const{message:t,depositorXOnlyHex:n,masterFingerprintHex:r,depositorPath:o}=e;if(!uo.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");if(!co.test(r))throw new Error("masterFingerprintHex must be 8 lowercase hex characters");$t("depositorPath",o);const s=new TextEncoder().encode(t),i=u.Buffer.from(n,"hex"),a=ct(n),c=wo(s,a.subarray(go)),l=new _.Psbt;return l.setVersion(Je),l.setLocktime(tn),l.addInput({hash:u.Buffer.from(c),index:io,sequence:en,witnessUtxo:{script:a,value:Pt},tapInternalKey:i,tapBip32Derivation:[{masterFingerprint:u.Buffer.from(r,"hex"),pubkey:i,path:$(o),leafHashes:[]}]}),l.addOutput({script:ao,value:Pt}),l.addUnknownKeyValToGlobal({key:u.Buffer.from(so),value:u.Buffer.from(s)}),l.toHex()}const To=/^[0-9a-f]{64}$/,mo=/^[0-9a-f]{8}$/,So=192,yt=32,Io=0,Po=1,yo=32,bo=75,Ro=76,Ao=79,xo=80,Oo=81,Bo=96,vo=173,Co=178,Ee=4,we=128,Lo=1+yt+1+1+1,No=2,Mo=34,Do=2147483648,$o=4194304,ko=65535,Uo=2,Ho=0,Vo=0;function Go(e){if(e.length<Lo)return;let t=0;if(e[t++]!==yo)return;const n=u.Buffer.from(e.subarray(t,t+yt)).toString("hex");if(t+=yt,e[t++]!==vo||t>=e.length)return;const r=e[t++];let o=0;if(!(r===Io||r===Ao)){if(r>=Po&&r<=bo){const s=r;if(s>Ee||t+s>e.length||(e[t+s-1]&we)!==0)return;for(let i=0;i<s;i++)o|=e[t+i]<<8*i;t+=s}else if(r===Ro){if(t>=e.length)return;const s=e[t++];if(s>Ee||t+s>e.length||(e[t+s-1]&we)!==0)return;for(let i=0;i<s;i++)o|=e[t+i]<<8*i;t+=s}else if(r>=Oo&&r<=Bo)o=r-xo;else return;if(!(o===0||o>ko)&&!(t>=e.length)&&e[t++]===Co&&t===e.length)return{leafKeyHex:n,csv:o}}}function nn(e){let t;try{t=_.Psbt.fromHex(e)}catch{return}if(t.version<Uo||t.locktime!==Ho||t.data.inputs.length!==1||t.data.outputs.length!==1)return;const n=t.data.inputs[0],r=n.tapLeafScript??[];if(r.length!==1||r[0].leafVersion!==So)return;const o=Go(r[0].script);if(o!==void 0)return{...o,inputTxidInternalHex:u.Buffer.from(t.txInputs[0].hash).toString("hex"),sequence:t.txInputs[0].sequence??0,sighashType:n.sighashType,witnessUtxo:n.witnessUtxo?{scriptLength:n.witnessUtxo.script.length,value:n.witnessUtxo.value}:void 0,outputScriptHex:u.Buffer.from(t.txOutputs[0].script).toString("hex"),outputValue:t.txOutputs[0].value}}function rn(e){if(e.sighashType!==void 0&&e.sighashType!==Vo)throw new Error(`refund input sighash type ${e.sighashType} must be absent or SIGHASH_DEFAULT — the device rejects any other value`);if(e.witnessUtxo===void 0||e.witnessUtxo.scriptLength!==Mo)throw new Error("refund input must carry a P2TR witnessUtxo — the device rejects a missing or non-34-byte scriptPubKey");if(e.outputValue>e.witnessUtxo.value)throw new Error(`refund output value ${e.outputValue} exceeds the HTLC value ${e.witnessUtxo.value} — the device rejects it`);if(e.outputScriptHex!==ct(e.leafKeyHex).toString("hex"))throw new Error("refund output does not pay the refund leaf key's own BIP-86 address");if(e.csv<ot)throw new Error(`refund leaf CSV ${e.csv} is below the device's timelock floor of ${ot} blocks`);if((e.sequence&Do)!==0||(e.sequence&$o)!==0)throw new Error("refund input sequence must be a plain block-count relative timelock (BIP-68 disable/time flags clear)");if(e.sequence!==e.csv)throw new Error(`refund input sequence ${e.sequence} must equal the leaf CSV ${e.csv} — the device compares them unmasked and rejects a mismatch`)}function Ko(e){const{psbtHex:t,depositorXOnlyHex:n,masterFingerprintHex:r,depositorPath:o}=e;if(!To.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");if(!mo.test(r))throw new Error("masterFingerprintHex must be 8 lowercase hex characters (the 4-byte master fingerprint)");$t("depositorPath",o);const s=nn(t);if(s===void 0)throw new Error("not a refund-shaped PSBT (expected 1 input, 1 output, and one refund tapscript leaf)");if(rn(s),s.leafKeyHex!==n)throw new Error("refund leaf key does not equal the depositor key — this device cannot sign this refund");const i=_.Psbt.fromHex(t),a=u.Buffer.from(i.txOutputs[0].script),c=u.Buffer.from(r,"hex"),l=$(o);return i.updateInput(0,{tapBip32Derivation:[{masterFingerprint:c,pubkey:u.Buffer.from(n,"hex"),path:l,leafHashes:[]}]}),i.updateOutput(0,{tapBip32Derivation:[{masterFingerprint:c,pubkey:a.subarray(No),path:l,leafHashes:[]}]}),i.toHex()}class H{constructor(t,n=_.crypto.sha256){p(this,"leaves");p(this,"rootNode");p(this,"leafNodes");p(this,"h");this.leaves=t,this.h=n;const r=this.calculateRoot(t);this.rootNode=r.root,this.leafNodes=r.leaves}getRoot(){return this.rootNode.hash}size(){return this.leaves.length}getLeaves(){return this.leaves}getLeafHash(t){const n=this.leafNodes[t];if(n===void 0)throw Error("Index out of bounds");return n.hash}getProof(t){const n=this.leafNodes[t];if(n===void 0)throw Error("Index out of bounds");return bt(n)}calculateRoot(t){const n=t.length;if(n==0)return{root:new Et(void 0,void 0,u.Buffer.alloc(32,0)),leaves:[]};if(n==1){const f=new Et(void 0,void 0,t[0]);return{root:f,leaves:[f]}}const r=Yo(n),o=this.calculateRoot(t.slice(0,r)),s=this.calculateRoot(t.slice(r)),i=o.root,a=s.root,c=this.hashNode(i.hash,a.hash),l=new Et(i,a,c);return i.parent=l,a.parent=l,{root:l,leaves:o.leaves.concat(s.leaves)}}hashNode(t,n){return this.h(u.Buffer.concat([u.Buffer.from([1]),t,n]))}}function V(e,t=_.crypto.sha256){return Fo(u.Buffer.from([0]),e,t)}function Fo(e,t,n){return n(u.Buffer.concat([e,t]))}class Et{constructor(t,n,r){p(this,"leftChild");p(this,"rightChild");p(this,"parent");p(this,"hash");this.leftChild=t,this.rightChild=n,this.hash=r}isLeaf(){return this.leftChild==null}}function bt(e){if(!e.parent)return[];if(e.parent.leftChild==e){if(!e.parent.rightChild)throw new Error("Expected right child to exist");return[e.parent.rightChild.hash,...bt(e.parent)]}else{if(!e.parent.leftChild)throw new Error("Expected left child to exist");return[e.parent.leftChild.hash,...bt(e.parent)]}}function Yo(e){if(e<2)throw Error("Expected n >= 2");return Xo(e)?e/2:1<<Math.floor(Math.log2(e))}function Xo(e){return(e&e-1)==0}const kt=255,qo=2,S=32;class W{}class Wo extends W{constructor(n,r,o){super();p(this,"results");p(this,"code",16);this.progressCallback=r,this.onYield=o,this.results=n}execute(n){const r=u.Buffer.from(n.subarray(1));return this.onYield&&this.onYield(u.Buffer.from(r)),this.results.push(r),this.progressCallback&&this.progressCallback(),u.Buffer.from("")}}class zo extends W{constructor(n,r){super();p(this,"knownPreimages");p(this,"queue");p(this,"code",64);this.knownPreimages=n,this.queue=r}execute(n){const r=u.Buffer.from(n.subarray(1));if(r.length!==1+S)throw new Error("Invalid request, unexpected trailing data");if(r[0]!==0)throw new Error("Unsupported request, the first byte should be 0");const s=u.Buffer.from(r.subarray(1,1+S)).toString("hex"),i=this.knownPreimages.get(s);if(i!==void 0){const a=k(i.length),c=kt-a.length-1,l=Math.min(c,i.length);if(l<i.length)for(let f=l;f<i.length;f++)this.queue.push(u.Buffer.from(i.subarray(f,f+1)));return u.Buffer.concat([a,u.Buffer.from([l]),u.Buffer.from(i.subarray(0,l))])}throw new Error(`Requested unknown preimage for: ${s}`)}}class jo extends W{constructor(n,r){super();p(this,"knownTrees");p(this,"queue");p(this,"code",65);this.knownTrees=n,this.queue=r}execute(n){const r=u.Buffer.from(n.subarray(1));if(r.length<S+1+1)throw new Error("Invalid request, expected at least 34 bytes");const o=new D(r),i=o.readSlice(S).toString("hex");let a,c;try{a=R(o.readVarInt()),c=R(o.readVarInt())}catch{throw new Error("Invalid request, couldn't parse tree_size or leaf_index")}const l=this.knownTrees.get(i);if(!l)throw new Error(`Requested Merkle leaf proof for unknown tree: ${i}`);if(c>=a||l.size()!==a)throw new Error("Invalid index or tree size.");if(this.queue.length!==0)throw new Error("This command should not execute when the queue is not empty.");const f=l.getProof(c),g=Math.min(Math.floor((kt-S-1-1)/S),f.length),h=f.length-g;return h>0&&this.queue.push(...f.slice(-h)),u.Buffer.concat([l.getLeafHash(c),u.Buffer.from([f.length]),u.Buffer.from([g]),...f.slice(0,g)])}}class Qo extends W{constructor(n){super();p(this,"knownTrees");p(this,"code",66);this.knownTrees=n}execute(n){const r=u.Buffer.from(n.subarray(1));if(r.length!==S+S)throw new Error("Invalid request, unexpected trailing data");const s=u.Buffer.from(r.subarray(0,S)).toString("hex"),a=u.Buffer.from(r.subarray(S,S+S)).toString("hex"),c=this.knownTrees.get(s);if(!c)throw new Error(`Requested Merkle leaf index for unknown root: ${s}`);let l=0,f=0;for(let g=0;g<c.size();g++)if(c.getLeafHash(g).toString("hex")===a){f=1,l=g;break}return u.Buffer.concat([u.Buffer.from([f]),k(l)])}}class Zo extends W{constructor(n){super();p(this,"queue");p(this,"code",160);this.queue=n}execute(n){if(n.length!==1)throw new Error("Invalid request, unexpected trailing data");const r=this.queue[0];if(r===void 0)throw new Error("No elements to get");const o=r.length;if(this.queue.some(c=>c.length!==o))throw new Error("The queue contains elements with different byte length, which is not expected");const s=Math.floor((kt-qo)/o),i=Math.min(s,this.queue.length),a=this.queue.splice(0,i);return u.Buffer.concat([u.Buffer.from([i]),u.Buffer.from([o]),...a])}}class Jo{constructor(t,n){p(this,"roots",new Map);p(this,"preimages",new Map);p(this,"yielded",[]);p(this,"queue",[]);p(this,"commands",new Map);const r=[new Wo(this.yielded,t,n),new zo(this.preimages,this.queue),new Qo(this.roots),new jo(this.roots,this.queue),new Zo(this.queue)];for(const o of r){if(this.commands.has(o.code))throw new Error(`Multiple commands with code ${o.code}`);this.commands.set(o.code,o)}}getYielded(){return this.yielded}addKnownPreimage(t){this.preimages.set(_.crypto.sha256(t).toString("hex"),t)}addKnownList(t){for(const r of t){const o=u.Buffer.concat([u.Buffer.from([0]),r]);this.addKnownPreimage(o)}const n=new H(t.map(r=>V(r)));this.roots.set(n.getRoot().toString("hex"),n)}addKnownMapping(t){this.addKnownList(t.keys),this.addKnownList(t.values)}addKnownWalletPolicy(t){this.addKnownPreimage(t.serialize()),this.addKnownList(t.keys.map(n=>u.Buffer.from(n,"ascii"))),this.addKnownPreimage(u.Buffer.from(t.descriptorTemplate))}execute(t){if(t.length===0)throw new Error("Unexpected empty command");const n=t[0],r=this.commands.get(n);if(!r)throw new Error(`Unexpected command code ${n}`);return r.execute(t)}}class ts{constructor(t,n){p(this,"keys");p(this,"keysTree");p(this,"values");p(this,"valuesTree");if(t.length!=n.length)throw new Error("keys and values should have the same length");for(let r=0;r<t.length-1;r++)if(t[r].toString("hex")>=t[r+1].toString("hex"))throw new Error("keys must be in strictly increasing order");this.keys=t,this.keysTree=new H(t.map(r=>V(r))),this.values=n,this.valuesTree=new H(n.map(r=>V(r)))}commitment(){return u.Buffer.concat([k(this.keys.length),this.keysTree.getRoot(),this.valuesTree.getRoot()])}}class X extends qe{constructor(n){super();p(this,"globalMerkleMap");p(this,"inputMerkleMaps",[]);p(this,"outputMerkleMaps",[]);p(this,"inputMapCommitments");p(this,"outputMapCommitments");n.copy(this),this.globalMerkleMap=X.createMerkleMap(this.globalMap);const r=this.getGlobalInputCount();if(this.inputMaps.length!==r)throw new Error(`Input map count ${this.inputMaps.length} != declared PSBT_GLOBAL_INPUT_COUNT ${r}`);for(let s=0;s<r;s++){const i=this.inputMaps[s];if(i===void 0)throw new Error(`Missing input map ${s}`);this.inputMerkleMaps.push(X.createMerkleMap(i))}this.inputMapCommitments=this.inputMerkleMaps.map(s=>s.commitment());const o=this.getGlobalOutputCount();if(this.outputMaps.length!==o)throw new Error(`Output map count ${this.outputMaps.length} != declared PSBT_GLOBAL_OUTPUT_COUNT ${o}`);for(let s=0;s<o;s++){const i=this.outputMaps[s];if(i===void 0)throw new Error(`Missing output map ${s}`);this.outputMerkleMaps.push(X.createMerkleMap(i))}this.outputMapCommitments=this.outputMerkleMaps.map(s=>s.commitment())}getGlobalSize(){return this.globalMap.size}getGlobalKeysValuesRoot(){return this.globalMerkleMap.commitment()}static createMerkleMap(n){const r=[...n.keys()].sort(),o=r.map(i=>{const a=n.get(i);if(!a)throw new Error("No value for key "+i);return a}),s=r.map(i=>u.Buffer.from(i,"hex"));return new ts(s,o)}}const es=2;class ns{constructor(t,n,r){p(this,"name");p(this,"descriptorTemplate");p(this,"keys");this.name=t,this.descriptorTemplate=n,this.keys=r}getId(){return _.crypto.sha256(this.serialize())}serialize(){const t=this.keys.map(o=>u.Buffer.from(o,"ascii")),n=new H(t.map(o=>V(o))),r=new B;return r.writeUInt8(es),r.writeVarSlice(u.Buffer.from(this.name,"ascii")),r.writeVarInt(this.descriptorTemplate.length),r.writeSlice(_.crypto.sha256(u.Buffer.from(this.descriptorTemplate))),r.writeVarInt(this.keys.length),r.writeSlice(n.getRoot()),r.buffer()}}class on extends ns{constructor(t,n){super("",t,[n])}}const rs=4,os=0,ss=1,sn=32,is=new Uint8Array(sn),as=new Uint8Array(sn),us=/^[0-9a-f]{64}$/,cs=/^(?:[0-9a-fA-F]{2})+$/;function ls(e,t){const n=new H(e.inputMapCommitments.map(o=>V(o))).getRoot(),r=new H(e.outputMapCommitments.map(o=>V(o))).getRoot();return Uint8Array.from(u.Buffer.concat([e.getGlobalKeysValuesRoot(),k(e.getGlobalInputCount()),n,k(e.getGlobalOutputCount()),r,u.Buffer.from(t),u.Buffer.from(as)]))}function hs(e){return{cla:A,ins:rs,p1:os,p2:ss,data:e}}const fs=0;function ps(e,t){for(const[n]of t.byInput){const r=e.data.inputs[n].sighashType;if(r!==void 0&&r!==fs)throw new d(`input ${n} requests sighash type ${r}, but vault flows sign SIGHASH_DEFAULT only`)}}function ds(e,t){var n;for(const[r,o]of t.byInput){const s=e.data.inputs[r];if(s.finalScriptWitness||s.finalScriptSig)throw new d(`input ${r} is already finalized and this round signs it — pass an unsigned PSBT`);if(o.kind==="tapscript"){if((n=s.tapScriptSig)==null?void 0:n.some(a=>a.pubkey.toString("hex")===o.expectedSignerXOnlyHex&&o.expectedLeafHashHexes.has(a.leafHash.toString("hex"))))throw new d(`input ${r} already carries a tapScriptSig for a (key, leaf) we sign — pass an unsigned PSBT`);continue}if(s.tapKeySig)throw new d(`input ${r} already carries a tapKeySig and this round signs its keypath — pass an unsigned PSBT`)}}const an=new WeakMap;function gs(e,t){const n={...e};return an.set(n,t),n}function un(e){const t=an.get(e);if(!t)throw new d("unrecognised prepared signing state — use prepareSignPsbt's return value");return t}function cn(e){const{psbtHex:t,depositorXOnlyHex:n,signInputIndexes:r,walletPolicy:o}=e;if(!us.test(n))throw new d("depositorXOnlyHex must be 64 lowercase hex characters");let s;if(o!==void 0&&(s=new on(o.descriptorTemplate,o.keyInfo),s.getId().toString("hex")!==o.walletIdHex))throw new d("walletPolicy.walletIdHex does not match sha256 of the serialized policy");if(!cs.test(t))throw new d("psbtHex is not even-length hexadecimal");let i;try{i=_.Psbt.fromHex(t)}catch(E){throw new d(`PSBT rejected at parse (merge target): ${E instanceof Error?E.message:String(E)}`)}const a=new qe;try{a.deserialize(u.Buffer.from(t,"hex"))}catch(E){throw new d(`PSBT rejected at parse: ${E instanceof Error?E.message:String(E)}`)}let c,l;try{c=new X(a),l=Zr({psbt:c,depositorXOnlyHex:n,signInputIndexes:r})}catch(E){throw E instanceof d?E:new d(`PSBT rejected at preflight: ${E instanceof Error?E.message:String(E)}`)}ds(i,l),ps(i,l);const f=Jr(l),g=new Jo(void 0,E=>f.assertAndRecord(E));g.addKnownMapping(c.globalMerkleMap);for(const E of c.inputMerkleMaps)g.addKnownMapping(E);for(const E of c.outputMerkleMaps)g.addKnownMapping(E);g.addKnownList(c.inputMapCommitments),g.addKnownList(c.outputMapCommitments);const h=o?u.Buffer.from(o.walletIdHex,"hex"):is;return s&&g.addKnownWalletPolicy(s),gs({table:l,unsignedTxid:_.Transaction.fromBuffer(i.data.globalMap.unsignedTx.toBuffer()).getId()},{cdata:ls(c,h),interpreter:g,collector:f,originalPsbtHex:t,signsUnderWalletPolicy:o!==void 0})}const Es=248,ws=1,_s=0,Ts=0,ms=36864,Ss=57344;async function Is(e,t,n){const{collector:r,interpreter:o,cdata:s}=un(t),{table:i}=t;if(n.signal.aborted)throw new _t(r.yields.length);const a=hs(s);let c=a,l=await e(a),f=0;for(;l.sw===Ss;){let g;try{g=o.execute(u.Buffer.from(l.data))}catch(h){throw Le(h)?h:Ne(h)?new d(h.detail,et(r.yields)):new d(`client command failed: ${h instanceof Error?h.message:String(h)}`,et(r.yields))}if(r.yields.length>f){f=r.yields.length;const h=r.lastYield;if(h!==void 0&&n.onProgress!==void 0)try{n.onProgress({inputIndex:h.inputIndex,yieldedCount:f,expectedYieldCount:i.expectedYieldCount})}catch{}}if(n.signal.aborted)throw new _t(r.yields.length);c={cla:Es,ins:ws,p1:_s,p2:Ts,data:g},l=await e(c)}if(l.sw!==ms){const g=ke(l.sw,{...n.appIdentity,ins:c.ins,p1:c.p1,preDispatch:c===a});throw g===void 0?new d(`status word 0x${l.sw.toString(16)} escaped classification`,et(r.yields)):g}return r.assertComplete(),r.yields}function Ps(e,t){const n=_.Psbt.fromHex(e);for(const r of t)r.kind==="tapscript"?n.updateInput(r.inputIndex,{tapScriptSig:[{pubkey:u.Buffer.from(r.signerXOnlyHex,"hex"),leafHash:u.Buffer.from(r.leafHashHex,"hex"),signature:u.Buffer.from(r.signature)}]}):n.updateInput(r.inputIndex,{tapKeySig:u.Buffer.from(r.signature)});return n.toHex()}const _e=new WeakSet;async function ln(e,t,n){const{originalPsbtHex:r,signsUnderWalletPolicy:o}=un(t);if(_e.has(t))throw new d("prepared signing state was already used — call prepareSignPsbt again for a retry");if([...t.table.byInput.values()].some(c=>c.kind==="taproot-keypath")&&!o)throw new d("PSBT signs a key-path input but was prepared without a walletPolicy — the device would answer SW_OK with no signature");_e.add(t);const i=await Is(e,t,n);let a;try{a=Ps(r,i)}catch(c){throw new d(`merge failed after signing: ${c instanceof Error?c.message:String(c)}`,et(i))}return{signedPsbtHex:a,yields:[...i]}}async function ys(e,t){const{psbtHex:n,depositorXOnlyHex:r,signInputIndexes:o,...s}=t,i=cn({psbtHex:n,depositorXOnlyHex:r,signInputIndexes:o});return ln(e,i,s)}const Te="tr(@0/**)",me=2147483647,bs=/^[0-9a-f]{8}$/;function Rs(e){const{masterFingerprintHex:t,coinType:n,accountIndex:r,accountXpub:o,bip32Versions:s}=e;if(!bs.test(t))throw new Error("masterFingerprintHex must be 8 lowercase hex characters");if(!Number.isInteger(n)||n<0||n>me||!Number.isInteger(r)||r<0||r>me)throw new Error("coinType and accountIndex must be non-negative integers in 0..0x7fffffff");try{at.HDKey.fromExtendedKey(o,s)}catch(c){throw new Error(`accountXpub is not a valid extended key for this network: ${c instanceof Error?c.message:String(c)}`)}const i=`[${t}/${st}'/${n}'/${r}']${o}`,a=new on(Te,i).getId().toString("hex");return{descriptorTemplate:Te,keyInfo:i,walletIdHex:a,accountXpub:o,bip32Versions:s,keyOriginPath:[(b|st)>>>0,(b|n)>>>0,(b|r)>>>0],masterFingerprintHex:t}}exports.closeDmk=q.closeDmk;exports.connectDmkSession=q.connectDmkSession;exports.disconnectDmkSession=q.disconnectDmkSession;exports.isSessionAlive=q.isSessionAlive;exports.refreshSessionApp=q.refreshSessionApp;exports.DEPOSIT_TERMS_REJECTED_ERROR_NAME=Ve;exports.DepositTermsRejectedError=m;exports.LEDGER_DEVICE_ERROR_NAME=Ot;exports.LEDGER_DEVICE_LOCKED_ERROR_NAME=xt;exports.LEDGER_SIGN_PSBT_ABORTED_ERROR_NAME=Lt;exports.LEDGER_SIGN_PSBT_INCOMPLETE_ERROR_NAME=vt;exports.LEDGER_SIGN_PSBT_PROTOCOL_ERROR_NAME=Ct;exports.LEDGER_USER_REFUSED_ERROR_NAME=At;exports.LEDGER_YIELD_MISMATCH_ERROR_NAME=Bt;exports.LedgerDeviceError=ve;exports.LedgerDeviceLockedError=Be;exports.LedgerSignPsbtAbortedError=_t;exports.LedgerSignPsbtIncompleteError=Ce;exports.LedgerSignPsbtProtocolError=d;exports.LedgerUserRefusedError=Oe;exports.LedgerYieldMismatchError=I;exports.SW_BAD_STATE=Me;exports.SW_CAP_EXCEEDED=De;exports.SW_CLA_NOT_SUPPORTED=Nt;exports.SW_INS_NOT_SUPPORTED=Mt;exports.approveVaultIntent=Wn;exports.assertDepositTermsDeviceCompatible=Pr;exports.assertRefundPsbtSignable=rn;exports.augmentPsbtForRefund=Ko;exports.augmentPsbtForWalletPolicy=ro;exports.buildDefaultTaprootPolicy=Rs;exports.buildPopPsbtHex=_o;exports.classifyRefundPsbt=nn;exports.createDmkApduSender=dr;exports.createDmkRawApduSender=Ue;exports.deriveChangeXOnlyHex=Qe;exports.deriveContextHash=qn;exports.deriveReceiveXOnlyHex=eo;exports.encodeIntentGroup=Ie;exports.encodeIntentScalars=Se;exports.encodeKeyBatches=Pe;exports.getExtendedPublicKey=Re;exports.getMasterFingerprintHex=Jn;exports.getXOnlyPublicKeyHex=tr;exports.isLedgerDeviceError=rr;exports.isLedgerDeviceLockedError=or;exports.isLedgerSignPsbtAbortedError=ir;exports.isLedgerSignPsbtIncompleteError=sr;exports.isLedgerSignPsbtProtocolError=Ne;exports.isLedgerUserRefusedError=nr;exports.isLedgerYieldMismatchError=Le;exports.prepareSignPsbt=cn;exports.psbtPaysChangeScript=no;exports.signPreparedVaultPsbt=ln;exports.signVaultPsbt=ys;
|
|
1
|
+
"use strict";var An=Object.defineProperty;var xn=(e,t,n)=>t in e?An(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var p=(e,t,n)=>xn(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("bitcoinjs-lib"),u=require("buffer"),ft=require("@scure/bip32"),j=require("./testing-DjacXOYK.cjs"),vn=require("@bitcoin-js/tiny-secp256k1-asmjs");function Cn(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const Pt=Cn(vn),O=2147483648,Bn=4294967295,it=86,Be=0,Le=1,jt=5,Bt=3,Ln=3,Nn=4;function ht(e,t){if(t.length!==jt)throw new Error(`${e} must have exactly ${jt} levels, got ${t.length}`);for(const r of t)if(!Number.isInteger(r)||r<0||r>Bn)throw new Error(`${e} levels must be integers in 0..0xffffffff`);if(!t.slice(0,Bt).every(r=>(r&O)!==0)||(t[Nn]&O)!==0)throw new Error(`${e} must harden purpose'/coin'/account' and leave the address index unhardened`);if(t[0]!==(O|it)>>>0)throw new Error(`${e} must use BIP-86 purpose ${it}'`)}function L(e){return"m/"+e.map(t=>(t&O)!==0?`${(t&~O)>>>0}'`:`${t>>>0}`).join("/")}const Mn=/^[0-9a-f]{64}$/,Un=/^[0-9a-f]{8}$/,Dn=192,Lt=32,Ne=1,$n=2,x=32,kn=130,Hn=135,Vn=136,Fn=168,Nt=172,Mt=173,Gn=178,Kn=81,Me=128,Ut=1,N=Ut+Lt,Yn=1+Lt+1,Ue=68,De=34,$e=67,Xn=73,Wn=34,qn=35,zn=36,jn=37,Qn=38,Zn=39,Jn=72,Qt=90,Zt=4032,tr=Me-1;function er(e){const t=e.length;if(t<=Ue||e[0]!==x||e[N]!==Mt||e[t-1]!==Gn||e[De]!==x||e[$e]!==Nt)return;const n=u.Buffer.from(e.subarray(Ut,N)).toString("hex");if(e[t-4]===$n&&(e[t-2]&Me)===0){const r=e[t-3]|e[t-2]<<8;if(r>=Qt&&r<=Zt)return{leafKeyHex:n}}if(e[t-3]===Ne){const r=e[t-2];if(r>=Qt&&r<=Zt&&r<=tr)return{leafKeyHex:n}}}const S={claim:0,wronglyChallenged:0,payoutFinalize:1,assert:0,payoutDepositor:0},nr=2,rr=0,or=1,sr=2,ir=1,ar=1,ur=1,cr=2,lr=2,fr=0;function gt(e){const t=e.tapLeafScript??[];if(!(t.length!==1||t[0].leafVersion!==Dn))return t[0].script}function hr(e){return e.length===Yn&&e[0]===x&&e[N]===Nt}function pr(e){return e.length===Xn&&e[0]===x&&e[N]===Mt&&e[Wn]===kn&&e[qn]===Ne&&e[zn]===Lt&&e[jn]===Vn&&e[Qn]===Fn&&e[Zn]===x&&e[Jn]===Hn}function dr(e){return e.length>Ue&&e[0]===x&&e[N]===Mt&&e[De]===x&&e[$e]===Nt&&e[e.length-1]===Kn}function J(e){return u.Buffer.from(e.subarray(Ut,N)).toString("hex")}function ke(e,t){let n;try{n=w.Psbt.fromHex(e)}catch{return}if(n.version<nr||n.locktime!==rr)return;const r=n.data.inputs.length,o=n.data.outputs.length;if(r===cr&&o===lr){const i=gt(n.data.inputs[S.payoutFinalize]);if(i===void 0)return;const a=er(i);if(a===void 0)return;const c=n.data.inputs[fr];if(t===S.payoutDepositor){const l=gt(c);return l===void 0||l[0]!==x||l.length<=N?void 0:{kind:"payoutDepositor",signInputIndex:S.payoutDepositor,leafKeyHex:J(l)}}return t!==S.payoutFinalize||(c.tapLeafScript??[]).length>0||(c.tapBip32Derivation??[]).some(l=>l.pubkey.toString("hex")===a.leafKeyHex)?void 0:{kind:"payoutFinalize",signInputIndex:S.payoutFinalize,leafKeyHex:a.leafKeyHex}}if(t!==S.claim)return;const s=gt(n.data.inputs[S.claim]);if(s!==void 0){if(r===or&&o===sr&&hr(s))return{kind:"claim",signInputIndex:S.claim,leafKeyHex:J(s)};if(r===ur&&dr(s))return{kind:"assert",signInputIndex:S.assert,leafKeyHex:J(s)};if(r===ir&&o===ar&&pr(s))return{kind:"wronglyChallenged",signInputIndex:S.wronglyChallenged,leafKeyHex:J(s)}}}function Er(e){const{kind:t,psbtHex:n,depositorXOnlyHex:r,masterFingerprintHex:o,depositorPath:s}=e;if(!Mn.test(r))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");if(!Un.test(o))throw new Error("masterFingerprintHex must be 8 lowercase hex characters (the 4-byte master fingerprint)");if(ht("depositorPath",s),t==="payoutDepositor")throw new Error("payoutDepositor needs no derivation entry — the device takes its path from the intent; sign it through signPsbt");const i=ke(n,S[t]);if(i===void 0||i.kind!==t)throw new Error(`not a ${t}-shaped PSBT for input ${S[t]}`);if(i.leafKeyHex!==r)throw new Error(`${t} leaf key does not equal the depositor key — this device cannot sign this PSBT`);const a=w.Psbt.fromHex(n),c=a.data.inputs[i.signInputIndex];return c.tapBip32Derivation=void 0,a.updateInput(i.signInputIndex,{tapBip32Derivation:[{masterFingerprint:u.Buffer.from(o,"hex"),pubkey:u.Buffer.from(r,"hex"),path:L(s),leafHashes:[]}]}),a.toHex()}const gr=1,_r=1,wr=1,Tr=2,Sr=33,mr=256,Ir=257,Pr=258,yr=39,br=259,Or=105,Rr=260,Ar=261,xr=262,vr=271,Cr=265,Br=266,Lr=267,Nr=268,Mr=269,Ur=270,Dr=263,$r=264,at=32,kr=32,W=255,Hr=3+at,Jt=Math.floor(W/Hr);function v(e,t){if(t.length>W)throw new Error(`TLV value for tag 0x${e.toString(16)} exceeds 255 bytes`);const n=new Uint8Array(3+t.length);return n[0]=e>>8&255,n[1]=e&255,n[2]=t.length,n.set(t,3),n}function pt(e,t,n){if(e<0n||e>=1n<<BigInt(8*t))throw new Error(`${n} ${e} does not fit in ${t} bytes`);const r=new Uint8Array(t);let o=e;for(let s=t-1;s>=0;s--)r[s]=Number(o&0xffn),o>>=8n;return r}function D(e,t,n){return v(e,pt(BigInt(t),1,n))}function tt(e,t,n){return v(e,pt(BigInt(t),4,n))}function $(e,t,n){return v(e,pt(t,8,n))}function ut(e){const t=e.reduce((o,s)=>o+s.length,0),n=new Uint8Array(t);let r=0;for(const o of e)n.set(o,r),r+=o.length;return n}function Dt(e,t,n){if(e.length!==t)throw new Error(`${n} must be ${t} bytes, got ${e.length}`);return e}const te=5;function He(e){if(e.depositorPath.length!==te)throw new Error(`depositorPath must have exactly ${te} levels, got ${e.depositorPath.length}`);const t=ut(e.depositorPath.map(n=>pt(BigInt(n>>>0),4,"path level")));return ut([D(wr,gr,"structureType"),D(Tr,_r,"version"),tt(Sr,e.coinType,"coinType"),$(mr,e.baseFeeRate,"baseFeeRate"),tt(Ir,e.peginCsvTimelock,"peginCsvTimelock"),tt(Pr,e.payoutTimelock,"payoutTimelock"),v(yr,Dt(e.prepeginTxidInternal,kr,"prepeginTxid")),tt(br,e.htlcRefundTimelock,"htlcRefundTimelock"),v(Or,t),D(Rr,e.keeperCount,"keeperCount"),D(Ar,e.challengerCount,"challengerCount"),D(xr,e.vaultCount,"vaultCount"),$(vr,e.prepeginMaxFee,"prepeginMaxFee")])}function Ve(e){return ut([D(Cr,e.htlcVout,"htlcVout"),v(Br,Dt(e.vaultProviderPubkey,at,"vaultProviderPubkey")),$(Lr,e.vaultAmount,"vaultAmount"),$(Nr,e.commissionFee,"commissionFee"),$(Mr,e.depositorClaimValue,"depositorClaimValue"),$(Ur,e.peginMaxFee,"peginMaxFee")])}function Fe(e,t){const n=(s,i)=>s.map((a,c)=>Dt(a,at,`${i}[${c}]`)).sort((a,c)=>{for(let l=0;l<at;l++)if(a[l]!==c[l])return a[l]-c[l];return 0}),r=[...n(e,"keeper").map(s=>v(Dr,s)),...n(t,"challenger").map(s=>v($r,s))],o=[];for(let s=0;s<r.length;s+=Jt)o.push(ut(r.slice(s,s+Jt)));return o}const A=225,_t=128,ee=129,Vr=0,Fr=1,Gr=0,Kr=1,Yr=2,q=0,ne=64,re=1024,oe=10,se=32;function Xr(e){return new Uint8Array([e>>8&255,e&255])}function Wr(e){const t=e>>>0;return new Uint8Array([t>>>24&255,t>>>16&255,t>>>8&255,t&255])}function wt(e){const t=new Uint8Array(e.reduce((r,o)=>r+o.length,0));let n=0;for(const r of e)t.set(r,n),n+=r.length;return t}const ie=/^[a-z0-9-]+$/;async function qr(e,{appName:t,derivationPath:n,context:r}){const o=new TextEncoder().encode(t);if(o.length<1||o.length>ne)throw new Error(`appName must be 1..${ne} bytes, got ${o.length}`);if(!ie.test(t))throw new Error(`appName must match ${ie} — the device rejects other characters`);if(n.length<1||n.length>oe)throw new Error(`derivationPath must have 1..${oe} levels`);if(r.length<1||r.length>re)throw new Error(`context must be 1..${re} bytes, got ${r.length}`);const s=wt([new Uint8Array([o.length]),o,new Uint8Array([n.length]),wt(n.map(Wr)),Xr(r.length)]),i=Math.min(r.length,W-s.length);if(i<0)throw new Error("appName and derivationPath leave no room for context in the first APDU");let a=await e({cla:A,ins:ee,p1:Vr,p2:q,data:wt([s,r.subarray(0,i)])});for(let c=i;c<r.length;c+=W)a=await e({cla:A,ins:ee,p1:Fr,p2:q,data:r.subarray(c,c+W)});if(a.length!==se)throw new Error(`Expected a ${se}-byte context root, got ${a.length} bytes`);return a}async function zr(e,{scalars:t,groups:n,keeperPubkeys:r,challengerPubkeys:o}){if(n.length!==t.vaultCount)throw new Error(`vaultCount ${t.vaultCount} does not match ${n.length} group(s)`);if(r.length!==t.keeperCount)throw new Error(`keeperCount ${t.keeperCount} does not match ${r.length} key(s)`);if(t.keeperCount<1||t.challengerCount<1)throw new Error(`Both rosters must be non-empty: keeperCount=${t.keeperCount}, challengerCount=${t.challengerCount}`);if(o.length!==t.challengerCount)throw new Error(`challengerCount ${t.challengerCount} does not match ${o.length} key(s)`);await e({cla:A,ins:_t,p1:Gr,p2:q,data:He(t)});for(const s of n)await e({cla:A,ins:_t,p1:Kr,p2:q,data:Ve(s)});for(const s of Fe(r,o))await e({cla:A,ins:_t,p1:Yr,p2:q,data:s})}const jr=0,Ge=0,Ke=1,Qr=0,ae=33,ue=10,Zr=5,Jr=4;async function to(e){const t=await e({cla:A,ins:Zr,p1:Ge,p2:Ke,data:new Uint8Array(0)});if(t.length!==Jr)throw new Error(`Ledger returned a ${t.length}-byte response instead of the 4-byte master fingerprint`);return Xe(t)}async function Ye(e,t,n){if(t.length<1||t.length>ue)throw new Error(`BIP-32 path must have 1..${ue} levels, got ${t.length}`);const r=await e({cla:A,ins:jr,p1:Ge,p2:Ke,data:no(t)}),o=new TextDecoder().decode(r);if(o.length===0)throw new Error("Ledger returned an empty extended key");return ft.HDKey.fromExtendedKey(o,n),o}async function eo(e,t,n){const r=await Ye(e,t,n),o=ft.HDKey.fromExtendedKey(r,n);if(!o.publicKey||o.publicKey.length!==ae)throw new Error(`Ledger returned an extended key without a ${ae}-byte public key`);return Xe(o.publicKey.subarray(1))}function Xe(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function no(e){const t=new Uint8Array(2+e.length*4);return t[0]=Qr,t[1]=e.length,e.forEach((n,r)=>{const o=2+r*4;t[o]=n>>>24&255,t[o+1]=n>>>16&255,t[o+2]=n>>>8&255,t[o+3]=n&255}),t}const $t="LedgerUserRefusedError",kt="LedgerDeviceLockedError",Ht="LedgerDeviceError",Vt="LedgerYieldMismatchError",Ft="LedgerSignPsbtIncompleteError",Gt="LedgerSignPsbtProtocolError",Kt="LedgerSignPsbtAbortedError";function We(e){return e.toString(16).padStart(4,"0")}class qe extends Error{constructor(n){super(`User rejected the request on the Ledger device (0x${We(n)})`);p(this,"statusWord");this.name=$t,this.statusWord=n}}class ze extends Error{constructor(n,r){super(`The Ledger device is locked — unlock it and retry (0x${We(n)})`);p(this,"statusWord");p(this,"preDispatch");this.name=kt,this.statusWord=n,this.preDispatch=(r==null?void 0:r.preDispatch)??!1}}class je extends Error{constructor(n,r){super(r);p(this,"statusWord");this.name=Ht,this.statusWord=n}}class P extends Error{constructor(n,r){super(`The device yielded a signature that fails the expected-signature table (${n}${r===void 0?"":` on input ${r}`})`);p(this,"kind");p(this,"inputIndex");this.name=Vt,this.kind=n,this.inputIndex=r}}class Qe extends Error{constructor(n){super(`The device completed SIGN_PSBT without yielding every expected signature (missing ${n.length}: ${n.join(", ")})`);p(this,"missing");this.name=Ft,this.missing=n}}function st(e){return e.map(({inputIndex:t,leafHashHex:n})=>n===void 0?{inputIndex:t}:{inputIndex:t,leafHashHex:n})}class d extends Error{constructor(n,r=[]){super(`SIGN_PSBT protocol failure: ${n}`);p(this,"detail");p(this,"collectedYields");this.name=Gt,this.detail=n,this.collectedYields=r}}class yt extends Error{constructor(n){super("SIGN_PSBT was abandoned host-side before completion");p(this,"yieldedCount");this.name=Kt,this.yieldedCount=n}}function ro(e){return e instanceof Error&&e.name===$t}function oo(e){return e instanceof Error&&e.name===Ht}function so(e){return e instanceof Error&&e.name===kt}function Ze(e){return e instanceof Error&&e.name===Vt}function io(e){return e instanceof Error&&e.name===Ft}function Je(e){return e instanceof Error&&e.name===Gt}function ao(e){return e instanceof Error&&e.name===Kt}const uo=36864,co=new Set([21761,27013]),lo=new Set([21781,27010,21251]),Yt=28160,Xt=27904,tn=45063,en=45066,fo={27264:"The device rejected the data as invalid",27266:"The device does not support this request — check that the app build matches the selected network",27270:"The device rejected the instruction parameters",27271:"The device rejected the payload length",[Xt]:"The running app does not support this instruction",26881:"The device was still busy with the previous request",[Yt]:"The running app does not handle vault instructions — open the Babylon Vault app for this network",45056:"The device reported a wrong response length",[tn]:"The device is not in the expected state for this step",45064:"The device rejected a signature or HMAC as invalid",45065:"The device rejected the CPFP anchor",[en]:"The device has already signed the maximum number of these transactions",28416:"The device could not derive the key at the requested path"};function k(e){return e.toString(16).padStart(2,"0")}function nn(e){return e.toString(16).padStart(4,"0")}function rn(e,t){if(e===uo)return;if(co.has(e))return new qe(e);if(lo.has(e))return new ze(e,{preDispatch:t.preDispatch===!0});const n=fo[e],r=(e===Yt||e===Xt)&&t.appName?` (app at connect time: "${t.appName}"${t.appVersion?` v${t.appVersion}`:""})`:"";return new je(e,`${n??"The device rejected the request"} (ins 0x${k(t.ins)} p1 0x${k(t.p1)}, sw 0x${nn(e)})${r}`)}function ho(e,t){return async n=>{const{sw:r,data:o}=await e(n),s=rn(r,{...t,ins:n.ins,p1:n.p1});if(s)throw s;return o}}const ce=2;function po(e){if(e.statusCode.length!==ce)throw new Error(`The device returned a ${e.statusCode.length}-byte status word; expected ${ce}.`);return e.statusCode[0]<<8|e.statusCode[1]}function et(e,t){if(!Number.isInteger(e)||e<0||e>255)throw new Error(`APDU ${t} ${e} is not a single byte (0..255)`)}function Eo(e){if(et(e.cla,"cla"),et(e.ins,"ins"),et(e.p1,"p1"),et(e.p2,"p2"),e.data.length>255)throw new Error(`APDU data is ${e.data.length} bytes; Lc is a single byte (max 255)`);const t=new Uint8Array(5+e.data.length);return t[0]=e.cla,t[1]=e.ins,t[2]=e.p1,t[3]=e.p2,t[4]=e.data.length,t.set(e.data,5),t}function le(){return globalThis.__LEDGER_VAULT_APDU_TRACE__===!0}function on(e){return async t=>{const n=`${k(t.cla)} ${k(t.ins)} ${k(t.p1)} ${k(t.p2)} Lc=${t.data.length}`;let r;try{r=await e.dmk.sendApdu({sessionId:e.sessionId,apdu:Eo(t)})}catch(s){throw le()&&console.debug(`[ledger-vault] APDU ${n} -> transport error`,s),s}const o=po(r);return le()&&console.debug(`[ledger-vault] APDU ${n} -> sw=0x${nn(o)} len=${r.data.length}`),{sw:o,data:r.data}}}function go(e){return ho(on(e),{appName:e.appName,appVersion:e.appVersion})}const _o=2,wo=3,fe=32,To=10,he=10000n,pe=100000000n,ct=72,So=1008,mo=4320,Io=91,Po=4031,sn=546n,de=sn,yo=2n,an="DepositTermsRejectedError";class m extends Error{constructor(n,r="device-envelope"){super(n);p(this,"reason");this.name=an,this.reason=r}}const y="Deposit terms outside the device-supported range";function C(e,t,n,r){if(!Number.isInteger(t)||t<n||t>r)throw new m(`${y}: ${e} ${t} not in [${n}, ${r}]`)}function bo(e){if(C("vaultCoreVersion",e.vaultCoreVersion,_o,wo),e.protocolFeeRate<1n||e.protocolFeeRate>he)throw new m(`${y}: protocolFeeRate ${e.protocolFeeRate} not in [1, ${he}]`);if(C("timelockPegin",e.timelockPegin,ct,So),C("timelockAssert",e.timelockAssert,Io,Po),C("timelockRefund",e.timelockRefund,ct,mo),C("keeper count",e.vaultKeeperBtcPubkeys.length,1,fe),C("challenger count",e.universalChallengerBtcPubkeys.length,1,fe),C("vault count",e.vaults.length,1,To),X("prepeginMaxFee",e.prepeginMaxFee),e.prepeginMaxFee<1n||e.prepeginMaxFee>pe)throw new m(`${y}: prepeginMaxFee ${e.prepeginMaxFee} not in [1, ${pe}]`);let t=-1;for(const a of e.vaults){if(!Number.isInteger(a.htlcVout)||a.htlcVout<0||a.htlcVout>255)throw new m(`${y}: htlcVout ${a.htlcVout} not in [0, 255]`);if(a.htlcVout<=t)throw new m(`${y}: vault groups must be in strictly ascending htlcVout order; got ${a.htlcVout} after ${t}`);t=a.htlcVout}const n=a=>a.replace(/^0x/,"").toLowerCase(),r=new Set(e.vaults.map(a=>n(a.vaultProviderBtcPubkey))),o=new Set;for(const[a,c]of[["vaultKeeperBtcPubkeys",e.vaultKeeperBtcPubkeys],["universalChallengerBtcPubkeys",e.universalChallengerBtcPubkeys]])for(const l of c){const h=n(l);if(r.has(h))throw new m(`${y}: ${a} contains the vault provider's own key (${h.slice(0,16)}…)`);if(o.has(h))throw new m(`${y}: duplicate participant key in ${a} (${h.slice(0,16)}…)`);o.add(h)}const s=sn,i=yo*s;for(const a of e.vaults){if(X(`vault ${a.htlcVout} peginAmount`,a.peginAmount),X(`vault ${a.htlcVout} commissionFee`,a.commissionFee),X(`vault ${a.htlcVout} depositorClaimValue`,a.depositorClaimValue),X(`vault ${a.htlcVout} peginMaxFee`,a.peginMaxFee),a.commissionFee<s)throw new m(`${y}: vault ${a.htlcVout} commissionFee ${a.commissionFee} below the ${s}-sat dust limit`);if(a.depositorClaimValue<de)throw new m(`${y}: vault ${a.htlcVout} depositorClaimValue ${a.depositorClaimValue} below the ${de}-sat device floor`);if(a.peginAmount<=a.commissionFee+i)throw new m(`${y}: vault ${a.htlcVout} peginAmount ${a.peginAmount} must exceed commissionFee + ${i} (${a.commissionFee+i})`)}}const Oo=(1n<<64n)-1n;function X(e,t){if(t<0n||t>Oo)throw new m(`${y}: ${e} ${t} does not fit in an unsigned 64-bit field`)}const Ee=253,Ro=254,Ao=65535,xo=4294967295;function vo(e){if(e<Ee)return u.Buffer.from([e]);if(e<=Ao){const t=u.Buffer.alloc(2);return t.writeUInt16LE(e),u.Buffer.concat([u.Buffer.from([Ee]),t])}if(e<=xo){const t=u.Buffer.alloc(4);return t.writeUInt32LE(e),u.Buffer.concat([u.Buffer.from([Ro]),t])}throw new Error(`Script too large to encode as CompactSize: ${e} bytes`)}const Co="TapLeaf";function Bo(e,t){const n=u.Buffer.concat([u.Buffer.from([e]),vo(t.length),u.Buffer.from(t)]);return w.crypto.taggedHash(Co,n)}function Lo(e,t,n,r){for(let o=0;o<t;o++){if(n[o+r]===void 0)throw Error("Buffer too small");n[o+r]=Number(e%BigInt(256)),e=e>>BigInt(8)}}function No(e,t,n){let r=BigInt(0);for(let o=0;o<n;o++){const s=e[o+t];if(s===void 0)throw Error("Buffer too small");r+=BigInt(s)<<BigInt(o*8)}return r}function R(e){if(e<0)throw RangeError("Negative bigint is not a valid varint");if(e>Number.MAX_SAFE_INTEGER)throw RangeError("Too large for a Number");return Number(e)}function Mo(e){if(typeof e=="number"&&(e=R(e)),e<BigInt(0))throw new RangeError("Negative numbers are not supported");if(e>=BigInt(1)<<BigInt(64))throw new RangeError("Too large for a Bitcoin-style varint");return e<BigInt(253)?1:e<=BigInt(65535)?3:e<=BigInt(4294967295)?5:9}const Uo=BigInt(253),Do=BigInt(65535)+BigInt(1),$o=BigInt(4294967295)+BigInt(1);function un(e,t){if(t<0)throw RangeError("Negative offset is invalid");const n=e[t];if(n===void 0)throw Error("Buffer too small");if(n<253)return[BigInt(n),1];{let r,o;n===253?(r=2,o=Uo):n===254?(r=4,o=Do):(r=8,o=$o);const s=No(e,t+1,r);if(s<o)throw RangeError(`Non-minimal varint at offset ${t}: a ${r+1}-byte CompactSize must encode a value of at least ${o}; re-encode it in its canonical (shorter) form`);return[s,r+1]}}function V(e){typeof e=="number"&&(e=R(e));const t=Mo(e);e=BigInt(e);const n=u.Buffer.alloc(t);return t==1?n[0]=Number(e):(t==3?n[0]=253:t===5?n[0]=254:n[0]=255,Lo(e,t-1,n,1)),n}const ko=31;function cn(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Can't convert a number that is not a non-negative safe integer to 64-bit LE");const t=u.Buffer.alloc(8,0);for(let n=0;n<t.length;n++){const r=e&255;t[n]=r,e=(e-r)/256}return t}function bt(e){let t=0;if(e.length!==8)throw new Error("Expected Buffer of length 8");if(e[7]!==0)throw new Error("Can't encode numbers > MAX_SAFE_INT");const n=e[6];if(n===void 0||n>ko)throw new Error("Can't encode numbers > MAX_SAFE_INT");for(let r=e.length-1;r>=0;r--){const o=e[r];if(o===void 0)throw new Error("Buffer too small");t=t*256+o}return t}class B{constructor(){p(this,"bufs",[])}write(t,n){const r=u.Buffer.alloc(t);n(r),this.bufs.push(r)}writeUInt8(t){this.write(1,n=>n.writeUInt8(t,0))}writeInt32(t){this.write(4,n=>n.writeInt32LE(t,0))}writeUInt32(t){this.write(4,n=>n.writeUInt32LE(t,0))}writeUInt64(t){const n=cn(t);this.writeSlice(n)}writeVarInt(t){this.bufs.push(V(t))}writeSlice(t){this.bufs.push(u.Buffer.from(t))}writeVarSlice(t){this.writeVarInt(t.length),this.writeSlice(t)}buffer(){return u.Buffer.concat(this.bufs)}}class H{constructor(t,n=0){this.buffer=t,this.offset=n}available(){return this.buffer.length-this.offset}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=this.readSlice(8);return bt(t)}readVarInt(){const[t,n]=un(this.buffer,this.offset);return this.offset+=n,t}readSlice(t){if(this.buffer.length<this.offset+t)throw new Error("Cannot read slice out of bounds");const n=this.buffer.subarray(this.offset,this.offset+t);return this.offset+=t,n}readVarSlice(){const t=R(this.readVarInt());return this.readSlice(t)}readVector(){const t=this.readVarInt(),n=[];for(let r=0;r<t;r++)n.push(this.readVarSlice());return n}}var Ot=(e=>(e[e.NON_WITNESS_UTXO=0]="NON_WITNESS_UTXO",e[e.WITNESS_UTXO=1]="WITNESS_UTXO",e[e.PARTIAL_SIG=2]="PARTIAL_SIG",e[e.SIGHASH_TYPE=3]="SIGHASH_TYPE",e[e.REDEEM_SCRIPT=4]="REDEEM_SCRIPT",e[e.WITNESS_SCRIPT=5]="WITNESS_SCRIPT",e[e.BIP32_DERIVATION=6]="BIP32_DERIVATION",e[e.FINAL_SCRIPTSIG=7]="FINAL_SCRIPTSIG",e[e.FINAL_SCRIPTWITNESS=8]="FINAL_SCRIPTWITNESS",e[e.PREVIOUS_TXID=14]="PREVIOUS_TXID",e[e.OUTPUT_INDEX=15]="OUTPUT_INDEX",e[e.SEQUENCE=16]="SEQUENCE",e[e.TAP_KEY_SIG=19]="TAP_KEY_SIG",e[e.TAP_LEAF_SCRIPT=21]="TAP_LEAF_SCRIPT",e[e.TAP_BIP32_DERIVATION=22]="TAP_BIP32_DERIVATION",e[e.TAP_INTERNAL_KEY=23]="TAP_INTERNAL_KEY",e))(Ot||{});const ge=u.Buffer.from([112,115,98,116,255]),Ho=4294967295;class ln extends Error{}class fn{constructor(){p(this,"globalMap",new Map);p(this,"inputMaps",[]);p(this,"outputMaps",[])}setGlobalTxVersion(t){this.setGlobal(2,U(t))}getGlobalTxVersion(){return this.getGlobal(2).readUInt32LE(0)}setGlobalFallbackLocktime(t){this.setGlobal(3,U(t))}getGlobalFallbackLocktime(){var t;return(t=this.getGlobalOptional(3))==null?void 0:t.readUInt32LE(0)}setGlobalInputCount(t){this.setGlobal(4,Te(t))}getGlobalInputCount(){return Se(this.getGlobal(4))}setGlobalOutputCount(t){this.setGlobal(5,Te(t))}getGlobalOutputCount(){return Se(this.getGlobal(5))}setGlobalTxModifiable(t){this.setGlobal(6,t)}getGlobalTxModifiable(){return this.getGlobalOptional(6)}setGlobalPsbtVersion(t){this.setGlobal(251,U(t))}getGlobalPsbtVersion(){return this.getGlobal(251).readUInt32LE(0)}setInputNonWitnessUtxo(t,n){this.setInput(t,0,_(),n)}getInputNonWitnessUtxo(t){return this.getInputOptional(t,0,_())}setInputWitnessUtxo(t,n,r){const o=new B;o.writeSlice(we(n)),o.writeVarSlice(r),this.setInput(t,1,_(),o.buffer())}getInputWitnessUtxo(t){const n=this.getInputOptional(t,1,_());if(!n)return;const r=new H(n);return{amount:bt(r.readSlice(8)),scriptPubKey:r.readVarSlice()}}setInputPartialSig(t,n,r){this.setInput(t,2,n,r)}getInputPartialSig(t,n){return this.getInputOptional(t,2,n)}setInputSighashType(t,n){this.setInput(t,3,_(),U(n))}getInputSighashType(t){const n=this.getInputOptional(t,3,_());if(n)return n.readUInt32LE(0)}setInputRedeemScript(t,n){this.setInput(t,4,_(),n)}getInputRedeemScript(t){return this.getInputOptional(t,4,_())}setInputWitnessScript(t,n){this.setInput(t,5,_(),n)}getInputWitnessScript(t){return this.getInputOptional(t,5,_())}setInputBip32Derivation(t,n,r,o){if(n.length!==33)throw new Error("Invalid pubkey length: "+n.length);this.setInput(t,6,n,this.encodeBip32Derivation(r,o))}getInputBip32Derivation(t,n){const r=this.getInputOptional(t,6,n);if(r)return this.decodeBip32Derivation(r)}setInputFinalScriptsig(t,n){this.setInput(t,7,_(),n)}getInputFinalScriptsig(t){return this.getInputOptional(t,7,_())}setInputFinalScriptwitness(t,n){this.setInput(t,8,_(),n)}getInputFinalScriptwitness(t){return this.getInput(t,8,_())}setInputPreviousTxId(t,n){this.setInput(t,14,_(),n)}getInputPreviousTxid(t){return this.getInput(t,14,_())}setInputOutputIndex(t,n){this.setInput(t,15,_(),U(n))}getInputOutputIndex(t){return this.getInput(t,15,_()).readUInt32LE(0)}setInputSequence(t,n){this.setInput(t,16,_(),U(n))}getInputSequence(t){var n;return((n=this.getInputOptional(t,16,_()))==null?void 0:n.readUInt32LE(0))??Ho}setInputTapKeySig(t,n){this.setInput(t,19,_(),n)}getInputTapKeySig(t){return this.getInputOptional(t,19,_())}setInputTapBip32Derivation(t,n,r,o,s){if(n.length!==32)throw new Error("Invalid pubkey length: "+n.length);const i=this.encodeTapBip32Derivation(r,o,s);this.setInput(t,22,n,i)}getInputTapBip32Derivation(t,n){const r=this.getInput(t,22,n);return this.decodeTapBip32Derivation(r)}getInputKeyDatas(t,n){return this.getKeyDatas(this.inputMaps[t],n)}getInputEntriesOfType(t,n){const r=this.inputMaps[t];if(!r)throw new Error("No such map");const o=[];return r.forEach((s,i)=>{this.isKeyType(i,[n])&&o.push({keyData:u.Buffer.from(i.substring(2),"hex"),value:u.Buffer.from(s)})}),o}setOutputRedeemScript(t,n){this.setOutput(t,0,_(),n)}getOutputRedeemScript(t){return this.getOutput(t,0,_())}setOutputBip32Derivation(t,n,r,o){this.setOutput(t,2,n,this.encodeBip32Derivation(r,o))}getOutputBip32Derivation(t,n){const r=this.getOutput(t,2,n);return this.decodeBip32Derivation(r)}setOutputAmount(t,n){this.setOutput(t,3,_(),we(n))}getOutputAmount(t){const n=this.getOutput(t,3,_());return bt(n)}setOutputScript(t,n){this.setOutput(t,4,_(),n)}getOutputScript(t){return this.getOutput(t,4,_())}setOutputTapBip32Derivation(t,n,r,o,s){const i=this.encodeTapBip32Derivation(r,o,s);this.setOutput(t,7,n,i)}getOutputTapBip32Derivation(t,n){const r=this.getOutput(t,7,n);return this.decodeTapBip32Derivation(r)}deleteInputEntries(t,n){const r=this.inputMaps[t];if(!r)throw new Error("No such map");r.forEach((o,s,i)=>{this.isKeyType(s,n)&&i.delete(s)})}copy(t){this.copyMap(this.globalMap,t.globalMap),this.copyMaps(this.inputMaps,t.inputMaps),this.copyMaps(this.outputMaps,t.outputMaps)}copyMaps(t,n){t.forEach((r,o)=>{const s=new Map;this.copyMap(r,s),n[o]=s})}copyMap(t,n){t.forEach((r,o)=>n.set(o,u.Buffer.from(r)))}serialize(){const t=new B;return t.writeSlice(ge),St(t,this.globalMap),this.inputMaps.forEach(n=>{St(t,n)}),this.outputMaps.forEach(n=>{St(t,n)}),t.buffer()}deserialize(t){const n=new H(t);if(!n.readSlice(5).equals(ge))throw new Error("Invalid magic bytes");for(;this.readKeyPair(this.globalMap,n););let r;try{r=this.getGlobalPsbtVersion()}catch(i){if(!(i instanceof ln))throw i;r=0}if(r!==0&&r!==2)throw new Error("Only PSBTs of version 0 or 2 are supported");let o,s;if(r===0){const i=this.getGlobal(0),a=w.Transaction.fromBuffer(i);o=a.ins.length,s=a.outs.length}else o=this.getGlobalInputCount(),s=this.getGlobalOutputCount();for(let i=0;i<o;i++){const a=new Map;for(this.inputMaps[i]=a;this.readKeyPair(a,n););}for(let i=0;i<s;i++){const a=new Map;for(this.outputMaps[i]=a;this.readKeyPair(a,n););}if(n.available()!==0)throw new Error("Trailing bytes after PSBT output maps");this.normalizeToV2()}normalizeToV2(){var o;const t=(o=this.getGlobalOptional(251))==null?void 0:o.readUInt32LE(0);if(t===2)return;if(t!==void 0)throw new Error("Invalid or unsupported value for PSBT_GLOBAL_VERSION");const n=this.getGlobal(0),r=w.Transaction.fromBuffer(n);this.setGlobalPsbtVersion(2),this.setGlobalTxVersion(r.version),this.setGlobalFallbackLocktime(r.locktime),this.setGlobalInputCount(r.ins.length),this.setGlobalOutputCount(r.outs.length),r.ins.forEach((s,i)=>{this.setInputPreviousTxId(i,s.hash),this.setInputOutputIndex(i,s.index),this.setInputSequence(i,s.sequence)}),r.outs.forEach((s,i)=>{this.setOutputAmount(i,s.value),this.setOutputScript(i,s.script)}),this.globalMap.delete("0".padStart(2,"0"))}readKeyPair(t,n){const r=R(n.readVarInt());if(r===0)return!1;const o=n.readUInt8(),s=n.readSlice(r-1),i=n.readVarSlice(),a=new F(o,s).toString();if(t.has(a))throw new Error("Repeated keypair in PSBT map");return t.set(a,i),!0}getKeyDatas(t,n){if(!t)throw new Error("No such map");const r=[];return t.forEach((o,s)=>{this.isKeyType(s,[n])&&r.push(u.Buffer.from(s.substring(2),"hex"))}),r}isKeyType(t,n){const r=u.Buffer.from(t.substring(0,2),"hex").readUInt8(0);return n.some(o=>o===r)}setGlobal(t,n){const r=new F(t,u.Buffer.from([]));this.globalMap.set(r.toString(),n)}getGlobal(t){return Tt(this.globalMap,t,_())}getGlobalOptional(t){return Rt(this.globalMap,t,_())}setInput(t,n,r,o){_e(this.getMap(t,this.inputMaps),n,r,o)}getInput(t,n,r){return Tt(this.inputMaps[t],n,r)}getInputOptional(t,n,r){return Rt(this.inputMaps[t],n,r)}setOutput(t,n,r,o){_e(this.getMap(t,this.outputMaps),n,r,o)}getOutput(t,n,r){return Tt(this.outputMaps[t],n,r)}getMap(t,n){const r=n[t];if(r)return r;const o=new Map;return n[t]=o,o}encodeBip32Derivation(t,n){const r=new B;return this.writeBip32Derivation(r,t,n),r.buffer()}decodeBip32Derivation(t){const n=new H(t);return this.readBip32Derivation(n)}writeBip32Derivation(t,n,r){t.writeSlice(n),r.forEach(o=>{t.writeUInt32(o)})}readBip32Derivation(t){const n=t.readSlice(4),r=[];for(;t.offset<t.buffer.length;)r.push(t.readUInt32());return{masterFingerprint:n,path:r}}encodeTapBip32Derivation(t,n,r){const o=new B;return o.writeVarInt(t.length),t.forEach(s=>{o.writeSlice(s)}),this.writeBip32Derivation(o,n,r),o.buffer()}decodeTapBip32Derivation(t){const n=new H(t),r=R(n.readVarInt()),o=[];for(let i=0;i<r;i++)o.push(n.readSlice(32));const s=this.readBip32Derivation(n);return{hashes:o,...s}}}function Tt(e,t,n){const r=Rt(e,t,n);if(r===void 0)throw new ln(new F(t,n).toString());return r}function Rt(e,t,n){if(!e)throw new Error("No such map");const r=new F(t,n),o=e.get(r.toString());if(o!==void 0)return u.Buffer.from(o)}class F{constructor(t,n){p(this,"keyType");p(this,"keyData");this.keyType=t,this.keyData=n}toString(){const t=new B;return this.toBuffer(t),t.buffer().toString("hex")}serialize(t){t.writeVarInt(1+this.keyData.length),this.toBuffer(t)}toBuffer(t){t.writeUInt8(this.keyType),t.writeSlice(this.keyData)}}class Vo{constructor(t,n){p(this,"key");p(this,"value");this.key=t,this.value=n}serialize(t){this.key.serialize(t),t.writeVarSlice(this.value)}}function Fo(e){return new F(e.readUInt8(0),e.subarray(1))}function St(e,t){const n=[...t].sort(([r],[o])=>r<o?-1:r>o?1:0);for(const[r,o]of n)new Vo(Fo(u.Buffer.from(r,"hex")),o).serialize(e);e.writeUInt8(0)}function _(){return u.Buffer.from([])}function _e(e,t,n,r){const o=new F(t,n);e.set(o.toString(),r)}function U(e){const t=u.Buffer.alloc(4);return t.writeUInt32LE(e,0),t}function we(e){return cn(e)}function Te(e){const t=new B;return t.writeVarInt(e),t.buffer()}function Se(e){return R(new H(e).readVarInt())}const me=192,At=32,Ie=2,nt=33,rt=32,Go=1,Ko="TapBranch",Yo="TapTweak",Pe=64,ye=32,mt=64,Xo=34,lt=u.Buffer.from([81,32]),Wo=u.Buffer.from([0,20]),qo=2,zo=3;function dt(e){w.initEccLib(Pt);const t=w.payments.p2tr({internalPubkey:u.Buffer.from(e,"hex")}).output;if(!t)throw new d("p2tr produced no output script for the depositor key");return t}function be(e,t){const n=u.Buffer.concat([u.Buffer.from([t]),u.Buffer.from(e,"hex")]);return u.Buffer.concat([Wo,w.crypto.hash160(n)])}function hn(e){return e.length===Xo&&e.subarray(0,lt.length).equals(lt)}function jo(e,t,n,r){if(!hn(r))throw new d(`input ${e} is tapscript but its witnessUtxo script is not P2TR`);const o=t.length-nt;if(o<0||o%rt!==0)throw new d(`input ${e} control block length ${t.length} is not ${nt} plus a multiple of ${rt}`);const s=t.subarray(1,nt);if(!Pt.isXOnlyPoint(s))throw new d(`input ${e} control block internal key is not an x-only point`);let i=n;for(let h=nt;h<t.length;h+=rt){const E=t.subarray(h,h+rt),f=u.Buffer.compare(i,E)<0?[i,E]:[E,i];i=w.crypto.taggedHash(Ko,u.Buffer.concat(f))}const a=w.crypto.taggedHash(Yo,u.Buffer.concat([s,i])),c=Pt.xOnlyPointAddTweak(s,a);if(!c)throw new d(`input ${e} control block internal key has no taproot output key`);if(!r.subarray(lt.length).equals(u.Buffer.from(c.xOnlyPubkey)))throw new d(`input ${e} control block does not commit to its TAP_LEAF_SCRIPT (recomputed taproot output key differs from the witnessUtxo witness program)`);if(c.parity!==(t[0]&Go))throw new d(`input ${e} control block parity bit disagrees with the recomputed taproot output key`)}function Qo(e){const{psbt:t,depositorXOnlyHex:n,signInputIndexes:r}=e,o=new Map,s=new Map,i=t.getGlobalInputCount(),a=r===void 0?void 0:new Set(r),c=f=>a===void 0||a.has(f);if((a==null?void 0:a.size)===0)throw new d("signInputIndexes is empty — pass the indices to sign, or omit it to sign every device-signable input");for(const f of a??[])if(!Number.isInteger(f)||f<0||f>=i)throw new d(`input ${f} was requested for signing but this PSBT has ${i} input(s)`);const l=dt(n),h=[be(n,qo),be(n,zo)];for(let f=0;f<i;f++){const g=t.getInputEntriesOfType(f,Ot.TAP_LEAF_SCRIPT);if(g.length>0){if(g.length>1)throw new d(`input ${f} carries an ambiguous leaf set (${g.length} TAP_LEAF_SCRIPT entries)`);const T=g[0].value;if(T.length<Ie)throw new d(`input ${f} TAP_LEAF_SCRIPT value length ${T.length} is below the ${Ie}-byte minimum (script byte plus the leaf-version byte)`);const Y=T[T.length-1];if(Y!==me)throw new d(`input ${f} leaf version 0x${Y.toString(16)} is not tapscript (0xc0)`);const M=t.getInputWitnessUtxo(f);if(!M)throw new d(`input ${f} is tapscript but has no witnessUtxo`);const Z=T.subarray(0,T.length-1),qt=Bo(me,Z);jo(f,g[0].keyData,qt,M.scriptPubKey);const zt={kind:"tapscript",expectedLeafHashHexes:new Set([qt.toString("hex")]),expectedSignerXOnlyHex:n};s.set(f,zt),c(f)&&o.set(f,zt);continue}const b=t.getInputEntriesOfType(f,Ot.TAP_INTERNAL_KEY);if(b.length>0){const T=b[0];if(b.length>1||T.keyData.length!==0||T.value.length!==At)throw new d(`input ${f} carries a malformed TAP_INTERNAL_KEY entry`);if(T.value.toString("hex")!==n)throw new d(`input ${f} internal key is not the connected depositor key`);const Y=t.getInputWitnessUtxo(f);if(!Y)throw new d(`input ${f} is keypath but has no witnessUtxo`);const M=Y.scriptPubKey;if(!hn(M))throw new d(`input ${f} witnessUtxo script is not P2TR`);if(!M.equals(l))throw new d(`input ${f} witnessUtxo is not the BIP-86 P2TR of the depositor key`);const Z={kind:"taproot-keypath",expectedOutputKeyHex:M.subarray(lt.length).toString("hex")};s.set(f,Z),o.set(f,Z);continue}const Et=t.getInputWitnessUtxo(f);if(Et&&(Et.scriptPubKey.equals(l)||h.some(T=>Et.scriptPubKey.equals(T))))throw new d(`input ${f} spends a depositor-owned UTXO but carries no signing metadata`)}for(const f of a??[])if(!o.has(f))throw new d(`input ${f} was requested for signing but carries no signing metadata`);if(o.size===0)throw new d("PSBT contains no depositor-signable input");let E=0;for(const f of o.values())E+=f.kind==="tapscript"?f.expectedLeafHashHexes.size:1;return{byInput:o,classifiedByInput:s,expectedYieldCount:E}}function ot(e){return e.kind==="tapscript"?`${e.inputIndex}:${e.leafHashHex}`:`${e.inputIndex}`}function Oe(e,t){if(e<mt)throw new d(`YIELD payload truncated inside the signature (${e} of ${mt} bytes on input ${t})`);if(e!==mt)throw new P("non-default-sighash",t)}function Zo(e){const t=[],n=new Set;return{assertAndRecord:s=>{let i,a;try{const[h,E]=un(s,0);i=R(h),a=E}catch(h){throw new d(`unparseable YIELD payload: ${h instanceof Error?h.message:String(h)}`)}const c=s[a];if(c===void 0)throw new d("YIELD payload truncated before the augmented-pubkey length");const l=e.byInput.get(i);if(l===void 0)throw new P("unexpected-input",i);if(c===Pe){if(l.kind!=="tapscript")throw new P("wrong-spend-type",i);const h=a+1+Pe;if(s.length<h)throw new d("YIELD payload truncated inside the augmented pubkey");const E=s.subarray(a+1,a+1+At).toString("hex"),f=s.subarray(a+1+At,h).toString("hex"),g=s.subarray(h);if(E!==l.expectedSignerXOnlyHex)throw new P("wrong-signer-key",i);if(!l.expectedLeafHashHexes.has(f))throw new P("unknown-leaf-hash",i);Oe(g.length,i);const b={kind:"tapscript",inputIndex:i,signerXOnlyHex:E,leafHashHex:f,signature:Uint8Array.from(g)};if(n.has(ot(b)))throw new P("duplicate-yield",i);n.add(ot(b)),t.push(b);return}if(c===ye){if(l.kind!=="taproot-keypath")throw new P("wrong-spend-type",i);const h=a+1+ye;if(s.length<h)throw new d("YIELD payload truncated inside the augmented pubkey");const E=s.subarray(a+1,h).toString("hex"),f=s.subarray(h);if(E!==l.expectedOutputKeyHex)throw new P("wrong-signer-key",i);Oe(f.length,i);const g={kind:"taproot-keypath",inputIndex:i,outputKeyHex:E,signature:Uint8Array.from(f)};if(n.has(ot(g)))throw new P("duplicate-yield",i);n.add(ot(g)),t.push(g);return}throw new P("unexpected-encoding",i)},get yields(){return t},get lastYield(){return t[t.length-1]},assertComplete:()=>{const s=new Set;for(const[c,l]of e.byInput)if(l.kind==="tapscript")for(const h of l.expectedLeafHashHexes)s.add(`${c}:${h}`);else s.add(`${c}`);const i=[...s].filter(c=>!n.has(c)),a=[...n].some(c=>!s.has(c));if(i.length>0||a||n.size!==e.expectedYieldCount)throw new Qe(i)}}}const pn=/^[0-9a-f]{64}$/;function Jo(e,t){if(ht("depositorPath",e),e[Ln]!==Be)throw new Error("depositorPath must use BIP-86 receive branch 0");for(let n=0;n<Bt;n++)if(e[n]!==t[n])throw new Error(`depositorPath ${L(e)} is not under the wallet policy's key origin ${L(t)} — the device could never mark the input internal`)}function dn(e,t,n,r){if(!Number.isInteger(r)||r<0||r>=O)throw new Error("addressIndex must be a non-hardened integer in 0..2^31-1");const o=ft.HDKey.fromExtendedKey(e,t).deriveChild(n).deriveChild(r);if(!o.publicKey)throw new Error(`account xpub derived no public key at ${n}/${r}`);return u.Buffer.from(o.publicKey.subarray(1)).toString("hex")}function En(e,t,n){return dn(e,t,Le,n)}function ts(e,t,n){return dn(e,t,Be,n)}function gn(e,t){const n=dt(t);return e.txOutputs.flatMap((r,o)=>u.Buffer.from(r.script).equals(n)?[o]:[])}function es(e,t){if(!pn.test(t))throw new Error("changeXOnlyHex must be 64 lowercase hex characters");return gn(w.Psbt.fromHex(e),t).length>0}function ns(e){const{psbtHex:t,depositorXOnlyHex:n,walletPolicy:r,depositorPath:o,change:s}=e;if(!pn.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");Jo(o,r.keyOriginPath);const i=w.Psbt.fromHex(t),a=u.Buffer.from(r.masterFingerprintHex,"hex"),c=u.Buffer.from(n,"hex");let l=0;if(i.data.inputs.forEach((h,E)=>{h.tapInternalKey&&u.Buffer.from(h.tapInternalKey).equals(c)&&(l++,i.updateInput(E,{tapBip32Derivation:[{masterFingerprint:a,pubkey:c,path:L(o),leafHashes:[]}]}))}),l!==i.data.inputs.length)throw new Error(`${i.data.inputs.length-l} of ${i.data.inputs.length} inputs do not carry the depositor key as TAP_INTERNAL_KEY — every Pre-PegIn input must be internal`);if(s){const h=En(r.accountXpub,r.bip32Versions,s.addressIndex),E=[...o.slice(0,Bt),Le,s.addressIndex],f=u.Buffer.from(h,"hex"),g=gn(i,h);if(g.length===0)throw new Error("change script matches no output — the PSBT does not pay the wallet's change address");for(const b of g)i.updateOutput(b,{tapInternalKey:f,tapBip32Derivation:[{masterFingerprint:a,pubkey:f,path:L(E),leafHashes:[]}]})}return i.toHex()}const rs="BIP0322-signed-message",os=new Uint8Array([252,6,98,118,97,117,108,116,0]),_n=0,wn=0,Tn=0,ss=0,xt=0,is=u.Buffer.from([106]),as=/^[0-9a-f]{64}$/,us=/^[0-9a-f]{8}$/,cs=u.Buffer.alloc(32,0),ls=4294967295,fs=u.Buffer.from([0,32]),hs=u.Buffer.from([81,32]),ps=2;function ds(e,t){const n=w.crypto.sha256(u.Buffer.from(e,"utf8"));return w.crypto.sha256(u.Buffer.concat([n,n,u.Buffer.from(t)]))}function Es(e,t){const n=new w.Transaction;n.version=_n,n.locktime=wn;const r=u.Buffer.concat([fs,ds(rs,e)]);return n.addInput(cs,ls,Tn,r),n.addOutput(u.Buffer.concat([hs,u.Buffer.from(t)]),xt),Uint8Array.from(n.getHash(!1))}function gs(e){const{message:t,depositorXOnlyHex:n,masterFingerprintHex:r,depositorPath:o}=e;if(!as.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");if(!us.test(r))throw new Error("masterFingerprintHex must be 8 lowercase hex characters");ht("depositorPath",o);const s=new TextEncoder().encode(t),i=u.Buffer.from(n,"hex"),a=dt(n),c=Es(s,a.subarray(ps)),l=new w.Psbt;return l.setVersion(_n),l.setLocktime(wn),l.addInput({hash:u.Buffer.from(c),index:ss,sequence:Tn,witnessUtxo:{script:a,value:xt},tapInternalKey:i,tapBip32Derivation:[{masterFingerprint:u.Buffer.from(r,"hex"),pubkey:i,path:L(o),leafHashes:[]}]}),l.addOutput({script:is,value:xt}),l.addUnknownKeyValToGlobal({key:u.Buffer.from(os),value:u.Buffer.from(s)}),l.toHex()}const _s=/^[0-9a-f]{64}$/,ws=/^[0-9a-f]{8}$/,Ts=192,vt=32,Ss=0,ms=1,Is=32,Ps=75,ys=76,bs=79,Os=80,Rs=81,As=96,xs=173,vs=178,Re=4,Ae=128,Cs=1+vt+1+1+1,Bs=2,Ls=34,Ns=2147483648,Ms=4194304,Us=65535,Ds=2,$s=0,ks=0;function Hs(e){if(e.length<Cs)return;let t=0;if(e[t++]!==Is)return;const n=u.Buffer.from(e.subarray(t,t+vt)).toString("hex");if(t+=vt,e[t++]!==xs||t>=e.length)return;const r=e[t++];let o=0;if(!(r===Ss||r===bs)){if(r>=ms&&r<=Ps){const s=r;if(s>Re||t+s>e.length||(e[t+s-1]&Ae)!==0)return;for(let i=0;i<s;i++)o|=e[t+i]<<8*i;t+=s}else if(r===ys){if(t>=e.length)return;const s=e[t++];if(s>Re||t+s>e.length||(e[t+s-1]&Ae)!==0)return;for(let i=0;i<s;i++)o|=e[t+i]<<8*i;t+=s}else if(r>=Rs&&r<=As)o=r-Os;else return;if(!(o===0||o>Us)&&!(t>=e.length)&&e[t++]===vs&&t===e.length)return{leafKeyHex:n,csv:o}}}function Sn(e){let t;try{t=w.Psbt.fromHex(e)}catch{return}if(t.version<Ds||t.locktime!==$s||t.data.inputs.length!==1||t.data.outputs.length!==1)return;const n=t.data.inputs[0],r=n.tapLeafScript??[];if(r.length!==1||r[0].leafVersion!==Ts)return;const o=Hs(r[0].script);if(o!==void 0)return{...o,inputTxidInternalHex:u.Buffer.from(t.txInputs[0].hash).toString("hex"),sequence:t.txInputs[0].sequence??0,sighashType:n.sighashType,witnessUtxo:n.witnessUtxo?{scriptLength:n.witnessUtxo.script.length,value:n.witnessUtxo.value}:void 0,outputScriptHex:u.Buffer.from(t.txOutputs[0].script).toString("hex"),outputValue:t.txOutputs[0].value}}function mn(e){if(e.sighashType!==void 0&&e.sighashType!==ks)throw new Error(`refund input sighash type ${e.sighashType} must be absent or SIGHASH_DEFAULT — the device rejects any other value`);if(e.witnessUtxo===void 0||e.witnessUtxo.scriptLength!==Ls)throw new Error("refund input must carry a P2TR witnessUtxo — the device rejects a missing or non-34-byte scriptPubKey");if(e.outputValue>e.witnessUtxo.value)throw new Error(`refund output value ${e.outputValue} exceeds the HTLC value ${e.witnessUtxo.value} — the device rejects it`);if(e.outputScriptHex!==dt(e.leafKeyHex).toString("hex"))throw new Error("refund output does not pay the refund leaf key's own BIP-86 address");if(e.csv<ct)throw new Error(`refund leaf CSV ${e.csv} is below the device's timelock floor of ${ct} blocks`);if((e.sequence&Ns)!==0||(e.sequence&Ms)!==0)throw new Error("refund input sequence must be a plain block-count relative timelock (BIP-68 disable/time flags clear)");if(e.sequence!==e.csv)throw new Error(`refund input sequence ${e.sequence} must equal the leaf CSV ${e.csv} — the device compares them unmasked and rejects a mismatch`)}function Vs(e){const{psbtHex:t,depositorXOnlyHex:n,masterFingerprintHex:r,depositorPath:o}=e;if(!_s.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");if(!ws.test(r))throw new Error("masterFingerprintHex must be 8 lowercase hex characters (the 4-byte master fingerprint)");ht("depositorPath",o);const s=Sn(t);if(s===void 0)throw new Error("not a refund-shaped PSBT (expected 1 input, 1 output, and one refund tapscript leaf)");if(mn(s),s.leafKeyHex!==n)throw new Error("refund leaf key does not equal the depositor key — this device cannot sign this refund");const i=w.Psbt.fromHex(t),a=u.Buffer.from(i.txOutputs[0].script),c=u.Buffer.from(r,"hex"),l=L(o);return i.updateInput(0,{tapBip32Derivation:[{masterFingerprint:c,pubkey:u.Buffer.from(n,"hex"),path:l,leafHashes:[]}]}),i.updateOutput(0,{tapBip32Derivation:[{masterFingerprint:c,pubkey:a.subarray(Bs),path:l,leafHashes:[]}]}),i.toHex()}class G{constructor(t,n=w.crypto.sha256){p(this,"leaves");p(this,"rootNode");p(this,"leafNodes");p(this,"h");this.leaves=t,this.h=n;const r=this.calculateRoot(t);this.rootNode=r.root,this.leafNodes=r.leaves}getRoot(){return this.rootNode.hash}size(){return this.leaves.length}getLeaves(){return this.leaves}getLeafHash(t){const n=this.leafNodes[t];if(n===void 0)throw Error("Index out of bounds");return n.hash}getProof(t){const n=this.leafNodes[t];if(n===void 0)throw Error("Index out of bounds");return Ct(n)}calculateRoot(t){const n=t.length;if(n==0)return{root:new It(void 0,void 0,u.Buffer.alloc(32,0)),leaves:[]};if(n==1){const h=new It(void 0,void 0,t[0]);return{root:h,leaves:[h]}}const r=Gs(n),o=this.calculateRoot(t.slice(0,r)),s=this.calculateRoot(t.slice(r)),i=o.root,a=s.root,c=this.hashNode(i.hash,a.hash),l=new It(i,a,c);return i.parent=l,a.parent=l,{root:l,leaves:o.leaves.concat(s.leaves)}}hashNode(t,n){return this.h(u.Buffer.concat([u.Buffer.from([1]),t,n]))}}function K(e,t=w.crypto.sha256){return Fs(u.Buffer.from([0]),e,t)}function Fs(e,t,n){return n(u.Buffer.concat([e,t]))}class It{constructor(t,n,r){p(this,"leftChild");p(this,"rightChild");p(this,"parent");p(this,"hash");this.leftChild=t,this.rightChild=n,this.hash=r}isLeaf(){return this.leftChild==null}}function Ct(e){if(!e.parent)return[];if(e.parent.leftChild==e){if(!e.parent.rightChild)throw new Error("Expected right child to exist");return[e.parent.rightChild.hash,...Ct(e.parent)]}else{if(!e.parent.leftChild)throw new Error("Expected left child to exist");return[e.parent.leftChild.hash,...Ct(e.parent)]}}function Gs(e){if(e<2)throw Error("Expected n >= 2");return Ks(e)?e/2:1<<Math.floor(Math.log2(e))}function Ks(e){return(e&e-1)==0}const Wt=255,Ys=2,I=32;class Q{}class Xs extends Q{constructor(n,r,o){super();p(this,"results");p(this,"code",16);this.progressCallback=r,this.onYield=o,this.results=n}execute(n){const r=u.Buffer.from(n.subarray(1));return this.onYield&&this.onYield(u.Buffer.from(r)),this.results.push(r),this.progressCallback&&this.progressCallback(),u.Buffer.from("")}}class Ws extends Q{constructor(n,r){super();p(this,"knownPreimages");p(this,"queue");p(this,"code",64);this.knownPreimages=n,this.queue=r}execute(n){const r=u.Buffer.from(n.subarray(1));if(r.length!==1+I)throw new Error("Invalid request, unexpected trailing data");if(r[0]!==0)throw new Error("Unsupported request, the first byte should be 0");const s=u.Buffer.from(r.subarray(1,1+I)).toString("hex"),i=this.knownPreimages.get(s);if(i!==void 0){const a=V(i.length),c=Wt-a.length-1,l=Math.min(c,i.length);if(l<i.length)for(let h=l;h<i.length;h++)this.queue.push(u.Buffer.from(i.subarray(h,h+1)));return u.Buffer.concat([a,u.Buffer.from([l]),u.Buffer.from(i.subarray(0,l))])}throw new Error(`Requested unknown preimage for: ${s}`)}}class qs extends Q{constructor(n,r){super();p(this,"knownTrees");p(this,"queue");p(this,"code",65);this.knownTrees=n,this.queue=r}execute(n){const r=u.Buffer.from(n.subarray(1));if(r.length<I+1+1)throw new Error("Invalid request, expected at least 34 bytes");const o=new H(r),i=o.readSlice(I).toString("hex");let a,c;try{a=R(o.readVarInt()),c=R(o.readVarInt())}catch{throw new Error("Invalid request, couldn't parse tree_size or leaf_index")}const l=this.knownTrees.get(i);if(!l)throw new Error(`Requested Merkle leaf proof for unknown tree: ${i}`);if(c>=a||l.size()!==a)throw new Error("Invalid index or tree size.");if(this.queue.length!==0)throw new Error("This command should not execute when the queue is not empty.");const h=l.getProof(c),E=Math.min(Math.floor((Wt-I-1-1)/I),h.length),f=h.length-E;return f>0&&this.queue.push(...h.slice(-f)),u.Buffer.concat([l.getLeafHash(c),u.Buffer.from([h.length]),u.Buffer.from([E]),...h.slice(0,E)])}}class zs extends Q{constructor(n){super();p(this,"knownTrees");p(this,"code",66);this.knownTrees=n}execute(n){const r=u.Buffer.from(n.subarray(1));if(r.length!==I+I)throw new Error("Invalid request, unexpected trailing data");const s=u.Buffer.from(r.subarray(0,I)).toString("hex"),a=u.Buffer.from(r.subarray(I,I+I)).toString("hex"),c=this.knownTrees.get(s);if(!c)throw new Error(`Requested Merkle leaf index for unknown root: ${s}`);let l=0,h=0;for(let E=0;E<c.size();E++)if(c.getLeafHash(E).toString("hex")===a){h=1,l=E;break}return u.Buffer.concat([u.Buffer.from([h]),V(l)])}}class js extends Q{constructor(n){super();p(this,"queue");p(this,"code",160);this.queue=n}execute(n){if(n.length!==1)throw new Error("Invalid request, unexpected trailing data");const r=this.queue[0];if(r===void 0)throw new Error("No elements to get");const o=r.length;if(this.queue.some(c=>c.length!==o))throw new Error("The queue contains elements with different byte length, which is not expected");const s=Math.floor((Wt-Ys)/o),i=Math.min(s,this.queue.length),a=this.queue.splice(0,i);return u.Buffer.concat([u.Buffer.from([i]),u.Buffer.from([o]),...a])}}class Qs{constructor(t,n){p(this,"roots",new Map);p(this,"preimages",new Map);p(this,"yielded",[]);p(this,"queue",[]);p(this,"commands",new Map);const r=[new Xs(this.yielded,t,n),new Ws(this.preimages,this.queue),new zs(this.roots),new qs(this.roots,this.queue),new js(this.queue)];for(const o of r){if(this.commands.has(o.code))throw new Error(`Multiple commands with code ${o.code}`);this.commands.set(o.code,o)}}getYielded(){return this.yielded}addKnownPreimage(t){this.preimages.set(w.crypto.sha256(t).toString("hex"),t)}addKnownList(t){for(const r of t){const o=u.Buffer.concat([u.Buffer.from([0]),r]);this.addKnownPreimage(o)}const n=new G(t.map(r=>K(r)));this.roots.set(n.getRoot().toString("hex"),n)}addKnownMapping(t){this.addKnownList(t.keys),this.addKnownList(t.values)}addKnownWalletPolicy(t){this.addKnownPreimage(t.serialize()),this.addKnownList(t.keys.map(n=>u.Buffer.from(n,"ascii"))),this.addKnownPreimage(u.Buffer.from(t.descriptorTemplate))}execute(t){if(t.length===0)throw new Error("Unexpected empty command");const n=t[0],r=this.commands.get(n);if(!r)throw new Error(`Unexpected command code ${n}`);return r.execute(t)}}class Zs{constructor(t,n){p(this,"keys");p(this,"keysTree");p(this,"values");p(this,"valuesTree");if(t.length!=n.length)throw new Error("keys and values should have the same length");for(let r=0;r<t.length-1;r++)if(t[r].toString("hex")>=t[r+1].toString("hex"))throw new Error("keys must be in strictly increasing order");this.keys=t,this.keysTree=new G(t.map(r=>K(r))),this.values=n,this.valuesTree=new G(n.map(r=>K(r)))}commitment(){return u.Buffer.concat([V(this.keys.length),this.keysTree.getRoot(),this.valuesTree.getRoot()])}}class z extends fn{constructor(n){super();p(this,"globalMerkleMap");p(this,"inputMerkleMaps",[]);p(this,"outputMerkleMaps",[]);p(this,"inputMapCommitments");p(this,"outputMapCommitments");n.copy(this),this.globalMerkleMap=z.createMerkleMap(this.globalMap);const r=this.getGlobalInputCount();if(this.inputMaps.length!==r)throw new Error(`Input map count ${this.inputMaps.length} != declared PSBT_GLOBAL_INPUT_COUNT ${r}`);for(let s=0;s<r;s++){const i=this.inputMaps[s];if(i===void 0)throw new Error(`Missing input map ${s}`);this.inputMerkleMaps.push(z.createMerkleMap(i))}this.inputMapCommitments=this.inputMerkleMaps.map(s=>s.commitment());const o=this.getGlobalOutputCount();if(this.outputMaps.length!==o)throw new Error(`Output map count ${this.outputMaps.length} != declared PSBT_GLOBAL_OUTPUT_COUNT ${o}`);for(let s=0;s<o;s++){const i=this.outputMaps[s];if(i===void 0)throw new Error(`Missing output map ${s}`);this.outputMerkleMaps.push(z.createMerkleMap(i))}this.outputMapCommitments=this.outputMerkleMaps.map(s=>s.commitment())}getGlobalSize(){return this.globalMap.size}getGlobalKeysValuesRoot(){return this.globalMerkleMap.commitment()}static createMerkleMap(n){const r=[...n.keys()].sort(),o=r.map(i=>{const a=n.get(i);if(!a)throw new Error("No value for key "+i);return a}),s=r.map(i=>u.Buffer.from(i,"hex"));return new Zs(s,o)}}const Js=2;class ti{constructor(t,n,r){p(this,"name");p(this,"descriptorTemplate");p(this,"keys");this.name=t,this.descriptorTemplate=n,this.keys=r}getId(){return w.crypto.sha256(this.serialize())}serialize(){const t=this.keys.map(o=>u.Buffer.from(o,"ascii")),n=new G(t.map(o=>K(o))),r=new B;return r.writeUInt8(Js),r.writeVarSlice(u.Buffer.from(this.name,"ascii")),r.writeVarInt(this.descriptorTemplate.length),r.writeSlice(w.crypto.sha256(u.Buffer.from(this.descriptorTemplate))),r.writeVarInt(this.keys.length),r.writeSlice(n.getRoot()),r.buffer()}}class In extends ti{constructor(t,n){super("",t,[n])}}const ei=4,ni=0,ri=1,Pn=32,oi=new Uint8Array(Pn),si=new Uint8Array(Pn),ii=/^[0-9a-f]{64}$/,ai=/^(?:[0-9a-fA-F]{2})+$/;function ui(e,t){const n=new G(e.inputMapCommitments.map(o=>K(o))).getRoot(),r=new G(e.outputMapCommitments.map(o=>K(o))).getRoot();return Uint8Array.from(u.Buffer.concat([e.getGlobalKeysValuesRoot(),V(e.getGlobalInputCount()),n,V(e.getGlobalOutputCount()),r,u.Buffer.from(t),u.Buffer.from(si)]))}function ci(e){return{cla:A,ins:ei,p1:ni,p2:ri,data:e}}const li=0;function fi(e,t){for(const[n]of t.byInput){const r=e.data.inputs[n].sighashType;if(r!==void 0&&r!==li)throw new d(`input ${n} requests sighash type ${r}, but vault flows sign SIGHASH_DEFAULT only`)}}function hi(e,t){var n;for(const[r,o]of t.byInput){const s=e.data.inputs[r];if(s.finalScriptWitness||s.finalScriptSig)throw new d(`input ${r} is already finalized and this round signs it — pass an unsigned PSBT`);if(o.kind==="tapscript"){if((n=s.tapScriptSig)==null?void 0:n.some(a=>a.pubkey.toString("hex")===o.expectedSignerXOnlyHex&&o.expectedLeafHashHexes.has(a.leafHash.toString("hex"))))throw new d(`input ${r} already carries a tapScriptSig for a (key, leaf) we sign — pass an unsigned PSBT`);continue}if(s.tapKeySig)throw new d(`input ${r} already carries a tapKeySig and this round signs its keypath — pass an unsigned PSBT`)}}const yn=new WeakMap;function pi(e,t){const n={...e};return yn.set(n,t),n}function bn(e){const t=yn.get(e);if(!t)throw new d("unrecognised prepared signing state — use prepareSignPsbt's return value");return t}function On(e){const{psbtHex:t,depositorXOnlyHex:n,signInputIndexes:r,walletPolicy:o}=e;if(!ii.test(n))throw new d("depositorXOnlyHex must be 64 lowercase hex characters");let s;if(o!==void 0&&(s=new In(o.descriptorTemplate,o.keyInfo),s.getId().toString("hex")!==o.walletIdHex))throw new d("walletPolicy.walletIdHex does not match sha256 of the serialized policy");if(!ai.test(t))throw new d("psbtHex is not even-length hexadecimal");let i;try{i=w.Psbt.fromHex(t)}catch(g){throw new d(`PSBT rejected at parse (merge target): ${g instanceof Error?g.message:String(g)}`)}const a=new fn;try{a.deserialize(u.Buffer.from(t,"hex"))}catch(g){throw new d(`PSBT rejected at parse: ${g instanceof Error?g.message:String(g)}`)}let c,l;try{c=new z(a),l=Qo({psbt:c,depositorXOnlyHex:n,signInputIndexes:r})}catch(g){throw g instanceof d?g:new d(`PSBT rejected at preflight: ${g instanceof Error?g.message:String(g)}`)}hi(i,l),fi(i,l);const h=Zo(l),E=new Qs(void 0,g=>h.assertAndRecord(g));E.addKnownMapping(c.globalMerkleMap);for(const g of c.inputMerkleMaps)E.addKnownMapping(g);for(const g of c.outputMerkleMaps)E.addKnownMapping(g);E.addKnownList(c.inputMapCommitments),E.addKnownList(c.outputMapCommitments);const f=o?u.Buffer.from(o.walletIdHex,"hex"):oi;return s&&E.addKnownWalletPolicy(s),pi({table:l,unsignedTxid:w.Transaction.fromBuffer(i.data.globalMap.unsignedTx.toBuffer()).getId()},{cdata:ui(c,f),interpreter:E,collector:h,originalPsbtHex:t,signsUnderWalletPolicy:o!==void 0})}const di=248,Ei=1,gi=0,_i=0,wi=36864,Ti=57344;async function Si(e,t,n){const{collector:r,interpreter:o,cdata:s}=bn(t),{table:i}=t;if(n.signal.aborted)throw new yt(r.yields.length);const a=ci(s);let c=a,l=await e(a),h=0;for(;l.sw===Ti;){let E;try{E=o.execute(u.Buffer.from(l.data))}catch(f){throw Ze(f)?f:Je(f)?new d(f.detail,st(r.yields)):new d(`client command failed: ${f instanceof Error?f.message:String(f)}`,st(r.yields))}if(r.yields.length>h){h=r.yields.length;const f=r.lastYield;if(f!==void 0&&n.onProgress!==void 0)try{n.onProgress({inputIndex:f.inputIndex,yieldedCount:h,expectedYieldCount:i.expectedYieldCount})}catch{}}if(n.signal.aborted)throw new yt(r.yields.length);c={cla:di,ins:Ei,p1:gi,p2:_i,data:E},l=await e(c)}if(l.sw!==wi){const E=rn(l.sw,{...n.appIdentity,ins:c.ins,p1:c.p1,preDispatch:c===a});throw E===void 0?new d(`status word 0x${l.sw.toString(16)} escaped classification`,st(r.yields)):E}return r.assertComplete(),r.yields}function mi(e,t){const n=w.Psbt.fromHex(e);for(const r of t)r.kind==="tapscript"?n.updateInput(r.inputIndex,{tapScriptSig:[{pubkey:u.Buffer.from(r.signerXOnlyHex,"hex"),leafHash:u.Buffer.from(r.leafHashHex,"hex"),signature:u.Buffer.from(r.signature)}]}):n.updateInput(r.inputIndex,{tapKeySig:u.Buffer.from(r.signature)});return n.toHex()}const xe=new WeakSet;async function Rn(e,t,n){const{originalPsbtHex:r,signsUnderWalletPolicy:o}=bn(t);if(xe.has(t))throw new d("prepared signing state was already used — call prepareSignPsbt again for a retry");if([...t.table.byInput.values()].some(c=>c.kind==="taproot-keypath")&&!o)throw new d("PSBT signs a key-path input but was prepared without a walletPolicy — the device would answer SW_OK with no signature");xe.add(t);const i=await Si(e,t,n);let a;try{a=mi(r,i)}catch(c){throw new d(`merge failed after signing: ${c instanceof Error?c.message:String(c)}`,st(i))}return{signedPsbtHex:a,yields:[...i]}}async function Ii(e,t){const{psbtHex:n,depositorXOnlyHex:r,signInputIndexes:o,...s}=t,i=On({psbtHex:n,depositorXOnlyHex:r,signInputIndexes:o});return Rn(e,i,s)}const ve="tr(@0/**)",Ce=2147483647,Pi=/^[0-9a-f]{8}$/;function yi(e){const{masterFingerprintHex:t,coinType:n,accountIndex:r,accountXpub:o,bip32Versions:s}=e;if(!Pi.test(t))throw new Error("masterFingerprintHex must be 8 lowercase hex characters");if(!Number.isInteger(n)||n<0||n>Ce||!Number.isInteger(r)||r<0||r>Ce)throw new Error("coinType and accountIndex must be non-negative integers in 0..0x7fffffff");try{ft.HDKey.fromExtendedKey(o,s)}catch(c){throw new Error(`accountXpub is not a valid extended key for this network: ${c instanceof Error?c.message:String(c)}`)}const i=`[${t}/${it}'/${n}'/${r}']${o}`,a=new In(ve,i).getId().toString("hex");return{descriptorTemplate:ve,keyInfo:i,walletIdHex:a,accountXpub:o,bip32Versions:s,keyOriginPath:[(O|it)>>>0,(O|n)>>>0,(O|r)>>>0],masterFingerprintHex:t}}exports.closeDmk=j.closeDmk;exports.connectDmkSession=j.connectDmkSession;exports.disconnectDmkSession=j.disconnectDmkSession;exports.isSessionAlive=j.isSessionAlive;exports.refreshSessionApp=j.refreshSessionApp;exports.DEPOSIT_TERMS_REJECTED_ERROR_NAME=an;exports.DepositTermsRejectedError=m;exports.LEDGER_DEVICE_ERROR_NAME=Ht;exports.LEDGER_DEVICE_LOCKED_ERROR_NAME=kt;exports.LEDGER_SIGN_PSBT_ABORTED_ERROR_NAME=Kt;exports.LEDGER_SIGN_PSBT_INCOMPLETE_ERROR_NAME=Ft;exports.LEDGER_SIGN_PSBT_PROTOCOL_ERROR_NAME=Gt;exports.LEDGER_USER_REFUSED_ERROR_NAME=$t;exports.LEDGER_YIELD_MISMATCH_ERROR_NAME=Vt;exports.LedgerDeviceError=je;exports.LedgerDeviceLockedError=ze;exports.LedgerSignPsbtAbortedError=yt;exports.LedgerSignPsbtIncompleteError=Qe;exports.LedgerSignPsbtProtocolError=d;exports.LedgerUserRefusedError=qe;exports.LedgerYieldMismatchError=P;exports.SW_BAD_STATE=tn;exports.SW_CAP_EXCEEDED=en;exports.SW_CLA_NOT_SUPPORTED=Yt;exports.SW_INS_NOT_SUPPORTED=Xt;exports.approveVaultIntent=zr;exports.assertDepositTermsDeviceCompatible=bo;exports.assertRefundPsbtSignable=mn;exports.augmentPsbtForDelegatedClaim=Er;exports.augmentPsbtForRefund=Vs;exports.augmentPsbtForWalletPolicy=ns;exports.buildDefaultTaprootPolicy=yi;exports.buildPopPsbtHex=gs;exports.classifyDelegatedClaimPsbt=ke;exports.classifyRefundPsbt=Sn;exports.createDmkApduSender=go;exports.createDmkRawApduSender=on;exports.deriveChangeXOnlyHex=En;exports.deriveContextHash=qr;exports.deriveReceiveXOnlyHex=ts;exports.encodeIntentGroup=Ve;exports.encodeIntentScalars=He;exports.encodeKeyBatches=Fe;exports.getExtendedPublicKey=Ye;exports.getMasterFingerprintHex=to;exports.getXOnlyPublicKeyHex=eo;exports.isLedgerDeviceError=oo;exports.isLedgerDeviceLockedError=so;exports.isLedgerSignPsbtAbortedError=ao;exports.isLedgerSignPsbtIncompleteError=io;exports.isLedgerSignPsbtProtocolError=Je;exports.isLedgerUserRefusedError=ro;exports.isLedgerYieldMismatchError=Ze;exports.prepareSignPsbt=On;exports.psbtPaysChangeScript=es;exports.signPreparedVaultPsbt=Rn;exports.signVaultPsbt=Ii;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|