@babylonlabs-io/ts-sdk 0.70.1 → 0.71.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/PeginManager-BIKAnZ-X.cjs +2 -0
- package/dist/PeginManager-BIKAnZ-X.cjs.map +1 -0
- package/dist/{PeginManager-BNtg6jgY.js → PeginManager-Byvmccdd.js} +10 -10
- package/dist/PeginManager-Byvmccdd.js.map +1 -0
- package/dist/abortSignals-BPpAUL1Z.js +18 -0
- package/dist/abortSignals-BPpAUL1Z.js.map +1 -0
- package/dist/abortSignals-msbmbqFe.cjs +2 -0
- package/dist/abortSignals-msbmbqFe.cjs.map +1 -0
- package/dist/{bitcoin-Ch_jxnDa.js → bitcoin-C-TuHb-v.js} +21 -22
- package/dist/bitcoin-C-TuHb-v.js.map +1 -0
- package/dist/bitcoin-D-O2GjbC.cjs +2 -0
- package/dist/bitcoin-D-O2GjbC.cjs.map +1 -0
- package/dist/{buildAndBroadcastReclaim-kBHwOL02.js → buildAndBroadcastReclaim-C0TdwO2M.js} +60 -59
- package/dist/{buildAndBroadcastReclaim-kBHwOL02.js.map → buildAndBroadcastReclaim-C0TdwO2M.js.map} +1 -1
- package/dist/buildAndBroadcastReclaim-kRx7-o2y.cjs +2 -0
- package/dist/{buildAndBroadcastReclaim-iNJfx0ZG.cjs.map → buildAndBroadcastReclaim-kRx7-o2y.cjs.map} +1 -1
- package/dist/{challengeAssert-BNQ8sToz.js → challengeAssert-Cp_GeRg8.js} +3 -3
- package/dist/challengeAssert-Cp_GeRg8.js.map +1 -0
- package/dist/challengeAssert-Z7_YULBb.cjs +2 -0
- package/dist/challengeAssert-Z7_YULBb.cjs.map +1 -0
- package/dist/constants-Bh38W9mq.cjs +2 -0
- package/dist/constants-Bh38W9mq.cjs.map +1 -0
- package/dist/constants-CPzppOdq.js +17 -0
- package/dist/constants-CPzppOdq.js.map +1 -0
- package/dist/index-Cs7_Evtk.cjs +2 -0
- package/dist/index-Cs7_Evtk.cjs.map +1 -0
- package/dist/index-LgmJhdEN.js +505 -0
- package/dist/index-LgmJhdEN.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +230 -226
- package/dist/index.js.map +1 -1
- package/dist/mempoolApi-BQllf-ji.cjs +2 -0
- package/dist/{mempoolApi-Q90mz17e.cjs.map → mempoolApi-BQllf-ji.cjs.map} +1 -1
- package/dist/{mempoolApi-CfOFmov6.js → mempoolApi-CRNMOsbC.js} +36 -35
- package/dist/{mempoolApi-CfOFmov6.js.map → mempoolApi-CRNMOsbC.js.map} +1 -1
- package/dist/noPayout--lxo7qe4.js +300 -0
- package/dist/noPayout--lxo7qe4.js.map +1 -0
- package/dist/noPayout-CegnEwfp.cjs +2 -0
- package/dist/noPayout-CegnEwfp.cjs.map +1 -0
- package/dist/{onChainBtcPubkey-C_a2L3kL.cjs → onChainBtcPubkey-B5ZvWCCF.cjs} +2 -2
- package/dist/{onChainBtcPubkey-C_a2L3kL.cjs.map → onChainBtcPubkey-B5ZvWCCF.cjs.map} +1 -1
- package/dist/{onChainBtcPubkey-BAHZyKQL.js → onChainBtcPubkey-DATNfAAl.js} +2 -2
- package/dist/{onChainBtcPubkey-BAHZyKQL.js.map → onChainBtcPubkey-DATNfAAl.js.map} +1 -1
- package/dist/parseFundingOutpoints-BkgGihaY.cjs +2 -0
- package/dist/parseFundingOutpoints-BkgGihaY.cjs.map +1 -0
- package/dist/{parseFundingOutpoints-CO-f6IHK.js → parseFundingOutpoints-DlINgQ3X.js} +30 -29
- package/dist/parseFundingOutpoints-DlINgQ3X.js.map +1 -0
- package/dist/{batchPoll-BM4iQ9jT.js → primeVpAuth-D1qbOkhb.js} +311 -803
- package/dist/primeVpAuth-D1qbOkhb.js.map +1 -0
- package/dist/primeVpAuth-tEXx9TGx.cjs +2 -0
- package/dist/primeVpAuth-tEXx9TGx.cjs.map +1 -0
- package/dist/{reservation-CBAvoF3U.js → reservation-Cj9F0rP9.js} +2 -2
- package/dist/{reservation-CBAvoF3U.js.map → reservation-Cj9F0rP9.js.map} +1 -1
- package/dist/{reservation-CDbInVw0.cjs → reservation-Dr2HLCxx.cjs} +2 -2
- package/dist/{reservation-CDbInVw0.cjs.map → reservation-Dr2HLCxx.cjs.map} +1 -1
- package/dist/{signPsbtsWithFallback-X6ivsbh7.js → signPsbtsWithFallback-BjXdnI0X.js} +18 -19
- package/dist/{signPsbtsWithFallback-X6ivsbh7.js.map → signPsbtsWithFallback-BjXdnI0X.js.map} +1 -1
- package/dist/signPsbtsWithFallback-zOQWokmk.cjs +2 -0
- package/dist/{signPsbtsWithFallback-Bo1PJX90.cjs.map → signPsbtsWithFallback-zOQWokmk.cjs.map} +1 -1
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +36 -35
- package/dist/tbv/core/clients/index.js.map +1 -1
- package/dist/tbv/core/clients/vault-provider/auth/serverIdentity.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/auth/verifyDepositorCwt.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/status/index.cjs +2 -0
- package/dist/tbv/core/clients/vault-provider/status/index.cjs.map +1 -0
- package/dist/tbv/core/clients/vault-provider/status/index.d.ts +18 -0
- package/dist/tbv/core/clients/vault-provider/status/index.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/status/index.js +17 -0
- package/dist/tbv/core/clients/vault-provider/status/index.js.map +1 -0
- package/dist/tbv/core/clients/vault-provider/validators.d.ts.map +1 -1
- package/dist/tbv/core/deposit-terms/rebuildDepositTermsCore.d.ts +1 -1
- package/dist/tbv/core/deposit-terms/rebuildDepositTermsCore.d.ts.map +1 -1
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +224 -220
- package/dist/tbv/core/index.js.map +1 -1
- package/dist/tbv/core/managers/index.cjs +1 -1
- package/dist/tbv/core/managers/index.js +2 -2
- package/dist/tbv/core/primitives/index.cjs +1 -1
- package/dist/tbv/core/primitives/index.d.ts +2 -2
- package/dist/tbv/core/primitives/index.d.ts.map +1 -1
- package/dist/tbv/core/primitives/index.js +7 -7
- package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/challengeAssert.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/challengeAssert.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/noPayout.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/noPayout.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/payout.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/payout.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/pegin.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/peginInput.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/peginInput.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/refund.d.ts.map +1 -1
- package/dist/tbv/core/primitives/scripts/payout.d.ts +1 -1
- package/dist/tbv/core/primitives/scripts/payout.d.ts.map +1 -1
- package/dist/tbv/core/primitives/utils/bitcoin.d.ts +0 -10
- package/dist/tbv/core/primitives/utils/bitcoin.d.ts.map +1 -1
- package/dist/tbv/core/recovery/reconstructPeginParams.d.ts.map +1 -1
- package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts.map +1 -1
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.js +2 -2
- package/dist/tbv/core/utils/index.cjs +1 -1
- package/dist/tbv/core/utils/index.js +47 -44
- package/dist/tbv/core/utils/index.js.map +1 -1
- package/dist/tbv/core/utils/utxo/reservation.d.ts.map +1 -1
- package/dist/tbv/core/utils/validation.d.ts +4 -0
- package/dist/tbv/core/utils/validation.d.ts.map +1 -1
- package/dist/tbv/core/vault-secrets/deriveVaultRoot.d.ts.map +1 -1
- package/dist/tbv/core/vault-secrets/index.cjs +1 -1
- package/dist/tbv/core/vault-secrets/index.d.ts +1 -1
- package/dist/tbv/core/vault-secrets/index.d.ts.map +1 -1
- package/dist/tbv/core/vault-secrets/index.js +2 -2
- package/dist/tbv/core/wasm/__tests__/constants.test.d.ts +2 -0
- package/dist/tbv/core/wasm/__tests__/constants.test.d.ts.map +1 -0
- package/dist/tbv/core/wasm/__tests__/loader.test.d.ts +2 -0
- package/dist/tbv/core/wasm/__tests__/loader.test.d.ts.map +1 -0
- package/dist/tbv/core/wasm/__tests__/value-guards.test.d.ts +2 -0
- package/dist/tbv/core/wasm/__tests__/value-guards.test.d.ts.map +1 -0
- package/dist/tbv/core/wasm/constants.d.ts +11 -0
- package/dist/tbv/core/wasm/constants.d.ts.map +1 -0
- package/dist/tbv/core/wasm/index.cjs +2 -0
- package/dist/tbv/core/wasm/index.cjs.map +1 -0
- package/dist/tbv/core/wasm/index.d.ts +191 -0
- package/dist/tbv/core/wasm/index.d.ts.map +1 -0
- package/dist/tbv/core/wasm/index.js +144 -0
- package/dist/tbv/core/wasm/index.js.map +1 -0
- package/dist/tbv/core/wasm/value-guards.d.ts +30 -0
- package/dist/tbv/core/wasm/value-guards.d.ts.map +1 -0
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +224 -220
- package/dist/tbv/index.js.map +1 -1
- package/dist/testing/index.cjs +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/toRefundInputs-Bdtz8p27.cjs +2 -0
- package/dist/toRefundInputs-Bdtz8p27.cjs.map +1 -0
- package/dist/{toRefundInputs-DPNYBFkP.js → toRefundInputs-CgXMcHrk.js} +7 -7
- package/dist/toRefundInputs-CgXMcHrk.js.map +1 -0
- package/dist/validation-C6XTfZak.cjs +2 -0
- package/dist/validation-C6XTfZak.cjs.map +1 -0
- package/dist/validation-OSC0xTHB.js +17 -0
- package/dist/validation-OSC0xTHB.js.map +1 -0
- package/dist/vaultCoreVersion-DYfw3qed.cjs +2 -0
- package/dist/vaultCoreVersion-DYfw3qed.cjs.map +1 -0
- package/dist/vaultCoreVersion-D_fP9P3C.js +10 -0
- package/dist/vaultCoreVersion-D_fP9P3C.js.map +1 -0
- package/dist/verifyKeyPathSchnorrSignature-BedSbH2D.cjs +2 -0
- package/dist/verifyKeyPathSchnorrSignature-BedSbH2D.cjs.map +1 -0
- package/dist/{verifyKeyPathSchnorrSignature-C6Cmk0R1.js → verifyKeyPathSchnorrSignature-BrgUJmV0.js} +3 -3
- package/dist/verifyKeyPathSchnorrSignature-BrgUJmV0.js.map +1 -0
- package/dist/{verifyScriptPathSchnorrSignature-CQYucnJA.js → verifyScriptPathSchnorrSignature-ZAZfFJ6S.js} +35 -34
- package/dist/verifyScriptPathSchnorrSignature-ZAZfFJ6S.js.map +1 -0
- package/dist/verifyScriptPathSchnorrSignature-mzYCzaSy.cjs +2 -0
- package/dist/verifyScriptPathSchnorrSignature-mzYCzaSy.cjs.map +1 -0
- package/package.json +12 -2
- package/dist/PeginManager-BNtg6jgY.js.map +0 -1
- package/dist/PeginManager-CvI99Uhd.cjs +0 -2
- package/dist/PeginManager-CvI99Uhd.cjs.map +0 -1
- package/dist/batchPoll-BM4iQ9jT.js.map +0 -1
- package/dist/batchPoll-cqpEfBjr.cjs +0 -2
- package/dist/batchPoll-cqpEfBjr.cjs.map +0 -1
- package/dist/bitcoin-Ch_jxnDa.js.map +0 -1
- package/dist/bitcoin-m84N5a8o.cjs +0 -2
- package/dist/bitcoin-m84N5a8o.cjs.map +0 -1
- package/dist/buildAndBroadcastReclaim-iNJfx0ZG.cjs +0 -2
- package/dist/challengeAssert-BNQ8sToz.js.map +0 -1
- package/dist/challengeAssert-BrpC3-cQ.cjs +0 -2
- package/dist/challengeAssert-BrpC3-cQ.cjs.map +0 -1
- package/dist/constants-BCdDRd_Y.cjs +0 -2
- package/dist/constants-BCdDRd_Y.cjs.map +0 -1
- package/dist/constants-DRiWbItj.js +0 -24
- package/dist/constants-DRiWbItj.js.map +0 -1
- package/dist/mempoolApi-Q90mz17e.cjs +0 -2
- package/dist/noPayout-BKP3mRu3.cjs +0 -2
- package/dist/noPayout-BKP3mRu3.cjs.map +0 -1
- package/dist/noPayout-BdATUPjF.js +0 -280
- package/dist/noPayout-BdATUPjF.js.map +0 -1
- package/dist/parseFundingOutpoints-CIO9Ok1L.cjs +0 -2
- package/dist/parseFundingOutpoints-CIO9Ok1L.cjs.map +0 -1
- package/dist/parseFundingOutpoints-CO-f6IHK.js.map +0 -1
- package/dist/signPsbtsWithFallback-Bo1PJX90.cjs +0 -2
- package/dist/toRefundInputs-BJojfg3k.cjs +0 -2
- package/dist/toRefundInputs-BJojfg3k.cjs.map +0 -1
- package/dist/toRefundInputs-DPNYBFkP.js.map +0 -1
- package/dist/validation-CDbOaDj7.cjs +0 -2
- package/dist/validation-CDbOaDj7.cjs.map +0 -1
- package/dist/validation-Dj3dqYtl.js +0 -30
- package/dist/validation-Dj3dqYtl.js.map +0 -1
- package/dist/verifyKeyPathSchnorrSignature-C6Cmk0R1.js.map +0 -1
- package/dist/verifyKeyPathSchnorrSignature-Cr5T4Aym.cjs +0 -2
- package/dist/verifyKeyPathSchnorrSignature-Cr5T4Aym.cjs.map +0 -1
- package/dist/verifyScriptPathSchnorrSignature-CQYucnJA.js.map +0 -1
- package/dist/verifyScriptPathSchnorrSignature-D-ppKNjT.cjs +0 -2
- package/dist/verifyScriptPathSchnorrSignature-D-ppKNjT.cjs.map +0 -1
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var Te=Object.defineProperty;var Se=(e,t,r)=>t in e?Te(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var A=(e,t,r)=>Se(e,typeof t!="symbol"?t+"":t,r);const le=require("./BTCVaultRegistry.abi-z7d_eP22.cjs"),p=require("./bitcoin-m84N5a8o.cjs"),C=require("./signPsbtsWithFallback-Bo1PJX90.cjs"),Re=require("viem"),x=require("./json-rpc-client-BiAmg_ho.cjs"),R=require("bitcoinjs-lib"),E=require("./verifyScriptPathSchnorrSignature-D-ppKNjT.cjs"),F=require("./constants-BCdDRd_Y.cjs"),_=require("./noPayout-BKP3mRu3.cjs"),V=require("./signing-Bnsro0hE.cjs"),oe=require("./onChainBtcPubkey-C_a2L3kL.cjs"),Ae=/^0x[0-9a-fA-F]{64}$/,_e=/^0x[0-9a-fA-F]{40}$/,Ce=/^0x([0-9a-fA-F]{2})*$/;function O(e,t){if(e.length!==66)throw new Error(`${t} must be 32 bytes (66 hex chars with 0x prefix), got length ${e.length}`);if(!Ae.test(e))throw new Error(`${t} must contain only hex characters after the 0x prefix`)}function Be(e,t){if(!_e.test(e))throw new Error(`${t} must be a 20-byte 0x-prefixed hex address (42 chars)`)}function $e(e,t){if(!Ce.test(e))throw new Error(`${t} must be a 0x-prefixed hex string with an even number of hex chars`)}function he(e){Be(e.btcVaultRegistryAddress,"btcVaultRegistryAddress"),O(e.vaultId,"vaultId");const t=p.ensureHexPrefix(e.secret);if(O(t,"secret"),e.hashlock!==void 0&&(O(e.hashlock,"hashlock"),!C.validateSecretAgainstHashlock(t,e.hashlock)))throw new Error("Invalid secret: SHA256(secret) does not match the provided hashlock");return t}async function Ie(e){const{btcVaultRegistryAddress:t,vaultId:r,hashlock:n,activationMetadata:s,writeContract:c,signal:i}=e;i==null||i.throwIfAborted();const o=he({btcVaultRegistryAddress:t,vaultId:r,secret:e.secret,hashlock:n});return $e(s,"activationMetadata"),c({address:t,abi:le.BTCVaultRegistryABI,functionName:"activateVaultWithSecret",args:[r,o,s]})}async function Ve(e){const{btcVaultRegistryAddress:t,vaultId:r,hashlock:n,writeContract:s,signal:c}=e;c==null||c.throwIfAborted();const i=he({btcVaultRegistryAddress:t,vaultId:r,secret:e.secret,hashlock:n});return s({address:t,abi:le.BTCVaultRegistryABI,functionName:"activateVaultWithSecretAndRedeem",args:[r,i]})}const pe=8,Oe=6e3,Ne=10*6e4,Ke=10;class W extends Error{constructor(t){super(t),this.name="PeginRegistrationMissingError"}}class Y extends Error{constructor(t){super(t),this.name="PeginRegistrationNotFinalError"}}function de(e){return e instanceof W||e instanceof Error&&e.name==="PeginRegistrationMissingError"}function He(e){return e instanceof Y||e instanceof Error&&e.name==="PeginRegistrationNotFinalError"}function ie(e){const{currentBlock:t,createdAtBlock:r}=e,n=t-r+1n;return n<0n?0:Number(n)}async function De(e){const{vaultRegistryReader:t,getBlockNumber:r,vaultIds:n,required:s=pe,pollIntervalMs:c=Oe,timeoutMs:i=Ne,signal:o,onProgress:a}=e;if(n.length===0)throw new Error("waitForPeginRegistrationDepth requires at least one vault ID");const u=Date.now();let h=!1,l=0,d;for(;;){if(o!=null&&o.aborted)throw new Error(`Aborted while waiting for peg-in registration depth (${n.length} vault(s))`);if(Date.now()-u>=i)throw new Y(`Peg-in registration did not reach ${s} Ethereum confirmations within ${i}ms. The registration transaction was submitted but is not yet final, so the Pre-PegIn Bitcoin transaction was never sent and no funds are at risk. Resume this deposit from the dashboard once the network settles.`+(d instanceof Error?` Last read error: ${d.message}`:""));try{const g=await r(),f=await Promise.all(n.map(P=>t.getVaultBasicInfo(P))),b=f.findIndex(P=>P.depositor===Re.zeroAddress||P.createdAt===0n);if(b!==-1){if(l+=1,!h&&l>Ke)throw new W(`Vault ${n[b]} is still not visible on-chain after ${l} reads — the registration does not exist.`);console.warn(`Peg-in registration for vault ${n[b]} is not visible in chain state at block ${g} — a lagging RPC backend or an Ethereum reorg. Still polling.`),a==null||a({confirmations:0,required:s})}else{h=!0,l=0,d=void 0;let P=f[0],m=ie({currentBlock:g,createdAtBlock:f[0].createdAt});for(const v of f.slice(1)){const y=ie({currentBlock:g,createdAtBlock:v.createdAt});y<m&&(m=y,P=v)}if(a==null||a({confirmations:m,required:s}),m>=s)return{confirmations:m,basicInfo:P}}}catch(g){if(de(g))throw g;console.warn(`Registration-depth read failed (retrying in ${c}ms): `+(g instanceof Error?g.message:String(g))),d=g}await new Promise((g,f)=>{const b=()=>{clearTimeout(P),f(new Error(`Aborted while waiting for peg-in registration depth (${n.length} vault(s))`))},P=setTimeout(()=>{o==null||o.removeEventListener("abort",b),g()},c);o==null||o.addEventListener("abort",b,{once:!0})})}}const Fe=1;function Me(e,t,r){const n=r.map(l=>p.stripHexPrefix(l).toLowerCase()),s=t.filter(l=>n.includes(l));if(s.length>0)throw new Error(`Cannot validate challenger set: vault keepers and universal challengers overlap (${s.join(", ")})`);const c=[...t,...n],i=e.map(l=>p.stripHexPrefix(l.challenger_pubkey).toLowerCase()),o=new Set(i);if(o.size!==i.length)throw new Error("Depositor graph contains duplicate challenger entries in challenger_presign_data");const a=new Set(c),u=c.filter(l=>!o.has(l)),h=i.filter(l=>!a.has(l));if(u.length>0||h.length>0)throw new Error("Depositor graph challenger set does not match expected (local ∪ universal)"+(u.length>0?` (missing: ${u.join(", ")})`:"")+(h.length>0?` (unexpected: ${h.join(", ")})`:""))}function Ue(e,t){const r=e.ins[t];return p.uint8ArrayToHex(new Uint8Array(r.hash).slice().reverse())}function N(e,t,r,n,s){const c=e.ins[t];if(c.index!==0)throw new Error(`NoPayout (challenger ${s}) input ${t} expected to spend ${n} vout 0, got vout ${c.index}`);const i=r.getId(),o=Ue(e,t);if(o!==i)throw new Error(`NoPayout (challenger ${s}) input ${t} does not reference ${n} (expected txid ${i}, got ${o})`)}async function Le(e,t,r){const n=[],s=[],c=[],i=E.deriveLocalChallengers({claimerBtcPubkey:r.depositorBtcPubkey,depositorBtcPubkey:r.depositorBtcPubkey,vaultProviderBtcPubkey:r.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:r.vaultKeeperBtcPubkeys});Me(e.challenger_presign_data,i,r.universalChallengerBtcPubkeys);const o=await E.buildPayoutPsbt({vaultCoreVersion:r.vaultCoreVersion,vkClaimerPayoutScriptPubKeys:r.vkClaimerPayoutScriptPubKeys,vpCommissionScriptPubKey:r.vpCommissionScriptPubKey,payoutTxHex:e.payout_tx.tx_hex,peginTxHex:r.peginTxHex,assertTxHex:e.assert_tx.tx_hex,timelockAssert:r.timelockAssert,depositorBtcPubkey:r.depositorBtcPubkey,vaultProviderBtcPubkey:r.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:r.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:r.universalChallengerBtcPubkeys,timelockPegin:r.timelockPegin,network:r.network,claimerBtcPubkey:r.depositorBtcPubkey,registeredPayoutScriptPubKey:r.registeredPayoutScriptPubKey,commissionBps:Fe,protocolFeeRate:r.protocolFeeRate,councilMembers:r.councilMembers,councilQuorum:r.councilQuorum});n.push(o.psbtHex),s.push(V.createTaprootScriptPathSignOptions(t,F.DEPOSITOR_SIGNED_INPUT_COUNT));const a=p.stripHexPrefix(r.depositorBtcPubkey),u=R.Transaction.fromHex(p.stripHexPrefix(e.assert_tx.tx_hex));for(const h of e.challenger_presign_data){const l=p.stripHexPrefix(h.challenger_pubkey),d=n.length,g=await Xe({challenger:h,challengerPubkey:l,claimerPubkey:a,localChallengers:i,assertTxParsed:u,ctx:r});n.push(g),s.push(V.createTaprootScriptPathSignOptions(t,F.DEPOSITOR_SIGNED_INPUT_COUNT)),c.push({challengerPubkey:l,noPayoutIdx:d})}return{psbtHexes:n,signOptions:s,challengerEntries:c}}async function Xe(e){const{challenger:t,challengerPubkey:r,claimerPubkey:n,localChallengers:s,assertTxParsed:c,ctx:i}=e;_.assertNoPayoutOutputMatchesChallenger(t.nopayout_tx.tx_hex,r,i.network);const o=R.Transaction.fromHex(p.stripHexPrefix(t.nopayout_tx.tx_hex)),a=R.Transaction.fromHex(p.stripHexPrefix(t.challenge_assert_x_tx.tx_hex)),u=R.Transaction.fromHex(p.stripHexPrefix(t.challenge_assert_y_tx.tx_hex));if(o.ins.length!==3)throw new Error(`NoPayout (challenger ${r}) must have exactly 3 inputs, got ${o.ins.length}`);N(o,0,c,"Assert",r),N(o,1,a,"ChallengeAssertX",r),N(o,2,u,"ChallengeAssertY",r);const h=[c.outs[0],a.outs[0],u.outs[0]].map(l=>({script_pubkey:p.uint8ArrayToHex(new Uint8Array(l.script)),value:l.value}));return _.buildNoPayoutPsbt({noPayoutTxHex:t.nopayout_tx.tx_hex,challengerPubkey:r,prevouts:h,connectorParams:{txGraphVersion:i.vaultCoreVersion,claimer:n,localChallengers:s,universalChallengers:i.universalChallengerBtcPubkeys,timelockAssert:i.timelockAssert,councilMembers:i.councilMembers,councilQuorum:i.councilQuorum}})}function ze(e,t,r){E.assertPsbtUnsignedTxMatches(e[0]);const s=E.extractPayoutSignature(e[0].returnedPsbtHex,r);E.assertScriptPathSchnorrSignature({requestedPsbtHex:e[0].requestedPsbtHex,signatureHex:s,signerXOnlyPubkeyHex:r,inputIndex:0});const c={};for(const i of t){E.assertPsbtUnsignedTxMatches(e[i.noPayoutIdx]);const o=E.extractPayoutSignature(e[i.noPayoutIdx].returnedPsbtHex,r);E.assertScriptPathSchnorrSignature({requestedPsbtHex:e[i.noPayoutIdx].requestedPsbtHex,signatureHex:o,signerXOnlyPubkeyHex:r,inputIndex:0}),c[i.challengerPubkey]={nopayout_signature:o}}return{payout_signatures:{payout_signature:s},per_challenger:c}}async function ge(e){const{depositorGraph:t,btcWallet:r,signingContext:n}=e,s=await r.getPublicKeyHex(),{depositorPubkey:c}=p.validateWalletPubkey(s,p.stripHexPrefix(n.depositorBtcPubkey)),{psbtHexes:i,signOptions:o,challengerEntries:a}=await Le(t,s,n),u=await C.signPsbtsWithFallback(r,i,o),h=i.map((l,d)=>({requestedPsbtHex:l,returnedPsbtHex:u[d]}));return ze(h,a,c)}const qe=1e4;async function Z(e){const{statusReader:t,peginTxid:r,targetStatuses:n,timeoutMs:s,pollIntervalMs:c=qe,signal:i}=e,o=Date.now();for(;;){if(i!=null&&i.aborted)throw new Error(`Polling aborted for pegin ${r.slice(0,8)}… (target: ${[...n].join(", ")})`);if(Date.now()-o>=s)throw new Error(`Polling timeout after ${s}ms for pegin ${r.slice(0,8)}… (target: ${[...n].join(", ")})`);try{const a=await t.getPeginStatus({pegin_txid:r},i);if(a.pegin_txid.toLowerCase()!==r.toLowerCase())throw new Error(`getPeginStatus returned status for pegin ${a.pegin_txid.slice(0,8)}…, requested ${r.slice(0,8)}…`);const u=a.status;if(n.has(u)||u===x.DaemonStatus.ACTIVATED)return u;if(u===x.DaemonStatus.EXPIRED||x.VP_TERMINAL_FAILURE_STATUSES.has(u))throw new Error(`Pegin ${r.slice(0,8)}… reached terminal status "${u}" while waiting for ${[...n].join(", ")}`)}catch(a){if(!(a instanceof x.JsonRpcError&&a.code===x.RpcErrorCode.PEGIN_NOT_FOUND))throw a}await new Promise((a,u)=>{const h=()=>{clearTimeout(l),u(new Error(`Polling aborted for pegin ${r.slice(0,8)}… (target: ${[...n].join(", ")})`))},l=setTimeout(()=>{i==null||i.removeEventListener("abort",h),a()},c);i==null||i.addEventListener("abort",h,{once:!0})})}}const Ge=1200*1e3,fe=new Set([x.DaemonStatus.PENDING_ACKS,x.DaemonStatus.PENDING_ACTIVATION,x.DaemonStatus.ACTIVATED_PENDING_BROADCAST,x.DaemonStatus.ACTIVATED]),je=new Set([x.DaemonStatus.PENDING_DEPOSITOR_SIGNATURES,...fe]);function Qe(e){return e.map(t=>({claimerPubkeyXOnly:p.processPublicKeyToXOnly(t.claimer_pubkey),payoutTxHex:t.payout_tx.tx_hex,assertTxHex:t.assert_tx.tx_hex}))}function T(e){return p.processPublicKeyToXOnly(e).toLowerCase()}function We(e,t){const r=(a,u,h)=>{throw new Error(`Deposit terms ${a} (${String(u)}) does not match the vault's version-locked signing context (${String(h)}); refusing to sign payouts against terms that describe a different graph.`)},n=[["protocolFeeRate",e.protocolFeeRate,t.protocolFeeRate],["vaultCoreVersion",e.vaultCoreVersion,t.vaultCoreVersion],["timelockPegin",e.timelockPegin,t.timelockPegin],["timelockAssert",e.timelockAssert,t.timelockAssert]];for(const[a,u,h]of n)u!==h&&r(a,u,h);const s=a=>a.map(T).sort(),c=(a,u)=>{const h=s(a),l=s(u);return h.length===l.length&&h.every((d,g)=>d===l[g])};c(e.vaultKeeperBtcPubkeys,t.vaultKeeperBtcPubkeys)||r("vaultKeeperBtcPubkeys",e.vaultKeeperBtcPubkeys.join(","),t.vaultKeeperBtcPubkeys.join(",")),c(e.universalChallengerBtcPubkeys,t.universalChallengerBtcPubkeys)||r("universalChallengerBtcPubkeys",e.universalChallengerBtcPubkeys.join(","),t.universalChallengerBtcPubkeys.join(","));const i=T(t.vaultProviderBtcPubkey),o=e.vaults.map(a=>T(a.vaultProviderBtcPubkey));o.includes(i)||r("vaults[].vaultProviderBtcPubkey",o.join(",")||"<no vaults>",t.vaultProviderBtcPubkey)}function Ye(e,t,r,n){const s=T(n),c=[T(t),...r.map(T)],i=new Set(c);if(i.size!==c.length)throw new Error("Cannot validate claimer set: signing context contains duplicate vault provider or vault keeper key");if(i.has(s))throw new Error("Cannot validate claimer set: depositor key overlaps with vault provider or vault keeper set");const o=e.map(d=>T(d.claimer_pubkey));if(new Set(o).size!==o.length)throw new Error("Presign response contains duplicate claimer entries");const a=o.filter(d=>d!==s),u=new Set(a),h=c.filter(d=>!u.has(d)),l=a.filter(d=>!i.has(d));if(h.length>0||l.length>0)throw new Error("Presign response claimer set does not match expected (vault provider ∪ vault keepers)"+(h.length>0?` (missing: ${h.join(", ")})`:"")+(l.length>0?` (unexpected: ${l.join(", ")})`:""))}function se(e,t){return{vaultCoreVersion:t.vaultCoreVersion,payoutTxHex:e.payoutTxHex,peginTxHex:t.peginTxHex,assertTxHex:e.assertTxHex,vaultProviderBtcPubkey:t.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:t.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:t.universalChallengerBtcPubkeys,depositorBtcPubkey:t.depositorBtcPubkey,timelockPegin:t.timelockPegin,timelockAssert:t.timelockAssert,registeredPayoutScriptPubKey:t.registeredPayoutScriptPubKey,claimerBtcPubkey:e.claimerPubkeyXOnly,commissionBps:t.commissionBps,protocolFeeRate:t.protocolFeeRate,councilMembers:t.councilMembers,councilQuorum:t.councilQuorum,vkClaimerPayoutScriptPubKeys:t.vkClaimerPayoutScriptPubKeys,vpCommissionScriptPubKey:t.vpCommissionScriptPubKey}}async function Ze(e,t,r,n){const s=new C.PayoutManager({network:t.network,btcWallet:e}),c=r.length;n==null||n(0,c);let i;if(s.supportsBatchSigning())i=(await s.signPayoutTransactionsBatch(r.map(u=>se(u,t)))).map(u=>u.payoutSignature);else{i=[];for(let a=0;a<r.length;a++){n==null||n(a,c);const u=await s.signPayoutTransaction(se(r[a],t));i.push(u.signature)}}const o={};for(let a=0;a<r.length;a++)o[r[a].claimerPubkeyXOnly]={payout_signature:i[a]};return n==null||n(c,c),o}async function Je(e){const{statusReader:t,presignClient:r,btcWallet:n,peginTxid:s,depositorPk:c,signingContext:i,depositTerms:o,timeoutMs:a=Ge,signal:u,onProgress:h}=e,l=await Z({statusReader:t,peginTxid:s,targetStatuses:je,timeoutMs:a,signal:u});if(fe.has(l))return;if(u==null||u.throwIfAborted(),o!==void 0&&We(o,i),C.supportsDepositApproval(n)){if(!o)throw new Error("runDepositorPresignFlow: this wallet requires approved deposit terms but none were provided. Fresh deposits must pass PreparePeginResult.depositTerms; resume flows must rebuild them from on-chain state (the vault app's rebuildDepositTerms).");typeof n.validateDepositTerms=="function"&&await n.validateDepositTerms(o),await n.approveDepositTerms(o)}const d=await r.requestDepositorPresignTransactions({pegin_txid:s,depositor_pk:c},u);u==null||u.throwIfAborted();const g=T(c);Ye(d.txs,i.vaultProviderBtcPubkey,i.vaultKeeperBtcPubkeys,c);const f=d.txs.filter(y=>T(y.claimer_pubkey)!==g),b=Qe(f),P=await Ze(n,i,b,h);u==null||u.throwIfAborted();const m=await ge({depositorGraph:d.depositor_graph,btcWallet:n,signingContext:{vaultCoreVersion:i.vaultCoreVersion,peginTxHex:i.peginTxHex,depositorBtcPubkey:c,vaultProviderBtcPubkey:i.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:i.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:i.universalChallengerBtcPubkeys,timelockPegin:i.timelockPegin,timelockAssert:i.timelockAssert,councilMembers:i.councilMembers,councilQuorum:i.councilQuorum,network:i.network,registeredPayoutScriptPubKey:i.registeredPayoutScriptPubKey,protocolFeeRate:i.protocolFeeRate,vkClaimerPayoutScriptPubKeys:i.vkClaimerPayoutScriptPubKeys,vpCommissionScriptPubKey:i.vpCommissionScriptPubKey}});u==null||u.throwIfAborted();const v={...P};v[p.stripHexPrefix(c)]=m.payout_signatures,await r.submitDepositorPresignatures({pegin_txid:s,depositor_pk:c,signatures:v,depositor_claimer_presignatures:m},u)}const et=300*1e3,tt=new Set([x.DaemonStatus.PENDING_DEPOSITOR_WOTS_PK,...x.POST_WOTS_STATUSES]);async function rt(e){const{statusReader:t,wotsSubmitter:r,peginTxid:n,depositorPk:s,wotsPublicKeys:c,timeoutMs:i=et,signal:o}=e;o==null||o.throwIfAborted();const a=await Z({statusReader:t,peginTxid:n,targetStatuses:tt,timeoutMs:i,signal:o});x.POST_WOTS_STATUSES.has(a)||(o==null||o.throwIfAborted(),await r.submitDepositorWotsKey({pegin_txid:n,depositor_pk:s,wots_public_keys:c},o))}function I(e){return e.registration||e.operation}function Pe(e,t,r){const n=p.canonicalizeBtcPubkey(e);return{registration:n===p.canonicalizeBtcPubkey(t),operation:n===p.canonicalizeBtcPubkey(r)}}function M(e,t,r){const n=K(e);return{registration:ae(n,K(t)),operation:ae(n,K(r))}}function K(e){return e.map(p.canonicalizeBtcPubkey).sort()}function ae(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}async function nt(e){const{vaultProviderEthAddress:t,hintBtcPubkey:r,registrationBtcPubkey:n,readCurrentOperationBtcPubkey:s,context:c}=e;if(!r)return;const i=p.canonicalizeBtcPubkey(r);if(i===p.canonicalizeBtcPubkey(n))return;const o=p.canonicalizeBtcPubkey(await s());if(i!==o)throw new Error(`Vault provider BTC pubkey mismatch for ${t}: indexer hint matches neither the registration key nor the current operation key on-chain.${c?` ${c}`:""}`)}function H(e,t,r){const n=`${e} operation key (admin=${t.ethAddress})`,s=oe.assertOnChainBtcPubkey(t.btcPubKey,`${e} roster key (admin=${t.ethAddress})`),c=oe.assertOnChainBtcPubkey(r,n);return{adminAddress:t.ethAddress,genesisBtcPubkey:s,operationBtcPubkey:c,rotated:c!==s}}function ot(e){const t=new Map;for(const r of e){const n=t.get(r.operationBtcPubkey);if(n)throw new Error(`Participant operation key collision: ${n} and ${r.adminAddress} both resolve to operation key ${r.operationBtcPubkey}`);t.set(r.operationBtcPubkey,r.adminAddress)}}function ye(e,t,r){if(t.vaultKeepers.length!==e.vaultKeepers.length||t.universalChallengers.length!==e.universalChallengers.length)throw new Error(`Operation-key resolution returned ${t.vaultKeepers.length} keeper and ${t.universalChallengers.length} challenger keys for a roster of ${e.vaultKeepers.length} keepers and ${e.universalChallengers.length} challengers`);const n=H("vault provider",{ethAddress:e.vaultProviderEthAddress,btcPubKey:e.vaultProviderGenesisBtcPubkey},t.vaultProvider),s=e.vaultKeepers.map((i,o)=>H("vault keeper",i,t.vaultKeepers[o])),c=e.universalChallengers.map((i,o)=>H("universal challenger",i,t.universalChallengers[o]));return ot([n,...s,...c]),{vaultProvider:n,vaultKeepers:s,universalChallengers:c,vaultKeeperOperationKeysSorted:s.map(i=>i.operationBtcPubkey).sort(),universalChallengerOperationKeysSorted:c.map(i=>i.operationBtcPubkey).sort(),resolvedAt:r,query:e}}async function me(e){const t=await e.operationKeyReader.getCurrentOperationKeys(e.query);return ye(e.query,t,{mode:"current"})}async function ve(e){const t=await e.operationKeyReader.getOperationKeysAtEpochs(e.query,e.epochs);return ye(e.query,t,{mode:"epochs",epochs:e.epochs})}const ue=e=>e.map(p.canonicalizeBtcPubkey).sort();async function it(e){const{vaultRegistryReader:t,vaultKeeperReader:r,universalChallengerReader:n,vaultProviderEthAddress:s,applicationEntryPoint:c,expectedVaultProviderBtcPubkey:i,expectedVaultKeeperBtcPubkeys:o,expectedUniversalChallengerBtcPubkeys:a,operationKeyReader:u,onIndexerServingOperationKeys:h,onIndexerHintsInconsistent:l}=e,[d,g,f]=await Promise.all([t.getVaultProviderGenesisBtcPubKey(s),r.getCurrentVaultKeepersVersion(c),n.getLatestUniversalChallengersVersion()]),[b,P]=await Promise.all([r.getVaultKeepersByVersion(c,g),n.getUniversalChallengersByVersion(f)]),m={vaultProvider:p.canonicalizeBtcPubkey(d),vaultKeepers:ue(b.map(k=>k.btcPubKey)),universalChallengers:ue(P.map(k=>k.btcPubKey))},v=await me({operationKeyReader:u,query:{vaultProviderEthAddress:s,vaultProviderGenesisBtcPubkey:`0x${d}`,applicationEntryPoint:c,vaultKeepers:b,universalChallengers:P}}),y={vaultProvider:v.vaultProvider.operationBtcPubkey,vaultKeepers:[...v.vaultKeeperOperationKeysSorted],universalChallengers:[...v.universalChallengerOperationKeysSorted]},S=Pe(i,m.vaultProvider,y.vaultProvider),B=M(o,m.vaultKeepers,y.vaultKeepers),$=M(a,m.universalChallengers,y.universalChallengers);if(!I(S))throw new Error(`Vault provider BTC pubkey indexer hint does not match BTCVaultRegistry for ${s}. Refresh and try again.`);if(!I(B))throw new Error(`Vault keeper BTC pubkeys (v${g}) indexer set does not match ApplicationRegistry on-chain set. Refresh and try again.`);if(!I($))throw new Error(`Universal challenger BTC pubkeys (v${f}) indexer set does not match ProtocolParams on-chain set. Refresh and try again.`);const w=[S,B,$],ke=w.some(k=>k.registration&&!k.operation),ne=w.some(k=>k.operation&&!k.registration);if(ke&&ne){const k=`Indexer participant hints are internally inconsistent for vault provider ${s}: some roles match the registration keys while others match the rotated operation keys.`;throw l==null||l(k),new Error(`${k} Refresh and try again.`)}return ne&&(h==null||h(`Indexer is serving rotated operation keys for vault provider ${s}`)),{vaultProviderBtcPubkeyXOnly:y.vaultProvider,vaultKeeperBtcPubkeysSorted:y.vaultKeepers,universalChallengerBtcPubkeysSorted:y.universalChallengers,expectedAppVaultKeepersVersion:g,expectedUniversalChallengersVersion:f,registrationKeys:m,participantKeys:v}}function st(e){return/^[0-9a-fA-F]{64}$/.test(e)}function at(e){const{amountSats:t,minDeposit:r,maxDeposit:n,btcBalance:s,estimatedFeeSats:c,depositorClaimValue:i}=e;return!(t<=0n||t<r||n&&n>0n&&t>n||c==null||i==null||t+c+i>s)}function ut(e,t,r){return e<=0n?{valid:!1,error:"Deposit amount must be greater than zero"}:e<t?{valid:!1,error:`Minimum deposit is ${p.formatSatoshisToBtc(t)} BTC`}:r&&r>0n&&e>r?{valid:!1,error:`Maximum deposit is ${p.formatSatoshisToBtc(r)} BTC`}:{valid:!0}}function ct(e){const{amount:t,effectiveRemaining:r}=e;return r===null?{valid:!0}:r===0n?{valid:!1,error:"Supply cap reached — deposits temporarily paused"}:t>r?{valid:!1,error:`Vault size exceeds remaining capacity (${p.formatSatoshisToBtc(r)} BTC)`}:{valid:!0}}function lt(e,t){if(!e||e.length===0)return{valid:!1,error:"At least one vault provider must be selected"};const r=t.map(s=>s.toLowerCase());return e.filter(s=>!r.includes(s.toLowerCase())).length>0?{valid:!1,error:"Invalid vault provider selected"}:{valid:!0}}function be(e,t,r){if(!e||e.length===0)return{valid:!1,error:"At least one vault amount required"};for(let n=0;n<e.length;n++){const s=e[n];if(s<=0n)return{valid:!1,error:`Vault ${n+1} amount must be positive`};if(t&&s<t)return{valid:!1,error:`Vault ${n+1} amount ${p.formatSatoshisToBtc(s)} BTC is below minimum deposit ${p.formatSatoshisToBtc(t)} BTC`};if(r&&s>r)return{valid:!1,error:`Vault ${n+1} amount ${p.formatSatoshisToBtc(s)} BTC exceeds maximum deposit ${p.formatSatoshisToBtc(r)} BTC`}}return{valid:!0}}function we(e){const t=p.stripHexPrefix(e);return st(t)?{valid:!0}:{valid:!1,error:"Invalid pubkey format: must be 64 hex characters (32-byte x-only public key, no 0x prefix)"}}function ht(e){if(!e||e.length===0)throw new Error("No vault keepers available. The system requires at least one vault keeper to create a deposit.")}function pt(e){if(!e||e.length===0)throw new Error("No universal challengers available. The system requires at least one universal challenger to create a deposit.")}function dt(e){if(e.length===0)throw new Error("No spendable UTXOs available")}function gt(e){const{vaultAmounts:t,confirmedUTXOs:r,vaultProviderBtcPubkey:n,vaultKeeperBtcPubkeys:s,universalChallengerBtcPubkeys:c,minDeposit:i,maxDeposit:o}=e,a=be(t,i,o);if(!a.valid)throw new Error(a.error);const u=we(n);if(!u.valid)throw new Error(u.error);ht(s),pt(c),dt(r)}class J extends Error{constructor(t){super(t),this.name="ParticipantKeyDriftError"}}function ft(e){return e instanceof J||e instanceof Error&&e.name==="ParticipantKeyDriftError"}function ce(e,t,r){return t.length===r.length&&t.every((n,s)=>n===r[s])?null:`${e} expected [${t.join(", ")}], got [${r.join(", ")}]`}async function Pt(e){const{vaultRegistryReader:t,operationKeyReader:r,vaultIds:n,expected:s}=e,c=s.query;if(n.length===0)return;const i=await t.getVaultKeyEpochsBatch(n),o=[];for(const[a,u]of i.entries()){const h=n[a];let l;try{l=await ve({operationKeyReader:r,query:c,epochs:u})}catch(f){o.push(`vault ${h}: could not resolve participants at frozen epochs (vp=${u.vpKeyEpoch}, keeper=${u.appKeeperKeyEpoch}, uc=${u.ucKeyEpoch}): ${f.message}`);continue}l.vaultProvider.operationBtcPubkey!==s.vaultProvider.operationBtcPubkey&&o.push(`vault ${h}: vault provider key expected ${s.vaultProvider.operationBtcPubkey}, got ${l.vaultProvider.operationBtcPubkey}`);const d=ce(`vault ${h}: vault keeper keys`,s.vaultKeeperOperationKeysSorted,l.vaultKeeperOperationKeysSorted);d&&o.push(d);const g=ce(`vault ${h}: universal challenger keys`,s.universalChallengerOperationKeysSorted,l.universalChallengerOperationKeysSorted);g&&o.push(g)}if(o.length>0)throw new J(`Aborting BTC broadcast: participant operation keys changed during registration (${o.join("; ")}). The Pre-PegIn was not broadcast; the registered ETH vault will time out per protocol rules.`)}class ee extends Error{constructor(t){super(t),this.name="RegisteredVaultVersionMismatchError"}}function yt(e){return e instanceof ee||e instanceof Error&&e.name==="RegisteredVaultVersionMismatchError"}async function mt(e){const{vaultRegistryReader:t,vaultIds:r,expectedOffchainParamsVersion:n,expectedAppVaultKeepersVersion:s,expectedUniversalChallengersVersion:c,expectedVaultCoreVersion:i}=e,o=await t.getProtocolInfoBatch(r),a=[];if(o.forEach((u,h)=>{const l=r[h];u.offchainParamsVersion!==n&&a.push(`vault ${l}: offchainParams expected v${n}, got v${u.offchainParamsVersion}`),u.appVaultKeepersVersion!==s&&a.push(`vault ${l}: appVaultKeepers expected v${s}, got v${u.appVaultKeepersVersion}`),u.universalChallengersVersion!==c&&a.push(`vault ${l}: universalChallengers expected v${c}, got v${u.universalChallengersVersion}`),u.vaultCoreVersion!==i&&a.push(`vault ${l}: vaultCoreVersion expected v${i} (build-time active), got v${u.vaultCoreVersion}`)}),a.length>0)throw new ee(`Aborting BTC broadcast: signer-set or offchain-params versions changed during registration (${a.join("; ")}). The Pre-PegIn was not broadcast; the registered ETH vault will time out per protocol rules.`)}var te=(e=>(e.CLAIM_EVENT_RECEIVED="ClaimEventReceived",e.CLAIM_BROADCAST="ClaimBroadcast",e.ASSERT_BROADCAST="AssertBroadcast",e.PAYOUT_BROADCAST="PayoutBroadcast",e.PAYOUT_BLOCKED="PayoutBlocked",e))(te||{});const vt=new Set(["PayoutBroadcast","PayoutBlocked"]);function bt(e){return Object.values(te).includes(e)}function wt(e){return!!e&&vt.has(e)}class Ee extends Error{constructor(r,n){super(`Refund not yet mature (BIP68 not final): ${n.message}`);A(this,"vaultId");A(this,"cause");this.name="BIP68NotMatureError",this.vaultId=r,this.cause=n}}const Et=/^0x[0-9a-fA-F]{64}$/,xt=/^(?:0x)?(?:[0-9a-fA-F]{2})+$/,xe=/^(?:0x)?(?:[0-9a-fA-F]{64}|[0-9a-fA-F]{66})$/,re=160,U=2e3,L=10n,X=100n;function kt(e){if(!Number.isFinite(e)||e<=0)throw new Error(`feeRateSatsVb must be a positive finite number, got ${e}`);return BigInt(Math.ceil(e*re))}const Tt=1,St=/non-BIP68-final/i;function z(e,t){if(e.length!==66)throw new Error(`${t} must be 32 bytes (66 hex chars with 0x prefix), got length ${e.length}`);if(!Et.test(e))throw new Error(`${t} must contain only hex characters after the 0x prefix`)}function D(e,t){if(!Number.isInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer, got ${e}`)}function Rt(e){if(z(e.hashlock,"hashlock"),!Number.isInteger(e.htlcVout)||e.htlcVout<0)throw new Error(`htlcVout must be a non-negative integer, got ${e.htlcVout}`);if(!Array.isArray(e.batch)||e.batch.length===0)throw new Error("batch must be a non-empty array of HTLC entries");if(e.htlcVout>=e.batch.length)throw new Error(`htlcVout ${e.htlcVout} is out of range for batch of size ${e.batch.length}`);for(let r=0;r<e.batch.length;r++){const n=e.batch[r];if(z(n.hashlock,`batch[${r}].hashlock`),!Number.isInteger(n.htlcVout)||n.htlcVout!==r)throw new Error(`batch[${r}].htlcVout must equal ${r} (contiguous vout-ordered vector), got ${n.htlcVout}`);if(typeof n.amount!="bigint"||n.amount<=0n)throw new Error(`batch[${r}].amount must be a positive bigint, got ${n.amount}`)}const t=e.batch[e.htlcVout];if(t.hashlock.toLowerCase()!==e.hashlock.toLowerCase())throw new Error(`batch[${e.htlcVout}].hashlock (${t.hashlock}) does not match target hashlock (${e.hashlock})`);if(t.amount!==e.amount)throw new Error(`batch[${e.htlcVout}].amount (${t.amount}) does not match target amount (${e.amount})`);if(D(e.offchainParamsVersion,"offchainParamsVersion"),D(e.appVaultKeepersVersion,"appVaultKeepersVersion"),D(e.universalChallengersVersion,"universalChallengersVersion"),F.assertValidVaultCoreVersion(e.vaultCoreVersion,"VaultRefundData.vaultCoreVersion"),typeof e.unsignedPrePeginTxHex!="string"||e.unsignedPrePeginTxHex.length===0)throw new Error("unsignedPrePeginTxHex must be a non-empty hex string");if(!xt.test(e.unsignedPrePeginTxHex))throw new Error("unsignedPrePeginTxHex must be a hex byte string (optional 0x prefix, even length)");if(!e.depositorBtcPubkey||!xe.test(e.depositorBtcPubkey))throw new Error("depositorBtcPubkey must be 32 or 33 bytes of hex (optional 0x prefix)");if(typeof e.amount!="bigint"||e.amount<=0n)throw new Error(`amount must be a positive bigint, got ${e.amount}`)}function At(e){if(!e.vaultProviderPubkey||!xe.test(e.vaultProviderPubkey))throw new Error("vaultProviderPubkey must be 32 or 33 bytes of hex");if(e.vaultKeeperPubkeys.length===0)throw new Error("vaultKeeperPubkeys must be non-empty");if(e.universalChallengerPubkeys.length===0)throw new Error("universalChallengerPubkeys must be non-empty");if(!Number.isInteger(e.timelockRefund)||e.timelockRefund<=0)throw new Error(`timelockRefund must be a positive integer, got ${e.timelockRefund}`);if(typeof e.feeRate!="bigint"||e.feeRate<=0n)throw new Error(`protocol feeRate must be a positive bigint, got ${e.feeRate}`);if(typeof e.minPeginFeeRate!="bigint"||e.minPeginFeeRate<=0n)throw new Error(`minPeginFeeRate must be a positive bigint, got ${e.minPeginFeeRate}`);if(!Number.isInteger(e.numLocalChallengers)||e.numLocalChallengers<0)throw new Error("numLocalChallengers must be a non-negative integer");if(!Number.isInteger(e.councilQuorum)||!Number.isInteger(e.councilSize)||e.councilQuorum<=0||e.councilSize<=0||e.councilQuorum>e.councilSize)throw new Error(`councilQuorum (${e.councilQuorum}) must be in [1, councilSize=${e.councilSize}]`)}function _t(e){const t=R.Psbt.fromHex(e);try{t.finalizeAllInputs()}catch(r){const n=r instanceof Error?r.message:String(r);if(!n.includes("already finalized"))throw new Error(`Failed to finalize refund PSBT: ${n}`)}return t.extractTransaction().toHex()}async function Ct(e){const{vaultId:t,readVault:r,readPrePeginContext:n,feeRate:s,signPsbt:c,broadcastTx:i,signal:o}=e;o==null||o.throwIfAborted(),z(t,"vaultId");const a=await r();Rt(a),o==null||o.throwIfAborted();const u=await n(a);if(At(u),o==null||o.throwIfAborted(),!Number.isFinite(s)||s<=0)throw new Error(`feeRate must be a positive number, got ${s}`);if(s>U)throw new Error(`feeRate ${s} sat/vB exceeds refund safety cap ${U} sat/vB; refusing to sign refund.`);const h=BigInt(Math.ceil(s*re)),l=a.amount*L/X;if(h>l)throw new Error(`Refund fee ${h} sats exceeds the per-vault safety cap of ${l} sats (${L}/${X} of vault.amount=${a.amount}); refusing to sign refund.`);o==null||o.throwIfAborted();const d=p.processPublicKeyToXOnly(a.depositorBtcPubkey),g=p.stripHexPrefix(a.unsignedPrePeginTxHex),f=C.findAuthAnchorOpReturn(g);if(f!==void 0&&f.vout!==a.batch.length)throw new Error(`Auth-anchor OP_RETURN at vout ${f.vout} does not match batch size (${a.batch.length} HTLC outputs expect the anchor at vout ${a.batch.length}). Refund refused — sibling HTLC vector is incomplete.`);const b=f==null?void 0:f.hash;let P;try{P=R.Transaction.fromHex(g)}catch(w){throw new Error(`Failed to parse funded Pre-PegIn transaction hex: ${w instanceof Error?w.message:String(w)}`)}if(P.outs.length<a.batch.length)throw new Error(`Funded Pre-PegIn tx has ${P.outs.length} outputs but batch requires at least ${a.batch.length} HTLC outputs. Refund refused — funded tx shape disagrees with sibling vector.`);const{psbtHex:m}=await _.buildRefundPsbt({prePeginParams:{vaultCoreVersion:a.vaultCoreVersion,depositorPubkey:d,vaultProviderPubkey:p.stripHexPrefix(u.vaultProviderPubkey),vaultKeeperPubkeys:u.vaultKeeperPubkeys.map(p.stripHexPrefix),universalChallengerPubkeys:u.universalChallengerPubkeys.map(p.stripHexPrefix),hashlocks:a.batch.map(w=>p.stripHexPrefix(w.hashlock)),timelockRefund:u.timelockRefund,pegInAmounts:a.batch.map(w=>w.amount),feeRate:u.feeRate,minPeginFeeRate:u.minPeginFeeRate,numLocalChallengers:u.numLocalChallengers,councilQuorum:u.councilQuorum,councilSize:u.councilSize,network:u.network,authAnchorHash:b},fundedPrePeginTxHex:g,htlcVout:a.htlcVout,refundFee:h,hashlock:p.stripHexPrefix(a.hashlock)});o==null||o.throwIfAborted();const v=V.createTaprootScriptPathSignOptions(a.depositorBtcPubkey,Tt),y=await c(m,v);E.assertPsbtUnsignedTxMatches({requestedPsbtHex:m,returnedPsbtHex:y});const S=0,B=E.extractPayoutSignature(y,d,S);E.assertScriptPathSchnorrSignature({requestedPsbtHex:m,signatureHex:B,signerXOnlyPubkeyHex:d,inputIndex:S});const $=_t(y);o==null||o.throwIfAborted();try{return await i($)}catch(w){throw w instanceof Error&&St.test(w.message)?new Ee(t,w):w}}class q extends Error{constructor(r,n,s){super(r);A(this,"feeSats");A(this,"sweptTotalSats");this.name="ReclaimUneconomicalError",this.feeSats=n,this.sweptTotalSats=s}}const G=2e3,j=25n,Q=100n,Bt=10n;function $t(e){const t=R.Psbt.fromHex(e);try{t.finalizeAllInputs()}catch(r){const n=r instanceof Error?r.message:String(r);if(!n.includes("already finalized"))throw new Error(`Failed to finalize reclaim PSBT: ${n}`)}return t.extractTransaction().toHex()}async function It(e){const{vaultIds:t,depositorBtcPubkey:r,readVaults:n,feeRate:s,signPsbt:c,broadcastTx:i,signal:o}=e;if(o==null||o.throwIfAborted(),t.length===0)throw new Error("Reclaim requires at least one vault id; got none.");if(!Number.isFinite(s)||s<=0)throw new Error(`feeRate must be a positive number, got ${s}`);if(s>G)throw new q(`Fee rate ${s} sat/vB exceeds the reclaim safety cap of ${G} sat/vB; refusing to sign.`,0n,0n);const a=await n();if(o==null||o.throwIfAborted(),a.length!==t.length)throw new Error(`readVaults returned ${a.length} reserves for ${t.length} vault id(s); refusing to sweep a set that does not match the request.`);const u=p.processPublicKeyToXOnly(r),h=a.map(v=>({depositorSignedPeginTxHex:v.depositorSignedPeginTxHex,observed:v.observed,expectedValue:v.expectedClaimValue})),l=_.estimateReclaimFeeSats(s,h.length),d=h.reduce((v,y)=>v+y.expectedValue,0n),g=d*j/Q;if(l>g)throw new q(`Reclaim fee ${l} sats exceeds ${j}/${Q} of the swept total (${d} sats, cap ${g} sats). The reserve is not at risk — it stays where it is until fee rates fall.`,l,d);o==null||o.throwIfAborted();const{psbtHex:f}=_.buildReclaimPsbt({depositorPubkey:u,inputs:h,feeSats:l});o==null||o.throwIfAborted();const b=V.createTaprootScriptPathSignOptions(r,h.length),P=await c(f,b);E.assertPsbtUnsignedTxMatches({requestedPsbtHex:f,returnedPsbtHex:P}),h.forEach((v,y)=>{const S=E.extractPayoutSignature(P,u,y);E.assertScriptPathSchnorrSignature({requestedPsbtHex:f,signatureHex:S,signerXOnlyPubkeyHex:u,inputIndex:y})});const m=$t(P);return o==null||o.throwIfAborted(),i(m)}exports.BIP68NotMatureError=Ee;exports.ClaimerPegoutStatusValue=te;exports.PEGIN_ETH_CONFIRMATIONS=pe;exports.ParticipantKeyDriftError=J;exports.PeginRegistrationMissingError=W;exports.PeginRegistrationNotFinalError=Y;exports.RECLAIM_MAX_FEE_FRACTION_DENOMINATOR=Q;exports.RECLAIM_MAX_FEE_FRACTION_NUMERATOR=j;exports.RECLAIM_MAX_FEE_RATE_SATS_VB=G;exports.RECLAIM_WARN_FEE_FRACTION_NUMERATOR=Bt;exports.REFUND_MAX_FEE_FRACTION_DENOMINATOR=X;exports.REFUND_MAX_FEE_FRACTION_NUMERATOR=L;exports.REFUND_MAX_FEE_RATE_SATS_VB=U;exports.REFUND_VSIZE=re;exports.ReclaimUneconomicalError=q;exports.RegisteredVaultVersionMismatchError=ee;exports.activateVault=Ie;exports.activateVaultAndRedeem=Ve;exports.assertVaultProviderHintAccepted=nt;exports.buildAndBroadcastReclaim=It;exports.buildAndBroadcastRefund=Ct;exports.estimateRefundFeeSats=kt;exports.isDepositAmountValid=at;exports.isHintAccepted=I;exports.isParticipantKeyDriftError=ft;exports.isPeginRegistrationMissingError=de;exports.isPeginRegistrationNotFinalError=He;exports.isPegoutTerminalStatus=wt;exports.isRecognizedPegoutStatus=bt;exports.isRegisteredVaultVersionMismatchError=yt;exports.matchKeyHint=Pe;exports.matchKeySetHint=M;exports.resolveCurrentParticipantKeys=me;exports.resolveParticipantKeysAtEpochs=ve;exports.runDepositorPresignFlow=Je;exports.signDepositorGraph=ge;exports.submitWotsPublicKey=rt;exports.validateDepositAmount=ut;exports.validateMultiVaultDepositInputs=gt;exports.validateOnChainParticipantKeys=it;exports.validateProviderSelection=lt;exports.validateRemainingCapacity=ct;exports.validateVaultAmounts=be;exports.validateVaultProviderPubkey=we;exports.verifyRegisteredParticipantKeys=Pt;exports.verifyRegisteredVaultVersions=mt;exports.waitForPeginRegistrationDepth=De;exports.waitForPeginStatus=Z;
|
|
2
|
-
//# sourceMappingURL=buildAndBroadcastReclaim-iNJfx0ZG.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"challengeAssert-BNQ8sToz.js","sources":["../src/tbv/core/primitives/psbt/challengeAssert.ts"],"sourcesContent":["/**\n * ChallengeAssert PSBT Builder\n *\n * Builds an unsigned PSBT for a ChallengeAssert transaction\n * (depositor-as-claimer path, per challenger). ChallengeAssert is split across\n * two single-input transactions — ChallengeAssertX (spends the challenger's\n * ConnectorX Assert output) and ChallengeAssertY (spends ConnectorY). This\n * builder handles one such transaction; the depositor signs every input, each\n * with its own taproot script derived from that input's connector params.\n *\n * @module primitives/psbt/challengeAssert\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — ChallengeAssertX / ChallengeAssertY\n */\n\nimport {\n type ChallengeAssertConnectorParams,\n getChallengeAssertScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n inputTxidHex,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a ChallengeAssert PSBT\n */\nexport interface ChallengeAssertParams {\n /** ChallengeAssert transaction hex (unsigned) */\n challengeAssertTxHex: string;\n /** Authoritative Assert transaction hex — every input must spend an Assert output */\n assertTxHex: string;\n /** Per-input connector params (one per input/segment, determines the taproot script) */\n connectorParamsPerInput: ChallengeAssertConnectorParams[];\n}\n\n/**\n * Build unsigned ChallengeAssert PSBT.\n *\n * Each input has its own taproot script derived from its connector params; the\n * number of connector params must match the transaction's input count. The\n * depositor signs all inputs. Every prevout is derived from the authoritative\n * Assert transaction, never trusted from external input.\n *\n * @param params - ChallengeAssert parameters\n * @returns Unsigned PSBT hex ready for signing\n *\n * @throws If the number of connector params does not match the number of inputs\n * @throws If any input does not reference assertTxHex\n * @throws If any referenced Assert output is missing\n * @throws If two inputs reference the same Assert output index\n */\nexport async function buildChallengeAssertPsbt(\n params: ChallengeAssertParams,\n): Promise<string> {\n const challengeAssertTx = Transaction.fromHex(\n stripHexPrefix(params.challengeAssertTxHex),\n );\n const assertTx = Transaction.fromHex(stripHexPrefix(params.assertTxHex));\n const assertTxid = assertTx.getId();\n\n if (params.connectorParamsPerInput.length !== challengeAssertTx.ins.length) {\n throw new Error(\n `Expected ${challengeAssertTx.ins.length} connector params, got ${params.connectorParamsPerInput.length}`,\n );\n }\n\n const seenAssertOutputs = new Set<number>();\n for (let i = 0; i < challengeAssertTx.ins.length; i++) {\n const input = challengeAssertTx.ins[i];\n const inputTxid = inputTxidHex(input);\n if (inputTxid !== assertTxid) {\n throw new Error(\n `ChallengeAssert input ${i} must spend an Assert output. ` +\n `Expected txid ${assertTxid}, got ${inputTxid}`,\n );\n }\n if (!assertTx.outs[input.index]) {\n throw new Error(\n `Assert output ${input.index} not found for ChallengeAssert input ${i} (txid: ${assertTxid})`,\n );\n }\n if (seenAssertOutputs.has(input.index)) {\n throw new Error(\n `ChallengeAssert input ${i} duplicates Assert output index ${input.index}`,\n );\n }\n seenAssertOutputs.add(input.index);\n }\n\n const scriptInfos = await Promise.all(\n params.connectorParamsPerInput.map((cp) => getChallengeAssertScriptInfo(cp)),\n );\n\n const psbt = new Psbt();\n psbt.setVersion(challengeAssertTx.version);\n psbt.setLocktime(challengeAssertTx.locktime);\n\n for (let i = 0; i < challengeAssertTx.ins.length; i++) {\n const input = challengeAssertTx.ins[i];\n const assertPrevOut = assertTx.outs[input.index];\n\n const { script, controlBlock } = scriptInfos[i];\n const scriptBytes = hexToUint8Array(script);\n const controlBlockBytes = hexToUint8Array(controlBlock);\n\n psbt.addInput({\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: assertPrevOut.script,\n value: assertPrevOut.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n }\n\n for (const output of challengeAssertTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n"],"names":["buildChallengeAssertPsbt","params","challengeAssertTx","Transaction","stripHexPrefix","assertTx","assertTxid","seenAssertOutputs","i","input","inputTxid","inputTxidHex","scriptInfos","cp","getChallengeAssertScriptInfo","psbt","Psbt","assertPrevOut","script","controlBlock","scriptBytes","hexToUint8Array","controlBlockBytes","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output"],"mappings":";;;;AAyDA,eAAsBA,EACpBC,GACiB;AACjB,QAAMC,IAAoBC,EAAY;AAAA,IACpCC,EAAeH,EAAO,oBAAoB;AAAA,EAAA,GAEtCI,IAAWF,EAAY,QAAQC,EAAeH,EAAO,WAAW,CAAC,GACjEK,IAAaD,EAAS,MAAA;AAE5B,MAAIJ,EAAO,wBAAwB,WAAWC,EAAkB,IAAI;AAClE,UAAM,IAAI;AAAA,MACR,YAAYA,EAAkB,IAAI,MAAM,0BAA0BD,EAAO,wBAAwB,MAAM;AAAA,IAAA;AAI3G,QAAMM,wBAAwB,IAAA;AAC9B,WAASC,IAAI,GAAGA,IAAIN,EAAkB,IAAI,QAAQM,KAAK;AACrD,UAAMC,IAAQP,EAAkB,IAAIM,CAAC,GAC/BE,IAAYC,EAAaF,CAAK;AACpC,QAAIC,MAAcJ;AAChB,YAAM,IAAI;AAAA,QACR,yBAAyBE,CAAC,+CACPF,CAAU,SAASI,CAAS;AAAA,MAAA;AAGnD,QAAI,CAACL,EAAS,KAAKI,EAAM,KAAK;AAC5B,YAAM,IAAI;AAAA,QACR,iBAAiBA,EAAM,KAAK,wCAAwCD,CAAC,WAAWF,CAAU;AAAA,MAAA;AAG9F,QAAIC,EAAkB,IAAIE,EAAM,KAAK;AACnC,YAAM,IAAI;AAAA,QACR,yBAAyBD,CAAC,mCAAmCC,EAAM,KAAK;AAAA,MAAA;AAG5E,IAAAF,EAAkB,IAAIE,EAAM,KAAK;AAAA,EACnC;AAEA,QAAMG,IAAc,MAAM,QAAQ;AAAA,IAChCX,EAAO,wBAAwB,IAAI,CAACY,MAAOC,EAA6BD,CAAE,CAAC;AAAA,EAAA,GAGvEE,IAAO,IAAIC,EAAA;AACjB,EAAAD,EAAK,WAAWb,EAAkB,OAAO,GACzCa,EAAK,YAAYb,EAAkB,QAAQ;AAE3C,WAASM,IAAI,GAAGA,IAAIN,EAAkB,IAAI,QAAQM,KAAK;AACrD,UAAMC,IAAQP,EAAkB,IAAIM,CAAC,GAC/BS,IAAgBZ,EAAS,KAAKI,EAAM,KAAK,GAEzC,EAAE,QAAAS,GAAQ,cAAAC,MAAiBP,EAAYJ,CAAC,GACxCY,IAAcC,EAAgBH,CAAM,GACpCI,IAAoBD,EAAgBF,CAAY;AAEtD,IAAAJ,EAAK,SAAS;AAAA,MACZ,MAAMN,EAAM;AAAA,MACZ,OAAOA,EAAM;AAAA,MACb,UAAUA,EAAM;AAAA,MAChB,aAAa;AAAA,QACX,QAAQQ,EAAc;AAAA,QACtB,OAAOA,EAAc;AAAA,MAAA;AAAA,MAEvB,eAAe;AAAA,QACb;AAAA,UACE,aAAaM;AAAA,UACb,QAAQC,EAAO,KAAKJ,CAAW;AAAA,UAC/B,cAAcI,EAAO,KAAKF,CAAiB;AAAA,QAAA;AAAA,MAC7C;AAAA,MAEF,gBAAgBE,EAAO,KAAKC,CAAiB;AAAA,IAAA,CAC9C;AAAA,EACH;AAEA,aAAWC,KAAUxB,EAAkB;AACrC,IAAAa,EAAK,UAAU;AAAA,MACb,QAAQW,EAAO;AAAA,MACf,OAAOA,EAAO;AAAA,IAAA,CACf;AAGH,SAAOX,EAAK,MAAA;AACd;"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const x=require("@babylonlabs-io/babylon-tbv-rust-wasm"),a=require("buffer"),l=require("bitcoinjs-lib"),s=require("./bitcoin-m84N5a8o.cjs");async function P(r){const n=l.Transaction.fromHex(s.stripHexPrefix(r.challengeAssertTxHex)),c=l.Transaction.fromHex(s.stripHexPrefix(r.assertTxHex)),u=c.getId();if(r.connectorParamsPerInput.length!==n.ins.length)throw new Error(`Expected ${n.ins.length} connector params, got ${r.connectorParamsPerInput.length}`);const p=new Set;for(let t=0;t<n.ins.length;t++){const e=n.ins[t],i=s.inputTxidHex(e);if(i!==u)throw new Error(`ChallengeAssert input ${t} must spend an Assert output. Expected txid ${u}, got ${i}`);if(!c.outs[e.index])throw new Error(`Assert output ${e.index} not found for ChallengeAssert input ${t} (txid: ${u})`);if(p.has(e.index))throw new Error(`ChallengeAssert input ${t} duplicates Assert output index ${e.index}`);p.add(e.index)}const f=await Promise.all(r.connectorParamsPerInput.map(t=>x.getChallengeAssertScriptInfo(t))),o=new l.Psbt;o.setVersion(n.version),o.setLocktime(n.locktime);for(let t=0;t<n.ins.length;t++){const e=n.ins[t],i=c.outs[e.index],{script:d,controlBlock:h}=f[t],g=s.hexToUint8Array(d),A=s.hexToUint8Array(h);o.addInput({hash:e.hash,index:e.index,sequence:e.sequence,witnessUtxo:{script:i.script,value:i.value},tapLeafScript:[{leafVersion:s.TAPSCRIPT_LEAF_VERSION,script:a.Buffer.from(g),controlBlock:a.Buffer.from(A)}],tapInternalKey:a.Buffer.from(x.tapInternalPubkey)})}for(const t of n.outs)o.addOutput({script:t.script,value:t.value});return o.toHex()}exports.buildChallengeAssertPsbt=P;
|
|
2
|
-
//# sourceMappingURL=challengeAssert-BrpC3-cQ.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"challengeAssert-BrpC3-cQ.cjs","sources":["../src/tbv/core/primitives/psbt/challengeAssert.ts"],"sourcesContent":["/**\n * ChallengeAssert PSBT Builder\n *\n * Builds an unsigned PSBT for a ChallengeAssert transaction\n * (depositor-as-claimer path, per challenger). ChallengeAssert is split across\n * two single-input transactions — ChallengeAssertX (spends the challenger's\n * ConnectorX Assert output) and ChallengeAssertY (spends ConnectorY). This\n * builder handles one such transaction; the depositor signs every input, each\n * with its own taproot script derived from that input's connector params.\n *\n * @module primitives/psbt/challengeAssert\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — ChallengeAssertX / ChallengeAssertY\n */\n\nimport {\n type ChallengeAssertConnectorParams,\n getChallengeAssertScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n inputTxidHex,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a ChallengeAssert PSBT\n */\nexport interface ChallengeAssertParams {\n /** ChallengeAssert transaction hex (unsigned) */\n challengeAssertTxHex: string;\n /** Authoritative Assert transaction hex — every input must spend an Assert output */\n assertTxHex: string;\n /** Per-input connector params (one per input/segment, determines the taproot script) */\n connectorParamsPerInput: ChallengeAssertConnectorParams[];\n}\n\n/**\n * Build unsigned ChallengeAssert PSBT.\n *\n * Each input has its own taproot script derived from its connector params; the\n * number of connector params must match the transaction's input count. The\n * depositor signs all inputs. Every prevout is derived from the authoritative\n * Assert transaction, never trusted from external input.\n *\n * @param params - ChallengeAssert parameters\n * @returns Unsigned PSBT hex ready for signing\n *\n * @throws If the number of connector params does not match the number of inputs\n * @throws If any input does not reference assertTxHex\n * @throws If any referenced Assert output is missing\n * @throws If two inputs reference the same Assert output index\n */\nexport async function buildChallengeAssertPsbt(\n params: ChallengeAssertParams,\n): Promise<string> {\n const challengeAssertTx = Transaction.fromHex(\n stripHexPrefix(params.challengeAssertTxHex),\n );\n const assertTx = Transaction.fromHex(stripHexPrefix(params.assertTxHex));\n const assertTxid = assertTx.getId();\n\n if (params.connectorParamsPerInput.length !== challengeAssertTx.ins.length) {\n throw new Error(\n `Expected ${challengeAssertTx.ins.length} connector params, got ${params.connectorParamsPerInput.length}`,\n );\n }\n\n const seenAssertOutputs = new Set<number>();\n for (let i = 0; i < challengeAssertTx.ins.length; i++) {\n const input = challengeAssertTx.ins[i];\n const inputTxid = inputTxidHex(input);\n if (inputTxid !== assertTxid) {\n throw new Error(\n `ChallengeAssert input ${i} must spend an Assert output. ` +\n `Expected txid ${assertTxid}, got ${inputTxid}`,\n );\n }\n if (!assertTx.outs[input.index]) {\n throw new Error(\n `Assert output ${input.index} not found for ChallengeAssert input ${i} (txid: ${assertTxid})`,\n );\n }\n if (seenAssertOutputs.has(input.index)) {\n throw new Error(\n `ChallengeAssert input ${i} duplicates Assert output index ${input.index}`,\n );\n }\n seenAssertOutputs.add(input.index);\n }\n\n const scriptInfos = await Promise.all(\n params.connectorParamsPerInput.map((cp) => getChallengeAssertScriptInfo(cp)),\n );\n\n const psbt = new Psbt();\n psbt.setVersion(challengeAssertTx.version);\n psbt.setLocktime(challengeAssertTx.locktime);\n\n for (let i = 0; i < challengeAssertTx.ins.length; i++) {\n const input = challengeAssertTx.ins[i];\n const assertPrevOut = assertTx.outs[input.index];\n\n const { script, controlBlock } = scriptInfos[i];\n const scriptBytes = hexToUint8Array(script);\n const controlBlockBytes = hexToUint8Array(controlBlock);\n\n psbt.addInput({\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: assertPrevOut.script,\n value: assertPrevOut.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n }\n\n for (const output of challengeAssertTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n"],"names":["buildChallengeAssertPsbt","params","challengeAssertTx","Transaction","stripHexPrefix","assertTx","assertTxid","seenAssertOutputs","i","input","inputTxid","inputTxidHex","scriptInfos","cp","getChallengeAssertScriptInfo","psbt","Psbt","assertPrevOut","script","controlBlock","scriptBytes","hexToUint8Array","controlBlockBytes","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output"],"mappings":"yJAyDA,eAAsBA,EACpBC,EACiB,CACjB,MAAMC,EAAoBC,EAAAA,YAAY,QACpCC,EAAAA,eAAeH,EAAO,oBAAoB,CAAA,EAEtCI,EAAWF,EAAAA,YAAY,QAAQC,EAAAA,eAAeH,EAAO,WAAW,CAAC,EACjEK,EAAaD,EAAS,MAAA,EAE5B,GAAIJ,EAAO,wBAAwB,SAAWC,EAAkB,IAAI,OAClE,MAAM,IAAI,MACR,YAAYA,EAAkB,IAAI,MAAM,0BAA0BD,EAAO,wBAAwB,MAAM,EAAA,EAI3G,MAAMM,MAAwB,IAC9B,QAASC,EAAI,EAAGA,EAAIN,EAAkB,IAAI,OAAQM,IAAK,CACrD,MAAMC,EAAQP,EAAkB,IAAIM,CAAC,EAC/BE,EAAYC,EAAAA,aAAaF,CAAK,EACpC,GAAIC,IAAcJ,EAChB,MAAM,IAAI,MACR,yBAAyBE,CAAC,+CACPF,CAAU,SAASI,CAAS,EAAA,EAGnD,GAAI,CAACL,EAAS,KAAKI,EAAM,KAAK,EAC5B,MAAM,IAAI,MACR,iBAAiBA,EAAM,KAAK,wCAAwCD,CAAC,WAAWF,CAAU,GAAA,EAG9F,GAAIC,EAAkB,IAAIE,EAAM,KAAK,EACnC,MAAM,IAAI,MACR,yBAAyBD,CAAC,mCAAmCC,EAAM,KAAK,EAAA,EAG5EF,EAAkB,IAAIE,EAAM,KAAK,CACnC,CAEA,MAAMG,EAAc,MAAM,QAAQ,IAChCX,EAAO,wBAAwB,IAAKY,GAAOC,EAAAA,6BAA6BD,CAAE,CAAC,CAAA,EAGvEE,EAAO,IAAIC,OACjBD,EAAK,WAAWb,EAAkB,OAAO,EACzCa,EAAK,YAAYb,EAAkB,QAAQ,EAE3C,QAASM,EAAI,EAAGA,EAAIN,EAAkB,IAAI,OAAQM,IAAK,CACrD,MAAMC,EAAQP,EAAkB,IAAIM,CAAC,EAC/BS,EAAgBZ,EAAS,KAAKI,EAAM,KAAK,EAEzC,CAAE,OAAAS,EAAQ,aAAAC,GAAiBP,EAAYJ,CAAC,EACxCY,EAAcC,EAAAA,gBAAgBH,CAAM,EACpCI,EAAoBD,EAAAA,gBAAgBF,CAAY,EAEtDJ,EAAK,SAAS,CACZ,KAAMN,EAAM,KACZ,MAAOA,EAAM,MACb,SAAUA,EAAM,SAChB,YAAa,CACX,OAAQQ,EAAc,OACtB,MAAOA,EAAc,KAAA,EAEvB,cAAe,CACb,CACE,YAAaM,EAAAA,uBACb,OAAQC,EAAAA,OAAO,KAAKJ,CAAW,EAC/B,aAAcI,EAAAA,OAAO,KAAKF,CAAiB,CAAA,CAC7C,EAEF,eAAgBE,EAAAA,OAAO,KAAKC,EAAAA,iBAAiB,CAAA,CAC9C,CACH,CAEA,UAAWC,KAAUxB,EAAkB,KACrCa,EAAK,UAAU,CACb,OAAQW,EAAO,OACf,MAAOA,EAAO,KAAA,CACf,EAGH,OAAOX,EAAK,MAAA,CACd"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";function O(_,T){if(!Number.isInteger(_)||_<1||_>65535)throw new Error(`Invalid vaultCoreVersion ${_} from ${T}: expected an integer in [1, 65535].`)}const U=2,E=1,N=0,P=0,A=546,I=2,S=0,C=3,R=2,t=2,V=1e4,L=1e4,n=128;exports.ASSERT_PAYOUT_OUTPUT_INDEX=P;exports.BPS_DENOMINATOR=L;exports.CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER=t;exports.DEPOSITOR_PAYOUT_INPUT_COUNT=U;exports.DEPOSITOR_SIGNED_INPUT_COUNT=E;exports.MAX_PAYOUT_SCRIPT_LEN=n;exports.MAX_VP_COMMISSION_BPS_EXCLUSIVE=V;exports.NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT=R;exports.PAYOUT_ANCHOR_DUST_SATS=A;exports.PAYOUT_TX_LOCKTIME=S;exports.PAYOUT_TX_VERSION=I;exports.PEGIN_VAULT_OUTPUT_INDEX=N;exports.VP_CLAIMER_PAYOUT_OUTPUT_COUNT=C;exports.assertValidVaultCoreVersion=O;
|
|
2
|
-
//# sourceMappingURL=constants-BCdDRd_Y.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"constants-BCdDRd_Y.cjs","sources":["../src/tbv/core/primitives/vaultCoreVersion.ts","../src/tbv/core/primitives/psbt/constants.ts"],"sourcesContent":["/**\n * Vault core version — the on-chain version axis that selects which tx graph\n * the vault-wasm facade builds.\n *\n * One number, two names: the contract calls it `vaultCoreVersion`\n * (`ProtocolParams.activeVaultCoreVersion()` for fresh deposits, the vault's\n * stamped `BTCVaultProtocolInfo.vaultCoreVersion` for resume), while the\n * vault-wasm facade calls the same axis `txGraphVersion`. SDK params carry\n * `vaultCoreVersion` and map it to `txGraphVersion` at each WASM call site.\n */\n\n/** `vaultCoreVersion` is `uint16` on-chain (see `IProtocolParams.sol`). */\nconst VAULT_CORE_VERSION_UINT16_MAX = 65_535;\n\n/**\n * Assert a vault core version is a well-formed on-chain value: an integer in\n * `[1, 65535]`. Mirrors the contract (`uint16`, setter rejects 0) and vaultd\n * (`SUPPORTED_CORE_VERSIONS` never contains 0). A `0` here means the vault\n * predates the `vaultCoreVersion` contract field or the read was mis-decoded —\n * fail closed rather than guess a graph version.\n *\n * Whether the version is *buildable* by the bundled WASM is a separate\n * question — the facade fails closed on unsupported versions at construction.\n *\n * @param version - The value to validate.\n * @param source - Where the value came from, for the error message\n * (e.g. `\"ProtocolParams.activeVaultCoreVersion()\"`).\n */\nexport function assertValidVaultCoreVersion(\n version: number,\n source: string,\n): void {\n if (\n !Number.isInteger(version) ||\n version < 1 ||\n version > VAULT_CORE_VERSION_UINT16_MAX\n ) {\n throw new Error(\n `Invalid vaultCoreVersion ${version} from ${source}: expected an ` +\n `integer in [1, ${VAULT_CORE_VERSION_UINT16_MAX}].`,\n );\n }\n}\n","/**\n * Protocol invariants for depositor graph transactions.\n *\n * These indices and counts encode the on-chain vault protocol layout\n * (which output of PegIn/Assert each child transaction spends, and how\n * many inputs each transaction has). Consumed by the PSBT builders and\n * the depositor graph signing service; a drift between copies of these\n * values would silently change validation behaviour.\n *\n * @module primitives/psbt/constants\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md\n */\n\n/**\n * Depositor Payout transaction input count.\n * Input 0: PegIn:0 (signed). Input 1: Assert:0 (in sighash, not signed).\n */\nexport const DEPOSITOR_PAYOUT_INPUT_COUNT = 2;\n\n/**\n * Inputs the depositor signs per Payout / NoPayout PSBT: input 0 only. The\n * other inputs are in the SIGHASH_DEFAULT sighash but carry no depositor\n * signature — the Ledger host expects exactly this many yields, so a drift\n * here re-arms an input the device never signs.\n */\nexport const DEPOSITOR_SIGNED_INPUT_COUNT = 1;\n\n/** PegIn vault output index spent by the depositor's Payout input 0. */\nexport const PEGIN_VAULT_OUTPUT_INDEX = 0;\n\n/** Assert output index spent by the depositor's Payout input 1 (NOT signed). */\nexport const ASSERT_PAYOUT_OUTPUT_INDEX = 0;\n\n/**\n * Dust amount (sats) for the payout CPFP anchor output. Matches `DUST_AMOUNT`\n * in `btc-vault crates/vault/src/lib.rs`.\n */\nexport const PAYOUT_ANCHOR_DUST_SATS = 546;\n\n/**\n * Payout transaction literals btc-vault builds deterministically\n * (`crates/vault/src/transactions/payout.rs`: `Version::TWO`,\n * `LockTime::ZERO`). The depositor's signature commits to both, so a\n * VP-supplied payout that deviates would produce a signature over a\n * transaction the protocol never constructs.\n */\nexport const PAYOUT_TX_VERSION = 2;\nexport const PAYOUT_TX_LOCKTIME = 0;\n\n/** VP-claimer payout output count: [depositor payout, VP commission, CPFP anchor]. */\nexport const VP_CLAIMER_PAYOUT_OUTPUT_COUNT = 3;\n\n/** Depositor/VK-claimer payout output count: [claimer payout, CPFP anchor]. */\nexport const NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT = 2;\n\n/**\n * ChallengeAssert connectors the VP returns per challenger: one for the\n * ChallengeAssertX transaction and one for ChallengeAssertY — two single-input\n * transactions, not a single multi-input one. This is a per-challenger array\n * cardinality, NOT a count of inputs in one transaction.\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md (ChallengeAssertX / ChallengeAssertY)\n */\nexport const CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER = 2;\n\n/**\n * Exclusive upper bound on VP commission (bps). Matches\n * `VPKeyRegistryLogic.sol` (`commissionBps >= 10000` reverts).\n * The minimum is version-locked (`minVpCommissionBps`) and enforced upstream,\n * not here.\n */\nexport const MAX_VP_COMMISSION_BPS_EXCLUSIVE = 10_000;\n\n/**\n * Basis-points denominator for commission math:\n * `floor(value * bps / BPS_DENOMINATOR)`. Numerically equal to\n * {@link MAX_VP_COMMISSION_BPS_EXCLUSIVE} but a distinct concept — tightening\n * the accepted bps range must never change the arithmetic.\n */\nexport const BPS_DENOMINATOR = 10_000;\n\n/**\n * Contract cap on a registered payout/commission scriptPubKey's byte length\n * (`MAX_PAYOUT_ADDRESS_LENGTH`, Constants.sol; empty scripts are rejected at\n * registration, so valid lengths are `[1, 128]`). A measured length outside\n * this range is provably not a registered script.\n */\nexport const MAX_PAYOUT_SCRIPT_LEN = 128;\n"],"names":["assertValidVaultCoreVersion","version","source","DEPOSITOR_PAYOUT_INPUT_COUNT","DEPOSITOR_SIGNED_INPUT_COUNT","PEGIN_VAULT_OUTPUT_INDEX","ASSERT_PAYOUT_OUTPUT_INDEX","PAYOUT_ANCHOR_DUST_SATS","PAYOUT_TX_VERSION","PAYOUT_TX_LOCKTIME","VP_CLAIMER_PAYOUT_OUTPUT_COUNT","NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT","CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER","MAX_VP_COMMISSION_BPS_EXCLUSIVE","BPS_DENOMINATOR","MAX_PAYOUT_SCRIPT_LEN"],"mappings":"aA4BO,SAASA,EACdC,EACAC,EACM,CACN,GACE,CAAC,OAAO,UAAUD,CAAO,GACzBA,EAAU,GACVA,EAAU,MAEV,MAAM,IAAI,MACR,4BAA4BA,CAAO,SAASC,CAAM,sCACD,CAGvD,CCzBO,MAAMC,EAA+B,EAQ/BC,EAA+B,EAG/BC,EAA2B,EAG3BC,EAA6B,EAM7BC,EAA0B,IAS1BC,EAAoB,EACpBC,EAAqB,EAGrBC,EAAiC,EAGjCC,EAAqC,EASrCC,EAA6C,EAQ7CC,EAAkC,IAQlCC,EAAkB,IAQlBC,EAAwB"}
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
function O(_, T) {
|
|
2
|
-
if (!Number.isInteger(_) || _ < 1 || _ > 65535)
|
|
3
|
-
throw new Error(
|
|
4
|
-
`Invalid vaultCoreVersion ${_} from ${T}: expected an integer in [1, 65535].`
|
|
5
|
-
);
|
|
6
|
-
}
|
|
7
|
-
const U = 2, s = 1, N = 0, E = 0, A = 546, I = 2, P = 0, t = 3, a = 2, n = 2, C = 1e4, S = 1e4, o = 128;
|
|
8
|
-
export {
|
|
9
|
-
E as A,
|
|
10
|
-
S as B,
|
|
11
|
-
n as C,
|
|
12
|
-
s as D,
|
|
13
|
-
C as M,
|
|
14
|
-
a as N,
|
|
15
|
-
I as P,
|
|
16
|
-
t as V,
|
|
17
|
-
O as a,
|
|
18
|
-
U as b,
|
|
19
|
-
P as c,
|
|
20
|
-
A as d,
|
|
21
|
-
o as e,
|
|
22
|
-
N as f
|
|
23
|
-
};
|
|
24
|
-
//# sourceMappingURL=constants-DRiWbItj.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"constants-DRiWbItj.js","sources":["../src/tbv/core/primitives/vaultCoreVersion.ts","../src/tbv/core/primitives/psbt/constants.ts"],"sourcesContent":["/**\n * Vault core version — the on-chain version axis that selects which tx graph\n * the vault-wasm facade builds.\n *\n * One number, two names: the contract calls it `vaultCoreVersion`\n * (`ProtocolParams.activeVaultCoreVersion()` for fresh deposits, the vault's\n * stamped `BTCVaultProtocolInfo.vaultCoreVersion` for resume), while the\n * vault-wasm facade calls the same axis `txGraphVersion`. SDK params carry\n * `vaultCoreVersion` and map it to `txGraphVersion` at each WASM call site.\n */\n\n/** `vaultCoreVersion` is `uint16` on-chain (see `IProtocolParams.sol`). */\nconst VAULT_CORE_VERSION_UINT16_MAX = 65_535;\n\n/**\n * Assert a vault core version is a well-formed on-chain value: an integer in\n * `[1, 65535]`. Mirrors the contract (`uint16`, setter rejects 0) and vaultd\n * (`SUPPORTED_CORE_VERSIONS` never contains 0). A `0` here means the vault\n * predates the `vaultCoreVersion` contract field or the read was mis-decoded —\n * fail closed rather than guess a graph version.\n *\n * Whether the version is *buildable* by the bundled WASM is a separate\n * question — the facade fails closed on unsupported versions at construction.\n *\n * @param version - The value to validate.\n * @param source - Where the value came from, for the error message\n * (e.g. `\"ProtocolParams.activeVaultCoreVersion()\"`).\n */\nexport function assertValidVaultCoreVersion(\n version: number,\n source: string,\n): void {\n if (\n !Number.isInteger(version) ||\n version < 1 ||\n version > VAULT_CORE_VERSION_UINT16_MAX\n ) {\n throw new Error(\n `Invalid vaultCoreVersion ${version} from ${source}: expected an ` +\n `integer in [1, ${VAULT_CORE_VERSION_UINT16_MAX}].`,\n );\n }\n}\n","/**\n * Protocol invariants for depositor graph transactions.\n *\n * These indices and counts encode the on-chain vault protocol layout\n * (which output of PegIn/Assert each child transaction spends, and how\n * many inputs each transaction has). Consumed by the PSBT builders and\n * the depositor graph signing service; a drift between copies of these\n * values would silently change validation behaviour.\n *\n * @module primitives/psbt/constants\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md\n */\n\n/**\n * Depositor Payout transaction input count.\n * Input 0: PegIn:0 (signed). Input 1: Assert:0 (in sighash, not signed).\n */\nexport const DEPOSITOR_PAYOUT_INPUT_COUNT = 2;\n\n/**\n * Inputs the depositor signs per Payout / NoPayout PSBT: input 0 only. The\n * other inputs are in the SIGHASH_DEFAULT sighash but carry no depositor\n * signature — the Ledger host expects exactly this many yields, so a drift\n * here re-arms an input the device never signs.\n */\nexport const DEPOSITOR_SIGNED_INPUT_COUNT = 1;\n\n/** PegIn vault output index spent by the depositor's Payout input 0. */\nexport const PEGIN_VAULT_OUTPUT_INDEX = 0;\n\n/** Assert output index spent by the depositor's Payout input 1 (NOT signed). */\nexport const ASSERT_PAYOUT_OUTPUT_INDEX = 0;\n\n/**\n * Dust amount (sats) for the payout CPFP anchor output. Matches `DUST_AMOUNT`\n * in `btc-vault crates/vault/src/lib.rs`.\n */\nexport const PAYOUT_ANCHOR_DUST_SATS = 546;\n\n/**\n * Payout transaction literals btc-vault builds deterministically\n * (`crates/vault/src/transactions/payout.rs`: `Version::TWO`,\n * `LockTime::ZERO`). The depositor's signature commits to both, so a\n * VP-supplied payout that deviates would produce a signature over a\n * transaction the protocol never constructs.\n */\nexport const PAYOUT_TX_VERSION = 2;\nexport const PAYOUT_TX_LOCKTIME = 0;\n\n/** VP-claimer payout output count: [depositor payout, VP commission, CPFP anchor]. */\nexport const VP_CLAIMER_PAYOUT_OUTPUT_COUNT = 3;\n\n/** Depositor/VK-claimer payout output count: [claimer payout, CPFP anchor]. */\nexport const NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT = 2;\n\n/**\n * ChallengeAssert connectors the VP returns per challenger: one for the\n * ChallengeAssertX transaction and one for ChallengeAssertY — two single-input\n * transactions, not a single multi-input one. This is a per-challenger array\n * cardinality, NOT a count of inputs in one transaction.\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md (ChallengeAssertX / ChallengeAssertY)\n */\nexport const CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER = 2;\n\n/**\n * Exclusive upper bound on VP commission (bps). Matches\n * `VPKeyRegistryLogic.sol` (`commissionBps >= 10000` reverts).\n * The minimum is version-locked (`minVpCommissionBps`) and enforced upstream,\n * not here.\n */\nexport const MAX_VP_COMMISSION_BPS_EXCLUSIVE = 10_000;\n\n/**\n * Basis-points denominator for commission math:\n * `floor(value * bps / BPS_DENOMINATOR)`. Numerically equal to\n * {@link MAX_VP_COMMISSION_BPS_EXCLUSIVE} but a distinct concept — tightening\n * the accepted bps range must never change the arithmetic.\n */\nexport const BPS_DENOMINATOR = 10_000;\n\n/**\n * Contract cap on a registered payout/commission scriptPubKey's byte length\n * (`MAX_PAYOUT_ADDRESS_LENGTH`, Constants.sol; empty scripts are rejected at\n * registration, so valid lengths are `[1, 128]`). A measured length outside\n * this range is provably not a registered script.\n */\nexport const MAX_PAYOUT_SCRIPT_LEN = 128;\n"],"names":["assertValidVaultCoreVersion","version","source","DEPOSITOR_PAYOUT_INPUT_COUNT","DEPOSITOR_SIGNED_INPUT_COUNT","PEGIN_VAULT_OUTPUT_INDEX","ASSERT_PAYOUT_OUTPUT_INDEX","PAYOUT_ANCHOR_DUST_SATS","PAYOUT_TX_VERSION","PAYOUT_TX_LOCKTIME","VP_CLAIMER_PAYOUT_OUTPUT_COUNT","NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT","CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER","MAX_VP_COMMISSION_BPS_EXCLUSIVE","BPS_DENOMINATOR","MAX_PAYOUT_SCRIPT_LEN"],"mappings":"AA4BO,SAASA,EACdC,GACAC,GACM;AACN,MACE,CAAC,OAAO,UAAUD,CAAO,KACzBA,IAAU,KACVA,IAAU;AAEV,UAAM,IAAI;AAAA,MACR,4BAA4BA,CAAO,SAASC,CAAM;AAAA,IACD;AAGvD;ACzBO,MAAMC,IAA+B,GAQ/BC,IAA+B,GAG/BC,IAA2B,GAG3BC,IAA6B,GAM7BC,IAA0B,KAS1BC,IAAoB,GACpBC,IAAqB,GAGrBC,IAAiC,GAGjCC,IAAqC,GASrCC,IAA6C,GAQ7CC,IAAkC,KAQlCC,IAAkB,KAQlBC,IAAwB;"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const Q=require("@bitcoin-js/tiny-secp256k1-asmjs"),a=require("bitcoinjs-lib"),E=require("./sha2-DsrLC4NM.cjs"),u=require("buffer"),c=require("./BTCVaultRegistry.abi-z7d_eP22.cjs"),$=require("./BTCVaultRegistryKeyEpochs.abi-_NERAdc5.cjs"),A=require("./onChainBtcPubkey-C_a2L3kL.cjs"),Y=require("./constants-BCdDRd_Y.cjs"),f=require("./validation-CDbOaDj7.cjs");function Z(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const o=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,o.get?o:{enumerable:!0,get:()=>t[n]})}}return e.default=t,Object.freeze(e)}const m=Z(Q),J="BIP0322-signed-message",tt="TapTweak",K=32,et=64,nt=33,k=71,R=72,d=0,B=0,V=0,C=0,ot=32,rt=4294967295,it=0,st=0,at=32,ct=106;function U(t,e){const n=new TextEncoder().encode(t),o=E.sha256(n),i=new Uint8Array(o.length*2+e.length);return i.set(o,0),i.set(o,o.length),i.set(e,o.length*2),E.sha256(i)}function ut(t){if(t.length!==K)return null;const e=U(tt,t),n=m.xOnlyPointAddTweak(t,e);return n?n.xOnlyPubkey:null}function H(t,e){const n=U(J,t),o=new a.Transaction;o.version=B,o.locktime=V;const i=u.Buffer.concat([u.Buffer.from([st,at]),u.Buffer.from(n)]);o.addInput(u.Buffer.alloc(ot,0),rt,C,i),o.addOutput(e,d);const r=new a.Transaction;return r.version=B,r.locktime=V,r.addInput(o.getHash(),it,C),r.addOutput(u.Buffer.from([ct]),d),r}function lt(t,e,n,o=a.Transaction.SIGHASH_DEFAULT){if(e.length!==K||n.length!==et||o!==a.Transaction.SIGHASH_DEFAULT&&o!==a.Transaction.SIGHASH_ALL)return!1;try{const i=a.payments.p2tr({internalPubkey:u.Buffer.from(e)});if(!i.output)return!1;const r=i.output,g=H(t,r).hashForWitnessV1(0,[r],[d],o),p=ut(e);return p?m.verifySchnorr(g,p,n):!1}catch{return!1}}function ft(t,e,n){if(e.length!==nt||n.length<k||n.length>R)return!1;try{if(!m.isPointCompressed(e))return!1;const{signature:o,hashType:i}=a.script.signature.decode(u.Buffer.from(n));if(!a.script.signature.encode(o,i).equals(u.Buffer.from(n))||i!==a.Transaction.SIGHASH_ALL)return!1;const r=a.payments.p2wpkh({pubkey:u.Buffer.from(e)});if(!r.output||!r.hash)return!1;const s=H(t,r.output),g=a.payments.p2pkh({hash:r.hash}).output;if(!g)return!1;const p=s.hashForWitnessV0(0,g,d,i);return m.verify(p,e,o,!0)}catch{return!1}}const w=65535,_=1e4,P=4294967295,v=255;function M(t){if(!Number.isInteger(t)||t<0||t>P)throw new Error(`Invalid offchainParamsVersion from contract: must be a uint32, got ${t}`)}function D(t){const e=[];if(t.timelockAssert<=0n&&e.push(`timelockAssert must be positive, got ${t.timelockAssert}`),t.timelockAssert>BigInt(w)&&e.push(`timelockAssert ${t.timelockAssert} exceeds uint16 max (${w})`),t.timelockChallengeAssert<=0n&&e.push(`timelockChallengeAssert must be positive, got ${t.timelockChallengeAssert}`),t.tRefund<=0&&e.push(`tRefund must be positive, got ${t.tRefund}`),t.tStale<=0&&e.push(`tStale must be positive, got ${t.tStale}`),t.securityCouncilKeys.length===0&&e.push("securityCouncilKeys must not be empty"),t.councilQuorum<=0&&e.push(`councilQuorum must be positive, got ${t.councilQuorum}`),t.councilQuorum>t.securityCouncilKeys.length&&e.push(`councilQuorum (${t.councilQuorum}) exceeds securityCouncilKeys count (${t.securityCouncilKeys.length})`),t.feeRate<=0n&&e.push(`feeRate must be positive, got ${t.feeRate}`),t.minPeginFeeRate<=0n&&e.push(`minPeginFeeRate must be positive, got ${t.minPeginFeeRate}`),(!Number.isInteger(t.proverCircuitVersion)||t.proverCircuitVersion<0||t.proverCircuitVersion>w)&&e.push(`proverCircuitVersion must be a uint16, got ${t.proverCircuitVersion}`),(!Number.isInteger(t.minPrepeginDepth)||t.minPrepeginDepth<=0||t.minPrepeginDepth>P)&&e.push(`minPrepeginDepth must be a uint32 in [1, ${P}], got ${t.minPrepeginDepth}`),t.babeTotalInstances<=0&&e.push(`babeTotalInstances must be positive, got ${t.babeTotalInstances}`),t.babeInstancesToFinalize<=0&&e.push(`babeInstancesToFinalize must be positive, got ${t.babeInstancesToFinalize}`),t.babeInstancesToFinalize>t.babeTotalInstances&&e.push(`babeInstancesToFinalize (${t.babeInstancesToFinalize}) exceeds babeTotalInstances (${t.babeTotalInstances})`),(t.minVpCommissionBps<0||t.minVpCommissionBps>_)&&e.push(`minVpCommissionBps must be in [0, ${_}], got ${t.minVpCommissionBps}`),e.length>0)throw new Error(`Invalid offchain protocol parameters: ${e.join("; ")}`)}function X(t){const e=[];if(t.minimumPegInAmount<=0n&&e.push(`minimumPegInAmount must be positive, got ${t.minimumPegInAmount}`),t.maxPegInAmount<t.minimumPegInAmount&&e.push(`maxPegInAmount (${t.maxPegInAmount}) must be >= minimumPegInAmount (${t.minimumPegInAmount})`),t.pegInAckTimeout<=0n&&e.push(`pegInAckTimeout must be positive, got ${t.pegInAckTimeout}`),t.pegInActivationTimeout<=0n&&e.push(`pegInActivationTimeout must be positive, got ${t.pegInActivationTimeout}`),(!Number.isInteger(t.maxHtlcOutputCount)||t.maxHtlcOutputCount<=0||t.maxHtlcOutputCount>v)&&e.push(`maxHtlcOutputCount must be an integer in [1, ${v}], got ${t.maxHtlcOutputCount}`),(typeof t.expiredPegInGraceBlocks!="bigint"||t.expiredPegInGraceBlocks<=0n)&&e.push(`expiredPegInGraceBlocks must be a positive bigint, got ${t.expiredPegInGraceBlocks}`),e.length>0)throw new Error(`Invalid TBV protocol parameters: ${e.join("; ")}`)}function ht(t){if(X(t),D(t.offchainParams),!Number.isInteger(t.offchainParamsVersion)||t.offchainParamsVersion<0||t.offchainParamsVersion>P)throw new Error(`Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${t.offchainParamsVersion}`);Y.assertValidVaultCoreVersion(t.activeVaultCoreVersion,"ProtocolParams.activeVaultCoreVersion()")}const S=9999;function O(t){return{depositor:t.depositor,depositorBtcPubKey:t.depositorBtcPubKey,amount:t.amount,vaultProvider:t.vaultProvider,status:t.status,applicationEntryPoint:t.applicationEntryPoint,createdAt:t.createdAt}}function b(t){const e=Number(t.offchainParamsVersion);return M(e),{depositorSignedPeginTx:t.depositorSignedPeginTx,universalChallengersVersion:t.universalChallengersVersion,appVaultKeepersVersion:t.appVaultKeepersVersion,offchainParamsVersion:e,verifiedAt:t.verifiedAt,depositorWotsPkHash:t.depositorWotsPkHash,hashlock:t.hashlock,htlcVout:t.htlcVout,depositorPopSignature:t.depositorPopSignature,prePeginTxHash:t.prePeginTxHash,vaultProviderCommissionBps:t.vaultProviderCommissionBps,claimExpiredUntil:t.claimExpiredUntil,vaultCoreVersion:t.vaultCoreVersion}}const gt=1n<<64n,x=0n;function T(t,e,n){if(t<0n||t>=gt)throw new Error(`getBtcVaultProtocolInfo returned ${e}=${t} for vault ${n}, outside the uint64 range — the registry may predate RFC-006`);return t}function F(t,e){return{vpKeyEpoch:T(t.vpKeyEpoch,"vpKeyEpoch",e),appKeeperKeyEpoch:T(t.appKeeperKeyEpoch,"appKeeperKeyEpoch",e),ucKeyEpoch:T(t.ucKeyEpoch,"ucKeyEpoch",e)}}class pt{constructor(e,n){this.publicClient=e,this.contractAddress=n}async getVaultProviderGenesisBtcPubKey(e){const n=await this.publicClient.readContract({address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getOperationBtcKeyAtEpoch",args:[e,x]});return A.assertOnChainBtcPubkey(n,`getOperationBtcKeyAtEpoch (vp=${e}, epoch=${x})`)}async getCurrentVaultProviderOperationBtcKey(e){const n=await this.publicClient.readContract({address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getCurrentOperationBtcKey",args:[e]});return A.assertOnChainBtcPubkey(n,`getCurrentOperationBtcKey (vp=${e})`)}async getVaultKeyEpochs(e){const n=await this.publicClient.readContract({address:this.contractAddress,abi:$.BTCVaultRegistryKeyEpochsABI,functionName:"getBtcVaultProtocolInfo",args:[e]});return F(n,e)}async getVaultKeyEpochsBatch(e){return e.length===0?[]:(await this.publicClient.multicall({contracts:e.map(o=>({address:this.contractAddress,abi:$.BTCVaultRegistryKeyEpochsABI,functionName:"getBtcVaultProtocolInfo",args:[o]})),allowFailure:!1})).map((o,i)=>F(o,e[i]))}async getVaultBasicInfo(e){const n=await this.publicClient.readContract({address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[e]});return O(n)}async getVaultProtocolInfo(e){const n=await this.publicClient.readContract({address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[e]});return b(n)}async getProtocolInfoBatch(e){return e.length===0?[]:(await this.publicClient.multicall({contracts:e.map(o=>({address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[o]})),allowFailure:!1})).map((o,i)=>{const r=o;if(!r.depositorSignedPeginTx||r.depositorSignedPeginTx==="0x")throw new Error(`Vault ${e[i]} not found on-chain or has no pegin transaction`);return b(r)})}async getPegInFee(e){return await this.publicClient.readContract({address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getPegInFee",args:[e]})}async getVaultProviderCommission(e){const n=await this.publicClient.readContract({address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getVaultProviderCommission",args:[e]});if(!Number.isInteger(n)||n<0||n>S)throw new Error(`getVaultProviderCommission returned ${n} bps for ${e}, outside the protocol range [0, ${S}]`);return n}async getVaultData(e){const[n,o]=await this.publicClient.multicall({contracts:[{address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[e]},{address:this.contractAddress,abi:c.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[e]}],allowFailure:!1}),i=O(n),r=b(o);if(!r.depositorSignedPeginTx||r.depositorSignedPeginTx==="0x")throw new Error(`Vault ${e} not found on-chain or has no pegin transaction`);return{basic:i,protocol:r}}}const mt=21e6*1e8,N=3e4;async function I(t,e){const n=new AbortController,o=setTimeout(()=>n.abort(),N),i=[n.signal,e==null?void 0:e.signal].filter(Boolean),r=f.combineAbortSignals(i);try{return await fetch(t,{...e,signal:r.signal})}catch(s){throw clearTimeout(o),r.cleanup(),s!=null&&typeof s=="object"&&"name"in s&&s.name==="AbortError"?new Error(`Mempool API request timed out after ${N}ms: ${t}`):s}}const G=1e4;function L(t){return Number.isInteger(t)&&t>0&&t<=mt}function dt(t){return Number.isInteger(t)&&t>0&&t<=G}function y(t,e){return!Number.isInteger(t)||t<0?!1:e===void 0||t<e}function h(t){if(!f.TXID_RE.test(t))throw new Error(`Invalid transaction ID format: ${t}`)}function W(t){if(!f.BITCOIN_ADDRESS_RE.test(t))throw new Error(`Invalid Bitcoin address format: ${t}`)}function q(t,e){if(!f.HEX_RE.test(t))throw new Error(`Invalid scriptPubKey: not valid hex for ${e}`);if(!f.KNOWN_SCRIPT_PREFIXES.some(o=>t.toLowerCase().startsWith(o)))throw new Error(`Unrecognized scriptPubKey type for ${e}: prefix ${t.slice(0,6)} does not match any known Bitcoin script type`)}const j={mainnet:"https://mempool.space/api",testnet:"https://mempool.space/testnet/api",signet:"https://mempool.space/signet/api"};async function l(t,e){try{const n=await I(t,e);if(!n.ok){const i=await n.text();throw new Error(`Mempool API error (${n.status}): ${i||n.statusText}`)}const o=n.headers.get("content-type");return o!=null&&o.includes("application/json")?await n.json():await n.text()}catch(n){throw n instanceof Error?new Error(`Failed to fetch from mempool API: ${n.message}`):new Error("Failed to fetch from mempool API: Unknown error")}}async function Pt(t,e){try{const n=await I(`${e}/tx`,{method:"POST",body:t,headers:{"Content-Type":"text/plain"}});if(!n.ok){const i=await n.text();let r;try{const s=JSON.parse(i);r=s.message??s.error}catch{r=i}throw new Error(r||`Failed to broadcast transaction: ${n.statusText}`)}return await n.text()}catch(n){throw n instanceof Error?new Error(`Failed to broadcast BTC transaction: ${n.message}`):new Error("Failed to broadcast BTC transaction: Unknown error")}}async function z(t,e){return h(t),l(`${e}/tx/${t}`)}async function It(t){const e=await l(`${t}/blocks/tip/height`),n=e.trim();if(!/^\d+$/.test(n))throw new Error(`Mempool API returned an invalid block tip height: "${e}"`);return Number.parseInt(n,10)}async function wt(t,e,n){if(h(t),!y(e))throw new Error(`Invalid vout ${e} for transaction ${t}`);return l(`${n}/tx/${t}/outspend/${e}`)}async function bt(t,e){h(t);try{const n=await I(`${e}/tx/${t}/hex`);if(!n.ok){const o=await n.text();throw new Error(`Mempool API error (${n.status}): ${o||n.statusText}`)}return await n.text()}catch(n){throw n instanceof Error?new Error(`Failed to get transaction hex for ${t}: ${n.message}`):new Error(`Failed to get transaction hex for ${t}: Unknown error`)}}async function Tt(t,e,n){h(t);const o=await z(t,n);if(!y(e,o.vout.length))throw new Error(`Invalid vout ${e} for transaction ${t} (has ${o.vout.length} outputs)`);const i=o.vout[e];if(!L(i.value))throw new Error(`Invalid UTXO value ${i.value} for ${t}:${e}`);return q(i.scriptpubkey,`${t}:${e}`),{txid:t,vout:e,value:i.value,scriptPubKey:i.scriptpubkey}}async function yt(t,e){W(t);try{const n=await l(`${e}/address/${t}/utxo`),o=await l(`${e}/v1/validate-address/${t}`);if(!o.isvalid)throw new Error(`Invalid Bitcoin address: ${t}. Mempool API validation failed.`);q(o.scriptPubKey,t);for(const r of n){if(h(r.txid),!y(r.vout))throw new Error(`Invalid vout ${r.vout} for ${r.txid}`);if(!L(r.value))throw new Error(`Invalid UTXO value ${r.value} for ${r.txid}:${r.vout}`)}return n.sort((r,s)=>s.value-r.value).map(r=>({txid:r.txid,vout:r.vout,value:r.value,scriptPubKey:o.scriptPubKey,confirmed:r.status.confirmed}))}catch(n){throw n instanceof Error?new Error(`Failed to get UTXOs for address ${t}: ${n.message}`):new Error(`Failed to get UTXOs for address ${t}: Unknown error`)}}function Et(t){return j[t]}async function $t(t,e){return W(t),l(`${e}/address/${t}/txs`)}async function At(t){const e=await I(`${t}/v1/fees/recommended`);if(!e.ok)throw new Error(`Failed to fetch network fees: ${e.status} ${e.statusText}`);const n=await e.json(),o=["fastestFee","halfHourFee","hourFee","economyFee","minimumFee"];for(const i of o)if(!dt(n[i]))throw new Error(`Invalid fee rate ${i}=${n[i]} from mempool API: expected a positive number ≤ ${G}`);if(n.minimumFee>n.economyFee||n.economyFee>n.hourFee||n.hourFee>n.halfHourFee||n.halfHourFee>n.fastestFee)throw new Error(`Fee rate ordering violation from mempool API: expected minimumFee (${n.minimumFee}) <= economyFee (${n.economyFee}) <= hourFee (${n.hourFee}) <= halfHourFee (${n.halfHourFee}) <= fastestFee (${n.fastestFee}).`);return n}exports.MEMPOOL_API_URLS=j;exports.P2WPKH_ENCODED_SIG_MAX=R;exports.P2WPKH_ENCODED_SIG_MIN=k;exports.ViemVaultRegistryReader=pt;exports.assertValidOffchainParamsVersion=M;exports.getAddressTxs=$t;exports.getAddressUtxos=yt;exports.getMempoolApiUrl=Et;exports.getNetworkFees=At;exports.getOutspend=wt;exports.getTipHeight=It;exports.getTxHex=bt;exports.getTxInfo=z;exports.getUtxoInfo=Tt;exports.pushTx=Pt;exports.validateOffchainParams=D;exports.validatePegInConfiguration=ht;exports.validateTBVProtocolParams=X;exports.verifyBip322P2wpkhSimple=ft;exports.verifyBip322Simple=lt;
|
|
2
|
-
//# sourceMappingURL=mempoolApi-Q90mz17e.cjs.map
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const I=require("@babylonlabs-io/babylon-tbv-rust-wasm"),y=require("buffer"),w=require("bitcoinjs-lib"),t=require("./bitcoin-m84N5a8o.cjs"),P=require("./verifyScriptPathSchnorrSignature-D-ppKNjT.cjs"),_=require("./fundPeginTransaction-BLD8FRL9.cjs");async function C(o){await I.initWasm();const{prePeginParams:e,fundedPrePeginTxHex:i,htlcVout:r,refundFee:u,hashlock:l}=o,x=P.normalizeAuthAnchorHash(e.authAnchorHash),s=new I.WasmPrePeginTx(e.vaultCoreVersion,e.depositorPubkey,e.vaultProviderPubkey,e.vaultKeeperPubkeys,e.universalChallengerPubkeys,[...e.hashlocks],new BigUint64Array(I.assertPositiveBigintArray(e.pegInAmounts,"pegInAmounts")),e.timelockRefund,e.feeRate,e.minPeginFeeRate,e.numLocalChallengers,e.councilQuorum,e.councilSize,e.network,x);let n=null;try{const p=s.getHtlcScriptPubKey(r).toLowerCase(),m=s.getHtlcValue(r);n=s.fromFundedTransaction(i);const c=n.buildRefundTx(u,r),b=await I.getPrePeginHtlcConnectorInfo({txGraphVersion:e.vaultCoreVersion,depositorPubkey:e.depositorPubkey,vaultProviderPubkey:e.vaultProviderPubkey,vaultKeeperPubkeys:e.vaultKeeperPubkeys,universalChallengerPubkeys:e.universalChallengerPubkeys,hashlock:l,timelockRefund:e.timelockRefund,network:e.network}),g=i.startsWith("0x")?i.slice(2):i,d=w.Transaction.fromHex(g),f=d.outs[r];if(!f)throw new Error(`HTLC output at vout ${r} not found in funded Pre-PegIn tx (tx has ${d.outs.length} outputs)`);const v=t.uint8ArrayToHex(new Uint8Array(f.script)).toLowerCase();if(v!==p)throw new Error(`HTLC scriptPubKey mismatch at vout ${r}: reconstructed template expects ${p}, funded tx carries ${v}. Refund refused — the (hashlocks, pegInAmounts) vector does not match the on-chain commitment.`);const T=BigInt(f.value);if(T!==m)throw new Error(`HTLC value mismatch at vout ${r}: reconstructed template expects ${m} sat, funded tx carries ${T} sat. Refund refused — the pegInAmounts vector does not match the on-chain commitment.`);const a=w.Transaction.fromHex(c);if(a.ins.length!==1)throw new Error(`Refund transaction must have exactly 1 input, got ${a.ins.length}`);const h=a.ins[0],$=d.getId(),H=t.uint8ArrayToHex(new Uint8Array(h.hash).slice().reverse());if(H!==$)throw new Error(`Refund input does not reference the Pre-PegIn transaction. Expected ${$}, got ${H}`);if(h.index!==r)throw new Error(`Refund input index ${h.index} does not match expected htlcVout ${r}`);const E=new w.Psbt;if(E.setVersion(a.version),E.setLocktime(a.locktime),E.addInput({hash:h.hash,index:h.index,sequence:h.sequence,witnessUtxo:{script:f.script,value:f.value},tapLeafScript:[{leafVersion:t.TAPSCRIPT_LEAF_VERSION,script:y.Buffer.from(t.hexToUint8Array(b.refundScript)),controlBlock:y.Buffer.from(t.hexToUint8Array(b.refundControlBlock))}],tapInternalKey:y.Buffer.from(I.tapInternalPubkey)}),a.outs.length!==1)throw new Error(`Refund transaction must have exactly 1 output, got ${a.outs.length}`);const R=a.outs[0],S=t.stripHexPrefix(t.deriveBip86ScriptPubKeyHex(e.depositorPubkey)).toLowerCase(),A=t.uint8ArrayToHex(new Uint8Array(R.script)).toLowerCase();if(A!==S)throw new Error(`Refund output scriptPubKey ${A} does not match the depositor's BIP-86 address ${S}. Refund refused — the reclaimed funds would not return to the depositor.`);const O=T-u;if(BigInt(R.value)!==O)throw new Error(`Refund output value ${BigInt(R.value)} sat does not equal the HTLC value ${T} sat minus the requested fee ${u} sat (expected ${O} sat). Refund refused — the reclaimed amount would be burned as excess fee.`);return E.addOutput({script:R.script,value:R.value}),{psbtHex:E.toHex()}}finally{n==null||n.free(),s.free()}}const L=2,U=4294967293,V=214,B=299,N=4;function k(o){if(!Number.isInteger(o)||o<1)throw new Error(`Reclaim input count must be a positive integer, got ${o}.`);return Math.ceil((V+B*o)/N)}function K(o,e){if(!Number.isFinite(o)||o<=0)throw new Error(`Reclaim fee rate must be a positive number, got ${o}.`);return BigInt(Math.ceil(o*k(e)))}function M(o){const{depositorPubkey:e,inputs:i,feeSats:r}=o;if(i.length===0)throw new Error("Reclaim requires at least one input; got none.");if(r<=0n)throw new Error(`Reclaim fee must be positive, got ${r} sat. Refusing to build a transaction that would not relay.`);const u=P.deriveDepositorClaimDescriptor(e),l=t.uint8ArrayToHex(new Uint8Array(u.scriptPubKey)).toLowerCase(),x=new w.Psbt;x.setVersion(L),x.setLocktime(0);let s=0n;const n=new Set;if(i.forEach((c,b)=>{const g=w.Transaction.fromHex(t.stripHexPrefix(c.depositorSignedPeginTxHex)),d=g.getId(),f=g.outs[P.PEGIN_DEPOSITOR_CLAIM_VOUT];if(!f)throw new Error(`PegIn ${d} has no output at vout ${P.PEGIN_DEPOSITOR_CLAIM_VOUT} (tx has ${g.outs.length}); there is no depositor-claim reserve to reclaim.`);const v=t.uint8ArrayToHex(new Uint8Array(f.script)).toLowerCase();if(v!==l)throw new Error(`Input ${b}: PegIn ${d} vout ${P.PEGIN_DEPOSITOR_CLAIM_VOUT} pays ${v}, but the connected wallet's depositor-claim script is ${l}. Reclaim refused — this reserve belongs to a different wallet.`);const T=t.stripHexPrefix(c.observed.scriptPubKey).toLowerCase();if(T!==l)throw new Error(`Input ${b}: the observed UTXO ${d}:${P.PEGIN_DEPOSITOR_CLAIM_VOUT} pays ${T}, expected ${l}. Reclaim refused — chain state disagrees with the contract's PegIn.`);const a=BigInt(f.value);if(a!==c.observed.value)throw new Error(`Input ${b}: PegIn ${d} vout ${P.PEGIN_DEPOSITOR_CLAIM_VOUT} carries ${a} sat, but the observed UTXO carries ${c.observed.value} sat. Reclaim refused.`);if(a!==c.expectedValue)throw new Error(`Input ${b}: PegIn ${d} vout ${P.PEGIN_DEPOSITOR_CLAIM_VOUT} carries ${a} sat, but this vault's parameters compute a depositor-claim value of ${c.expectedValue} sat. Reclaim refused.`);const h=`${d}:${P.PEGIN_DEPOSITOR_CLAIM_VOUT}`;if(n.has(h))throw new Error(`Input ${b} repeats outpoint ${h}, which is already being swept by an earlier input. Reclaim refused.`);n.add(h),s+=a,x.addInput({hash:d,index:P.PEGIN_DEPOSITOR_CLAIM_VOUT,sequence:U,witnessUtxo:{script:f.script,value:f.value},tapLeafScript:[{leafVersion:t.TAPSCRIPT_LEAF_VERSION,script:u.leafScript,controlBlock:u.controlBlock}],tapInternalKey:u.internalKey})}),r>=s)throw new Error(`Reclaim fee ${r} sat is not less than the swept total ${s} sat. Refusing to build a transaction with no output.`);const p=s-r;if(p<=_.DUST_THRESHOLD)throw new Error(`Reclaim output ${p} sat is at or below the dust threshold ${_.DUST_THRESHOLD} sat. The reserve is not at risk — it stays where it is until fee rates fall.`);const m=t.stripHexPrefix(t.deriveBip86ScriptPubKeyHex(e));return x.addOutput({script:y.Buffer.from(t.hexToUint8Array(m)),value:Number(p)}),{psbtHex:x.toHex(),outputValue:p,totalInputValue:s}}async function D(o){const e=t.stripHexPrefix(o.noPayoutTxHex),i=w.Transaction.fromHex(e),{noPayoutScript:r,noPayoutControlBlock:u}=await I.getAssertNoPayoutScriptInfo(o.connectorParams,o.challengerPubkey),l=t.hexToUint8Array(r),x=t.hexToUint8Array(u),s=new w.Psbt;s.setVersion(i.version),s.setLocktime(i.locktime);for(let n=0;n<i.ins.length;n++){const p=i.ins[n],m=o.prevouts[n];if(!m)throw new Error(`Missing prevout data for input ${n}`);const c={hash:p.hash,index:p.index,sequence:p.sequence,witnessUtxo:{script:y.Buffer.from(t.hexToUint8Array(t.stripHexPrefix(m.script_pubkey))),value:m.value}};n===0&&(c.tapLeafScript=[{leafVersion:t.TAPSCRIPT_LEAF_VERSION,script:y.Buffer.from(l),controlBlock:y.Buffer.from(x)}],c.tapInternalKey=y.Buffer.from(I.tapInternalPubkey)),s.addInput(c)}for(const n of i.outs)s.addOutput({script:n.script,value:n.value});return s.toHex()}function q(o,e,i){const r=w.Transaction.fromHex(t.stripHexPrefix(o));if(r.outs.length!==1)throw new Error(`NoPayout transaction must have exactly 1 output, got ${r.outs.length}`);const u=t.hexToUint8Array(t.processPublicKeyToXOnly(e)),{output:l}=w.payments.p2tr({internalPubkey:y.Buffer.from(u),network:t.getNetwork(i)});if(!l)throw new Error("Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation");if(!r.outs[0].script.equals(l))throw new Error("NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address")}exports.assertNoPayoutOutputMatchesChallenger=q;exports.buildNoPayoutPsbt=D;exports.buildReclaimPsbt=M;exports.buildRefundPsbt=C;exports.estimateReclaimFeeSats=K;exports.reclaimVsize=k;
|
|
2
|
-
//# sourceMappingURL=noPayout-BKP3mRu3.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"noPayout-BKP3mRu3.cjs","sources":["../src/tbv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/psbt/reclaim.ts","../src/tbv/core/primitives/psbt/noPayout.ts"],"sourcesContent":["/**\n * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport {\n assertPositiveBigintArray,\n getPrePeginHtlcConnectorInfo,\n initWasm,\n tapInternalPubkey,\n WasmPrePeginTx,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport { normalizeAuthAnchorHash, type PrePeginParams } from \"./pegin\";\n\n/**\n * Parameters for building a refund PSBT\n */\nexport interface BuildRefundPsbtParams {\n /** Same PrePeginParams used when the original Pre-PegIn tx was created */\n prePeginParams: PrePeginParams;\n /** Funded Pre-PegIn transaction hex (the tx whose HTLC output is being refunded) */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output in the Pre-PegIn transaction */\n htlcVout: number;\n /** Transaction fee in satoshis for the refund transaction */\n refundFee: bigint;\n /** SHA256 hash commitment for the HTLC (64 hex chars, no 0x prefix) */\n hashlock: string;\n}\n\n/**\n * Result of building a refund PSBT\n */\nexport interface BuildRefundPsbtResult {\n /** PSBT hex ready for depositor signing */\n psbtHex: string;\n}\n\n/**\n * Build a PSBT for signing the refund transaction.\n *\n * The refund transaction spends the Pre-PegIn HTLC output via leaf 1\n * (the refund script: `<timelockRefund> CSV DROP <depositorPubkey> CHECKSIG`).\n * The PSBT includes the tapLeafScript entry so the depositor's wallet can\n * sign using Taproot script-path spending.\n *\n * The input's sequence is set to `timelockRefund` by the WASM, enforcing\n * the Bitcoin CSV timelock. The refund broadcast will be rejected by the\n * network if the timelock has not yet expired.\n *\n * @param params - Refund PSBT parameters\n * @returns PSBT hex for depositor signing\n * @throws If the HTLC output at htlcVout is not found\n * @throws If the refund transaction does not have exactly 1 input\n */\nexport async function buildRefundPsbt(\n params: BuildRefundPsbtParams,\n): Promise<BuildRefundPsbtResult> {\n await initWasm();\n\n const { prePeginParams, fundedPrePeginTxHex, htlcVout, refundFee, hashlock } =\n params;\n\n // The 14th positional arg `auth_anchor_hash` is `Option<String>` in\n // the Rust WASM constructor (the 9th arg `min_pegin_fee_rate` requires\n // the two-rate constructor from btc-vault #1930). Production peg-ins\n // (PeginManager) always commit an OP_RETURN <PUSH32 SHA256(authAnchor)>\n // output at `vout = hashlocks.length`; the unfunded template must\n // include it so `fromFundedTransaction` aligns with the funded tx.\n // Normalize identically to the peg-in primitives (`0x` strip,\n // lowercase, length/charset validation) so a direct primitive caller\n // reusing successful peg-in params doesn't hand unnormalized bytes to\n // WASM. Pass `undefined` for legacy non-auth-anchored Pre-PegIns.\n const normalizedAuthAnchorHash = normalizeAuthAnchorHash(\n prePeginParams.authAnchorHash,\n );\n // Reconstruct the template under the same graph version the Pre-PegIn\n // was originally built with (the vault's stamped vaultCoreVersion).\n const unfundedTx = new WasmPrePeginTx(\n prePeginParams.vaultCoreVersion,\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(\n assertPositiveBigintArray(prePeginParams.pegInAmounts, \"pegInAmounts\"),\n ),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.minPeginFeeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n normalizedAuthAnchorHash,\n );\n\n let fundedTx: WasmPrePeginTx | null = null;\n try {\n // Cross-check the reconstructed unfunded template against the funded\n // transaction: the WASM template's HTLC scriptPubKey at `htlcVout`\n // must equal the bytes the funded tx carries at the same output.\n // If they disagree, the template was reconstructed from the wrong\n // (hashlocks, amounts) vector — signing it would produce a refund\n // that does not spend the on-chain HTLC the depositor expects.\n // This is the explicit invariant the audit recommends: never sign a\n // refund whose template doesn't match the on-chain output bytes.\n const expectedHtlcScriptPubKey = unfundedTx\n .getHtlcScriptPubKey(htlcVout)\n .toLowerCase();\n // The reconstructed template's HTLC output value at `htlcVout`,\n // sized by WASM from the supplied `pegInAmounts` via the protocol\n // formula `htlcValue = peginAmount + depositorClaimValue + minPeginFee`.\n // Captured before `fromFundedTransaction` to bind it to the value the\n // funded tx actually carries (see the cross-check below).\n const expectedHtlcValue = unfundedTx.getHtlcValue(htlcVout);\n\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n txGraphVersion: prePeginParams.vaultCoreVersion,\n depositorPubkey: prePeginParams.depositorPubkey,\n vaultProviderPubkey: prePeginParams.vaultProviderPubkey,\n vaultKeeperPubkeys: prePeginParams.vaultKeeperPubkeys,\n universalChallengerPubkeys: prePeginParams.universalChallengerPubkeys,\n hashlock,\n timelockRefund: prePeginParams.timelockRefund,\n network: prePeginParams.network,\n });\n\n const cleanPrePeginHex = fundedPrePeginTxHex.startsWith(\"0x\")\n ? fundedPrePeginTxHex.slice(2)\n : fundedPrePeginTxHex;\n const prePeginTx = Transaction.fromHex(cleanPrePeginHex);\n\n const htlcOutput = prePeginTx.outs[htlcVout];\n if (!htlcOutput) {\n throw new Error(\n `HTLC output at vout ${htlcVout} not found in funded Pre-PegIn tx ` +\n `(tx has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const actualHtlcScriptPubKey = uint8ArrayToHex(\n new Uint8Array(htlcOutput.script),\n ).toLowerCase();\n if (actualHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `HTLC scriptPubKey mismatch at vout ${htlcVout}: reconstructed ` +\n `template expects ${expectedHtlcScriptPubKey}, funded tx carries ` +\n `${actualHtlcScriptPubKey}. Refund refused — the (hashlocks, ` +\n `pegInAmounts) vector does not match the on-chain commitment.`,\n );\n }\n\n // Value cross-check (mirrors the script check above): the template's\n // HTLC value — derived by WASM from `pegInAmounts` via the protocol\n // formula — must equal the value the funded tx pays at this output.\n // A caller that hands the full HTLC output value (or any wrong amount)\n // as `pegInAmounts` would inflate the template value and trip this\n // guard, rather than silently signing a refund built from a template\n // that disagrees with the on-chain commitment.\n const actualHtlcValue = BigInt(htlcOutput.value);\n if (actualHtlcValue !== expectedHtlcValue) {\n throw new Error(\n `HTLC value mismatch at vout ${htlcVout}: reconstructed template ` +\n `expects ${expectedHtlcValue} sat, funded tx carries ` +\n `${actualHtlcValue} sat. Refund refused — the pegInAmounts vector ` +\n `does not match the on-chain commitment.`,\n );\n }\n\n const refundTx = Transaction.fromHex(refundTxHex);\n\n if (refundTx.ins.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 input, got ${refundTx.ins.length}`,\n );\n }\n\n const refundInput = refundTx.ins[0];\n\n // Verify the refund input spends the correct Pre-PegIn HTLC output\n const prePeginTxid = prePeginTx.getId();\n const refundInputTxid = uint8ArrayToHex(\n new Uint8Array(refundInput.hash).slice().reverse(),\n );\n if (refundInputTxid !== prePeginTxid) {\n throw new Error(\n `Refund input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${refundInputTxid}`,\n );\n }\n if (refundInput.index !== htlcVout) {\n throw new Error(\n `Refund input index ${refundInput.index} does not match expected htlcVout ${htlcVout}`,\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(refundTx.version);\n psbt.setLocktime(refundTx.locktime);\n\n psbt.addInput({\n hash: refundInput.hash,\n index: refundInput.index,\n sequence: refundInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hexToUint8Array(htlcConnector.refundScript)),\n controlBlock: Buffer.from(\n hexToUint8Array(htlcConnector.refundControlBlock),\n ),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n\n // Output side: pin the single refund output to the depositor's own\n // BIP-86 P2TR address, mirroring the input-side pinning above. WASM\n // builds the refund output from the refund leaf's depositor key, so a\n // correct template always pays exactly one output back to the depositor.\n // Asserting it here means a malformed template (or a tampered WASM)\n // cannot redirect the reclaimed funds to a script the depositor does\n // not control.\n if (refundTx.outs.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 output, got ${refundTx.outs.length}`,\n );\n }\n const refundOutput = refundTx.outs[0];\n const expectedDepositorScriptPubKey = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(prePeginParams.depositorPubkey),\n ).toLowerCase();\n const actualRefundOutputScriptPubKey = uint8ArrayToHex(\n new Uint8Array(refundOutput.script),\n ).toLowerCase();\n if (actualRefundOutputScriptPubKey !== expectedDepositorScriptPubKey) {\n throw new Error(\n `Refund output scriptPubKey ${actualRefundOutputScriptPubKey} does not ` +\n `match the depositor's BIP-86 address ${expectedDepositorScriptPubKey}. ` +\n `Refund refused — the reclaimed funds would not return to the depositor.`,\n );\n }\n\n // Value: the single refund output must return the full HTLC value minus\n // exactly the requested fee. The refund is 1-in/1-out (asserted above), so\n // a value below `htlcValue - refundFee` means WASM applied a larger fee\n // than requested — the difference would be burned as miner fee. Pin it so\n // the depositor reclaims the expected amount, not a silently reduced one.\n const expectedRefundOutputValue = actualHtlcValue - refundFee;\n if (BigInt(refundOutput.value) !== expectedRefundOutputValue) {\n throw new Error(\n `Refund output value ${BigInt(refundOutput.value)} sat does not equal ` +\n `the HTLC value ${actualHtlcValue} sat minus the requested fee ` +\n `${refundFee} sat (expected ${expectedRefundOutputValue} sat). ` +\n `Refund refused — the reclaimed amount would be burned as excess fee.`,\n );\n }\n\n psbt.addOutput({\n script: refundOutput.script,\n value: refundOutput.value,\n });\n\n return { psbtHex: psbt.toHex() };\n } finally {\n fundedTx?.free();\n unfundedTx.free();\n }\n}\n","/**\n * Reclaim PSBT Builder Primitive\n *\n * Builds an unsigned PSBT that sweeps the depositor-claim reserve — PegIn\n * vout 1 — back to the depositor's own BIP-86 address.\n *\n * The reserve funds the depositor's `claim_tx`, their recourse if the vault\n * provider fails during peg-out. When the vault provider claims instead and\n * the depositor withdraws normally, nothing ever spends it. This primitive is\n * the only thing in the repository that can.\n *\n * Spend path: the single `<depositor> OP_CHECKSIG` tapleaf (see\n * ./depositorClaim). No timelock, no counterparty signature — the depositor's\n * Schnorr signature alone. That is also why the *caller* must gate: this\n * builder will happily sweep a reserve whose vault is still live, which would\n * permanently void the depositor's pre-signed recourse graph. Eligibility is\n * enforced upstream, in the service.\n *\n * @module primitives/psbt/reclaim\n */\n\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { DUST_THRESHOLD } from \"../../utils/fee/constants\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport {\n PEGIN_DEPOSITOR_CLAIM_VOUT,\n deriveDepositorClaimDescriptor,\n} from \"./depositorClaim\";\n\n/**\n * nVersion for the reclaim transaction. Plain v2, not TRUC: the reserve is only\n * offered once its PegIn is deeply confirmed, so the v2/v3 PegIn's nVersion-3\n * topology limits no longer constrain its children.\n */\nconst RECLAIM_TX_VERSION = 2;\n\n/**\n * nSequence for every reclaim input: RBF-enabled, no relative timelock. The\n * claim leaf carries no CSV, so this is a fee-bumping signal only.\n */\nconst RECLAIM_INPUT_SEQUENCE = 0xfffffffd;\n\n/**\n * Weight units of the reclaim transaction's skeleton — everything except the\n * inputs. Non-witness `version(4) + inCount(1) + outCount(1) + locktime(4) +\n * output(8 + 1 + 34)` = 53 B × 4, plus the 2 WU SegWit marker and flag.\n */\nconst RECLAIM_SKELETON_WEIGHT_UNITS = 214;\n\n/**\n * Weight units each script-path input adds. Non-witness `outpoint(36) +\n * scriptSigLen(1) + sequence(4)` = 41 B × 4 = 164, plus a witness of\n * `stackCount(1) + sig(1 + 64) + leafScript(1 + 34) + controlBlock(1 + 33)` =\n * 135 WU.\n *\n * Exact rather than conservative: every element is fixed-length here — a\n * 64-byte BIP-340 signature under SIGHASH_DEFAULT, the 34-byte leaf, and a\n * 33-byte control block with no merkle path.\n */\nconst RECLAIM_INPUT_WEIGHT_UNITS = 299;\n\n/** Weight units per virtual byte. */\nconst WEIGHT_UNITS_PER_VBYTE = 4;\n\n/**\n * Virtual size of an N-in/1-out reclaim transaction.\n *\n * `REFUND_VSIZE = 160` does not generalise to N inputs, and\n * `computePeginBaseFeeSats` is wrong for this shape entirely — its\n * `P2TR_INPUT_SIZE = 58` is a *key-path* input and under-fees a script-path\n * spend by roughly a quarter.\n *\n * N=1 → 129 vB; each additional input adds 75 vB.\n */\nexport function reclaimVsize(numInputs: number): number {\n if (!Number.isInteger(numInputs) || numInputs < 1) {\n throw new Error(\n `Reclaim input count must be a positive integer, got ${numInputs}.`,\n );\n }\n return Math.ceil(\n (RECLAIM_SKELETON_WEIGHT_UNITS +\n RECLAIM_INPUT_WEIGHT_UNITS * numInputs) /\n WEIGHT_UNITS_PER_VBYTE,\n );\n}\n\n/** Absolute fee in satoshis for an N-in/1-out reclaim at a given rate. */\nexport function estimateReclaimFeeSats(\n feeRateSatsVb: number,\n numInputs: number,\n): bigint {\n if (!Number.isFinite(feeRateSatsVb) || feeRateSatsVb <= 0) {\n throw new Error(\n `Reclaim fee rate must be a positive number, got ${feeRateSatsVb}.`,\n );\n }\n return BigInt(Math.ceil(feeRateSatsVb * reclaimVsize(numInputs)));\n}\n\n/** One depositor-claim reserve to sweep, with the material to bind it. */\nexport interface ReclaimReserve {\n /**\n * The contract's own copy of the depositor-signed PegIn transaction\n * (`VaultProtocolInfo.depositorSignedPeginTx`). Authoritative: its SegWit\n * txid equals the broadcast PegIn's, and its `outs[1]` carries the reserve's\n * script and value at no extra RPC cost.\n */\n depositorSignedPeginTxHex: string;\n /** Independent chain observation of `peginTxid:1` (esplora UTXO lookup). */\n observed: {\n /** scriptPubKey hex, with or without `0x` prefix. */\n scriptPubKey: string;\n /** Output value in satoshis. */\n value: bigint;\n };\n /**\n * The reserve value recomputed from this vault's protocol parameters via\n * `computeMinClaimValue`. Bound so a doctored PegIn that agrees with itself\n * and with a compromised indexer still fails.\n */\n expectedValue: bigint;\n}\n\nexport interface BuildReclaimPsbtParams {\n /**\n * The **connected wallet's live** x-only pubkey, 64-char hex. Never the\n * indexer's `depositorBtcPubkey`: re-deriving from the live key is what\n * proves the wallet about to sign is the wallet that can spend, and rejects\n * the wrong-wallet case with an error instead of an unspendable broadcast.\n */\n depositorPubkey: string;\n /**\n * Reserves to sweep. An array so batching several vaults into one\n * transaction is a later change rather than a rewrite; today the app passes\n * exactly one.\n */\n inputs: ReclaimReserve[];\n /** Absolute fee in satoshis. The caller sizes it; see `reclaimVsize`. */\n feeSats: bigint;\n}\n\nexport interface BuildReclaimPsbtResult {\n /** PSBT hex ready for depositor signing. */\n psbtHex: string;\n /** Value of the single output — what the depositor actually receives. */\n outputValue: bigint;\n /** Sum of the swept reserves, before fee. */\n totalInputValue: bigint;\n}\n\n/**\n * Build the N-in/1-out reclaim PSBT.\n *\n * Every input is bound three ways before it reaches the PSBT: the contract's\n * PegIn bytes, the chain observation, and a JS re-derivation from the live\n * wallet key must agree on both script and value. Any disagreement throws.\n *\n * @throws If `inputs` is empty, the fee is non-positive, any input fails its\n * script or value bind, or the resulting output would be at or below dust.\n */\nexport function buildReclaimPsbt(\n params: BuildReclaimPsbtParams,\n): BuildReclaimPsbtResult {\n const { depositorPubkey, inputs, feeSats } = params;\n\n if (inputs.length === 0) {\n throw new Error(\"Reclaim requires at least one input; got none.\");\n }\n if (feeSats <= 0n) {\n throw new Error(\n `Reclaim fee must be positive, got ${feeSats} sat. Refusing to build a ` +\n `transaction that would not relay.`,\n );\n }\n\n // One derivation, reused for every input's bind and for the destination.\n const descriptor = deriveDepositorClaimDescriptor(depositorPubkey);\n const expectedScriptPubKey = uint8ArrayToHex(\n new Uint8Array(descriptor.scriptPubKey),\n ).toLowerCase();\n\n const psbt = new Psbt();\n psbt.setVersion(RECLAIM_TX_VERSION);\n psbt.setLocktime(0);\n\n let totalInputValue = 0n;\n const seenOutpoints = new Set<string>();\n\n inputs.forEach((input, i) => {\n const peginTx = Transaction.fromHex(\n stripHexPrefix(input.depositorSignedPeginTxHex),\n );\n const peginTxid = peginTx.getId();\n\n const claimOut = peginTx.outs[PEGIN_DEPOSITOR_CLAIM_VOUT];\n if (!claimOut) {\n throw new Error(\n `PegIn ${peginTxid} has no output at vout ` +\n `${PEGIN_DEPOSITOR_CLAIM_VOUT} (tx has ${peginTx.outs.length}); ` +\n `there is no depositor-claim reserve to reclaim.`,\n );\n }\n\n // Bind 1: the contract's PegIn bytes against the JS re-derivation from the\n // live wallet key. This is the assertion that proves the connected wallet\n // can actually spend the output we are about to sign for.\n const contractScriptPubKey = uint8ArrayToHex(\n new Uint8Array(claimOut.script),\n ).toLowerCase();\n if (contractScriptPubKey !== expectedScriptPubKey) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} pays ` +\n `${contractScriptPubKey}, but the connected wallet's depositor-claim ` +\n `script is ${expectedScriptPubKey}. Reclaim refused — this reserve ` +\n `belongs to a different wallet.`,\n );\n }\n\n // Bind 2: the independent chain observation must agree with both.\n const observedScriptPubKey = stripHexPrefix(\n input.observed.scriptPubKey,\n ).toLowerCase();\n if (observedScriptPubKey !== expectedScriptPubKey) {\n throw new Error(\n `Input ${i}: the observed UTXO ${peginTxid}:${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `pays ${observedScriptPubKey}, expected ${expectedScriptPubKey}. ` +\n `Reclaim refused — chain state disagrees with the contract's PegIn.`,\n );\n }\n\n // Value bind, same three ways.\n const contractValue = BigInt(claimOut.value);\n if (contractValue !== input.observed.value) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `carries ${contractValue} sat, but the observed UTXO carries ` +\n `${input.observed.value} sat. Reclaim refused.`,\n );\n }\n if (contractValue !== input.expectedValue) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `carries ${contractValue} sat, but this vault's parameters compute a ` +\n `depositor-claim value of ${input.expectedValue} sat. Reclaim refused.`,\n );\n }\n\n // A batch that names the same vault twice would otherwise double-count the\n // swept total and then fail deep inside bitcoinjs. Reject it here, where\n // the message can say which input is the duplicate.\n const outpoint = `${peginTxid}:${PEGIN_DEPOSITOR_CLAIM_VOUT}`;\n if (seenOutpoints.has(outpoint)) {\n throw new Error(\n `Input ${i} repeats outpoint ${outpoint}, which is already being ` +\n `swept by an earlier input. Reclaim refused.`,\n );\n }\n seenOutpoints.add(outpoint);\n\n totalInputValue += contractValue;\n\n psbt.addInput({\n hash: peginTxid,\n index: PEGIN_DEPOSITOR_CLAIM_VOUT,\n sequence: RECLAIM_INPUT_SEQUENCE,\n witnessUtxo: { script: claimOut.script, value: claimOut.value },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: descriptor.leafScript,\n controlBlock: descriptor.controlBlock,\n },\n ],\n tapInternalKey: descriptor.internalKey,\n });\n });\n\n if (feeSats >= totalInputValue) {\n throw new Error(\n `Reclaim fee ${feeSats} sat is not less than the swept total ` +\n `${totalInputValue} sat. Refusing to build a transaction with no output.`,\n );\n }\n\n const outputValue = totalInputValue - feeSats;\n if (outputValue <= DUST_THRESHOLD) {\n throw new Error(\n `Reclaim output ${outputValue} sat is at or below the dust threshold ` +\n `${DUST_THRESHOLD} sat. The reserve is not at risk — it stays where it ` +\n `is until fee rates fall.`,\n );\n }\n\n const destination = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(depositorPubkey),\n );\n psbt.addOutput({\n script: Buffer.from(hexToUint8Array(destination)),\n value: Number(outputValue),\n });\n\n return { psbtHex: psbt.toHex(), outputValue, totalInputValue };\n}\n","/**\n * NoPayout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's NoPayout transaction\n * (depositor-as-claimer path, per challenger). The depositor signs input 0\n * using the NoPayout taproot script from WasmAssertPayoutNoPayoutConnector.\n *\n * @module primitives/psbt/noPayout\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — Assert output 0 NoPayout connector\n */\n\nimport {\n type AssertPayoutNoPayoutConnectorParams,\n type Network,\n getAssertNoPayoutScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction, payments } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n getNetwork,\n hexToUint8Array,\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a NoPayout PSBT\n */\nexport interface NoPayoutParams {\n /** NoPayout transaction hex (unsigned) from VP */\n noPayoutTxHex: string;\n /** Challenger's x-only public key (hex encoded) */\n challengerPubkey: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/**\n * Validate that a NoPayout transaction pays to the challenger via the\n * protocol-defined output structure: a single BIP-86 P2TR output derived from\n * the challenger's x-only pubkey.\n *\n * Mirrors the per-role payout output validation now inlined in\n * `buildPayoutPsbt` for the NoPayout path, where the sink is fixed by the\n * protocol rather than read from on-chain registration\n * (see `crates/vault/src/transactions/nopayout.rs::NoPayoutTx::new`).\n *\n * @param noPayoutTxHex - Raw NoPayout transaction hex\n * @param challengerPubkey - Challenger's x-only public key (hex)\n * @param network - Bitcoin network used to derive the P2TR scriptPubKey\n * @throws If the transaction does not have exactly one output\n * @throws If the single output's scriptPubKey does not equal the BIP-86 P2TR\n * scriptPubKey for the challenger\n */\nexport function assertNoPayoutOutputMatchesChallenger(\n noPayoutTxHex: string,\n challengerPubkey: string,\n network: Network,\n): void {\n const tx = Transaction.fromHex(stripHexPrefix(noPayoutTxHex));\n\n if (tx.outs.length !== 1) {\n throw new Error(\n `NoPayout transaction must have exactly 1 output, got ${tx.outs.length}`,\n );\n }\n\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(challengerPubkey));\n const { output: expectedScript } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!expectedScript) {\n throw new Error(\n \"Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation\",\n );\n }\n\n if (!tx.outs[0].script.equals(expectedScript)) {\n throw new Error(\n \"NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address\",\n );\n }\n}\n"],"names":["buildRefundPsbt","params","initWasm","prePeginParams","fundedPrePeginTxHex","htlcVout","refundFee","hashlock","normalizedAuthAnchorHash","normalizeAuthAnchorHash","unfundedTx","WasmPrePeginTx","assertPositiveBigintArray","fundedTx","expectedHtlcScriptPubKey","expectedHtlcValue","refundTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","cleanPrePeginHex","prePeginTx","Transaction","htlcOutput","actualHtlcScriptPubKey","uint8ArrayToHex","actualHtlcValue","refundTx","refundInput","prePeginTxid","refundInputTxid","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","hexToUint8Array","tapInternalPubkey","refundOutput","expectedDepositorScriptPubKey","stripHexPrefix","deriveBip86ScriptPubKeyHex","actualRefundOutputScriptPubKey","expectedRefundOutputValue","RECLAIM_TX_VERSION","RECLAIM_INPUT_SEQUENCE","RECLAIM_SKELETON_WEIGHT_UNITS","RECLAIM_INPUT_WEIGHT_UNITS","WEIGHT_UNITS_PER_VBYTE","reclaimVsize","numInputs","estimateReclaimFeeSats","feeRateSatsVb","buildReclaimPsbt","depositorPubkey","inputs","feeSats","descriptor","deriveDepositorClaimDescriptor","expectedScriptPubKey","totalInputValue","seenOutpoints","input","i","peginTx","peginTxid","claimOut","PEGIN_DEPOSITOR_CLAIM_VOUT","contractScriptPubKey","observedScriptPubKey","contractValue","outpoint","outputValue","DUST_THRESHOLD","destination","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","prevout","inputData","output","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","expectedScript","payments","getNetwork"],"mappings":"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"}
|