@babylonlabs-io/ledger-vault-signer 0.6.3 → 0.7.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.
@@ -1,4 +1,4 @@
1
- import { DeviceManagementKit, DeviceSessionId } from '@ledgerhq/device-management-kit';
1
+ import { DeviceManagementKit, DeviceSessionId, TransportFactory, TransportIdentifier } from '@ledgerhq/device-management-kit';
2
2
  export interface DmkSessionHandle {
3
3
  readonly dmk: DeviceManagementKit;
4
4
  readonly sessionId: DeviceSessionId;
@@ -9,6 +9,32 @@ export interface DmkSessionHandle {
9
9
  readonly appName?: string;
10
10
  readonly appVersion?: string;
11
11
  }
12
+ /** Transport pair injected in place of the web-hid default. Test/E2E only. */
13
+ export interface DmkTransportOverride {
14
+ readonly transportFactory: TransportFactory;
15
+ /** Must match what the factory's transport reports via `getIdentifier()`. */
16
+ readonly transportIdentifier: TransportIdentifier;
17
+ }
18
+ /**
19
+ * TEST/E2E SEAM — replace the web-hid transport before the DMK is built. For
20
+ * Speculos, pass `speculosTransportFactory(url)` + `speculosIdentifier` from
21
+ * `@ledgerhq/device-transport-kit-speculos` (LedgerHQ/device-sdk-ts, tag
22
+ * `@ledgerhq/device-transport-kit-speculos@1.2.1`, api/SpeculosTransport.ts).
23
+ * The injector passes the factory in; this module never imports that package,
24
+ * so production bundles stay speculos-free.
25
+ *
26
+ * Package-internal for now: deliberately NOT re-exported from `index.ts`, so
27
+ * the only callers are this package's own tests. The env-gated dApp seam that
28
+ * needs it publicly is a separate task and re-exports it with its consumer.
29
+ *
30
+ * The override persists across {@link closeDmk}; pass `undefined` to restore
31
+ * the web-hid default.
32
+ *
33
+ * @throws while a DMK singleton exists (built or building): each build captures
34
+ * the factory it was given, so a late swap would leave discovery pointed at a
35
+ * transport that DMK does not hold. Call {@link closeDmk} first.
36
+ */
37
+ export declare function setDmkTransportOverride(override: DmkTransportOverride | undefined): void;
12
38
  /**
13
39
  * Discover and connect to a device, returning a handle for further commands.
14
40
  *
@@ -1 +1 @@
1
- {"version":3,"file":"dmkSession.d.ts","sourceRoot":"","sources":["../src/dmkSession.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,eAAe,EAAoB,MAAM,iCAAiC,CAAC;AAU9G,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,GAAG,EAAE,mBAAmB,CAAC;IAClC,QAAQ,CAAC,SAAS,EAAE,eAAe,CAAC;IACpC;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;CAC9B;AAwCD;;;;;;;GAOG;AACH,wBAAsB,iBAAiB,IAAI,OAAO,CAAC,gBAAgB,CAAC,CAkBnE;AAuBD;;;;;GAKG;AACH,wBAAsB,cAAc,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAC,CAU/E;AAED,sEAAsE;AACtE,wBAAsB,oBAAoB,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAMlF;AAED;;;GAGG;AACH,wBAAgB,QAAQ,IAAI,IAAI,CAI/B"}
1
+ {"version":3,"file":"dmkSession.d.ts","sourceRoot":"","sources":["../src/dmkSession.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EACV,mBAAmB,EACnB,eAAe,EAEf,gBAAgB,EAChB,mBAAmB,EACpB,MAAM,iCAAiC,CAAC;AAUzC,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,GAAG,EAAE,mBAAmB,CAAC;IAClC,QAAQ,CAAC,SAAS,EAAE,eAAe,CAAC;IACpC;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;CAC9B;AAgBD,8EAA8E;AAC9E,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,gBAAgB,EAAE,gBAAgB,CAAC;IAC5C,6EAA6E;IAC7E,QAAQ,CAAC,mBAAmB,EAAE,mBAAmB,CAAC;CACnD;AAID;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,oBAAoB,GAAG,SAAS,GAAG,IAAI,CAKxF;AAiED;;;;;;;GAOG;AACH,wBAAsB,iBAAiB,IAAI,OAAO,CAAC,gBAAgB,CAAC,CAkBnE;AAuBD;;;;;GAKG;AACH,wBAAsB,cAAc,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAC,CAU/E;AAED,sEAAsE;AACtE,wBAAsB,oBAAoB,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAMlF;AAED;;;GAGG;AACH,wBAAgB,QAAQ,IAAI,IAAI,CAI/B"}
@@ -14,6 +14,13 @@ export type InputSigExpectation = {
14
14
  export interface ExpectedSignatureTable {
15
15
  /** inputIndex → expectation. Inputs absent here must never appear in a YIELD. */
16
16
  readonly byInput: ReadonlyMap<number, InputSigExpectation>;
17
+ /**
18
+ * The same classification BEFORE `signInputIndexes` narrowing — what the PSBT
19
+ * *is*, independent of what the caller asked to sign. Flow identity reads this
20
+ * (mixed-input gate, replay fingerprint) so a caller cannot reshape either by
21
+ * varying its options; expectations read {@link byInput}.
22
+ */
23
+ readonly classifiedByInput: ReadonlyMap<number, InputSigExpectation>;
17
24
  /** Σ over inputs: tapscript → |expectedLeafHashHexes|; keypath → 1. */
18
25
  readonly expectedYieldCount: number;
19
26
  }
@@ -56,9 +63,10 @@ export interface BuildExpectedSignatureTableParams {
56
63
  readonly depositorXOnlyHex: string;
57
64
  /**
58
65
  * Input indices the caller asked to sign. Narrows TAPSCRIPT expectations
59
- * only, and is inert for key-path/policy signing there the base app picks
60
- * the set. Structural gates still run on EVERY input. Omit to expect every
61
- * device-signable input (the pre-#2281 behaviour).
66
+ * only: key-path expectations are never narrowed, because under a policy the
67
+ * base app picks the set. Every gate in this file still runs on EVERY input,
68
+ * and the indices themselves are range-checked. Omit to expect every
69
+ * device-signable input (the pre-#2281 behaviour); an empty array is rejected.
62
70
  */
63
71
  readonly signInputIndexes?: readonly number[];
64
72
  }
@@ -75,9 +83,16 @@ export declare function bip86OutputScript(xOnlyKeyHex: string): Buffer;
75
83
  *
76
84
  * Carrying signing metadata is NOT the same as being signed: since #2281 Payout
77
85
  * input 1 carries the Assert payout leaf purely so the device can display the
78
- * terms, while the firmware signs input 0 alone the index is the literal 0 at
79
- * `fw:sign_custom_inputs.c:276,334`, with no loop over inputs.
80
- * `signInputIndexes` is what separates the two.
86
+ * terms, and the device never signs it. `signInputIndexes` separates the two.
87
+ *
88
+ * The signed index is a property of the loaded ceremony, NOT of the PSBT shape:
89
+ * `sign_custom_inputs` signs exactly ONE literal index per branch with no loop —
90
+ * 0 for PegIn/NoPayout/Payout/standalone (`fw:sign_custom_inputs.c:167,256,334,611`)
91
+ * but 1 for PayoutFinalize (`:467`), which is byte-identical in shape to a
92
+ * depositor Payout (2-in/2-out) and separated only by device state. So the
93
+ * requested set must come from the caller that knows the flow — it cannot be
94
+ * inferred here, and it must not be pinned to a constant.
95
+ * (`LedgerHQ/app-babylon-vault` @ `develop` 0468801138.)
81
96
  */
82
97
  export declare function buildExpectedSignatureTable(params: BuildExpectedSignatureTableParams): ExpectedSignatureTable;
