@babylonlabs-io/ledger-vault-signer 0.7.4 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1053 -938
- package/dist/index.js.map +1 -1
- package/dist/refundPsbt.d.ts +88 -0
- package/dist/refundPsbt.d.ts.map +1 -0
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var un=Object.create;var ht=Object.defineProperty;var ln=Object.getOwnPropertyDescriptor;var hn=Object.getOwnPropertyNames;var fn=Object.getPrototypeOf,pn=Object.prototype.hasOwnProperty;var dn=(e,t,n)=>t in e?ht(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var gn=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of hn(t))!pn.call(e,o)&&o!==n&&ht(e,o,{get:()=>t[o],enumerable:!(r=ln(t,o))||r.enumerable});return e};var Z=(e,t,n)=>(n=e!=null?un(fn(e)):{},gn(t||!e||!e.__esModule?ht(n,"default",{value:e,enumerable:!0}):n,e));var p=(e,t,n)=>dn(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ct=require("@scure/bip32"),m=require("bitcoinjs-lib"),c=require("buffer"),En=require("@bitcoin-js/tiny-secp256k1-asmjs");function wn(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 mt=wn(En),mn=1,_n=1,Tn=1,In=2,Sn=33,yn=256,Pn=257,bn=258,Rn=39,An=259,On=105,Bn=260,xn=261,Cn=262,vn=271,Ln=265,Mn=266,Nn=267,Dn=268,kn=269,$n=270,Un=263,Vn=264,ot=32,Hn=32,Y=255,Gn=3+ot,Vt=Math.floor(Y/Gn);function O(e,t){if(t.length>Y)throw new Error(`TLV value for tag 0x${e.toString(16)} exceeds 255 bytes`);const n=new Uint8Array(3+t.length);return n[0]=e>>8&255,n[1]=e&255,n[2]=t.length,n.set(t,3),n}function ut(e,t,n){if(e<0n||e>=1n<<BigInt(8*t))throw new Error(`${n} ${e} does not fit in ${t} bytes`);const r=new Uint8Array(t);let o=e;for(let s=t-1;s>=0;s--)r[s]=Number(o&0xffn),o>>=8n;return r}function M(e,t,n){return O(e,ut(BigInt(t),1,n))}function Q(e,t,n){return O(e,ut(BigInt(t),4,n))}function N(e,t,n){return O(e,ut(t,8,n))}function st(e){const t=e.reduce((o,s)=>o+s.length,0),n=new Uint8Array(t);let r=0;for(const o of e)n.set(o,r),r+=o.length;return n}function Rt(e,t,n){if(e.length!==t)throw new Error(`${n} must be ${t} bytes, got ${e.length}`);return e}const Ht=5;function me(e){if(e.depositorPath.length!==Ht)throw new Error(`depositorPath must have exactly ${Ht} levels, got ${e.depositorPath.length}`);const t=st(e.depositorPath.map(n=>ut(BigInt(n>>>0),4,"path level")));return st([M(Tn,mn,"structureType"),M(In,_n,"version"),Q(Sn,e.coinType,"coinType"),N(yn,e.baseFeeRate,"baseFeeRate"),Q(Pn,e.peginCsvTimelock,"peginCsvTimelock"),Q(bn,e.payoutTimelock,"payoutTimelock"),O(Rn,Rt(e.prepeginTxidInternal,Hn,"prepeginTxid")),Q(An,e.htlcRefundTimelock,"htlcRefundTimelock"),O(On,t),M(Bn,e.keeperCount,"keeperCount"),M(xn,e.challengerCount,"challengerCount"),M(Cn,e.vaultCount,"vaultCount"),N(vn,e.prepeginMaxFee,"prepeginMaxFee")])}function _e(e){return st([M(Ln,e.htlcVout,"htlcVout"),O(Mn,Rt(e.vaultProviderPubkey,ot,"vaultProviderPubkey")),N(Nn,e.vaultAmount,"vaultAmount"),N(Dn,e.commissionFee,"commissionFee"),N(kn,e.depositorClaimValue,"depositorClaimValue"),N($n,e.peginMaxFee,"peginMaxFee")])}function Te(e,t){const n=(s,i)=>s.map((a,u)=>Rt(a,ot,`${i}[${u}]`)).sort((a,u)=>{for(let l=0;l<ot;l++)if(a[l]!==u[l])return a[l]-u[l];return 0}),r=[...n(e,"keeper").map(s=>O(Un,s)),...n(t,"challenger").map(s=>O(Vn,s))],o=[];for(let s=0;s<r.length;s+=Vt)o.push(st(r.slice(s,s+Vt)));return o}const A=225,ft=128,Gt=129,Kn=0,Fn=1,Yn=0,Xn=1,Wn=2,X=0,Kt=64,Ft=1024,Yt=10,Xt=32;function qn(e){return new Uint8Array([e>>8&255,e&255])}function zn(e){const t=e>>>0;return new Uint8Array([t>>>24&255,t>>>16&255,t>>>8&255,t&255])}function pt(e){const t=new Uint8Array(e.reduce((r,o)=>r+o.length,0));let n=0;for(const r of e)t.set(r,n),n+=r.length;return t}const Wt=/^[a-z0-9-]+$/;async function jn(e,{appName:t,derivationPath:n,context:r}){const o=new TextEncoder().encode(t);if(o.length<1||o.length>Kt)throw new Error(`appName must be 1..${Kt} bytes, got ${o.length}`);if(!Wt.test(t))throw new Error(`appName must match ${Wt} — the device rejects other characters`);if(n.length<1||n.length>Yt)throw new Error(`derivationPath must have 1..${Yt} levels`);if(r.length<1||r.length>Ft)throw new Error(`context must be 1..${Ft} bytes, got ${r.length}`);const s=pt([new Uint8Array([o.length]),o,new Uint8Array([n.length]),pt(n.map(zn)),qn(r.length)]),i=Math.min(r.length,Y-s.length);if(i<0)throw new Error("appName and derivationPath leave no room for context in the first APDU");let a=await e({cla:A,ins:Gt,p1:Kn,p2:X,data:pt([s,r.subarray(0,i)])});for(let u=i;u<r.length;u+=Y)a=await e({cla:A,ins:Gt,p1:Fn,p2:X,data:r.subarray(u,u+Y)});if(a.length!==Xt)throw new Error(`Expected a ${Xt}-byte context root, got ${a.length} bytes`);return a}async function Zn(e,{scalars:t,groups:n,keeperPubkeys:r,challengerPubkeys:o}){if(n.length!==t.vaultCount)throw new Error(`vaultCount ${t.vaultCount} does not match ${n.length} group(s)`);if(r.length!==t.keeperCount)throw new Error(`keeperCount ${t.keeperCount} does not match ${r.length} key(s)`);if(t.keeperCount<1||t.challengerCount<1)throw new Error(`Both rosters must be non-empty: keeperCount=${t.keeperCount}, challengerCount=${t.challengerCount}`);if(o.length!==t.challengerCount)throw new Error(`challengerCount ${t.challengerCount} does not match ${o.length} key(s)`);await e({cla:A,ins:ft,p1:Yn,p2:X,data:me(t)});for(const s of n)await e({cla:A,ins:ft,p1:Xn,p2:X,data:_e(s)});for(const s of Te(r,o))await e({cla:A,ins:ft,p1:Wn,p2:X,data:s})}const Qn=0,Ie=0,Se=1,Jn=0,qt=33,zt=10,tr=5,er=4;async function nr(e){const t=await e({cla:A,ins:tr,p1:Ie,p2:Se,data:new Uint8Array(0)});if(t.length!==er)throw new Error(`Ledger returned a ${t.length}-byte response instead of the 4-byte master fingerprint`);return Pe(t)}async function ye(e,t,n){if(t.length<1||t.length>zt)throw new Error(`BIP-32 path must have 1..${zt} levels, got ${t.length}`);const r=await e({cla:A,ins:Qn,p1:Ie,p2:Se,data:or(t)}),o=new TextDecoder().decode(r);if(o.length===0)throw new Error("Ledger returned an empty extended key");return ct.HDKey.fromExtendedKey(o,n),o}async function rr(e,t,n){const r=await ye(e,t,n),o=ct.HDKey.fromExtendedKey(r,n);if(!o.publicKey||o.publicKey.length!==qt)throw new Error(`Ledger returned an extended key without a ${qt}-byte public key`);return Pe(o.publicKey.subarray(1))}function Pe(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function or(e){const t=new Uint8Array(2+e.length*4);return t[0]=Jn,t[1]=e.length,e.forEach((n,r)=>{const o=2+r*4;t[o]=n>>>24&255,t[o+1]=n>>>16&255,t[o+2]=n>>>8&255,t[o+3]=n&255}),t}const At="LedgerUserRefusedError",Ot="LedgerDeviceLockedError",Bt="LedgerDeviceError",xt="LedgerYieldMismatchError",Ct="LedgerSignPsbtIncompleteError",vt="LedgerSignPsbtProtocolError",Lt="LedgerSignPsbtAbortedError";function be(e){return e.toString(16).padStart(4,"0")}class Re extends Error{constructor(n){super(`User rejected the request on the Ledger device (0x${be(n)})`);p(this,"statusWord");this.name=At,this.statusWord=n}}class Ae extends Error{constructor(n,r){super(`The Ledger device is locked — unlock it and retry (0x${be(n)})`);p(this,"statusWord");p(this,"preDispatch");this.name=Ot,this.statusWord=n,this.preDispatch=(r==null?void 0:r.preDispatch)??!1}}class Oe extends Error{constructor(n,r){super(r);p(this,"statusWord");this.name=Bt,this.statusWord=n}}class S extends Error{constructor(n,r){super(`The device yielded a signature that fails the expected-signature table (${n}${r===void 0?"":` on input ${r}`})`);p(this,"kind");p(this,"inputIndex");this.name=xt,this.kind=n,this.inputIndex=r}}class Be extends Error{constructor(n){super(`The device completed SIGN_PSBT without yielding every expected signature (missing ${n.length}: ${n.join(", ")})`);p(this,"missing");this.name=Ct,this.missing=n}}function rt(e){return e.map(({inputIndex:t,leafHashHex:n})=>n===void 0?{inputIndex:t}:{inputIndex:t,leafHashHex:n})}class d extends Error{constructor(n,r=[]){super(`SIGN_PSBT protocol failure: ${n}`);p(this,"detail");p(this,"collectedYields");this.name=vt,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 sr(e){return e instanceof Error&&e.name===At}function ir(e){return e instanceof Error&&e.name===Bt}function ar(e){return e instanceof Error&&e.name===Ot}function xe(e){return e instanceof Error&&e.name===xt}function cr(e){return e instanceof Error&&e.name===Ct}function Ce(e){return e instanceof Error&&e.name===vt}function ur(e){return e instanceof Error&&e.name===Lt}const lr=36864,hr=new Set([21761,27013]),fr=new Set([21781,27010,21251]),Mt=28160,ve=45063,Le=45066,pr={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",[ve]:"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",[Le]:"The device has already signed the maximum number of these transactions",28416:"The device reported an internal error"};function D(e){return e.toString(16).padStart(2,"0")}function Me(e){return e.toString(16).padStart(4,"0")}function Ne(e,t){if(e===lr)return;if(hr.has(e))return new Re(e);if(fr.has(e))return new Ae(e,{preDispatch:t.preDispatch===!0});const n=pr[e],r=e===Mt&&t.appName?` (app at connect time: "${t.appName}"${t.appVersion?` v${t.appVersion}`:""})`:"";return new Oe(e,`${n??"The device rejected the request"} (ins 0x${D(t.ins)} p1 0x${D(t.p1)}, sw 0x${Me(e)})${r}`)}function dr(e,t){return async n=>{const{sw:r,data:o}=await e(n),s=Ne(r,{...t,ins:n.ins,p1:n.p1});if(s)throw s;return o}}const jt=2;function gr(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 Er(e){if(J(e.cla,"cla"),J(e.ins,"ins"),J(e.p1,"p1"),J(e.p2,"p2"),e.data.length>255)throw new Error(`APDU data is ${e.data.length} bytes; Lc is a single byte (max 255)`);const t=new Uint8Array(5+e.data.length);return t[0]=e.cla,t[1]=e.ins,t[2]=e.p1,t[3]=e.p2,t[4]=e.data.length,t.set(e.data,5),t}function Zt(){return globalThis.__LEDGER_VAULT_APDU_TRACE__===!0}function De(e){return async t=>{const n=`${D(t.cla)} ${D(t.ins)} ${D(t.p1)} ${D(t.p2)} Lc=${t.data.length}`;let r;try{r=await e.dmk.sendApdu({sessionId:e.sessionId,apdu:Er(t)})}catch(s){throw Zt()&&console.debug(`[ledger-vault] APDU ${n} -> transport error`,s),s}const o=gr(r);return Zt()&&console.debug(`[ledger-vault] APDU ${n} -> sw=0x${Me(o)} len=${r.data.length}`),{sw:o,data:r.data}}}function wr(e){return dr(De(e),{appName:e.appName,appVersion:e.appVersion})}const mr={isRefresherDisabled:!0};let F,x;function ke(e){let t;return()=>(t||(t=e().catch(n=>{throw t=void 0,n})),t)}const $e=ke(()=>import("@ledgerhq/device-management-kit")),_r=ke(()=>import("@ledgerhq/device-transport-kit-web-hid"));function Tr(){if(!x){let e=function(n){if(x!==t)throw new Error("connectDmkSession: closeDmk() tore down this DMK while it was still building — retry to connect over a fresh one");return F=n.dmk,n};const t=(async()=>{const[{DeviceManagementKitBuilder:n},{webHidTransportFactory:r,webHidIdentifier:o}]=await Promise.all([$e(),_r()]),s=new n().addTransport(r).build();return e({dmk:s,transportIdentifier:o})})().catch(n=>{throw x===t&&(x=void 0),n});x=t}return x}async function Ir(){const{dmk:e,transportIdentifier:t}=await Tr(),{firstValueFrom:n}=await import("rxjs"),r=await n(e.startDiscovering({transport:t})),o=await e.connect({device:r,sessionRefresherOptions:mr}),s=await Sr(e,o);return{dmk:e,sessionId:o,...s}}async function Sr(e,t){try{const{GetAppAndVersionCommand:n,isSuccessCommandResult:r}=await $e(),o=await e.sendCommand({sessionId:t,command:new n});return r(o)?{appName:o.data.name,appVersion:o.data.version}:{}}catch{return{}}}async function yr(e){const{firstValueFrom:t}=await import("rxjs");try{return await t(e.dmk.getDeviceSessionState({sessionId:e.sessionId})),!0}catch(n){if((n==null?void 0:n._tag)==="DeviceSessionNotFound")return!1;throw n}}async function Pr(e){try{await e.dmk.disconnect({sessionId:e.sessionId})}catch{}}function br(){F==null||F.close(),F=void 0,x=void 0}const Rr=2,Ar=3,Qt=32,Or=10,Jt=0xffffffffn,te=72,Br=1008,xr=4320,Cr=91,vr=4031,Ue=546n,ee=Ue,Lr=2n,Ve="DepositTermsRejectedError";class T extends Error{constructor(n,r="device-envelope"){super(n);p(this,"reason");this.name=Ve,this.reason=r}}const y="Deposit terms outside the device-supported range";function B(e,t,n,r){if(!Number.isInteger(t)||t<n||t>r)throw new T(`${y}: ${e} ${t} not in [${n}, ${r}]`)}function Mr(e){if(B("vaultCoreVersion",e.vaultCoreVersion,Rr,Ar),e.protocolFeeRate<1n||e.protocolFeeRate>Jt)throw new T(`${y}: protocolFeeRate ${e.protocolFeeRate} not in [1, ${Jt}]`);if(B("timelockPegin",e.timelockPegin,te,Br),B("timelockAssert",e.timelockAssert,Cr,vr),B("timelockRefund",e.timelockRefund,te,xr),B("keeper count",e.vaultKeeperBtcPubkeys.length,1,Qt),B("challenger count",e.universalChallengerBtcPubkeys.length,1,Qt),B("vault count",e.vaults.length,1,Or),K("prepeginMaxFee",e.prepeginMaxFee),e.prepeginMaxFee<1n)throw new T(`${y}: prepeginMaxFee ${e.prepeginMaxFee} must be >= 1`);let t=-1;for(const a of e.vaults){if(!Number.isInteger(a.htlcVout)||a.htlcVout<0||a.htlcVout>255)throw new T(`${y}: htlcVout ${a.htlcVout} not in [0, 255]`);if(a.htlcVout<=t)throw new T(`${y}: vault groups must be in strictly ascending htlcVout order; got ${a.htlcVout} after ${t}`);t=a.htlcVout}const n=a=>a.replace(/^0x/,"").toLowerCase(),r=new Set(e.vaults.map(a=>n(a.vaultProviderBtcPubkey))),o=new Set;for(const[a,u]of[["vaultKeeperBtcPubkeys",e.vaultKeeperBtcPubkeys],["universalChallengerBtcPubkeys",e.universalChallengerBtcPubkeys]])for(const l of u){const f=n(l);if(r.has(f))throw new T(`${y}: ${a} contains the vault provider's own key (${f.slice(0,16)}…)`);if(o.has(f))throw new T(`${y}: duplicate participant key in ${a} (${f.slice(0,16)}…)`);o.add(f)}const s=Ue,i=Lr*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(`${y}: vault ${a.htlcVout} commissionFee ${a.commissionFee} below the ${s}-sat dust limit`);if(a.depositorClaimValue<ee)throw new T(`${y}: vault ${a.htlcVout} depositorClaimValue ${a.depositorClaimValue} below the ${ee}-sat device floor`);if(a.peginAmount<=a.commissionFee+i)throw new T(`${y}: vault ${a.htlcVout} peginAmount ${a.peginAmount} must exceed commissionFee + ${i} (${a.commissionFee+i})`)}}const Nr=(1n<<64n)-1n;function K(e,t){if(t<0n||t>Nr)throw new T(`${y}: ${e} ${t} does not fit in an unsigned 64-bit field`)}const b=2147483648,Dr=4294967295,it=86,He=0,Ge=1,ne=5,Nt=3,kr=3,$r=4;function Ke(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>Dr)throw new Error(`${e} levels must be integers in 0..0xffffffff`);if(!t.slice(0,Nt).every(r=>(r&b)!==0)||(t[$r]&b)!==0)throw new Error(`${e} must harden purpose'/coin'/account' and leave the address index unhardened`);if(t[0]!==(b|it)>>>0)throw new Error(`${e} must use BIP-86 purpose ${it}'`)}function q(e){return"m/"+e.map(t=>(t&b)!==0?`${(t&~b)>>>0}'`:`${t>>>0}`).join("/")}const re=253,Ur=254,Vr=65535,Hr=4294967295;function Gr(e){if(e<re)return c.Buffer.from([e]);if(e<=Vr){const t=c.Buffer.alloc(2);return t.writeUInt16LE(e),c.Buffer.concat([c.Buffer.from([re]),t])}if(e<=Hr){const t=c.Buffer.alloc(4);return t.writeUInt32LE(e),c.Buffer.concat([c.Buffer.from([Ur]),t])}throw new Error(`Script too large to encode as CompactSize: ${e} bytes`)}const Kr="TapLeaf";function Fr(e,t){const n=c.Buffer.concat([c.Buffer.from([e]),Gr(t.length),c.Buffer.from(t)]);return m.crypto.taggedHash(Kr,n)}function Yr(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 Xr(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 Wr(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 qr=BigInt(253),zr=BigInt(65535)+BigInt(1),jr=BigInt(4294967295)+BigInt(1);function Fe(e,t){if(t<0)throw RangeError("Negative offset is invalid");const n=e[t];if(n===void 0)throw Error("Buffer too small");if(n<253)return[BigInt(n),1];{let r,o;n===253?(r=2,o=qr):n===254?(r=4,o=zr):(r=8,o=jr);const s=Xr(e,t+1,r);if(s<o)throw RangeError(`Non-minimal varint at offset ${t}: a ${r+1}-byte CompactSize must encode a value of at least ${o}; re-encode it in its canonical (shorter) form`);return[s,r+1]}}function $(e){typeof e=="number"&&(e=R(e));const t=Wr(e);e=BigInt(e);const n=c.Buffer.alloc(t);return t==1?n[0]=Number(e):(t==3?n[0]=253:t===5?n[0]=254:n[0]=255,Yr(e,t-1,n,1)),n}const Zr=31;function Ye(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Can't convert a number that is not a non-negative safe integer to 64-bit LE");const t=c.Buffer.alloc(8,0);for(let n=0;n<t.length;n++){const r=e&255;t[n]=r,e=(e-r)/256}return t}function Tt(e){let t=0;if(e.length!==8)throw new Error("Expected Buffer of length 8");if(e[7]!==0)throw new Error("Can't encode numbers > MAX_SAFE_INT");const n=e[6];if(n===void 0||n>Zr)throw new Error("Can't encode numbers > MAX_SAFE_INT");for(let r=e.length-1;r>=0;r--){const o=e[r];if(o===void 0)throw new Error("Buffer too small");t=t*256+o}return t}class C{constructor(){p(this,"bufs",[])}write(t,n){const r=c.Buffer.alloc(t);n(r),this.bufs.push(r)}writeUInt8(t){this.write(1,n=>n.writeUInt8(t,0))}writeInt32(t){this.write(4,n=>n.writeInt32LE(t,0))}writeUInt32(t){this.write(4,n=>n.writeUInt32LE(t,0))}writeUInt64(t){const n=Ye(t);this.writeSlice(n)}writeVarInt(t){this.bufs.push($(t))}writeSlice(t){this.bufs.push(c.Buffer.from(t))}writeVarSlice(t){this.writeVarInt(t.length),this.writeSlice(t)}buffer(){return c.Buffer.concat(this.bufs)}}class k{constructor(t,n=0){this.buffer=t,this.offset=n}available(){return this.buffer.length-this.offset}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=this.readSlice(8);return Tt(t)}readVarInt(){const[t,n]=Fe(this.buffer,this.offset);return this.offset+=n,t}readSlice(t){if(this.buffer.length<this.offset+t)throw new Error("Cannot read slice out of bounds");const n=this.buffer.subarray(this.offset,this.offset+t);return this.offset+=t,n}readVarSlice(){const t=R(this.readVarInt());return this.readSlice(t)}readVector(){const t=this.readVarInt(),n=[];for(let r=0;r<t;r++)n.push(this.readVarSlice());return n}}var It=(e=>(e[e.NON_WITNESS_UTXO=0]="NON_WITNESS_UTXO",e[e.WITNESS_UTXO=1]="WITNESS_UTXO",e[e.PARTIAL_SIG=2]="PARTIAL_SIG",e[e.SIGHASH_TYPE=3]="SIGHASH_TYPE",e[e.REDEEM_SCRIPT=4]="REDEEM_SCRIPT",e[e.WITNESS_SCRIPT=5]="WITNESS_SCRIPT",e[e.BIP32_DERIVATION=6]="BIP32_DERIVATION",e[e.FINAL_SCRIPTSIG=7]="FINAL_SCRIPTSIG",e[e.FINAL_SCRIPTWITNESS=8]="FINAL_SCRIPTWITNESS",e[e.PREVIOUS_TXID=14]="PREVIOUS_TXID",e[e.OUTPUT_INDEX=15]="OUTPUT_INDEX",e[e.SEQUENCE=16]="SEQUENCE",e[e.TAP_KEY_SIG=19]="TAP_KEY_SIG",e[e.TAP_LEAF_SCRIPT=21]="TAP_LEAF_SCRIPT",e[e.TAP_BIP32_DERIVATION=22]="TAP_BIP32_DERIVATION",e[e.TAP_INTERNAL_KEY=23]="TAP_INTERNAL_KEY",e))(It||{});const oe=c.Buffer.from([112,115,98,116,255]),Qr=4294967295;class Xe extends Error{}class We{constructor(){p(this,"globalMap",new Map);p(this,"inputMaps",[]);p(this,"outputMaps",[])}setGlobalTxVersion(t){this.setGlobal(2,L(t))}getGlobalTxVersion(){return this.getGlobal(2).readUInt32LE(0)}setGlobalFallbackLocktime(t){this.setGlobal(3,L(t))}getGlobalFallbackLocktime(){var t;return(t=this.getGlobalOptional(3))==null?void 0:t.readUInt32LE(0)}setGlobalInputCount(t){this.setGlobal(4,ae(t))}getGlobalInputCount(){return ce(this.getGlobal(4))}setGlobalOutputCount(t){this.setGlobal(5,ae(t))}getGlobalOutputCount(){return ce(this.getGlobal(5))}setGlobalTxModifiable(t){this.setGlobal(6,t)}getGlobalTxModifiable(){return this.getGlobalOptional(6)}setGlobalPsbtVersion(t){this.setGlobal(251,L(t))}getGlobalPsbtVersion(){return this.getGlobal(251).readUInt32LE(0)}setInputNonWitnessUtxo(t,n){this.setInput(t,0,w(),n)}getInputNonWitnessUtxo(t){return this.getInputOptional(t,0,w())}setInputWitnessUtxo(t,n,r){const o=new C;o.writeSlice(ie(n)),o.writeVarSlice(r),this.setInput(t,1,w(),o.buffer())}getInputWitnessUtxo(t){const n=this.getInputOptional(t,1,w());if(!n)return;const r=new k(n);return{amount:Tt(r.readSlice(8)),scriptPubKey:r.readVarSlice()}}setInputPartialSig(t,n,r){this.setInput(t,2,n,r)}getInputPartialSig(t,n){return this.getInputOptional(t,2,n)}setInputSighashType(t,n){this.setInput(t,3,w(),L(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(),L(n))}getInputOutputIndex(t){return this.getInput(t,15,w()).readUInt32LE(0)}setInputSequence(t,n){this.setInput(t,16,w(),L(n))}getInputSequence(t){var n;return((n=this.getInputOptional(t,16,w()))==null?void 0:n.readUInt32LE(0))??Qr}setInputTapKeySig(t,n){this.setInput(t,19,w(),n)}getInputTapKeySig(t){return this.getInputOptional(t,19,w())}setInputTapBip32Derivation(t,n,r,o,s){if(n.length!==32)throw new Error("Invalid pubkey length: "+n.length);const i=this.encodeTapBip32Derivation(r,o,s);this.setInput(t,22,n,i)}getInputTapBip32Derivation(t,n){const r=this.getInput(t,22,n);return this.decodeTapBip32Derivation(r)}getInputKeyDatas(t,n){return this.getKeyDatas(this.inputMaps[t],n)}getInputEntriesOfType(t,n){const r=this.inputMaps[t];if(!r)throw new Error("No such map");const o=[];return r.forEach((s,i)=>{this.isKeyType(i,[n])&&o.push({keyData:c.Buffer.from(i.substring(2),"hex"),value:c.Buffer.from(s)})}),o}setOutputRedeemScript(t,n){this.setOutput(t,0,w(),n)}getOutputRedeemScript(t){return this.getOutput(t,0,w())}setOutputBip32Derivation(t,n,r,o){this.setOutput(t,2,n,this.encodeBip32Derivation(r,o))}getOutputBip32Derivation(t,n){const r=this.getOutput(t,2,n);return this.decodeBip32Derivation(r)}setOutputAmount(t,n){this.setOutput(t,3,w(),ie(n))}getOutputAmount(t){const n=this.getOutput(t,3,w());return Tt(n)}setOutputScript(t,n){this.setOutput(t,4,w(),n)}getOutputScript(t){return this.getOutput(t,4,w())}setOutputTapBip32Derivation(t,n,r,o,s){const i=this.encodeTapBip32Derivation(r,o,s);this.setOutput(t,7,n,i)}getOutputTapBip32Derivation(t,n){const r=this.getOutput(t,7,n);return this.decodeTapBip32Derivation(r)}deleteInputEntries(t,n){const r=this.inputMaps[t];if(!r)throw new Error("No such map");r.forEach((o,s,i)=>{this.isKeyType(s,n)&&i.delete(s)})}copy(t){this.copyMap(this.globalMap,t.globalMap),this.copyMaps(this.inputMaps,t.inputMaps),this.copyMaps(this.outputMaps,t.outputMaps)}copyMaps(t,n){t.forEach((r,o)=>{const s=new Map;this.copyMap(r,s),n[o]=s})}copyMap(t,n){t.forEach((r,o)=>n.set(o,c.Buffer.from(r)))}serialize(){const t=new C;return t.writeSlice(oe),gt(t,this.globalMap),this.inputMaps.forEach(n=>{gt(t,n)}),this.outputMaps.forEach(n=>{gt(t,n)}),t.buffer()}deserialize(t){const n=new k(t);if(!n.readSlice(5).equals(oe))throw new Error("Invalid magic bytes");for(;this.readKeyPair(this.globalMap,n););let r;try{r=this.getGlobalPsbtVersion()}catch(i){if(!(i instanceof Xe))throw i;r=0}if(r!==0&&r!==2)throw new Error("Only PSBTs of version 0 or 2 are supported");let o,s;if(r===0){const i=this.getGlobal(0),a=m.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=m.Transaction.fromBuffer(n);this.setGlobalPsbtVersion(2),this.setGlobalTxVersion(r.version),this.setGlobalFallbackLocktime(r.locktime),this.setGlobalInputCount(r.ins.length),this.setGlobalOutputCount(r.outs.length),r.ins.forEach((s,i)=>{this.setInputPreviousTxId(i,s.hash),this.setInputOutputIndex(i,s.index),this.setInputSequence(i,s.sequence)}),r.outs.forEach((s,i)=>{this.setOutputAmount(i,s.value),this.setOutputScript(i,s.script)}),this.globalMap.delete("0".padStart(2,"0"))}readKeyPair(t,n){const r=R(n.readVarInt());if(r===0)return!1;const o=n.readUInt8(),s=n.readSlice(r-1),i=n.readVarSlice(),a=new U(o,s).toString();if(t.has(a))throw new Error("Repeated keypair in PSBT map");return t.set(a,i),!0}getKeyDatas(t,n){if(!t)throw new Error("No such map");const r=[];return t.forEach((o,s)=>{this.isKeyType(s,[n])&&r.push(c.Buffer.from(s.substring(2),"hex"))}),r}isKeyType(t,n){const r=c.Buffer.from(t.substring(0,2),"hex").readUInt8(0);return n.some(o=>o===r)}setGlobal(t,n){const r=new U(t,c.Buffer.from([]));this.globalMap.set(r.toString(),n)}getGlobal(t){return dt(this.globalMap,t,w())}getGlobalOptional(t){return St(this.globalMap,t,w())}setInput(t,n,r,o){se(this.getMap(t,this.inputMaps),n,r,o)}getInput(t,n,r){return dt(this.inputMaps[t],n,r)}getInputOptional(t,n,r){return St(this.inputMaps[t],n,r)}setOutput(t,n,r,o){se(this.getMap(t,this.outputMaps),n,r,o)}getOutput(t,n,r){return dt(this.outputMaps[t],n,r)}getMap(t,n){const r=n[t];if(r)return r;const o=new Map;return n[t]=o,o}encodeBip32Derivation(t,n){const r=new C;return this.writeBip32Derivation(r,t,n),r.buffer()}decodeBip32Derivation(t){const n=new k(t);return this.readBip32Derivation(n)}writeBip32Derivation(t,n,r){t.writeSlice(n),r.forEach(o=>{t.writeUInt32(o)})}readBip32Derivation(t){const n=t.readSlice(4),r=[];for(;t.offset<t.buffer.length;)r.push(t.readUInt32());return{masterFingerprint:n,path:r}}encodeTapBip32Derivation(t,n,r){const o=new C;return o.writeVarInt(t.length),t.forEach(s=>{o.writeSlice(s)}),this.writeBip32Derivation(o,n,r),o.buffer()}decodeTapBip32Derivation(t){const n=new k(t),r=R(n.readVarInt()),o=[];for(let i=0;i<r;i++)o.push(n.readSlice(32));const s=this.readBip32Derivation(n);return{hashes:o,...s}}}function dt(e,t,n){const r=St(e,t,n);if(r===void 0)throw new Xe(new U(t,n).toString());return r}function St(e,t,n){if(!e)throw new Error("No such map");const r=new U(t,n),o=e.get(r.toString());if(o!==void 0)return c.Buffer.from(o)}class U{constructor(t,n){p(this,"keyType");p(this,"keyData");this.keyType=t,this.keyData=n}toString(){const t=new C;return this.toBuffer(t),t.buffer().toString("hex")}serialize(t){t.writeVarInt(1+this.keyData.length),this.toBuffer(t)}toBuffer(t){t.writeUInt8(this.keyType),t.writeSlice(this.keyData)}}class Jr{constructor(t,n){p(this,"key");p(this,"value");this.key=t,this.value=n}serialize(t){this.key.serialize(t),t.writeVarSlice(this.value)}}function to(e){return new U(e.readUInt8(0),e.subarray(1))}function gt(e,t){const n=[...t].sort(([r],[o])=>r<o?-1:r>o?1:0);for(const[r,o]of n)new Jr(to(c.Buffer.from(r,"hex")),o).serialize(e);e.writeUInt8(0)}function w(){return c.Buffer.from([])}function se(e,t,n,r){const o=new U(t,n);e.set(o.toString(),r)}function L(e){const t=c.Buffer.alloc(4);return t.writeUInt32LE(e,0),t}function ie(e){return Ye(e)}function ae(e){const t=new C;return t.writeVarInt(e),t.buffer()}function ce(e){return R(new k(e).readVarInt())}const ue=192,yt=32,le=2,tt=33,et=32,eo=1,no="TapBranch",ro="TapTweak",he=64,fe=32,Et=64,oo=34,at=c.Buffer.from([81,32]),so=c.Buffer.from([0,20]),io=2,ao=3;function Dt(e){m.initEccLib(mt);const t=m.payments.p2tr({internalPubkey:c.Buffer.from(e,"hex")}).output;if(!t)throw new d("p2tr produced no output script for the depositor key");return t}function pe(e,t){const n=c.Buffer.concat([c.Buffer.from([t]),c.Buffer.from(e,"hex")]);return c.Buffer.concat([so,m.crypto.hash160(n)])}function qe(e){return e.length===oo&&e.subarray(0,at.length).equals(at)}function co(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-tt;if(o<0||o%et!==0)throw new d(`input ${e} control block length ${t.length} is not ${tt} plus a multiple of ${et}`);const s=t.subarray(1,tt);if(!mt.isXOnlyPoint(s))throw new d(`input ${e} control block internal key is not an x-only point`);let i=n;for(let f=tt;f<t.length;f+=et){const g=t.subarray(f,f+et),h=c.Buffer.compare(i,g)<0?[i,g]:[g,i];i=m.crypto.taggedHash(no,c.Buffer.concat(h))}const a=m.crypto.taggedHash(ro,c.Buffer.concat([s,i])),u=mt.xOnlyPointAddTweak(s,a);if(!u)throw new d(`input ${e} control block internal key has no taproot output key`);if(!r.subarray(at.length).equals(c.Buffer.from(u.xOnlyPubkey)))throw new d(`input ${e} control block does not commit to its TAP_LEAF_SCRIPT (recomputed taproot output key differs from the witnessUtxo witness program)`);if(u.parity!==(t[0]&eo))throw new d(`input ${e} control block parity bit disagrees with the recomputed taproot output key`)}function uo(e){const{psbt:t,depositorXOnlyHex:n,signInputIndexes:r}=e,o=new Map,s=new Map,i=t.getGlobalInputCount(),a=r===void 0?void 0:new Set(r),u=h=>a===void 0||a.has(h);if((a==null?void 0:a.size)===0)throw new d("signInputIndexes is empty — pass the indices to sign, or omit it to sign every device-signable input");for(const h of a??[])if(!Number.isInteger(h)||h<0||h>=i)throw new d(`input ${h} was requested for signing but this PSBT has ${i} input(s)`);const l=Dt(n),f=[pe(n,io),pe(n,ao)];for(let h=0;h<i;h++){const E=t.getInputEntriesOfType(h,It.TAP_LEAF_SCRIPT);if(E.length>0){if(E.length>1)throw new d(`input ${h} carries an ambiguous leaf set (${E.length} TAP_LEAF_SCRIPT entries)`);const _=E[0].value;if(_.length<le)throw new d(`input ${h} TAP_LEAF_SCRIPT value length ${_.length} is below the ${le}-byte minimum (script byte plus the leaf-version byte)`);const G=_[_.length-1];if(G!==ue)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 j=_.subarray(0,_.length-1),$t=Fr(ue,j);co(h,E[0].keyData,$t,v.scriptPubKey);const Ut={kind:"tapscript",expectedLeafHashHexes:new Set([$t.toString("hex")]),expectedSignerXOnlyHex:n};s.set(h,Ut),u(h)&&o.set(h,Ut);continue}const P=t.getInputEntriesOfType(h,It.TAP_INTERNAL_KEY);if(P.length>0){const _=P[0];if(P.length>1||_.keyData.length!==0||_.value.length!==yt)throw new d(`input ${h} carries a malformed TAP_INTERNAL_KEY entry`);if(_.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 j={kind:"taproot-keypath",expectedOutputKeyHex:v.subarray(at.length).toString("hex")};s.set(h,j),o.set(h,j);continue}const lt=t.getInputWitnessUtxo(h);if(lt&&(lt.scriptPubKey.equals(l)||f.some(_=>lt.scriptPubKey.equals(_))))throw new d(`input ${h} spends a depositor-owned UTXO but carries no signing metadata`)}for(const h of a??[])if(!o.has(h))throw new d(`input ${h} was requested for signing but carries no signing metadata`);if(o.size===0)throw new d("PSBT contains no depositor-signable input");let g=0;for(const h of o.values())g+=h.kind==="tapscript"?h.expectedLeafHashHexes.size:1;return{byInput:o,classifiedByInput:s,expectedYieldCount:g}}function nt(e){return e.kind==="tapscript"?`${e.inputIndex}:${e.leafHashHex}`:`${e.inputIndex}`}function de(e,t){if(e<Et)throw new d(`YIELD payload truncated inside the signature (${e} of ${Et} bytes on input ${t})`);if(e!==Et)throw new S("non-default-sighash",t)}function lo(e){const t=[],n=new Set;return{assertAndRecord:s=>{let i,a;try{const[f,g]=Fe(s,0);i=R(f),a=g}catch(f){throw new d(`unparseable YIELD payload: ${f instanceof Error?f.message:String(f)}`)}const u=s[a];if(u===void 0)throw new d("YIELD payload truncated before the augmented-pubkey length");const l=e.byInput.get(i);if(l===void 0)throw new S("unexpected-input",i);if(u===he){if(l.kind!=="tapscript")throw new S("wrong-spend-type",i);const f=a+1+he;if(s.length<f)throw new d("YIELD payload truncated inside the augmented pubkey");const g=s.subarray(a+1,a+1+yt).toString("hex"),h=s.subarray(a+1+yt,f).toString("hex"),E=s.subarray(f);if(g!==l.expectedSignerXOnlyHex)throw new S("wrong-signer-key",i);if(!l.expectedLeafHashHexes.has(h))throw new S("unknown-leaf-hash",i);de(E.length,i);const P={kind:"tapscript",inputIndex:i,signerXOnlyHex:g,leafHashHex:h,signature:Uint8Array.from(E)};if(n.has(nt(P)))throw new S("duplicate-yield",i);n.add(nt(P)),t.push(P);return}if(u===fe){if(l.kind!=="taproot-keypath")throw new S("wrong-spend-type",i);const f=a+1+fe;if(s.length<f)throw new d("YIELD payload truncated inside the augmented pubkey");const g=s.subarray(a+1,f).toString("hex"),h=s.subarray(f);if(g!==l.expectedOutputKeyHex)throw new S("wrong-signer-key",i);de(h.length,i);const E={kind:"taproot-keypath",inputIndex:i,outputKeyHex:g,signature:Uint8Array.from(h)};if(n.has(nt(E)))throw new S("duplicate-yield",i);n.add(nt(E)),t.push(E);return}throw new S("unexpected-encoding",i)},get yields(){return t},get lastYield(){return t[t.length-1]},assertComplete:()=>{const s=new Set;for(const[u,l]of e.byInput)if(l.kind==="tapscript")for(const f of l.expectedLeafHashHexes)s.add(`${u}:${f}`);else s.add(`${u}`);const i=[...s].filter(u=>!n.has(u)),a=[...n].some(u=>!s.has(u));if(i.length>0||a||n.size!==e.expectedYieldCount)throw new Be(i)}}}const ze=/^[0-9a-f]{64}$/;function ho(e,t){if(Ke("depositorPath",e),e[kr]!==He)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 ${q(e)} is not under the wallet policy's key origin ${q(t)} — the device could never mark the input internal`)}function je(e,t,n,r){if(!Number.isInteger(r)||r<0||r>=b)throw new Error("addressIndex must be a non-hardened integer in 0..2^31-1");const o=ct.HDKey.fromExtendedKey(e,t).deriveChild(n).deriveChild(r);if(!o.publicKey)throw new Error(`account xpub derived no public key at ${n}/${r}`);return c.Buffer.from(o.publicKey.subarray(1)).toString("hex")}function Ze(e,t,n){return je(e,t,Ge,n)}function fo(e,t,n){return je(e,t,He,n)}function Qe(e,t){const n=Dt(t);return e.txOutputs.flatMap((r,o)=>c.Buffer.from(r.script).equals(n)?[o]:[])}function po(e,t){if(!ze.test(t))throw new Error("changeXOnlyHex must be 64 lowercase hex characters");return Qe(m.Psbt.fromHex(e),t).length>0}function go(e){const{psbtHex:t,depositorXOnlyHex:n,walletPolicy:r,depositorPath:o,change:s}=e;if(!ze.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");ho(o,r.keyOriginPath);const i=m.Psbt.fromHex(t),a=c.Buffer.from(r.masterFingerprintHex,"hex"),u=c.Buffer.from(n,"hex");let l=0;if(i.data.inputs.forEach((f,g)=>{f.tapInternalKey&&c.Buffer.from(f.tapInternalKey).equals(u)&&(l++,i.updateInput(g,{tapBip32Derivation:[{masterFingerprint:a,pubkey:u,path:q(o),leafHashes:[]}]}))}),l!==i.data.inputs.length)throw new Error(`${i.data.inputs.length-l} of ${i.data.inputs.length} inputs do not carry the depositor key as TAP_INTERNAL_KEY — every Pre-PegIn input must be internal`);if(s){const f=Ze(r.accountXpub,r.bip32Versions,s.addressIndex),g=[...o.slice(0,Nt),Ge,s.addressIndex],h=c.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 P of E)i.updateOutput(P,{tapInternalKey:h,tapBip32Derivation:[{masterFingerprint:a,pubkey:h,path:q(g),leafHashes:[]}]})}return i.toHex()}const Eo="BIP0322-signed-message",wo=new Uint8Array([252,6,98,118,97,117,108,116,0]),Je=0,tn=0,en=0,mo=0,Pt=0,_o=c.Buffer.from([106]),To=/^[0-9a-f]{64}$/,Io=/^[0-9a-f]{8}$/,So=c.Buffer.alloc(32,0),yo=4294967295,Po=c.Buffer.from([0,32]),bo=c.Buffer.from([81,32]),Ro=2;function Ao(e,t){const n=m.crypto.sha256(c.Buffer.from(e,"utf8"));return m.crypto.sha256(c.Buffer.concat([n,n,c.Buffer.from(t)]))}function Oo(e,t){const n=new m.Transaction;n.version=Je,n.locktime=tn;const r=c.Buffer.concat([Po,Ao(Eo,e)]);return n.addInput(So,yo,en,r),n.addOutput(c.Buffer.concat([bo,c.Buffer.from(t)]),Pt),Uint8Array.from(n.getHash(!1))}function Bo(e){const{message:t,depositorXOnlyHex:n,masterFingerprintHex:r,depositorPath:o}=e;if(!To.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");if(!Io.test(r))throw new Error("masterFingerprintHex must be 8 lowercase hex characters");Ke("depositorPath",o);const s=new TextEncoder().encode(t),i=c.Buffer.from(n,"hex"),a=Dt(n),u=Oo(s,a.subarray(Ro)),l=new m.Psbt;return l.setVersion(Je),l.setLocktime(tn),l.addInput({hash:c.Buffer.from(u),index:mo,sequence:en,witnessUtxo:{script:a,value:Pt},tapInternalKey:i,tapBip32Derivation:[{masterFingerprint:c.Buffer.from(r,"hex"),pubkey:i,path:q(o),leafHashes:[]}]}),l.addOutput({script:_o,value:Pt}),l.addUnknownKeyValToGlobal({key:c.Buffer.from(wo),value:c.Buffer.from(s)}),l.toHex()}class V{constructor(t,n=m.crypto.sha256){p(this,"leaves");p(this,"rootNode");p(this,"leafNodes");p(this,"h");this.leaves=t,this.h=n;const r=this.calculateRoot(t);this.rootNode=r.root,this.leafNodes=r.leaves}getRoot(){return this.rootNode.hash}size(){return this.leaves.length}getLeaves(){return this.leaves}getLeafHash(t){const n=this.leafNodes[t];if(n===void 0)throw Error("Index out of bounds");return n.hash}getProof(t){const n=this.leafNodes[t];if(n===void 0)throw Error("Index out of bounds");return bt(n)}calculateRoot(t){const n=t.length;if(n==0)return{root:new wt(void 0,void 0,c.Buffer.alloc(32,0)),leaves:[]};if(n==1){const f=new wt(void 0,void 0,t[0]);return{root:f,leaves:[f]}}const r=Co(n),o=this.calculateRoot(t.slice(0,r)),s=this.calculateRoot(t.slice(r)),i=o.root,a=s.root,u=this.hashNode(i.hash,a.hash),l=new wt(i,a,u);return i.parent=l,a.parent=l,{root:l,leaves:o.leaves.concat(s.leaves)}}hashNode(t,n){return this.h(c.Buffer.concat([c.Buffer.from([1]),t,n]))}}function H(e,t=m.crypto.sha256){return xo(c.Buffer.from([0]),e,t)}function xo(e,t,n){return n(c.Buffer.concat([e,t]))}class wt{constructor(t,n,r){p(this,"leftChild");p(this,"rightChild");p(this,"parent");p(this,"hash");this.leftChild=t,this.rightChild=n,this.hash=r}isLeaf(){return this.leftChild==null}}function bt(e){if(!e.parent)return[];if(e.parent.leftChild==e){if(!e.parent.rightChild)throw new Error("Expected right child to exist");return[e.parent.rightChild.hash,...bt(e.parent)]}else{if(!e.parent.leftChild)throw new Error("Expected left child to exist");return[e.parent.leftChild.hash,...bt(e.parent)]}}function Co(e){if(e<2)throw Error("Expected n >= 2");return vo(e)?e/2:1<<Math.floor(Math.log2(e))}function vo(e){return(e&e-1)==0}const kt=255,Lo=2,I=32;class z{}class Mo extends z{constructor(n,r,o){super();p(this,"results");p(this,"code",16);this.progressCallback=r,this.onYield=o,this.results=n}execute(n){const r=c.Buffer.from(n.subarray(1));return this.onYield&&this.onYield(c.Buffer.from(r)),this.results.push(r),this.progressCallback&&this.progressCallback(),c.Buffer.from("")}}class No extends z{constructor(n,r){super();p(this,"knownPreimages");p(this,"queue");p(this,"code",64);this.knownPreimages=n,this.queue=r}execute(n){const r=c.Buffer.from(n.subarray(1));if(r.length!==1+I)throw new Error("Invalid request, unexpected trailing data");if(r[0]!==0)throw new Error("Unsupported request, the first byte should be 0");const s=c.Buffer.from(r.subarray(1,1+I)).toString("hex"),i=this.knownPreimages.get(s);if(i!==void 0){const a=$(i.length),u=kt-a.length-1,l=Math.min(u,i.length);if(l<i.length)for(let f=l;f<i.length;f++)this.queue.push(c.Buffer.from(i.subarray(f,f+1)));return c.Buffer.concat([a,c.Buffer.from([l]),c.Buffer.from(i.subarray(0,l))])}throw new Error(`Requested unknown preimage for: ${s}`)}}class Do extends z{constructor(n,r){super();p(this,"knownTrees");p(this,"queue");p(this,"code",65);this.knownTrees=n,this.queue=r}execute(n){const r=c.Buffer.from(n.subarray(1));if(r.length<I+1+1)throw new Error("Invalid request, expected at least 34 bytes");const o=new k(r),i=o.readSlice(I).toString("hex");let a,u;try{a=R(o.readVarInt()),u=R(o.readVarInt())}catch{throw new Error("Invalid request, couldn't parse tree_size or leaf_index")}const l=this.knownTrees.get(i);if(!l)throw new Error(`Requested Merkle leaf proof for unknown tree: ${i}`);if(u>=a||l.size()!==a)throw new Error("Invalid index or tree size.");if(this.queue.length!==0)throw new Error("This command should not execute when the queue is not empty.");const f=l.getProof(u),g=Math.min(Math.floor((kt-I-1-1)/I),f.length),h=f.length-g;return h>0&&this.queue.push(...f.slice(-h)),c.Buffer.concat([l.getLeafHash(u),c.Buffer.from([f.length]),c.Buffer.from([g]),...f.slice(0,g)])}}class ko extends z{constructor(n){super();p(this,"knownTrees");p(this,"code",66);this.knownTrees=n}execute(n){const r=c.Buffer.from(n.subarray(1));if(r.length!==I+I)throw new Error("Invalid request, unexpected trailing data");const s=c.Buffer.from(r.subarray(0,I)).toString("hex"),a=c.Buffer.from(r.subarray(I,I+I)).toString("hex"),u=this.knownTrees.get(s);if(!u)throw new Error(`Requested Merkle leaf index for unknown root: ${s}`);let l=0,f=0;for(let g=0;g<u.size();g++)if(u.getLeafHash(g).toString("hex")===a){f=1,l=g;break}return c.Buffer.concat([c.Buffer.from([f]),$(l)])}}class $o extends z{constructor(n){super();p(this,"queue");p(this,"code",160);this.queue=n}execute(n){if(n.length!==1)throw new Error("Invalid request, unexpected trailing data");const r=this.queue[0];if(r===void 0)throw new Error("No elements to get");const o=r.length;if(this.queue.some(u=>u.length!==o))throw new Error("The queue contains elements with different byte length, which is not expected");const s=Math.floor((kt-Lo)/o),i=Math.min(s,this.queue.length),a=this.queue.splice(0,i);return c.Buffer.concat([c.Buffer.from([i]),c.Buffer.from([o]),...a])}}class Uo{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 Mo(this.yielded,t,n),new No(this.preimages,this.queue),new ko(this.roots),new Do(this.roots,this.queue),new $o(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(m.crypto.sha256(t).toString("hex"),t)}addKnownList(t){for(const r of t){const o=c.Buffer.concat([c.Buffer.from([0]),r]);this.addKnownPreimage(o)}const n=new V(t.map(r=>H(r)));this.roots.set(n.getRoot().toString("hex"),n)}addKnownMapping(t){this.addKnownList(t.keys),this.addKnownList(t.values)}addKnownWalletPolicy(t){this.addKnownPreimage(t.serialize()),this.addKnownList(t.keys.map(n=>c.Buffer.from(n,"ascii"))),this.addKnownPreimage(c.Buffer.from(t.descriptorTemplate))}execute(t){if(t.length===0)throw new Error("Unexpected empty command");const n=t[0],r=this.commands.get(n);if(!r)throw new Error(`Unexpected command code ${n}`);return r.execute(t)}}class Vo{constructor(t,n){p(this,"keys");p(this,"keysTree");p(this,"values");p(this,"valuesTree");if(t.length!=n.length)throw new Error("keys and values should have the same length");for(let r=0;r<t.length-1;r++)if(t[r].toString("hex")>=t[r+1].toString("hex"))throw new Error("keys must be in strictly increasing order");this.keys=t,this.keysTree=new V(t.map(r=>H(r))),this.values=n,this.valuesTree=new V(n.map(r=>H(r)))}commitment(){return c.Buffer.concat([$(this.keys.length),this.keysTree.getRoot(),this.valuesTree.getRoot()])}}class W extends We{constructor(n){super();p(this,"globalMerkleMap");p(this,"inputMerkleMaps",[]);p(this,"outputMerkleMaps",[]);p(this,"inputMapCommitments");p(this,"outputMapCommitments");n.copy(this),this.globalMerkleMap=W.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(W.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(W.createMerkleMap(i))}this.outputMapCommitments=this.outputMerkleMaps.map(s=>s.commitment())}getGlobalSize(){return this.globalMap.size}getGlobalKeysValuesRoot(){return this.globalMerkleMap.commitment()}static createMerkleMap(n){const r=[...n.keys()].sort(),o=r.map(i=>{const a=n.get(i);if(!a)throw new Error("No value for key "+i);return a}),s=r.map(i=>c.Buffer.from(i,"hex"));return new Vo(s,o)}}const Ho=2;class Go{constructor(t,n,r){p(this,"name");p(this,"descriptorTemplate");p(this,"keys");this.name=t,this.descriptorTemplate=n,this.keys=r}getId(){return m.crypto.sha256(this.serialize())}serialize(){const t=this.keys.map(o=>c.Buffer.from(o,"ascii")),n=new V(t.map(o=>H(o))),r=new C;return r.writeUInt8(Ho),r.writeVarSlice(c.Buffer.from(this.name,"ascii")),r.writeVarInt(this.descriptorTemplate.length),r.writeSlice(m.crypto.sha256(c.Buffer.from(this.descriptorTemplate))),r.writeVarInt(this.keys.length),r.writeSlice(n.getRoot()),r.buffer()}}class nn extends Go{constructor(t,n){super("",t,[n])}}const Ko=4,Fo=0,Yo=1,rn=32,Xo=new Uint8Array(rn),Wo=new Uint8Array(rn),qo=/^[0-9a-f]{64}$/,zo=/^(?:[0-9a-fA-F]{2})+$/,jo=/^[0-9a-f]{64}$/;function Zo(e,t){const n=new V(e.inputMapCommitments.map(o=>H(o))).getRoot(),r=new V(e.outputMapCommitments.map(o=>H(o))).getRoot();return Uint8Array.from(c.Buffer.concat([e.getGlobalKeysValuesRoot(),$(e.getGlobalInputCount()),n,$(e.getGlobalOutputCount()),r,c.Buffer.from(t),c.Buffer.from(Wo)]))}function Qo(e){return{cla:A,ins:Ko,p1:Fo,p2:Yo,data:e}}const Jo=0;function ts(e,t){for(const[n]of t.byInput){const r=e.data.inputs[n].sighashType;if(r!==void 0&&r!==Jo)throw new d(`input ${n} requests sighash type ${r}, but vault flows sign SIGHASH_DEFAULT only`)}}function es(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 on=new WeakMap;function ns(e,t){const n={...e};return on.set(n,t),n}function sn(e){const t=on.get(e);if(!t)throw new d("unrecognised prepared signing state — use prepareSignPsbt's return value");return t}function an(e){const{psbtHex:t,depositorXOnlyHex:n,signInputIndexes:r,walletPolicy:o}=e;if(!qo.test(n))throw new d("depositorXOnlyHex must be 64 lowercase hex characters");let s;if(o!==void 0){if(!jo.test(o.walletIdHex))throw new d("walletPolicy.walletIdHex must be 64 lowercase hex characters");if(s=new nn(o.descriptorTemplate,o.keyInfo),s.getId().toString("hex")!==o.walletIdHex)throw new d("walletPolicy.walletIdHex does not match sha256 of the serialized policy")}if(!zo.test(t))throw new d("psbtHex is not even-length hexadecimal");let i;try{i=m.Psbt.fromHex(t)}catch(E){throw new d(`PSBT rejected at parse (merge target): ${E instanceof Error?E.message:String(E)}`)}const a=new We;try{a.deserialize(c.Buffer.from(t,"hex"))}catch(E){throw new d(`PSBT rejected at parse: ${E instanceof Error?E.message:String(E)}`)}let u,l;try{u=new W(a),l=uo({psbt:u,depositorXOnlyHex:n,signInputIndexes:r})}catch(E){throw E instanceof d?E:new d(`PSBT rejected at preflight: ${E instanceof Error?E.message:String(E)}`)}es(i,l),ts(i,l);const f=lo(l),g=new Uo(void 0,E=>f.assertAndRecord(E));g.addKnownMapping(u.globalMerkleMap);for(const E of u.inputMerkleMaps)g.addKnownMapping(E);for(const E of u.outputMerkleMaps)g.addKnownMapping(E);g.addKnownList(u.inputMapCommitments),g.addKnownList(u.outputMapCommitments);const h=o?c.Buffer.from(o.walletIdHex,"hex"):Xo;return s&&g.addKnownWalletPolicy(s),ns({table:l,unsignedTxid:m.Transaction.fromBuffer(i.data.globalMap.unsignedTx.toBuffer()).getId()},{cdata:Zo(u,h),interpreter:g,collector:f,originalPsbtHex:t,signsUnderWalletPolicy:o!==void 0})}const rs=248,os=1,ss=0,is=0,as=36864,cs=57344;async function us(e,t,n){const{collector:r,interpreter:o,cdata:s}=sn(t),{table:i}=t;if(n.signal.aborted)throw new _t(r.yields.length);const a=Qo(s);let u=a,l=await e(a),f=0;for(;l.sw===cs;){let g;try{g=o.execute(c.Buffer.from(l.data))}catch(h){throw xe(h)?h:Ce(h)?new d(h.detail,rt(r.yields)):new d(`client command failed: ${h instanceof Error?h.message:String(h)}`,rt(r.yields))}if(r.yields.length>f){f=r.yields.length;const h=r.lastYield;if(h!==void 0&&n.onProgress!==void 0)try{n.onProgress({inputIndex:h.inputIndex,yieldedCount:f,expectedYieldCount:i.expectedYieldCount})}catch{}}if(n.signal.aborted)throw new _t(r.yields.length);u={cla:rs,ins:os,p1:ss,p2:is,data:g},l=await e(u)}if(l.sw!==as){const g=Ne(l.sw,{...n.appIdentity,ins:u.ins,p1:u.p1,preDispatch:u===a});throw g===void 0?new d(`status word 0x${l.sw.toString(16)} escaped classification`,rt(r.yields)):g}return r.assertComplete(),r.yields}function ls(e,t){const n=m.Psbt.fromHex(e);for(const r of t)r.kind==="tapscript"?n.updateInput(r.inputIndex,{tapScriptSig:[{pubkey:c.Buffer.from(r.signerXOnlyHex,"hex"),leafHash:c.Buffer.from(r.leafHashHex,"hex"),signature:c.Buffer.from(r.signature)}]}):n.updateInput(r.inputIndex,{tapKeySig:c.Buffer.from(r.signature)});return n.toHex()}const ge=new WeakSet;async function cn(e,t,n){const{originalPsbtHex:r,signsUnderWalletPolicy:o}=sn(t);if(ge.has(t))throw new d("prepared signing state was already used — call prepareSignPsbt again for a retry");if([...t.table.byInput.values()].some(u=>u.kind==="taproot-keypath")&&!o)throw new d("PSBT signs a key-path input but was prepared without a walletPolicy — the device would answer SW_OK with no signature");ge.add(t);const i=await us(e,t,n);let a;try{a=ls(r,i)}catch(u){throw new d(`merge failed after signing: ${u instanceof Error?u.message:String(u)}`,rt(i))}return{signedPsbtHex:a,yields:[...i]}}async function hs(e,t){const{psbtHex:n,depositorXOnlyHex:r,signInputIndexes:o,...s}=t,i=an({psbtHex:n,depositorXOnlyHex:r,signInputIndexes:o});return cn(e,i,s)}const Ee="tr(@0/**)",we=2147483647,fs=/^[0-9a-f]{8}$/;function ps(e){const{masterFingerprintHex:t,coinType:n,accountIndex:r,accountXpub:o,bip32Versions:s}=e;if(!fs.test(t))throw new Error("masterFingerprintHex must be 8 lowercase hex characters");if(!Number.isInteger(n)||n<0||n>we||!Number.isInteger(r)||r<0||r>we)throw new Error("coinType and accountIndex must be non-negative integers in 0..0x7fffffff");try{ct.HDKey.fromExtendedKey(o,s)}catch(u){throw new Error(`accountXpub is not a valid extended key for this network: ${u instanceof Error?u.message:String(u)}`)}const i=`[${t}/${it}'/${n}'/${r}']${o}`,a=new nn(Ee,i).getId().toString("hex");return{descriptorTemplate:Ee,keyInfo:i,walletIdHex:a,accountXpub:o,bip32Versions:s,keyOriginPath:[(b|it)>>>0,(b|n)>>>0,(b|r)>>>0],masterFingerprintHex:t}}exports.DEPOSIT_TERMS_REJECTED_ERROR_NAME=Ve;exports.DepositTermsRejectedError=T;exports.LEDGER_DEVICE_ERROR_NAME=Bt;exports.LEDGER_DEVICE_LOCKED_ERROR_NAME=Ot;exports.LEDGER_SIGN_PSBT_ABORTED_ERROR_NAME=Lt;exports.LEDGER_SIGN_PSBT_INCOMPLETE_ERROR_NAME=Ct;exports.LEDGER_SIGN_PSBT_PROTOCOL_ERROR_NAME=vt;exports.LEDGER_USER_REFUSED_ERROR_NAME=At;exports.LEDGER_YIELD_MISMATCH_ERROR_NAME=xt;exports.LedgerDeviceError=Oe;exports.LedgerDeviceLockedError=Ae;exports.LedgerSignPsbtAbortedError=_t;exports.LedgerSignPsbtIncompleteError=Be;exports.LedgerSignPsbtProtocolError=d;exports.LedgerUserRefusedError=Re;exports.LedgerYieldMismatchError=S;exports.SW_BAD_STATE=ve;exports.SW_CAP_EXCEEDED=Le;exports.SW_CLA_NOT_SUPPORTED=Mt;exports.approveVaultIntent=Zn;exports.assertDepositTermsDeviceCompatible=Mr;exports.augmentPsbtForWalletPolicy=go;exports.buildDefaultTaprootPolicy=ps;exports.buildPopPsbtHex=Bo;exports.closeDmk=br;exports.connectDmkSession=Ir;exports.createDmkApduSender=wr;exports.createDmkRawApduSender=De;exports.deriveChangeXOnlyHex=Ze;exports.deriveContextHash=jn;exports.deriveReceiveXOnlyHex=fo;exports.disconnectDmkSession=Pr;exports.encodeIntentGroup=_e;exports.encodeIntentScalars=me;exports.encodeKeyBatches=Te;exports.getExtendedPublicKey=ye;exports.getMasterFingerprintHex=nr;exports.getXOnlyPublicKeyHex=rr;exports.isLedgerDeviceError=ir;exports.isLedgerDeviceLockedError=ar;exports.isLedgerSignPsbtAbortedError=ur;exports.isLedgerSignPsbtIncompleteError=cr;exports.isLedgerSignPsbtProtocolError=Ce;exports.isLedgerUserRefusedError=sr;exports.isLedgerYieldMismatchError=xe;exports.isSessionAlive=yr;exports.prepareSignPsbt=an;exports.psbtPaysChangeScript=po;exports.signPreparedVaultPsbt=cn;exports.signVaultPsbt=hs;
|
|
1
|
+
"use strict";var gn=Object.create;var pt=Object.defineProperty;var En=Object.getOwnPropertyDescriptor;var wn=Object.getOwnPropertyNames;var _n=Object.getPrototypeOf,mn=Object.prototype.hasOwnProperty;var Tn=(e,t,n)=>t in e?pt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var In=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of wn(t))!mn.call(e,o)&&o!==n&&pt(e,o,{get:()=>t[o],enumerable:!(r=En(t,o))||r.enumerable});return e};var Q=(e,t,n)=>(n=e!=null?gn(_n(e)):{},In(t||!e||!e.__esModule?pt(n,"default",{value:e,enumerable:!0}):n,e));var p=(e,t,n)=>Tn(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ut=require("@scure/bip32"),_=require("bitcoinjs-lib"),c=require("buffer"),Sn=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 Tt=Pn(Sn),yn=1,bn=1,Rn=1,xn=2,An=33,On=256,Bn=257,vn=258,Cn=39,Ln=259,Nn=105,Mn=260,Dn=261,kn=262,$n=271,Un=265,Hn=266,Vn=267,Gn=268,Kn=269,Fn=270,Yn=263,Xn=264,ot=32,qn=32,X=255,Wn=3+ot,Kt=Math.floor(X/Wn);function A(e,t){if(t.length>X)throw new Error(`TLV value for tag 0x${e.toString(16)} exceeds 255 bytes`);const n=new Uint8Array(3+t.length);return n[0]=e>>8&255,n[1]=e&255,n[2]=t.length,n.set(t,3),n}function lt(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 N(e,t,n){return A(e,lt(BigInt(t),1,n))}function Z(e,t,n){return A(e,lt(BigInt(t),4,n))}function M(e,t,n){return A(e,lt(t,8,n))}function st(e){const t=e.reduce((o,s)=>o+s.length,0),n=new Uint8Array(t);let r=0;for(const o of e)n.set(o,r),r+=o.length;return n}function Ot(e,t,n){if(e.length!==t)throw new Error(`${n} must be ${t} bytes, got ${e.length}`);return e}const Ft=5;function Pe(e){if(e.depositorPath.length!==Ft)throw new Error(`depositorPath must have exactly ${Ft} levels, got ${e.depositorPath.length}`);const t=st(e.depositorPath.map(n=>lt(BigInt(n>>>0),4,"path level")));return st([N(Rn,yn,"structureType"),N(xn,bn,"version"),Z(An,e.coinType,"coinType"),M(On,e.baseFeeRate,"baseFeeRate"),Z(Bn,e.peginCsvTimelock,"peginCsvTimelock"),Z(vn,e.payoutTimelock,"payoutTimelock"),A(Cn,Ot(e.prepeginTxidInternal,qn,"prepeginTxid")),Z(Ln,e.htlcRefundTimelock,"htlcRefundTimelock"),A(Nn,t),N(Mn,e.keeperCount,"keeperCount"),N(Dn,e.challengerCount,"challengerCount"),N(kn,e.vaultCount,"vaultCount"),M($n,e.prepeginMaxFee,"prepeginMaxFee")])}function ye(e){return st([N(Un,e.htlcVout,"htlcVout"),A(Hn,Ot(e.vaultProviderPubkey,ot,"vaultProviderPubkey")),M(Vn,e.vaultAmount,"vaultAmount"),M(Gn,e.commissionFee,"commissionFee"),M(Kn,e.depositorClaimValue,"depositorClaimValue"),M(Fn,e.peginMaxFee,"peginMaxFee")])}function be(e,t){const n=(s,i)=>s.map((a,u)=>Ot(a,ot,`${i}[${u}]`)).sort((a,u)=>{for(let l=0;l<ot;l++)if(a[l]!==u[l])return a[l]-u[l];return 0}),r=[...n(e,"keeper").map(s=>A(Yn,s)),...n(t,"challenger").map(s=>A(Xn,s))],o=[];for(let s=0;s<r.length;s+=Kt)o.push(st(r.slice(s,s+Kt)));return o}const x=225,dt=128,Yt=129,zn=0,jn=1,Qn=0,Zn=1,Jn=2,q=0,Xt=64,qt=1024,Wt=10,zt=32;function tr(e){return new Uint8Array([e>>8&255,e&255])}function er(e){const t=e>>>0;return new Uint8Array([t>>>24&255,t>>>16&255,t>>>8&255,t&255])}function gt(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 jt=/^[a-z0-9-]+$/;async function nr(e,{appName:t,derivationPath:n,context:r}){const o=new TextEncoder().encode(t);if(o.length<1||o.length>Xt)throw new Error(`appName must be 1..${Xt} bytes, got ${o.length}`);if(!jt.test(t))throw new Error(`appName must match ${jt} — the device rejects other characters`);if(n.length<1||n.length>Wt)throw new Error(`derivationPath must have 1..${Wt} levels`);if(r.length<1||r.length>qt)throw new Error(`context must be 1..${qt} bytes, got ${r.length}`);const s=gt([new Uint8Array([o.length]),o,new Uint8Array([n.length]),gt(n.map(er)),tr(r.length)]),i=Math.min(r.length,X-s.length);if(i<0)throw new Error("appName and derivationPath leave no room for context in the first APDU");let a=await e({cla:x,ins:Yt,p1:zn,p2:q,data:gt([s,r.subarray(0,i)])});for(let u=i;u<r.length;u+=X)a=await e({cla:x,ins:Yt,p1:jn,p2:q,data:r.subarray(u,u+X)});if(a.length!==zt)throw new Error(`Expected a ${zt}-byte context root, got ${a.length} bytes`);return a}async function rr(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:dt,p1:Qn,p2:q,data:Pe(t)});for(const s of n)await e({cla:x,ins:dt,p1:Zn,p2:q,data:ye(s)});for(const s of be(r,o))await e({cla:x,ins:dt,p1:Jn,p2:q,data:s})}const or=0,Re=0,xe=1,sr=0,Qt=33,Zt=10,ir=5,ar=4;async function cr(e){const t=await e({cla:x,ins:ir,p1:Re,p2:xe,data:new Uint8Array(0)});if(t.length!==ar)throw new Error(`Ledger returned a ${t.length}-byte response instead of the 4-byte master fingerprint`);return Oe(t)}async function Ae(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:or,p1:Re,p2:xe,data:lr(t)}),o=new TextDecoder().decode(r);if(o.length===0)throw new Error("Ledger returned an empty extended key");return ut.HDKey.fromExtendedKey(o,n),o}async function ur(e,t,n){const r=await Ae(e,t,n),o=ut.HDKey.fromExtendedKey(r,n);if(!o.publicKey||o.publicKey.length!==Qt)throw new Error(`Ledger returned an extended key without a ${Qt}-byte public key`);return Oe(o.publicKey.subarray(1))}function Oe(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function lr(e){const t=new Uint8Array(2+e.length*4);return t[0]=sr,t[1]=e.length,e.forEach((n,r)=>{const o=2+r*4;t[o]=n>>>24&255,t[o+1]=n>>>16&255,t[o+2]=n>>>8&255,t[o+3]=n&255}),t}const Bt="LedgerUserRefusedError",vt="LedgerDeviceLockedError",Ct="LedgerDeviceError",Lt="LedgerYieldMismatchError",Nt="LedgerSignPsbtIncompleteError",Mt="LedgerSignPsbtProtocolError",Dt="LedgerSignPsbtAbortedError";function Be(e){return e.toString(16).padStart(4,"0")}class ve extends Error{constructor(n){super(`User rejected the request on the Ledger device (0x${Be(n)})`);p(this,"statusWord");this.name=Bt,this.statusWord=n}}class Ce extends Error{constructor(n,r){super(`The Ledger device is locked — unlock it and retry (0x${Be(n)})`);p(this,"statusWord");p(this,"preDispatch");this.name=vt,this.statusWord=n,this.preDispatch=(r==null?void 0:r.preDispatch)??!1}}class Le extends Error{constructor(n,r){super(r);p(this,"statusWord");this.name=Ct,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=Lt,this.kind=n,this.inputIndex=r}}class Ne 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=Nt,this.missing=n}}function rt(e){return e.map(({inputIndex:t,leafHashHex:n})=>n===void 0?{inputIndex:t}:{inputIndex:t,leafHashHex:n})}class d extends Error{constructor(n,r=[]){super(`SIGN_PSBT protocol failure: ${n}`);p(this,"detail");p(this,"collectedYields");this.name=Mt,this.detail=n,this.collectedYields=r}}class It extends Error{constructor(n){super("SIGN_PSBT was abandoned host-side before completion");p(this,"yieldedCount");this.name=Dt,this.yieldedCount=n}}function fr(e){return e instanceof Error&&e.name===Bt}function hr(e){return e instanceof Error&&e.name===Ct}function pr(e){return e instanceof Error&&e.name===vt}function Me(e){return e instanceof Error&&e.name===Lt}function dr(e){return e instanceof Error&&e.name===Nt}function De(e){return e instanceof Error&&e.name===Mt}function gr(e){return e instanceof Error&&e.name===Dt}const Er=36864,wr=new Set([21761,27013]),_r=new Set([21781,27010,21251]),kt=28160,ke=45063,$e=45066,mr={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",[kt]:"The running app does not handle vault instructions — open the Babylon Vault app for this network",45056:"The device reported a wrong response length",[ke]:"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",[$e]:"The device has already signed the maximum number of these transactions",28416:"The device reported an internal error"};function D(e){return e.toString(16).padStart(2,"0")}function Ue(e){return e.toString(16).padStart(4,"0")}function He(e,t){if(e===Er)return;if(wr.has(e))return new ve(e);if(_r.has(e))return new Ce(e,{preDispatch:t.preDispatch===!0});const n=mr[e],r=e===kt&&t.appName?` (app at connect time: "${t.appName}"${t.appVersion?` v${t.appVersion}`:""})`:"";return new Le(e,`${n??"The device rejected the request"} (ins 0x${D(t.ins)} p1 0x${D(t.p1)}, sw 0x${Ue(e)})${r}`)}function Tr(e,t){return async n=>{const{sw:r,data:o}=await e(n),s=He(r,{...t,ins:n.ins,p1:n.p1});if(s)throw s;return o}}const Jt=2;function Ir(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 Sr(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 te(){return globalThis.__LEDGER_VAULT_APDU_TRACE__===!0}function Ve(e){return async t=>{const n=`${D(t.cla)} ${D(t.ins)} ${D(t.p1)} ${D(t.p2)} Lc=${t.data.length}`;let r;try{r=await e.dmk.sendApdu({sessionId:e.sessionId,apdu:Sr(t)})}catch(s){throw te()&&console.debug(`[ledger-vault] APDU ${n} -> transport error`,s),s}const o=Ir(r);return te()&&console.debug(`[ledger-vault] APDU ${n} -> sw=0x${Ue(o)} len=${r.data.length}`),{sw:o,data:r.data}}}function Pr(e){return Tr(Ve(e),{appName:e.appName,appVersion:e.appVersion})}const yr={isRefresherDisabled:!0};let Y,B;function Ge(e){let t;return()=>(t||(t=e().catch(n=>{throw t=void 0,n})),t)}const Ke=Ge(()=>import("@ledgerhq/device-management-kit")),br=Ge(()=>import("@ledgerhq/device-transport-kit-web-hid"));function Rr(){if(!B){let e=function(n){if(B!==t)throw new Error("connectDmkSession: closeDmk() tore down this DMK while it was still building — retry to connect over a fresh one");return Y=n.dmk,n};const t=(async()=>{const[{DeviceManagementKitBuilder:n},{webHidTransportFactory:r,webHidIdentifier:o}]=await Promise.all([Ke(),br()]),s=new n().addTransport(r).build();return e({dmk:s,transportIdentifier:o})})().catch(n=>{throw B===t&&(B=void 0),n});B=t}return B}async function xr(){const{dmk:e,transportIdentifier:t}=await Rr(),{firstValueFrom:n}=await import("rxjs"),r=await n(e.startDiscovering({transport:t})),o=await e.connect({device:r,sessionRefresherOptions:yr}),s=await Ar(e,o);return{dmk:e,sessionId:o,...s}}async function Ar(e,t){try{const{GetAppAndVersionCommand:n,isSuccessCommandResult:r}=await Ke(),o=await e.sendCommand({sessionId:t,command:new n});return r(o)?{appName:o.data.name,appVersion:o.data.version}:{}}catch{return{}}}async function Or(e){const{firstValueFrom:t}=await import("rxjs");try{return await t(e.dmk.getDeviceSessionState({sessionId:e.sessionId})),!0}catch(n){if((n==null?void 0:n._tag)==="DeviceSessionNotFound")return!1;throw n}}async function Br(e){try{await e.dmk.disconnect({sessionId:e.sessionId})}catch{}}function vr(){Y==null||Y.close(),Y=void 0,B=void 0}const Cr=2,Lr=3,ee=32,Nr=10,ne=0xffffffffn,it=72,Mr=1008,Dr=4320,kr=91,$r=4031,Fe=546n,re=Fe,Ur=2n,Ye="DepositTermsRejectedError";class T extends Error{constructor(n,r="device-envelope"){super(n);p(this,"reason");this.name=Ye,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 Hr(e){if(O("vaultCoreVersion",e.vaultCoreVersion,Cr,Lr),e.protocolFeeRate<1n||e.protocolFeeRate>ne)throw new T(`${P}: protocolFeeRate ${e.protocolFeeRate} not in [1, ${ne}]`);if(O("timelockPegin",e.timelockPegin,it,Mr),O("timelockAssert",e.timelockAssert,kr,$r),O("timelockRefund",e.timelockRefund,it,Dr),O("keeper count",e.vaultKeeperBtcPubkeys.length,1,ee),O("challenger count",e.universalChallengerBtcPubkeys.length,1,ee),O("vault count",e.vaults.length,1,Nr),F("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,u]of[["vaultKeeperBtcPubkeys",e.vaultKeeperBtcPubkeys],["universalChallengerBtcPubkeys",e.universalChallengerBtcPubkeys]])for(const l of u){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=Fe,i=Ur*s;for(const a of e.vaults){if(F(`vault ${a.htlcVout} peginAmount`,a.peginAmount),F(`vault ${a.htlcVout} commissionFee`,a.commissionFee),F(`vault ${a.htlcVout} depositorClaimValue`,a.depositorClaimValue),F(`vault ${a.htlcVout} peginMaxFee`,a.peginMaxFee),a.commissionFee<s)throw new T(`${P}: vault ${a.htlcVout} commissionFee ${a.commissionFee} below the ${s}-sat dust limit`);if(a.depositorClaimValue<re)throw new T(`${P}: vault ${a.htlcVout} depositorClaimValue ${a.depositorClaimValue} below the ${re}-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 Vr=(1n<<64n)-1n;function F(e,t){if(t<0n||t>Vr)throw new T(`${P}: ${e} ${t} does not fit in an unsigned 64-bit field`)}const b=2147483648,Gr=4294967295,at=86,Xe=0,qe=1,oe=5,$t=3,Kr=3,Fr=4;function Ut(e,t){if(t.length!==oe)throw new Error(`${e} must have exactly ${oe} levels, got ${t.length}`);for(const r of t)if(!Number.isInteger(r)||r<0||r>Gr)throw new Error(`${e} levels must be integers in 0..0xffffffff`);if(!t.slice(0,$t).every(r=>(r&b)!==0)||(t[Fr]&b)!==0)throw new Error(`${e} must harden purpose'/coin'/account' and leave the address index unhardened`);if(t[0]!==(b|at)>>>0)throw new Error(`${e} must use BIP-86 purpose ${at}'`)}function $(e){return"m/"+e.map(t=>(t&b)!==0?`${(t&~b)>>>0}'`:`${t>>>0}`).join("/")}const se=253,Yr=254,Xr=65535,qr=4294967295;function Wr(e){if(e<se)return c.Buffer.from([e]);if(e<=Xr){const t=c.Buffer.alloc(2);return t.writeUInt16LE(e),c.Buffer.concat([c.Buffer.from([se]),t])}if(e<=qr){const t=c.Buffer.alloc(4);return t.writeUInt32LE(e),c.Buffer.concat([c.Buffer.from([Yr]),t])}throw new Error(`Script too large to encode as CompactSize: ${e} bytes`)}const zr="TapLeaf";function jr(e,t){const n=c.Buffer.concat([c.Buffer.from([e]),Wr(t.length),c.Buffer.from(t)]);return _.crypto.taggedHash(zr,n)}function Qr(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 Zr(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 Jr(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 to=BigInt(253),eo=BigInt(65535)+BigInt(1),no=BigInt(4294967295)+BigInt(1);function We(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=to):n===254?(r=4,o=eo):(r=8,o=no);const s=Zr(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 U(e){typeof e=="number"&&(e=R(e));const t=Jr(e);e=BigInt(e);const n=c.Buffer.alloc(t);return t==1?n[0]=Number(e):(t==3?n[0]=253:t===5?n[0]=254:n[0]=255,Qr(e,t-1,n,1)),n}const ro=31;function ze(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Can't convert a number that is not a non-negative safe integer to 64-bit LE");const t=c.Buffer.alloc(8,0);for(let n=0;n<t.length;n++){const r=e&255;t[n]=r,e=(e-r)/256}return t}function St(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>ro)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 v{constructor(){p(this,"bufs",[])}write(t,n){const r=c.Buffer.alloc(t);n(r),this.bufs.push(r)}writeUInt8(t){this.write(1,n=>n.writeUInt8(t,0))}writeInt32(t){this.write(4,n=>n.writeInt32LE(t,0))}writeUInt32(t){this.write(4,n=>n.writeUInt32LE(t,0))}writeUInt64(t){const n=ze(t);this.writeSlice(n)}writeVarInt(t){this.bufs.push(U(t))}writeSlice(t){this.bufs.push(c.Buffer.from(t))}writeVarSlice(t){this.writeVarInt(t.length),this.writeSlice(t)}buffer(){return c.Buffer.concat(this.bufs)}}class k{constructor(t,n=0){this.buffer=t,this.offset=n}available(){return this.buffer.length-this.offset}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=this.readSlice(8);return St(t)}readVarInt(){const[t,n]=We(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 Pt=(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))(Pt||{});const ie=c.Buffer.from([112,115,98,116,255]),oo=4294967295;class je extends Error{}class Qe{constructor(){p(this,"globalMap",new Map);p(this,"inputMaps",[]);p(this,"outputMaps",[])}setGlobalTxVersion(t){this.setGlobal(2,L(t))}getGlobalTxVersion(){return this.getGlobal(2).readUInt32LE(0)}setGlobalFallbackLocktime(t){this.setGlobal(3,L(t))}getGlobalFallbackLocktime(){var t;return(t=this.getGlobalOptional(3))==null?void 0:t.readUInt32LE(0)}setGlobalInputCount(t){this.setGlobal(4,ue(t))}getGlobalInputCount(){return le(this.getGlobal(4))}setGlobalOutputCount(t){this.setGlobal(5,ue(t))}getGlobalOutputCount(){return le(this.getGlobal(5))}setGlobalTxModifiable(t){this.setGlobal(6,t)}getGlobalTxModifiable(){return this.getGlobalOptional(6)}setGlobalPsbtVersion(t){this.setGlobal(251,L(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 v;o.writeSlice(ce(n)),o.writeVarSlice(r),this.setInput(t,1,w(),o.buffer())}getInputWitnessUtxo(t){const n=this.getInputOptional(t,1,w());if(!n)return;const r=new k(n);return{amount:St(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(),L(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(),L(n))}getInputOutputIndex(t){return this.getInput(t,15,w()).readUInt32LE(0)}setInputSequence(t,n){this.setInput(t,16,w(),L(n))}getInputSequence(t){var n;return((n=this.getInputOptional(t,16,w()))==null?void 0:n.readUInt32LE(0))??oo}setInputTapKeySig(t,n){this.setInput(t,19,w(),n)}getInputTapKeySig(t){return this.getInputOptional(t,19,w())}setInputTapBip32Derivation(t,n,r,o,s){if(n.length!==32)throw new Error("Invalid pubkey length: "+n.length);const i=this.encodeTapBip32Derivation(r,o,s);this.setInput(t,22,n,i)}getInputTapBip32Derivation(t,n){const r=this.getInput(t,22,n);return this.decodeTapBip32Derivation(r)}getInputKeyDatas(t,n){return this.getKeyDatas(this.inputMaps[t],n)}getInputEntriesOfType(t,n){const r=this.inputMaps[t];if(!r)throw new Error("No such map");const o=[];return r.forEach((s,i)=>{this.isKeyType(i,[n])&&o.push({keyData:c.Buffer.from(i.substring(2),"hex"),value:c.Buffer.from(s)})}),o}setOutputRedeemScript(t,n){this.setOutput(t,0,w(),n)}getOutputRedeemScript(t){return this.getOutput(t,0,w())}setOutputBip32Derivation(t,n,r,o){this.setOutput(t,2,n,this.encodeBip32Derivation(r,o))}getOutputBip32Derivation(t,n){const r=this.getOutput(t,2,n);return this.decodeBip32Derivation(r)}setOutputAmount(t,n){this.setOutput(t,3,w(),ce(n))}getOutputAmount(t){const n=this.getOutput(t,3,w());return St(n)}setOutputScript(t,n){this.setOutput(t,4,w(),n)}getOutputScript(t){return this.getOutput(t,4,w())}setOutputTapBip32Derivation(t,n,r,o,s){const i=this.encodeTapBip32Derivation(r,o,s);this.setOutput(t,7,n,i)}getOutputTapBip32Derivation(t,n){const r=this.getOutput(t,7,n);return this.decodeTapBip32Derivation(r)}deleteInputEntries(t,n){const r=this.inputMaps[t];if(!r)throw new Error("No such map");r.forEach((o,s,i)=>{this.isKeyType(s,n)&&i.delete(s)})}copy(t){this.copyMap(this.globalMap,t.globalMap),this.copyMaps(this.inputMaps,t.inputMaps),this.copyMaps(this.outputMaps,t.outputMaps)}copyMaps(t,n){t.forEach((r,o)=>{const s=new Map;this.copyMap(r,s),n[o]=s})}copyMap(t,n){t.forEach((r,o)=>n.set(o,c.Buffer.from(r)))}serialize(){const t=new v;return t.writeSlice(ie),wt(t,this.globalMap),this.inputMaps.forEach(n=>{wt(t,n)}),this.outputMaps.forEach(n=>{wt(t,n)}),t.buffer()}deserialize(t){const n=new k(t);if(!n.readSlice(5).equals(ie))throw new Error("Invalid magic bytes");for(;this.readKeyPair(this.globalMap,n););let r;try{r=this.getGlobalPsbtVersion()}catch(i){if(!(i instanceof je))throw i;r=0}if(r!==0&&r!==2)throw new Error("Only PSBTs of version 0 or 2 are supported");let o,s;if(r===0){const i=this.getGlobal(0),a=_.Transaction.fromBuffer(i);o=a.ins.length,s=a.outs.length}else o=this.getGlobalInputCount(),s=this.getGlobalOutputCount();for(let i=0;i<o;i++){const a=new Map;for(this.inputMaps[i]=a;this.readKeyPair(a,n););}for(let i=0;i<s;i++){const a=new Map;for(this.outputMaps[i]=a;this.readKeyPair(a,n););}if(n.available()!==0)throw new Error("Trailing bytes after PSBT output maps");this.normalizeToV2()}normalizeToV2(){var o;const t=(o=this.getGlobalOptional(251))==null?void 0:o.readUInt32LE(0);if(t===2)return;if(t!==void 0)throw new Error("Invalid or unsupported value for PSBT_GLOBAL_VERSION");const n=this.getGlobal(0),r=_.Transaction.fromBuffer(n);this.setGlobalPsbtVersion(2),this.setGlobalTxVersion(r.version),this.setGlobalFallbackLocktime(r.locktime),this.setGlobalInputCount(r.ins.length),this.setGlobalOutputCount(r.outs.length),r.ins.forEach((s,i)=>{this.setInputPreviousTxId(i,s.hash),this.setInputOutputIndex(i,s.index),this.setInputSequence(i,s.sequence)}),r.outs.forEach((s,i)=>{this.setOutputAmount(i,s.value),this.setOutputScript(i,s.script)}),this.globalMap.delete("0".padStart(2,"0"))}readKeyPair(t,n){const r=R(n.readVarInt());if(r===0)return!1;const o=n.readUInt8(),s=n.readSlice(r-1),i=n.readVarSlice(),a=new H(o,s).toString();if(t.has(a))throw new Error("Repeated keypair in PSBT map");return t.set(a,i),!0}getKeyDatas(t,n){if(!t)throw new Error("No such map");const r=[];return t.forEach((o,s)=>{this.isKeyType(s,[n])&&r.push(c.Buffer.from(s.substring(2),"hex"))}),r}isKeyType(t,n){const r=c.Buffer.from(t.substring(0,2),"hex").readUInt8(0);return n.some(o=>o===r)}setGlobal(t,n){const r=new H(t,c.Buffer.from([]));this.globalMap.set(r.toString(),n)}getGlobal(t){return Et(this.globalMap,t,w())}getGlobalOptional(t){return yt(this.globalMap,t,w())}setInput(t,n,r,o){ae(this.getMap(t,this.inputMaps),n,r,o)}getInput(t,n,r){return Et(this.inputMaps[t],n,r)}getInputOptional(t,n,r){return yt(this.inputMaps[t],n,r)}setOutput(t,n,r,o){ae(this.getMap(t,this.outputMaps),n,r,o)}getOutput(t,n,r){return Et(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 v;return this.writeBip32Derivation(r,t,n),r.buffer()}decodeBip32Derivation(t){const n=new k(t);return this.readBip32Derivation(n)}writeBip32Derivation(t,n,r){t.writeSlice(n),r.forEach(o=>{t.writeUInt32(o)})}readBip32Derivation(t){const n=t.readSlice(4),r=[];for(;t.offset<t.buffer.length;)r.push(t.readUInt32());return{masterFingerprint:n,path:r}}encodeTapBip32Derivation(t,n,r){const o=new v;return o.writeVarInt(t.length),t.forEach(s=>{o.writeSlice(s)}),this.writeBip32Derivation(o,n,r),o.buffer()}decodeTapBip32Derivation(t){const n=new k(t),r=R(n.readVarInt()),o=[];for(let i=0;i<r;i++)o.push(n.readSlice(32));const s=this.readBip32Derivation(n);return{hashes:o,...s}}}function Et(e,t,n){const r=yt(e,t,n);if(r===void 0)throw new je(new H(t,n).toString());return r}function yt(e,t,n){if(!e)throw new Error("No such map");const r=new H(t,n),o=e.get(r.toString());if(o!==void 0)return c.Buffer.from(o)}class H{constructor(t,n){p(this,"keyType");p(this,"keyData");this.keyType=t,this.keyData=n}toString(){const t=new v;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 so{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 io(e){return new H(e.readUInt8(0),e.subarray(1))}function wt(e,t){const n=[...t].sort(([r],[o])=>r<o?-1:r>o?1:0);for(const[r,o]of n)new so(io(c.Buffer.from(r,"hex")),o).serialize(e);e.writeUInt8(0)}function w(){return c.Buffer.from([])}function ae(e,t,n,r){const o=new H(t,n);e.set(o.toString(),r)}function L(e){const t=c.Buffer.alloc(4);return t.writeUInt32LE(e,0),t}function ce(e){return ze(e)}function ue(e){const t=new v;return t.writeVarInt(e),t.buffer()}function le(e){return R(new k(e).readVarInt())}const fe=192,bt=32,he=2,tt=33,et=32,ao=1,co="TapBranch",uo="TapTweak",pe=64,de=32,_t=64,lo=34,ct=c.Buffer.from([81,32]),fo=c.Buffer.from([0,20]),ho=2,po=3;function ft(e){_.initEccLib(Tt);const t=_.payments.p2tr({internalPubkey:c.Buffer.from(e,"hex")}).output;if(!t)throw new d("p2tr produced no output script for the depositor key");return t}function ge(e,t){const n=c.Buffer.concat([c.Buffer.from([t]),c.Buffer.from(e,"hex")]);return c.Buffer.concat([fo,_.crypto.hash160(n)])}function Ze(e){return e.length===lo&&e.subarray(0,ct.length).equals(ct)}function go(e,t,n,r){if(!Ze(r))throw new d(`input ${e} is tapscript but its witnessUtxo script is not P2TR`);const o=t.length-tt;if(o<0||o%et!==0)throw new d(`input ${e} control block length ${t.length} is not ${tt} plus a multiple of ${et}`);const s=t.subarray(1,tt);if(!Tt.isXOnlyPoint(s))throw new d(`input ${e} control block internal key is not an x-only point`);let i=n;for(let h=tt;h<t.length;h+=et){const g=t.subarray(h,h+et),f=c.Buffer.compare(i,g)<0?[i,g]:[g,i];i=_.crypto.taggedHash(co,c.Buffer.concat(f))}const a=_.crypto.taggedHash(uo,c.Buffer.concat([s,i])),u=Tt.xOnlyPointAddTweak(s,a);if(!u)throw new d(`input ${e} control block internal key has no taproot output key`);if(!r.subarray(ct.length).equals(c.Buffer.from(u.xOnlyPubkey)))throw new d(`input ${e} control block does not commit to its TAP_LEAF_SCRIPT (recomputed taproot output key differs from the witnessUtxo witness program)`);if(u.parity!==(t[0]&ao))throw new d(`input ${e} control block parity bit disagrees with the recomputed taproot output key`)}function Eo(e){const{psbt:t,depositorXOnlyHex:n,signInputIndexes:r}=e,o=new Map,s=new Map,i=t.getGlobalInputCount(),a=r===void 0?void 0:new Set(r),u=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=ft(n),h=[ge(n,ho),ge(n,po)];for(let f=0;f<i;f++){const E=t.getInputEntriesOfType(f,Pt.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<he)throw new d(`input ${f} TAP_LEAF_SCRIPT value length ${m.length} is below the ${he}-byte minimum (script byte plus the leaf-version byte)`);const K=m[m.length-1];if(K!==fe)throw new d(`input ${f} leaf version 0x${K.toString(16)} is not tapscript (0xc0)`);const C=t.getInputWitnessUtxo(f);if(!C)throw new d(`input ${f} is tapscript but has no witnessUtxo`);const j=m.subarray(0,m.length-1),Vt=jr(fe,j);go(f,E[0].keyData,Vt,C.scriptPubKey);const Gt={kind:"tapscript",expectedLeafHashHexes:new Set([Vt.toString("hex")]),expectedSignerXOnlyHex:n};s.set(f,Gt),u(f)&&o.set(f,Gt);continue}const y=t.getInputEntriesOfType(f,Pt.TAP_INTERNAL_KEY);if(y.length>0){const m=y[0];if(y.length>1||m.keyData.length!==0||m.value.length!==bt)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 K=t.getInputWitnessUtxo(f);if(!K)throw new d(`input ${f} is keypath but has no witnessUtxo`);const C=K.scriptPubKey;if(!Ze(C))throw new d(`input ${f} witnessUtxo script is not P2TR`);if(!C.equals(l))throw new d(`input ${f} witnessUtxo is not the BIP-86 P2TR of the depositor key`);const j={kind:"taproot-keypath",expectedOutputKeyHex:C.subarray(ct.length).toString("hex")};s.set(f,j),o.set(f,j);continue}const ht=t.getInputWitnessUtxo(f);if(ht&&(ht.scriptPubKey.equals(l)||h.some(m=>ht.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 nt(e){return e.kind==="tapscript"?`${e.inputIndex}:${e.leafHashHex}`:`${e.inputIndex}`}function Ee(e,t){if(e<_t)throw new d(`YIELD payload truncated inside the signature (${e} of ${_t} bytes on input ${t})`);if(e!==_t)throw new S("non-default-sighash",t)}function wo(e){const t=[],n=new Set;return{assertAndRecord:s=>{let i,a;try{const[h,g]=We(s,0);i=R(h),a=g}catch(h){throw new d(`unparseable YIELD payload: ${h instanceof Error?h.message:String(h)}`)}const u=s[a];if(u===void 0)throw new d("YIELD payload truncated before the augmented-pubkey length");const l=e.byInput.get(i);if(l===void 0)throw new S("unexpected-input",i);if(u===pe){if(l.kind!=="tapscript")throw new S("wrong-spend-type",i);const h=a+1+pe;if(s.length<h)throw new d("YIELD payload truncated inside the augmented pubkey");const g=s.subarray(a+1,a+1+bt).toString("hex"),f=s.subarray(a+1+bt,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);Ee(E.length,i);const y={kind:"tapscript",inputIndex:i,signerXOnlyHex:g,leafHashHex:f,signature:Uint8Array.from(E)};if(n.has(nt(y)))throw new S("duplicate-yield",i);n.add(nt(y)),t.push(y);return}if(u===de){if(l.kind!=="taproot-keypath")throw new S("wrong-spend-type",i);const h=a+1+de;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);Ee(f.length,i);const E={kind:"taproot-keypath",inputIndex:i,outputKeyHex:g,signature:Uint8Array.from(f)};if(n.has(nt(E)))throw new S("duplicate-yield",i);n.add(nt(E)),t.push(E);return}throw new S("unexpected-encoding",i)},get yields(){return t},get lastYield(){return t[t.length-1]},assertComplete:()=>{const s=new Set;for(const[u,l]of e.byInput)if(l.kind==="tapscript")for(const h of l.expectedLeafHashHexes)s.add(`${u}:${h}`);else s.add(`${u}`);const i=[...s].filter(u=>!n.has(u)),a=[...n].some(u=>!s.has(u));if(i.length>0||a||n.size!==e.expectedYieldCount)throw new Ne(i)}}}const Je=/^[0-9a-f]{64}$/;function _o(e,t){if(Ut("depositorPath",e),e[Kr]!==Xe)throw new Error("depositorPath must use BIP-86 receive branch 0");for(let n=0;n<$t;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 tn(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=ut.HDKey.fromExtendedKey(e,t).deriveChild(n).deriveChild(r);if(!o.publicKey)throw new Error(`account xpub derived no public key at ${n}/${r}`);return c.Buffer.from(o.publicKey.subarray(1)).toString("hex")}function en(e,t,n){return tn(e,t,qe,n)}function mo(e,t,n){return tn(e,t,Xe,n)}function nn(e,t){const n=ft(t);return e.txOutputs.flatMap((r,o)=>c.Buffer.from(r.script).equals(n)?[o]:[])}function To(e,t){if(!Je.test(t))throw new Error("changeXOnlyHex must be 64 lowercase hex characters");return nn(_.Psbt.fromHex(e),t).length>0}function Io(e){const{psbtHex:t,depositorXOnlyHex:n,walletPolicy:r,depositorPath:o,change:s}=e;if(!Je.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");_o(o,r.keyOriginPath);const i=_.Psbt.fromHex(t),a=c.Buffer.from(r.masterFingerprintHex,"hex"),u=c.Buffer.from(n,"hex");let l=0;if(i.data.inputs.forEach((h,g)=>{h.tapInternalKey&&c.Buffer.from(h.tapInternalKey).equals(u)&&(l++,i.updateInput(g,{tapBip32Derivation:[{masterFingerprint:a,pubkey:u,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=en(r.accountXpub,r.bip32Versions,s.addressIndex),g=[...o.slice(0,$t),qe,s.addressIndex],f=c.Buffer.from(h,"hex"),E=nn(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 So="BIP0322-signed-message",Po=new Uint8Array([252,6,98,118,97,117,108,116,0]),rn=0,on=0,sn=0,yo=0,Rt=0,bo=c.Buffer.from([106]),Ro=/^[0-9a-f]{64}$/,xo=/^[0-9a-f]{8}$/,Ao=c.Buffer.alloc(32,0),Oo=4294967295,Bo=c.Buffer.from([0,32]),vo=c.Buffer.from([81,32]),Co=2;function Lo(e,t){const n=_.crypto.sha256(c.Buffer.from(e,"utf8"));return _.crypto.sha256(c.Buffer.concat([n,n,c.Buffer.from(t)]))}function No(e,t){const n=new _.Transaction;n.version=rn,n.locktime=on;const r=c.Buffer.concat([Bo,Lo(So,e)]);return n.addInput(Ao,Oo,sn,r),n.addOutput(c.Buffer.concat([vo,c.Buffer.from(t)]),Rt),Uint8Array.from(n.getHash(!1))}function Mo(e){const{message:t,depositorXOnlyHex:n,masterFingerprintHex:r,depositorPath:o}=e;if(!Ro.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");if(!xo.test(r))throw new Error("masterFingerprintHex must be 8 lowercase hex characters");Ut("depositorPath",o);const s=new TextEncoder().encode(t),i=c.Buffer.from(n,"hex"),a=ft(n),u=No(s,a.subarray(Co)),l=new _.Psbt;return l.setVersion(rn),l.setLocktime(on),l.addInput({hash:c.Buffer.from(u),index:yo,sequence:sn,witnessUtxo:{script:a,value:Rt},tapInternalKey:i,tapBip32Derivation:[{masterFingerprint:c.Buffer.from(r,"hex"),pubkey:i,path:$(o),leafHashes:[]}]}),l.addOutput({script:bo,value:Rt}),l.addUnknownKeyValToGlobal({key:c.Buffer.from(Po),value:c.Buffer.from(s)}),l.toHex()}const Do=/^[0-9a-f]{64}$/,ko=/^[0-9a-f]{8}$/,$o=192,xt=32,Uo=0,Ho=1,Vo=32,Go=75,Ko=76,Fo=79,Yo=80,Xo=81,qo=96,Wo=173,zo=178,we=4,_e=128,jo=1+xt+1+1+1,Qo=2,Zo=34,Jo=2147483648,ts=4194304,me=65535,es=2,ns=0;function rs(e){if(e.length<jo)return;let t=0;if(e[t++]!==Vo)return;const n=c.Buffer.from(e.subarray(t,t+xt)).toString("hex");if(t+=xt,e[t++]!==Wo||t>=e.length)return;const r=e[t++];let o=0;if(!(r===Uo||r===Fo)){if(r>=Ho&&r<=Go){const s=r;if(s>we||t+s>e.length||(e[t+s-1]&_e)!==0)return;for(let i=0;i<s;i++)o|=e[t+i]<<8*i;t+=s}else if(r===Ko){if(t>=e.length)return;const s=e[t++];if(s>we||t+s>e.length||(e[t+s-1]&_e)!==0)return;for(let i=0;i<s;i++)o|=e[t+i]<<8*i;t+=s}else if(r>=Xo&&r<=qo)o=r-Yo;else return;if(o!==0&&!(t>=e.length)&&e[t++]===zo&&t===e.length)return{leafKeyHex:n,csv:o}}}function an(e){let t;try{t=_.Psbt.fromHex(e)}catch{return}if(t.version<es||t.locktime!==ns||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!==$o)return;const o=rs(r[0].script);if(o!==void 0)return{...o,inputTxidInternalHex:c.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:c.Buffer.from(t.txOutputs[0].script).toString("hex"),outputValue:t.txOutputs[0].value}}function cn(e){if(e.witnessUtxo===void 0||e.witnessUtxo.scriptLength!==Zo)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!==ft(e.leafKeyHex).toString("hex"))throw new Error("refund output does not pay the refund leaf key's own BIP-86 address");if(e.csv<it)throw new Error(`refund leaf CSV ${e.csv} is below the device's timelock floor of ${it} blocks`);if((e.sequence&Jo)!==0||(e.sequence&ts)!==0)throw new Error("refund input sequence must be a plain block-count relative timelock (BIP-68 disable/time flags clear)");if((e.sequence&me)!==(e.csv&me))throw new Error(`refund input sequence ${e.sequence} must encode exactly the leaf CSV ${e.csv} — a mismatch signs but can never broadcast`)}function os(e){const{psbtHex:t,depositorXOnlyHex:n,masterFingerprintHex:r,depositorPath:o}=e;if(!Do.test(n))throw new Error("depositorXOnlyHex must be 64 lowercase hex characters");if(!ko.test(r))throw new Error("masterFingerprintHex must be 8 lowercase hex characters (the 4-byte master fingerprint)");Ut("depositorPath",o);const s=an(t);if(s===void 0)throw new Error("not a refund-shaped PSBT (expected 1 input, 1 output, and one refund tapscript leaf)");if(cn(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=c.Buffer.from(i.txOutputs[0].script),u=c.Buffer.from(r,"hex"),l=$(o);return i.updateInput(0,{tapBip32Derivation:[{masterFingerprint:u,pubkey:c.Buffer.from(n,"hex"),path:l,leafHashes:[]}]}),i.updateOutput(0,{tapBip32Derivation:[{masterFingerprint:u,pubkey:a.subarray(Qo),path:l,leafHashes:[]}]}),i.toHex()}class V{constructor(t,n=_.crypto.sha256){p(this,"leaves");p(this,"rootNode");p(this,"leafNodes");p(this,"h");this.leaves=t,this.h=n;const r=this.calculateRoot(t);this.rootNode=r.root,this.leafNodes=r.leaves}getRoot(){return this.rootNode.hash}size(){return this.leaves.length}getLeaves(){return this.leaves}getLeafHash(t){const n=this.leafNodes[t];if(n===void 0)throw Error("Index out of bounds");return n.hash}getProof(t){const n=this.leafNodes[t];if(n===void 0)throw Error("Index out of bounds");return At(n)}calculateRoot(t){const n=t.length;if(n==0)return{root:new mt(void 0,void 0,c.Buffer.alloc(32,0)),leaves:[]};if(n==1){const h=new mt(void 0,void 0,t[0]);return{root:h,leaves:[h]}}const r=is(n),o=this.calculateRoot(t.slice(0,r)),s=this.calculateRoot(t.slice(r)),i=o.root,a=s.root,u=this.hashNode(i.hash,a.hash),l=new mt(i,a,u);return i.parent=l,a.parent=l,{root:l,leaves:o.leaves.concat(s.leaves)}}hashNode(t,n){return this.h(c.Buffer.concat([c.Buffer.from([1]),t,n]))}}function G(e,t=_.crypto.sha256){return ss(c.Buffer.from([0]),e,t)}function ss(e,t,n){return n(c.Buffer.concat([e,t]))}class mt{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 At(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,...At(e.parent)]}else{if(!e.parent.leftChild)throw new Error("Expected left child to exist");return[e.parent.leftChild.hash,...At(e.parent)]}}function is(e){if(e<2)throw Error("Expected n >= 2");return as(e)?e/2:1<<Math.floor(Math.log2(e))}function as(e){return(e&e-1)==0}const Ht=255,cs=2,I=32;class z{}class us extends z{constructor(n,r,o){super();p(this,"results");p(this,"code",16);this.progressCallback=r,this.onYield=o,this.results=n}execute(n){const r=c.Buffer.from(n.subarray(1));return this.onYield&&this.onYield(c.Buffer.from(r)),this.results.push(r),this.progressCallback&&this.progressCallback(),c.Buffer.from("")}}class ls extends z{constructor(n,r){super();p(this,"knownPreimages");p(this,"queue");p(this,"code",64);this.knownPreimages=n,this.queue=r}execute(n){const r=c.Buffer.from(n.subarray(1));if(r.length!==1+I)throw new Error("Invalid request, unexpected trailing data");if(r[0]!==0)throw new Error("Unsupported request, the first byte should be 0");const s=c.Buffer.from(r.subarray(1,1+I)).toString("hex"),i=this.knownPreimages.get(s);if(i!==void 0){const a=U(i.length),u=Ht-a.length-1,l=Math.min(u,i.length);if(l<i.length)for(let h=l;h<i.length;h++)this.queue.push(c.Buffer.from(i.subarray(h,h+1)));return c.Buffer.concat([a,c.Buffer.from([l]),c.Buffer.from(i.subarray(0,l))])}throw new Error(`Requested unknown preimage for: ${s}`)}}class fs extends z{constructor(n,r){super();p(this,"knownTrees");p(this,"queue");p(this,"code",65);this.knownTrees=n,this.queue=r}execute(n){const r=c.Buffer.from(n.subarray(1));if(r.length<I+1+1)throw new Error("Invalid request, expected at least 34 bytes");const o=new k(r),i=o.readSlice(I).toString("hex");let a,u;try{a=R(o.readVarInt()),u=R(o.readVarInt())}catch{throw new Error("Invalid request, couldn't parse tree_size or leaf_index")}const l=this.knownTrees.get(i);if(!l)throw new Error(`Requested Merkle leaf proof for unknown tree: ${i}`);if(u>=a||l.size()!==a)throw new Error("Invalid index or tree size.");if(this.queue.length!==0)throw new Error("This command should not execute when the queue is not empty.");const h=l.getProof(u),g=Math.min(Math.floor((Ht-I-1-1)/I),h.length),f=h.length-g;return f>0&&this.queue.push(...h.slice(-f)),c.Buffer.concat([l.getLeafHash(u),c.Buffer.from([h.length]),c.Buffer.from([g]),...h.slice(0,g)])}}class hs extends z{constructor(n){super();p(this,"knownTrees");p(this,"code",66);this.knownTrees=n}execute(n){const r=c.Buffer.from(n.subarray(1));if(r.length!==I+I)throw new Error("Invalid request, unexpected trailing data");const s=c.Buffer.from(r.subarray(0,I)).toString("hex"),a=c.Buffer.from(r.subarray(I,I+I)).toString("hex"),u=this.knownTrees.get(s);if(!u)throw new Error(`Requested Merkle leaf index for unknown root: ${s}`);let l=0,h=0;for(let g=0;g<u.size();g++)if(u.getLeafHash(g).toString("hex")===a){h=1,l=g;break}return c.Buffer.concat([c.Buffer.from([h]),U(l)])}}class ps extends z{constructor(n){super();p(this,"queue");p(this,"code",160);this.queue=n}execute(n){if(n.length!==1)throw new Error("Invalid request, unexpected trailing data");const r=this.queue[0];if(r===void 0)throw new Error("No elements to get");const o=r.length;if(this.queue.some(u=>u.length!==o))throw new Error("The queue contains elements with different byte length, which is not expected");const s=Math.floor((Ht-cs)/o),i=Math.min(s,this.queue.length),a=this.queue.splice(0,i);return c.Buffer.concat([c.Buffer.from([i]),c.Buffer.from([o]),...a])}}class ds{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 us(this.yielded,t,n),new ls(this.preimages,this.queue),new hs(this.roots),new fs(this.roots,this.queue),new ps(this.queue)];for(const o of r){if(this.commands.has(o.code))throw new Error(`Multiple commands with code ${o.code}`);this.commands.set(o.code,o)}}getYielded(){return this.yielded}addKnownPreimage(t){this.preimages.set(_.crypto.sha256(t).toString("hex"),t)}addKnownList(t){for(const r of t){const o=c.Buffer.concat([c.Buffer.from([0]),r]);this.addKnownPreimage(o)}const n=new V(t.map(r=>G(r)));this.roots.set(n.getRoot().toString("hex"),n)}addKnownMapping(t){this.addKnownList(t.keys),this.addKnownList(t.values)}addKnownWalletPolicy(t){this.addKnownPreimage(t.serialize()),this.addKnownList(t.keys.map(n=>c.Buffer.from(n,"ascii"))),this.addKnownPreimage(c.Buffer.from(t.descriptorTemplate))}execute(t){if(t.length===0)throw new Error("Unexpected empty command");const n=t[0],r=this.commands.get(n);if(!r)throw new Error(`Unexpected command code ${n}`);return r.execute(t)}}class gs{constructor(t,n){p(this,"keys");p(this,"keysTree");p(this,"values");p(this,"valuesTree");if(t.length!=n.length)throw new Error("keys and values should have the same length");for(let r=0;r<t.length-1;r++)if(t[r].toString("hex")>=t[r+1].toString("hex"))throw new Error("keys must be in strictly increasing order");this.keys=t,this.keysTree=new V(t.map(r=>G(r))),this.values=n,this.valuesTree=new V(n.map(r=>G(r)))}commitment(){return c.Buffer.concat([U(this.keys.length),this.keysTree.getRoot(),this.valuesTree.getRoot()])}}class W extends Qe{constructor(n){super();p(this,"globalMerkleMap");p(this,"inputMerkleMaps",[]);p(this,"outputMerkleMaps",[]);p(this,"inputMapCommitments");p(this,"outputMapCommitments");n.copy(this),this.globalMerkleMap=W.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(W.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(W.createMerkleMap(i))}this.outputMapCommitments=this.outputMerkleMaps.map(s=>s.commitment())}getGlobalSize(){return this.globalMap.size}getGlobalKeysValuesRoot(){return this.globalMerkleMap.commitment()}static createMerkleMap(n){const r=[...n.keys()].sort(),o=r.map(i=>{const a=n.get(i);if(!a)throw new Error("No value for key "+i);return a}),s=r.map(i=>c.Buffer.from(i,"hex"));return new gs(s,o)}}const Es=2;class ws{constructor(t,n,r){p(this,"name");p(this,"descriptorTemplate");p(this,"keys");this.name=t,this.descriptorTemplate=n,this.keys=r}getId(){return _.crypto.sha256(this.serialize())}serialize(){const t=this.keys.map(o=>c.Buffer.from(o,"ascii")),n=new V(t.map(o=>G(o))),r=new v;return r.writeUInt8(Es),r.writeVarSlice(c.Buffer.from(this.name,"ascii")),r.writeVarInt(this.descriptorTemplate.length),r.writeSlice(_.crypto.sha256(c.Buffer.from(this.descriptorTemplate))),r.writeVarInt(this.keys.length),r.writeSlice(n.getRoot()),r.buffer()}}class un extends ws{constructor(t,n){super("",t,[n])}}const _s=4,ms=0,Ts=1,ln=32,Is=new Uint8Array(ln),Ss=new Uint8Array(ln),Ps=/^[0-9a-f]{64}$/,ys=/^(?:[0-9a-fA-F]{2})+$/,bs=/^[0-9a-f]{64}$/;function Rs(e,t){const n=new V(e.inputMapCommitments.map(o=>G(o))).getRoot(),r=new V(e.outputMapCommitments.map(o=>G(o))).getRoot();return Uint8Array.from(c.Buffer.concat([e.getGlobalKeysValuesRoot(),U(e.getGlobalInputCount()),n,U(e.getGlobalOutputCount()),r,c.Buffer.from(t),c.Buffer.from(Ss)]))}function xs(e){return{cla:x,ins:_s,p1:ms,p2:Ts,data:e}}const As=0;function Os(e,t){for(const[n]of t.byInput){const r=e.data.inputs[n].sighashType;if(r!==void 0&&r!==As)throw new d(`input ${n} requests sighash type ${r}, but vault flows sign SIGHASH_DEFAULT only`)}}function Bs(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 fn=new WeakMap;function vs(e,t){const n={...e};return fn.set(n,t),n}function hn(e){const t=fn.get(e);if(!t)throw new d("unrecognised prepared signing state — use prepareSignPsbt's return value");return t}function pn(e){const{psbtHex:t,depositorXOnlyHex:n,signInputIndexes:r,walletPolicy:o}=e;if(!Ps.test(n))throw new d("depositorXOnlyHex must be 64 lowercase hex characters");let s;if(o!==void 0){if(!bs.test(o.walletIdHex))throw new d("walletPolicy.walletIdHex must be 64 lowercase hex characters");if(s=new un(o.descriptorTemplate,o.keyInfo),s.getId().toString("hex")!==o.walletIdHex)throw new d("walletPolicy.walletIdHex does not match sha256 of the serialized policy")}if(!ys.test(t))throw new d("psbtHex is not even-length hexadecimal");let i;try{i=_.Psbt.fromHex(t)}catch(E){throw new d(`PSBT rejected at parse (merge target): ${E instanceof Error?E.message:String(E)}`)}const a=new Qe;try{a.deserialize(c.Buffer.from(t,"hex"))}catch(E){throw new d(`PSBT rejected at parse: ${E instanceof Error?E.message:String(E)}`)}let u,l;try{u=new W(a),l=Eo({psbt:u,depositorXOnlyHex:n,signInputIndexes:r})}catch(E){throw E instanceof d?E:new d(`PSBT rejected at preflight: ${E instanceof Error?E.message:String(E)}`)}Bs(i,l),Os(i,l);const h=wo(l),g=new ds(void 0,E=>h.assertAndRecord(E));g.addKnownMapping(u.globalMerkleMap);for(const E of u.inputMerkleMaps)g.addKnownMapping(E);for(const E of u.outputMerkleMaps)g.addKnownMapping(E);g.addKnownList(u.inputMapCommitments),g.addKnownList(u.outputMapCommitments);const f=o?c.Buffer.from(o.walletIdHex,"hex"):Is;return s&&g.addKnownWalletPolicy(s),vs({table:l,unsignedTxid:_.Transaction.fromBuffer(i.data.globalMap.unsignedTx.toBuffer()).getId()},{cdata:Rs(u,f),interpreter:g,collector:h,originalPsbtHex:t,signsUnderWalletPolicy:o!==void 0})}const Cs=248,Ls=1,Ns=0,Ms=0,Ds=36864,ks=57344;async function $s(e,t,n){const{collector:r,interpreter:o,cdata:s}=hn(t),{table:i}=t;if(n.signal.aborted)throw new It(r.yields.length);const a=xs(s);let u=a,l=await e(a),h=0;for(;l.sw===ks;){let g;try{g=o.execute(c.Buffer.from(l.data))}catch(f){throw Me(f)?f:De(f)?new d(f.detail,rt(r.yields)):new d(`client command failed: ${f instanceof Error?f.message:String(f)}`,rt(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 It(r.yields.length);u={cla:Cs,ins:Ls,p1:Ns,p2:Ms,data:g},l=await e(u)}if(l.sw!==Ds){const g=He(l.sw,{...n.appIdentity,ins:u.ins,p1:u.p1,preDispatch:u===a});throw g===void 0?new d(`status word 0x${l.sw.toString(16)} escaped classification`,rt(r.yields)):g}return r.assertComplete(),r.yields}function Us(e,t){const n=_.Psbt.fromHex(e);for(const r of t)r.kind==="tapscript"?n.updateInput(r.inputIndex,{tapScriptSig:[{pubkey:c.Buffer.from(r.signerXOnlyHex,"hex"),leafHash:c.Buffer.from(r.leafHashHex,"hex"),signature:c.Buffer.from(r.signature)}]}):n.updateInput(r.inputIndex,{tapKeySig:c.Buffer.from(r.signature)});return n.toHex()}const Te=new WeakSet;async function dn(e,t,n){const{originalPsbtHex:r,signsUnderWalletPolicy:o}=hn(t);if(Te.has(t))throw new d("prepared signing state was already used — call prepareSignPsbt again for a retry");if([...t.table.byInput.values()].some(u=>u.kind==="taproot-keypath")&&!o)throw new d("PSBT signs a key-path input but was prepared without a walletPolicy — the device would answer SW_OK with no signature");Te.add(t);const i=await $s(e,t,n);let a;try{a=Us(r,i)}catch(u){throw new d(`merge failed after signing: ${u instanceof Error?u.message:String(u)}`,rt(i))}return{signedPsbtHex:a,yields:[...i]}}async function Hs(e,t){const{psbtHex:n,depositorXOnlyHex:r,signInputIndexes:o,...s}=t,i=pn({psbtHex:n,depositorXOnlyHex:r,signInputIndexes:o});return dn(e,i,s)}const Ie="tr(@0/**)",Se=2147483647,Vs=/^[0-9a-f]{8}$/;function Gs(e){const{masterFingerprintHex:t,coinType:n,accountIndex:r,accountXpub:o,bip32Versions:s}=e;if(!Vs.test(t))throw new Error("masterFingerprintHex must be 8 lowercase hex characters");if(!Number.isInteger(n)||n<0||n>Se||!Number.isInteger(r)||r<0||r>Se)throw new Error("coinType and accountIndex must be non-negative integers in 0..0x7fffffff");try{ut.HDKey.fromExtendedKey(o,s)}catch(u){throw new Error(`accountXpub is not a valid extended key for this network: ${u instanceof Error?u.message:String(u)}`)}const i=`[${t}/${at}'/${n}'/${r}']${o}`,a=new un(Ie,i).getId().toString("hex");return{descriptorTemplate:Ie,keyInfo:i,walletIdHex:a,accountXpub:o,bip32Versions:s,keyOriginPath:[(b|at)>>>0,(b|n)>>>0,(b|r)>>>0],masterFingerprintHex:t}}exports.DEPOSIT_TERMS_REJECTED_ERROR_NAME=Ye;exports.DepositTermsRejectedError=T;exports.LEDGER_DEVICE_ERROR_NAME=Ct;exports.LEDGER_DEVICE_LOCKED_ERROR_NAME=vt;exports.LEDGER_SIGN_PSBT_ABORTED_ERROR_NAME=Dt;exports.LEDGER_SIGN_PSBT_INCOMPLETE_ERROR_NAME=Nt;exports.LEDGER_SIGN_PSBT_PROTOCOL_ERROR_NAME=Mt;exports.LEDGER_USER_REFUSED_ERROR_NAME=Bt;exports.LEDGER_YIELD_MISMATCH_ERROR_NAME=Lt;exports.LedgerDeviceError=Le;exports.LedgerDeviceLockedError=Ce;exports.LedgerSignPsbtAbortedError=It;exports.LedgerSignPsbtIncompleteError=Ne;exports.LedgerSignPsbtProtocolError=d;exports.LedgerUserRefusedError=ve;exports.LedgerYieldMismatchError=S;exports.SW_BAD_STATE=ke;exports.SW_CAP_EXCEEDED=$e;exports.SW_CLA_NOT_SUPPORTED=kt;exports.approveVaultIntent=rr;exports.assertDepositTermsDeviceCompatible=Hr;exports.assertRefundPsbtSignable=cn;exports.augmentPsbtForRefund=os;exports.augmentPsbtForWalletPolicy=Io;exports.buildDefaultTaprootPolicy=Gs;exports.buildPopPsbtHex=Mo;exports.classifyRefundPsbt=an;exports.closeDmk=vr;exports.connectDmkSession=xr;exports.createDmkApduSender=Pr;exports.createDmkRawApduSender=Ve;exports.deriveChangeXOnlyHex=en;exports.deriveContextHash=nr;exports.deriveReceiveXOnlyHex=mo;exports.disconnectDmkSession=Br;exports.encodeIntentGroup=ye;exports.encodeIntentScalars=Pe;exports.encodeKeyBatches=be;exports.getExtendedPublicKey=Ae;exports.getMasterFingerprintHex=cr;exports.getXOnlyPublicKeyHex=ur;exports.isLedgerDeviceError=hr;exports.isLedgerDeviceLockedError=pr;exports.isLedgerSignPsbtAbortedError=gr;exports.isLedgerSignPsbtIncompleteError=dr;exports.isLedgerSignPsbtProtocolError=De;exports.isLedgerUserRefusedError=fr;exports.isLedgerYieldMismatchError=Me;exports.isSessionAlive=Or;exports.prepareSignPsbt=pn;exports.psbtPaysChangeScript=To;exports.signPreparedVaultPsbt=dn;exports.signVaultPsbt=Hs;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|