@babylonlabs-io/ledger-vault-signer 0.9.2 → 0.9.4
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 +17 -9
- package/dist/deviceCaps.d.ts.map +1 -1
- package/dist/envelope.d.ts.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +238 -231
- package/dist/index.js.map +1 -1
- package/dist/refundPsbt.d.ts +16 -12
- package/dist/refundPsbt.d.ts.map +1 -1
- package/package.json +3 -3
package/dist/deviceCaps.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Ledger vault-app intent caps, mirrored from the firmware
|
|
3
|
-
* (`app-babylon-vault` @ `
|
|
3
|
+
* (`app-babylon-vault` @ `b0c0ac4d`: `vault_tlv.c`, `vault_intent.h`,
|
|
4
4
|
* `vault_constants.h`). The device rejects violations with SW_INCORRECT_DATA
|
|
5
5
|
* and a dead session, so we fail comprehensibly BEFORE the ceremony.
|
|
6
6
|
*
|
|
@@ -18,7 +18,7 @@ export declare const DEVICE_MIN_VAULT_CORE_VERSION = 2;
|
|
|
18
18
|
export declare const DEVICE_MAX_VAULT_CORE_VERSION = 3;
|
|
19
19
|
/**
|
|
20
20
|
* Keeper and universal-challenger counts, each `[1, 32]` (`vault_intent.h:8-9`,
|
|
21
|
-
* checked `vault_tlv.c:
|
|
21
|
+
* checked `vault_tlv.c:148,155`). Far below the protocol: the contract allows
|
|
22
22
|
* 1500 universal challengers and sets no keeper cap at all.
|
|
23
23
|
*/
|
|
24
24
|
export declare const DEVICE_MAX_PARTICIPANTS_PER_ROLE = 32;
|
|
@@ -30,19 +30,27 @@ export declare const DEVICE_MAX_PARTICIPANTS_PER_ROLE = 32;
|
|
|
30
30
|
export declare const DEVICE_MAX_VAULTS_PER_INTENT = 10;
|
|
31
31
|
/**
|
|
32
32
|
* Fee-rate bounds (sat/vB): the intent parser rejects rate == 0 AND
|
|
33
|
-
* rate >
|
|
34
|
-
*
|
|
33
|
+
* rate > 10000 (`vault_tlv.c:75`). The ceiling is vaultd's critical-tx config
|
|
34
|
+
* default (`btc-vault crates/vaultd/src/config/btc.rs:19` @ d0d139305), not a
|
|
35
|
+
* protocol constant; the contract caps `feeRate` at 1000 (`ProtocolParams.sol:44`),
|
|
36
|
+
* so a contract-sourced rate can never reach it.
|
|
35
37
|
*/
|
|
36
|
-
export declare const DEVICE_MAX_BASE_FEE_RATE_SAT_PER_VB =
|
|
37
|
-
/**
|
|
38
|
+
export declare const DEVICE_MAX_BASE_FEE_RATE_SAT_PER_VB = 10000n;
|
|
39
|
+
/**
|
|
40
|
+
* Upper bound on `prepegin_max_fee` (`vault_tlv.c:170`; `PREPEGIN_MAX_FEE_LIMIT`
|
|
41
|
+
* at `vault_constants.h:98`). Firmware-only — no btc-vault counterpart, and
|
|
42
|
+
* the SDK's sized fee cannot approach it at the contract's 1000 sat/vB cap.
|
|
43
|
+
*/
|
|
44
|
+
export declare const DEVICE_MAX_PREPEGIN_FEE_SATS = 100000000n;
|
|
45
|
+
/** Shared lower bound for the CSV/refund timelocks (`vault_constants.h:103`). */
|
|
38
46
|
export declare const DEVICE_TIMELOCK_MIN_BLOCKS = 72;
|
|
39
|
-
/** Inclusive upper bound for `pegin_csv_timelock` (`vault_constants.h:
|
|
47
|
+
/** Inclusive upper bound for `pegin_csv_timelock` (`vault_constants.h:106`). */
|
|
40
48
|
export declare const DEVICE_PEGIN_CSV_TIMELOCK_MAX_BLOCKS = 1008;
|
|
41
|
-
/** Inclusive upper bound for `htlc_refund_timelock` (`vault_constants.h:
|
|
49
|
+
/** Inclusive upper bound for `htlc_refund_timelock` (`vault_constants.h:109`). */
|
|
42
50
|
export declare const DEVICE_REFUND_TIMELOCK_MAX_BLOCKS = 4320;
|
|
43
51
|
/**
|
|
44
52
|
* Inclusive bounds for `payout_timelock`. The intent parser is EXCLUSIVE
|
|
45
|
-
* `(90, 4032)` (`vault_tlv.c`), so the accepted range is `[91, 4031]`; the
|
|
53
|
+
* `(90, 4032)` (`vault_tlv.c:94`), so the accepted range is `[91, 4031]`; the
|
|
46
54
|
* exclusive form gates deposits, so it wins over Screen 8's inclusive form.
|
|
47
55
|
*/
|
|
48
56
|
export declare const DEVICE_PAYOUT_TIMELOCK_MIN_BLOCKS = 91;
|
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,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,
|
|
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;;;;;;GAMG;AACH,eAAO,MAAM,mCAAmC,SAAU,CAAC;AAE3D;;;;GAIG;AACH,eAAO,MAAM,4BAA4B,aAAe,CAAC;AAEzD,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;AAkBH,OAAO,EAA6B,KAAK,YAAY,EAAE,MAAM,SAAS,CAAC;AAUvE;;;;GAIG;AACH,wBAAgB,kCAAkC,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI,CAoI5E"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var ln=Object.defineProperty;var fn=(e,t,n)=>t in e?ln(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var p=(e,t,n)=>fn(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const it=require("@scure/bip32"),at=require("./testing-DEVJn0Dm.cjs"),_=require("bitcoinjs-lib"),u=require("buffer"),hn=require("@bitcoin-js/tiny-secp256k1-asmjs");function pn(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const wt=pn(hn),dn=1,gn=1,En=1,wn=2,_n=33,mn=256,Tn=257,In=258,Sn=39,Pn=259,yn=105,bn=260,Rn=261,xn=262,An=271,On=265,Bn=266,vn=267,Cn=268,Ln=269,Mn=270,Nn=263,Dn=264,et=32,$n=32,F=255,kn=3+et,Ht=Math.floor(F/kn);function A(e,t){if(t.length>F)throw new Error(`TLV value for tag 0x${e.toString(16)} exceeds 255 bytes`);const n=new Uint8Array(3+t.length);return n[0]=e>>8&255,n[1]=e&255,n[2]=t.length,n.set(t,3),n}function ut(e,t,n){if(e<0n||e>=1n<<BigInt(8*t))throw new Error(`${n} ${e} does not fit in ${t} bytes`);const r=new Uint8Array(t);let o=e;for(let s=t-1;s>=0;s--)r[s]=Number(o&0xffn),o>>=8n;return r}function L(e,t,n){return A(e,ut(BigInt(t),1,n))}function z(e,t,n){return A(e,ut(BigInt(t),4,n))}function M(e,t,n){return A(e,ut(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 Rt(e,t,n){if(e.length!==t)throw new Error(`${n} must be ${t} bytes, got ${e.length}`);return e}const Vt=5;function Te(e){if(e.depositorPath.length!==Vt)throw new Error(`depositorPath must have exactly ${Vt} levels, got ${e.depositorPath.length}`);const t=nt(e.depositorPath.map(n=>ut(BigInt(n>>>0),4,"path level")));return nt([L(En,dn,"structureType"),L(wn,gn,"version"),z(_n,e.coinType,"coinType"),M(mn,e.baseFeeRate,"baseFeeRate"),z(Tn,e.peginCsvTimelock,"peginCsvTimelock"),z(In,e.payoutTimelock,"payoutTimelock"),A(Sn,Rt(e.prepeginTxidInternal,$n,"prepeginTxid")),z(Pn,e.htlcRefundTimelock,"htlcRefundTimelock"),A(yn,t),L(bn,e.keeperCount,"keeperCount"),L(Rn,e.challengerCount,"challengerCount"),L(xn,e.vaultCount,"vaultCount"),M(An,e.prepeginMaxFee,"prepeginMaxFee")])}function Ie(e){return nt([L(On,e.htlcVout,"htlcVout"),A(Bn,Rt(e.vaultProviderPubkey,et,"vaultProviderPubkey")),M(vn,e.vaultAmount,"vaultAmount"),M(Cn,e.commissionFee,"commissionFee"),M(Ln,e.depositorClaimValue,"depositorClaimValue"),M(Mn,e.peginMaxFee,"peginMaxFee")])}function Se(e,t){const n=(s,i)=>s.map((a,c)=>Rt(a,et,`${i}[${c}]`)).sort((a,c)=>{for(let l=0;l<et;l++)if(a[l]!==c[l])return a[l]-c[l];return 0}),r=[...n(e,"keeper").map(s=>A(Nn,s)),...n(t,"challenger").map(s=>A(Dn,s))],o=[];for(let s=0;s<r.length;s+=Ht)o.push(nt(r.slice(s,s+Ht)));return o}const x=225,ft=128,Gt=129,Un=0,Hn=1,Vn=0,Gn=1,Kn=2,Y=0,Kt=64,Ft=1024,Yt=10,Xt=32;function Fn(e){return new Uint8Array([e>>8&255,e&255])}function Yn(e){const t=e>>>0;return new Uint8Array([t>>>24&255,t>>>16&255,t>>>8&255,t&255])}function ht(e){const t=new Uint8Array(e.reduce((r,o)=>r+o.length,0));let n=0;for(const r of e)t.set(r,n),n+=r.length;return t}const qt=/^[a-z0-9-]+$/;async function Xn(e,{appName:t,derivationPath:n,context:r}){const o=new TextEncoder().encode(t);if(o.length<1||o.length>Kt)throw new Error(`appName must be 1..${Kt} bytes, got ${o.length}`);if(!qt.test(t))throw new Error(`appName must match ${qt} — the device rejects other characters`);if(n.length<1||n.length>Yt)throw new Error(`derivationPath must have 1..${Yt} levels`);if(r.length<1||r.length>Ft)throw new Error(`context must be 1..${Ft} bytes, got ${r.length}`);const s=ht([new Uint8Array([o.length]),o,new Uint8Array([n.length]),ht(n.map(Yn)),Fn(r.length)]),i=Math.min(r.length,F-s.length);if(i<0)throw new Error("appName and derivationPath leave no room for context in the first APDU");let a=await e({cla:x,ins:Gt,p1:Un,p2:Y,data:ht([s,r.subarray(0,i)])});for(let c=i;c<r.length;c+=F)a=await e({cla:x,ins:Gt,p1:Hn,p2:Y,data:r.subarray(c,c+F)});if(a.length!==Xt)throw new Error(`Expected a ${Xt}-byte context root, got ${a.length} bytes`);return a}async function qn(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:x,ins:ft,p1:Vn,p2:Y,data:Te(t)});for(const s of n)await e({cla:x,ins:ft,p1:Gn,p2:Y,data:Ie(s)});for(const s of Se(r,o))await e({cla:x,ins:ft,p1:Kn,p2:Y,data:s})}const Wn=0,Pe=0,ye=1,zn=0,Wt=33,zt=10,jn=5,Qn=4;async function Zn(e){const t=await e({cla:x,ins:jn,p1:Pe,p2:ye,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 Re(t)}async function be(e,t,n){if(t.length<1||t.length>zt)throw new Error(`BIP-32 path must have 1..${zt} levels, got ${t.length}`);const r=await e({cla:x,ins:Wn,p1:Pe,p2:ye,data:tr(t)}),o=new TextDecoder().decode(r);if(o.length===0)throw new Error("Ledger returned an empty extended key");return it.HDKey.fromExtendedKey(o,n),o}async function Jn(e,t,n){const r=await be(e,t,n),o=it.HDKey.fromExtendedKey(r,n);if(!o.publicKey||o.publicKey.length!==Wt)throw new Error(`Ledger returned an extended key without a ${Wt}-byte public key`);return Re(o.publicKey.subarray(1))}function Re(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function tr(e){const t=new Uint8Array(2+e.length*4);return t[0]=zn,t[1]=e.length,e.forEach((n,r)=>{const o=2+r*4;t[o]=n>>>24&255,t[o+1]=n>>>16&255,t[o+2]=n>>>8&255,t[o+3]=n&255}),t}const xt="LedgerUserRefusedError",At="LedgerDeviceLockedError",Ot="LedgerDeviceError",Bt="LedgerYieldMismatchError",vt="LedgerSignPsbtIncompleteError",Ct="LedgerSignPsbtProtocolError",Lt="LedgerSignPsbtAbortedError";function xe(e){return e.toString(16).padStart(4,"0")}class Ae extends Error{constructor(n){super(`User rejected the request on the Ledger device (0x${xe(n)})`);p(this,"statusWord");this.name=xt,this.statusWord=n}}class Oe extends Error{constructor(n,r){super(`The Ledger device is locked — unlock it and retry (0x${xe(n)})`);p(this,"statusWord");p(this,"preDispatch");this.name=At,this.statusWord=n,this.preDispatch=(r==null?void 0:r.preDispatch)??!1}}class Be extends Error{constructor(n,r){super(r);p(this,"statusWord");this.name=Ot,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 ve extends Error{constructor(n){super(`The device completed SIGN_PSBT without yielding every expected signature (missing ${n.length}: ${n.join(", ")})`);p(this,"missing");this.name=vt,this.missing=n}}function tt(e){return e.map(({inputIndex:t,leafHashHex:n})=>n===void 0?{inputIndex:t}:{inputIndex:t,leafHashHex:n})}class d extends Error{constructor(n,r=[]){super(`SIGN_PSBT protocol failure: ${n}`);p(this,"detail");p(this,"collectedYields");this.name=Ct,this.detail=n,this.collectedYields=r}}class _t extends Error{constructor(n){super("SIGN_PSBT was abandoned host-side before completion");p(this,"yieldedCount");this.name=Lt,this.yieldedCount=n}}function er(e){return e instanceof Error&&e.name===xt}function nr(e){return e instanceof Error&&e.name===Ot}function rr(e){return e instanceof Error&&e.name===At}function Ce(e){return e instanceof Error&&e.name===Bt}function or(e){return e instanceof Error&&e.name===vt}function Le(e){return e instanceof Error&&e.name===Ct}function sr(e){return e instanceof Error&&e.name===Lt}const ir=36864,ar=new Set([21761,27013]),ur=new Set([21781,27010,21251]),Mt=28160,Me=45063,Ne=45066,cr={27264:"The device rejected the data as invalid",27266:"The device does not support this request — check that the app build matches the selected network",27270:"The device rejected the instruction parameters",27271:"The device rejected the payload length",27904:"The running app does not support this instruction",[Mt]:"The running app does not handle vault instructions — open the Babylon Vault app for this network",45056:"The device reported a wrong response length",[Me]:"The device is not in the expected state for this step",45064:"The device rejected a signature or HMAC as invalid",45065:"The device rejected the CPFP anchor",[Ne]:"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 De(e){return e.toString(16).padStart(4,"0")}function $e(e,t){if(e===ir)return;if(ar.has(e))return new Ae(e);if(ur.has(e))return new Oe(e,{preDispatch:t.preDispatch===!0});const n=cr[e],r=e===Mt&&t.appName?` (app at connect time: "${t.appName}"${t.appVersion?` v${t.appVersion}`:""})`:"";return new Be(e,`${n??"The device rejected the request"} (ins 0x${N(t.ins)} p1 0x${N(t.p1)}, sw 0x${De(e)})${r}`)}function lr(e,t){return async n=>{const{sw:r,data:o}=await e(n),s=$e(r,{...t,ins:n.ins,p1:n.p1});if(s)throw s;return o}}const jt=2;function fr(e){if(e.statusCode.length!==jt)throw new Error(`The device returned a ${e.statusCode.length}-byte status word; expected ${jt}.`);return e.statusCode[0]<<8|e.statusCode[1]}function j(e,t){if(!Number.isInteger(e)||e<0||e>255)throw new Error(`APDU ${t} ${e} is not a single byte (0..255)`)}function hr(e){if(j(e.cla,"cla"),j(e.ins,"ins"),j(e.p1,"p1"),j(e.p2,"p2"),e.data.length>255)throw new Error(`APDU data is ${e.data.length} bytes; Lc is a single byte (max 255)`);const t=new Uint8Array(5+e.data.length);return t[0]=e.cla,t[1]=e.ins,t[2]=e.p1,t[3]=e.p2,t[4]=e.data.length,t.set(e.data,5),t}function Qt(){return globalThis.__LEDGER_VAULT_APDU_TRACE__===!0}function ke(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:hr(t)})}catch(s){throw Qt()&&console.debug(`[ledger-vault] APDU ${n} -> transport error`,s),s}const o=fr(r);return Qt()&&console.debug(`[ledger-vault] APDU ${n} -> sw=0x${De(o)} len=${r.data.length}`),{sw:o,data:r.data}}}function pr(e){return lr(ke(e),{appName:e.appName,appVersion:e.appVersion})}const dr=2,gr=3,Zt=32,Er=10,Jt=0xffffffffn,rt=72,wr=1008,_r=4320,mr=91,Tr=4031,Ue=546n,te=Ue,Ir=2n,He="DepositTermsRejectedError";class T extends Error{constructor(n,r="device-envelope"){super(n);p(this,"reason");this.name=He,this.reason=r}}const P="Deposit terms outside the device-supported range";function O(e,t,n,r){if(!Number.isInteger(t)||t<n||t>r)throw new T(`${P}: ${e} ${t} not in [${n}, ${r}]`)}function Sr(e){if(O("vaultCoreVersion",e.vaultCoreVersion,dr,gr),e.protocolFeeRate<1n||e.protocolFeeRate>Jt)throw new T(`${P}: protocolFeeRate ${e.protocolFeeRate} not in [1, ${Jt}]`);if(O("timelockPegin",e.timelockPegin,rt,wr),O("timelockAssert",e.timelockAssert,mr,Tr),O("timelockRefund",e.timelockRefund,rt,_r),O("keeper count",e.vaultKeeperBtcPubkeys.length,1,Zt),O("challenger count",e.universalChallengerBtcPubkeys.length,1,Zt),O("vault count",e.vaults.length,1,Er),K("prepeginMaxFee",e.prepeginMaxFee),e.prepeginMaxFee<1n)throw new T(`${P}: 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(`${P}: htlcVout ${a.htlcVout} not in [0, 255]`);if(a.htlcVout<=t)throw new T(`${P}: vault groups must be in strictly ascending htlcVout order; got ${a.htlcVout} after ${t}`);t=a.htlcVout}const n=a=>a.replace(/^0x/,"").toLowerCase(),r=new Set(e.vaults.map(a=>n(a.vaultProviderBtcPubkey))),o=new Set;for(const[a,c]of[["vaultKeeperBtcPubkeys",e.vaultKeeperBtcPubkeys],["universalChallengerBtcPubkeys",e.universalChallengerBtcPubkeys]])for(const l of c){const h=n(l);if(r.has(h))throw new T(`${P}: ${a} contains the vault provider's own key (${h.slice(0,16)}…)`);if(o.has(h))throw new T(`${P}: duplicate participant key in ${a} (${h.slice(0,16)}…)`);o.add(h)}const s=Ue,i=Ir*s;for(const a of e.vaults){if(K(`vault ${a.htlcVout} peginAmount`,a.peginAmount),K(`vault ${a.htlcVout} commissionFee`,a.commissionFee),K(`vault ${a.htlcVout} depositorClaimValue`,a.depositorClaimValue),K(`vault ${a.htlcVout} peginMaxFee`,a.peginMaxFee),a.commissionFee<s)throw new T(`${P}: vault ${a.htlcVout} commissionFee ${a.commissionFee} below the ${s}-sat dust limit`);if(a.depositorClaimValue<te)throw new T(`${P}: vault ${a.htlcVout} depositorClaimValue ${a.depositorClaimValue} below the ${te}-sat device floor`);if(a.peginAmount<=a.commissionFee+i)throw new T(`${P}: vault ${a.htlcVout} peginAmount ${a.peginAmount} must exceed commissionFee + ${i} (${a.commissionFee+i})`)}}const Pr=(1n<<64n)-1n;function K(e,t){if(t<0n||t>Pr)throw new T(`${P}: ${e} ${t} does not fit in an unsigned 64-bit field`)}const b=2147483648,yr=4294967295,ot=86,Ve=0,Ge=1,ee=5,Nt=3,br=3,Rr=4;function Dt(e,t){if(t.length!==ee)throw new Error(`${e} must have exactly ${ee} levels, got ${t.length}`);for(const r of t)if(!Number.isInteger(r)||r<0||r>yr)throw new Error(`${e} levels must be integers in 0..0xffffffff`);if(!t.slice(0,Nt).every(r=>(r&b)!==0)||(t[Rr]&b)!==0)throw new Error(`${e} must harden purpose'/coin'/account' and leave the address index unhardened`);if(t[0]!==(b|ot)>>>0)throw new Error(`${e} must use BIP-86 purpose ${ot}'`)}function $(e){return"m/"+e.map(t=>(t&b)!==0?`${(t&~b)>>>0}'`:`${t>>>0}`).join("/")}const ne=253,xr=254,Ar=65535,Or=4294967295;function Br(e){if(e<ne)return u.Buffer.from([e]);if(e<=Ar){const t=u.Buffer.alloc(2);return t.writeUInt16LE(e),u.Buffer.concat([u.Buffer.from([ne]),t])}if(e<=Or){const t=u.Buffer.alloc(4);return t.writeUInt32LE(e),u.Buffer.concat([u.Buffer.from([xr]),t])}throw new Error(`Script too large to encode as CompactSize: ${e} bytes`)}const vr="TapLeaf";function Cr(e,t){const n=u.Buffer.concat([u.Buffer.from([e]),Br(t.length),u.Buffer.from(t)]);return _.crypto.taggedHash(vr,n)}function Lr(e,t,n,r){for(let o=0;o<t;o++){if(n[o+r]===void 0)throw Error("Buffer too small");n[o+r]=Number(e%BigInt(256)),e=e>>BigInt(8)}}function Mr(e,t,n){let r=BigInt(0);for(let o=0;o<n;o++){const s=e[o+t];if(s===void 0)throw Error("Buffer too small");r+=BigInt(s)<<BigInt(o*8)}return r}function R(e){if(e<0)throw RangeError("Negative bigint is not a valid varint");if(e>Number.MAX_SAFE_INTEGER)throw RangeError("Too large for a Number");return Number(e)}function Nr(e){if(typeof e=="number"&&(e=R(e)),e<BigInt(0))throw new RangeError("Negative numbers are not supported");if(e>=BigInt(1)<<BigInt(64))throw new RangeError("Too large for a Bitcoin-style varint");return e<BigInt(253)?1:e<=BigInt(65535)?3:e<=BigInt(4294967295)?5:9}const Dr=BigInt(253),$r=BigInt(65535)+BigInt(1),kr=BigInt(4294967295)+BigInt(1);function Ke(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=Dr):n===254?(r=4,o=$r):(r=8,o=kr);const s=Mr(e,t+1,r);if(s<o)throw RangeError(`Non-minimal varint at offset ${t}: a ${r+1}-byte CompactSize must encode a value of at least ${o}; re-encode it in its canonical (shorter) form`);return[s,r+1]}}function k(e){typeof e=="number"&&(e=R(e));const t=Nr(e);e=BigInt(e);const n=u.Buffer.alloc(t);return t==1?n[0]=Number(e):(t==3?n[0]=253:t===5?n[0]=254:n[0]=255,Lr(e,t-1,n,1)),n}const Ur=31;function Fe(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Can't convert a number that is not a non-negative safe integer to 64-bit LE");const t=u.Buffer.alloc(8,0);for(let n=0;n<t.length;n++){const r=e&255;t[n]=r,e=(e-r)/256}return t}function mt(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>Ur)throw new Error("Can't encode numbers > MAX_SAFE_INT");for(let r=e.length-1;r>=0;r--){const o=e[r];if(o===void 0)throw new Error("Buffer too small");t=t*256+o}return t}class B{constructor(){p(this,"bufs",[])}write(t,n){const r=u.Buffer.alloc(t);n(r),this.bufs.push(r)}writeUInt8(t){this.write(1,n=>n.writeUInt8(t,0))}writeInt32(t){this.write(4,n=>n.writeInt32LE(t,0))}writeUInt32(t){this.write(4,n=>n.writeUInt32LE(t,0))}writeUInt64(t){const n=Fe(t);this.writeSlice(n)}writeVarInt(t){this.bufs.push(k(t))}writeSlice(t){this.bufs.push(u.Buffer.from(t))}writeVarSlice(t){this.writeVarInt(t.length),this.writeSlice(t)}buffer(){return u.Buffer.concat(this.bufs)}}class D{constructor(t,n=0){this.buffer=t,this.offset=n}available(){return this.buffer.length-this.offset}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=this.readSlice(8);return mt(t)}readVarInt(){const[t,n]=Ke(this.buffer,this.offset);return this.offset+=n,t}readSlice(t){if(this.buffer.length<this.offset+t)throw new Error("Cannot read slice out of bounds");const n=this.buffer.subarray(this.offset,this.offset+t);return this.offset+=t,n}readVarSlice(){const t=R(this.readVarInt());return this.readSlice(t)}readVector(){const t=this.readVarInt(),n=[];for(let r=0;r<t;r++)n.push(this.readVarSlice());return n}}var Tt=(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))(Tt||{});const re=u.Buffer.from([112,115,98,116,255]),Hr=4294967295;class Ye extends Error{}class Xe{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,ie(t))}getGlobalInputCount(){return ae(this.getGlobal(4))}setGlobalOutputCount(t){this.setGlobal(5,ie(t))}getGlobalOutputCount(){return ae(this.getGlobal(5))}setGlobalTxModifiable(t){this.setGlobal(6,t)}getGlobalTxModifiable(){return this.getGlobalOptional(6)}setGlobalPsbtVersion(t){this.setGlobal(251,C(t))}getGlobalPsbtVersion(){return this.getGlobal(251).readUInt32LE(0)}setInputNonWitnessUtxo(t,n){this.setInput(t,0,w(),n)}getInputNonWitnessUtxo(t){return this.getInputOptional(t,0,w())}setInputWitnessUtxo(t,n,r){const o=new B;o.writeSlice(se(n)),o.writeVarSlice(r),this.setInput(t,1,w(),o.buffer())}getInputWitnessUtxo(t){const n=this.getInputOptional(t,1,w());if(!n)return;const r=new D(n);return{amount:mt(r.readSlice(8)),scriptPubKey:r.readVarSlice()}}setInputPartialSig(t,n,r){this.setInput(t,2,n,r)}getInputPartialSig(t,n){return this.getInputOptional(t,2,n)}setInputSighashType(t,n){this.setInput(t,3,w(),C(n))}getInputSighashType(t){const n=this.getInputOptional(t,3,w());if(n)return n.readUInt32LE(0)}setInputRedeemScript(t,n){this.setInput(t,4,w(),n)}getInputRedeemScript(t){return this.getInputOptional(t,4,w())}setInputWitnessScript(t,n){this.setInput(t,5,w(),n)}getInputWitnessScript(t){return this.getInputOptional(t,5,w())}setInputBip32Derivation(t,n,r,o){if(n.length!==33)throw new Error("Invalid pubkey length: "+n.length);this.setInput(t,6,n,this.encodeBip32Derivation(r,o))}getInputBip32Derivation(t,n){const r=this.getInputOptional(t,6,n);if(r)return this.decodeBip32Derivation(r)}setInputFinalScriptsig(t,n){this.setInput(t,7,w(),n)}getInputFinalScriptsig(t){return this.getInputOptional(t,7,w())}setInputFinalScriptwitness(t,n){this.setInput(t,8,w(),n)}getInputFinalScriptwitness(t){return this.getInput(t,8,w())}setInputPreviousTxId(t,n){this.setInput(t,14,w(),n)}getInputPreviousTxid(t){return this.getInput(t,14,w())}setInputOutputIndex(t,n){this.setInput(t,15,w(),C(n))}getInputOutputIndex(t){return this.getInput(t,15,w()).readUInt32LE(0)}setInputSequence(t,n){this.setInput(t,16,w(),C(n))}getInputSequence(t){var n;return((n=this.getInputOptional(t,16,w()))==null?void 0:n.readUInt32LE(0))??Hr}setInputTapKeySig(t,n){this.setInput(t,19,w(),n)}getInputTapKeySig(t){return this.getInputOptional(t,19,w())}setInputTapBip32Derivation(t,n,r,o,s){if(n.length!==32)throw new Error("Invalid pubkey length: "+n.length);const i=this.encodeTapBip32Derivation(r,o,s);this.setInput(t,22,n,i)}getInputTapBip32Derivation(t,n){const r=this.getInput(t,22,n);return this.decodeTapBip32Derivation(r)}getInputKeyDatas(t,n){return this.getKeyDatas(this.inputMaps[t],n)}getInputEntriesOfType(t,n){const r=this.inputMaps[t];if(!r)throw new Error("No such map");const o=[];return r.forEach((s,i)=>{this.isKeyType(i,[n])&&o.push({keyData:u.Buffer.from(i.substring(2),"hex"),value:u.Buffer.from(s)})}),o}setOutputRedeemScript(t,n){this.setOutput(t,0,w(),n)}getOutputRedeemScript(t){return this.getOutput(t,0,w())}setOutputBip32Derivation(t,n,r,o){this.setOutput(t,2,n,this.encodeBip32Derivation(r,o))}getOutputBip32Derivation(t,n){const r=this.getOutput(t,2,n);return this.decodeBip32Derivation(r)}setOutputAmount(t,n){this.setOutput(t,3,w(),se(n))}getOutputAmount(t){const n=this.getOutput(t,3,w());return mt(n)}setOutputScript(t,n){this.setOutput(t,4,w(),n)}getOutputScript(t){return this.getOutput(t,4,w())}setOutputTapBip32Derivation(t,n,r,o,s){const i=this.encodeTapBip32Derivation(r,o,s);this.setOutput(t,7,n,i)}getOutputTapBip32Derivation(t,n){const r=this.getOutput(t,7,n);return this.decodeTapBip32Derivation(r)}deleteInputEntries(t,n){const r=this.inputMaps[t];if(!r)throw new Error("No such map");r.forEach((o,s,i)=>{this.isKeyType(s,n)&&i.delete(s)})}copy(t){this.copyMap(this.globalMap,t.globalMap),this.copyMaps(this.inputMaps,t.inputMaps),this.copyMaps(this.outputMaps,t.outputMaps)}copyMaps(t,n){t.forEach((r,o)=>{const s=new Map;this.copyMap(r,s),n[o]=s})}copyMap(t,n){t.forEach((r,o)=>n.set(o,u.Buffer.from(r)))}serialize(){const t=new B;return t.writeSlice(re),dt(t,this.globalMap),this.inputMaps.forEach(n=>{dt(t,n)}),this.outputMaps.forEach(n=>{dt(t,n)}),t.buffer()}deserialize(t){const n=new D(t);if(!n.readSlice(5).equals(re))throw new Error("Invalid magic bytes");for(;this.readKeyPair(this.globalMap,n););let r;try{r=this.getGlobalPsbtVersion()}catch(i){if(!(i instanceof Ye))throw i;r=0}if(r!==0&&r!==2)throw new Error("Only PSBTs of version 0 or 2 are supported");let o,s;if(r===0){const i=this.getGlobal(0),a=_.Transaction.fromBuffer(i);o=a.ins.length,s=a.outs.length}else o=this.getGlobalInputCount(),s=this.getGlobalOutputCount();for(let i=0;i<o;i++){const a=new Map;for(this.inputMaps[i]=a;this.readKeyPair(a,n););}for(let i=0;i<s;i++){const a=new Map;for(this.outputMaps[i]=a;this.readKeyPair(a,n););}if(n.available()!==0)throw new Error("Trailing bytes after PSBT output maps");this.normalizeToV2()}normalizeToV2(){var o;const t=(o=this.getGlobalOptional(251))==null?void 0:o.readUInt32LE(0);if(t===2)return;if(t!==void 0)throw new Error("Invalid or unsupported value for PSBT_GLOBAL_VERSION");const n=this.getGlobal(0),r=_.Transaction.fromBuffer(n);this.setGlobalPsbtVersion(2),this.setGlobalTxVersion(r.version),this.setGlobalFallbackLocktime(r.locktime),this.setGlobalInputCount(r.ins.length),this.setGlobalOutputCount(r.outs.length),r.ins.forEach((s,i)=>{this.setInputPreviousTxId(i,s.hash),this.setInputOutputIndex(i,s.index),this.setInputSequence(i,s.sequence)}),r.outs.forEach((s,i)=>{this.setOutputAmount(i,s.value),this.setOutputScript(i,s.script)}),this.globalMap.delete("0".padStart(2,"0"))}readKeyPair(t,n){const r=R(n.readVarInt());if(r===0)return!1;const o=n.readUInt8(),s=n.readSlice(r-1),i=n.readVarSlice(),a=new U(o,s).toString();if(t.has(a))throw new Error("Repeated keypair in PSBT map");return t.set(a,i),!0}getKeyDatas(t,n){if(!t)throw new Error("No such map");const r=[];return t.forEach((o,s)=>{this.isKeyType(s,[n])&&r.push(u.Buffer.from(s.substring(2),"hex"))}),r}isKeyType(t,n){const r=u.Buffer.from(t.substring(0,2),"hex").readUInt8(0);return n.some(o=>o===r)}setGlobal(t,n){const r=new U(t,u.Buffer.from([]));this.globalMap.set(r.toString(),n)}getGlobal(t){return pt(this.globalMap,t,w())}getGlobalOptional(t){return It(this.globalMap,t,w())}setInput(t,n,r,o){oe(this.getMap(t,this.inputMaps),n,r,o)}getInput(t,n,r){return pt(this.inputMaps[t],n,r)}getInputOptional(t,n,r){return It(this.inputMaps[t],n,r)}setOutput(t,n,r,o){oe(this.getMap(t,this.outputMaps),n,r,o)}getOutput(t,n,r){return pt(this.outputMaps[t],n,r)}getMap(t,n){const r=n[t];if(r)return r;const o=new Map;return n[t]=o,o}encodeBip32Derivation(t,n){const r=new B;return this.writeBip32Derivation(r,t,n),r.buffer()}decodeBip32Derivation(t){const n=new D(t);return this.readBip32Derivation(n)}writeBip32Derivation(t,n,r){t.writeSlice(n),r.forEach(o=>{t.writeUInt32(o)})}readBip32Derivation(t){const n=t.readSlice(4),r=[];for(;t.offset<t.buffer.length;)r.push(t.readUInt32());return{masterFingerprint:n,path:r}}encodeTapBip32Derivation(t,n,r){const o=new B;return o.writeVarInt(t.length),t.forEach(s=>{o.writeSlice(s)}),this.writeBip32Derivation(o,n,r),o.buffer()}decodeTapBip32Derivation(t){const n=new D(t),r=R(n.readVarInt()),o=[];for(let i=0;i<r;i++)o.push(n.readSlice(32));const s=this.readBip32Derivation(n);return{hashes:o,...s}}}function pt(e,t,n){const r=It(e,t,n);if(r===void 0)throw new Ye(new U(t,n).toString());return r}function It(e,t,n){if(!e)throw new Error("No such map");const r=new U(t,n),o=e.get(r.toString());if(o!==void 0)return u.Buffer.from(o)}class U{constructor(t,n){p(this,"keyType");p(this,"keyData");this.keyType=t,this.keyData=n}toString(){const t=new B;return this.toBuffer(t),t.buffer().toString("hex")}serialize(t){t.writeVarInt(1+this.keyData.length),this.toBuffer(t)}toBuffer(t){t.writeUInt8(this.keyType),t.writeSlice(this.keyData)}}class Vr{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 Gr(e){return new U(e.readUInt8(0),e.subarray(1))}function dt(e,t){const n=[...t].sort(([r],[o])=>r<o?-1:r>o?1:0);for(const[r,o]of n)new Vr(Gr(u.Buffer.from(r,"hex")),o).serialize(e);e.writeUInt8(0)}function w(){return u.Buffer.from([])}function oe(e,t,n,r){const o=new U(t,n);e.set(o.toString(),r)}function C(e){const t=u.Buffer.alloc(4);return t.writeUInt32LE(e,0),t}function se(e){return Fe(e)}function ie(e){const t=new B;return t.writeVarInt(e),t.buffer()}function ae(e){return R(new D(e).readVarInt())}const ue=192,St=32,ce=2,Q=33,Z=32,Kr=1,Fr="TapBranch",Yr="TapTweak",le=64,fe=32,gt=64,Xr=34,st=u.Buffer.from([81,32]),qr=u.Buffer.from([0,20]),Wr=2,zr=3;function ct(e){_.initEccLib(wt);const t=_.payments.p2tr({internalPubkey:u.Buffer.from(e,"hex")}).output;if(!t)throw new d("p2tr produced no output script for the depositor key");return t}function he(e,t){const n=u.Buffer.concat([u.Buffer.from([t]),u.Buffer.from(e,"hex")]);return u.Buffer.concat([qr,_.crypto.hash160(n)])}function qe(e){return e.length===Xr&&e.subarray(0,st.length).equals(st)}function jr(e,t,n,r){if(!qe(r))throw new d(`input ${e} is tapscript but its witnessUtxo script is not P2TR`);const o=t.length-Q;if(o<0||o%Z!==0)throw new d(`input ${e} control block length ${t.length} is not ${Q} plus a multiple of ${Z}`);const s=t.subarray(1,Q);if(!wt.isXOnlyPoint(s))throw new d(`input ${e} control block internal key is not an x-only point`);let i=n;for(let h=Q;h<t.length;h+=Z){const g=t.subarray(h,h+Z),f=u.Buffer.compare(i,g)<0?[i,g]:[g,i];i=_.crypto.taggedHash(Fr,u.Buffer.concat(f))}const a=_.crypto.taggedHash(Yr,u.Buffer.concat([s,i])),c=wt.xOnlyPointAddTweak(s,a);if(!c)throw new d(`input ${e} control block internal key has no taproot output key`);if(!r.subarray(st.length).equals(u.Buffer.from(c.xOnlyPubkey)))throw new d(`input ${e} control block does not commit to its TAP_LEAF_SCRIPT (recomputed taproot output key differs from the witnessUtxo witness program)`);if(c.parity!==(t[0]&Kr))throw new d(`input ${e} control block parity bit disagrees with the recomputed taproot output key`)}function Qr(e){const{psbt:t,depositorXOnlyHex:n,signInputIndexes:r}=e,o=new Map,s=new Map,i=t.getGlobalInputCount(),a=r===void 0?void 0:new Set(r),c=f=>a===void 0||a.has(f);if((a==null?void 0:a.size)===0)throw new d("signInputIndexes is empty — pass the indices to sign, or omit it to sign every device-signable input");for(const f of a??[])if(!Number.isInteger(f)||f<0||f>=i)throw new d(`input ${f} was requested for signing but this PSBT has ${i} input(s)`);const l=ct(n),h=[he(n,Wr),he(n,zr)];for(let f=0;f<i;f++){const E=t.getInputEntriesOfType(f,Tt.TAP_LEAF_SCRIPT);if(E.length>0){if(E.length>1)throw new d(`input ${f} carries an ambiguous leaf set (${E.length} TAP_LEAF_SCRIPT entries)`);const m=E[0].value;if(m.length<ce)throw new d(`input ${f} TAP_LEAF_SCRIPT value length ${m.length} is below the ${ce}-byte minimum (script byte plus the leaf-version byte)`);const G=m[m.length-1];if(G!==ue)throw new d(`input ${f} leaf version 0x${G.toString(16)} is not tapscript (0xc0)`);const v=t.getInputWitnessUtxo(f);if(!v)throw new d(`input ${f} is tapscript but has no witnessUtxo`);const W=m.subarray(0,m.length-1),kt=Cr(ue,W);jr(f,E[0].keyData,kt,v.scriptPubKey);const Ut={kind:"tapscript",expectedLeafHashHexes:new Set([kt.toString("hex")]),expectedSignerXOnlyHex:n};s.set(f,Ut),c(f)&&o.set(f,Ut);continue}const y=t.getInputEntriesOfType(f,Tt.TAP_INTERNAL_KEY);if(y.length>0){const m=y[0];if(y.length>1||m.keyData.length!==0||m.value.length!==St)throw new d(`input ${f} carries a malformed TAP_INTERNAL_KEY entry`);if(m.value.toString("hex")!==n)throw new d(`input ${f} internal key is not the connected depositor key`);const G=t.getInputWitnessUtxo(f);if(!G)throw new d(`input ${f} is keypath but has no witnessUtxo`);const v=G.scriptPubKey;if(!qe(v))throw new d(`input ${f} witnessUtxo script is not P2TR`);if(!v.equals(l))throw new d(`input ${f} witnessUtxo is not the BIP-86 P2TR of the depositor key`);const W={kind:"taproot-keypath",expectedOutputKeyHex:v.subarray(st.length).toString("hex")};s.set(f,W),o.set(f,W);continue}const lt=t.getInputWitnessUtxo(f);if(lt&&(lt.scriptPubKey.equals(l)||h.some(m=>lt.scriptPubKey.equals(m))))throw new d(`input ${f} spends a depositor-owned UTXO but carries no signing metadata`)}for(const f of a??[])if(!o.has(f))throw new d(`input ${f} was requested for signing but carries no signing metadata`);if(o.size===0)throw new d("PSBT contains no depositor-signable input");let g=0;for(const f of o.values())g+=f.kind==="tapscript"?f.expectedLeafHashHexes.size:1;return{byInput:o,classifiedByInput:s,expectedYieldCount:g}}function J(e){return e.kind==="tapscript"?`${e.inputIndex}:${e.leafHashHex}`:`${e.inputIndex}`}function pe(e,t){if(e<gt)throw new d(`YIELD payload truncated inside the signature (${e} of ${gt} bytes on input ${t})`);if(e!==gt)throw new S("non-default-sighash",t)}function Zr(e){const t=[],n=new Set;return{assertAndRecord:s=>{let i,a;try{const[h,g]=Ke(s,0);i=R(h),a=g}catch(h){throw new d(`unparseable YIELD payload: ${h instanceof Error?h.message:String(h)}`)}const c=s[a];if(c===void 0)throw new d("YIELD payload truncated before the augmented-pubkey length");const l=e.byInput.get(i);if(l===void 0)throw new S("unexpected-input",i);if(c===le){if(l.kind!=="tapscript")throw new S("wrong-spend-type",i);const h=a+1+le;if(s.length<h)throw new d("YIELD payload truncated inside the augmented pubkey");const g=s.subarray(a+1,a+1+St).toString("hex"),f=s.subarray(a+1+St,h).toString("hex"),E=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);pe(E.length,i);const y={kind:"tapscript",inputIndex:i,signerXOnlyHex:g,leafHashHex:f,signature:Uint8Array.from(E)};if(n.has(J(y)))throw new S("duplicate-yield",i);n.add(J(y)),t.push(y);return}if(c===fe){if(l.kind!=="taproot-keypath")throw new S("wrong-spend-type",i);const h=a+1+fe;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);pe(f.length,i);const E={kind:"taproot-keypath",inputIndex:i,outputKeyHex:g,signature:Uint8Array.from(f)};if(n.has(J(E)))throw new S("duplicate-yield",i);n.add(J(E)),t.push(E);return}throw new S("unexpected-encoding",i)},get yields(){return t},get lastYield(){return t[t.length-1]},assertComplete:()=>{const s=new Set;for(const[c,l]of e.byInput)if(l.kind==="tapscript")for(const h of l.expectedLeafHashHexes)s.add(`${c}:${h}`);else s.add(`${c}`);const i=[...s].filter(c=>!n.has(c)),a=[...n].some(c=>!s.has(c));if(i.length>0||a||n.size!==e.expectedYieldCount)throw new ve(i)}}}const We=/^[0-9a-f]{64}$/;function Jr(e,t){if(Dt("depositorPath",e),e[br]!==Ve)throw new Error("depositorPath must use BIP-86 receive branch 0");for(let n=0;n<Nt;n++)if(e[n]!==t[n])throw new Error(`depositorPath ${$(e)} is not under the wallet policy's key origin ${$(t)} — the device could never mark the input internal`)}function ze(e,t,n,r){if(!Number.isInteger(r)||r<0||r>=b)throw new Error("addressIndex must be a non-hardened integer in 0..2^31-1");const o=it.HDKey.fromExtendedKey(e,t).deriveChild(n).deriveChild(r);if(!o.publicKey)throw new Error(`account xpub derived no public key at ${n}/${r}`);return u.Buffer.from(o.publicKey.subarray(1)).toString("hex")}function je(e,t,n){return ze(e,t,Ge,n)}function to(e,t,n){return ze(e,t,Ve,n)}function Qe(e,t){const n=ct(t);return e.txOutputs.flatMap((r,o)=>u.Buffer.from(r.script).equals(n)?[o]:[])}function eo(e,t){if(!We.test(t))throw new Error("changeXOnlyHex must be 64 lowercase hex characters");return Qe(_.Psbt.fromHex(e),t).length>0}function no(e){const{psbtHex:t,depositorXOnlyHex:n,walletPolicy:r,depositorPath:o,change:s}=e;if(!We.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");Jr(o,r.keyOriginPath);const i=_.Psbt.fromHex(t),a=u.Buffer.from(r.masterFingerprintHex,"hex"),c=u.Buffer.from(n,"hex");let l=0;if(i.data.inputs.forEach((h,g)=>{h.tapInternalKey&&u.Buffer.from(h.tapInternalKey).equals(c)&&(l++,i.updateInput(g,{tapBip32Derivation:[{masterFingerprint:a,pubkey:c,path:$(o),leafHashes:[]}]}))}),l!==i.data.inputs.length)throw new Error(`${i.data.inputs.length-l} of ${i.data.inputs.length} inputs do not carry the depositor key as TAP_INTERNAL_KEY — every Pre-PegIn input must be internal`);if(s){const h=je(r.accountXpub,r.bip32Versions,s.addressIndex),g=[...o.slice(0,Nt),Ge,s.addressIndex],f=u.Buffer.from(h,"hex"),E=Qe(i,h);if(E.length===0)throw new Error("change script matches no output — the PSBT does not pay the wallet's change address");for(const y of E)i.updateOutput(y,{tapInternalKey:f,tapBip32Derivation:[{masterFingerprint:a,pubkey:f,path:$(g),leafHashes:[]}]})}return i.toHex()}const ro="BIP0322-signed-message",oo=new Uint8Array([252,6,98,118,97,117,108,116,0]),Ze=0,Je=0,tn=0,so=0,Pt=0,io=u.Buffer.from([106]),ao=/^[0-9a-f]{64}$/,uo=/^[0-9a-f]{8}$/,co=u.Buffer.alloc(32,0),lo=4294967295,fo=u.Buffer.from([0,32]),ho=u.Buffer.from([81,32]),po=2;function go(e,t){const n=_.crypto.sha256(u.Buffer.from(e,"utf8"));return _.crypto.sha256(u.Buffer.concat([n,n,u.Buffer.from(t)]))}function Eo(e,t){const n=new _.Transaction;n.version=Ze,n.locktime=Je;const r=u.Buffer.concat([fo,go(ro,e)]);return n.addInput(co,lo,tn,r),n.addOutput(u.Buffer.concat([ho,u.Buffer.from(t)]),Pt),Uint8Array.from(n.getHash(!1))}function wo(e){const{message:t,depositorXOnlyHex:n,masterFingerprintHex:r,depositorPath:o}=e;if(!ao.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");if(!uo.test(r))throw new Error("masterFingerprintHex must be 8 lowercase hex characters");Dt("depositorPath",o);const s=new TextEncoder().encode(t),i=u.Buffer.from(n,"hex"),a=ct(n),c=Eo(s,a.subarray(po)),l=new _.Psbt;return l.setVersion(Ze),l.setLocktime(Je),l.addInput({hash:u.Buffer.from(c),index:so,sequence:tn,witnessUtxo:{script:a,value:Pt},tapInternalKey:i,tapBip32Derivation:[{masterFingerprint:u.Buffer.from(r,"hex"),pubkey:i,path:$(o),leafHashes:[]}]}),l.addOutput({script:io,value:Pt}),l.addUnknownKeyValToGlobal({key:u.Buffer.from(oo),value:u.Buffer.from(s)}),l.toHex()}const _o=/^[0-9a-f]{64}$/,mo=/^[0-9a-f]{8}$/,To=192,yt=32,Io=0,So=1,Po=32,yo=75,bo=76,Ro=79,xo=80,Ao=81,Oo=96,Bo=173,vo=178,de=4,ge=128,Co=1+yt+1+1+1,Lo=2,Mo=34,No=2147483648,Do=4194304,Ee=65535,$o=2,ko=0;function Uo(e){if(e.length<Co)return;let t=0;if(e[t++]!==Po)return;const n=u.Buffer.from(e.subarray(t,t+yt)).toString("hex");if(t+=yt,e[t++]!==Bo||t>=e.length)return;const r=e[t++];let o=0;if(!(r===Io||r===Ro)){if(r>=So&&r<=yo){const s=r;if(s>de||t+s>e.length||(e[t+s-1]&ge)!==0)return;for(let i=0;i<s;i++)o|=e[t+i]<<8*i;t+=s}else if(r===bo){if(t>=e.length)return;const s=e[t++];if(s>de||t+s>e.length||(e[t+s-1]&ge)!==0)return;for(let i=0;i<s;i++)o|=e[t+i]<<8*i;t+=s}else if(r>=Ao&&r<=Oo)o=r-xo;else return;if(o!==0&&!(t>=e.length)&&e[t++]===vo&&t===e.length)return{leafKeyHex:n,csv:o}}}function en(e){let t;try{t=_.Psbt.fromHex(e)}catch{return}if(t.version<$o||t.locktime!==ko||t.data.inputs.length!==1||t.data.outputs.length!==1)return;const n=t.data.inputs[0],r=n.tapLeafScript??[];if(r.length!==1||r[0].leafVersion!==To)return;const o=Uo(r[0].script);if(o!==void 0)return{...o,inputTxidInternalHex:u.Buffer.from(t.txInputs[0].hash).toString("hex"),sequence:t.txInputs[0].sequence??0,witnessUtxo:n.witnessUtxo?{scriptLength:n.witnessUtxo.script.length,value:n.witnessUtxo.value}:void 0,outputScriptHex:u.Buffer.from(t.txOutputs[0].script).toString("hex"),outputValue:t.txOutputs[0].value}}function nn(e){if(e.witnessUtxo===void 0||e.witnessUtxo.scriptLength!==Mo)throw new Error("refund input must carry a P2TR witnessUtxo — the device rejects a missing or non-34-byte scriptPubKey");if(e.outputValue>e.witnessUtxo.value)throw new Error(`refund output value ${e.outputValue} exceeds the HTLC value ${e.witnessUtxo.value} — the device rejects it`);if(e.outputScriptHex!==ct(e.leafKeyHex).toString("hex"))throw new Error("refund output does not pay the refund leaf key's own BIP-86 address");if(e.csv<rt)throw new Error(`refund leaf CSV ${e.csv} is below the device's timelock floor of ${rt} blocks`);if((e.sequence&No)!==0||(e.sequence&Do)!==0)throw new Error("refund input sequence must be a plain block-count relative timelock (BIP-68 disable/time flags clear)");if((e.sequence&Ee)!==(e.csv&Ee))throw new Error(`refund input sequence ${e.sequence} must encode exactly the leaf CSV ${e.csv} — a mismatch signs but can never broadcast`)}function Ho(e){const{psbtHex:t,depositorXOnlyHex:n,masterFingerprintHex:r,depositorPath:o}=e;if(!_o.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");if(!mo.test(r))throw new Error("masterFingerprintHex must be 8 lowercase hex characters (the 4-byte master fingerprint)");Dt("depositorPath",o);const s=en(t);if(s===void 0)throw new Error("not a refund-shaped PSBT (expected 1 input, 1 output, and one refund tapscript leaf)");if(nn(s),s.leafKeyHex!==n)throw new Error("refund leaf key does not equal the depositor key — this device cannot sign this refund");const i=_.Psbt.fromHex(t),a=u.Buffer.from(i.txOutputs[0].script),c=u.Buffer.from(r,"hex"),l=$(o);return i.updateInput(0,{tapBip32Derivation:[{masterFingerprint:c,pubkey:u.Buffer.from(n,"hex"),path:l,leafHashes:[]}]}),i.updateOutput(0,{tapBip32Derivation:[{masterFingerprint:c,pubkey:a.subarray(Lo),path:l,leafHashes:[]}]}),i.toHex()}class H{constructor(t,n=_.crypto.sha256){p(this,"leaves");p(this,"rootNode");p(this,"leafNodes");p(this,"h");this.leaves=t,this.h=n;const r=this.calculateRoot(t);this.rootNode=r.root,this.leafNodes=r.leaves}getRoot(){return this.rootNode.hash}size(){return this.leaves.length}getLeaves(){return this.leaves}getLeafHash(t){const n=this.leafNodes[t];if(n===void 0)throw Error("Index out of bounds");return n.hash}getProof(t){const n=this.leafNodes[t];if(n===void 0)throw Error("Index out of bounds");return bt(n)}calculateRoot(t){const n=t.length;if(n==0)return{root:new Et(void 0,void 0,u.Buffer.alloc(32,0)),leaves:[]};if(n==1){const h=new Et(void 0,void 0,t[0]);return{root:h,leaves:[h]}}const r=Go(n),o=this.calculateRoot(t.slice(0,r)),s=this.calculateRoot(t.slice(r)),i=o.root,a=s.root,c=this.hashNode(i.hash,a.hash),l=new Et(i,a,c);return i.parent=l,a.parent=l,{root:l,leaves:o.leaves.concat(s.leaves)}}hashNode(t,n){return this.h(u.Buffer.concat([u.Buffer.from([1]),t,n]))}}function V(e,t=_.crypto.sha256){return Vo(u.Buffer.from([0]),e,t)}function Vo(e,t,n){return n(u.Buffer.concat([e,t]))}class Et{constructor(t,n,r){p(this,"leftChild");p(this,"rightChild");p(this,"parent");p(this,"hash");this.leftChild=t,this.rightChild=n,this.hash=r}isLeaf(){return this.leftChild==null}}function bt(e){if(!e.parent)return[];if(e.parent.leftChild==e){if(!e.parent.rightChild)throw new Error("Expected right child to exist");return[e.parent.rightChild.hash,...bt(e.parent)]}else{if(!e.parent.leftChild)throw new Error("Expected left child to exist");return[e.parent.leftChild.hash,...bt(e.parent)]}}function Go(e){if(e<2)throw Error("Expected n >= 2");return Ko(e)?e/2:1<<Math.floor(Math.log2(e))}function Ko(e){return(e&e-1)==0}const $t=255,Fo=2,I=32;class q{}class Yo extends q{constructor(n,r,o){super();p(this,"results");p(this,"code",16);this.progressCallback=r,this.onYield=o,this.results=n}execute(n){const r=u.Buffer.from(n.subarray(1));return this.onYield&&this.onYield(u.Buffer.from(r)),this.results.push(r),this.progressCallback&&this.progressCallback(),u.Buffer.from("")}}class Xo extends q{constructor(n,r){super();p(this,"knownPreimages");p(this,"queue");p(this,"code",64);this.knownPreimages=n,this.queue=r}execute(n){const r=u.Buffer.from(n.subarray(1));if(r.length!==1+I)throw new Error("Invalid request, unexpected trailing data");if(r[0]!==0)throw new Error("Unsupported request, the first byte should be 0");const s=u.Buffer.from(r.subarray(1,1+I)).toString("hex"),i=this.knownPreimages.get(s);if(i!==void 0){const a=k(i.length),c=$t-a.length-1,l=Math.min(c,i.length);if(l<i.length)for(let h=l;h<i.length;h++)this.queue.push(u.Buffer.from(i.subarray(h,h+1)));return u.Buffer.concat([a,u.Buffer.from([l]),u.Buffer.from(i.subarray(0,l))])}throw new Error(`Requested unknown preimage for: ${s}`)}}class qo extends q{constructor(n,r){super();p(this,"knownTrees");p(this,"queue");p(this,"code",65);this.knownTrees=n,this.queue=r}execute(n){const r=u.Buffer.from(n.subarray(1));if(r.length<I+1+1)throw new Error("Invalid request, expected at least 34 bytes");const o=new D(r),i=o.readSlice(I).toString("hex");let a,c;try{a=R(o.readVarInt()),c=R(o.readVarInt())}catch{throw new Error("Invalid request, couldn't parse tree_size or leaf_index")}const l=this.knownTrees.get(i);if(!l)throw new Error(`Requested Merkle leaf proof for unknown tree: ${i}`);if(c>=a||l.size()!==a)throw new Error("Invalid index or tree size.");if(this.queue.length!==0)throw new Error("This command should not execute when the queue is not empty.");const h=l.getProof(c),g=Math.min(Math.floor(($t-I-1-1)/I),h.length),f=h.length-g;return f>0&&this.queue.push(...h.slice(-f)),u.Buffer.concat([l.getLeafHash(c),u.Buffer.from([h.length]),u.Buffer.from([g]),...h.slice(0,g)])}}class Wo extends q{constructor(n){super();p(this,"knownTrees");p(this,"code",66);this.knownTrees=n}execute(n){const r=u.Buffer.from(n.subarray(1));if(r.length!==I+I)throw new Error("Invalid request, unexpected trailing data");const s=u.Buffer.from(r.subarray(0,I)).toString("hex"),a=u.Buffer.from(r.subarray(I,I+I)).toString("hex"),c=this.knownTrees.get(s);if(!c)throw new Error(`Requested Merkle leaf index for unknown root: ${s}`);let l=0,h=0;for(let g=0;g<c.size();g++)if(c.getLeafHash(g).toString("hex")===a){h=1,l=g;break}return u.Buffer.concat([u.Buffer.from([h]),k(l)])}}class zo extends q{constructor(n){super();p(this,"queue");p(this,"code",160);this.queue=n}execute(n){if(n.length!==1)throw new Error("Invalid request, unexpected trailing data");const r=this.queue[0];if(r===void 0)throw new Error("No elements to get");const o=r.length;if(this.queue.some(c=>c.length!==o))throw new Error("The queue contains elements with different byte length, which is not expected");const s=Math.floor(($t-Fo)/o),i=Math.min(s,this.queue.length),a=this.queue.splice(0,i);return u.Buffer.concat([u.Buffer.from([i]),u.Buffer.from([o]),...a])}}class jo{constructor(t,n){p(this,"roots",new Map);p(this,"preimages",new Map);p(this,"yielded",[]);p(this,"queue",[]);p(this,"commands",new Map);const r=[new Yo(this.yielded,t,n),new Xo(this.preimages,this.queue),new Wo(this.roots),new qo(this.roots,this.queue),new zo(this.queue)];for(const o of r){if(this.commands.has(o.code))throw new Error(`Multiple commands with code ${o.code}`);this.commands.set(o.code,o)}}getYielded(){return this.yielded}addKnownPreimage(t){this.preimages.set(_.crypto.sha256(t).toString("hex"),t)}addKnownList(t){for(const r of t){const o=u.Buffer.concat([u.Buffer.from([0]),r]);this.addKnownPreimage(o)}const n=new H(t.map(r=>V(r)));this.roots.set(n.getRoot().toString("hex"),n)}addKnownMapping(t){this.addKnownList(t.keys),this.addKnownList(t.values)}addKnownWalletPolicy(t){this.addKnownPreimage(t.serialize()),this.addKnownList(t.keys.map(n=>u.Buffer.from(n,"ascii"))),this.addKnownPreimage(u.Buffer.from(t.descriptorTemplate))}execute(t){if(t.length===0)throw new Error("Unexpected empty command");const n=t[0],r=this.commands.get(n);if(!r)throw new Error(`Unexpected command code ${n}`);return r.execute(t)}}class Qo{constructor(t,n){p(this,"keys");p(this,"keysTree");p(this,"values");p(this,"valuesTree");if(t.length!=n.length)throw new Error("keys and values should have the same length");for(let r=0;r<t.length-1;r++)if(t[r].toString("hex")>=t[r+1].toString("hex"))throw new Error("keys must be in strictly increasing order");this.keys=t,this.keysTree=new H(t.map(r=>V(r))),this.values=n,this.valuesTree=new H(n.map(r=>V(r)))}commitment(){return u.Buffer.concat([k(this.keys.length),this.keysTree.getRoot(),this.valuesTree.getRoot()])}}class X extends Xe{constructor(n){super();p(this,"globalMerkleMap");p(this,"inputMerkleMaps",[]);p(this,"outputMerkleMaps",[]);p(this,"inputMapCommitments");p(this,"outputMapCommitments");n.copy(this),this.globalMerkleMap=X.createMerkleMap(this.globalMap);const r=this.getGlobalInputCount();if(this.inputMaps.length!==r)throw new Error(`Input map count ${this.inputMaps.length} != declared PSBT_GLOBAL_INPUT_COUNT ${r}`);for(let s=0;s<r;s++){const i=this.inputMaps[s];if(i===void 0)throw new Error(`Missing input map ${s}`);this.inputMerkleMaps.push(X.createMerkleMap(i))}this.inputMapCommitments=this.inputMerkleMaps.map(s=>s.commitment());const o=this.getGlobalOutputCount();if(this.outputMaps.length!==o)throw new Error(`Output map count ${this.outputMaps.length} != declared PSBT_GLOBAL_OUTPUT_COUNT ${o}`);for(let s=0;s<o;s++){const i=this.outputMaps[s];if(i===void 0)throw new Error(`Missing output map ${s}`);this.outputMerkleMaps.push(X.createMerkleMap(i))}this.outputMapCommitments=this.outputMerkleMaps.map(s=>s.commitment())}getGlobalSize(){return this.globalMap.size}getGlobalKeysValuesRoot(){return this.globalMerkleMap.commitment()}static createMerkleMap(n){const r=[...n.keys()].sort(),o=r.map(i=>{const a=n.get(i);if(!a)throw new Error("No value for key "+i);return a}),s=r.map(i=>u.Buffer.from(i,"hex"));return new Qo(s,o)}}const Zo=2;class Jo{constructor(t,n,r){p(this,"name");p(this,"descriptorTemplate");p(this,"keys");this.name=t,this.descriptorTemplate=n,this.keys=r}getId(){return _.crypto.sha256(this.serialize())}serialize(){const t=this.keys.map(o=>u.Buffer.from(o,"ascii")),n=new H(t.map(o=>V(o))),r=new B;return r.writeUInt8(Zo),r.writeVarSlice(u.Buffer.from(this.name,"ascii")),r.writeVarInt(this.descriptorTemplate.length),r.writeSlice(_.crypto.sha256(u.Buffer.from(this.descriptorTemplate))),r.writeVarInt(this.keys.length),r.writeSlice(n.getRoot()),r.buffer()}}class rn extends Jo{constructor(t,n){super("",t,[n])}}const ts=4,es=0,ns=1,on=32,rs=new Uint8Array(on),os=new Uint8Array(on),ss=/^[0-9a-f]{64}$/,is=/^(?:[0-9a-fA-F]{2})+$/,as=/^[0-9a-f]{64}$/;function us(e,t){const n=new H(e.inputMapCommitments.map(o=>V(o))).getRoot(),r=new H(e.outputMapCommitments.map(o=>V(o))).getRoot();return Uint8Array.from(u.Buffer.concat([e.getGlobalKeysValuesRoot(),k(e.getGlobalInputCount()),n,k(e.getGlobalOutputCount()),r,u.Buffer.from(t),u.Buffer.from(os)]))}function cs(e){return{cla:x,ins:ts,p1:es,p2:ns,data:e}}const ls=0;function fs(e,t){for(const[n]of t.byInput){const r=e.data.inputs[n].sighashType;if(r!==void 0&&r!==ls)throw new d(`input ${n} requests sighash type ${r}, but vault flows sign SIGHASH_DEFAULT only`)}}function hs(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 sn=new WeakMap;function ps(e,t){const n={...e};return sn.set(n,t),n}function an(e){const t=sn.get(e);if(!t)throw new d("unrecognised prepared signing state — use prepareSignPsbt's return value");return t}function un(e){const{psbtHex:t,depositorXOnlyHex:n,signInputIndexes:r,walletPolicy:o}=e;if(!ss.test(n))throw new d("depositorXOnlyHex must be 64 lowercase hex characters");let s;if(o!==void 0){if(!as.test(o.walletIdHex))throw new d("walletPolicy.walletIdHex must be 64 lowercase hex characters");if(s=new rn(o.descriptorTemplate,o.keyInfo),s.getId().toString("hex")!==o.walletIdHex)throw new d("walletPolicy.walletIdHex does not match sha256 of the serialized policy")}if(!is.test(t))throw new d("psbtHex is not even-length hexadecimal");let i;try{i=_.Psbt.fromHex(t)}catch(E){throw new d(`PSBT rejected at parse (merge target): ${E instanceof Error?E.message:String(E)}`)}const a=new Xe;try{a.deserialize(u.Buffer.from(t,"hex"))}catch(E){throw new d(`PSBT rejected at parse: ${E instanceof Error?E.message:String(E)}`)}let c,l;try{c=new X(a),l=Qr({psbt:c,depositorXOnlyHex:n,signInputIndexes:r})}catch(E){throw E instanceof d?E:new d(`PSBT rejected at preflight: ${E instanceof Error?E.message:String(E)}`)}hs(i,l),fs(i,l);const h=Zr(l),g=new jo(void 0,E=>h.assertAndRecord(E));g.addKnownMapping(c.globalMerkleMap);for(const E of c.inputMerkleMaps)g.addKnownMapping(E);for(const E of c.outputMerkleMaps)g.addKnownMapping(E);g.addKnownList(c.inputMapCommitments),g.addKnownList(c.outputMapCommitments);const f=o?u.Buffer.from(o.walletIdHex,"hex"):rs;return s&&g.addKnownWalletPolicy(s),ps({table:l,unsignedTxid:_.Transaction.fromBuffer(i.data.globalMap.unsignedTx.toBuffer()).getId()},{cdata:us(c,f),interpreter:g,collector:h,originalPsbtHex:t,signsUnderWalletPolicy:o!==void 0})}const ds=248,gs=1,Es=0,ws=0,_s=36864,ms=57344;async function Ts(e,t,n){const{collector:r,interpreter:o,cdata:s}=an(t),{table:i}=t;if(n.signal.aborted)throw new _t(r.yields.length);const a=cs(s);let c=a,l=await e(a),h=0;for(;l.sw===ms;){let g;try{g=o.execute(u.Buffer.from(l.data))}catch(f){throw Ce(f)?f:Le(f)?new d(f.detail,tt(r.yields)):new d(`client command failed: ${f instanceof Error?f.message:String(f)}`,tt(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 _t(r.yields.length);c={cla:ds,ins:gs,p1:Es,p2:ws,data:g},l=await e(c)}if(l.sw!==_s){const g=$e(l.sw,{...n.appIdentity,ins:c.ins,p1:c.p1,preDispatch:c===a});throw g===void 0?new d(`status word 0x${l.sw.toString(16)} escaped classification`,tt(r.yields)):g}return r.assertComplete(),r.yields}function Is(e,t){const n=_.Psbt.fromHex(e);for(const r of t)r.kind==="tapscript"?n.updateInput(r.inputIndex,{tapScriptSig:[{pubkey:u.Buffer.from(r.signerXOnlyHex,"hex"),leafHash:u.Buffer.from(r.leafHashHex,"hex"),signature:u.Buffer.from(r.signature)}]}):n.updateInput(r.inputIndex,{tapKeySig:u.Buffer.from(r.signature)});return n.toHex()}const we=new WeakSet;async function cn(e,t,n){const{originalPsbtHex:r,signsUnderWalletPolicy:o}=an(t);if(we.has(t))throw new d("prepared signing state was already used — call prepareSignPsbt again for a retry");if([...t.table.byInput.values()].some(c=>c.kind==="taproot-keypath")&&!o)throw new d("PSBT signs a key-path input but was prepared without a walletPolicy — the device would answer SW_OK with no signature");we.add(t);const i=await Ts(e,t,n);let a;try{a=Is(r,i)}catch(c){throw new d(`merge failed after signing: ${c instanceof Error?c.message:String(c)}`,tt(i))}return{signedPsbtHex:a,yields:[...i]}}async function Ss(e,t){const{psbtHex:n,depositorXOnlyHex:r,signInputIndexes:o,...s}=t,i=un({psbtHex:n,depositorXOnlyHex:r,signInputIndexes:o});return cn(e,i,s)}const _e="tr(@0/**)",me=2147483647,Ps=/^[0-9a-f]{8}$/;function ys(e){const{masterFingerprintHex:t,coinType:n,accountIndex:r,accountXpub:o,bip32Versions:s}=e;if(!Ps.test(t))throw new Error("masterFingerprintHex must be 8 lowercase hex characters");if(!Number.isInteger(n)||n<0||n>me||!Number.isInteger(r)||r<0||r>me)throw new Error("coinType and accountIndex must be non-negative integers in 0..0x7fffffff");try{it.HDKey.fromExtendedKey(o,s)}catch(c){throw new Error(`accountXpub is not a valid extended key for this network: ${c instanceof Error?c.message:String(c)}`)}const i=`[${t}/${ot}'/${n}'/${r}']${o}`,a=new rn(_e,i).getId().toString("hex");return{descriptorTemplate:_e,keyInfo:i,walletIdHex:a,accountXpub:o,bip32Versions:s,keyOriginPath:[(b|ot)>>>0,(b|n)>>>0,(b|r)>>>0],masterFingerprintHex:t}}exports.closeDmk=at.closeDmk;exports.connectDmkSession=at.connectDmkSession;exports.disconnectDmkSession=at.disconnectDmkSession;exports.isSessionAlive=at.isSessionAlive;exports.DEPOSIT_TERMS_REJECTED_ERROR_NAME=He;exports.DepositTermsRejectedError=T;exports.LEDGER_DEVICE_ERROR_NAME=Ot;exports.LEDGER_DEVICE_LOCKED_ERROR_NAME=At;exports.LEDGER_SIGN_PSBT_ABORTED_ERROR_NAME=Lt;exports.LEDGER_SIGN_PSBT_INCOMPLETE_ERROR_NAME=vt;exports.LEDGER_SIGN_PSBT_PROTOCOL_ERROR_NAME=Ct;exports.LEDGER_USER_REFUSED_ERROR_NAME=xt;exports.LEDGER_YIELD_MISMATCH_ERROR_NAME=Bt;exports.LedgerDeviceError=Be;exports.LedgerDeviceLockedError=Oe;exports.LedgerSignPsbtAbortedError=_t;exports.LedgerSignPsbtIncompleteError=ve;exports.LedgerSignPsbtProtocolError=d;exports.LedgerUserRefusedError=Ae;exports.LedgerYieldMismatchError=S;exports.SW_BAD_STATE=Me;exports.SW_CAP_EXCEEDED=Ne;exports.SW_CLA_NOT_SUPPORTED=Mt;exports.approveVaultIntent=qn;exports.assertDepositTermsDeviceCompatible=Sr;exports.assertRefundPsbtSignable=nn;exports.augmentPsbtForRefund=Ho;exports.augmentPsbtForWalletPolicy=no;exports.buildDefaultTaprootPolicy=ys;exports.buildPopPsbtHex=wo;exports.classifyRefundPsbt=en;exports.createDmkApduSender=pr;exports.createDmkRawApduSender=ke;exports.deriveChangeXOnlyHex=je;exports.deriveContextHash=Xn;exports.deriveReceiveXOnlyHex=to;exports.encodeIntentGroup=Ie;exports.encodeIntentScalars=Te;exports.encodeKeyBatches=Se;exports.getExtendedPublicKey=be;exports.getMasterFingerprintHex=Zn;exports.getXOnlyPublicKeyHex=Jn;exports.isLedgerDeviceError=nr;exports.isLedgerDeviceLockedError=rr;exports.isLedgerSignPsbtAbortedError=sr;exports.isLedgerSignPsbtIncompleteError=or;exports.isLedgerSignPsbtProtocolError=Le;exports.isLedgerUserRefusedError=er;exports.isLedgerYieldMismatchError=Ce;exports.prepareSignPsbt=un;exports.psbtPaysChangeScript=eo;exports.signPreparedVaultPsbt=cn;exports.signVaultPsbt=Ss;
|
|
1
|
+
"use strict";var ln=Object.defineProperty;var hn=(e,t,n)=>t in e?ln(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var p=(e,t,n)=>hn(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const it=require("@scure/bip32"),at=require("./testing-DEVJn0Dm.cjs"),_=require("bitcoinjs-lib"),u=require("buffer"),fn=require("@bitcoin-js/tiny-secp256k1-asmjs");function pn(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const wt=pn(fn),dn=1,gn=1,En=1,wn=2,_n=33,mn=256,Tn=257,Sn=258,In=39,Pn=259,yn=105,bn=260,Rn=261,xn=262,An=271,On=265,Bn=266,vn=267,Cn=268,Ln=269,Mn=270,Nn=263,Dn=264,et=32,$n=32,F=255,kn=3+et,Ht=Math.floor(F/kn);function A(e,t){if(t.length>F)throw new Error(`TLV value for tag 0x${e.toString(16)} exceeds 255 bytes`);const n=new Uint8Array(3+t.length);return n[0]=e>>8&255,n[1]=e&255,n[2]=t.length,n.set(t,3),n}function ut(e,t,n){if(e<0n||e>=1n<<BigInt(8*t))throw new Error(`${n} ${e} does not fit in ${t} bytes`);const r=new Uint8Array(t);let o=e;for(let s=t-1;s>=0;s--)r[s]=Number(o&0xffn),o>>=8n;return r}function L(e,t,n){return A(e,ut(BigInt(t),1,n))}function z(e,t,n){return A(e,ut(BigInt(t),4,n))}function M(e,t,n){return A(e,ut(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 Rt(e,t,n){if(e.length!==t)throw new Error(`${n} must be ${t} bytes, got ${e.length}`);return e}const Vt=5;function Te(e){if(e.depositorPath.length!==Vt)throw new Error(`depositorPath must have exactly ${Vt} levels, got ${e.depositorPath.length}`);const t=nt(e.depositorPath.map(n=>ut(BigInt(n>>>0),4,"path level")));return nt([L(En,dn,"structureType"),L(wn,gn,"version"),z(_n,e.coinType,"coinType"),M(mn,e.baseFeeRate,"baseFeeRate"),z(Tn,e.peginCsvTimelock,"peginCsvTimelock"),z(Sn,e.payoutTimelock,"payoutTimelock"),A(In,Rt(e.prepeginTxidInternal,$n,"prepeginTxid")),z(Pn,e.htlcRefundTimelock,"htlcRefundTimelock"),A(yn,t),L(bn,e.keeperCount,"keeperCount"),L(Rn,e.challengerCount,"challengerCount"),L(xn,e.vaultCount,"vaultCount"),M(An,e.prepeginMaxFee,"prepeginMaxFee")])}function Se(e){return nt([L(On,e.htlcVout,"htlcVout"),A(Bn,Rt(e.vaultProviderPubkey,et,"vaultProviderPubkey")),M(vn,e.vaultAmount,"vaultAmount"),M(Cn,e.commissionFee,"commissionFee"),M(Ln,e.depositorClaimValue,"depositorClaimValue"),M(Mn,e.peginMaxFee,"peginMaxFee")])}function Ie(e,t){const n=(s,i)=>s.map((a,c)=>Rt(a,et,`${i}[${c}]`)).sort((a,c)=>{for(let l=0;l<et;l++)if(a[l]!==c[l])return a[l]-c[l];return 0}),r=[...n(e,"keeper").map(s=>A(Nn,s)),...n(t,"challenger").map(s=>A(Dn,s))],o=[];for(let s=0;s<r.length;s+=Ht)o.push(nt(r.slice(s,s+Ht)));return o}const x=225,ht=128,Gt=129,Un=0,Hn=1,Vn=0,Gn=1,Kn=2,Y=0,Kt=64,Ft=1024,Yt=10,Xt=32;function Fn(e){return new Uint8Array([e>>8&255,e&255])}function Yn(e){const t=e>>>0;return new Uint8Array([t>>>24&255,t>>>16&255,t>>>8&255,t&255])}function ft(e){const t=new Uint8Array(e.reduce((r,o)=>r+o.length,0));let n=0;for(const r of e)t.set(r,n),n+=r.length;return t}const qt=/^[a-z0-9-]+$/;async function Xn(e,{appName:t,derivationPath:n,context:r}){const o=new TextEncoder().encode(t);if(o.length<1||o.length>Kt)throw new Error(`appName must be 1..${Kt} bytes, got ${o.length}`);if(!qt.test(t))throw new Error(`appName must match ${qt} — the device rejects other characters`);if(n.length<1||n.length>Yt)throw new Error(`derivationPath must have 1..${Yt} levels`);if(r.length<1||r.length>Ft)throw new Error(`context must be 1..${Ft} bytes, got ${r.length}`);const s=ft([new Uint8Array([o.length]),o,new Uint8Array([n.length]),ft(n.map(Yn)),Fn(r.length)]),i=Math.min(r.length,F-s.length);if(i<0)throw new Error("appName and derivationPath leave no room for context in the first APDU");let a=await e({cla:x,ins:Gt,p1:Un,p2:Y,data:ft([s,r.subarray(0,i)])});for(let c=i;c<r.length;c+=F)a=await e({cla:x,ins:Gt,p1:Hn,p2:Y,data:r.subarray(c,c+F)});if(a.length!==Xt)throw new Error(`Expected a ${Xt}-byte context root, got ${a.length} bytes`);return a}async function qn(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:x,ins:ht,p1:Vn,p2:Y,data:Te(t)});for(const s of n)await e({cla:x,ins:ht,p1:Gn,p2:Y,data:Se(s)});for(const s of Ie(r,o))await e({cla:x,ins:ht,p1:Kn,p2:Y,data:s})}const Wn=0,Pe=0,ye=1,zn=0,Wt=33,zt=10,jn=5,Qn=4;async function Zn(e){const t=await e({cla:x,ins:jn,p1:Pe,p2:ye,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 Re(t)}async function be(e,t,n){if(t.length<1||t.length>zt)throw new Error(`BIP-32 path must have 1..${zt} levels, got ${t.length}`);const r=await e({cla:x,ins:Wn,p1:Pe,p2:ye,data:tr(t)}),o=new TextDecoder().decode(r);if(o.length===0)throw new Error("Ledger returned an empty extended key");return it.HDKey.fromExtendedKey(o,n),o}async function Jn(e,t,n){const r=await be(e,t,n),o=it.HDKey.fromExtendedKey(r,n);if(!o.publicKey||o.publicKey.length!==Wt)throw new Error(`Ledger returned an extended key without a ${Wt}-byte public key`);return Re(o.publicKey.subarray(1))}function Re(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function tr(e){const t=new Uint8Array(2+e.length*4);return t[0]=zn,t[1]=e.length,e.forEach((n,r)=>{const o=2+r*4;t[o]=n>>>24&255,t[o+1]=n>>>16&255,t[o+2]=n>>>8&255,t[o+3]=n&255}),t}const xt="LedgerUserRefusedError",At="LedgerDeviceLockedError",Ot="LedgerDeviceError",Bt="LedgerYieldMismatchError",vt="LedgerSignPsbtIncompleteError",Ct="LedgerSignPsbtProtocolError",Lt="LedgerSignPsbtAbortedError";function xe(e){return e.toString(16).padStart(4,"0")}class Ae extends Error{constructor(n){super(`User rejected the request on the Ledger device (0x${xe(n)})`);p(this,"statusWord");this.name=xt,this.statusWord=n}}class Oe extends Error{constructor(n,r){super(`The Ledger device is locked — unlock it and retry (0x${xe(n)})`);p(this,"statusWord");p(this,"preDispatch");this.name=At,this.statusWord=n,this.preDispatch=(r==null?void 0:r.preDispatch)??!1}}class Be extends Error{constructor(n,r){super(r);p(this,"statusWord");this.name=Ot,this.statusWord=n}}class I extends Error{constructor(n,r){super(`The device yielded a signature that fails the expected-signature table (${n}${r===void 0?"":` on input ${r}`})`);p(this,"kind");p(this,"inputIndex");this.name=Bt,this.kind=n,this.inputIndex=r}}class ve extends Error{constructor(n){super(`The device completed SIGN_PSBT without yielding every expected signature (missing ${n.length}: ${n.join(", ")})`);p(this,"missing");this.name=vt,this.missing=n}}function tt(e){return e.map(({inputIndex:t,leafHashHex:n})=>n===void 0?{inputIndex:t}:{inputIndex:t,leafHashHex:n})}class d extends Error{constructor(n,r=[]){super(`SIGN_PSBT protocol failure: ${n}`);p(this,"detail");p(this,"collectedYields");this.name=Ct,this.detail=n,this.collectedYields=r}}class _t extends Error{constructor(n){super("SIGN_PSBT was abandoned host-side before completion");p(this,"yieldedCount");this.name=Lt,this.yieldedCount=n}}function er(e){return e instanceof Error&&e.name===xt}function nr(e){return e instanceof Error&&e.name===Ot}function rr(e){return e instanceof Error&&e.name===At}function Ce(e){return e instanceof Error&&e.name===Bt}function or(e){return e instanceof Error&&e.name===vt}function Le(e){return e instanceof Error&&e.name===Ct}function sr(e){return e instanceof Error&&e.name===Lt}const ir=36864,ar=new Set([21761,27013]),ur=new Set([21781,27010,21251]),Mt=28160,Me=45063,Ne=45066,cr={27264:"The device rejected the data as invalid",27266:"The device does not support this request — check that the app build matches the selected network",27270:"The device rejected the instruction parameters",27271:"The device rejected the payload length",27904:"The running app does not support this instruction",[Mt]:"The running app does not handle vault instructions — open the Babylon Vault app for this network",45056:"The device reported a wrong response length",[Me]:"The device is not in the expected state for this step",45064:"The device rejected a signature or HMAC as invalid",45065:"The device rejected the CPFP anchor",[Ne]:"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 De(e){return e.toString(16).padStart(4,"0")}function $e(e,t){if(e===ir)return;if(ar.has(e))return new Ae(e);if(ur.has(e))return new Oe(e,{preDispatch:t.preDispatch===!0});const n=cr[e],r=e===Mt&&t.appName?` (app at connect time: "${t.appName}"${t.appVersion?` v${t.appVersion}`:""})`:"";return new Be(e,`${n??"The device rejected the request"} (ins 0x${N(t.ins)} p1 0x${N(t.p1)}, sw 0x${De(e)})${r}`)}function lr(e,t){return async n=>{const{sw:r,data:o}=await e(n),s=$e(r,{...t,ins:n.ins,p1:n.p1});if(s)throw s;return o}}const jt=2;function hr(e){if(e.statusCode.length!==jt)throw new Error(`The device returned a ${e.statusCode.length}-byte status word; expected ${jt}.`);return e.statusCode[0]<<8|e.statusCode[1]}function j(e,t){if(!Number.isInteger(e)||e<0||e>255)throw new Error(`APDU ${t} ${e} is not a single byte (0..255)`)}function fr(e){if(j(e.cla,"cla"),j(e.ins,"ins"),j(e.p1,"p1"),j(e.p2,"p2"),e.data.length>255)throw new Error(`APDU data is ${e.data.length} bytes; Lc is a single byte (max 255)`);const t=new Uint8Array(5+e.data.length);return t[0]=e.cla,t[1]=e.ins,t[2]=e.p1,t[3]=e.p2,t[4]=e.data.length,t.set(e.data,5),t}function Qt(){return globalThis.__LEDGER_VAULT_APDU_TRACE__===!0}function ke(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:fr(t)})}catch(s){throw Qt()&&console.debug(`[ledger-vault] APDU ${n} -> transport error`,s),s}const o=hr(r);return Qt()&&console.debug(`[ledger-vault] APDU ${n} -> sw=0x${De(o)} len=${r.data.length}`),{sw:o,data:r.data}}}function pr(e){return lr(ke(e),{appName:e.appName,appVersion:e.appVersion})}const dr=2,gr=3,Zt=32,Er=10,Jt=10000n,te=100000000n,rt=72,wr=1008,_r=4320,mr=91,Tr=4031,Ue=546n,ee=Ue,Sr=2n,He="DepositTermsRejectedError";class T extends Error{constructor(n,r="device-envelope"){super(n);p(this,"reason");this.name=He,this.reason=r}}const P="Deposit terms outside the device-supported range";function O(e,t,n,r){if(!Number.isInteger(t)||t<n||t>r)throw new T(`${P}: ${e} ${t} not in [${n}, ${r}]`)}function Ir(e){if(O("vaultCoreVersion",e.vaultCoreVersion,dr,gr),e.protocolFeeRate<1n||e.protocolFeeRate>Jt)throw new T(`${P}: protocolFeeRate ${e.protocolFeeRate} not in [1, ${Jt}]`);if(O("timelockPegin",e.timelockPegin,rt,wr),O("timelockAssert",e.timelockAssert,mr,Tr),O("timelockRefund",e.timelockRefund,rt,_r),O("keeper count",e.vaultKeeperBtcPubkeys.length,1,Zt),O("challenger count",e.universalChallengerBtcPubkeys.length,1,Zt),O("vault count",e.vaults.length,1,Er),K("prepeginMaxFee",e.prepeginMaxFee),e.prepeginMaxFee<1n||e.prepeginMaxFee>te)throw new T(`${P}: prepeginMaxFee ${e.prepeginMaxFee} not in [1, ${te}]`);let t=-1;for(const a of e.vaults){if(!Number.isInteger(a.htlcVout)||a.htlcVout<0||a.htlcVout>255)throw new T(`${P}: htlcVout ${a.htlcVout} not in [0, 255]`);if(a.htlcVout<=t)throw new T(`${P}: vault groups must be in strictly ascending htlcVout order; got ${a.htlcVout} after ${t}`);t=a.htlcVout}const n=a=>a.replace(/^0x/,"").toLowerCase(),r=new Set(e.vaults.map(a=>n(a.vaultProviderBtcPubkey))),o=new Set;for(const[a,c]of[["vaultKeeperBtcPubkeys",e.vaultKeeperBtcPubkeys],["universalChallengerBtcPubkeys",e.universalChallengerBtcPubkeys]])for(const l of c){const f=n(l);if(r.has(f))throw new T(`${P}: ${a} contains the vault provider's own key (${f.slice(0,16)}…)`);if(o.has(f))throw new T(`${P}: duplicate participant key in ${a} (${f.slice(0,16)}…)`);o.add(f)}const s=Ue,i=Sr*s;for(const a of e.vaults){if(K(`vault ${a.htlcVout} peginAmount`,a.peginAmount),K(`vault ${a.htlcVout} commissionFee`,a.commissionFee),K(`vault ${a.htlcVout} depositorClaimValue`,a.depositorClaimValue),K(`vault ${a.htlcVout} peginMaxFee`,a.peginMaxFee),a.commissionFee<s)throw new T(`${P}: vault ${a.htlcVout} commissionFee ${a.commissionFee} below the ${s}-sat dust limit`);if(a.depositorClaimValue<ee)throw new T(`${P}: vault ${a.htlcVout} depositorClaimValue ${a.depositorClaimValue} below the ${ee}-sat device floor`);if(a.peginAmount<=a.commissionFee+i)throw new T(`${P}: vault ${a.htlcVout} peginAmount ${a.peginAmount} must exceed commissionFee + ${i} (${a.commissionFee+i})`)}}const Pr=(1n<<64n)-1n;function K(e,t){if(t<0n||t>Pr)throw new T(`${P}: ${e} ${t} does not fit in an unsigned 64-bit field`)}const b=2147483648,yr=4294967295,ot=86,Ve=0,Ge=1,ne=5,Nt=3,br=3,Rr=4;function Dt(e,t){if(t.length!==ne)throw new Error(`${e} must have exactly ${ne} levels, got ${t.length}`);for(const r of t)if(!Number.isInteger(r)||r<0||r>yr)throw new Error(`${e} levels must be integers in 0..0xffffffff`);if(!t.slice(0,Nt).every(r=>(r&b)!==0)||(t[Rr]&b)!==0)throw new Error(`${e} must harden purpose'/coin'/account' and leave the address index unhardened`);if(t[0]!==(b|ot)>>>0)throw new Error(`${e} must use BIP-86 purpose ${ot}'`)}function $(e){return"m/"+e.map(t=>(t&b)!==0?`${(t&~b)>>>0}'`:`${t>>>0}`).join("/")}const re=253,xr=254,Ar=65535,Or=4294967295;function Br(e){if(e<re)return u.Buffer.from([e]);if(e<=Ar){const t=u.Buffer.alloc(2);return t.writeUInt16LE(e),u.Buffer.concat([u.Buffer.from([re]),t])}if(e<=Or){const t=u.Buffer.alloc(4);return t.writeUInt32LE(e),u.Buffer.concat([u.Buffer.from([xr]),t])}throw new Error(`Script too large to encode as CompactSize: ${e} bytes`)}const vr="TapLeaf";function Cr(e,t){const n=u.Buffer.concat([u.Buffer.from([e]),Br(t.length),u.Buffer.from(t)]);return _.crypto.taggedHash(vr,n)}function Lr(e,t,n,r){for(let o=0;o<t;o++){if(n[o+r]===void 0)throw Error("Buffer too small");n[o+r]=Number(e%BigInt(256)),e=e>>BigInt(8)}}function Mr(e,t,n){let r=BigInt(0);for(let o=0;o<n;o++){const s=e[o+t];if(s===void 0)throw Error("Buffer too small");r+=BigInt(s)<<BigInt(o*8)}return r}function R(e){if(e<0)throw RangeError("Negative bigint is not a valid varint");if(e>Number.MAX_SAFE_INTEGER)throw RangeError("Too large for a Number");return Number(e)}function Nr(e){if(typeof e=="number"&&(e=R(e)),e<BigInt(0))throw new RangeError("Negative numbers are not supported");if(e>=BigInt(1)<<BigInt(64))throw new RangeError("Too large for a Bitcoin-style varint");return e<BigInt(253)?1:e<=BigInt(65535)?3:e<=BigInt(4294967295)?5:9}const Dr=BigInt(253),$r=BigInt(65535)+BigInt(1),kr=BigInt(4294967295)+BigInt(1);function Ke(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=Dr):n===254?(r=4,o=$r):(r=8,o=kr);const s=Mr(e,t+1,r);if(s<o)throw RangeError(`Non-minimal varint at offset ${t}: a ${r+1}-byte CompactSize must encode a value of at least ${o}; re-encode it in its canonical (shorter) form`);return[s,r+1]}}function k(e){typeof e=="number"&&(e=R(e));const t=Nr(e);e=BigInt(e);const n=u.Buffer.alloc(t);return t==1?n[0]=Number(e):(t==3?n[0]=253:t===5?n[0]=254:n[0]=255,Lr(e,t-1,n,1)),n}const Ur=31;function Fe(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Can't convert a number that is not a non-negative safe integer to 64-bit LE");const t=u.Buffer.alloc(8,0);for(let n=0;n<t.length;n++){const r=e&255;t[n]=r,e=(e-r)/256}return t}function mt(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>Ur)throw new Error("Can't encode numbers > MAX_SAFE_INT");for(let r=e.length-1;r>=0;r--){const o=e[r];if(o===void 0)throw new Error("Buffer too small");t=t*256+o}return t}class B{constructor(){p(this,"bufs",[])}write(t,n){const r=u.Buffer.alloc(t);n(r),this.bufs.push(r)}writeUInt8(t){this.write(1,n=>n.writeUInt8(t,0))}writeInt32(t){this.write(4,n=>n.writeInt32LE(t,0))}writeUInt32(t){this.write(4,n=>n.writeUInt32LE(t,0))}writeUInt64(t){const n=Fe(t);this.writeSlice(n)}writeVarInt(t){this.bufs.push(k(t))}writeSlice(t){this.bufs.push(u.Buffer.from(t))}writeVarSlice(t){this.writeVarInt(t.length),this.writeSlice(t)}buffer(){return u.Buffer.concat(this.bufs)}}class D{constructor(t,n=0){this.buffer=t,this.offset=n}available(){return this.buffer.length-this.offset}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=this.readSlice(8);return mt(t)}readVarInt(){const[t,n]=Ke(this.buffer,this.offset);return this.offset+=n,t}readSlice(t){if(this.buffer.length<this.offset+t)throw new Error("Cannot read slice out of bounds");const n=this.buffer.subarray(this.offset,this.offset+t);return this.offset+=t,n}readVarSlice(){const t=R(this.readVarInt());return this.readSlice(t)}readVector(){const t=this.readVarInt(),n=[];for(let r=0;r<t;r++)n.push(this.readVarSlice());return n}}var Tt=(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))(Tt||{});const oe=u.Buffer.from([112,115,98,116,255]),Hr=4294967295;class Ye extends Error{}class Xe{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,ae(t))}getGlobalInputCount(){return ue(this.getGlobal(4))}setGlobalOutputCount(t){this.setGlobal(5,ae(t))}getGlobalOutputCount(){return ue(this.getGlobal(5))}setGlobalTxModifiable(t){this.setGlobal(6,t)}getGlobalTxModifiable(){return this.getGlobalOptional(6)}setGlobalPsbtVersion(t){this.setGlobal(251,C(t))}getGlobalPsbtVersion(){return this.getGlobal(251).readUInt32LE(0)}setInputNonWitnessUtxo(t,n){this.setInput(t,0,w(),n)}getInputNonWitnessUtxo(t){return this.getInputOptional(t,0,w())}setInputWitnessUtxo(t,n,r){const o=new B;o.writeSlice(ie(n)),o.writeVarSlice(r),this.setInput(t,1,w(),o.buffer())}getInputWitnessUtxo(t){const n=this.getInputOptional(t,1,w());if(!n)return;const r=new D(n);return{amount:mt(r.readSlice(8)),scriptPubKey:r.readVarSlice()}}setInputPartialSig(t,n,r){this.setInput(t,2,n,r)}getInputPartialSig(t,n){return this.getInputOptional(t,2,n)}setInputSighashType(t,n){this.setInput(t,3,w(),C(n))}getInputSighashType(t){const n=this.getInputOptional(t,3,w());if(n)return n.readUInt32LE(0)}setInputRedeemScript(t,n){this.setInput(t,4,w(),n)}getInputRedeemScript(t){return this.getInputOptional(t,4,w())}setInputWitnessScript(t,n){this.setInput(t,5,w(),n)}getInputWitnessScript(t){return this.getInputOptional(t,5,w())}setInputBip32Derivation(t,n,r,o){if(n.length!==33)throw new Error("Invalid pubkey length: "+n.length);this.setInput(t,6,n,this.encodeBip32Derivation(r,o))}getInputBip32Derivation(t,n){const r=this.getInputOptional(t,6,n);if(r)return this.decodeBip32Derivation(r)}setInputFinalScriptsig(t,n){this.setInput(t,7,w(),n)}getInputFinalScriptsig(t){return this.getInputOptional(t,7,w())}setInputFinalScriptwitness(t,n){this.setInput(t,8,w(),n)}getInputFinalScriptwitness(t){return this.getInput(t,8,w())}setInputPreviousTxId(t,n){this.setInput(t,14,w(),n)}getInputPreviousTxid(t){return this.getInput(t,14,w())}setInputOutputIndex(t,n){this.setInput(t,15,w(),C(n))}getInputOutputIndex(t){return this.getInput(t,15,w()).readUInt32LE(0)}setInputSequence(t,n){this.setInput(t,16,w(),C(n))}getInputSequence(t){var n;return((n=this.getInputOptional(t,16,w()))==null?void 0:n.readUInt32LE(0))??Hr}setInputTapKeySig(t,n){this.setInput(t,19,w(),n)}getInputTapKeySig(t){return this.getInputOptional(t,19,w())}setInputTapBip32Derivation(t,n,r,o,s){if(n.length!==32)throw new Error("Invalid pubkey length: "+n.length);const i=this.encodeTapBip32Derivation(r,o,s);this.setInput(t,22,n,i)}getInputTapBip32Derivation(t,n){const r=this.getInput(t,22,n);return this.decodeTapBip32Derivation(r)}getInputKeyDatas(t,n){return this.getKeyDatas(this.inputMaps[t],n)}getInputEntriesOfType(t,n){const r=this.inputMaps[t];if(!r)throw new Error("No such map");const o=[];return r.forEach((s,i)=>{this.isKeyType(i,[n])&&o.push({keyData:u.Buffer.from(i.substring(2),"hex"),value:u.Buffer.from(s)})}),o}setOutputRedeemScript(t,n){this.setOutput(t,0,w(),n)}getOutputRedeemScript(t){return this.getOutput(t,0,w())}setOutputBip32Derivation(t,n,r,o){this.setOutput(t,2,n,this.encodeBip32Derivation(r,o))}getOutputBip32Derivation(t,n){const r=this.getOutput(t,2,n);return this.decodeBip32Derivation(r)}setOutputAmount(t,n){this.setOutput(t,3,w(),ie(n))}getOutputAmount(t){const n=this.getOutput(t,3,w());return mt(n)}setOutputScript(t,n){this.setOutput(t,4,w(),n)}getOutputScript(t){return this.getOutput(t,4,w())}setOutputTapBip32Derivation(t,n,r,o,s){const i=this.encodeTapBip32Derivation(r,o,s);this.setOutput(t,7,n,i)}getOutputTapBip32Derivation(t,n){const r=this.getOutput(t,7,n);return this.decodeTapBip32Derivation(r)}deleteInputEntries(t,n){const r=this.inputMaps[t];if(!r)throw new Error("No such map");r.forEach((o,s,i)=>{this.isKeyType(s,n)&&i.delete(s)})}copy(t){this.copyMap(this.globalMap,t.globalMap),this.copyMaps(this.inputMaps,t.inputMaps),this.copyMaps(this.outputMaps,t.outputMaps)}copyMaps(t,n){t.forEach((r,o)=>{const s=new Map;this.copyMap(r,s),n[o]=s})}copyMap(t,n){t.forEach((r,o)=>n.set(o,u.Buffer.from(r)))}serialize(){const t=new B;return t.writeSlice(oe),dt(t,this.globalMap),this.inputMaps.forEach(n=>{dt(t,n)}),this.outputMaps.forEach(n=>{dt(t,n)}),t.buffer()}deserialize(t){const n=new D(t);if(!n.readSlice(5).equals(oe))throw new Error("Invalid magic bytes");for(;this.readKeyPair(this.globalMap,n););let r;try{r=this.getGlobalPsbtVersion()}catch(i){if(!(i instanceof Ye))throw i;r=0}if(r!==0&&r!==2)throw new Error("Only PSBTs of version 0 or 2 are supported");let o,s;if(r===0){const i=this.getGlobal(0),a=_.Transaction.fromBuffer(i);o=a.ins.length,s=a.outs.length}else o=this.getGlobalInputCount(),s=this.getGlobalOutputCount();for(let i=0;i<o;i++){const a=new Map;for(this.inputMaps[i]=a;this.readKeyPair(a,n););}for(let i=0;i<s;i++){const a=new Map;for(this.outputMaps[i]=a;this.readKeyPair(a,n););}if(n.available()!==0)throw new Error("Trailing bytes after PSBT output maps");this.normalizeToV2()}normalizeToV2(){var o;const t=(o=this.getGlobalOptional(251))==null?void 0:o.readUInt32LE(0);if(t===2)return;if(t!==void 0)throw new Error("Invalid or unsupported value for PSBT_GLOBAL_VERSION");const n=this.getGlobal(0),r=_.Transaction.fromBuffer(n);this.setGlobalPsbtVersion(2),this.setGlobalTxVersion(r.version),this.setGlobalFallbackLocktime(r.locktime),this.setGlobalInputCount(r.ins.length),this.setGlobalOutputCount(r.outs.length),r.ins.forEach((s,i)=>{this.setInputPreviousTxId(i,s.hash),this.setInputOutputIndex(i,s.index),this.setInputSequence(i,s.sequence)}),r.outs.forEach((s,i)=>{this.setOutputAmount(i,s.value),this.setOutputScript(i,s.script)}),this.globalMap.delete("0".padStart(2,"0"))}readKeyPair(t,n){const r=R(n.readVarInt());if(r===0)return!1;const o=n.readUInt8(),s=n.readSlice(r-1),i=n.readVarSlice(),a=new U(o,s).toString();if(t.has(a))throw new Error("Repeated keypair in PSBT map");return t.set(a,i),!0}getKeyDatas(t,n){if(!t)throw new Error("No such map");const r=[];return t.forEach((o,s)=>{this.isKeyType(s,[n])&&r.push(u.Buffer.from(s.substring(2),"hex"))}),r}isKeyType(t,n){const r=u.Buffer.from(t.substring(0,2),"hex").readUInt8(0);return n.some(o=>o===r)}setGlobal(t,n){const r=new U(t,u.Buffer.from([]));this.globalMap.set(r.toString(),n)}getGlobal(t){return pt(this.globalMap,t,w())}getGlobalOptional(t){return St(this.globalMap,t,w())}setInput(t,n,r,o){se(this.getMap(t,this.inputMaps),n,r,o)}getInput(t,n,r){return pt(this.inputMaps[t],n,r)}getInputOptional(t,n,r){return St(this.inputMaps[t],n,r)}setOutput(t,n,r,o){se(this.getMap(t,this.outputMaps),n,r,o)}getOutput(t,n,r){return pt(this.outputMaps[t],n,r)}getMap(t,n){const r=n[t];if(r)return r;const o=new Map;return n[t]=o,o}encodeBip32Derivation(t,n){const r=new B;return this.writeBip32Derivation(r,t,n),r.buffer()}decodeBip32Derivation(t){const n=new D(t);return this.readBip32Derivation(n)}writeBip32Derivation(t,n,r){t.writeSlice(n),r.forEach(o=>{t.writeUInt32(o)})}readBip32Derivation(t){const n=t.readSlice(4),r=[];for(;t.offset<t.buffer.length;)r.push(t.readUInt32());return{masterFingerprint:n,path:r}}encodeTapBip32Derivation(t,n,r){const o=new B;return o.writeVarInt(t.length),t.forEach(s=>{o.writeSlice(s)}),this.writeBip32Derivation(o,n,r),o.buffer()}decodeTapBip32Derivation(t){const n=new D(t),r=R(n.readVarInt()),o=[];for(let i=0;i<r;i++)o.push(n.readSlice(32));const s=this.readBip32Derivation(n);return{hashes:o,...s}}}function pt(e,t,n){const r=St(e,t,n);if(r===void 0)throw new Ye(new U(t,n).toString());return r}function St(e,t,n){if(!e)throw new Error("No such map");const r=new U(t,n),o=e.get(r.toString());if(o!==void 0)return u.Buffer.from(o)}class U{constructor(t,n){p(this,"keyType");p(this,"keyData");this.keyType=t,this.keyData=n}toString(){const t=new B;return this.toBuffer(t),t.buffer().toString("hex")}serialize(t){t.writeVarInt(1+this.keyData.length),this.toBuffer(t)}toBuffer(t){t.writeUInt8(this.keyType),t.writeSlice(this.keyData)}}class Vr{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 Gr(e){return new U(e.readUInt8(0),e.subarray(1))}function dt(e,t){const n=[...t].sort(([r],[o])=>r<o?-1:r>o?1:0);for(const[r,o]of n)new Vr(Gr(u.Buffer.from(r,"hex")),o).serialize(e);e.writeUInt8(0)}function w(){return u.Buffer.from([])}function se(e,t,n,r){const o=new U(t,n);e.set(o.toString(),r)}function C(e){const t=u.Buffer.alloc(4);return t.writeUInt32LE(e,0),t}function ie(e){return Fe(e)}function ae(e){const t=new B;return t.writeVarInt(e),t.buffer()}function ue(e){return R(new D(e).readVarInt())}const ce=192,It=32,le=2,Q=33,Z=32,Kr=1,Fr="TapBranch",Yr="TapTweak",he=64,fe=32,gt=64,Xr=34,st=u.Buffer.from([81,32]),qr=u.Buffer.from([0,20]),Wr=2,zr=3;function ct(e){_.initEccLib(wt);const t=_.payments.p2tr({internalPubkey:u.Buffer.from(e,"hex")}).output;if(!t)throw new d("p2tr produced no output script for the depositor key");return t}function pe(e,t){const n=u.Buffer.concat([u.Buffer.from([t]),u.Buffer.from(e,"hex")]);return u.Buffer.concat([qr,_.crypto.hash160(n)])}function qe(e){return e.length===Xr&&e.subarray(0,st.length).equals(st)}function jr(e,t,n,r){if(!qe(r))throw new d(`input ${e} is tapscript but its witnessUtxo script is not P2TR`);const o=t.length-Q;if(o<0||o%Z!==0)throw new d(`input ${e} control block length ${t.length} is not ${Q} plus a multiple of ${Z}`);const s=t.subarray(1,Q);if(!wt.isXOnlyPoint(s))throw new d(`input ${e} control block internal key is not an x-only point`);let i=n;for(let f=Q;f<t.length;f+=Z){const g=t.subarray(f,f+Z),h=u.Buffer.compare(i,g)<0?[i,g]:[g,i];i=_.crypto.taggedHash(Fr,u.Buffer.concat(h))}const a=_.crypto.taggedHash(Yr,u.Buffer.concat([s,i])),c=wt.xOnlyPointAddTweak(s,a);if(!c)throw new d(`input ${e} control block internal key has no taproot output key`);if(!r.subarray(st.length).equals(u.Buffer.from(c.xOnlyPubkey)))throw new d(`input ${e} control block does not commit to its TAP_LEAF_SCRIPT (recomputed taproot output key differs from the witnessUtxo witness program)`);if(c.parity!==(t[0]&Kr))throw new d(`input ${e} control block parity bit disagrees with the recomputed taproot output key`)}function Qr(e){const{psbt:t,depositorXOnlyHex:n,signInputIndexes:r}=e,o=new Map,s=new Map,i=t.getGlobalInputCount(),a=r===void 0?void 0:new Set(r),c=h=>a===void 0||a.has(h);if((a==null?void 0:a.size)===0)throw new d("signInputIndexes is empty — pass the indices to sign, or omit it to sign every device-signable input");for(const h of a??[])if(!Number.isInteger(h)||h<0||h>=i)throw new d(`input ${h} was requested for signing but this PSBT has ${i} input(s)`);const l=ct(n),f=[pe(n,Wr),pe(n,zr)];for(let h=0;h<i;h++){const E=t.getInputEntriesOfType(h,Tt.TAP_LEAF_SCRIPT);if(E.length>0){if(E.length>1)throw new d(`input ${h} carries an ambiguous leaf set (${E.length} TAP_LEAF_SCRIPT entries)`);const m=E[0].value;if(m.length<le)throw new d(`input ${h} TAP_LEAF_SCRIPT value length ${m.length} is below the ${le}-byte minimum (script byte plus the leaf-version byte)`);const G=m[m.length-1];if(G!==ce)throw new d(`input ${h} leaf version 0x${G.toString(16)} is not tapscript (0xc0)`);const v=t.getInputWitnessUtxo(h);if(!v)throw new d(`input ${h} is tapscript but has no witnessUtxo`);const W=m.subarray(0,m.length-1),kt=Cr(ce,W);jr(h,E[0].keyData,kt,v.scriptPubKey);const Ut={kind:"tapscript",expectedLeafHashHexes:new Set([kt.toString("hex")]),expectedSignerXOnlyHex:n};s.set(h,Ut),c(h)&&o.set(h,Ut);continue}const y=t.getInputEntriesOfType(h,Tt.TAP_INTERNAL_KEY);if(y.length>0){const m=y[0];if(y.length>1||m.keyData.length!==0||m.value.length!==It)throw new d(`input ${h} carries a malformed TAP_INTERNAL_KEY entry`);if(m.value.toString("hex")!==n)throw new d(`input ${h} internal key is not the connected depositor key`);const G=t.getInputWitnessUtxo(h);if(!G)throw new d(`input ${h} is keypath but has no witnessUtxo`);const v=G.scriptPubKey;if(!qe(v))throw new d(`input ${h} witnessUtxo script is not P2TR`);if(!v.equals(l))throw new d(`input ${h} witnessUtxo is not the BIP-86 P2TR of the depositor key`);const W={kind:"taproot-keypath",expectedOutputKeyHex:v.subarray(st.length).toString("hex")};s.set(h,W),o.set(h,W);continue}const lt=t.getInputWitnessUtxo(h);if(lt&&(lt.scriptPubKey.equals(l)||f.some(m=>lt.scriptPubKey.equals(m))))throw new d(`input ${h} spends a depositor-owned UTXO but carries no signing metadata`)}for(const h of a??[])if(!o.has(h))throw new d(`input ${h} was requested for signing but carries no signing metadata`);if(o.size===0)throw new d("PSBT contains no depositor-signable input");let g=0;for(const h of o.values())g+=h.kind==="tapscript"?h.expectedLeafHashHexes.size:1;return{byInput:o,classifiedByInput:s,expectedYieldCount:g}}function J(e){return e.kind==="tapscript"?`${e.inputIndex}:${e.leafHashHex}`:`${e.inputIndex}`}function de(e,t){if(e<gt)throw new d(`YIELD payload truncated inside the signature (${e} of ${gt} bytes on input ${t})`);if(e!==gt)throw new I("non-default-sighash",t)}function Zr(e){const t=[],n=new Set;return{assertAndRecord:s=>{let i,a;try{const[f,g]=Ke(s,0);i=R(f),a=g}catch(f){throw new d(`unparseable YIELD payload: ${f instanceof Error?f.message:String(f)}`)}const c=s[a];if(c===void 0)throw new d("YIELD payload truncated before the augmented-pubkey length");const l=e.byInput.get(i);if(l===void 0)throw new I("unexpected-input",i);if(c===he){if(l.kind!=="tapscript")throw new I("wrong-spend-type",i);const f=a+1+he;if(s.length<f)throw new d("YIELD payload truncated inside the augmented pubkey");const g=s.subarray(a+1,a+1+It).toString("hex"),h=s.subarray(a+1+It,f).toString("hex"),E=s.subarray(f);if(g!==l.expectedSignerXOnlyHex)throw new I("wrong-signer-key",i);if(!l.expectedLeafHashHexes.has(h))throw new I("unknown-leaf-hash",i);de(E.length,i);const y={kind:"tapscript",inputIndex:i,signerXOnlyHex:g,leafHashHex:h,signature:Uint8Array.from(E)};if(n.has(J(y)))throw new I("duplicate-yield",i);n.add(J(y)),t.push(y);return}if(c===fe){if(l.kind!=="taproot-keypath")throw new I("wrong-spend-type",i);const f=a+1+fe;if(s.length<f)throw new d("YIELD payload truncated inside the augmented pubkey");const g=s.subarray(a+1,f).toString("hex"),h=s.subarray(f);if(g!==l.expectedOutputKeyHex)throw new I("wrong-signer-key",i);de(h.length,i);const E={kind:"taproot-keypath",inputIndex:i,outputKeyHex:g,signature:Uint8Array.from(h)};if(n.has(J(E)))throw new I("duplicate-yield",i);n.add(J(E)),t.push(E);return}throw new I("unexpected-encoding",i)},get yields(){return t},get lastYield(){return t[t.length-1]},assertComplete:()=>{const s=new Set;for(const[c,l]of e.byInput)if(l.kind==="tapscript")for(const f of l.expectedLeafHashHexes)s.add(`${c}:${f}`);else s.add(`${c}`);const i=[...s].filter(c=>!n.has(c)),a=[...n].some(c=>!s.has(c));if(i.length>0||a||n.size!==e.expectedYieldCount)throw new ve(i)}}}const We=/^[0-9a-f]{64}$/;function Jr(e,t){if(Dt("depositorPath",e),e[br]!==Ve)throw new Error("depositorPath must use BIP-86 receive branch 0");for(let n=0;n<Nt;n++)if(e[n]!==t[n])throw new Error(`depositorPath ${$(e)} is not under the wallet policy's key origin ${$(t)} — the device could never mark the input internal`)}function ze(e,t,n,r){if(!Number.isInteger(r)||r<0||r>=b)throw new Error("addressIndex must be a non-hardened integer in 0..2^31-1");const o=it.HDKey.fromExtendedKey(e,t).deriveChild(n).deriveChild(r);if(!o.publicKey)throw new Error(`account xpub derived no public key at ${n}/${r}`);return u.Buffer.from(o.publicKey.subarray(1)).toString("hex")}function je(e,t,n){return ze(e,t,Ge,n)}function to(e,t,n){return ze(e,t,Ve,n)}function Qe(e,t){const n=ct(t);return e.txOutputs.flatMap((r,o)=>u.Buffer.from(r.script).equals(n)?[o]:[])}function eo(e,t){if(!We.test(t))throw new Error("changeXOnlyHex must be 64 lowercase hex characters");return Qe(_.Psbt.fromHex(e),t).length>0}function no(e){const{psbtHex:t,depositorXOnlyHex:n,walletPolicy:r,depositorPath:o,change:s}=e;if(!We.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");Jr(o,r.keyOriginPath);const i=_.Psbt.fromHex(t),a=u.Buffer.from(r.masterFingerprintHex,"hex"),c=u.Buffer.from(n,"hex");let l=0;if(i.data.inputs.forEach((f,g)=>{f.tapInternalKey&&u.Buffer.from(f.tapInternalKey).equals(c)&&(l++,i.updateInput(g,{tapBip32Derivation:[{masterFingerprint:a,pubkey:c,path:$(o),leafHashes:[]}]}))}),l!==i.data.inputs.length)throw new Error(`${i.data.inputs.length-l} of ${i.data.inputs.length} inputs do not carry the depositor key as TAP_INTERNAL_KEY — every Pre-PegIn input must be internal`);if(s){const f=je(r.accountXpub,r.bip32Versions,s.addressIndex),g=[...o.slice(0,Nt),Ge,s.addressIndex],h=u.Buffer.from(f,"hex"),E=Qe(i,f);if(E.length===0)throw new Error("change script matches no output — the PSBT does not pay the wallet's change address");for(const y of E)i.updateOutput(y,{tapInternalKey:h,tapBip32Derivation:[{masterFingerprint:a,pubkey:h,path:$(g),leafHashes:[]}]})}return i.toHex()}const ro="BIP0322-signed-message",oo=new Uint8Array([252,6,98,118,97,117,108,116,0]),Ze=0,Je=0,tn=0,so=0,Pt=0,io=u.Buffer.from([106]),ao=/^[0-9a-f]{64}$/,uo=/^[0-9a-f]{8}$/,co=u.Buffer.alloc(32,0),lo=4294967295,ho=u.Buffer.from([0,32]),fo=u.Buffer.from([81,32]),po=2;function go(e,t){const n=_.crypto.sha256(u.Buffer.from(e,"utf8"));return _.crypto.sha256(u.Buffer.concat([n,n,u.Buffer.from(t)]))}function Eo(e,t){const n=new _.Transaction;n.version=Ze,n.locktime=Je;const r=u.Buffer.concat([ho,go(ro,e)]);return n.addInput(co,lo,tn,r),n.addOutput(u.Buffer.concat([fo,u.Buffer.from(t)]),Pt),Uint8Array.from(n.getHash(!1))}function wo(e){const{message:t,depositorXOnlyHex:n,masterFingerprintHex:r,depositorPath:o}=e;if(!ao.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");if(!uo.test(r))throw new Error("masterFingerprintHex must be 8 lowercase hex characters");Dt("depositorPath",o);const s=new TextEncoder().encode(t),i=u.Buffer.from(n,"hex"),a=ct(n),c=Eo(s,a.subarray(po)),l=new _.Psbt;return l.setVersion(Ze),l.setLocktime(Je),l.addInput({hash:u.Buffer.from(c),index:so,sequence:tn,witnessUtxo:{script:a,value:Pt},tapInternalKey:i,tapBip32Derivation:[{masterFingerprint:u.Buffer.from(r,"hex"),pubkey:i,path:$(o),leafHashes:[]}]}),l.addOutput({script:io,value:Pt}),l.addUnknownKeyValToGlobal({key:u.Buffer.from(oo),value:u.Buffer.from(s)}),l.toHex()}const _o=/^[0-9a-f]{64}$/,mo=/^[0-9a-f]{8}$/,To=192,yt=32,So=0,Io=1,Po=32,yo=75,bo=76,Ro=79,xo=80,Ao=81,Oo=96,Bo=173,vo=178,ge=4,Ee=128,Co=1+yt+1+1+1,Lo=2,Mo=34,No=2147483648,Do=4194304,$o=65535,ko=2,Uo=0,Ho=0;function Vo(e){if(e.length<Co)return;let t=0;if(e[t++]!==Po)return;const n=u.Buffer.from(e.subarray(t,t+yt)).toString("hex");if(t+=yt,e[t++]!==Bo||t>=e.length)return;const r=e[t++];let o=0;if(!(r===So||r===Ro)){if(r>=Io&&r<=yo){const s=r;if(s>ge||t+s>e.length||(e[t+s-1]&Ee)!==0)return;for(let i=0;i<s;i++)o|=e[t+i]<<8*i;t+=s}else if(r===bo){if(t>=e.length)return;const s=e[t++];if(s>ge||t+s>e.length||(e[t+s-1]&Ee)!==0)return;for(let i=0;i<s;i++)o|=e[t+i]<<8*i;t+=s}else if(r>=Ao&&r<=Oo)o=r-xo;else return;if(!(o===0||o>$o)&&!(t>=e.length)&&e[t++]===vo&&t===e.length)return{leafKeyHex:n,csv:o}}}function en(e){let t;try{t=_.Psbt.fromHex(e)}catch{return}if(t.version<ko||t.locktime!==Uo||t.data.inputs.length!==1||t.data.outputs.length!==1)return;const n=t.data.inputs[0],r=n.tapLeafScript??[];if(r.length!==1||r[0].leafVersion!==To)return;const o=Vo(r[0].script);if(o!==void 0)return{...o,inputTxidInternalHex:u.Buffer.from(t.txInputs[0].hash).toString("hex"),sequence:t.txInputs[0].sequence??0,sighashType:n.sighashType,witnessUtxo:n.witnessUtxo?{scriptLength:n.witnessUtxo.script.length,value:n.witnessUtxo.value}:void 0,outputScriptHex:u.Buffer.from(t.txOutputs[0].script).toString("hex"),outputValue:t.txOutputs[0].value}}function nn(e){if(e.sighashType!==void 0&&e.sighashType!==Ho)throw new Error(`refund input sighash type ${e.sighashType} must be absent or SIGHASH_DEFAULT — the device rejects any other value`);if(e.witnessUtxo===void 0||e.witnessUtxo.scriptLength!==Mo)throw new Error("refund input must carry a P2TR witnessUtxo — the device rejects a missing or non-34-byte scriptPubKey");if(e.outputValue>e.witnessUtxo.value)throw new Error(`refund output value ${e.outputValue} exceeds the HTLC value ${e.witnessUtxo.value} — the device rejects it`);if(e.outputScriptHex!==ct(e.leafKeyHex).toString("hex"))throw new Error("refund output does not pay the refund leaf key's own BIP-86 address");if(e.csv<rt)throw new Error(`refund leaf CSV ${e.csv} is below the device's timelock floor of ${rt} blocks`);if((e.sequence&No)!==0||(e.sequence&Do)!==0)throw new Error("refund input sequence must be a plain block-count relative timelock (BIP-68 disable/time flags clear)");if(e.sequence!==e.csv)throw new Error(`refund input sequence ${e.sequence} must equal the leaf CSV ${e.csv} — the device compares them unmasked and rejects a mismatch`)}function Go(e){const{psbtHex:t,depositorXOnlyHex:n,masterFingerprintHex:r,depositorPath:o}=e;if(!_o.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");if(!mo.test(r))throw new Error("masterFingerprintHex must be 8 lowercase hex characters (the 4-byte master fingerprint)");Dt("depositorPath",o);const s=en(t);if(s===void 0)throw new Error("not a refund-shaped PSBT (expected 1 input, 1 output, and one refund tapscript leaf)");if(nn(s),s.leafKeyHex!==n)throw new Error("refund leaf key does not equal the depositor key — this device cannot sign this refund");const i=_.Psbt.fromHex(t),a=u.Buffer.from(i.txOutputs[0].script),c=u.Buffer.from(r,"hex"),l=$(o);return i.updateInput(0,{tapBip32Derivation:[{masterFingerprint:c,pubkey:u.Buffer.from(n,"hex"),path:l,leafHashes:[]}]}),i.updateOutput(0,{tapBip32Derivation:[{masterFingerprint:c,pubkey:a.subarray(Lo),path:l,leafHashes:[]}]}),i.toHex()}class H{constructor(t,n=_.crypto.sha256){p(this,"leaves");p(this,"rootNode");p(this,"leafNodes");p(this,"h");this.leaves=t,this.h=n;const r=this.calculateRoot(t);this.rootNode=r.root,this.leafNodes=r.leaves}getRoot(){return this.rootNode.hash}size(){return this.leaves.length}getLeaves(){return this.leaves}getLeafHash(t){const n=this.leafNodes[t];if(n===void 0)throw Error("Index out of bounds");return n.hash}getProof(t){const n=this.leafNodes[t];if(n===void 0)throw Error("Index out of bounds");return bt(n)}calculateRoot(t){const n=t.length;if(n==0)return{root:new Et(void 0,void 0,u.Buffer.alloc(32,0)),leaves:[]};if(n==1){const f=new Et(void 0,void 0,t[0]);return{root:f,leaves:[f]}}const r=Fo(n),o=this.calculateRoot(t.slice(0,r)),s=this.calculateRoot(t.slice(r)),i=o.root,a=s.root,c=this.hashNode(i.hash,a.hash),l=new Et(i,a,c);return i.parent=l,a.parent=l,{root:l,leaves:o.leaves.concat(s.leaves)}}hashNode(t,n){return this.h(u.Buffer.concat([u.Buffer.from([1]),t,n]))}}function V(e,t=_.crypto.sha256){return Ko(u.Buffer.from([0]),e,t)}function Ko(e,t,n){return n(u.Buffer.concat([e,t]))}class Et{constructor(t,n,r){p(this,"leftChild");p(this,"rightChild");p(this,"parent");p(this,"hash");this.leftChild=t,this.rightChild=n,this.hash=r}isLeaf(){return this.leftChild==null}}function bt(e){if(!e.parent)return[];if(e.parent.leftChild==e){if(!e.parent.rightChild)throw new Error("Expected right child to exist");return[e.parent.rightChild.hash,...bt(e.parent)]}else{if(!e.parent.leftChild)throw new Error("Expected left child to exist");return[e.parent.leftChild.hash,...bt(e.parent)]}}function Fo(e){if(e<2)throw Error("Expected n >= 2");return Yo(e)?e/2:1<<Math.floor(Math.log2(e))}function Yo(e){return(e&e-1)==0}const $t=255,Xo=2,S=32;class q{}class qo extends q{constructor(n,r,o){super();p(this,"results");p(this,"code",16);this.progressCallback=r,this.onYield=o,this.results=n}execute(n){const r=u.Buffer.from(n.subarray(1));return this.onYield&&this.onYield(u.Buffer.from(r)),this.results.push(r),this.progressCallback&&this.progressCallback(),u.Buffer.from("")}}class Wo extends q{constructor(n,r){super();p(this,"knownPreimages");p(this,"queue");p(this,"code",64);this.knownPreimages=n,this.queue=r}execute(n){const r=u.Buffer.from(n.subarray(1));if(r.length!==1+S)throw new Error("Invalid request, unexpected trailing data");if(r[0]!==0)throw new Error("Unsupported request, the first byte should be 0");const s=u.Buffer.from(r.subarray(1,1+S)).toString("hex"),i=this.knownPreimages.get(s);if(i!==void 0){const a=k(i.length),c=$t-a.length-1,l=Math.min(c,i.length);if(l<i.length)for(let f=l;f<i.length;f++)this.queue.push(u.Buffer.from(i.subarray(f,f+1)));return u.Buffer.concat([a,u.Buffer.from([l]),u.Buffer.from(i.subarray(0,l))])}throw new Error(`Requested unknown preimage for: ${s}`)}}class zo extends q{constructor(n,r){super();p(this,"knownTrees");p(this,"queue");p(this,"code",65);this.knownTrees=n,this.queue=r}execute(n){const r=u.Buffer.from(n.subarray(1));if(r.length<S+1+1)throw new Error("Invalid request, expected at least 34 bytes");const o=new D(r),i=o.readSlice(S).toString("hex");let a,c;try{a=R(o.readVarInt()),c=R(o.readVarInt())}catch{throw new Error("Invalid request, couldn't parse tree_size or leaf_index")}const l=this.knownTrees.get(i);if(!l)throw new Error(`Requested Merkle leaf proof for unknown tree: ${i}`);if(c>=a||l.size()!==a)throw new Error("Invalid index or tree size.");if(this.queue.length!==0)throw new Error("This command should not execute when the queue is not empty.");const f=l.getProof(c),g=Math.min(Math.floor(($t-S-1-1)/S),f.length),h=f.length-g;return h>0&&this.queue.push(...f.slice(-h)),u.Buffer.concat([l.getLeafHash(c),u.Buffer.from([f.length]),u.Buffer.from([g]),...f.slice(0,g)])}}class jo extends q{constructor(n){super();p(this,"knownTrees");p(this,"code",66);this.knownTrees=n}execute(n){const r=u.Buffer.from(n.subarray(1));if(r.length!==S+S)throw new Error("Invalid request, unexpected trailing data");const s=u.Buffer.from(r.subarray(0,S)).toString("hex"),a=u.Buffer.from(r.subarray(S,S+S)).toString("hex"),c=this.knownTrees.get(s);if(!c)throw new Error(`Requested Merkle leaf index for unknown root: ${s}`);let l=0,f=0;for(let g=0;g<c.size();g++)if(c.getLeafHash(g).toString("hex")===a){f=1,l=g;break}return u.Buffer.concat([u.Buffer.from([f]),k(l)])}}class Qo extends q{constructor(n){super();p(this,"queue");p(this,"code",160);this.queue=n}execute(n){if(n.length!==1)throw new Error("Invalid request, unexpected trailing data");const r=this.queue[0];if(r===void 0)throw new Error("No elements to get");const o=r.length;if(this.queue.some(c=>c.length!==o))throw new Error("The queue contains elements with different byte length, which is not expected");const s=Math.floor(($t-Xo)/o),i=Math.min(s,this.queue.length),a=this.queue.splice(0,i);return u.Buffer.concat([u.Buffer.from([i]),u.Buffer.from([o]),...a])}}class Zo{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 qo(this.yielded,t,n),new Wo(this.preimages,this.queue),new jo(this.roots),new zo(this.roots,this.queue),new Qo(this.queue)];for(const o of r){if(this.commands.has(o.code))throw new Error(`Multiple commands with code ${o.code}`);this.commands.set(o.code,o)}}getYielded(){return this.yielded}addKnownPreimage(t){this.preimages.set(_.crypto.sha256(t).toString("hex"),t)}addKnownList(t){for(const r of t){const o=u.Buffer.concat([u.Buffer.from([0]),r]);this.addKnownPreimage(o)}const n=new H(t.map(r=>V(r)));this.roots.set(n.getRoot().toString("hex"),n)}addKnownMapping(t){this.addKnownList(t.keys),this.addKnownList(t.values)}addKnownWalletPolicy(t){this.addKnownPreimage(t.serialize()),this.addKnownList(t.keys.map(n=>u.Buffer.from(n,"ascii"))),this.addKnownPreimage(u.Buffer.from(t.descriptorTemplate))}execute(t){if(t.length===0)throw new Error("Unexpected empty command");const n=t[0],r=this.commands.get(n);if(!r)throw new Error(`Unexpected command code ${n}`);return r.execute(t)}}class Jo{constructor(t,n){p(this,"keys");p(this,"keysTree");p(this,"values");p(this,"valuesTree");if(t.length!=n.length)throw new Error("keys and values should have the same length");for(let r=0;r<t.length-1;r++)if(t[r].toString("hex")>=t[r+1].toString("hex"))throw new Error("keys must be in strictly increasing order");this.keys=t,this.keysTree=new H(t.map(r=>V(r))),this.values=n,this.valuesTree=new H(n.map(r=>V(r)))}commitment(){return u.Buffer.concat([k(this.keys.length),this.keysTree.getRoot(),this.valuesTree.getRoot()])}}class X extends Xe{constructor(n){super();p(this,"globalMerkleMap");p(this,"inputMerkleMaps",[]);p(this,"outputMerkleMaps",[]);p(this,"inputMapCommitments");p(this,"outputMapCommitments");n.copy(this),this.globalMerkleMap=X.createMerkleMap(this.globalMap);const r=this.getGlobalInputCount();if(this.inputMaps.length!==r)throw new Error(`Input map count ${this.inputMaps.length} != declared PSBT_GLOBAL_INPUT_COUNT ${r}`);for(let s=0;s<r;s++){const i=this.inputMaps[s];if(i===void 0)throw new Error(`Missing input map ${s}`);this.inputMerkleMaps.push(X.createMerkleMap(i))}this.inputMapCommitments=this.inputMerkleMaps.map(s=>s.commitment());const o=this.getGlobalOutputCount();if(this.outputMaps.length!==o)throw new Error(`Output map count ${this.outputMaps.length} != declared PSBT_GLOBAL_OUTPUT_COUNT ${o}`);for(let s=0;s<o;s++){const i=this.outputMaps[s];if(i===void 0)throw new Error(`Missing output map ${s}`);this.outputMerkleMaps.push(X.createMerkleMap(i))}this.outputMapCommitments=this.outputMerkleMaps.map(s=>s.commitment())}getGlobalSize(){return this.globalMap.size}getGlobalKeysValuesRoot(){return this.globalMerkleMap.commitment()}static createMerkleMap(n){const r=[...n.keys()].sort(),o=r.map(i=>{const a=n.get(i);if(!a)throw new Error("No value for key "+i);return a}),s=r.map(i=>u.Buffer.from(i,"hex"));return new Jo(s,o)}}const ts=2;class es{constructor(t,n,r){p(this,"name");p(this,"descriptorTemplate");p(this,"keys");this.name=t,this.descriptorTemplate=n,this.keys=r}getId(){return _.crypto.sha256(this.serialize())}serialize(){const t=this.keys.map(o=>u.Buffer.from(o,"ascii")),n=new H(t.map(o=>V(o))),r=new B;return r.writeUInt8(ts),r.writeVarSlice(u.Buffer.from(this.name,"ascii")),r.writeVarInt(this.descriptorTemplate.length),r.writeSlice(_.crypto.sha256(u.Buffer.from(this.descriptorTemplate))),r.writeVarInt(this.keys.length),r.writeSlice(n.getRoot()),r.buffer()}}class rn extends es{constructor(t,n){super("",t,[n])}}const ns=4,rs=0,os=1,on=32,ss=new Uint8Array(on),is=new Uint8Array(on),as=/^[0-9a-f]{64}$/,us=/^(?:[0-9a-fA-F]{2})+$/,cs=/^[0-9a-f]{64}$/;function ls(e,t){const n=new H(e.inputMapCommitments.map(o=>V(o))).getRoot(),r=new H(e.outputMapCommitments.map(o=>V(o))).getRoot();return Uint8Array.from(u.Buffer.concat([e.getGlobalKeysValuesRoot(),k(e.getGlobalInputCount()),n,k(e.getGlobalOutputCount()),r,u.Buffer.from(t),u.Buffer.from(is)]))}function hs(e){return{cla:x,ins:ns,p1:rs,p2:os,data:e}}const fs=0;function ps(e,t){for(const[n]of t.byInput){const r=e.data.inputs[n].sighashType;if(r!==void 0&&r!==fs)throw new d(`input ${n} requests sighash type ${r}, but vault flows sign SIGHASH_DEFAULT only`)}}function ds(e,t){var n;for(const[r,o]of t.byInput){const s=e.data.inputs[r];if(s.finalScriptWitness||s.finalScriptSig)throw new d(`input ${r} is already finalized and this round signs it — pass an unsigned PSBT`);if(o.kind==="tapscript"){if((n=s.tapScriptSig)==null?void 0:n.some(a=>a.pubkey.toString("hex")===o.expectedSignerXOnlyHex&&o.expectedLeafHashHexes.has(a.leafHash.toString("hex"))))throw new d(`input ${r} already carries a tapScriptSig for a (key, leaf) we sign — pass an unsigned PSBT`);continue}if(s.tapKeySig)throw new d(`input ${r} already carries a tapKeySig and this round signs its keypath — pass an unsigned PSBT`)}}const sn=new WeakMap;function gs(e,t){const n={...e};return sn.set(n,t),n}function an(e){const t=sn.get(e);if(!t)throw new d("unrecognised prepared signing state — use prepareSignPsbt's return value");return t}function un(e){const{psbtHex:t,depositorXOnlyHex:n,signInputIndexes:r,walletPolicy:o}=e;if(!as.test(n))throw new d("depositorXOnlyHex must be 64 lowercase hex characters");let s;if(o!==void 0){if(!cs.test(o.walletIdHex))throw new d("walletPolicy.walletIdHex must be 64 lowercase hex characters");if(s=new rn(o.descriptorTemplate,o.keyInfo),s.getId().toString("hex")!==o.walletIdHex)throw new d("walletPolicy.walletIdHex does not match sha256 of the serialized policy")}if(!us.test(t))throw new d("psbtHex is not even-length hexadecimal");let i;try{i=_.Psbt.fromHex(t)}catch(E){throw new d(`PSBT rejected at parse (merge target): ${E instanceof Error?E.message:String(E)}`)}const a=new Xe;try{a.deserialize(u.Buffer.from(t,"hex"))}catch(E){throw new d(`PSBT rejected at parse: ${E instanceof Error?E.message:String(E)}`)}let c,l;try{c=new X(a),l=Qr({psbt:c,depositorXOnlyHex:n,signInputIndexes:r})}catch(E){throw E instanceof d?E:new d(`PSBT rejected at preflight: ${E instanceof Error?E.message:String(E)}`)}ds(i,l),ps(i,l);const f=Zr(l),g=new Zo(void 0,E=>f.assertAndRecord(E));g.addKnownMapping(c.globalMerkleMap);for(const E of c.inputMerkleMaps)g.addKnownMapping(E);for(const E of c.outputMerkleMaps)g.addKnownMapping(E);g.addKnownList(c.inputMapCommitments),g.addKnownList(c.outputMapCommitments);const h=o?u.Buffer.from(o.walletIdHex,"hex"):ss;return s&&g.addKnownWalletPolicy(s),gs({table:l,unsignedTxid:_.Transaction.fromBuffer(i.data.globalMap.unsignedTx.toBuffer()).getId()},{cdata:ls(c,h),interpreter:g,collector:f,originalPsbtHex:t,signsUnderWalletPolicy:o!==void 0})}const Es=248,ws=1,_s=0,ms=0,Ts=36864,Ss=57344;async function Is(e,t,n){const{collector:r,interpreter:o,cdata:s}=an(t),{table:i}=t;if(n.signal.aborted)throw new _t(r.yields.length);const a=hs(s);let c=a,l=await e(a),f=0;for(;l.sw===Ss;){let g;try{g=o.execute(u.Buffer.from(l.data))}catch(h){throw Ce(h)?h:Le(h)?new d(h.detail,tt(r.yields)):new d(`client command failed: ${h instanceof Error?h.message:String(h)}`,tt(r.yields))}if(r.yields.length>f){f=r.yields.length;const h=r.lastYield;if(h!==void 0&&n.onProgress!==void 0)try{n.onProgress({inputIndex:h.inputIndex,yieldedCount:f,expectedYieldCount:i.expectedYieldCount})}catch{}}if(n.signal.aborted)throw new _t(r.yields.length);c={cla:Es,ins:ws,p1:_s,p2:ms,data:g},l=await e(c)}if(l.sw!==Ts){const g=$e(l.sw,{...n.appIdentity,ins:c.ins,p1:c.p1,preDispatch:c===a});throw g===void 0?new d(`status word 0x${l.sw.toString(16)} escaped classification`,tt(r.yields)):g}return r.assertComplete(),r.yields}function Ps(e,t){const n=_.Psbt.fromHex(e);for(const r of t)r.kind==="tapscript"?n.updateInput(r.inputIndex,{tapScriptSig:[{pubkey:u.Buffer.from(r.signerXOnlyHex,"hex"),leafHash:u.Buffer.from(r.leafHashHex,"hex"),signature:u.Buffer.from(r.signature)}]}):n.updateInput(r.inputIndex,{tapKeySig:u.Buffer.from(r.signature)});return n.toHex()}const we=new WeakSet;async function cn(e,t,n){const{originalPsbtHex:r,signsUnderWalletPolicy:o}=an(t);if(we.has(t))throw new d("prepared signing state was already used — call prepareSignPsbt again for a retry");if([...t.table.byInput.values()].some(c=>c.kind==="taproot-keypath")&&!o)throw new d("PSBT signs a key-path input but was prepared without a walletPolicy — the device would answer SW_OK with no signature");we.add(t);const i=await Is(e,t,n);let a;try{a=Ps(r,i)}catch(c){throw new d(`merge failed after signing: ${c instanceof Error?c.message:String(c)}`,tt(i))}return{signedPsbtHex:a,yields:[...i]}}async function ys(e,t){const{psbtHex:n,depositorXOnlyHex:r,signInputIndexes:o,...s}=t,i=un({psbtHex:n,depositorXOnlyHex:r,signInputIndexes:o});return cn(e,i,s)}const _e="tr(@0/**)",me=2147483647,bs=/^[0-9a-f]{8}$/;function Rs(e){const{masterFingerprintHex:t,coinType:n,accountIndex:r,accountXpub:o,bip32Versions:s}=e;if(!bs.test(t))throw new Error("masterFingerprintHex must be 8 lowercase hex characters");if(!Number.isInteger(n)||n<0||n>me||!Number.isInteger(r)||r<0||r>me)throw new Error("coinType and accountIndex must be non-negative integers in 0..0x7fffffff");try{it.HDKey.fromExtendedKey(o,s)}catch(c){throw new Error(`accountXpub is not a valid extended key for this network: ${c instanceof Error?c.message:String(c)}`)}const i=`[${t}/${ot}'/${n}'/${r}']${o}`,a=new rn(_e,i).getId().toString("hex");return{descriptorTemplate:_e,keyInfo:i,walletIdHex:a,accountXpub:o,bip32Versions:s,keyOriginPath:[(b|ot)>>>0,(b|n)>>>0,(b|r)>>>0],masterFingerprintHex:t}}exports.closeDmk=at.closeDmk;exports.connectDmkSession=at.connectDmkSession;exports.disconnectDmkSession=at.disconnectDmkSession;exports.isSessionAlive=at.isSessionAlive;exports.DEPOSIT_TERMS_REJECTED_ERROR_NAME=He;exports.DepositTermsRejectedError=T;exports.LEDGER_DEVICE_ERROR_NAME=Ot;exports.LEDGER_DEVICE_LOCKED_ERROR_NAME=At;exports.LEDGER_SIGN_PSBT_ABORTED_ERROR_NAME=Lt;exports.LEDGER_SIGN_PSBT_INCOMPLETE_ERROR_NAME=vt;exports.LEDGER_SIGN_PSBT_PROTOCOL_ERROR_NAME=Ct;exports.LEDGER_USER_REFUSED_ERROR_NAME=xt;exports.LEDGER_YIELD_MISMATCH_ERROR_NAME=Bt;exports.LedgerDeviceError=Be;exports.LedgerDeviceLockedError=Oe;exports.LedgerSignPsbtAbortedError=_t;exports.LedgerSignPsbtIncompleteError=ve;exports.LedgerSignPsbtProtocolError=d;exports.LedgerUserRefusedError=Ae;exports.LedgerYieldMismatchError=I;exports.SW_BAD_STATE=Me;exports.SW_CAP_EXCEEDED=Ne;exports.SW_CLA_NOT_SUPPORTED=Mt;exports.approveVaultIntent=qn;exports.assertDepositTermsDeviceCompatible=Ir;exports.assertRefundPsbtSignable=nn;exports.augmentPsbtForRefund=Go;exports.augmentPsbtForWalletPolicy=no;exports.buildDefaultTaprootPolicy=Rs;exports.buildPopPsbtHex=wo;exports.classifyRefundPsbt=en;exports.createDmkApduSender=pr;exports.createDmkRawApduSender=ke;exports.deriveChangeXOnlyHex=je;exports.deriveContextHash=Xn;exports.deriveReceiveXOnlyHex=to;exports.encodeIntentGroup=Se;exports.encodeIntentScalars=Te;exports.encodeKeyBatches=Ie;exports.getExtendedPublicKey=be;exports.getMasterFingerprintHex=Zn;exports.getXOnlyPublicKeyHex=Jn;exports.isLedgerDeviceError=nr;exports.isLedgerDeviceLockedError=rr;exports.isLedgerSignPsbtAbortedError=sr;exports.isLedgerSignPsbtIncompleteError=or;exports.isLedgerSignPsbtProtocolError=Le;exports.isLedgerUserRefusedError=er;exports.isLedgerYieldMismatchError=Ce;exports.prepareSignPsbt=un;exports.psbtPaysChangeScript=eo;exports.signPreparedVaultPsbt=cn;exports.signVaultPsbt=ys;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|