83
98
  export interface YieldCollector {
@@ -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,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;;;;;OAKG;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;;;;;;;;;;;GAWG;AACH,wBAAgB,2BAA2B,CAAC,MAAM,EAAE,iCAAiC,GAAG,sBAAsB,CAuI7G;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"}
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,CA4J7G;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 on=Object.create;var ut=Object.defineProperty;var sn=Object.getOwnPropertyDescriptor;var an=Object.getOwnPropertyNames;var cn=Object.getPrototypeOf,un=Object.prototype.hasOwnProperty;var ln=(e,t,n)=>t in e?ut(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var hn=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of an(t))!un.call(e,o)&&o!==n&&ut(e,o,{get:()=>t[o],enumerable:!(r=sn(t,o))||r.enumerable});return e};var L=(e,t,n)=>(n=e!=null?on(cn(e)):{},hn(t||!e||!e.__esModule?ut(n,"default",{value:e,enumerable:!0}):n,e));var p=(e,t,n)=>ln(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const at=require("@scure/bip32"),_=require("bitcoinjs-lib"),c=require("buffer"),fn=require("@bitcoin-js/tiny-secp256k1-asmjs");function pn(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 Et=pn(fn),dn=1,gn=1,En=1,wn=2,_n=33,mn=256,Tn=257,In=258,Sn=39,yn=259,Pn=105,bn=260,Rn=261,An=262,On=271,Bn=265,xn=266,Cn=267,Ln=268,vn=269,Mn=270,Nn=263,Dn=264,rt=32,$n=32,X=255,kn=3+rt,$t=Math.floor(X/kn);function O(e,t){if(t.length>X)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 ct(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 M(e,t,n){return O(e,ct(BigInt(t),1,n))}function Z(e,t,n){return O(e,ct(BigInt(t),4,n))}function D(e,t,n){return O(e,ct(t,8,n))}function ot(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 Pt(e,t,n){if(e.length!==t)throw new Error(`${n} must be ${t} bytes, got ${e.length}`);return e}const kt=5;function ge(e){if(e.depositorPath.length!==kt)throw new Error(`depositorPath must have exactly ${kt} levels, got ${e.depositorPath.length}`);const t=ot(e.depositorPath.map(n=>ct(BigInt(n>>>0),4,"path level")));return ot([M(En,dn,"structureType"),M(wn,gn,"version"),Z(_n,e.coinType,"coinType"),D(mn,e.baseFeeRate,"baseFeeRate"),Z(Tn,e.peginCsvTimelock,"peginCsvTimelock"),Z(In,e.payoutTimelock,"payoutTimelock"),O(Sn,Pt(e.prepeginTxidInternal,$n,"prepeginTxid")),Z(yn,e.htlcRefundTimelock,"htlcRefundTimelock"),O(Pn,t),M(bn,e.keeperCount,"keeperCount"),M(Rn,e.challengerCount,"challengerCount"),M(An,e.vaultCount,"vaultCount"),D(On,e.prepeginMaxFee,"prepeginMaxFee")])}function Ee(e){return ot([M(Bn,e.htlcVout,"htlcVout"),O(xn,Pt(e.vaultProviderPubkey,rt,"vaultProviderPubkey")),D(Cn,e.vaultAmount,"vaultAmount"),D(Ln,e.commissionFee,"commissionFee"),D(vn,e.depositorClaimValue,"depositorClaimValue"),D(Mn,e.peginMaxFee,"peginMaxFee")])}function we(e,t){const n=(s,i)=>s.map((a,u)=>Pt(a,rt,`${i}[${u}]`)).sort((a,u)=>{for(let h=0;h<rt;h++)if(a[h]!==u[h])return a[h]-u[h];return 0}),r=[...n(e,"keeper").map(s=>O(Nn,s)),...n(t,"challenger").map(s=>O(Dn,s))],o=[];for(let s=0;s<r.length;s+=$t)o.push(ot(r.slice(s,s+$t)));return o}const A=225,lt=128,Ut=129,Un=0,Vn=1,Hn=0,Gn=1,Kn=2,W=0,Vt=64,Ht=1024,Gt=10,Kt=32;function Fn(e){return new Uint8Array([e>>8&255,e&255])}function Yn(e){const t=e>>>0;return new Uint8Array([t>>>24&255,t>>>16&255,t>>>8&255,t&255])}function ht(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 Ft=/^[a-z0-9-]+$/;async function Xn(e,{appName:t,derivationPath:n,context:r}){const o=new TextEncoder().encode(t);if(o.length<1||o.length>Vt)throw new Error(`appName must be 1..${Vt} bytes, got ${o.length}`);if(!Ft.test(t))throw new Error(`appName must match ${Ft} — the device rejects other characters`);if(n.length<1||n.length>Gt)throw new Error(`derivationPath must have 1..${Gt} levels`);if(r.length<1||r.length>Ht)throw new Error(`context must be 1..${Ht} bytes, got ${r.length}`);const s=ht([new Uint8Array([o.length]),o,new Uint8Array([n.length]),ht(n.map(Yn)),Fn(r.length)]),i=Math.min(r.length,X-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:Ut,p1:Un,p2:W,data:ht([s,r.subarray(0,i)])});for(let u=i;u<r.length;u+=X)a=await e({cla:A,ins:Ut,p1:Vn,p2:W,data:r.subarray(u,u+X)});if(a.length!==Kt)throw new Error(`Expected a ${Kt}-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:lt,p1:Hn,p2:W,data:ge(t)});for(const s of n)await e({cla:A,ins:lt,p1:Gn,p2:W,data:Ee(s)});for(const s of we(r,o))await e({cla:A,ins:lt,p1:Kn,p2:W,data:s})}const qn=0,_e=0,me=1,zn=0,Yt=33,Xt=10,jn=5,Zn=4;async function Qn(e){const t=await e({cla:A,ins:jn,p1:_e,p2:me,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 Ie(t)}async function Te(e,t,n){if(t.length<1||t.length>Xt)throw new Error(`BIP-32 path must have 1..${Xt} levels, got ${t.length}`);const r=await e({cla:A,ins:qn,p1:_e,p2:me,data:tr(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 Jn(e,t,n){const r=await Te(e,t,n),o=at.HDKey.fromExtendedKey(r,n);if(!o.publicKey||o.publicKey.length!==Yt)throw new Error(`Ledger returned an extended key without a ${Yt}-byte public key`);return Ie(o.publicKey.subarray(1))}function Ie(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function tr(e){const t=new Uint8Array(2+e.length*4);return t[0]=zn,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 bt="LedgerUserRefusedError",Rt="LedgerDeviceLockedError",At="LedgerDeviceError",Ot="LedgerYieldMismatchError",Bt="LedgerSignPsbtIncompleteError",xt="LedgerSignPsbtProtocolError",Ct="LedgerSignPsbtAbortedError";function Se(e){return e.toString(16).padStart(4,"0")}class ye extends Error{constructor(n){super(`User rejected the request on the Ledger device (0x${Se(n)})`);p(this,"statusWord");this.name=bt,this.statusWord=n}}class Pe extends Error{constructor(n){super(`The Ledger device is locked — unlock it and retry (0x${Se(n)})`);p(this,"statusWord");this.name=Rt,this.statusWord=n}}class be extends Error{constructor(n,r){super(r);p(this,"statusWord");this.name=At,this.statusWord=n}}class S 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=Ot,this.kind=n,this.inputIndex=r}}class Re 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=Bt,this.missing=n}}function nt(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=xt,this.detail=n,this.collectedYields=r}}class wt extends Error{constructor(n){super("SIGN_PSBT was abandoned host-side before completion");p(this,"yieldedCount");this.name=Ct,this.yieldedCount=n}}function er(e){return e instanceof Error&&e.name===bt}function nr(e){return e instanceof Error&&e.name===At}function rr(e){return e instanceof Error&&e.name===Rt}function Ae(e){return e instanceof Error&&e.name===Ot}function or(e){return e instanceof Error&&e.name===Bt}function Oe(e){return e instanceof Error&&e.name===xt}function sr(e){return e instanceof Error&&e.name===Ct}const ir=36864,ar=new Set([21761,27013]),cr=new Set([21781,27010,21251]),Lt=28160,Be=45063,xe=45066,ur={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",27904:"The running app does not support this instruction",[Lt]:"The running app does not handle vault instructions — open the Babylon Vault app for this network",45056:"The device reported a wrong response length",[Be]:"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",[xe]:"The device has already signed the maximum number of these transactions",28416:"The device reported an internal error"};function $(e){return e.toString(16).padStart(2,"0")}function Ce(e){return e.toString(16).padStart(4,"0")}function Le(e,t){if(e===ir)return;if(ar.has(e))return new ye(e);if(cr.has(e))return new Pe(e);const n=ur[e],r=e===Lt&&t.appName?` (app at connect time: "${t.appName}"${t.appVersion?` v${t.appVersion}`:""})`:"";return new be(e,`${n??"The device rejected the request"} (ins 0x${$(t.ins)} p1 0x${$(t.p1)}, sw 0x${Ce(e)})${r}`)}function lr(e,t){return async n=>{const{sw:r,data:o}=await e(n),s=Le(r,{...t,ins:n.ins,p1:n.p1});if(s)throw s;return o}}const Wt=2;function hr(e){if(e.statusCode.length!==Wt)throw new Error(`The device returned a ${e.statusCode.length}-byte status word; expected ${Wt}.`);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 fr(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 qt(){return globalThis.__LEDGER_VAULT_APDU_TRACE__===!0}function ve(e){return async t=>{const n=`${$(t.cla)} ${$(t.ins)} ${$(t.p1)} ${$(t.p2)} Lc=${t.data.length}`;let r;try{r=await e.dmk.sendApdu({sessionId:e.sessionId,apdu:fr(t)})}catch(s){throw qt()&&console.debug(`[ledger-vault] APDU ${n} -> transport error`,s),s}const o=hr(r);return qt()&&console.debug(`[ledger-vault] APDU ${n} -> sw=0x${Ce(o)} len=${r.data.length}`),{sw:o,data:r.data}}}function pr(e){return lr(ve(e),{appName:e.appName,appVersion:e.appVersion})}const dr={isRefresherDisabled:!0};let k,N;function gr(){if(!N){const e=(async()=>{const[{DeviceManagementKitBuilder:t},{webHidTransportFactory:n}]=await Promise.all([import("@ledgerhq/device-management-kit"),import("@ledgerhq/device-transport-kit-web-hid")]);return k=new t().addTransport(n).build(),k})().catch(t=>{throw N===e&&(N=void 0),t});N=e}return N}async function Er(){const e=await gr(),[{firstValueFrom:t},{webHidIdentifier:n}]=await Promise.all([import("rxjs"),import("@ledgerhq/device-transport-kit-web-hid")]),r=await t(e.startDiscovering({transport:n})),o=await e.connect({device:r,sessionRefresherOptions:dr}),s=await wr(e,o);return{dmk:e,sessionId:o,...s}}async function wr(e,t){try{const{GetAppAndVersionCommand:n,isSuccessCommandResult:r}=await import("@ledgerhq/device-management-kit"),o=await e.sendCommand({sessionId:t,command:new n});return r(o)?{appName:o.data.name,appVersion:o.data.version}:{}}catch{return{}}}async function _r(e){const{firstValueFrom:t}=await import("rxjs");try{return await t(e.dmk.getDeviceSessionState({sessionId:e.sessionId})),!0}catch(n){if((n==null?void 0:n._tag)==="DeviceSessionNotFound")return!1;throw n}}async function mr(e){try{await e.dmk.disconnect({sessionId:e.sessionId})}catch{}}function Tr(){k==null||k.close(),k=void 0,N=void 0}const Ir=2,Sr=3,zt=32,yr=10,jt=0xffffffffn,Zt=72,Pr=1008,br=4320,Rr=91,Ar=4031,Me=546n,Qt=Me,Or=2n,Ne="DepositTermsRejectedError";class T extends Error{constructor(n,r="device-envelope"){super(n);p(this,"reason");this.name=Ne,this.reason=r}}const y="Deposit terms outside the device-supported range";function B(e,t,n,r){if(!Number.isInteger(t)||t<n||t>r)throw new T(`${y}: ${e} ${t} not in [${n}, ${r}]`)}function Br(e){if(B("vaultCoreVersion",e.vaultCoreVersion,Ir,Sr),e.protocolFeeRate<1n||e.protocolFeeRate>jt)throw new T(`${y}: protocolFeeRate ${e.protocolFeeRate} not in [1, ${jt}]`);if(B("timelockPegin",e.timelockPegin,Zt,Pr),B("timelockAssert",e.timelockAssert,Rr,Ar),B("timelockRefund",e.timelockRefund,Zt,br),B("keeper count",e.vaultKeeperBtcPubkeys.length,1,zt),B("challenger count",e.universalChallengerBtcPubkeys.length,1,zt),B("vault count",e.vaults.length,1,yr),Y("prepeginMaxFee",e.prepeginMaxFee),e.prepeginMaxFee<1n)throw new T(`${y}: prepeginMaxFee ${e.prepeginMaxFee} must be >= 1`);let t=-1;for(const a of e.vaults){if(!Number.isInteger(a.htlcVout)||a.htlcVout<0||a.htlcVout>255)throw new T(`${y}: htlcVout ${a.htlcVout} not in [0, 255]`);if(a.htlcVout<=t)throw new T(`${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,u]of[["vaultKeeperBtcPubkeys",e.vaultKeeperBtcPubkeys],["universalChallengerBtcPubkeys",e.universalChallengerBtcPubkeys]])for(const h of u){const f=n(h);if(r.has(f))throw new T(`${y}: ${a} contains the vault provider's own key (${f.slice(0,16)}…)`);if(o.has(f))throw new T(`${y}: duplicate participant key in ${a} (${f.slice(0,16)}…)`);o.add(f)}const s=Me,i=Or*s;for(const a of e.vaults){if(Y(`vault ${a.htlcVout} peginAmount`,a.peginAmount),Y(`vault ${a.htlcVout} commissionFee`,a.commissionFee),Y(`vault ${a.htlcVout} depositorClaimValue`,a.depositorClaimValue),Y(`vault ${a.htlcVout} peginMaxFee`,a.peginMaxFee),a.commissionFee<s)throw new T(`${y}: vault ${a.htlcVout} commissionFee ${a.commissionFee} below the ${s}-sat dust limit`);if(a.depositorClaimValue<Qt)throw new T(`${y}: vault ${a.htlcVout} depositorClaimValue ${a.depositorClaimValue} below the ${Qt}-sat device floor`);if(a.peginAmount<=a.commissionFee+i)throw new T(`${y}: vault ${a.htlcVout} peginAmount ${a.peginAmount} must exceed commissionFee + ${i} (${a.commissionFee+i})`)}}const xr=(1n<<64n)-1n;function Y(e,t){if(t<0n||t>xr)throw new T(`${y}: ${e} ${t} does not fit in an unsigned 64-bit field`)}const b=2147483648,Cr=4294967295,st=86,De=0,$e=1,Jt=5,vt=3,Lr=3,vr=4;function ke(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>Cr)throw new Error(`${e} levels must be integers in 0..0xffffffff`);if(!t.slice(0,vt).every(r=>(r&b)!==0)||(t[vr]&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 z(e){return"m/"+e.map(t=>(t&b)!==0?`${(t&~b)>>>0}'`:`${t>>>0}`).join("/")}const te=253,Mr=254,Nr=65535,Dr=4294967295;function $r(e){if(e<te)return c.Buffer.from([e]);if(e<=Nr){const t=c.Buffer.alloc(2);return t.writeUInt16LE(e),c.Buffer.concat([c.Buffer.from([te]),t])}if(e<=Dr){const t=c.Buffer.alloc(4);return t.writeUInt32LE(e),c.Buffer.concat([c.Buffer.from([Mr]),t])}throw new Error(`Script too large to encode as CompactSize: ${e} bytes`)}const kr="TapLeaf";function Ur(e,t){const n=c.Buffer.concat([c.Buffer.from([e]),$r(t.length),c.Buffer.from(t)]);return _.crypto.taggedHash(kr,n)}function Vr(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 Hr(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 Gr(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 Kr=BigInt(253),Fr=BigInt(65535)+BigInt(1),Yr=BigInt(4294967295)+BigInt(1);function Ue(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=Kr):n===254?(r=4,o=Fr):(r=8,o=Yr);const s=Hr(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=Gr(e);e=BigInt(e);const n=c.Buffer.alloc(t);return t==1?n[0]=Number(e):(t==3?n[0]=253:t===5?n[0]=254:n[0]=255,Vr(e,t-1,n,1)),n}const Xr=31;function Ve(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=c.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 _t(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>Xr)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 x{constructor(){p(this,"bufs",[])}write(t,n){const r=c.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=Ve(t);this.writeSlice(n)}writeVarInt(t){this.bufs.push(V(t))}writeSlice(t){this.bufs.push(c.Buffer.from(t))}writeVarSlice(t){this.writeVarInt(t.length),this.writeSlice(t)}buffer(){return c.Buffer.concat(this.bufs)}}class U{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 _t(t)}readVarInt(){const[t,n]=Ue(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 ee=c.Buffer.from([112,115,98,116,255]),Wr=4294967295;class He extends Error{}class Ge{constructor(){p(this,"globalMap",new Map);p(this,"inputMaps",[]);p(this,"outputMaps",[])}setGlobalTxVersion(t){this.setGlobal(2,v(t))}getGlobalTxVersion(){return this.getGlobal(2).readUInt32LE(0)}setGlobalFallbackLocktime(t){this.setGlobal(3,v(t))}getGlobalFallbackLocktime(){var t;return(t=this.getGlobalOptional(3))==null?void 0:t.readUInt32LE(0)}setGlobalInputCount(t){this.setGlobal(4,oe(t))}getGlobalInputCount(){return se(this.getGlobal(4))}setGlobalOutputCount(t){this.setGlobal(5,oe(t))}getGlobalOutputCount(){return se(this.getGlobal(5))}setGlobalTxModifiable(t){this.setGlobal(6,t)}getGlobalTxModifiable(){return this.getGlobalOptional(6)}setGlobalPsbtVersion(t){this.setGlobal(251,v(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 x;o.writeSlice(re(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 U(n);return{amount:_t(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(),v(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(),v(n))}getInputOutputIndex(t){return this.getInput(t,15,w()).readUInt32LE(0)}setInputSequence(t,n){this.setInput(t,16,w(),v(n))}getInputSequence(t){var n;return((n=this.getInputOptional(t,16,w()))==null?void 0:n.readUInt32LE(0))??Wr}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:c.Buffer.from(i.substring(2),"hex"),value:c.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(),re(n))}getOutputAmount(t){const n=this.getOutput(t,3,w());return _t(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,c.Buffer.from(r)))}serialize(){const t=new x;return t.writeSlice(ee),pt(t,this.globalMap),this.inputMaps.forEach(n=>{pt(t,n)}),this.outputMaps.forEach(n=>{pt(t,n)}),t.buffer()}deserialize(t){const n=new U(t);if(!n.readSlice(5).equals(ee))throw new Error("Invalid magic bytes");for(;this.readKeyPair(this.globalMap,n););let r;try{r=this.getGlobalPsbtVersion()}catch(i){if(!(i instanceof He))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 H(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(c.Buffer.from(s.substring(2),"hex"))}),r}isKeyType(t,n){const r=c.Buffer.from(t.substring(0,2),"hex").readUInt8(0);return n.some(o=>o===r)}setGlobal(t,n){const r=new H(t,c.Buffer.from([]));this.globalMap.set(r.toString(),n)}getGlobal(t){return ft(this.globalMap,t,w())}getGlobalOptional(t){return Tt(this.globalMap,t,w())}setInput(t,n,r,o){ne(this.getMap(t,this.inputMaps),n,r,o)}getInput(t,n,r){return ft(this.inputMaps[t],n,r)}getInputOptional(t,n,r){return Tt(this.inputMaps[t],n,r)}setOutput(t,n,r,o){ne(this.getMap(t,this.outputMaps),n,r,o)}getOutput(t,n,r){return ft(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 x;return this.writeBip32Derivation(r,t,n),r.buffer()}decodeBip32Derivation(t){const n=new U(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 x;return o.writeVarInt(t.length),t.forEach(s=>{o.writeSlice(s)}),this.writeBip32Derivation(o,n,r),o.buffer()}decodeTapBip32Derivation(t){const n=new U(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 ft(e,t,n){const r=Tt(e,t,n);if(r===void 0)throw new He(new H(t,n).toString());return r}function Tt(e,t,n){if(!e)throw new Error("No such map");const r=new H(t,n),o=e.get(r.toString());if(o!==void 0)return c.Buffer.from(o)}class H{constructor(t,n){p(this,"keyType");p(this,"keyData");this.keyType=t,this.keyData=n}toString(){const t=new x;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 qr{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 zr(e){return new H(e.readUInt8(0),e.subarray(1))}function pt(e,t){const n=[...t].sort(([r],[o])=>r<o?-1:r>o?1:0);for(const[r,o]of n)new qr(zr(c.Buffer.from(r,"hex")),o).serialize(e);e.writeUInt8(0)}function w(){return c.Buffer.from([])}function ne(e,t,n,r){const o=new H(t,n);e.set(o.toString(),r)}function v(e){const t=c.Buffer.alloc(4);return t.writeUInt32LE(e,0),t}function re(e){return Ve(e)}function oe(e){const t=new x;return t.writeVarInt(e),t.buffer()}function se(e){return R(new U(e).readVarInt())}const ie=192,It=32,ae=2,J=33,tt=32,jr=1,Zr="TapBranch",Qr="TapTweak",ce=64,ue=32,dt=64,Jr=34,it=c.Buffer.from([81,32]),to=c.Buffer.from([0,20]),eo=2,no=3;function Mt(e){_.initEccLib(Et);const t=_.payments.p2tr({internalPubkey:c.Buffer.from(e,"hex")}).output;if(!t)throw new d("p2tr produced no output script for the depositor key");return t}function le(e,t){const n=c.Buffer.concat([c.Buffer.from([t]),c.Buffer.from(e,"hex")]);return c.Buffer.concat([to,_.crypto.hash160(n)])}function Ke(e){return e.length===Jr&&e.subarray(0,it.length).equals(it)}function ro(e,t,n,r){if(!Ke(r))throw new d(`input ${e} is tapscript but its witnessUtxo script is not P2TR`);const o=t.length-J;if(o<0||o%tt!==0)throw new d(`input ${e} control block length ${t.length} is not ${J} plus a multiple of ${tt}`);const s=t.subarray(1,J);if(!Et.isXOnlyPoint(s))throw new d(`input ${e} control block internal key is not an x-only point`);let i=n;for(let f=J;f<t.length;f+=tt){const l=t.subarray(f,f+tt),E=c.Buffer.compare(i,l)<0?[i,l]:[l,i];i=_.crypto.taggedHash(Zr,c.Buffer.concat(E))}const a=_.crypto.taggedHash(Qr,c.Buffer.concat([s,i])),u=Et.xOnlyPointAddTweak(s,a);if(!u)throw new d(`input ${e} control block internal key has no taproot output key`);if(!r.subarray(it.length).equals(c.Buffer.from(u.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(u.parity!==(t[0]&jr))throw new d(`input ${e} control block parity bit disagrees with the recomputed taproot output key`)}function oo(e){const{psbt:t,depositorXOnlyHex:n,signInputIndexes:r}=e,o=new Map,s=t.getGlobalInputCount(),i=r===void 0?void 0:new Set(r),a=l=>i===void 0||i.has(l),u=Mt(n),h=[le(n,eo),le(n,no)];for(let l=0;l<s;l++){const E=t.getInputEntriesOfType(l,mt.TAP_LEAF_SCRIPT);if(E.length>0){if(E.length>1)throw new d(`input ${l} carries an ambiguous leaf set (${E.length} TAP_LEAF_SCRIPT entries)`);const m=E[0].value;if(m.length<ae)throw new d(`input ${l} TAP_LEAF_SCRIPT value length ${m.length} is below the ${ae}-byte minimum (script byte plus the leaf-version byte)`);const F=m[m.length-1];if(F!==ie)throw new d(`input ${l} leaf version 0x${F.toString(16)} is not tapscript (0xc0)`);const C=t.getInputWitnessUtxo(l);if(!C)throw new d(`input ${l} is tapscript but has no witnessUtxo`);const rn=m.subarray(0,m.length-1),Dt=Ur(ie,rn);ro(l,E[0].keyData,Dt,C.scriptPubKey),a(l)&&o.set(l,{kind:"tapscript",expectedLeafHashHexes:new Set([Dt.toString("hex")]),expectedSignerXOnlyHex:n});continue}const g=t.getInputEntriesOfType(l,mt.TAP_INTERNAL_KEY);if(g.length>0){const m=g[0];if(g.length>1||m.keyData.length!==0||m.value.length!==It)throw new d(`input ${l} carries a malformed TAP_INTERNAL_KEY entry`);if(m.value.toString("hex")!==n)throw new d(`input ${l} internal key is not the connected depositor key`);const F=t.getInputWitnessUtxo(l);if(!F)throw new d(`input ${l} is keypath but has no witnessUtxo`);const C=F.scriptPubKey;if(!Ke(C))throw new d(`input ${l} witnessUtxo script is not P2TR`);if(!C.equals(u))throw new d(`input ${l} witnessUtxo is not the BIP-86 P2TR of the depositor key`);o.set(l,{kind:"taproot-keypath",expectedOutputKeyHex:C.subarray(it.length).toString("hex")});continue}const P=t.getInputWitnessUtxo(l);if(P&&(P.scriptPubKey.equals(u)||h.some(m=>P.scriptPubKey.equals(m))))throw new d(`input ${l} spends a depositor-owned UTXO but carries no signing metadata`)}for(const l of i??[])if(!o.has(l))throw new d(`input ${l} was requested for signing but carries no signing metadata`);if(o.size===0)throw new d("PSBT contains no depositor-signable input");let f=0;for(const l of o.values())f+=l.kind==="tapscript"?l.expectedLeafHashHexes.size:1;return{byInput:o,expectedYieldCount:f}}function et(e){return e.kind==="tapscript"?`${e.inputIndex}:${e.leafHashHex}`:`${e.inputIndex}`}function he(e,t){if(e<dt)throw new d(`YIELD payload truncated inside the signature (${e} of ${dt} bytes on input ${t})`);if(e!==dt)throw new S("non-default-sighash",t)}function so(e){const t=[],n=new Set;return{assertAndRecord:s=>{let i,a;try{const[f,l]=Ue(s,0);i=R(f),a=l}catch(f){throw new d(`unparseable YIELD payload: ${f instanceof Error?f.message:String(f)}`)}const u=s[a];if(u===void 0)throw new d("YIELD payload truncated before the augmented-pubkey length");const h=e.byInput.get(i);if(h===void 0)throw new S("unexpected-input",i);if(u===ce){if(h.kind!=="tapscript")throw new S("wrong-spend-type",i);const f=a+1+ce;if(s.length<f)throw new d("YIELD payload truncated inside the augmented pubkey");const l=s.subarray(a+1,a+1+It).toString("hex"),E=s.subarray(a+1+It,f).toString("hex"),g=s.subarray(f);if(l!==h.expectedSignerXOnlyHex)throw new S("wrong-signer-key",i);if(!h.expectedLeafHashHexes.has(E))throw new S("unknown-leaf-hash",i);he(g.length,i);const P={kind:"tapscript",inputIndex:i,signerXOnlyHex:l,leafHashHex:E,signature:Uint8Array.from(g)};if(n.has(et(P)))throw new S("duplicate-yield",i);n.add(et(P)),t.push(P);return}if(u===ue){if(h.kind!=="taproot-keypath")throw new S("wrong-spend-type",i);const f=a+1+ue;if(s.length<f)throw new d("YIELD payload truncated inside the augmented pubkey");const l=s.subarray(a+1,f).toString("hex"),E=s.subarray(f);if(l!==h.expectedOutputKeyHex)throw new S("wrong-signer-key",i);he(E.length,i);const g={kind:"taproot-keypath",inputIndex:i,outputKeyHex:l,signature:Uint8Array.from(E)};if(n.has(et(g)))throw new S("duplicate-yield",i);n.add(et(g)),t.push(g);return}throw new S("unexpected-encoding",i)},get yields(){return t},get lastYield(){return t[t.length-1]},assertComplete:()=>{const s=new Set;for(const[u,h]of e.byInput)if(h.kind==="tapscript")for(const f of h.expectedLeafHashHexes)s.add(`${u}:${f}`);else s.add(`${u}`);const i=[...s].filter(u=>!n.has(u)),a=[...n].some(u=>!s.has(u));if(i.length>0||a||n.size!==e.expectedYieldCount)throw new Re(i)}}}const Fe=/^[0-9a-f]{64}$/;function io(e,t){if(ke("depositorPath",e),e[Lr]!==De)throw new Error("depositorPath must use BIP-86 receive branch 0");for(let n=0;n<vt;n++)if(e[n]!==t[n])throw new Error(`depositorPath ${z(e)} is not under the wallet policy's key origin ${z(t)} — the device could never mark the input internal`)}function Ye(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 c.Buffer.from(o.publicKey.subarray(1)).toString("hex")}function Xe(e,t,n){return Ye(e,t,$e,n)}function ao(e,t,n){return Ye(e,t,De,n)}function We(e,t){const n=Mt(t);return e.txOutputs.flatMap((r,o)=>c.Buffer.from(r.script).equals(n)?[o]:[])}function co(e,t){if(!Fe.test(t))throw new Error("changeXOnlyHex must be 64 lowercase hex characters");return We(_.Psbt.fromHex(e),t).length>0}function uo(e){const{psbtHex:t,depositorXOnlyHex:n,walletPolicy:r,depositorPath:o,change:s}=e;if(!Fe.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");io(o,r.keyOriginPath);const i=_.Psbt.fromHex(t),a=c.Buffer.from(r.masterFingerprintHex,"hex"),u=c.Buffer.from(n,"hex");let h=0;if(i.data.inputs.forEach((f,l)=>{f.tapInternalKey&&c.Buffer.from(f.tapInternalKey).equals(u)&&(h++,i.updateInput(l,{tapBip32Derivation:[{masterFingerprint:a,pubkey:u,path:z(o),leafHashes:[]}]}))}),h!==i.data.inputs.length)throw new Error(`${i.data.inputs.length-h} 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=Xe(r.accountXpub,r.bip32Versions,s.addressIndex),l=[...o.slice(0,vt),$e,s.addressIndex],E=c.Buffer.from(f,"hex"),g=We(i,f);if(g.length===0)throw new Error("change script matches no output — the PSBT does not pay the wallet's change address");for(const P of g)i.updateOutput(P,{tapInternalKey:E,tapBip32Derivation:[{masterFingerprint:a,pubkey:E,path:z(l),leafHashes:[]}]})}return i.toHex()}const lo="BIP0322-signed-message",ho=new Uint8Array([252,6,98,118,97,117,108,116,0]),qe=0,ze=0,je=0,fo=0,St=0,po=c.Buffer.from([106]),go=/^[0-9a-f]{64}$/,Eo=/^[0-9a-f]{8}$/,wo=c.Buffer.alloc(32,0),_o=4294967295,mo=c.Buffer.from([0,32]),To=c.Buffer.from([81,32]),Io=2;function So(e,t){const n=_.crypto.sha256(c.Buffer.from(e,"utf8"));return _.crypto.sha256(c.Buffer.concat([n,n,c.Buffer.from(t)]))}function yo(e,t){const n=new _.Transaction;n.version=qe,n.locktime=ze;const r=c.Buffer.concat([mo,So(lo,e)]);return n.addInput(wo,_o,je,r),n.addOutput(c.Buffer.concat([To,c.Buffer.from(t)]),St),Uint8Array.from(n.getHash(!1))}function Po(e){const{message:t,depositorXOnlyHex:n,masterFingerprintHex:r,depositorPath:o}=e;if(!go.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");if(!Eo.test(r))throw new Error("masterFingerprintHex must be 8 lowercase hex characters");ke("depositorPath",o);const s=new TextEncoder().encode(t),i=c.Buffer.from(n,"hex"),a=Mt(n),u=yo(s,a.subarray(Io)),h=new _.Psbt;return h.setVersion(qe),h.setLocktime(ze),h.addInput({hash:c.Buffer.from(u),index:fo,sequence:je,witnessUtxo:{script:a,value:St},tapInternalKey:i,tapBip32Derivation:[{masterFingerprint:c.Buffer.from(r,"hex"),pubkey:i,path:z(o),leafHashes:[]}]}),h.addOutput({script:po,value:St}),h.addUnknownKeyValToGlobal({key:c.Buffer.from(ho),value:c.Buffer.from(s)}),h.toHex()}class G{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 yt(n)}calculateRoot(t){const n=t.length;if(n==0)return{root:new gt(void 0,void 0,c.Buffer.alloc(32,0)),leaves:[]};if(n==1){const f=new gt(void 0,void 0,t[0]);return{root:f,leaves:[f]}}const r=Ro(n),o=this.calculateRoot(t.slice(0,r)),s=this.calculateRoot(t.slice(r)),i=o.root,a=s.root,u=this.hashNode(i.hash,a.hash),h=new gt(i,a,u);return i.parent=h,a.parent=h,{root:h,leaves:o.leaves.concat(s.leaves)}}hashNode(t,n){return this.h(c.Buffer.concat([c.Buffer.from([1]),t,n]))}}function K(e,t=_.crypto.sha256){return bo(c.Buffer.from([0]),e,t)}function bo(e,t,n){return n(c.Buffer.concat([e,t]))}class gt{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 yt(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,...yt(e.parent)]}else{if(!e.parent.leftChild)throw new Error("Expected left child to exist");return[e.parent.leftChild.hash,...yt(e.parent)]}}function Ro(e){if(e<2)throw Error("Expected n >= 2");return Ao(e)?e/2:1<<Math.floor(Math.log2(e))}function Ao(e){return(e&e-1)==0}const Nt=255,Oo=2,I=32;class j{}class Bo extends j{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=c.Buffer.from(n.subarray(1));return this.onYield&&this.onYield(c.Buffer.from(r)),this.results.push(r),this.progressCallback&&this.progressCallback(),c.Buffer.from("")}}class xo extends j{constructor(n,r){super();p(this,"knownPreimages");p(this,"queue");p(this,"code",64);this.knownPreimages=n,this.queue=r}execute(n){const r=c.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=c.Buffer.from(r.subarray(1,1+I)).toString("hex"),i=this.knownPreimages.get(s);if(i!==void 0){const a=V(i.length),u=Nt-a.length-1,h=Math.min(u,i.length);if(h<i.length)for(let f=h;f<i.length;f++)this.queue.push(c.Buffer.from(i.subarray(f,f+1)));return c.Buffer.concat([a,c.Buffer.from([h]),c.Buffer.from(i.subarray(0,h))])}throw new Error(`Requested unknown preimage for: ${s}`)}}class Co extends j{constructor(n,r){super();p(this,"knownTrees");p(this,"queue");p(this,"code",65);this.knownTrees=n,this.queue=r}execute(n){const r=c.Buffer.from(n.subarray(1));if(r.length<I+1+1)throw new Error("Invalid request, expected at least 34 bytes");const o=new U(r),i=o.readSlice(I).toString("hex");let a,u;try{a=R(o.readVarInt()),u=R(o.readVarInt())}catch{throw new Error("Invalid request, couldn't parse tree_size or leaf_index")}const h=this.knownTrees.get(i);if(!h)throw new Error(`Requested Merkle leaf proof for unknown tree: ${i}`);if(u>=a||h.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=h.getProof(u),l=Math.min(Math.floor((Nt-I-1-1)/I),f.length),E=f.length-l;return E>0&&this.queue.push(...f.slice(-E)),c.Buffer.concat([h.getLeafHash(u),c.Buffer.from([f.length]),c.Buffer.from([l]),...f.slice(0,l)])}}class Lo extends j{constructor(n){super();p(this,"knownTrees");p(this,"code",66);this.knownTrees=n}execute(n){const r=c.Buffer.from(n.subarray(1));if(r.length!==I+I)throw new Error("Invalid request, unexpected trailing data");const s=c.Buffer.from(r.subarray(0,I)).toString("hex"),a=c.Buffer.from(r.subarray(I,I+I)).toString("hex"),u=this.knownTrees.get(s);if(!u)throw new Error(`Requested Merkle leaf index for unknown root: ${s}`);let h=0,f=0;for(let l=0;l<u.size();l++)if(u.getLeafHash(l).toString("hex")===a){f=1,h=l;break}return c.Buffer.concat([c.Buffer.from([f]),V(h)])}}class vo extends j{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(u=>u.length!==o))throw new Error("The queue contains elements with different byte length, which is not expected");const s=Math.floor((Nt-Oo)/o),i=Math.min(s,this.queue.length),a=this.queue.splice(0,i);return c.Buffer.concat([c.Buffer.from([i]),c.Buffer.from([o]),...a])}}class Mo{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 Bo(this.yielded,t,n),new xo(this.preimages,this.queue),new Lo(this.roots),new Co(this.roots,this.queue),new vo(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=c.Buffer.concat([c.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=>c.Buffer.from(n,"ascii"))),this.addKnownPreimage(c.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 No{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 c.Buffer.concat([V(this.keys.length),this.keysTree.getRoot(),this.valuesTree.getRoot()])}}class q extends Ge{constructor(n){super();p(this,"globalMerkleMap");p(this,"inputMerkleMaps",[]);p(this,"outputMerkleMaps",[]);p(this,"inputMapCommitments");p(this,"outputMapCommitments");n.copy(this),this.globalMerkleMap=q.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(q.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(q.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=>c.Buffer.from(i,"hex"));return new No(s,o)}}const Do=2;class $o{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=>c.Buffer.from(o,"ascii")),n=new G(t.map(o=>K(o))),r=new x;return r.writeUInt8(Do),r.writeVarSlice(c.Buffer.from(this.name,"ascii")),r.writeVarInt(this.descriptorTemplate.length),r.writeSlice(_.crypto.sha256(c.Buffer.from(this.descriptorTemplate))),r.writeVarInt(this.keys.length),r.writeSlice(n.getRoot()),r.buffer()}}class Ze extends $o{constructor(t,n){super("",t,[n])}}const ko=4,Uo=0,Vo=1,Qe=32,Ho=new Uint8Array(Qe),Go=new Uint8Array(Qe),Ko=/^[0-9a-f]{64}$/,Fo=/^(?:[0-9a-fA-F]{2})+$/,Yo=/^[0-9a-f]{64}$/;function Xo(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(c.Buffer.concat([e.getGlobalKeysValuesRoot(),V(e.getGlobalInputCount()),n,V(e.getGlobalOutputCount()),r,c.Buffer.from(t),c.Buffer.from(Go)]))}function Wo(e){return{cla:A,ins:ko,p1:Uo,p2:Vo,data:e}}const qo=0;function zo(e,t){for(const[n]of t.byInput){const r=e.data.inputs[n].sighashType;if(r!==void 0&&r!==qo)throw new d(`input ${n} requests sighash type ${r}, but vault flows sign SIGHASH_DEFAULT only`)}}function jo(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 Je=new WeakMap;function Zo(e,t){const n={...e};return Je.set(n,t),n}function tn(e){const t=Je.get(e);if(!t)throw new d("unrecognised prepared signing state — use prepareSignPsbt's return value");return t}function en(e){const{psbtHex:t,depositorXOnlyHex:n,signInputIndexes:r,walletPolicy:o}=e;if(!Ko.test(n))throw new d("depositorXOnlyHex must be 64 lowercase hex characters");let s;if(o!==void 0){if(!Yo.test(o.walletIdHex))throw new d("walletPolicy.walletIdHex must be 64 lowercase hex characters");if(s=new Ze(o.descriptorTemplate,o.keyInfo),s.getId().toString("hex")!==o.walletIdHex)throw new d("walletPolicy.walletIdHex does not match sha256 of the serialized policy")}if(!Fo.test(t))throw new d("psbtHex is not even-length hexadecimal");let i;try{i=_.Psbt.fromHex(t)}catch(g){throw new d(`PSBT rejected at parse (merge target): ${g instanceof Error?g.message:String(g)}`)}const a=new Ge;try{a.deserialize(c.Buffer.from(t,"hex"))}catch(g){throw new d(`PSBT rejected at parse: ${g instanceof Error?g.message:String(g)}`)}let u,h;try{u=new q(a),h=oo({psbt:u,depositorXOnlyHex:n,signInputIndexes:r})}catch(g){throw g instanceof d?g:new d(`PSBT rejected at preflight: ${g instanceof Error?g.message:String(g)}`)}jo(i,h),zo(i,h);const f=so(h),l=new Mo(void 0,g=>f.assertAndRecord(g));l.addKnownMapping(u.globalMerkleMap);for(const g of u.inputMerkleMaps)l.addKnownMapping(g);for(const g of u.outputMerkleMaps)l.addKnownMapping(g);l.addKnownList(u.inputMapCommitments),l.addKnownList(u.outputMapCommitments);const E=o?c.Buffer.from(o.walletIdHex,"hex"):Ho;return s&&l.addKnownWalletPolicy(s),Zo({table:h,unsignedTxid:_.Transaction.fromBuffer(i.data.globalMap.unsignedTx.toBuffer()).getId()},{cdata:Xo(u,E),interpreter:l,collector:f,originalPsbtHex:t,signsUnderWalletPolicy:o!==void 0})}const Qo=248,Jo=1,ts=0,es=0,ns=36864,rs=57344;async function os(e,t,n){const{collector:r,interpreter:o,cdata:s}=tn(t),{table:i}=t;if(n.signal.aborted)throw new wt(r.yields.length);const a=Wo(s);let u=a,h=await e(a),f=0;for(;h.sw===rs;){let l;try{l=o.execute(c.Buffer.from(h.data))}catch(E){throw Ae(E)?E:Oe(E)?new d(E.detail,nt(r.yields)):new d(`client command failed: ${E instanceof Error?E.message:String(E)}`,nt(r.yields))}if(r.yields.length>f){f=r.yields.length;const E=r.lastYield;if(E!==void 0&&n.onProgress!==void 0)try{n.onProgress({inputIndex:E.inputIndex,yieldedCount:f,expectedYieldCount:i.expectedYieldCount})}catch{}}if(n.signal.aborted)throw new wt(r.yields.length);u={cla:Qo,ins:Jo,p1:ts,p2:es,data:l},h=await e(u)}if(h.sw!==ns){const l=Le(h.sw,{...n.appIdentity,ins:u.ins,p1:u.p1});throw l===void 0?new d(`status word 0x${h.sw.toString(16)} escaped classification`,nt(r.yields)):l}return r.assertComplete(),r.yields}function ss(e,t){const n=_.Psbt.fromHex(e);for(const r of t)r.kind==="tapscript"?n.updateInput(r.inputIndex,{tapScriptSig:[{pubkey:c.Buffer.from(r.signerXOnlyHex,"hex"),leafHash:c.Buffer.from(r.leafHashHex,"hex"),signature:c.Buffer.from(r.signature)}]}):n.updateInput(r.inputIndex,{tapKeySig:c.Buffer.from(r.signature)});return n.toHex()}const fe=new WeakSet;async function nn(e,t,n){const{originalPsbtHex:r,signsUnderWalletPolicy:o}=tn(t);if(fe.has(t))throw new d("prepared signing state was already used — call prepareSignPsbt again for a retry");if([...t.table.byInput.values()].some(u=>u.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");fe.add(t);const i=await os(e,t,n);let a;try{a=ss(r,i)}catch(u){throw new d(`merge failed after signing: ${u instanceof Error?u.message:String(u)}`,nt(i))}return{signedPsbtHex:a,yields:[...i]}}async function is(e,t){const{psbtHex:n,depositorXOnlyHex:r,signInputIndexes:o,...s}=t,i=en({psbtHex:n,depositorXOnlyHex:r,signInputIndexes:o});return nn(e,i,s)}const pe="tr(@0/**)",de=2147483647,as=/^[0-9a-f]{8}$/;function cs(e){const{masterFingerprintHex:t,coinType:n,accountIndex:r,accountXpub:o,bip32Versions:s}=e;if(!as.test(t))throw new Error("masterFingerprintHex must be 8 lowercase hex characters");if(!Number.isInteger(n)||n<0||n>de||!Number.isInteger(r)||r<0||r>de)throw new Error("coinType and accountIndex must be non-negative integers in 0..0x7fffffff");try{at.HDKey.fromExtendedKey(o,s)}catch(u){throw new Error(`accountXpub is not a valid extended key for this network: ${u instanceof Error?u.message:String(u)}`)}const i=`[${t}/${st}'/${n}'/${r}']${o}`,a=new Ze(pe,i).getId().toString("hex");return{descriptorTemplate:pe,keyInfo:i,walletIdHex:a,accountXpub:o,bip32Versions:s,keyOriginPath:[(b|st)>>>0,(b|n)>>>0,(b|r)>>>0],masterFingerprintHex:t}}exports.DEPOSIT_TERMS_REJECTED_ERROR_NAME=Ne;exports.DepositTermsRejectedError=T;exports.LEDGER_DEVICE_ERROR_NAME=At;exports.LEDGER_DEVICE_LOCKED_ERROR_NAME=Rt;exports.LEDGER_SIGN_PSBT_ABORTED_ERROR_NAME=Ct;exports.LEDGER_SIGN_PSBT_INCOMPLETE_ERROR_NAME=Bt;exports.LEDGER_SIGN_PSBT_PROTOCOL_ERROR_NAME=xt;exports.LEDGER_USER_REFUSED_ERROR_NAME=bt;exports.LEDGER_YIELD_MISMATCH_ERROR_NAME=Ot;exports.LedgerDeviceError=be;exports.LedgerDeviceLockedError=Pe;exports.LedgerSignPsbtAbortedError=wt;exports.LedgerSignPsbtIncompleteError=Re;exports.LedgerSignPsbtProtocolError=d;exports.LedgerUserRefusedError=ye;exports.LedgerYieldMismatchError=S;exports.SW_BAD_STATE=Be;exports.SW_CAP_EXCEEDED=xe;exports.SW_CLA_NOT_SUPPORTED=Lt;exports.approveVaultIntent=Wn;exports.assertDepositTermsDeviceCompatible=Br;exports.augmentPsbtForWalletPolicy=uo;exports.buildDefaultTaprootPolicy=cs;exports.buildPopPsbtHex=Po;exports.closeDmk=Tr;exports.connectDmkSession=Er;exports.createDmkApduSender=pr;exports.createDmkRawApduSender=ve;exports.deriveChangeXOnlyHex=Xe;exports.deriveContextHash=Xn;exports.deriveReceiveXOnlyHex=ao;exports.disconnectDmkSession=mr;exports.encodeIntentGroup=Ee;exports.encodeIntentScalars=ge;exports.encodeKeyBatches=we;exports.getExtendedPublicKey=Te;exports.getMasterFingerprintHex=Qn;exports.getXOnlyPublicKeyHex=Jn;exports.isLedgerDeviceError=nr;exports.isLedgerDeviceLockedError=rr;exports.isLedgerSignPsbtAbortedError=sr;exports.isLedgerSignPsbtIncompleteError=or;exports.isLedgerSignPsbtProtocolError=Oe;exports.isLedgerUserRefusedError=er;exports.isLedgerYieldMismatchError=Ae;exports.isSessionAlive=_r;exports.prepareSignPsbt=en;exports.psbtPaysChangeScript=co;exports.signPreparedVaultPsbt=nn;exports.signVaultPsbt=is;
1
+ "use strict";var an=Object.create;var ht=Object.defineProperty;var cn=Object.getOwnPropertyDescriptor;var un=Object.getOwnPropertyNames;var ln=Object.getPrototypeOf,hn=Object.prototype.hasOwnProperty;var fn=(e,t,n)=>t in e?ht(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var pn=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of un(t))!hn.call(e,o)&&o!==n&&ht(e,o,{get:()=>t[o],enumerable:!(r=cn(t,o))||r.enumerable});return e};var K=(e,t,n)=>(n=e!=null?an(ln(e)):{},pn(t||!e||!e.__esModule?ht(n,"default",{value:e,enumerable:!0}):n,e));var p=(e,t,n)=>fn(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ct=require("@scure/bip32"),_=require("bitcoinjs-lib"),c=require("buffer"),dn=require("@bitcoin-js/tiny-secp256k1-asmjs");function gn(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 _t=gn(dn),En=1,wn=1,_n=1,mn=2,Tn=33,In=256,Sn=257,yn=258,Pn=39,bn=259,Rn=105,An=260,On=261,Bn=262,xn=271,Cn=265,Ln=266,vn=267,Mn=268,Nn=269,Dn=270,kn=263,$n=264,ot=32,Un=32,X=255,Vn=3+ot,Vt=Math.floor(X/Vn);function O(e,t){if(t.length>X)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 M(e,t,n){return O(e,ut(BigInt(t),1,n))}function Q(e,t,n){return O(e,ut(BigInt(t),4,n))}function N(e,t,n){return O(e,ut(t,8,n))}function st(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 Ht=5;function _e(e){if(e.depositorPath.length!==Ht)throw new Error(`depositorPath must have exactly ${Ht} levels, got ${e.depositorPath.length}`);const t=st(e.depositorPath.map(n=>ut(BigInt(n>>>0),4,"path level")));return st([M(_n,En,"structureType"),M(mn,wn,"version"),Q(Tn,e.coinType,"coinType"),N(In,e.baseFeeRate,"baseFeeRate"),Q(Sn,e.peginCsvTimelock,"peginCsvTimelock"),Q(yn,e.payoutTimelock,"payoutTimelock"),O(Pn,Rt(e.prepeginTxidInternal,Un,"prepeginTxid")),Q(bn,e.htlcRefundTimelock,"htlcRefundTimelock"),O(Rn,t),M(An,e.keeperCount,"keeperCount"),M(On,e.challengerCount,"challengerCount"),M(Bn,e.vaultCount,"vaultCount"),N(xn,e.prepeginMaxFee,"prepeginMaxFee")])}function me(e){return st([M(Cn,e.htlcVout,"htlcVout"),O(Ln,Rt(e.vaultProviderPubkey,ot,"vaultProviderPubkey")),N(vn,e.vaultAmount,"vaultAmount"),N(Mn,e.commissionFee,"commissionFee"),N(Nn,e.depositorClaimValue,"depositorClaimValue"),N(Dn,e.peginMaxFee,"peginMaxFee")])}function Te(e,t){const n=(s,i)=>s.map((a,u)=>Rt(a,ot,`${i}[${u}]`)).sort((a,u)=>{for(let l=0;l<ot;l++)if(a[l]!==u[l])return a[l]-u[l];return 0}),r=[...n(e,"keeper").map(s=>O(kn,s)),...n(t,"challenger").map(s=>O($n,s))],o=[];for(let s=0;s<r.length;s+=Vt)o.push(st(r.slice(s,s+Vt)));return o}const A=225,ft=128,Gt=129,Hn=0,Gn=1,Kn=0,Fn=1,Yn=2,W=0,Kt=64,Ft=1024,Yt=10,Xt=32;function Xn(e){return new Uint8Array([e>>8&255,e&255])}function Wn(e){const t=e>>>0;return new Uint8Array([t>>>24&255,t>>>16&255,t>>>8&255,t&255])}function pt(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>Kt)throw new Error(`appName must be 1..${Kt} 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>Yt)throw new Error(`derivationPath must have 1..${Yt} levels`);if(r.length<1||r.length>Ft)throw new Error(`context must be 1..${Ft} bytes, got ${r.length}`);const s=pt([new Uint8Array([o.length]),o,new Uint8Array([n.length]),pt(n.map(Wn)),Xn(r.length)]),i=Math.min(r.length,X-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:Gt,p1:Hn,p2:W,data:pt([s,r.subarray(0,i)])});for(let u=i;u<r.length;u+=X)a=await e({cla:A,ins:Gt,p1:Gn,p2:W,data:r.subarray(u,u+X)});if(a.length!==Xt)throw new Error(`Expected a ${Xt}-byte context root, got ${a.length} bytes`);return a}async function zn(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:ft,p1:Kn,p2:W,data:_e(t)});for(const s of n)await e({cla:A,ins:ft,p1:Fn,p2:W,data:me(s)});for(const s of Te(r,o))await e({cla:A,ins:ft,p1:Yn,p2:W,data:s})}const jn=0,Ie=0,Se=1,Zn=0,qt=33,zt=10,Qn=5,Jn=4;async function tr(e){const t=await e({cla:A,ins:Qn,p1:Ie,p2:Se,data:new Uint8Array(0)});if(t.length!==Jn)throw new Error(`Ledger returned a ${t.length}-byte response instead of the 4-byte master fingerprint`);return Pe(t)}async function ye(e,t,n){if(t.length<1||t.length>zt)throw new Error(`BIP-32 path must have 1..${zt} levels, got ${t.length}`);const r=await e({cla:A,ins:jn,p1:Ie,p2:Se,data:nr(t)}),o=new TextDecoder().decode(r);if(o.length===0)throw new Error("Ledger returned an empty extended key");return ct.HDKey.fromExtendedKey(o,n),o}async function er(e,t,n){const r=await ye(e,t,n),o=ct.HDKey.fromExtendedKey(r,n);if(!o.publicKey||o.publicKey.length!==qt)throw new Error(`Ledger returned an extended key without a ${qt}-byte public key`);return Pe(o.publicKey.subarray(1))}function Pe(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function nr(e){const t=new Uint8Array(2+e.length*4);return t[0]=Zn,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",Ot="LedgerDeviceLockedError",Bt="LedgerDeviceError",xt="LedgerYieldMismatchError",Ct="LedgerSignPsbtIncompleteError",Lt="LedgerSignPsbtProtocolError",vt="LedgerSignPsbtAbortedError";function be(e){return e.toString(16).padStart(4,"0")}class Re extends Error{constructor(n){super(`User rejected the request on the Ledger device (0x${be(n)})`);p(this,"statusWord");this.name=At,this.statusWord=n}}class Ae extends Error{constructor(n){super(`The Ledger device is locked — unlock it and retry (0x${be(n)})`);p(this,"statusWord");this.name=Ot,this.statusWord=n}}class Oe extends Error{constructor(n,r){super(r);p(this,"statusWord");this.name=Bt,this.statusWord=n}}class S 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=xt,this.kind=n,this.inputIndex=r}}class Be 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=Ct,this.missing=n}}function rt(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=Lt,this.detail=n,this.collectedYields=r}}class mt extends Error{constructor(n){super("SIGN_PSBT was abandoned host-side before completion");p(this,"yieldedCount");this.name=vt,this.yieldedCount=n}}function rr(e){return e instanceof Error&&e.name===At}function or(e){return e instanceof Error&&e.name===Bt}function sr(e){return e instanceof Error&&e.name===Ot}function xe(e){return e instanceof Error&&e.name===xt}function ir(e){return e instanceof Error&&e.name===Ct}function Ce(e){return e instanceof Error&&e.name===Lt}function ar(e){return e instanceof Error&&e.name===vt}const cr=36864,ur=new Set([21761,27013]),lr=new Set([21781,27010,21251]),Mt=28160,Le=45063,ve=45066,hr={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",27904:"The running app does not support this instruction",[Mt]:"The running app does not handle vault instructions — open the Babylon Vault app for this network",45056:"The device reported a wrong response length",[Le]:"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",[ve]:"The device has already signed the maximum number of these transactions",28416:"The device reported an internal error"};function D(e){return e.toString(16).padStart(2,"0")}function Me(e){return e.toString(16).padStart(4,"0")}function Ne(e,t){if(e===cr)return;if(ur.has(e))return new Re(e);if(lr.has(e))return new Ae(e);const n=hr[e],r=e===Mt&&t.appName?` (app at connect time: "${t.appName}"${t.appVersion?` v${t.appVersion}`:""})`:"";return new Oe(e,`${n??"The device rejected the request"} (ins 0x${D(t.ins)} p1 0x${D(t.p1)}, sw 0x${Me(e)})${r}`)}function fr(e,t){return async n=>{const{sw:r,data:o}=await e(n),s=Ne(r,{...t,ins:n.ins,p1:n.p1});if(s)throw s;return o}}const jt=2;function pr(e){if(e.statusCode.length!==jt)throw new Error(`The device returned a ${e.statusCode.length}-byte status word; expected ${jt}.`);return e.statusCode[0]<<8|e.statusCode[1]}function J(e,t){if(!Number.isInteger(e)||e<0||e>255)throw new Error(`APDU ${t} ${e} is not a single byte (0..255)`)}function dr(e){if(J(e.cla,"cla"),J(e.ins,"ins"),J(e.p1,"p1"),J(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 De(e){return async t=>{const n=`${D(t.cla)} ${D(t.ins)} ${D(t.p1)} ${D(t.p2)} Lc=${t.data.length}`;let r;try{r=await e.dmk.sendApdu({sessionId:e.sessionId,apdu:dr(t)})}catch(s){throw Zt()&&console.debug(`[ledger-vault] APDU ${n} -> transport error`,s),s}const o=pr(r);return Zt()&&console.debug(`[ledger-vault] APDU ${n} -> sw=0x${Me(o)} len=${r.data.length}`),{sw:o,data:r.data}}}function gr(e){return fr(De(e),{appName:e.appName,appVersion:e.appVersion})}const Er={isRefresherDisabled:!0};let Y,x;function wr(){if(!x){let e=function(n){if(x!==t)throw new Error("connectDmkSession: closeDmk() tore down this DMK while it was still building — retry to connect over a fresh one");return Y=n.dmk,n};const t=(async()=>{const[{DeviceManagementKitBuilder:n},{webHidTransportFactory:r,webHidIdentifier:o}]=await Promise.all([import("@ledgerhq/device-management-kit"),import("@ledgerhq/device-transport-kit-web-hid")]),s=new n().addTransport(r).build();return e({dmk:s,transportIdentifier:o})})().catch(n=>{throw x===t&&(x=void 0),n});x=t}return x}async function _r(){const{dmk:e,transportIdentifier:t}=await wr(),{firstValueFrom:n}=await import("rxjs"),r=await n(e.startDiscovering({transport:t})),o=await e.connect({device:r,sessionRefresherOptions:Er}),s=await mr(e,o);return{dmk:e,sessionId:o,...s}}async function mr(e,t){try{const{GetAppAndVersionCommand:n,isSuccessCommandResult:r}=await import("@ledgerhq/device-management-kit"),o=await e.sendCommand({sessionId:t,command:new n});return r(o)?{appName:o.data.name,appVersion:o.data.version}:{}}catch{return{}}}async function Tr(e){const{firstValueFrom:t}=await import("rxjs");try{return await t(e.dmk.getDeviceSessionState({sessionId:e.sessionId})),!0}catch(n){if((n==null?void 0:n._tag)==="DeviceSessionNotFound")return!1;throw n}}async function Ir(e){try{await e.dmk.disconnect({sessionId:e.sessionId})}catch{}}function Sr(){Y==null||Y.close(),Y=void 0,x=void 0}const yr=2,Pr=3,Qt=32,br=10,Jt=0xffffffffn,te=72,Rr=1008,Ar=4320,Or=91,Br=4031,ke=546n,ee=ke,xr=2n,$e="DepositTermsRejectedError";class T extends Error{constructor(n,r="device-envelope"){super(n);p(this,"reason");this.name=$e,this.reason=r}}const y="Deposit terms outside the device-supported range";function B(e,t,n,r){if(!Number.isInteger(t)||t<n||t>r)throw new T(`${y}: ${e} ${t} not in [${n}, ${r}]`)}function Cr(e){if(B("vaultCoreVersion",e.vaultCoreVersion,yr,Pr),e.protocolFeeRate<1n||e.protocolFeeRate>Jt)throw new T(`${y}: protocolFeeRate ${e.protocolFeeRate} not in [1, ${Jt}]`);if(B("timelockPegin",e.timelockPegin,te,Rr),B("timelockAssert",e.timelockAssert,Or,Br),B("timelockRefund",e.timelockRefund,te,Ar),B("keeper count",e.vaultKeeperBtcPubkeys.length,1,Qt),B("challenger count",e.universalChallengerBtcPubkeys.length,1,Qt),B("vault count",e.vaults.length,1,br),F("prepeginMaxFee",e.prepeginMaxFee),e.prepeginMaxFee<1n)throw new T(`${y}: prepeginMaxFee ${e.prepeginMaxFee} must be >= 1`);let t=-1;for(const a of e.vaults){if(!Number.isInteger(a.htlcVout)||a.htlcVout<0||a.htlcVout>255)throw new T(`${y}: htlcVout ${a.htlcVout} not in [0, 255]`);if(a.htlcVout<=t)throw new T(`${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,u]of[["vaultKeeperBtcPubkeys",e.vaultKeeperBtcPubkeys],["universalChallengerBtcPubkeys",e.universalChallengerBtcPubkeys]])for(const l of u){const f=n(l);if(r.has(f))throw new T(`${y}: ${a} contains the vault provider's own key (${f.slice(0,16)}…)`);if(o.has(f))throw new T(`${y}: duplicate participant key in ${a} (${f.slice(0,16)}…)`);o.add(f)}const s=ke,i=xr*s;for(const a of e.vaults){if(F(`vault ${a.htlcVout} peginAmount`,a.peginAmount),F(`vault ${a.htlcVout} commissionFee`,a.commissionFee),F(`vault ${a.htlcVout} depositorClaimValue`,a.depositorClaimValue),F(`vault ${a.htlcVout} peginMaxFee`,a.peginMaxFee),a.commissionFee<s)throw new T(`${y}: vault ${a.htlcVout} commissionFee ${a.commissionFee} below the ${s}-sat dust limit`);if(a.depositorClaimValue<ee)throw new T(`${y}: vault ${a.htlcVout} depositorClaimValue ${a.depositorClaimValue} below the ${ee}-sat device floor`);if(a.peginAmount<=a.commissionFee+i)throw new T(`${y}: vault ${a.htlcVout} peginAmount ${a.peginAmount} must exceed commissionFee + ${i} (${a.commissionFee+i})`)}}const Lr=(1n<<64n)-1n;function F(e,t){if(t<0n||t>Lr)throw new T(`${y}: ${e} ${t} does not fit in an unsigned 64-bit field`)}const b=2147483648,vr=4294967295,it=86,Ue=0,Ve=1,ne=5,Nt=3,Mr=3,Nr=4;function He(e,t){if(t.length!==ne)throw new Error(`${e} must have exactly ${ne} levels, got ${t.length}`);for(const r of t)if(!Number.isInteger(r)||r<0||r>vr)throw new Error(`${e} levels must be integers in 0..0xffffffff`);if(!t.slice(0,Nt).every(r=>(r&b)!==0)||(t[Nr]&b)!==0)throw new Error(`${e} must harden purpose'/coin'/account' and leave the address index unhardened`);if(t[0]!==(b|it)>>>0)throw new Error(`${e} must use BIP-86 purpose ${it}'`)}function z(e){return"m/"+e.map(t=>(t&b)!==0?`${(t&~b)>>>0}'`:`${t>>>0}`).join("/")}const re=253,Dr=254,kr=65535,$r=4294967295;function Ur(e){if(e<re)return c.Buffer.from([e]);if(e<=kr){const t=c.Buffer.alloc(2);return t.writeUInt16LE(e),c.Buffer.concat([c.Buffer.from([re]),t])}if(e<=$r){const t=c.Buffer.alloc(4);return t.writeUInt32LE(e),c.Buffer.concat([c.Buffer.from([Dr]),t])}throw new Error(`Script too large to encode as CompactSize: ${e} bytes`)}const Vr="TapLeaf";function Hr(e,t){const n=c.Buffer.concat([c.Buffer.from([e]),Ur(t.length),c.Buffer.from(t)]);return _.crypto.taggedHash(Vr,n)}function Gr(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 Kr(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 Fr(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 Yr=BigInt(253),Xr=BigInt(65535)+BigInt(1),Wr=BigInt(4294967295)+BigInt(1);function Ge(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=Yr):n===254?(r=4,o=Xr):(r=8,o=Wr);const s=Kr(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 $(e){typeof e=="number"&&(e=R(e));const t=Fr(e);e=BigInt(e);const n=c.Buffer.alloc(t);return t==1?n[0]=Number(e):(t==3?n[0]=253:t===5?n[0]=254:n[0]=255,Gr(e,t-1,n,1)),n}const qr=31;function Ke(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=c.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>qr)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 C{constructor(){p(this,"bufs",[])}write(t,n){const r=c.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=Ke(t);this.writeSlice(n)}writeVarInt(t){this.bufs.push($(t))}writeSlice(t){this.bufs.push(c.Buffer.from(t))}writeVarSlice(t){this.writeVarInt(t.length),this.writeSlice(t)}buffer(){return c.Buffer.concat(this.bufs)}}class k{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]=Ge(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 It=(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))(It||{});const oe=c.Buffer.from([112,115,98,116,255]),zr=4294967295;class Fe extends Error{}class Ye{constructor(){p(this,"globalMap",new Map);p(this,"inputMaps",[]);p(this,"outputMaps",[])}setGlobalTxVersion(t){this.setGlobal(2,v(t))}getGlobalTxVersion(){return this.getGlobal(2).readUInt32LE(0)}setGlobalFallbackLocktime(t){this.setGlobal(3,v(t))}getGlobalFallbackLocktime(){var t;return(t=this.getGlobalOptional(3))==null?void 0:t.readUInt32LE(0)}setGlobalInputCount(t){this.setGlobal(4,ae(t))}getGlobalInputCount(){return ce(this.getGlobal(4))}setGlobalOutputCount(t){this.setGlobal(5,ae(t))}getGlobalOutputCount(){return ce(this.getGlobal(5))}setGlobalTxModifiable(t){this.setGlobal(6,t)}getGlobalTxModifiable(){return this.getGlobalOptional(6)}setGlobalPsbtVersion(t){this.setGlobal(251,v(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 C;o.writeSlice(ie(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 k(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(),v(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(),v(n))}getInputOutputIndex(t){return this.getInput(t,15,w()).readUInt32LE(0)}setInputSequence(t,n){this.setInput(t,16,w(),v(n))}getInputSequence(t){var n;return((n=this.getInputOptional(t,16,w()))==null?void 0:n.readUInt32LE(0))??zr}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:c.Buffer.from(i.substring(2),"hex"),value:c.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(),ie(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,c.Buffer.from(r)))}serialize(){const t=new C;return t.writeSlice(oe),gt(t,this.globalMap),this.inputMaps.forEach(n=>{gt(t,n)}),this.outputMaps.forEach(n=>{gt(t,n)}),t.buffer()}deserialize(t){const n=new k(t);if(!n.readSlice(5).equals(oe))throw new Error("Invalid magic bytes");for(;this.readKeyPair(this.globalMap,n););let r;try{r=this.getGlobalPsbtVersion()}catch(i){if(!(i instanceof Fe))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(c.Buffer.from(s.substring(2),"hex"))}),r}isKeyType(t,n){const r=c.Buffer.from(t.substring(0,2),"hex").readUInt8(0);return n.some(o=>o===r)}setGlobal(t,n){const r=new U(t,c.Buffer.from([]));this.globalMap.set(r.toString(),n)}getGlobal(t){return dt(this.globalMap,t,w())}getGlobalOptional(t){return St(this.globalMap,t,w())}setInput(t,n,r,o){se(this.getMap(t,this.inputMaps),n,r,o)}getInput(t,n,r){return dt(this.inputMaps[t],n,r)}getInputOptional(t,n,r){return St(this.inputMaps[t],n,r)}setOutput(t,n,r,o){se(this.getMap(t,this.outputMaps),n,r,o)}getOutput(t,n,r){return dt(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 C;return this.writeBip32Derivation(r,t,n),r.buffer()}decodeBip32Derivation(t){const n=new k(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 C;return o.writeVarInt(t.length),t.forEach(s=>{o.writeSlice(s)}),this.writeBip32Derivation(o,n,r),o.buffer()}decodeTapBip32Derivation(t){const n=new k(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 dt(e,t,n){const r=St(e,t,n);if(r===void 0)throw new Fe(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 c.Buffer.from(o)}class U{constructor(t,n){p(this,"keyType");p(this,"keyData");this.keyType=t,this.keyData=n}toString(){const t=new C;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 jr{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 Zr(e){return new U(e.readUInt8(0),e.subarray(1))}function gt(e,t){const n=[...t].sort(([r],[o])=>r<o?-1:r>o?1:0);for(const[r,o]of n)new jr(Zr(c.Buffer.from(r,"hex")),o).serialize(e);e.writeUInt8(0)}function w(){return c.Buffer.from([])}function se(e,t,n,r){const o=new U(t,n);e.set(o.toString(),r)}function v(e){const t=c.Buffer.alloc(4);return t.writeUInt32LE(e,0),t}function ie(e){return Ke(e)}function ae(e){const t=new C;return t.writeVarInt(e),t.buffer()}function ce(e){return R(new k(e).readVarInt())}const ue=192,yt=32,le=2,tt=33,et=32,Qr=1,Jr="TapBranch",to="TapTweak",he=64,fe=32,Et=64,eo=34,at=c.Buffer.from([81,32]),no=c.Buffer.from([0,20]),ro=2,oo=3;function Dt(e){_.initEccLib(_t);const t=_.payments.p2tr({internalPubkey:c.Buffer.from(e,"hex")}).output;if(!t)throw new d("p2tr produced no output script for the depositor key");return t}function pe(e,t){const n=c.Buffer.concat([c.Buffer.from([t]),c.Buffer.from(e,"hex")]);return c.Buffer.concat([no,_.crypto.hash160(n)])}function Xe(e){return e.length===eo&&e.subarray(0,at.length).equals(at)}function so(e,t,n,r){if(!Xe(r))throw new d(`input ${e} is tapscript but its witnessUtxo script is not P2TR`);const o=t.length-tt;if(o<0||o%et!==0)throw new d(`input ${e} control block length ${t.length} is not ${tt} plus a multiple of ${et}`);const s=t.subarray(1,tt);if(!_t.isXOnlyPoint(s))throw new d(`input ${e} control block internal key is not an x-only point`);let i=n;for(let f=tt;f<t.length;f+=et){const g=t.subarray(f,f+et),h=c.Buffer.compare(i,g)<0?[i,g]:[g,i];i=_.crypto.taggedHash(Jr,c.Buffer.concat(h))}const a=_.crypto.taggedHash(to,c.Buffer.concat([s,i])),u=_t.xOnlyPointAddTweak(s,a);if(!u)throw new d(`input ${e} control block internal key has no taproot output key`);if(!r.subarray(at.length).equals(c.Buffer.from(u.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(u.parity!==(t[0]&Qr))throw new d(`input ${e} control block parity bit disagrees with the recomputed taproot output key`)}function io(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),u=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=Dt(n),f=[pe(n,ro),pe(n,oo)];for(let h=0;h<i;h++){const E=t.getInputEntriesOfType(h,It.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 m=E[0].value;if(m.length<le)throw new d(`input ${h} TAP_LEAF_SCRIPT value length ${m.length} is below the ${le}-byte minimum (script byte plus the leaf-version byte)`);const G=m[m.length-1];if(G!==ue)throw new d(`input ${h} leaf version 0x${G.toString(16)} is not tapscript (0xc0)`);const L=t.getInputWitnessUtxo(h);if(!L)throw new d(`input ${h} is tapscript but has no witnessUtxo`);const Z=m.subarray(0,m.length-1),$t=Hr(ue,Z);so(h,E[0].keyData,$t,L.scriptPubKey);const Ut={kind:"tapscript",expectedLeafHashHexes:new Set([$t.toString("hex")]),expectedSignerXOnlyHex:n};s.set(h,Ut),u(h)&&o.set(h,Ut);continue}const P=t.getInputEntriesOfType(h,It.TAP_INTERNAL_KEY);if(P.length>0){const m=P[0];if(P.length>1||m.keyData.length!==0||m.value.length!==yt)throw new d(`input ${h} carries a malformed TAP_INTERNAL_KEY entry`);if(m.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 L=G.scriptPubKey;if(!Xe(L))throw new d(`input ${h} witnessUtxo script is not P2TR`);if(!L.equals(l))throw new d(`input ${h} witnessUtxo is not the BIP-86 P2TR of the depositor key`);const Z={kind:"taproot-keypath",expectedOutputKeyHex:L.subarray(at.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(m=>lt.scriptPubKey.equals(m))))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 nt(e){return e.kind==="tapscript"?`${e.inputIndex}:${e.leafHashHex}`:`${e.inputIndex}`}function de(e,t){if(e<Et)throw new d(`YIELD payload truncated inside the signature (${e} of ${Et} bytes on input ${t})`);if(e!==Et)throw new S("non-default-sighash",t)}function ao(e){const t=[],n=new Set;return{assertAndRecord:s=>{let i,a;try{const[f,g]=Ge(s,0);i=R(f),a=g}catch(f){throw new d(`unparseable YIELD payload: ${f instanceof Error?f.message:String(f)}`)}const u=s[a];if(u===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 S("unexpected-input",i);if(u===he){if(l.kind!=="tapscript")throw new S("wrong-spend-type",i);const f=a+1+he;if(s.length<f)throw new d("YIELD payload truncated inside the augmented pubkey");const g=s.subarray(a+1,a+1+yt).toString("hex"),h=s.subarray(a+1+yt,f).toString("hex"),E=s.subarray(f);if(g!==l.expectedSignerXOnlyHex)throw new S("wrong-signer-key",i);if(!l.expectedLeafHashHexes.has(h))throw new S("unknown-leaf-hash",i);de(E.length,i);const P={kind:"tapscript",inputIndex:i,signerXOnlyHex:g,leafHashHex:h,signature:Uint8Array.from(E)};if(n.has(nt(P)))throw new S("duplicate-yield",i);n.add(nt(P)),t.push(P);return}if(u===fe){if(l.kind!=="taproot-keypath")throw new S("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,f).toString("hex"),h=s.subarray(f);if(g!==l.expectedOutputKeyHex)throw new S("wrong-signer-key",i);de(h.length,i);const E={kind:"taproot-keypath",inputIndex:i,outputKeyHex:g,signature:Uint8Array.from(h)};if(n.has(nt(E)))throw new S("duplicate-yield",i);n.add(nt(E)),t.push(E);return}throw new S("unexpected-encoding",i)},get yields(){return t},get lastYield(){return t[t.length-1]},assertComplete:()=>{const s=new Set;for(const[u,l]of e.byInput)if(l.kind==="tapscript")for(const f of l.expectedLeafHashHexes)s.add(`${u}:${f}`);else s.add(`${u}`);const i=[...s].filter(u=>!n.has(u)),a=[...n].some(u=>!s.has(u));if(i.length>0||a||n.size!==e.expectedYieldCount)throw new Be(i)}}}const We=/^[0-9a-f]{64}$/;function co(e,t){if(He("depositorPath",e),e[Mr]!==Ue)throw new Error("depositorPath must use BIP-86 receive branch 0");for(let n=0;n<Nt;n++)if(e[n]!==t[n])throw new Error(`depositorPath ${z(e)} is not under the wallet policy's key origin ${z(t)} — the device could never mark the input internal`)}function qe(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=ct.HDKey.fromExtendedKey(e,t).deriveChild(n).deriveChild(r);if(!o.publicKey)throw new Error(`account xpub derived no public key at ${n}/${r}`);return c.Buffer.from(o.publicKey.subarray(1)).toString("hex")}function ze(e,t,n){return qe(e,t,Ve,n)}function uo(e,t,n){return qe(e,t,Ue,n)}function je(e,t){const n=Dt(t);return e.txOutputs.flatMap((r,o)=>c.Buffer.from(r.script).equals(n)?[o]:[])}function lo(e,t){if(!We.test(t))throw new Error("changeXOnlyHex must be 64 lowercase hex characters");return je(_.Psbt.fromHex(e),t).length>0}function ho(e){const{psbtHex:t,depositorXOnlyHex:n,walletPolicy:r,depositorPath:o,change:s}=e;if(!We.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");co(o,r.keyOriginPath);const i=_.Psbt.fromHex(t),a=c.Buffer.from(r.masterFingerprintHex,"hex"),u=c.Buffer.from(n,"hex");let l=0;if(i.data.inputs.forEach((f,g)=>{f.tapInternalKey&&c.Buffer.from(f.tapInternalKey).equals(u)&&(l++,i.updateInput(g,{tapBip32Derivation:[{masterFingerprint:a,pubkey:u,path:z(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=ze(r.accountXpub,r.bip32Versions,s.addressIndex),g=[...o.slice(0,Nt),Ve,s.addressIndex],h=c.Buffer.from(f,"hex"),E=je(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 P of E)i.updateOutput(P,{tapInternalKey:h,tapBip32Derivation:[{masterFingerprint:a,pubkey:h,path:z(g),leafHashes:[]}]})}return i.toHex()}const fo="BIP0322-signed-message",po=new Uint8Array([252,6,98,118,97,117,108,116,0]),Ze=0,Qe=0,Je=0,go=0,Pt=0,Eo=c.Buffer.from([106]),wo=/^[0-9a-f]{64}$/,_o=/^[0-9a-f]{8}$/,mo=c.Buffer.alloc(32,0),To=4294967295,Io=c.Buffer.from([0,32]),So=c.Buffer.from([81,32]),yo=2;function Po(e,t){const n=_.crypto.sha256(c.Buffer.from(e,"utf8"));return _.crypto.sha256(c.Buffer.concat([n,n,c.Buffer.from(t)]))}function bo(e,t){const n=new _.Transaction;n.version=Ze,n.locktime=Qe;const r=c.Buffer.concat([Io,Po(fo,e)]);return n.addInput(mo,To,Je,r),n.addOutput(c.Buffer.concat([So,c.Buffer.from(t)]),Pt),Uint8Array.from(n.getHash(!1))}function Ro(e){const{message:t,depositorXOnlyHex:n,masterFingerprintHex:r,depositorPath:o}=e;if(!wo.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");if(!_o.test(r))throw new Error("masterFingerprintHex must be 8 lowercase hex characters");He("depositorPath",o);const s=new TextEncoder().encode(t),i=c.Buffer.from(n,"hex"),a=Dt(n),u=bo(s,a.subarray(yo)),l=new _.Psbt;return l.setVersion(Ze),l.setLocktime(Qe),l.addInput({hash:c.Buffer.from(u),index:go,sequence:Je,witnessUtxo:{script:a,value:Pt},tapInternalKey:i,tapBip32Derivation:[{masterFingerprint:c.Buffer.from(r,"hex"),pubkey:i,path:z(o),leafHashes:[]}]}),l.addOutput({script:Eo,value:Pt}),l.addUnknownKeyValToGlobal({key:c.Buffer.from(po),value:c.Buffer.from(s)}),l.toHex()}class V{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 wt(void 0,void 0,c.Buffer.alloc(32,0)),leaves:[]};if(n==1){const f=new wt(void 0,void 0,t[0]);return{root:f,leaves:[f]}}const r=Oo(n),o=this.calculateRoot(t.slice(0,r)),s=this.calculateRoot(t.slice(r)),i=o.root,a=s.root,u=this.hashNode(i.hash,a.hash),l=new wt(i,a,u);return i.parent=l,a.parent=l,{root:l,leaves:o.leaves.concat(s.leaves)}}hashNode(t,n){return this.h(c.Buffer.concat([c.Buffer.from([1]),t,n]))}}function H(e,t=_.crypto.sha256){return Ao(c.Buffer.from([0]),e,t)}function Ao(e,t,n){return n(c.Buffer.concat([e,t]))}class wt{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 Oo(e){if(e<2)throw Error("Expected n >= 2");return Bo(e)?e/2:1<<Math.floor(Math.log2(e))}function Bo(e){return(e&e-1)==0}const kt=255,xo=2,I=32;class j{}class Co extends j{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=c.Buffer.from(n.subarray(1));return this.onYield&&this.onYield(c.Buffer.from(r)),this.results.push(r),this.progressCallback&&this.progressCallback(),c.Buffer.from("")}}class Lo extends j{constructor(n,r){super();p(this,"knownPreimages");p(this,"queue");p(this,"code",64);this.knownPreimages=n,this.queue=r}execute(n){const r=c.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=c.Buffer.from(r.subarray(1,1+I)).toString("hex"),i=this.knownPreimages.get(s);if(i!==void 0){const a=$(i.length),u=kt-a.length-1,l=Math.min(u,i.length);if(l<i.length)for(let f=l;f<i.length;f++)this.queue.push(c.Buffer.from(i.subarray(f,f+1)));return c.Buffer.concat([a,c.Buffer.from([l]),c.Buffer.from(i.subarray(0,l))])}throw new Error(`Requested unknown preimage for: ${s}`)}}class vo extends j{constructor(n,r){super();p(this,"knownTrees");p(this,"queue");p(this,"code",65);this.knownTrees=n,this.queue=r}execute(n){const r=c.Buffer.from(n.subarray(1));if(r.length<I+1+1)throw new Error("Invalid request, expected at least 34 bytes");const o=new k(r),i=o.readSlice(I).toString("hex");let a,u;try{a=R(o.readVarInt()),u=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(u>=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(u),g=Math.min(Math.floor((kt-I-1-1)/I),f.length),h=f.length-g;return h>0&&this.queue.push(...f.slice(-h)),c.Buffer.concat([l.getLeafHash(u),c.Buffer.from([f.length]),c.Buffer.from([g]),...f.slice(0,g)])}}class Mo extends j{constructor(n){super();p(this,"knownTrees");p(this,"code",66);this.knownTrees=n}execute(n){const r=c.Buffer.from(n.subarray(1));if(r.length!==I+I)throw new Error("Invalid request, unexpected trailing data");const s=c.Buffer.from(r.subarray(0,I)).toString("hex"),a=c.Buffer.from(r.subarray(I,I+I)).toString("hex"),u=this.knownTrees.get(s);if(!u)throw new Error(`Requested Merkle leaf index for unknown root: ${s}`);let l=0,f=0;for(let g=0;g<u.size();g++)if(u.getLeafHash(g).toString("hex")===a){f=1,l=g;break}return c.Buffer.concat([c.Buffer.from([f]),$(l)])}}class No extends j{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(u=>u.length!==o))throw new Error("The queue contains elements with different byte length, which is not expected");const s=Math.floor((kt-xo)/o),i=Math.min(s,this.queue.length),a=this.queue.splice(0,i);return c.Buffer.concat([c.Buffer.from([i]),c.Buffer.from([o]),...a])}}class Do{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 Co(this.yielded,t,n),new Lo(this.preimages,this.queue),new Mo(this.roots),new vo(this.roots,this.queue),new No(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=c.Buffer.concat([c.Buffer.from([0]),r]);this.addKnownPreimage(o)}const n=new V(t.map(r=>H(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=>c.Buffer.from(n,"ascii"))),this.addKnownPreimage(c.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 ko{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 V(t.map(r=>H(r))),this.values=n,this.valuesTree=new V(n.map(r=>H(r)))}commitment(){return c.Buffer.concat([$(this.keys.length),this.keysTree.getRoot(),this.valuesTree.getRoot()])}}class q extends Ye{constructor(n){super();p(this,"globalMerkleMap");p(this,"inputMerkleMaps",[]);p(this,"outputMerkleMaps",[]);p(this,"inputMapCommitments");p(this,"outputMapCommitments");n.copy(this),this.globalMerkleMap=q.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(q.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(q.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=>c.Buffer.from(i,"hex"));return new ko(s,o)}}const $o=2;class Uo{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=>c.Buffer.from(o,"ascii")),n=new V(t.map(o=>H(o))),r=new C;return r.writeUInt8($o),r.writeVarSlice(c.Buffer.from(this.name,"ascii")),r.writeVarInt(this.descriptorTemplate.length),r.writeSlice(_.crypto.sha256(c.Buffer.from(this.descriptorTemplate))),r.writeVarInt(this.keys.length),r.writeSlice(n.getRoot()),r.buffer()}}class tn extends Uo{constructor(t,n){super("",t,[n])}}const Vo=4,Ho=0,Go=1,en=32,Ko=new Uint8Array(en),Fo=new Uint8Array(en),Yo=/^[0-9a-f]{64}$/,Xo=/^(?:[0-9a-fA-F]{2})+$/,Wo=/^[0-9a-f]{64}$/;function qo(e,t){const n=new V(e.inputMapCommitments.map(o=>H(o))).getRoot(),r=new V(e.outputMapCommitments.map(o=>H(o))).getRoot();return Uint8Array.from(c.Buffer.concat([e.getGlobalKeysValuesRoot(),$(e.getGlobalInputCount()),n,$(e.getGlobalOutputCount()),r,c.Buffer.from(t),c.Buffer.from(Fo)]))}function zo(e){return{cla:A,ins:Vo,p1:Ho,p2:Go,data:e}}const jo=0;function Zo(e,t){for(const[n]of t.byInput){const r=e.data.inputs[n].sighashType;if(r!==void 0&&r!==jo)throw new d(`input ${n} requests sighash type ${r}, but vault flows sign SIGHASH_DEFAULT only`)}}function Qo(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 nn=new WeakMap;function Jo(e,t){const n={...e};return nn.set(n,t),n}function rn(e){const t=nn.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(!Yo.test(n))throw new d("depositorXOnlyHex must be 64 lowercase hex characters");let s;if(o!==void 0){if(!Wo.test(o.walletIdHex))throw new d("walletPolicy.walletIdHex must be 64 lowercase hex characters");if(s=new tn(o.descriptorTemplate,o.keyInfo),s.getId().toString("hex")!==o.walletIdHex)throw new d("walletPolicy.walletIdHex does not match sha256 of the serialized policy")}if(!Xo.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 Ye;try{a.deserialize(c.Buffer.from(t,"hex"))}catch(E){throw new d(`PSBT rejected at parse: ${E instanceof Error?E.message:String(E)}`)}let u,l;try{u=new q(a),l=io({psbt:u,depositorXOnlyHex:n,signInputIndexes:r})}catch(E){throw E instanceof d?E:new d(`PSBT rejected at preflight: ${E instanceof Error?E.message:String(E)}`)}Qo(i,l),Zo(i,l);const f=ao(l),g=new Do(void 0,E=>f.assertAndRecord(E));g.addKnownMapping(u.globalMerkleMap);for(const E of u.inputMerkleMaps)g.addKnownMapping(E);for(const E of u.outputMerkleMaps)g.addKnownMapping(E);g.addKnownList(u.inputMapCommitments),g.addKnownList(u.outputMapCommitments);const h=o?c.Buffer.from(o.walletIdHex,"hex"):Ko;return s&&g.addKnownWalletPolicy(s),Jo({table:l,unsignedTxid:_.Transaction.fromBuffer(i.data.globalMap.unsignedTx.toBuffer()).getId()},{cdata:qo(u,h),interpreter:g,collector:f,originalPsbtHex:t,signsUnderWalletPolicy:o!==void 0})}const ts=248,es=1,ns=0,rs=0,os=36864,ss=57344;async function is(e,t,n){const{collector:r,interpreter:o,cdata:s}=rn(t),{table:i}=t;if(n.signal.aborted)throw new mt(r.yields.length);const a=zo(s);let u=a,l=await e(a),f=0;for(;l.sw===ss;){let g;try{g=o.execute(c.Buffer.from(l.data))}catch(h){throw xe(h)?h:Ce(h)?new d(h.detail,rt(r.yields)):new d(`client command failed: ${h instanceof Error?h.message:String(h)}`,rt(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 mt(r.yields.length);u={cla:ts,ins:es,p1:ns,p2:rs,data:g},l=await e(u)}if(l.sw!==os){const g=Ne(l.sw,{...n.appIdentity,ins:u.ins,p1:u.p1});throw g===void 0?new d(`status word 0x${l.sw.toString(16)} escaped classification`,rt(r.yields)):g}return r.assertComplete(),r.yields}function as(e,t){const n=_.Psbt.fromHex(e);for(const r of t)r.kind==="tapscript"?n.updateInput(r.inputIndex,{tapScriptSig:[{pubkey:c.Buffer.from(r.signerXOnlyHex,"hex"),leafHash:c.Buffer.from(r.leafHashHex,"hex"),signature:c.Buffer.from(r.signature)}]}):n.updateInput(r.inputIndex,{tapKeySig:c.Buffer.from(r.signature)});return n.toHex()}const ge=new WeakSet;async function sn(e,t,n){const{originalPsbtHex:r,signsUnderWalletPolicy:o}=rn(t);if(ge.has(t))throw new d("prepared signing state was already used — call prepareSignPsbt again for a retry");if([...t.table.byInput.values()].some(u=>u.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");ge.add(t);const i=await is(e,t,n);let a;try{a=as(r,i)}catch(u){throw new d(`merge failed after signing: ${u instanceof Error?u.message:String(u)}`,rt(i))}return{signedPsbtHex:a,yields:[...i]}}async function cs(e,t){const{psbtHex:n,depositorXOnlyHex:r,signInputIndexes:o,...s}=t,i=on({psbtHex:n,depositorXOnlyHex:r,signInputIndexes:o});return sn(e,i,s)}const Ee="tr(@0/**)",we=2147483647,us=/^[0-9a-f]{8}$/;function ls(e){const{masterFingerprintHex:t,coinType:n,accountIndex:r,accountXpub:o,bip32Versions:s}=e;if(!us.test(t))throw new Error("masterFingerprintHex must be 8 lowercase hex characters");if(!Number.isInteger(n)||n<0||n>we||!Number.isInteger(r)||r<0||r>we)throw new Error("coinType and accountIndex must be non-negative integers in 0..0x7fffffff");try{ct.HDKey.fromExtendedKey(o,s)}catch(u){throw new Error(`accountXpub is not a valid extended key for this network: ${u instanceof Error?u.message:String(u)}`)}const i=`[${t}/${it}'/${n}'/${r}']${o}`,a=new tn(Ee,i).getId().toString("hex");return{descriptorTemplate:Ee,keyInfo:i,walletIdHex:a,accountXpub:o,bip32Versions:s,keyOriginPath:[(b|it)>>>0,(b|n)>>>0,(b|r)>>>0],masterFingerprintHex:t}}exports.DEPOSIT_TERMS_REJECTED_ERROR_NAME=$e;exports.DepositTermsRejectedError=T;exports.LEDGER_DEVICE_ERROR_NAME=Bt;exports.LEDGER_DEVICE_LOCKED_ERROR_NAME=Ot;exports.LEDGER_SIGN_PSBT_ABORTED_ERROR_NAME=vt;exports.LEDGER_SIGN_PSBT_INCOMPLETE_ERROR_NAME=Ct;exports.LEDGER_SIGN_PSBT_PROTOCOL_ERROR_NAME=Lt;exports.LEDGER_USER_REFUSED_ERROR_NAME=At;exports.LEDGER_YIELD_MISMATCH_ERROR_NAME=xt;exports.LedgerDeviceError=Oe;exports.LedgerDeviceLockedError=Ae;exports.LedgerSignPsbtAbortedError=mt;exports.LedgerSignPsbtIncompleteError=Be;exports.LedgerSignPsbtProtocolError=d;exports.LedgerUserRefusedError=Re;exports.LedgerYieldMismatchError=S;exports.SW_BAD_STATE=Le;exports.SW_CAP_EXCEEDED=ve;exports.SW_CLA_NOT_SUPPORTED=Mt;exports.approveVaultIntent=zn;exports.assertDepositTermsDeviceCompatible=Cr;exports.augmentPsbtForWalletPolicy=ho;exports.buildDefaultTaprootPolicy=ls;exports.buildPopPsbtHex=Ro;exports.closeDmk=Sr;exports.connectDmkSession=_r;exports.createDmkApduSender=gr;exports.createDmkRawApduSender=De;exports.deriveChangeXOnlyHex=ze;exports.deriveContextHash=qn;exports.deriveReceiveXOnlyHex=uo;exports.disconnectDmkSession=Ir;exports.encodeIntentGroup=me;exports.encodeIntentScalars=_e;exports.encodeKeyBatches=Te;exports.getExtendedPublicKey=ye;exports.getMasterFingerprintHex=tr;exports.getXOnlyPublicKeyHex=er;exports.isLedgerDeviceError=or;exports.isLedgerDeviceLockedError=sr;exports.isLedgerSignPsbtAbortedError=ar;exports.isLedgerSignPsbtIncompleteError=ir;exports.isLedgerSignPsbtProtocolError=Ce;exports.isLedgerUserRefusedError=rr;exports.isLedgerYieldMismatchError=xe;exports.isSessionAlive=Tr;exports.prepareSignPsbt=on;exports.psbtPaysChangeScript=lo;exports.signPreparedVaultPsbt=sn;exports.signVaultPsbt=cs;
2
2
  //# sourceMappingURL=index.cjs.map