@babylonlabs-io/ledger-vault-signer 0.6.0 → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/deviceCaps.d.ts +7 -0
- package/dist/deviceCaps.d.ts.map +1 -1
- package/dist/envelope.d.ts.map +1 -1
- package/dist/errors.d.ts +9 -18
- package/dist/errors.d.ts.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +346 -350
- package/dist/index.js.map +1 -1
- package/dist/rawApdu.d.ts.map +1 -1
- package/dist/signPsbt.d.ts +0 -6
- package/dist/signPsbt.d.ts.map +1 -1
- package/dist/signPsbtLoop.d.ts +0 -8
- package/dist/signPsbtLoop.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/deviceCaps.d.ts
CHANGED
|
@@ -9,6 +9,13 @@
|
|
|
9
9
|
*
|
|
10
10
|
* @module ledger-vault-signer/deviceCaps
|
|
11
11
|
*/
|
|
12
|
+
/**
|
|
13
|
+
* Vault-core (tx-graph) versions the device can sign: v2 is the firmware's
|
|
14
|
+
* Core-2 tx shape; v3 is byte-identical (btc-vault e1e50f66; SDK parity vector
|
|
15
|
+
* pegin.test.ts). Widen only on evidence a future version is device-compatible.
|
|
16
|
+
*/
|
|
17
|
+
export declare const DEVICE_MIN_VAULT_CORE_VERSION = 2;
|
|
18
|
+
export declare const DEVICE_MAX_VAULT_CORE_VERSION = 3;
|
|
12
19
|
/**
|
|
13
20
|
* Keeper and universal-challenger counts, each `[1, 32]` (`vault_intent.h:8-9`,
|
|
14
21
|
* checked `vault_tlv.c:130,137`). Far below the protocol: the contract allows
|
package/dist/deviceCaps.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"deviceCaps.d.ts","sourceRoot":"","sources":["../src/deviceCaps.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH;;;;GAIG;AACH,eAAO,MAAM,gCAAgC,KAAK,CAAC;AAEnD;;;;GAIG;AACH,eAAO,MAAM,4BAA4B,KAAK,CAAC;AAE/C;;;;GAIG;AACH,eAAO,MAAM,mCAAmC,cAAc,CAAC;AAE/D,iFAAiF;AACjF,eAAO,MAAM,0BAA0B,KAAK,CAAC;AAE7C,gFAAgF;AAChF,eAAO,MAAM,oCAAoC,OAAO,CAAC;AAEzD,kFAAkF;AAClF,eAAO,MAAM,iCAAiC,OAAO,CAAC;AAEtD;;;;GAIG;AACH,eAAO,MAAM,iCAAiC,KAAK,CAAC;AACpD,eAAO,MAAM,iCAAiC,OAAO,CAAC;AAEtD;;;;GAIG;AACH,eAAO,MAAM,4BAA4B,OAAO,CAAC;AAEjD;;;;GAIG;AACH,eAAO,MAAM,qCAAqC,OAA+B,CAAC;AAElF;;;;GAIG;AACH,eAAO,MAAM,iCAAiC,KAAK,CAAC"}
|
|
1
|
+
{"version":3,"file":"deviceCaps.d.ts","sourceRoot":"","sources":["../src/deviceCaps.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH;;;;GAIG;AACH,eAAO,MAAM,6BAA6B,IAAI,CAAC;AAC/C,eAAO,MAAM,6BAA6B,IAAI,CAAC;AAE/C;;;;GAIG;AACH,eAAO,MAAM,gCAAgC,KAAK,CAAC;AAEnD;;;;GAIG;AACH,eAAO,MAAM,4BAA4B,KAAK,CAAC;AAE/C;;;;GAIG;AACH,eAAO,MAAM,mCAAmC,cAAc,CAAC;AAE/D,iFAAiF;AACjF,eAAO,MAAM,0BAA0B,KAAK,CAAC;AAE7C,gFAAgF;AAChF,eAAO,MAAM,oCAAoC,OAAO,CAAC;AAEzD,kFAAkF;AAClF,eAAO,MAAM,iCAAiC,OAAO,CAAC;AAEtD;;;;GAIG;AACH,eAAO,MAAM,iCAAiC,KAAK,CAAC;AACpD,eAAO,MAAM,iCAAiC,OAAO,CAAC;AAEtD;;;;GAIG;AACH,eAAO,MAAM,4BAA4B,OAAO,CAAC;AAEjD;;;;GAIG;AACH,eAAO,MAAM,qCAAqC,OAA+B,CAAC;AAElF;;;;GAIG;AACH,eAAO,MAAM,iCAAiC,KAAK,CAAC"}
|
package/dist/envelope.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"envelope.d.ts","sourceRoot":"","sources":["../src/envelope.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;
|
|
1
|
+
{"version":3,"file":"envelope.d.ts","sourceRoot":"","sources":["../src/envelope.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAiBH,OAAO,EAA6B,KAAK,YAAY,EAAE,MAAM,SAAS,CAAC;AAUvE;;;;GAIG;AACH,wBAAgB,kCAAkC,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI,CAkI5E"}
|
package/dist/errors.d.ts
CHANGED
|
@@ -106,31 +106,22 @@ export declare class LedgerSignPsbtProtocolError extends Error {
|
|
|
106
106
|
}
|
|
107
107
|
/**
|
|
108
108
|
* The host abandoned the SIGN_PSBT loop (abort signal) — the loop stops
|
|
109
|
-
* sending, nothing else.
|
|
110
|
-
*
|
|
111
|
-
*
|
|
109
|
+
* sending, nothing else. Retry after this is always a FULL re-ceremony (the
|
|
110
|
+
* provider resets its mirror to idle). Device aftermath (verified at base app
|
|
111
|
+
* rev `e400d8d8` + fw `90cf41f`):
|
|
112
112
|
*
|
|
113
113
|
* - Within ~5 s (50 ticks, `base:io_ext.h:28`) the device sits blocked
|
|
114
|
-
* awaiting CONTINUE
|
|
115
|
-
*
|
|
116
|
-
*
|
|
117
|
-
* - A validation-phase abandonment leaves the intent intact; a Payout/NoPayout
|
|
118
|
-
* SIGNING-phase abandonment invalidates it (`fw:sign_custom_inputs.c:207-344`)
|
|
119
|
-
* — post-abort "intent-loaded" is a HINT only, and the retry path must also
|
|
120
|
-
* absorb 0xB007.
|
|
114
|
+
* awaiting CONTINUE and eats the next non-CONTINUE APDU with 0x6A80
|
|
115
|
+
* (`base:dispatcher.c:107-111`) — a fast retry's first DERIVE APDU surfaces
|
|
116
|
+
* as the generic invalid-data error; the second attempt is clean.
|
|
121
117
|
* - After >5 s of host silence the app exits to the dashboard
|
|
122
|
-
* (`base:io_ext.c:103-111` → SDK `app_exit()`); the host then sees 0x6E00
|
|
123
|
-
*
|
|
118
|
+
* (`base:io_ext.c:103-111` → SDK `app_exit()`); the host then sees 0x6E00,
|
|
119
|
+
* whose wrong-app copy guides reopening the app.
|
|
124
120
|
*/
|
|
125
121
|
export declare class LedgerSignPsbtAbortedError extends Error {
|
|
126
122
|
/** Yields the device had already delivered when the host stopped sending. */
|
|
127
123
|
readonly yieldedCount: number;
|
|
128
|
-
|
|
129
|
-
* True only when the abort left a dispatcher mid-interruption (device
|
|
130
|
-
* awaiting CONTINUE) — the one state the resend-once recovery exists for.
|
|
131
|
-
*/
|
|
132
|
-
readonly dispatcherInterrupted: boolean;
|
|
133
|
-
constructor(yieldedCount: number, dispatcherInterrupted: boolean);
|
|
124
|
+
constructor(yieldedCount: number);
|
|
134
125
|
}
|
|
135
126
|
export declare function isLedgerUserRefusedError(error: unknown): error is LedgerUserRefusedError;
|
|
136
127
|
export declare function isLedgerDeviceError(error: unknown): error is LedgerDeviceError;
|
package/dist/errors.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,eAAO,MAAM,8BAA8B,2BAA2B,CAAC;AACvE,eAAO,MAAM,+BAA+B,4BAA4B,CAAC;AACzE,eAAO,MAAM,wBAAwB,sBAAsB,CAAC;AAC5D,eAAO,MAAM,gCAAgC,6BAA6B,CAAC;AAC3E,eAAO,MAAM,sCAAsC,kCAAkC,CAAC;AACtF,eAAO,MAAM,oCAAoC,gCAAgC,CAAC;AAClF,eAAO,MAAM,mCAAmC,+BAA+B,CAAC;AAMhF;;;;;GAKG;AACH,qBAAa,sBAAuB,SAAQ,KAAK;IAC/C,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;gBAEhB,UAAU,EAAE,MAAM;CAK/B;AAED,+DAA+D;AAC/D,qBAAa,uBAAwB,SAAQ,KAAK;IAChD,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;gBAEhB,UAAU,EAAE,MAAM;CAK/B;AAED;;;;GAIG;AACH,qBAAa,iBAAkB,SAAQ,KAAK;IAC1C,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;gBAEhB,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM;CAKhD;AAED,MAAM,MAAM,uBAAuB,GAC/B,kBAAkB,GAClB,kBAAkB,GAClB,kBAAkB,GAClB,mBAAmB,GACnB,qBAAqB,GACrB,iBAAiB,GACjB,qBAAqB,CAAC;AAE1B;;;;;;GAMG;AACH,qBAAa,wBAAyB,SAAQ,KAAK;IACjD,QAAQ,CAAC,IAAI,EAAE,uBAAuB,CAAC;IACvC,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;gBAEjB,IAAI,EAAE,uBAAuB,EAAE,UAAU,CAAC,EAAE,MAAM;CAS/D;AAED;;;;GAIG;AACH,qBAAa,6BAA8B,SAAQ,KAAK;IACtD,mFAAmF;IACnF,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;gBAExB,OAAO,EAAE,SAAS,MAAM,EAAE;CAQvC;AAED;;;;;;;;GAQG;AACH,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,4DAA4D;IAC5D,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,2EAA2E;IAC3E,QAAQ,CAAC,SAAS,CAAC,EAAE,KAAK,CAAC;CAC5B;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,SAAS;IAAE,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAAE,EAAE,GAChF,SAAS,iBAAiB,EAAE,CAI9B;AAED;;;;;GAKG;AACH,qBAAa,2BAA4B,SAAQ,KAAK;IACpD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB;;;;;;OAMG;IACH,QAAQ,CAAC,eAAe,EAAE,SAAS,iBAAiB,EAAE,CAAC;gBAE3C,MAAM,EAAE,MAAM,EAAE,eAAe,GAAE,SAAS,iBAAiB,EAAO;CAM/E;AAED
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,eAAO,MAAM,8BAA8B,2BAA2B,CAAC;AACvE,eAAO,MAAM,+BAA+B,4BAA4B,CAAC;AACzE,eAAO,MAAM,wBAAwB,sBAAsB,CAAC;AAC5D,eAAO,MAAM,gCAAgC,6BAA6B,CAAC;AAC3E,eAAO,MAAM,sCAAsC,kCAAkC,CAAC;AACtF,eAAO,MAAM,oCAAoC,gCAAgC,CAAC;AAClF,eAAO,MAAM,mCAAmC,+BAA+B,CAAC;AAMhF;;;;;GAKG;AACH,qBAAa,sBAAuB,SAAQ,KAAK;IAC/C,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;gBAEhB,UAAU,EAAE,MAAM;CAK/B;AAED,+DAA+D;AAC/D,qBAAa,uBAAwB,SAAQ,KAAK;IAChD,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;gBAEhB,UAAU,EAAE,MAAM;CAK/B;AAED;;;;GAIG;AACH,qBAAa,iBAAkB,SAAQ,KAAK;IAC1C,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;gBAEhB,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM;CAKhD;AAED,MAAM,MAAM,uBAAuB,GAC/B,kBAAkB,GAClB,kBAAkB,GAClB,kBAAkB,GAClB,mBAAmB,GACnB,qBAAqB,GACrB,iBAAiB,GACjB,qBAAqB,CAAC;AAE1B;;;;;;GAMG;AACH,qBAAa,wBAAyB,SAAQ,KAAK;IACjD,QAAQ,CAAC,IAAI,EAAE,uBAAuB,CAAC;IACvC,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;gBAEjB,IAAI,EAAE,uBAAuB,EAAE,UAAU,CAAC,EAAE,MAAM;CAS/D;AAED;;;;GAIG;AACH,qBAAa,6BAA8B,SAAQ,KAAK;IACtD,mFAAmF;IACnF,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;gBAExB,OAAO,EAAE,SAAS,MAAM,EAAE;CAQvC;AAED;;;;;;;;GAQG;AACH,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,4DAA4D;IAC5D,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,2EAA2E;IAC3E,QAAQ,CAAC,SAAS,CAAC,EAAE,KAAK,CAAC;CAC5B;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,SAAS;IAAE,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAAE,EAAE,GAChF,SAAS,iBAAiB,EAAE,CAI9B;AAED;;;;;GAKG;AACH,qBAAa,2BAA4B,SAAQ,KAAK;IACpD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB;;;;;;OAMG;IACH,QAAQ,CAAC,eAAe,EAAE,SAAS,iBAAiB,EAAE,CAAC;gBAE3C,MAAM,EAAE,MAAM,EAAE,eAAe,GAAE,SAAS,iBAAiB,EAAO;CAM/E;AAED;;;;;;;;;;;;;GAaG;AACH,qBAAa,0BAA2B,SAAQ,KAAK;IACnD,6EAA6E;IAC7E,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;gBAElB,YAAY,EAAE,MAAM;CAKjC;AAED,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,sBAAsB,CAExF;AAED,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,iBAAiB,CAE9E;AAED,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,uBAAuB,CAE1F;AAED,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,wBAAwB,CAE5F;AAED,wBAAgB,+BAA+B,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,6BAA6B,CAEtG;AAED,wBAAgB,6BAA6B,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,2BAA2B,CAElG;AAED,wBAAgB,4BAA4B,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,0BAA0B,CAEhG"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var en=Object.create;var at=Object.defineProperty;var nn=Object.getOwnPropertyDescriptor;var rn=Object.getOwnPropertyNames;var on=Object.getPrototypeOf,sn=Object.prototype.hasOwnProperty;var an=(e,t,n)=>t in e?at(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var cn=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of rn(t))!sn.call(e,o)&&o!==n&&at(e,o,{get:()=>t[o],enumerable:!(r=nn(t,o))||r.enumerable});return e};var B=(e,t,n)=>(n=e!=null?en(on(e)):{},cn(t||!e||!e.__esModule?at(n,"default",{value:e,enumerable:!0}):n,e));var p=(e,t,n)=>an(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const st=require("@scure/bip32"),w=require("bitcoinjs-lib"),c=require("buffer"),un=require("@bitcoin-js/tiny-secp256k1-asmjs");function ln(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 dt=ln(un),hn=1,fn=1,pn=1,dn=2,gn=33,En=256,wn=257,_n=258,mn=39,Tn=259,In=105,Sn=260,yn=261,Pn=262,bn=271,Rn=265,An=266,On=267,Bn=268,xn=269,Cn=270,Ln=263,Mn=264,et=32,vn=32,K=255,Nn=3+et,vt=Math.floor(K/Nn);function A(e,t){if(t.length>K)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 it(e,t,n){if(e<0n||e>=1n<<BigInt(8*t))throw new Error(`${n} ${e} does not fit in ${t} bytes`);const r=new Uint8Array(t);let o=e;for(let s=t-1;s>=0;s--)r[s]=Number(o&0xffn),o>>=8n;return r}function L(e,t,n){return A(e,it(BigInt(t),1,n))}function q(e,t,n){return A(e,it(BigInt(t),4,n))}function v(e,t,n){return A(e,it(t,8,n))}function nt(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 It(e,t,n){if(e.length!==t)throw new Error(`${n} must be ${t} bytes, got ${e.length}`);return e}const Nt=5;function fe(e){if(e.depositorPath.length!==Nt)throw new Error(`depositorPath must have exactly ${Nt} levels, got ${e.depositorPath.length}`);const t=nt(e.depositorPath.map(n=>it(BigInt(n>>>0),4,"path level")));return nt([L(pn,hn,"structureType"),L(dn,fn,"version"),q(gn,e.coinType,"coinType"),v(En,e.baseFeeRate,"baseFeeRate"),q(wn,e.peginCsvTimelock,"peginCsvTimelock"),q(_n,e.payoutTimelock,"payoutTimelock"),A(mn,It(e.prepeginTxidInternal,vn,"prepeginTxid")),q(Tn,e.htlcRefundTimelock,"htlcRefundTimelock"),A(In,t),L(Sn,e.keeperCount,"keeperCount"),L(yn,e.challengerCount,"challengerCount"),L(Pn,e.vaultCount,"vaultCount"),v(bn,e.prepeginMaxFee,"prepeginMaxFee")])}function pe(e){return nt([L(Rn,e.htlcVout,"htlcVout"),A(An,It(e.vaultProviderPubkey,et,"vaultProviderPubkey")),v(On,e.vaultAmount,"vaultAmount"),v(Bn,e.commissionFee,"commissionFee"),v(xn,e.depositorClaimValue,"depositorClaimValue"),v(Cn,e.peginMaxFee,"peginMaxFee")])}function de(e,t){const n=(s,i)=>s.map((a,u)=>It(a,et,`${i}[${u}]`)).sort((a,u)=>{for(let l=0;l<et;l++)if(a[l]!==u[l])return a[l]-u[l];return 0}),r=[...n(e,"keeper").map(s=>A(Ln,s)),...n(t,"challenger").map(s=>A(Mn,s))],o=[];for(let s=0;s<r.length;s+=vt)o.push(nt(r.slice(s,s+vt)));return o}const R=225,ct=128,Dt=129,Dn=0,$n=1,kn=0,Un=1,Hn=2,F=0,$t=64,kt=1024,Ut=10,Ht=32;function Vn(e){return new Uint8Array([e>>8&255,e&255])}function Gn(e){const t=e>>>0;return new Uint8Array([t>>>24&255,t>>>16&255,t>>>8&255,t&255])}function ut(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 Vt=/^[a-z0-9-]+$/;async function Kn(e,{appName:t,derivationPath:n,context:r}){const o=new TextEncoder().encode(t);if(o.length<1||o.length>$t)throw new Error(`appName must be 1..${$t} bytes, got ${o.length}`);if(!Vt.test(t))throw new Error(`appName must match ${Vt} — the device rejects other characters`);if(n.length<1||n.length>Ut)throw new Error(`derivationPath must have 1..${Ut} levels`);if(r.length<1||r.length>kt)throw new Error(`context must be 1..${kt} bytes, got ${r.length}`);const s=ut([new Uint8Array([o.length]),o,new Uint8Array([n.length]),ut(n.map(Gn)),Vn(r.length)]),i=Math.min(r.length,K-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:R,ins:Dt,p1:Dn,p2:F,data:ut([s,r.subarray(0,i)])});for(let u=i;u<r.length;u+=K)a=await e({cla:R,ins:Dt,p1:$n,p2:F,data:r.subarray(u,u+K)});if(a.length!==Ht)throw new Error(`Expected a ${Ht}-byte context root, got ${a.length} bytes`);return a}async function Fn(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:R,ins:ct,p1:kn,p2:F,data:fe(t)});for(const s of n)await e({cla:R,ins:ct,p1:Un,p2:F,data:pe(s)});for(const s of de(r,o))await e({cla:R,ins:ct,p1:Hn,p2:F,data:s})}const Yn=0,ge=0,Ee=1,Xn=0,Gt=33,Kt=10,Wn=5,qn=4;async function zn(e){const t=await e({cla:R,ins:Wn,p1:ge,p2:Ee,data:new Uint8Array(0)});if(t.length!==qn)throw new Error(`Ledger returned a ${t.length}-byte response instead of the 4-byte master fingerprint`);return _e(t)}async function we(e,t,n){if(t.length<1||t.length>Kt)throw new Error(`BIP-32 path must have 1..${Kt} levels, got ${t.length}`);const r=await e({cla:R,ins:Yn,p1:ge,p2:Ee,data:Zn(t)}),o=new TextDecoder().decode(r);if(o.length===0)throw new Error("Ledger returned an empty extended key");return st.HDKey.fromExtendedKey(o,n),o}async function jn(e,t,n){const r=await we(e,t,n),o=st.HDKey.fromExtendedKey(r,n);if(!o.publicKey||o.publicKey.length!==Gt)throw new Error(`Ledger returned an extended key without a ${Gt}-byte public key`);return _e(o.publicKey.subarray(1))}function _e(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function Zn(e){const t=new Uint8Array(2+e.length*4);return t[0]=Xn,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 St="LedgerUserRefusedError",yt="LedgerDeviceLockedError",Pt="LedgerDeviceError",bt="LedgerYieldMismatchError",Rt="LedgerSignPsbtIncompleteError",At="LedgerSignPsbtProtocolError",Ot="LedgerSignPsbtAbortedError";function me(e){return e.toString(16).padStart(4,"0")}class Te extends Error{constructor(n){super(`User rejected the request on the Ledger device (0x${me(n)})`);p(this,"statusWord");this.name=St,this.statusWord=n}}class Ie extends Error{constructor(n){super(`The Ledger device is locked — unlock it and retry (0x${me(n)})`);p(this,"statusWord");this.name=yt,this.statusWord=n}}class Se extends Error{constructor(n,r){super(r);p(this,"statusWord");this.name=Pt,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=bt,this.kind=n,this.inputIndex=r}}class ye 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=Rt,this.missing=n}}function J(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=At,this.detail=n,this.collectedYields=r}}class tt extends Error{constructor(n,r){super("SIGN_PSBT was abandoned host-side before completion");p(this,"yieldedCount");p(this,"dispatcherInterrupted");this.name=Ot,this.yieldedCount=n,this.dispatcherInterrupted=r}}function Qn(e){return e instanceof Error&&e.name===St}function Jn(e){return e instanceof Error&&e.name===Pt}function tr(e){return e instanceof Error&&e.name===yt}function Pe(e){return e instanceof Error&&e.name===bt}function er(e){return e instanceof Error&&e.name===Rt}function be(e){return e instanceof Error&&e.name===At}function nr(e){return e instanceof Error&&e.name===Ot}const rr=36864,or=new Set([21761,27013]),sr=new Set([21781,27010,21251]),Bt=28160,Re=45063,Ae=45066,ir={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",[Bt]:"The running app does not handle vault instructions — open the Babylon Vault app",45056:"The device reported a wrong response length",[Re]:"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",[Ae]:"The device has already signed the maximum number of these transactions",28416:"The device reported an internal error"};function N(e){return e.toString(16).padStart(2,"0")}function Oe(e){return e.toString(16).padStart(4,"0")}function Be(e,t){if(e===rr)return;if(or.has(e))return new Te(e);if(sr.has(e))return new Ie(e);const n=ir[e],r=e===Bt&&t.appName?` (app at connect time: "${t.appName}"${t.appVersion?` v${t.appVersion}`:""})`:"";return new Se(e,`${n??"The device rejected the request"} (ins 0x${N(t.ins)} p1 0x${N(t.p1)}, sw 0x${Oe(e)})${r}`)}function ar(e,t){return async n=>{const{sw:r,data:o}=await e(n),s=Be(r,{...t,ins:n.ins,p1:n.p1});if(s)throw s;return o}}const Ft=2;function cr(e){if(e.statusCode.length!==Ft)throw new Error(`The device returned a ${e.statusCode.length}-byte status word; expected ${Ft}.`);return e.statusCode[0]<<8|e.statusCode[1]}function z(e,t){if(!Number.isInteger(e)||e<0||e>255)throw new Error(`APDU ${t} ${e} is not a single byte (0..255)`)}function ur(e){if(z(e.cla,"cla"),z(e.ins,"ins"),z(e.p1,"p1"),z(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 Yt(){return globalThis.__LEDGER_VAULT_APDU_TRACE__===!0}function xe(e){return async t=>{const n=`${N(t.cla)} ${N(t.ins)} ${N(t.p1)} ${N(t.p2)} Lc=${t.data.length}`;let r;try{r=await e.dmk.sendApdu({sessionId:e.sessionId,apdu:ur(t)})}catch(s){throw Yt()&&console.debug(`[ledger-vault] APDU ${n} -> transport error`,s),s}const o=cr(r);return Yt()&&console.debug(`[ledger-vault] APDU ${n} -> sw=0x${Oe(o)} len=${r.data.length}`),{sw:o,data:r.data}}}function lr(e){return ar(xe(e),{appName:e.appName,appVersion:e.appVersion})}const hr={isRefresherDisabled:!0};let D,M;function fr(){if(!M){const e=(async()=>{const[{DeviceManagementKitBuilder:t},{webHidTransportFactory:n}]=await Promise.all([import("@ledgerhq/device-management-kit"),import("@ledgerhq/device-transport-kit-web-hid")]);return D=new t().addTransport(n).build(),D})().catch(t=>{throw M===e&&(M=void 0),t});M=e}return M}async function pr(){const e=await fr(),[{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:hr}),s=await dr(e,o);return{dmk:e,sessionId:o,...s}}async function dr(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 gr(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 Er(e){try{await e.dmk.disconnect({sessionId:e.sessionId})}catch{}}function wr(){D==null||D.close(),D=void 0,M=void 0}const Xt=32,_r=10,Wt=0xffffffffn,qt=72,mr=1008,Tr=4320,Ir=91,Sr=4031,Ce=546n,zt=Ce,yr=2n,Le="DepositTermsRejectedError";class T extends Error{constructor(n,r="device-envelope"){super(n);p(this,"reason");this.name=Le,this.reason=r}}const y="Deposit terms outside the device-supported range";function x(e,t,n,r){if(!Number.isInteger(t)||t<n||t>r)throw new T(`${y}: ${e} ${t} not in [${n}, ${r}]`)}function Pr(e){if(e.protocolFeeRate<1n||e.protocolFeeRate>Wt)throw new T(`${y}: protocolFeeRate ${e.protocolFeeRate} not in [1, ${Wt}]`);if(x("timelockPegin",e.timelockPegin,qt,mr),x("timelockAssert",e.timelockAssert,Ir,Sr),x("timelockRefund",e.timelockRefund,qt,Tr),x("keeper count",e.vaultKeeperBtcPubkeys.length,1,Xt),x("challenger count",e.universalChallengerBtcPubkeys.length,1,Xt),x("vault count",e.vaults.length,1,_r),G("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 h=n(l);if(r.has(h))throw new T(`${y}: ${a} contains the vault provider's own key (${h.slice(0,16)}…)`);if(o.has(h))throw new T(`${y}: duplicate participant key in ${a} (${h.slice(0,16)}…)`);o.add(h)}const s=Ce,i=yr*s;for(const a of e.vaults){if(G(`vault ${a.htlcVout} peginAmount`,a.peginAmount),G(`vault ${a.htlcVout} commissionFee`,a.commissionFee),G(`vault ${a.htlcVout} depositorClaimValue`,a.depositorClaimValue),G(`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<zt)throw new T(`${y}: vault ${a.htlcVout} depositorClaimValue ${a.depositorClaimValue} below the ${zt}-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 br=(1n<<64n)-1n;function G(e,t){if(t<0n||t>br)throw new T(`${y}: ${e} ${t} does not fit in an unsigned 64-bit field`)}const P=2147483648,Rr=4294967295,rt=86,Me=0,ve=1,jt=5,xt=3,Ar=3,Or=4;function Ne(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>Rr)throw new Error(`${e} levels must be integers in 0..0xffffffff`);if(!t.slice(0,xt).every(r=>(r&P)!==0)||(t[Or]&P)!==0)throw new Error(`${e} must harden purpose'/coin'/account' and leave the address index unhardened`);if(t[0]!==(P|rt)>>>0)throw new Error(`${e} must use BIP-86 purpose ${rt}'`)}function X(e){return"m/"+e.map(t=>(t&P)!==0?`${(t&~P)>>>0}'`:`${t>>>0}`).join("/")}const Zt=253,Br=254,xr=65535,Cr=4294967295;function Lr(e){if(e<Zt)return c.Buffer.from([e]);if(e<=xr){const t=c.Buffer.alloc(2);return t.writeUInt16LE(e),c.Buffer.concat([c.Buffer.from([Zt]),t])}if(e<=Cr){const t=c.Buffer.alloc(4);return t.writeUInt32LE(e),c.Buffer.concat([c.Buffer.from([Br]),t])}throw new Error(`Script too large to encode as CompactSize: ${e} bytes`)}const Mr="TapLeaf";function vr(e,t){const n=c.Buffer.concat([c.Buffer.from([e]),Lr(t.length),c.Buffer.from(t)]);return w.crypto.taggedHash(Mr,n)}function Nr(e,t,n,r){for(let o=0;o<t;o++){if(n[o+r]===void 0)throw Error("Buffer too small");n[o+r]=Number(e%BigInt(256)),e=e>>BigInt(8)}}function Dr(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 b(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 $r(e){if(typeof e=="number"&&(e=b(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),Ur=BigInt(65535)+BigInt(1),Hr=BigInt(4294967295)+BigInt(1);function De(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=Ur):(r=8,o=Hr);const s=Dr(e,t+1,r);if(s<o)throw RangeError(`Non-minimal varint at offset ${t}: a ${r+1}-byte CompactSize must encode a value of at least ${o}; re-encode it in its canonical (shorter) form`);return[s,r+1]}}function k(e){typeof e=="number"&&(e=b(e));const t=$r(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,Nr(e,t-1,n,1)),n}const Vr=31;function $e(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 gt(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>Vr)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 O{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=$e(t);this.writeSlice(n)}writeVarInt(t){this.bufs.push(k(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 ${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 gt(t)}readVarInt(){const[t,n]=De(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=b(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 Et=(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))(Et||{});const Qt=c.Buffer.from([112,115,98,116,255]),Gr=4294967295;class ke extends Error{}class Ue{constructor(){p(this,"globalMap",new Map);p(this,"inputMaps",[]);p(this,"outputMaps",[])}setGlobalTxVersion(t){this.setGlobal(2,C(t))}getGlobalTxVersion(){return this.getGlobal(2).readUInt32LE(0)}setGlobalFallbackLocktime(t){this.setGlobal(3,C(t))}getGlobalFallbackLocktime(){var t;return(t=this.getGlobalOptional(3))==null?void 0:t.readUInt32LE(0)}setGlobalInputCount(t){this.setGlobal(4,ee(t))}getGlobalInputCount(){return ne(this.getGlobal(4))}setGlobalOutputCount(t){this.setGlobal(5,ee(t))}getGlobalOutputCount(){return ne(this.getGlobal(5))}setGlobalTxModifiable(t){this.setGlobal(6,t)}getGlobalTxModifiable(){return this.getGlobalOptional(6)}setGlobalPsbtVersion(t){this.setGlobal(251,C(t))}getGlobalPsbtVersion(){return this.getGlobal(251).readUInt32LE(0)}setInputNonWitnessUtxo(t,n){this.setInput(t,0,E(),n)}getInputNonWitnessUtxo(t){return this.getInputOptional(t,0,E())}setInputWitnessUtxo(t,n,r){const o=new O;o.writeSlice(te(n)),o.writeVarSlice(r),this.setInput(t,1,E(),o.buffer())}getInputWitnessUtxo(t){const n=this.getInputOptional(t,1,E());if(!n)return;const r=new $(n);return{amount:gt(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,E(),C(n))}getInputSighashType(t){const n=this.getInputOptional(t,3,E());if(n)return n.readUInt32LE(0)}setInputRedeemScript(t,n){this.setInput(t,4,E(),n)}getInputRedeemScript(t){return this.getInputOptional(t,4,E())}setInputWitnessScript(t,n){this.setInput(t,5,E(),n)}getInputWitnessScript(t){return this.getInputOptional(t,5,E())}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,E(),n)}getInputFinalScriptsig(t){return this.getInputOptional(t,7,E())}setInputFinalScriptwitness(t,n){this.setInput(t,8,E(),n)}getInputFinalScriptwitness(t){return this.getInput(t,8,E())}setInputPreviousTxId(t,n){this.setInput(t,14,E(),n)}getInputPreviousTxid(t){return this.getInput(t,14,E())}setInputOutputIndex(t,n){this.setInput(t,15,E(),C(n))}getInputOutputIndex(t){return this.getInput(t,15,E()).readUInt32LE(0)}setInputSequence(t,n){this.setInput(t,16,E(),C(n))}getInputSequence(t){var n;return((n=this.getInputOptional(t,16,E()))==null?void 0:n.readUInt32LE(0))??Gr}setInputTapKeySig(t,n){this.setInput(t,19,E(),n)}getInputTapKeySig(t){return this.getInputOptional(t,19,E())}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,E(),n)}getOutputRedeemScript(t){return this.getOutput(t,0,E())}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,E(),te(n))}getOutputAmount(t){const n=this.getOutput(t,3,E());return gt(n)}setOutputScript(t,n){this.setOutput(t,4,E(),n)}getOutputScript(t){return this.getOutput(t,4,E())}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 O;return t.writeSlice(Qt),ht(t,this.globalMap),this.inputMaps.forEach(n=>{ht(t,n)}),this.outputMaps.forEach(n=>{ht(t,n)}),t.buffer()}deserialize(t){const n=new $(t);if(!n.readSlice(5).equals(Qt))throw new Error("Invalid magic bytes");for(;this.readKeyPair(this.globalMap,n););let r;try{r=this.getGlobalPsbtVersion()}catch(i){if(!(i instanceof ke))throw i;r=0}if(r!==0&&r!==2)throw new Error("Only PSBTs of version 0 or 2 are supported");let o,s;if(r===0){const i=this.getGlobal(0),a=w.Transaction.fromBuffer(i);o=a.ins.length,s=a.outs.length}else o=this.getGlobalInputCount(),s=this.getGlobalOutputCount();for(let i=0;i<o;i++){const a=new Map;for(this.inputMaps[i]=a;this.readKeyPair(a,n););}for(let i=0;i<s;i++){const a=new Map;for(this.outputMaps[i]=a;this.readKeyPair(a,n););}if(n.available()!==0)throw new Error("Trailing bytes after PSBT output maps");this.normalizeToV2()}normalizeToV2(){var o;const t=(o=this.getGlobalOptional(251))==null?void 0:o.readUInt32LE(0);if(t===2)return;if(t!==void 0)throw new Error("Invalid or unsupported value for PSBT_GLOBAL_VERSION");const n=this.getGlobal(0),r=w.Transaction.fromBuffer(n);this.setGlobalPsbtVersion(2),this.setGlobalTxVersion(r.version),this.setGlobalFallbackLocktime(r.locktime),this.setGlobalInputCount(r.ins.length),this.setGlobalOutputCount(r.outs.length),r.ins.forEach((s,i)=>{this.setInputPreviousTxId(i,s.hash),this.setInputOutputIndex(i,s.index),this.setInputSequence(i,s.sequence)}),r.outs.forEach((s,i)=>{this.setOutputAmount(i,s.value),this.setOutputScript(i,s.script)}),this.globalMap.delete("0".padStart(2,"0"))}readKeyPair(t,n){const r=b(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 lt(this.globalMap,t,E())}getGlobalOptional(t){return wt(this.globalMap,t,E())}setInput(t,n,r,o){Jt(this.getMap(t,this.inputMaps),n,r,o)}getInput(t,n,r){return lt(this.inputMaps[t],n,r)}getInputOptional(t,n,r){return wt(this.inputMaps[t],n,r)}setOutput(t,n,r,o){Jt(this.getMap(t,this.outputMaps),n,r,o)}getOutput(t,n,r){return lt(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 O;return this.writeBip32Derivation(r,t,n),r.buffer()}decodeBip32Derivation(t){const n=new $(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 O;return o.writeVarInt(t.length),t.forEach(s=>{o.writeSlice(s)}),this.writeBip32Derivation(o,n,r),o.buffer()}decodeTapBip32Derivation(t){const n=new $(t),r=b(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 lt(e,t,n){const r=wt(e,t,n);if(r===void 0)throw new ke(new U(t,n).toString());return r}function wt(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 O;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 Kr{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 Fr(e){return new U(e.readUInt8(0),e.subarray(1))}function ht(e,t){const n=[...t].sort(([r],[o])=>r<o?-1:r>o?1:0);for(const[r,o]of n)new Kr(Fr(c.Buffer.from(r,"hex")),o).serialize(e);e.writeUInt8(0)}function E(){return c.Buffer.from([])}function Jt(e,t,n,r){const o=new U(t,n);e.set(o.toString(),r)}function C(e){const t=c.Buffer.alloc(4);return t.writeUInt32LE(e,0),t}function te(e){return $e(e)}function ee(e){const t=new O;return t.writeVarInt(e),t.buffer()}function ne(e){return b(new $(e).readVarInt())}const re=192,_t=32,oe=2,j=33,Z=32,Yr=1,Xr="TapBranch",Wr="TapTweak",se=64,ie=32,ft=64,qr=34,ot=c.Buffer.from([81,32]),zr=c.Buffer.from([0,20]),jr=2,Zr=3;function Ct(e){w.initEccLib(dt);const t=w.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 ae(e,t){const n=c.Buffer.concat([c.Buffer.from([t]),c.Buffer.from(e,"hex")]);return c.Buffer.concat([zr,w.crypto.hash160(n)])}function He(e){return e.length===qr&&e.subarray(0,ot.length).equals(ot)}function Qr(e,t,n,r){if(!He(r))throw new d(`input ${e} is tapscript but its witnessUtxo script is not P2TR`);const o=t.length-j;if(o<0||o%Z!==0)throw new d(`input ${e} control block length ${t.length} is not ${j} plus a multiple of ${Z}`);const s=t.subarray(1,j);if(!dt.isXOnlyPoint(s))throw new d(`input ${e} control block internal key is not an x-only point`);let i=n;for(let h=j;h<t.length;h+=Z){const g=t.subarray(h,h+Z),f=c.Buffer.compare(i,g)<0?[i,g]:[g,i];i=w.crypto.taggedHash(Xr,c.Buffer.concat(f))}const a=w.crypto.taggedHash(Wr,c.Buffer.concat([s,i])),u=dt.xOnlyPointAddTweak(s,a);if(!u)throw new d(`input ${e} control block internal key has no taproot output key`);if(!r.subarray(ot.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]&Yr))throw new d(`input ${e} control block parity bit disagrees with the recomputed taproot output key`)}function Jr(e){const{psbt:t,depositorXOnlyHex:n}=e,r=new Map,o=t.getGlobalInputCount(),s=Ct(n),i=[ae(n,jr),ae(n,Zr)];for(let u=0;u<o;u++){const l=t.getInputEntriesOfType(u,Et.TAP_LEAF_SCRIPT);if(l.length>0){if(l.length>1)throw new d(`input ${u} carries an ambiguous leaf set (${l.length} TAP_LEAF_SCRIPT entries)`);const f=l[0].value;if(f.length<oe)throw new d(`input ${u} TAP_LEAF_SCRIPT value length ${f.length} is below the ${oe}-byte minimum (script byte plus the leaf-version byte)`);const _=f[f.length-1];if(_!==re)throw new d(`input ${u} leaf version 0x${_.toString(16)} is not tapscript (0xc0)`);const m=t.getInputWitnessUtxo(u);if(!m)throw new d(`input ${u} is tapscript but has no witnessUtxo`);const tn=f.subarray(0,f.length-1),Mt=vr(re,tn);Qr(u,l[0].keyData,Mt,m.scriptPubKey),r.set(u,{kind:"tapscript",expectedLeafHashHexes:new Set([Mt.toString("hex")]),expectedSignerXOnlyHex:n});continue}const h=t.getInputEntriesOfType(u,Et.TAP_INTERNAL_KEY);if(h.length>0){const f=h[0];if(h.length>1||f.keyData.length!==0||f.value.length!==_t)throw new d(`input ${u} carries a malformed TAP_INTERNAL_KEY entry`);if(f.value.toString("hex")!==n)throw new d(`input ${u} internal key is not the connected depositor key`);const _=t.getInputWitnessUtxo(u);if(!_)throw new d(`input ${u} is keypath but has no witnessUtxo`);const m=_.scriptPubKey;if(!He(m))throw new d(`input ${u} witnessUtxo script is not P2TR`);if(!m.equals(s))throw new d(`input ${u} witnessUtxo is not the BIP-86 P2TR of the depositor key`);r.set(u,{kind:"taproot-keypath",expectedOutputKeyHex:m.subarray(ot.length).toString("hex")});continue}const g=t.getInputWitnessUtxo(u);if(g&&(g.scriptPubKey.equals(s)||i.some(f=>g.scriptPubKey.equals(f))))throw new d(`input ${u} spends a depositor-owned UTXO but carries no signing metadata`)}if(r.size===0)throw new d("PSBT contains no depositor-signable input");let a=0;for(const u of r.values())a+=u.kind==="tapscript"?u.expectedLeafHashHexes.size:1;return{byInput:r,expectedYieldCount:a}}function Q(e){return e.kind==="tapscript"?`${e.inputIndex}:${e.leafHashHex}`:`${e.inputIndex}`}function ce(e,t){if(e<ft)throw new d(`YIELD payload truncated inside the signature (${e} of ${ft} bytes on input ${t})`);if(e!==ft)throw new S("non-default-sighash",t)}function to(e){const t=[],n=new Set;return{assertAndRecord:s=>{let i,a;try{const[h,g]=De(s,0);i=b(h),a=g}catch(h){throw new d(`unparseable YIELD payload: ${h instanceof Error?h.message:String(h)}`)}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===se){if(l.kind!=="tapscript")throw new S("wrong-spend-type",i);const h=a+1+se;if(s.length<h)throw new d("YIELD payload truncated inside the augmented pubkey");const g=s.subarray(a+1,a+1+_t).toString("hex"),f=s.subarray(a+1+_t,h).toString("hex"),_=s.subarray(h);if(g!==l.expectedSignerXOnlyHex)throw new S("wrong-signer-key",i);if(!l.expectedLeafHashHexes.has(f))throw new S("unknown-leaf-hash",i);ce(_.length,i);const m={kind:"tapscript",inputIndex:i,signerXOnlyHex:g,leafHashHex:f,signature:Uint8Array.from(_)};if(n.has(Q(m)))throw new S("duplicate-yield",i);n.add(Q(m)),t.push(m);return}if(u===ie){if(l.kind!=="taproot-keypath")throw new S("wrong-spend-type",i);const h=a+1+ie;if(s.length<h)throw new d("YIELD payload truncated inside the augmented pubkey");const g=s.subarray(a+1,h).toString("hex"),f=s.subarray(h);if(g!==l.expectedOutputKeyHex)throw new S("wrong-signer-key",i);ce(f.length,i);const _={kind:"taproot-keypath",inputIndex:i,outputKeyHex:g,signature:Uint8Array.from(f)};if(n.has(Q(_)))throw new S("duplicate-yield",i);n.add(Q(_)),t.push(_);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 h of l.expectedLeafHashHexes)s.add(`${u}:${h}`);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 ye(i)}}}const Ve=/^[0-9a-f]{64}$/;function eo(e,t){if(Ne("depositorPath",e),e[Ar]!==Me)throw new Error("depositorPath must use BIP-86 receive branch 0");for(let n=0;n<xt;n++)if(e[n]!==t[n])throw new Error(`depositorPath ${X(e)} is not under the wallet policy's key origin ${X(t)} — the device could never mark the input internal`)}function Ge(e,t,n,r){if(!Number.isInteger(r)||r<0||r>=P)throw new Error("addressIndex must be a non-hardened integer in 0..2^31-1");const o=st.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 Ke(e,t,n){return Ge(e,t,ve,n)}function no(e,t,n){return Ge(e,t,Me,n)}function Fe(e,t){const n=Ct(t);return e.txOutputs.flatMap((r,o)=>c.Buffer.from(r.script).equals(n)?[o]:[])}function ro(e,t){if(!Ve.test(t))throw new Error("changeXOnlyHex must be 64 lowercase hex characters");return Fe(w.Psbt.fromHex(e),t).length>0}function oo(e){const{psbtHex:t,depositorXOnlyHex:n,walletPolicy:r,depositorPath:o,change:s}=e;if(!Ve.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");eo(o,r.keyOriginPath);const i=w.Psbt.fromHex(t),a=c.Buffer.from(r.masterFingerprintHex,"hex"),u=c.Buffer.from(n,"hex");let l=0;if(i.data.inputs.forEach((h,g)=>{h.tapInternalKey&&c.Buffer.from(h.tapInternalKey).equals(u)&&(l++,i.updateInput(g,{tapBip32Derivation:[{masterFingerprint:a,pubkey:u,path:X(o),leafHashes:[]}]}))}),l!==i.data.inputs.length)throw new Error(`${i.data.inputs.length-l} of ${i.data.inputs.length} inputs do not carry the depositor key as TAP_INTERNAL_KEY — every Pre-PegIn input must be internal`);if(s){const h=Ke(r.accountXpub,r.bip32Versions,s.addressIndex),g=[...o.slice(0,xt),ve,s.addressIndex],f=c.Buffer.from(h,"hex"),_=Fe(i,h);if(_.length===0)throw new Error("change script matches no output — the PSBT does not pay the wallet's change address");for(const m of _)i.updateOutput(m,{tapInternalKey:f,tapBip32Derivation:[{masterFingerprint:a,pubkey:f,path:X(g),leafHashes:[]}]})}return i.toHex()}const so="BIP0322-signed-message",io=new Uint8Array([252,6,98,118,97,117,108,116,0]),Ye=0,Xe=0,We=0,ao=0,mt=0,co=c.Buffer.from([106]),uo=/^[0-9a-f]{64}$/,lo=/^[0-9a-f]{8}$/,ho=c.Buffer.alloc(32,0),fo=4294967295,po=c.Buffer.from([0,32]),go=c.Buffer.from([81,32]),Eo=2;function wo(e,t){const n=w.crypto.sha256(c.Buffer.from(e,"utf8"));return w.crypto.sha256(c.Buffer.concat([n,n,c.Buffer.from(t)]))}function _o(e,t){const n=new w.Transaction;n.version=Ye,n.locktime=Xe;const r=c.Buffer.concat([po,wo(so,e)]);return n.addInput(ho,fo,We,r),n.addOutput(c.Buffer.concat([go,c.Buffer.from(t)]),mt),Uint8Array.from(n.getHash(!1))}function mo(e){const{message:t,depositorXOnlyHex:n,masterFingerprintHex:r,depositorPath:o}=e;if(!uo.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");if(!lo.test(r))throw new Error("masterFingerprintHex must be 8 lowercase hex characters");Ne("depositorPath",o);const s=new TextEncoder().encode(t),i=c.Buffer.from(n,"hex"),a=Ct(n),u=_o(s,a.subarray(Eo)),l=new w.Psbt;return l.setVersion(Ye),l.setLocktime(Xe),l.addInput({hash:c.Buffer.from(u),index:ao,sequence:We,witnessUtxo:{script:a,value:mt},tapInternalKey:i,tapBip32Derivation:[{masterFingerprint:c.Buffer.from(r,"hex"),pubkey:i,path:X(o),leafHashes:[]}]}),l.addOutput({script:co,value:mt}),l.addUnknownKeyValToGlobal({key:c.Buffer.from(io),value:c.Buffer.from(s)}),l.toHex()}class H{constructor(t,n=w.crypto.sha256){p(this,"leaves");p(this,"rootNode");p(this,"leafNodes");p(this,"h");this.leaves=t,this.h=n;const r=this.calculateRoot(t);this.rootNode=r.root,this.leafNodes=r.leaves}getRoot(){return this.rootNode.hash}size(){return this.leaves.length}getLeaves(){return this.leaves}getLeafHash(t){const n=this.leafNodes[t];if(n===void 0)throw Error("Index out of bounds");return n.hash}getProof(t){const n=this.leafNodes[t];if(n===void 0)throw Error("Index out of bounds");return Tt(n)}calculateRoot(t){const n=t.length;if(n==0)return{root:new pt(void 0,void 0,c.Buffer.alloc(32,0)),leaves:[]};if(n==1){const h=new pt(void 0,void 0,t[0]);return{root:h,leaves:[h]}}const r=Io(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 pt(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 V(e,t=w.crypto.sha256){return To(c.Buffer.from([0]),e,t)}function To(e,t,n){return n(c.Buffer.concat([e,t]))}class pt{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 Tt(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,...Tt(e.parent)]}else{if(!e.parent.leftChild)throw new Error("Expected left child to exist");return[e.parent.leftChild.hash,...Tt(e.parent)]}}function Io(e){if(e<2)throw Error("Expected n >= 2");return So(e)?e/2:1<<Math.floor(Math.log2(e))}function So(e){return(e&e-1)==0}const Lt=255,yo=2,I=32;class W{}class Po extends W{constructor(n,r,o){super();p(this,"results");p(this,"code",16);this.progressCallback=r,this.onYield=o,this.results=n}execute(n){const r=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 bo extends W{constructor(n,r){super();p(this,"knownPreimages");p(this,"queue");p(this,"code",64);this.knownPreimages=n,this.queue=r}execute(n){const r=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=k(i.length),u=Lt-a.length-1,l=Math.min(u,i.length);if(l<i.length)for(let h=l;h<i.length;h++)this.queue.push(c.Buffer.from(i.subarray(h,h+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 Ro extends W{constructor(n,r){super();p(this,"knownTrees");p(this,"queue");p(this,"code",65);this.knownTrees=n,this.queue=r}execute(n){const r=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 $(r),i=o.readSlice(I).toString("hex");let a,u;try{a=b(o.readVarInt()),u=b(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 h=l.getProof(u),g=Math.min(Math.floor((Lt-I-1-1)/I),h.length),f=h.length-g;return f>0&&this.queue.push(...h.slice(-f)),c.Buffer.concat([l.getLeafHash(u),c.Buffer.from([h.length]),c.Buffer.from([g]),...h.slice(0,g)])}}class Ao extends W{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,h=0;for(let g=0;g<u.size();g++)if(u.getLeafHash(g).toString("hex")===a){h=1,l=g;break}return c.Buffer.concat([c.Buffer.from([h]),k(l)])}}class Oo extends W{constructor(n){super();p(this,"queue");p(this,"code",160);this.queue=n}execute(n){if(n.length!==1)throw new Error("Invalid request, unexpected trailing data");const r=this.queue[0];if(r===void 0)throw new Error("No elements to get");const o=r.length;if(this.queue.some(u=>u.length!==o))throw new Error("The queue contains elements with different byte length, which is not expected");const s=Math.floor((Lt-yo)/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 Bo{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 Po(this.yielded,t,n),new bo(this.preimages,this.queue),new Ao(this.roots),new Ro(this.roots,this.queue),new Oo(this.queue)];for(const o of r){if(this.commands.has(o.code))throw new Error(`Multiple commands with code ${o.code}`);this.commands.set(o.code,o)}}getYielded(){return this.yielded}addKnownPreimage(t){this.preimages.set(w.crypto.sha256(t).toString("hex"),t)}addKnownList(t){for(const r of t){const o=c.Buffer.concat([c.Buffer.from([0]),r]);this.addKnownPreimage(o)}const n=new H(t.map(r=>V(r)));this.roots.set(n.getRoot().toString("hex"),n)}addKnownMapping(t){this.addKnownList(t.keys),this.addKnownList(t.values)}addKnownWalletPolicy(t){this.addKnownPreimage(t.serialize()),this.addKnownList(t.keys.map(n=>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 xo{constructor(t,n){p(this,"keys");p(this,"keysTree");p(this,"values");p(this,"valuesTree");if(t.length!=n.length)throw new Error("keys and values should have the same length");for(let r=0;r<t.length-1;r++)if(t[r].toString("hex")>=t[r+1].toString("hex"))throw new Error("keys must be in strictly increasing order");this.keys=t,this.keysTree=new H(t.map(r=>V(r))),this.values=n,this.valuesTree=new H(n.map(r=>V(r)))}commitment(){return c.Buffer.concat([k(this.keys.length),this.keysTree.getRoot(),this.valuesTree.getRoot()])}}class Y extends Ue{constructor(n){super();p(this,"globalMerkleMap");p(this,"inputMerkleMaps",[]);p(this,"outputMerkleMaps",[]);p(this,"inputMapCommitments");p(this,"outputMapCommitments");n.copy(this),this.globalMerkleMap=Y.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(Y.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(Y.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 xo(s,o)}}const Co=2;class Lo{constructor(t,n,r){p(this,"name");p(this,"descriptorTemplate");p(this,"keys");this.name=t,this.descriptorTemplate=n,this.keys=r}getId(){return w.crypto.sha256(this.serialize())}serialize(){const t=this.keys.map(o=>c.Buffer.from(o,"ascii")),n=new H(t.map(o=>V(o))),r=new O;return r.writeUInt8(Co),r.writeVarSlice(c.Buffer.from(this.name,"ascii")),r.writeVarInt(this.descriptorTemplate.length),r.writeSlice(w.crypto.sha256(c.Buffer.from(this.descriptorTemplate))),r.writeVarInt(this.keys.length),r.writeSlice(n.getRoot()),r.buffer()}}class qe extends Lo{constructor(t,n){super("",t,[n])}}const Mo=4,vo=0,No=1,ze=32,Do=new Uint8Array(ze),$o=new Uint8Array(ze),ko=/^[0-9a-f]{64}$/,Uo=/^(?:[0-9a-fA-F]{2})+$/,Ho=/^[0-9a-f]{64}$/;function Vo(e,t){const n=new H(e.inputMapCommitments.map(o=>V(o))).getRoot(),r=new H(e.outputMapCommitments.map(o=>V(o))).getRoot();return Uint8Array.from(c.Buffer.concat([e.getGlobalKeysValuesRoot(),k(e.getGlobalInputCount()),n,k(e.getGlobalOutputCount()),r,c.Buffer.from(t),c.Buffer.from($o)]))}function Go(e){return{cla:R,ins:Mo,p1:vo,p2:No,data:e}}const Ko=0;function Fo(e,t){for(const[n]of t.byInput){const r=e.data.inputs[n].sighashType;if(r!==void 0&&r!==Ko)throw new d(`input ${n} requests sighash type ${r}, but vault flows sign SIGHASH_DEFAULT only`)}}function Yo(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 Xo(e,t){const n={...e};return je.set(n,t),n}function Ze(e){const t=je.get(e);if(!t)throw new d("unrecognised prepared signing state — use prepareSignPsbt's return value");return t}function Qe(e){const{psbtHex:t,depositorXOnlyHex:n,walletPolicy:r}=e;if(!ko.test(n))throw new d("depositorXOnlyHex must be 64 lowercase hex characters");let o;if(r!==void 0){if(!Ho.test(r.walletIdHex))throw new d("walletPolicy.walletIdHex must be 64 lowercase hex characters");if(o=new qe(r.descriptorTemplate,r.keyInfo),o.getId().toString("hex")!==r.walletIdHex)throw new d("walletPolicy.walletIdHex does not match sha256 of the serialized policy")}if(!Uo.test(t))throw new d("psbtHex is not even-length hexadecimal");let s;try{s=w.Psbt.fromHex(t)}catch(f){throw new d(`PSBT rejected at parse (merge target): ${f instanceof Error?f.message:String(f)}`)}const i=new Ue;try{i.deserialize(c.Buffer.from(t,"hex"))}catch(f){throw new d(`PSBT rejected at parse: ${f instanceof Error?f.message:String(f)}`)}let a,u;try{a=new Y(i),u=Jr({psbt:a,depositorXOnlyHex:n})}catch(f){throw f instanceof d?f:new d(`PSBT rejected at preflight: ${f instanceof Error?f.message:String(f)}`)}Yo(s,u),Fo(s,u);const l=to(u),h=new Bo(void 0,f=>l.assertAndRecord(f));h.addKnownMapping(a.globalMerkleMap);for(const f of a.inputMerkleMaps)h.addKnownMapping(f);for(const f of a.outputMerkleMaps)h.addKnownMapping(f);h.addKnownList(a.inputMapCommitments),h.addKnownList(a.outputMapCommitments);const g=r?c.Buffer.from(r.walletIdHex,"hex"):Do;return o&&h.addKnownWalletPolicy(o),Xo({table:u,unsignedTxid:w.Transaction.fromBuffer(s.data.globalMap.unsignedTx.toBuffer()).getId()},{cdata:Vo(a,g),interpreter:h,collector:l,originalPsbtHex:t,signsUnderWalletPolicy:r!==void 0})}const Wo=248,qo=1,zo=0,jo=0,Zo=36864,Qo=57344,Jo=27264;async function ts(e,t,n){const{collector:r,interpreter:o,cdata:s}=Ze(t),{table:i}=t;if(n.signal.aborted)throw new tt(r.yields.length,!1);const a=Go(s);let u=a,l=await e(a);if(l.sw===Jo&&n.resendOnceOnIncorrectData===!0){if(n.signal.aborted)throw new tt(r.yields.length,!1);l=await e(a)}let h=0;for(;l.sw===Qo;){let g;try{g=o.execute(c.Buffer.from(l.data))}catch(f){throw Pe(f)?f:be(f)?new d(f.detail,J(r.yields)):new d(`client command failed: ${f instanceof Error?f.message:String(f)}`,J(r.yields))}if(r.yields.length>h){h=r.yields.length;const f=r.lastYield;if(f!==void 0&&n.onProgress!==void 0)try{n.onProgress({inputIndex:f.inputIndex,yieldedCount:h,expectedYieldCount:i.expectedYieldCount})}catch{}}if(n.signal.aborted)throw new tt(r.yields.length,!0);u={cla:Wo,ins:qo,p1:zo,p2:jo,data:g},l=await e(u)}if(l.sw!==Zo){const g=Be(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`,J(r.yields)):g}return r.assertComplete(),r.yields}function es(e,t){const n=w.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 ue=new WeakSet;async function Je(e,t,n){const{originalPsbtHex:r,signsUnderWalletPolicy:o}=Ze(t);if(ue.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");ue.add(t);const i=await ts(e,t,n);let a;try{a=es(r,i)}catch(u){throw new d(`merge failed after signing: ${u instanceof Error?u.message:String(u)}`,J(i))}return{signedPsbtHex:a,yields:[...i]}}async function ns(e,t){const{psbtHex:n,depositorXOnlyHex:r,...o}=t,s=Qe({psbtHex:n,depositorXOnlyHex:r});return Je(e,s,o)}const le="tr(@0/**)",he=2147483647,rs=/^[0-9a-f]{8}$/;function os(e){const{masterFingerprintHex:t,coinType:n,accountIndex:r,accountXpub:o,bip32Versions:s}=e;if(!rs.test(t))throw new Error("masterFingerprintHex must be 8 lowercase hex characters");if(!Number.isInteger(n)||n<0||n>he||!Number.isInteger(r)||r<0||r>he)throw new Error("coinType and accountIndex must be non-negative integers in 0..0x7fffffff");try{st.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}/${rt}'/${n}'/${r}']${o}`,a=new qe(le,i).getId().toString("hex");return{descriptorTemplate:le,keyInfo:i,walletIdHex:a,accountXpub:o,bip32Versions:s,keyOriginPath:[(P|rt)>>>0,(P|n)>>>0,(P|r)>>>0],masterFingerprintHex:t}}exports.DEPOSIT_TERMS_REJECTED_ERROR_NAME=Le;exports.DepositTermsRejectedError=T;exports.LEDGER_DEVICE_ERROR_NAME=Pt;exports.LEDGER_DEVICE_LOCKED_ERROR_NAME=yt;exports.LEDGER_SIGN_PSBT_ABORTED_ERROR_NAME=Ot;exports.LEDGER_SIGN_PSBT_INCOMPLETE_ERROR_NAME=Rt;exports.LEDGER_SIGN_PSBT_PROTOCOL_ERROR_NAME=At;exports.LEDGER_USER_REFUSED_ERROR_NAME=St;exports.LEDGER_YIELD_MISMATCH_ERROR_NAME=bt;exports.LedgerDeviceError=Se;exports.LedgerDeviceLockedError=Ie;exports.LedgerSignPsbtAbortedError=tt;exports.LedgerSignPsbtIncompleteError=ye;exports.LedgerSignPsbtProtocolError=d;exports.LedgerUserRefusedError=Te;exports.LedgerYieldMismatchError=S;exports.SW_BAD_STATE=Re;exports.SW_CAP_EXCEEDED=Ae;exports.SW_CLA_NOT_SUPPORTED=Bt;exports.approveVaultIntent=Fn;exports.assertDepositTermsDeviceCompatible=Pr;exports.augmentPsbtForWalletPolicy=oo;exports.buildDefaultTaprootPolicy=os;exports.buildPopPsbtHex=mo;exports.closeDmk=wr;exports.connectDmkSession=pr;exports.createDmkApduSender=lr;exports.createDmkRawApduSender=xe;exports.deriveChangeXOnlyHex=Ke;exports.deriveContextHash=Kn;exports.deriveReceiveXOnlyHex=no;exports.disconnectDmkSession=Er;exports.encodeIntentGroup=pe;exports.encodeIntentScalars=fe;exports.encodeKeyBatches=de;exports.getExtendedPublicKey=we;exports.getMasterFingerprintHex=zn;exports.getXOnlyPublicKeyHex=jn;exports.isLedgerDeviceError=Jn;exports.isLedgerDeviceLockedError=tr;exports.isLedgerSignPsbtAbortedError=nr;exports.isLedgerSignPsbtIncompleteError=er;exports.isLedgerSignPsbtProtocolError=be;exports.isLedgerUserRefusedError=Qn;exports.isLedgerYieldMismatchError=Pe;exports.isSessionAlive=gr;exports.prepareSignPsbt=Qe;exports.psbtPaysChangeScript=ro;exports.signPreparedVaultPsbt=Je;exports.signVaultPsbt=ns;
|
|
1
|
+
"use strict";var en=Object.create;var it=Object.defineProperty;var nn=Object.getOwnPropertyDescriptor;var rn=Object.getOwnPropertyNames;var on=Object.getPrototypeOf,sn=Object.prototype.hasOwnProperty;var an=(e,t,n)=>t in e?it(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var cn=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of rn(t))!sn.call(e,o)&&o!==n&&it(e,o,{get:()=>t[o],enumerable:!(r=nn(t,o))||r.enumerable});return e};var x=(e,t,n)=>(n=e!=null?en(on(e)):{},cn(t||!e||!e.__esModule?it(n,"default",{value:e,enumerable:!0}):n,e));var p=(e,t,n)=>an(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ot=require("@scure/bip32"),w=require("bitcoinjs-lib"),c=require("buffer"),un=require("@bitcoin-js/tiny-secp256k1-asmjs");function ln(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const pt=ln(un),hn=1,fn=1,pn=1,dn=2,gn=33,En=256,wn=257,_n=258,mn=39,Tn=259,In=105,Sn=260,yn=261,Pn=262,bn=271,Rn=265,An=266,On=267,Bn=268,xn=269,Cn=270,Ln=263,Mn=264,tt=32,vn=32,K=255,Nn=3+tt,vt=Math.floor(K/Nn);function A(e,t){if(t.length>K)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 st(e,t,n){if(e<0n||e>=1n<<BigInt(8*t))throw new Error(`${n} ${e} does not fit in ${t} bytes`);const r=new Uint8Array(t);let o=e;for(let s=t-1;s>=0;s--)r[s]=Number(o&0xffn),o>>=8n;return r}function L(e,t,n){return A(e,st(BigInt(t),1,n))}function q(e,t,n){return A(e,st(BigInt(t),4,n))}function v(e,t,n){return A(e,st(t,8,n))}function et(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 It(e,t,n){if(e.length!==t)throw new Error(`${n} must be ${t} bytes, got ${e.length}`);return e}const Nt=5;function fe(e){if(e.depositorPath.length!==Nt)throw new Error(`depositorPath must have exactly ${Nt} levels, got ${e.depositorPath.length}`);const t=et(e.depositorPath.map(n=>st(BigInt(n>>>0),4,"path level")));return et([L(pn,hn,"structureType"),L(dn,fn,"version"),q(gn,e.coinType,"coinType"),v(En,e.baseFeeRate,"baseFeeRate"),q(wn,e.peginCsvTimelock,"peginCsvTimelock"),q(_n,e.payoutTimelock,"payoutTimelock"),A(mn,It(e.prepeginTxidInternal,vn,"prepeginTxid")),q(Tn,e.htlcRefundTimelock,"htlcRefundTimelock"),A(In,t),L(Sn,e.keeperCount,"keeperCount"),L(yn,e.challengerCount,"challengerCount"),L(Pn,e.vaultCount,"vaultCount"),v(bn,e.prepeginMaxFee,"prepeginMaxFee")])}function pe(e){return et([L(Rn,e.htlcVout,"htlcVout"),A(An,It(e.vaultProviderPubkey,tt,"vaultProviderPubkey")),v(On,e.vaultAmount,"vaultAmount"),v(Bn,e.commissionFee,"commissionFee"),v(xn,e.depositorClaimValue,"depositorClaimValue"),v(Cn,e.peginMaxFee,"peginMaxFee")])}function de(e,t){const n=(s,i)=>s.map((a,u)=>It(a,tt,`${i}[${u}]`)).sort((a,u)=>{for(let h=0;h<tt;h++)if(a[h]!==u[h])return a[h]-u[h];return 0}),r=[...n(e,"keeper").map(s=>A(Ln,s)),...n(t,"challenger").map(s=>A(Mn,s))],o=[];for(let s=0;s<r.length;s+=vt)o.push(et(r.slice(s,s+vt)));return o}const R=225,at=128,Dt=129,Dn=0,kn=1,$n=0,Un=1,Vn=2,F=0,kt=64,$t=1024,Ut=10,Vt=32;function Hn(e){return new Uint8Array([e>>8&255,e&255])}function Gn(e){const t=e>>>0;return new Uint8Array([t>>>24&255,t>>>16&255,t>>>8&255,t&255])}function ct(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 Ht=/^[a-z0-9-]+$/;async function Kn(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(!Ht.test(t))throw new Error(`appName must match ${Ht} — the device rejects other characters`);if(n.length<1||n.length>Ut)throw new Error(`derivationPath must have 1..${Ut} levels`);if(r.length<1||r.length>$t)throw new Error(`context must be 1..${$t} bytes, got ${r.length}`);const s=ct([new Uint8Array([o.length]),o,new Uint8Array([n.length]),ct(n.map(Gn)),Hn(r.length)]),i=Math.min(r.length,K-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:R,ins:Dt,p1:Dn,p2:F,data:ct([s,r.subarray(0,i)])});for(let u=i;u<r.length;u+=K)a=await e({cla:R,ins:Dt,p1:kn,p2:F,data:r.subarray(u,u+K)});if(a.length!==Vt)throw new Error(`Expected a ${Vt}-byte context root, got ${a.length} bytes`);return a}async function Fn(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:R,ins:at,p1:$n,p2:F,data:fe(t)});for(const s of n)await e({cla:R,ins:at,p1:Un,p2:F,data:pe(s)});for(const s of de(r,o))await e({cla:R,ins:at,p1:Vn,p2:F,data:s})}const Yn=0,ge=0,Ee=1,Xn=0,Gt=33,Kt=10,Wn=5,qn=4;async function zn(e){const t=await e({cla:R,ins:Wn,p1:ge,p2:Ee,data:new Uint8Array(0)});if(t.length!==qn)throw new Error(`Ledger returned a ${t.length}-byte response instead of the 4-byte master fingerprint`);return _e(t)}async function we(e,t,n){if(t.length<1||t.length>Kt)throw new Error(`BIP-32 path must have 1..${Kt} levels, got ${t.length}`);const r=await e({cla:R,ins:Yn,p1:ge,p2:Ee,data:Zn(t)}),o=new TextDecoder().decode(r);if(o.length===0)throw new Error("Ledger returned an empty extended key");return ot.HDKey.fromExtendedKey(o,n),o}async function jn(e,t,n){const r=await we(e,t,n),o=ot.HDKey.fromExtendedKey(r,n);if(!o.publicKey||o.publicKey.length!==Gt)throw new Error(`Ledger returned an extended key without a ${Gt}-byte public key`);return _e(o.publicKey.subarray(1))}function _e(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function Zn(e){const t=new Uint8Array(2+e.length*4);return t[0]=Xn,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 St="LedgerUserRefusedError",yt="LedgerDeviceLockedError",Pt="LedgerDeviceError",bt="LedgerYieldMismatchError",Rt="LedgerSignPsbtIncompleteError",At="LedgerSignPsbtProtocolError",Ot="LedgerSignPsbtAbortedError";function me(e){return e.toString(16).padStart(4,"0")}class Te extends Error{constructor(n){super(`User rejected the request on the Ledger device (0x${me(n)})`);p(this,"statusWord");this.name=St,this.statusWord=n}}class Ie extends Error{constructor(n){super(`The Ledger device is locked — unlock it and retry (0x${me(n)})`);p(this,"statusWord");this.name=yt,this.statusWord=n}}class Se extends Error{constructor(n,r){super(r);p(this,"statusWord");this.name=Pt,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=bt,this.kind=n,this.inputIndex=r}}class ye 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=Rt,this.missing=n}}function J(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=At,this.detail=n,this.collectedYields=r}}class dt extends Error{constructor(n){super("SIGN_PSBT was abandoned host-side before completion");p(this,"yieldedCount");this.name=Ot,this.yieldedCount=n}}function Qn(e){return e instanceof Error&&e.name===St}function Jn(e){return e instanceof Error&&e.name===Pt}function tr(e){return e instanceof Error&&e.name===yt}function Pe(e){return e instanceof Error&&e.name===bt}function er(e){return e instanceof Error&&e.name===Rt}function be(e){return e instanceof Error&&e.name===At}function nr(e){return e instanceof Error&&e.name===Ot}const rr=36864,or=new Set([21761,27013]),sr=new Set([21781,27010,21251]),Bt=28160,Re=45063,Ae=45066,ir={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",[Bt]:"The running app does not handle vault instructions — open the Babylon Vault app for this network",45056:"The device reported a wrong response length",[Re]:"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",[Ae]:"The device has already signed the maximum number of these transactions",28416:"The device reported an internal error"};function N(e){return e.toString(16).padStart(2,"0")}function Oe(e){return e.toString(16).padStart(4,"0")}function Be(e,t){if(e===rr)return;if(or.has(e))return new Te(e);if(sr.has(e))return new Ie(e);const n=ir[e],r=e===Bt&&t.appName?` (app at connect time: "${t.appName}"${t.appVersion?` v${t.appVersion}`:""})`:"";return new Se(e,`${n??"The device rejected the request"} (ins 0x${N(t.ins)} p1 0x${N(t.p1)}, sw 0x${Oe(e)})${r}`)}function ar(e,t){return async n=>{const{sw:r,data:o}=await e(n),s=Be(r,{...t,ins:n.ins,p1:n.p1});if(s)throw s;return o}}const Ft=2;function cr(e){if(e.statusCode.length!==Ft)throw new Error(`The device returned a ${e.statusCode.length}-byte status word; expected ${Ft}.`);return e.statusCode[0]<<8|e.statusCode[1]}function z(e,t){if(!Number.isInteger(e)||e<0||e>255)throw new Error(`APDU ${t} ${e} is not a single byte (0..255)`)}function ur(e){if(z(e.cla,"cla"),z(e.ins,"ins"),z(e.p1,"p1"),z(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 Yt(){return globalThis.__LEDGER_VAULT_APDU_TRACE__===!0}function xe(e){return async t=>{const n=`${N(t.cla)} ${N(t.ins)} ${N(t.p1)} ${N(t.p2)} Lc=${t.data.length}`;let r;try{r=await e.dmk.sendApdu({sessionId:e.sessionId,apdu:ur(t)})}catch(s){throw Yt()&&console.debug(`[ledger-vault] APDU ${n} -> transport error`,s),s}const o=cr(r);return Yt()&&console.debug(`[ledger-vault] APDU ${n} -> sw=0x${Oe(o)} len=${r.data.length}`),{sw:o,data:r.data}}}function lr(e){return ar(xe(e),{appName:e.appName,appVersion:e.appVersion})}const hr={isRefresherDisabled:!0};let D,M;function fr(){if(!M){const e=(async()=>{const[{DeviceManagementKitBuilder:t},{webHidTransportFactory:n}]=await Promise.all([import("@ledgerhq/device-management-kit"),import("@ledgerhq/device-transport-kit-web-hid")]);return D=new t().addTransport(n).build(),D})().catch(t=>{throw M===e&&(M=void 0),t});M=e}return M}async function pr(){const e=await fr(),[{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:hr}),s=await dr(e,o);return{dmk:e,sessionId:o,...s}}async function dr(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 gr(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 Er(e){try{await e.dmk.disconnect({sessionId:e.sessionId})}catch{}}function wr(){D==null||D.close(),D=void 0,M=void 0}const _r=2,mr=3,Xt=32,Tr=10,Wt=0xffffffffn,qt=72,Ir=1008,Sr=4320,yr=91,Pr=4031,Ce=546n,zt=Ce,br=2n,Le="DepositTermsRejectedError";class T extends Error{constructor(n,r="device-envelope"){super(n);p(this,"reason");this.name=Le,this.reason=r}}const y="Deposit terms outside the device-supported range";function O(e,t,n,r){if(!Number.isInteger(t)||t<n||t>r)throw new T(`${y}: ${e} ${t} not in [${n}, ${r}]`)}function Rr(e){if(O("vaultCoreVersion",e.vaultCoreVersion,_r,mr),e.protocolFeeRate<1n||e.protocolFeeRate>Wt)throw new T(`${y}: protocolFeeRate ${e.protocolFeeRate} not in [1, ${Wt}]`);if(O("timelockPegin",e.timelockPegin,qt,Ir),O("timelockAssert",e.timelockAssert,yr,Pr),O("timelockRefund",e.timelockRefund,qt,Sr),O("keeper count",e.vaultKeeperBtcPubkeys.length,1,Xt),O("challenger count",e.universalChallengerBtcPubkeys.length,1,Xt),O("vault count",e.vaults.length,1,Tr),G("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 l=n(h);if(r.has(l))throw new T(`${y}: ${a} contains the vault provider's own key (${l.slice(0,16)}…)`);if(o.has(l))throw new T(`${y}: duplicate participant key in ${a} (${l.slice(0,16)}…)`);o.add(l)}const s=Ce,i=br*s;for(const a of e.vaults){if(G(`vault ${a.htlcVout} peginAmount`,a.peginAmount),G(`vault ${a.htlcVout} commissionFee`,a.commissionFee),G(`vault ${a.htlcVout} depositorClaimValue`,a.depositorClaimValue),G(`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<zt)throw new T(`${y}: vault ${a.htlcVout} depositorClaimValue ${a.depositorClaimValue} below the ${zt}-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 Ar=(1n<<64n)-1n;function G(e,t){if(t<0n||t>Ar)throw new T(`${y}: ${e} ${t} does not fit in an unsigned 64-bit field`)}const P=2147483648,Or=4294967295,nt=86,Me=0,ve=1,jt=5,xt=3,Br=3,xr=4;function Ne(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>Or)throw new Error(`${e} levels must be integers in 0..0xffffffff`);if(!t.slice(0,xt).every(r=>(r&P)!==0)||(t[xr]&P)!==0)throw new Error(`${e} must harden purpose'/coin'/account' and leave the address index unhardened`);if(t[0]!==(P|nt)>>>0)throw new Error(`${e} must use BIP-86 purpose ${nt}'`)}function X(e){return"m/"+e.map(t=>(t&P)!==0?`${(t&~P)>>>0}'`:`${t>>>0}`).join("/")}const Zt=253,Cr=254,Lr=65535,Mr=4294967295;function vr(e){if(e<Zt)return c.Buffer.from([e]);if(e<=Lr){const t=c.Buffer.alloc(2);return t.writeUInt16LE(e),c.Buffer.concat([c.Buffer.from([Zt]),t])}if(e<=Mr){const t=c.Buffer.alloc(4);return t.writeUInt32LE(e),c.Buffer.concat([c.Buffer.from([Cr]),t])}throw new Error(`Script too large to encode as CompactSize: ${e} bytes`)}const Nr="TapLeaf";function Dr(e,t){const n=c.Buffer.concat([c.Buffer.from([e]),vr(t.length),c.Buffer.from(t)]);return w.crypto.taggedHash(Nr,n)}function kr(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 $r(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 b(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 Ur(e){if(typeof e=="number"&&(e=b(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 Vr=BigInt(253),Hr=BigInt(65535)+BigInt(1),Gr=BigInt(4294967295)+BigInt(1);function De(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=Vr):n===254?(r=4,o=Hr):(r=8,o=Gr);const s=$r(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=b(e));const t=Ur(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,kr(e,t-1,n,1)),n}const Kr=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 gt(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>Kr)throw new Error("Can't encode numbers > MAX_SAFE_INT");for(let r=e.length-1;r>=0;r--){const o=e[r];if(o===void 0)throw new Error("Buffer too small");t=t*256+o}return t}class B{constructor(){p(this,"bufs",[])}write(t,n){const r=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 gt(t)}readVarInt(){const[t,n]=De(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=b(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 Et=(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))(Et||{});const Qt=c.Buffer.from([112,115,98,116,255]),Fr=4294967295;class $e extends Error{}class Ue{constructor(){p(this,"globalMap",new Map);p(this,"inputMaps",[]);p(this,"outputMaps",[])}setGlobalTxVersion(t){this.setGlobal(2,C(t))}getGlobalTxVersion(){return this.getGlobal(2).readUInt32LE(0)}setGlobalFallbackLocktime(t){this.setGlobal(3,C(t))}getGlobalFallbackLocktime(){var t;return(t=this.getGlobalOptional(3))==null?void 0:t.readUInt32LE(0)}setGlobalInputCount(t){this.setGlobal(4,ee(t))}getGlobalInputCount(){return ne(this.getGlobal(4))}setGlobalOutputCount(t){this.setGlobal(5,ee(t))}getGlobalOutputCount(){return ne(this.getGlobal(5))}setGlobalTxModifiable(t){this.setGlobal(6,t)}getGlobalTxModifiable(){return this.getGlobalOptional(6)}setGlobalPsbtVersion(t){this.setGlobal(251,C(t))}getGlobalPsbtVersion(){return this.getGlobal(251).readUInt32LE(0)}setInputNonWitnessUtxo(t,n){this.setInput(t,0,E(),n)}getInputNonWitnessUtxo(t){return this.getInputOptional(t,0,E())}setInputWitnessUtxo(t,n,r){const o=new B;o.writeSlice(te(n)),o.writeVarSlice(r),this.setInput(t,1,E(),o.buffer())}getInputWitnessUtxo(t){const n=this.getInputOptional(t,1,E());if(!n)return;const r=new k(n);return{amount:gt(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,E(),C(n))}getInputSighashType(t){const n=this.getInputOptional(t,3,E());if(n)return n.readUInt32LE(0)}setInputRedeemScript(t,n){this.setInput(t,4,E(),n)}getInputRedeemScript(t){return this.getInputOptional(t,4,E())}setInputWitnessScript(t,n){this.setInput(t,5,E(),n)}getInputWitnessScript(t){return this.getInputOptional(t,5,E())}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,E(),n)}getInputFinalScriptsig(t){return this.getInputOptional(t,7,E())}setInputFinalScriptwitness(t,n){this.setInput(t,8,E(),n)}getInputFinalScriptwitness(t){return this.getInput(t,8,E())}setInputPreviousTxId(t,n){this.setInput(t,14,E(),n)}getInputPreviousTxid(t){return this.getInput(t,14,E())}setInputOutputIndex(t,n){this.setInput(t,15,E(),C(n))}getInputOutputIndex(t){return this.getInput(t,15,E()).readUInt32LE(0)}setInputSequence(t,n){this.setInput(t,16,E(),C(n))}getInputSequence(t){var n;return((n=this.getInputOptional(t,16,E()))==null?void 0:n.readUInt32LE(0))??Fr}setInputTapKeySig(t,n){this.setInput(t,19,E(),n)}getInputTapKeySig(t){return this.getInputOptional(t,19,E())}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,E(),n)}getOutputRedeemScript(t){return this.getOutput(t,0,E())}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,E(),te(n))}getOutputAmount(t){const n=this.getOutput(t,3,E());return gt(n)}setOutputScript(t,n){this.setOutput(t,4,E(),n)}getOutputScript(t){return this.getOutput(t,4,E())}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 B;return t.writeSlice(Qt),lt(t,this.globalMap),this.inputMaps.forEach(n=>{lt(t,n)}),this.outputMaps.forEach(n=>{lt(t,n)}),t.buffer()}deserialize(t){const n=new k(t);if(!n.readSlice(5).equals(Qt))throw new Error("Invalid magic bytes");for(;this.readKeyPair(this.globalMap,n););let r;try{r=this.getGlobalPsbtVersion()}catch(i){if(!(i instanceof $e))throw i;r=0}if(r!==0&&r!==2)throw new Error("Only PSBTs of version 0 or 2 are supported");let o,s;if(r===0){const i=this.getGlobal(0),a=w.Transaction.fromBuffer(i);o=a.ins.length,s=a.outs.length}else o=this.getGlobalInputCount(),s=this.getGlobalOutputCount();for(let i=0;i<o;i++){const a=new Map;for(this.inputMaps[i]=a;this.readKeyPair(a,n););}for(let i=0;i<s;i++){const a=new Map;for(this.outputMaps[i]=a;this.readKeyPair(a,n););}if(n.available()!==0)throw new Error("Trailing bytes after PSBT output maps");this.normalizeToV2()}normalizeToV2(){var o;const t=(o=this.getGlobalOptional(251))==null?void 0:o.readUInt32LE(0);if(t===2)return;if(t!==void 0)throw new Error("Invalid or unsupported value for PSBT_GLOBAL_VERSION");const n=this.getGlobal(0),r=w.Transaction.fromBuffer(n);this.setGlobalPsbtVersion(2),this.setGlobalTxVersion(r.version),this.setGlobalFallbackLocktime(r.locktime),this.setGlobalInputCount(r.ins.length),this.setGlobalOutputCount(r.outs.length),r.ins.forEach((s,i)=>{this.setInputPreviousTxId(i,s.hash),this.setInputOutputIndex(i,s.index),this.setInputSequence(i,s.sequence)}),r.outs.forEach((s,i)=>{this.setOutputAmount(i,s.value),this.setOutputScript(i,s.script)}),this.globalMap.delete("0".padStart(2,"0"))}readKeyPair(t,n){const r=b(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 ut(this.globalMap,t,E())}getGlobalOptional(t){return wt(this.globalMap,t,E())}setInput(t,n,r,o){Jt(this.getMap(t,this.inputMaps),n,r,o)}getInput(t,n,r){return ut(this.inputMaps[t],n,r)}getInputOptional(t,n,r){return wt(this.inputMaps[t],n,r)}setOutput(t,n,r,o){Jt(this.getMap(t,this.outputMaps),n,r,o)}getOutput(t,n,r){return ut(this.outputMaps[t],n,r)}getMap(t,n){const r=n[t];if(r)return r;const o=new Map;return n[t]=o,o}encodeBip32Derivation(t,n){const r=new B;return this.writeBip32Derivation(r,t,n),r.buffer()}decodeBip32Derivation(t){const n=new 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 B;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=b(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 ut(e,t,n){const r=wt(e,t,n);if(r===void 0)throw new $e(new U(t,n).toString());return r}function wt(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 B;return this.toBuffer(t),t.buffer().toString("hex")}serialize(t){t.writeVarInt(1+this.keyData.length),this.toBuffer(t)}toBuffer(t){t.writeUInt8(this.keyType),t.writeSlice(this.keyData)}}class Yr{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 Xr(e){return new U(e.readUInt8(0),e.subarray(1))}function lt(e,t){const n=[...t].sort(([r],[o])=>r<o?-1:r>o?1:0);for(const[r,o]of n)new Yr(Xr(c.Buffer.from(r,"hex")),o).serialize(e);e.writeUInt8(0)}function E(){return c.Buffer.from([])}function Jt(e,t,n,r){const o=new U(t,n);e.set(o.toString(),r)}function C(e){const t=c.Buffer.alloc(4);return t.writeUInt32LE(e,0),t}function te(e){return ke(e)}function ee(e){const t=new B;return t.writeVarInt(e),t.buffer()}function ne(e){return b(new k(e).readVarInt())}const re=192,_t=32,oe=2,j=33,Z=32,Wr=1,qr="TapBranch",zr="TapTweak",se=64,ie=32,ht=64,jr=34,rt=c.Buffer.from([81,32]),Zr=c.Buffer.from([0,20]),Qr=2,Jr=3;function Ct(e){w.initEccLib(pt);const t=w.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 ae(e,t){const n=c.Buffer.concat([c.Buffer.from([t]),c.Buffer.from(e,"hex")]);return c.Buffer.concat([Zr,w.crypto.hash160(n)])}function Ve(e){return e.length===jr&&e.subarray(0,rt.length).equals(rt)}function to(e,t,n,r){if(!Ve(r))throw new d(`input ${e} is tapscript but its witnessUtxo script is not P2TR`);const o=t.length-j;if(o<0||o%Z!==0)throw new d(`input ${e} control block length ${t.length} is not ${j} plus a multiple of ${Z}`);const s=t.subarray(1,j);if(!pt.isXOnlyPoint(s))throw new d(`input ${e} control block internal key is not an x-only point`);let i=n;for(let l=j;l<t.length;l+=Z){const g=t.subarray(l,l+Z),f=c.Buffer.compare(i,g)<0?[i,g]:[g,i];i=w.crypto.taggedHash(qr,c.Buffer.concat(f))}const a=w.crypto.taggedHash(zr,c.Buffer.concat([s,i])),u=pt.xOnlyPointAddTweak(s,a);if(!u)throw new d(`input ${e} control block internal key has no taproot output key`);if(!r.subarray(rt.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]&Wr))throw new d(`input ${e} control block parity bit disagrees with the recomputed taproot output key`)}function eo(e){const{psbt:t,depositorXOnlyHex:n}=e,r=new Map,o=t.getGlobalInputCount(),s=Ct(n),i=[ae(n,Qr),ae(n,Jr)];for(let u=0;u<o;u++){const h=t.getInputEntriesOfType(u,Et.TAP_LEAF_SCRIPT);if(h.length>0){if(h.length>1)throw new d(`input ${u} carries an ambiguous leaf set (${h.length} TAP_LEAF_SCRIPT entries)`);const f=h[0].value;if(f.length<oe)throw new d(`input ${u} TAP_LEAF_SCRIPT value length ${f.length} is below the ${oe}-byte minimum (script byte plus the leaf-version byte)`);const _=f[f.length-1];if(_!==re)throw new d(`input ${u} leaf version 0x${_.toString(16)} is not tapscript (0xc0)`);const m=t.getInputWitnessUtxo(u);if(!m)throw new d(`input ${u} is tapscript but has no witnessUtxo`);const tn=f.subarray(0,f.length-1),Mt=Dr(re,tn);to(u,h[0].keyData,Mt,m.scriptPubKey),r.set(u,{kind:"tapscript",expectedLeafHashHexes:new Set([Mt.toString("hex")]),expectedSignerXOnlyHex:n});continue}const l=t.getInputEntriesOfType(u,Et.TAP_INTERNAL_KEY);if(l.length>0){const f=l[0];if(l.length>1||f.keyData.length!==0||f.value.length!==_t)throw new d(`input ${u} carries a malformed TAP_INTERNAL_KEY entry`);if(f.value.toString("hex")!==n)throw new d(`input ${u} internal key is not the connected depositor key`);const _=t.getInputWitnessUtxo(u);if(!_)throw new d(`input ${u} is keypath but has no witnessUtxo`);const m=_.scriptPubKey;if(!Ve(m))throw new d(`input ${u} witnessUtxo script is not P2TR`);if(!m.equals(s))throw new d(`input ${u} witnessUtxo is not the BIP-86 P2TR of the depositor key`);r.set(u,{kind:"taproot-keypath",expectedOutputKeyHex:m.subarray(rt.length).toString("hex")});continue}const g=t.getInputWitnessUtxo(u);if(g&&(g.scriptPubKey.equals(s)||i.some(f=>g.scriptPubKey.equals(f))))throw new d(`input ${u} spends a depositor-owned UTXO but carries no signing metadata`)}if(r.size===0)throw new d("PSBT contains no depositor-signable input");let a=0;for(const u of r.values())a+=u.kind==="tapscript"?u.expectedLeafHashHexes.size:1;return{byInput:r,expectedYieldCount:a}}function Q(e){return e.kind==="tapscript"?`${e.inputIndex}:${e.leafHashHex}`:`${e.inputIndex}`}function ce(e,t){if(e<ht)throw new d(`YIELD payload truncated inside the signature (${e} of ${ht} bytes on input ${t})`);if(e!==ht)throw new S("non-default-sighash",t)}function no(e){const t=[],n=new Set;return{assertAndRecord:s=>{let i,a;try{const[l,g]=De(s,0);i=b(l),a=g}catch(l){throw new d(`unparseable YIELD payload: ${l instanceof Error?l.message:String(l)}`)}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===se){if(h.kind!=="tapscript")throw new S("wrong-spend-type",i);const l=a+1+se;if(s.length<l)throw new d("YIELD payload truncated inside the augmented pubkey");const g=s.subarray(a+1,a+1+_t).toString("hex"),f=s.subarray(a+1+_t,l).toString("hex"),_=s.subarray(l);if(g!==h.expectedSignerXOnlyHex)throw new S("wrong-signer-key",i);if(!h.expectedLeafHashHexes.has(f))throw new S("unknown-leaf-hash",i);ce(_.length,i);const m={kind:"tapscript",inputIndex:i,signerXOnlyHex:g,leafHashHex:f,signature:Uint8Array.from(_)};if(n.has(Q(m)))throw new S("duplicate-yield",i);n.add(Q(m)),t.push(m);return}if(u===ie){if(h.kind!=="taproot-keypath")throw new S("wrong-spend-type",i);const l=a+1+ie;if(s.length<l)throw new d("YIELD payload truncated inside the augmented pubkey");const g=s.subarray(a+1,l).toString("hex"),f=s.subarray(l);if(g!==h.expectedOutputKeyHex)throw new S("wrong-signer-key",i);ce(f.length,i);const _={kind:"taproot-keypath",inputIndex:i,outputKeyHex:g,signature:Uint8Array.from(f)};if(n.has(Q(_)))throw new S("duplicate-yield",i);n.add(Q(_)),t.push(_);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 l of h.expectedLeafHashHexes)s.add(`${u}:${l}`);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 ye(i)}}}const He=/^[0-9a-f]{64}$/;function ro(e,t){if(Ne("depositorPath",e),e[Br]!==Me)throw new Error("depositorPath must use BIP-86 receive branch 0");for(let n=0;n<xt;n++)if(e[n]!==t[n])throw new Error(`depositorPath ${X(e)} is not under the wallet policy's key origin ${X(t)} — the device could never mark the input internal`)}function Ge(e,t,n,r){if(!Number.isInteger(r)||r<0||r>=P)throw new Error("addressIndex must be a non-hardened integer in 0..2^31-1");const o=ot.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 Ke(e,t,n){return Ge(e,t,ve,n)}function oo(e,t,n){return Ge(e,t,Me,n)}function Fe(e,t){const n=Ct(t);return e.txOutputs.flatMap((r,o)=>c.Buffer.from(r.script).equals(n)?[o]:[])}function so(e,t){if(!He.test(t))throw new Error("changeXOnlyHex must be 64 lowercase hex characters");return Fe(w.Psbt.fromHex(e),t).length>0}function io(e){const{psbtHex:t,depositorXOnlyHex:n,walletPolicy:r,depositorPath:o,change:s}=e;if(!He.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");ro(o,r.keyOriginPath);const i=w.Psbt.fromHex(t),a=c.Buffer.from(r.masterFingerprintHex,"hex"),u=c.Buffer.from(n,"hex");let h=0;if(i.data.inputs.forEach((l,g)=>{l.tapInternalKey&&c.Buffer.from(l.tapInternalKey).equals(u)&&(h++,i.updateInput(g,{tapBip32Derivation:[{masterFingerprint:a,pubkey:u,path:X(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 l=Ke(r.accountXpub,r.bip32Versions,s.addressIndex),g=[...o.slice(0,xt),ve,s.addressIndex],f=c.Buffer.from(l,"hex"),_=Fe(i,l);if(_.length===0)throw new Error("change script matches no output — the PSBT does not pay the wallet's change address");for(const m of _)i.updateOutput(m,{tapInternalKey:f,tapBip32Derivation:[{masterFingerprint:a,pubkey:f,path:X(g),leafHashes:[]}]})}return i.toHex()}const ao="BIP0322-signed-message",co=new Uint8Array([252,6,98,118,97,117,108,116,0]),Ye=0,Xe=0,We=0,uo=0,mt=0,lo=c.Buffer.from([106]),ho=/^[0-9a-f]{64}$/,fo=/^[0-9a-f]{8}$/,po=c.Buffer.alloc(32,0),go=4294967295,Eo=c.Buffer.from([0,32]),wo=c.Buffer.from([81,32]),_o=2;function mo(e,t){const n=w.crypto.sha256(c.Buffer.from(e,"utf8"));return w.crypto.sha256(c.Buffer.concat([n,n,c.Buffer.from(t)]))}function To(e,t){const n=new w.Transaction;n.version=Ye,n.locktime=Xe;const r=c.Buffer.concat([Eo,mo(ao,e)]);return n.addInput(po,go,We,r),n.addOutput(c.Buffer.concat([wo,c.Buffer.from(t)]),mt),Uint8Array.from(n.getHash(!1))}function Io(e){const{message:t,depositorXOnlyHex:n,masterFingerprintHex:r,depositorPath:o}=e;if(!ho.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");if(!fo.test(r))throw new Error("masterFingerprintHex must be 8 lowercase hex characters");Ne("depositorPath",o);const s=new TextEncoder().encode(t),i=c.Buffer.from(n,"hex"),a=Ct(n),u=To(s,a.subarray(_o)),h=new w.Psbt;return h.setVersion(Ye),h.setLocktime(Xe),h.addInput({hash:c.Buffer.from(u),index:uo,sequence:We,witnessUtxo:{script:a,value:mt},tapInternalKey:i,tapBip32Derivation:[{masterFingerprint:c.Buffer.from(r,"hex"),pubkey:i,path:X(o),leafHashes:[]}]}),h.addOutput({script:lo,value:mt}),h.addUnknownKeyValToGlobal({key:c.Buffer.from(co),value:c.Buffer.from(s)}),h.toHex()}class V{constructor(t,n=w.crypto.sha256){p(this,"leaves");p(this,"rootNode");p(this,"leafNodes");p(this,"h");this.leaves=t,this.h=n;const r=this.calculateRoot(t);this.rootNode=r.root,this.leafNodes=r.leaves}getRoot(){return this.rootNode.hash}size(){return this.leaves.length}getLeaves(){return this.leaves}getLeafHash(t){const n=this.leafNodes[t];if(n===void 0)throw Error("Index out of bounds");return n.hash}getProof(t){const n=this.leafNodes[t];if(n===void 0)throw Error("Index out of bounds");return Tt(n)}calculateRoot(t){const n=t.length;if(n==0)return{root:new ft(void 0,void 0,c.Buffer.alloc(32,0)),leaves:[]};if(n==1){const l=new ft(void 0,void 0,t[0]);return{root:l,leaves:[l]}}const r=yo(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 ft(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 H(e,t=w.crypto.sha256){return So(c.Buffer.from([0]),e,t)}function So(e,t,n){return n(c.Buffer.concat([e,t]))}class ft{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 Tt(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,...Tt(e.parent)]}else{if(!e.parent.leftChild)throw new Error("Expected left child to exist");return[e.parent.leftChild.hash,...Tt(e.parent)]}}function yo(e){if(e<2)throw Error("Expected n >= 2");return Po(e)?e/2:1<<Math.floor(Math.log2(e))}function Po(e){return(e&e-1)==0}const Lt=255,bo=2,I=32;class W{}class Ro extends W{constructor(n,r,o){super();p(this,"results");p(this,"code",16);this.progressCallback=r,this.onYield=o,this.results=n}execute(n){const r=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 Ao extends W{constructor(n,r){super();p(this,"knownPreimages");p(this,"queue");p(this,"code",64);this.knownPreimages=n,this.queue=r}execute(n){const r=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=Lt-a.length-1,h=Math.min(u,i.length);if(h<i.length)for(let l=h;l<i.length;l++)this.queue.push(c.Buffer.from(i.subarray(l,l+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 Oo extends W{constructor(n,r){super();p(this,"knownTrees");p(this,"queue");p(this,"code",65);this.knownTrees=n,this.queue=r}execute(n){const r=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=b(o.readVarInt()),u=b(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 l=h.getProof(u),g=Math.min(Math.floor((Lt-I-1-1)/I),l.length),f=l.length-g;return f>0&&this.queue.push(...l.slice(-f)),c.Buffer.concat([h.getLeafHash(u),c.Buffer.from([l.length]),c.Buffer.from([g]),...l.slice(0,g)])}}class Bo extends W{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,l=0;for(let g=0;g<u.size();g++)if(u.getLeafHash(g).toString("hex")===a){l=1,h=g;break}return c.Buffer.concat([c.Buffer.from([l]),$(h)])}}class xo extends W{constructor(n){super();p(this,"queue");p(this,"code",160);this.queue=n}execute(n){if(n.length!==1)throw new Error("Invalid request, unexpected trailing data");const r=this.queue[0];if(r===void 0)throw new Error("No elements to get");const o=r.length;if(this.queue.some(u=>u.length!==o))throw new Error("The queue contains elements with different byte length, which is not expected");const s=Math.floor((Lt-bo)/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 Co{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 Ro(this.yielded,t,n),new Ao(this.preimages,this.queue),new Bo(this.roots),new Oo(this.roots,this.queue),new xo(this.queue)];for(const o of r){if(this.commands.has(o.code))throw new Error(`Multiple commands with code ${o.code}`);this.commands.set(o.code,o)}}getYielded(){return this.yielded}addKnownPreimage(t){this.preimages.set(w.crypto.sha256(t).toString("hex"),t)}addKnownList(t){for(const r of t){const o=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 Lo{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 Y extends Ue{constructor(n){super();p(this,"globalMerkleMap");p(this,"inputMerkleMaps",[]);p(this,"outputMerkleMaps",[]);p(this,"inputMapCommitments");p(this,"outputMapCommitments");n.copy(this),this.globalMerkleMap=Y.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(Y.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(Y.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 Lo(s,o)}}const Mo=2;class vo{constructor(t,n,r){p(this,"name");p(this,"descriptorTemplate");p(this,"keys");this.name=t,this.descriptorTemplate=n,this.keys=r}getId(){return w.crypto.sha256(this.serialize())}serialize(){const t=this.keys.map(o=>c.Buffer.from(o,"ascii")),n=new V(t.map(o=>H(o))),r=new B;return r.writeUInt8(Mo),r.writeVarSlice(c.Buffer.from(this.name,"ascii")),r.writeVarInt(this.descriptorTemplate.length),r.writeSlice(w.crypto.sha256(c.Buffer.from(this.descriptorTemplate))),r.writeVarInt(this.keys.length),r.writeSlice(n.getRoot()),r.buffer()}}class qe extends vo{constructor(t,n){super("",t,[n])}}const No=4,Do=0,ko=1,ze=32,$o=new Uint8Array(ze),Uo=new Uint8Array(ze),Vo=/^[0-9a-f]{64}$/,Ho=/^(?:[0-9a-fA-F]{2})+$/,Go=/^[0-9a-f]{64}$/;function Ko(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(Uo)]))}function Fo(e){return{cla:R,ins:No,p1:Do,p2:ko,data:e}}const Yo=0;function Xo(e,t){for(const[n]of t.byInput){const r=e.data.inputs[n].sighashType;if(r!==void 0&&r!==Yo)throw new d(`input ${n} requests sighash type ${r}, but vault flows sign SIGHASH_DEFAULT only`)}}function Wo(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 qo(e,t){const n={...e};return je.set(n,t),n}function Ze(e){const t=je.get(e);if(!t)throw new d("unrecognised prepared signing state — use prepareSignPsbt's return value");return t}function Qe(e){const{psbtHex:t,depositorXOnlyHex:n,walletPolicy:r}=e;if(!Vo.test(n))throw new d("depositorXOnlyHex must be 64 lowercase hex characters");let o;if(r!==void 0){if(!Go.test(r.walletIdHex))throw new d("walletPolicy.walletIdHex must be 64 lowercase hex characters");if(o=new qe(r.descriptorTemplate,r.keyInfo),o.getId().toString("hex")!==r.walletIdHex)throw new d("walletPolicy.walletIdHex does not match sha256 of the serialized policy")}if(!Ho.test(t))throw new d("psbtHex is not even-length hexadecimal");let s;try{s=w.Psbt.fromHex(t)}catch(f){throw new d(`PSBT rejected at parse (merge target): ${f instanceof Error?f.message:String(f)}`)}const i=new Ue;try{i.deserialize(c.Buffer.from(t,"hex"))}catch(f){throw new d(`PSBT rejected at parse: ${f instanceof Error?f.message:String(f)}`)}let a,u;try{a=new Y(i),u=eo({psbt:a,depositorXOnlyHex:n})}catch(f){throw f instanceof d?f:new d(`PSBT rejected at preflight: ${f instanceof Error?f.message:String(f)}`)}Wo(s,u),Xo(s,u);const h=no(u),l=new Co(void 0,f=>h.assertAndRecord(f));l.addKnownMapping(a.globalMerkleMap);for(const f of a.inputMerkleMaps)l.addKnownMapping(f);for(const f of a.outputMerkleMaps)l.addKnownMapping(f);l.addKnownList(a.inputMapCommitments),l.addKnownList(a.outputMapCommitments);const g=r?c.Buffer.from(r.walletIdHex,"hex"):$o;return o&&l.addKnownWalletPolicy(o),qo({table:u,unsignedTxid:w.Transaction.fromBuffer(s.data.globalMap.unsignedTx.toBuffer()).getId()},{cdata:Ko(a,g),interpreter:l,collector:h,originalPsbtHex:t,signsUnderWalletPolicy:r!==void 0})}const zo=248,jo=1,Zo=0,Qo=0,Jo=36864,ts=57344;async function es(e,t,n){const{collector:r,interpreter:o,cdata:s}=Ze(t),{table:i}=t;if(n.signal.aborted)throw new dt(r.yields.length);const a=Fo(s);let u=a,h=await e(a),l=0;for(;h.sw===ts;){let g;try{g=o.execute(c.Buffer.from(h.data))}catch(f){throw Pe(f)?f:be(f)?new d(f.detail,J(r.yields)):new d(`client command failed: ${f instanceof Error?f.message:String(f)}`,J(r.yields))}if(r.yields.length>l){l=r.yields.length;const f=r.lastYield;if(f!==void 0&&n.onProgress!==void 0)try{n.onProgress({inputIndex:f.inputIndex,yieldedCount:l,expectedYieldCount:i.expectedYieldCount})}catch{}}if(n.signal.aborted)throw new dt(r.yields.length);u={cla:zo,ins:jo,p1:Zo,p2:Qo,data:g},h=await e(u)}if(h.sw!==Jo){const g=Be(h.sw,{...n.appIdentity,ins:u.ins,p1:u.p1});throw g===void 0?new d(`status word 0x${h.sw.toString(16)} escaped classification`,J(r.yields)):g}return r.assertComplete(),r.yields}function ns(e,t){const n=w.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 ue=new WeakSet;async function Je(e,t,n){const{originalPsbtHex:r,signsUnderWalletPolicy:o}=Ze(t);if(ue.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");ue.add(t);const i=await es(e,t,n);let a;try{a=ns(r,i)}catch(u){throw new d(`merge failed after signing: ${u instanceof Error?u.message:String(u)}`,J(i))}return{signedPsbtHex:a,yields:[...i]}}async function rs(e,t){const{psbtHex:n,depositorXOnlyHex:r,...o}=t,s=Qe({psbtHex:n,depositorXOnlyHex:r});return Je(e,s,o)}const le="tr(@0/**)",he=2147483647,os=/^[0-9a-f]{8}$/;function ss(e){const{masterFingerprintHex:t,coinType:n,accountIndex:r,accountXpub:o,bip32Versions:s}=e;if(!os.test(t))throw new Error("masterFingerprintHex must be 8 lowercase hex characters");if(!Number.isInteger(n)||n<0||n>he||!Number.isInteger(r)||r<0||r>he)throw new Error("coinType and accountIndex must be non-negative integers in 0..0x7fffffff");try{ot.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}/${nt}'/${n}'/${r}']${o}`,a=new qe(le,i).getId().toString("hex");return{descriptorTemplate:le,keyInfo:i,walletIdHex:a,accountXpub:o,bip32Versions:s,keyOriginPath:[(P|nt)>>>0,(P|n)>>>0,(P|r)>>>0],masterFingerprintHex:t}}exports.DEPOSIT_TERMS_REJECTED_ERROR_NAME=Le;exports.DepositTermsRejectedError=T;exports.LEDGER_DEVICE_ERROR_NAME=Pt;exports.LEDGER_DEVICE_LOCKED_ERROR_NAME=yt;exports.LEDGER_SIGN_PSBT_ABORTED_ERROR_NAME=Ot;exports.LEDGER_SIGN_PSBT_INCOMPLETE_ERROR_NAME=Rt;exports.LEDGER_SIGN_PSBT_PROTOCOL_ERROR_NAME=At;exports.LEDGER_USER_REFUSED_ERROR_NAME=St;exports.LEDGER_YIELD_MISMATCH_ERROR_NAME=bt;exports.LedgerDeviceError=Se;exports.LedgerDeviceLockedError=Ie;exports.LedgerSignPsbtAbortedError=dt;exports.LedgerSignPsbtIncompleteError=ye;exports.LedgerSignPsbtProtocolError=d;exports.LedgerUserRefusedError=Te;exports.LedgerYieldMismatchError=S;exports.SW_BAD_STATE=Re;exports.SW_CAP_EXCEEDED=Ae;exports.SW_CLA_NOT_SUPPORTED=Bt;exports.approveVaultIntent=Fn;exports.assertDepositTermsDeviceCompatible=Rr;exports.augmentPsbtForWalletPolicy=io;exports.buildDefaultTaprootPolicy=ss;exports.buildPopPsbtHex=Io;exports.closeDmk=wr;exports.connectDmkSession=pr;exports.createDmkApduSender=lr;exports.createDmkRawApduSender=xe;exports.deriveChangeXOnlyHex=Ke;exports.deriveContextHash=Kn;exports.deriveReceiveXOnlyHex=oo;exports.disconnectDmkSession=Er;exports.encodeIntentGroup=pe;exports.encodeIntentScalars=fe;exports.encodeKeyBatches=de;exports.getExtendedPublicKey=we;exports.getMasterFingerprintHex=zn;exports.getXOnlyPublicKeyHex=jn;exports.isLedgerDeviceError=Jn;exports.isLedgerDeviceLockedError=tr;exports.isLedgerSignPsbtAbortedError=nr;exports.isLedgerSignPsbtIncompleteError=er;exports.isLedgerSignPsbtProtocolError=be;exports.isLedgerUserRefusedError=Qn;exports.isLedgerYieldMismatchError=Pe;exports.isSessionAlive=gr;exports.prepareSignPsbt=Qe;exports.psbtPaysChangeScript=so;exports.signPreparedVaultPsbt=Je;exports.signVaultPsbt=rs;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|