@babylonlabs-io/ts-sdk 0.10.0 → 0.12.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/challengeAssert-DW0sEUgn.cjs +2 -0
- package/dist/challengeAssert-DW0sEUgn.cjs.map +1 -0
- package/dist/{challengeAssert-D50t_Qyo.js → challengeAssert-DnnliaRt.js} +66 -60
- package/dist/challengeAssert-DnnliaRt.js.map +1 -0
- package/dist/{errors-fLxe1eml.js → errors-DOJdtNTD.js} +367 -316
- package/dist/errors-DOJdtNTD.js.map +1 -0
- package/dist/errors-DbATYfYA.cjs +2 -0
- package/dist/errors-DbATYfYA.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +66 -64
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +68 -66
- package/dist/tbv/core/managers/PeginManager.d.ts +41 -44
- package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
- package/dist/tbv/core/primitives/__tests__/deriveVaultId.test.d.ts +6 -0
- package/dist/tbv/core/primitives/__tests__/deriveVaultId.test.d.ts.map +1 -0
- 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 +12 -12
- package/dist/tbv/core/primitives/psbt/pegin.d.ts +10 -11
- package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
- package/dist/tbv/core/utils/fee/constants.d.ts +16 -0
- package/dist/tbv/core/utils/fee/constants.d.ts.map +1 -1
- package/dist/tbv/core/utils/utxo/selectUtxos.d.ts +2 -1
- package/dist/tbv/core/utils/utxo/selectUtxos.d.ts.map +1 -1
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +68 -66
- package/package.json +3 -3
- package/dist/challengeAssert-D50t_Qyo.js.map +0 -1
- package/dist/challengeAssert-DDceAi0r.cjs +0 -2
- package/dist/challengeAssert-DDceAi0r.cjs.map +0 -1
- package/dist/errors-CIDTtluC.cjs +0 -2
- package/dist/errors-CIDTtluC.cjs.map +0 -1
- package/dist/errors-fLxe1eml.js.map +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";const y=require("@babylonlabs-io/babylon-tbv-rust-wasm"),p=require("bitcoinjs-lib"),a=require("buffer"),z=require("@bitcoin-js/tiny-secp256k1-asmjs");function $(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const e in t)if(e!=="default"){const r=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(n,e,r.get?r:{enumerable:!0,get:()=>t[e]})}}return n.default=t,Object.freeze(n)}const L=$(p),m=$(z);function P(t){return t.startsWith("0x")?t.slice(2):t}function M(t){return t.startsWith("0x")?t:`0x${t}`}function g(t){const n=P(t);if(!I(n))throw new Error(`Invalid hex string: ${t}`);const e=new Uint8Array(n.length/2);for(let r=0;r<n.length;r+=2)e[r/2]=parseInt(n.slice(r,r+2),16);return e}function x(t){return Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("")}function O(t){return t.length===32?t:t.slice(1,33)}function I(t){return/^[0-9a-fA-F]*$/.test(t)&&t.length%2===0}function w(t){const n=P(t);if(!I(n))throw new Error(`Invalid hex characters in public key: ${t}`);if(n.length===64)return n;if(n.length!==66&&n.length!==130)throw new Error(`Invalid public key length: ${n.length} (expected 64, 66, or 130 hex chars)`);const e=g(n);return x(O(e))}function X(t){const n=P(t);return I(n)}function Y(t,n){const e=w(t),r=n??e;if(e.toLowerCase()!==r.toLowerCase())throw new Error(`Wallet public key does not match vault depositor. Expected: ${r}, Got: ${e}. Please connect the wallet that was used to create this vault.`);return{walletPubkeyRaw:t,walletPubkeyXOnly:e,depositorPubkey:r}}let U=!1;function G(){U||(p.initEccLib(m),U=!0)}function B(t){switch(t){case"bitcoin":return p.networks.bitcoin;case"testnet":case"signet":return p.networks.testnet;case"regtest":return p.networks.regtest;default:throw new Error(`Unknown network: ${t}`)}}function F(t,n){G();const e=g(w(t)),{address:r}=p.payments.p2tr({internalPubkey:a.Buffer.from(e),network:B(n)});if(!r)throw new Error("Failed to derive taproot address from public key");return r}function R(t,n){const e=P(t);if(e.length!==66)throw new Error(`Native SegWit requires a compressed public key (66 hex chars), got ${e.length}`);const{address:r}=p.payments.p2wpkh({pubkey:a.Buffer.from(g(e)),network:B(n)});if(!r)throw new Error("Failed to derive native segwit address from public key");return r}function Z(t,n,e){const r=P(n);try{if(t===F(r,e))return!0}catch{}const o=[];r.length===66?o.push(r):r.length===64&&o.push(`02${r}`,`03${r}`);for(const i of o)try{if(t===R(i,e))return!0}catch{}return!1}function E(t){return w(t).toLowerCase()}function j(t,n,e){const r=new Set;r.add(E(t));for(const o of n)r.add(E(o));return r.delete(E(e)),r.size}const Q=58,J=43,tt=11,N=546,V=BigInt(N),W=30,K=2,et=1.1;function nt(t){return t<=K?W:0}const q=1;function rt(t){return t+q}const ot=5;function A(t){const e=t.substring(8,12)==="0001"?12:8,r=parseInt(t.substring(e,e+2),16),o=parseInt(t.substring(e+2,e+4),16);if(r!==0)throw new Error(`Expected 0 inputs from WASM, got ${r}`);if(o===0)throw new Error("Expected at least 1 output from WASM, got 0");const i=a.Buffer.from(t.substring(0,8),"hex").readUInt32LE(0),c=a.Buffer.from(t.substring(t.length-8),"hex").readUInt32LE(0),u=[];let s=e+4;for(let f=0;f<o;f++){const l=t.substring(s,s+16),d=Number(a.Buffer.from(l,"hex").readBigUInt64LE(0));s+=16;const h=parseInt(t.substring(s,s+2),16);s+=2;const b=t.substring(s,s+h*2),k=a.Buffer.from(b,"hex");s+=h*2,u.push({value:d,script:k})}return{version:i,locktime:c,outputs:u}}function it(t){const{unfundedTxHex:n,selectedUTXOs:e,changeAddress:r,changeAmount:o,network:i}=t,{version:c,locktime:u,outputs:s}=A(n),f=new L.Transaction;f.version=c,f.locktime=u;for(const l of e){const d=a.Buffer.from(l.txid,"hex").reverse();f.addInput(d,l.vout)}for(const l of s)f.addOutput(l.script,l.value);if(o>V){const l=L.address.toOutputScript(r,i);f.addOutput(l,Number(o))}return f.toHex()}async function st(t){const n=await y.createPrePeginTransaction({depositorPubkey:t.depositorPubkey,vaultProviderPubkey:t.vaultProviderPubkey,vaultKeeperPubkeys:t.vaultKeeperPubkeys,universalChallengerPubkeys:t.universalChallengerPubkeys,hashlocks:[...t.hashlocks],timelockRefund:t.timelockRefund,pegInAmounts:[...t.pegInAmounts],feeRate:t.feeRate,numLocalChallengers:t.numLocalChallengers,councilQuorum:t.councilQuorum,councilSize:t.councilSize,network:t.network}),r=A(n.txHex).outputs.reduce((o,i)=>o+BigInt(i.value),0n);return{psbtHex:n.txHex,totalOutputValue:r,htlcValues:n.htlcValues,htlcScriptPubKeys:n.htlcScriptPubKeys,htlcAddresses:n.htlcAddresses,peginAmounts:n.peginAmounts,depositorClaimValue:n.depositorClaimValue}}async function ut(t){const n=await y.buildPeginTxFromPrePegin({depositorPubkey:t.prePeginParams.depositorPubkey,vaultProviderPubkey:t.prePeginParams.vaultProviderPubkey,vaultKeeperPubkeys:t.prePeginParams.vaultKeeperPubkeys,universalChallengerPubkeys:t.prePeginParams.universalChallengerPubkeys,hashlocks:[...t.prePeginParams.hashlocks],timelockRefund:t.prePeginParams.timelockRefund,pegInAmounts:[...t.prePeginParams.pegInAmounts],feeRate:t.prePeginParams.feeRate,numLocalChallengers:t.prePeginParams.numLocalChallengers,councilQuorum:t.prePeginParams.councilQuorum,councilSize:t.prePeginParams.councilSize,network:t.prePeginParams.network},t.timelockPegin,t.fundedPrePeginTxHex,t.htlcVout);return{txHex:n.txHex,txid:n.txid,vaultScriptPubKey:n.vaultScriptPubKey,vaultValue:n.vaultValue}}async function ct(t){const n=P(t.peginTxHex),e=P(t.fundedPrePeginTxHex),r=await y.getPrePeginHtlcConnectorInfo({depositorPubkey:t.depositorPubkey,vaultProviderPubkey:t.vaultProviderPubkey,vaultKeeperPubkeys:t.vaultKeeperPubkeys,universalChallengerPubkeys:t.universalChallengerPubkeys,hashlock:t.hashlock,timelockRefund:t.timelockRefund,network:t.network}),o=p.Transaction.fromHex(n),i=p.Transaction.fromHex(e);if(o.ins.length!==1)throw new Error(`PegIn transaction must have exactly 1 input, got ${o.ins.length}`);const c=o.ins[0],u=i.getId(),s=x(new Uint8Array(c.hash).slice().reverse());if(s!==u)throw new Error(`PegIn input does not reference the Pre-PegIn transaction. Expected ${u}, got ${s}`);const f=i.outs[c.index];if(!f)throw new Error(`Pre-PegIn output ${c.index} not found (Pre-PegIn has ${i.outs.length} outputs)`);const l=g(r.hashlockScript),d=g(r.hashlockControlBlock),h=new p.Psbt;h.setVersion(o.version),h.setLocktime(o.locktime),h.addInput({hash:c.hash,index:c.index,sequence:c.sequence,witnessUtxo:{script:f.script,value:f.value},tapLeafScript:[{leafVersion:192,script:a.Buffer.from(l),controlBlock:a.Buffer.from(d)}],tapInternalKey:a.Buffer.from(y.tapInternalPubkey)});for(const b of o.outs)h.addOutput({script:b.script,value:b.value});return{psbtHex:h.toHex()}}function at(t,n){const r=p.Psbt.fromHex(t).data.inputs[0];if(!r)throw new Error("PegIn PSBT has no inputs");if(r.tapScriptSig&&r.tapScriptSig.length>0){const o=a.Buffer.from(g(n));for(const i of r.tapScriptSig)if(i.pubkey.equals(o))return pt(i.signature);throw new Error(`No PegIn input signature found for depositor pubkey: ${n}`)}throw r.finalScriptWitness&&r.finalScriptWitness.length>0?new Error("PegIn input PSBT is already finalized. Cannot reliably extract the depositor signature from the witness stack. Ensure the wallet returns a non-finalized PSBT with tapScriptSig entries."):new Error("No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT")}function lt(t){const n=p.Psbt.fromHex(t);try{n.finalizeAllInputs()}catch(e){if(!n.data.inputs.every(o=>o.finalScriptWitness||o.finalScriptSig))throw new Error(`PSBT finalization failed and wallet did not auto-finalize: ${e}`)}return n.extractTransaction().toHex()}function pt(t){if(t.length===64)return x(new Uint8Array(t));if(t.length===65)return x(new Uint8Array(t.subarray(0,64)));throw new Error(`Unexpected PegIn input signature length: ${t.length}`)}async function D(t){const n=await y.createPayoutConnector({depositor:t.depositor,vaultProvider:t.vaultProvider,vaultKeepers:t.vaultKeepers,universalChallengers:t.universalChallengers,timelockPegin:t.timelockPegin},t.network);return{payoutScript:n.payoutScript,taprootScriptHash:n.taprootScriptHash,scriptPubKey:n.scriptPubKey,address:n.address}}p.initEccLib(m);async function ft(t){const n=P(t.payoutTxHex),e=P(t.peginTxHex),r=P(t.assertTxHex),o=await D({depositor:t.depositorBtcPubkey,vaultProvider:t.vaultProviderBtcPubkey,vaultKeepers:t.vaultKeeperBtcPubkeys,universalChallengers:t.universalChallengerBtcPubkeys,timelockPegin:t.timelockPegin,network:t.network}),i=g(o.payoutScript),c=gt(y.tapInternalPubkey,i),u=p.Transaction.fromHex(n),s=p.Transaction.fromHex(e),f=p.Transaction.fromHex(r),l=new p.Psbt;if(l.setVersion(u.version),l.setLocktime(u.locktime),u.ins.length!==2)throw new Error(`Payout transaction must have exactly 2 inputs, got ${u.ins.length}`);const d=u.ins[0],h=u.ins[1],b=x(new Uint8Array(d.hash).slice().reverse()),k=s.getId();if(b!==k)throw new Error(`Input 0 does not reference pegin transaction. Expected ${k}, got ${b}`);const v=x(new Uint8Array(h.hash).slice().reverse()),H=f.getId();if(v!==H)throw new Error(`Input 1 does not reference assert transaction. Expected ${H}, got ${v}`);const S=s.outs[d.index];if(!S)throw new Error(`Previous output not found for input 0 (txid: ${b}, index: ${d.index})`);const T=f.outs[h.index];if(!T)throw new Error(`Previous output not found for input 1 (txid: ${v}, index: ${h.index})`);l.addInput({hash:d.hash,index:d.index,sequence:d.sequence,witnessUtxo:{script:S.script,value:S.value},tapLeafScript:[{leafVersion:192,script:a.Buffer.from(i),controlBlock:a.Buffer.from(c)}],tapInternalKey:a.Buffer.from(y.tapInternalPubkey)}),l.addInput({hash:h.hash,index:h.index,sequence:h.sequence,witnessUtxo:{script:T.script,value:T.value}});for(const _ of u.outs)l.addOutput({script:_.script,value:_.value});return{psbtHex:l.toHex()}}function dt(t,n,e=0){const r=p.Psbt.fromHex(t);if(e>=r.data.inputs.length)throw new Error(`Input index ${e} out of range (${r.data.inputs.length} inputs)`);const o=r.data.inputs[e];if(o.tapScriptSig&&o.tapScriptSig.length>0){const i=g(n);for(const c of o.tapScriptSig)if(c.pubkey.equals(a.Buffer.from(i)))return C(c.signature,e);throw new Error(`No signature found for depositor pubkey: ${n} at input ${e}`)}if(o.finalScriptWitness&&o.finalScriptWitness.length>0){const i=Pt(o.finalScriptWitness);if(i.length>=1)return C(i[0],e)}throw new Error(`No tapScriptSig or finalScriptWitness found in signed PSBT at input ${e}`)}function C(t,n){if(t.length===64)return x(new Uint8Array(t));if(t.length===65){const e=t[64];if(e!==p.Transaction.SIGHASH_ALL)throw new Error(`Unexpected sighash type 0x${e.toString(16).padStart(2,"0")} at input ${n}. Expected SIGHASH_ALL (0x01).`);return x(new Uint8Array(t.subarray(0,64)))}throw new Error(`Unexpected signature length at input ${n}: ${t.length}`)}function Pt(t){const n=[];let e=0;const r=()=>{const i=t[e++];if(i<253)return i;if(i===253){const c=t[e]|t[e+1]<<8;return e+=2,c}if(i===254){const c=t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24;return e+=4,c}return e+=8,0},o=r();for(let i=0;i<o;i++){const c=r();n.push(t.subarray(e,e+c)),e+=c}return n}function gt(t,n){const e={output:a.Buffer.from(n)},o=p.payments.p2tr({internalPubkey:a.Buffer.from(t),scriptTree:e}).pubkey;if(!o)throw new Error("Failed to compute output key");const i=192,c=o[0]===3?1:0,u=i|c,s=new Uint8Array(1+t.length);return s[0]=u,s.set(t,1),s}p.initEccLib(m);async function ht(t){const n=P(t.payoutTxHex),e=p.Transaction.fromHex(n),r=await y.getPeginPayoutScript(t.connectorParams),o=g(r),i=yt(y.tapInternalPubkey,o),c=new p.Psbt;c.setVersion(e.version),c.setLocktime(e.locktime);for(let u=0;u<e.ins.length;u++){const s=e.ins[u],f=t.prevouts[u];if(!f)throw new Error(`Missing prevout data for input ${u}`);const l={hash:s.hash,index:s.index,sequence:s.sequence,witnessUtxo:{script:a.Buffer.from(g(P(f.script_pubkey))),value:f.value}};u===0&&(l.tapLeafScript=[{leafVersion:192,script:a.Buffer.from(o),controlBlock:a.Buffer.from(i)}],l.tapInternalKey=a.Buffer.from(y.tapInternalPubkey)),c.addInput(l)}for(const u of e.outs)c.addOutput({script:u.script,value:u.value});return c.toHex()}function yt(t,n){const e={output:a.Buffer.from(n)},o=p.payments.p2tr({internalPubkey:a.Buffer.from(t),scriptTree:e}).pubkey;if(!o)throw new Error("Failed to compute output key");const i=192,c=o[0]===3?1:0,u=i|c,s=new Uint8Array(1+t.length);return s[0]=u,s.set(t,1),s}async function xt(t){const n=P(t.noPayoutTxHex),e=p.Transaction.fromHex(n),{noPayoutScript:r,noPayoutControlBlock:o}=await y.getAssertNoPayoutScriptInfo(t.connectorParams,t.challengerPubkey),i=g(r),c=g(o),u=new p.Psbt;u.setVersion(e.version),u.setLocktime(e.locktime);for(let s=0;s<e.ins.length;s++){const f=e.ins[s],l=t.prevouts[s];if(!l)throw new Error(`Missing prevout data for input ${s}`);const d={hash:f.hash,index:f.index,sequence:f.sequence,witnessUtxo:{script:a.Buffer.from(g(P(l.script_pubkey))),value:l.value}};s===0&&(d.tapLeafScript=[{leafVersion:192,script:a.Buffer.from(i),controlBlock:a.Buffer.from(c)}],d.tapInternalKey=a.Buffer.from(y.tapInternalPubkey)),u.addInput(d)}for(const s of e.outs)u.addOutput({script:s.script,value:s.value});return u.toHex()}async function bt(t){const n=P(t.challengeAssertTxHex),e=p.Transaction.fromHex(n);if(t.connectorParamsPerInput.length!==e.ins.length)throw new Error(`Expected ${e.ins.length} connector params, got ${t.connectorParamsPerInput.length}`);const r=await Promise.all(t.connectorParamsPerInput.map(i=>y.getChallengeAssertScriptInfo(i))),o=new p.Psbt;o.setVersion(e.version),o.setLocktime(e.locktime);for(let i=0;i<e.ins.length;i++){const c=e.ins[i],u=t.prevouts[i];if(!u)throw new Error(`Missing prevout data for input ${i}`);const{script:s,controlBlock:f}=r[i],l=g(s),d=g(f);o.addInput({hash:c.hash,index:c.index,sequence:c.sequence,witnessUtxo:{script:a.Buffer.from(g(P(u.script_pubkey))),value:u.value},tapLeafScript:[{leafVersion:192,script:a.Buffer.from(l),controlBlock:a.Buffer.from(d)}],tapInternalKey:a.Buffer.from(y.tapInternalPubkey)})}for(const i of e.outs)o.addOutput({script:i.script,value:i.value});return o.toHex()}exports.BTC_DUST_SAT=N;exports.DUST_THRESHOLD=V;exports.FEE_SAFETY_MARGIN=et;exports.LOW_RATE_ESTIMATION_ACCURACY_BUFFER=W;exports.MAX_NON_LEGACY_OUTPUT_SIZE=J;exports.P2TR_INPUT_SIZE=Q;exports.PEGIN_FIXED_OUTPUTS=q;exports.SPLIT_TX_FEE_SAFETY_MULTIPLIER=ot;exports.TX_BUFFER_SIZE_OVERHEAD=tt;exports.WALLET_RELAY_FEE_RATE_THRESHOLD=K;exports.buildChallengeAssertPsbt=bt;exports.buildDepositorPayoutPsbt=ht;exports.buildNoPayoutPsbt=xt;exports.buildPayoutPsbt=ft;exports.buildPeginInputPsbt=ct;exports.buildPeginTxFromFundedPrePegin=ut;exports.buildPrePeginPsbt=st;exports.computeNumLocalChallengers=j;exports.createPayoutScript=D;exports.deriveNativeSegwitAddress=R;exports.deriveTaprootAddress=F;exports.ensureHexPrefix=M;exports.extractPayoutSignature=dt;exports.extractPeginInputSignature=at;exports.finalizePeginInputPsbt=lt;exports.fundPeginTransaction=it;exports.getNetwork=B;exports.hexToUint8Array=g;exports.isAddressFromPublicKey=Z;exports.isValidHex=X;exports.parseUnfundedWasmTransaction=A;exports.peginOutputCount=rt;exports.processPublicKeyToXOnly=w;exports.rateBasedTxBufferFee=nt;exports.stripHexPrefix=P;exports.toXOnly=O;exports.uint8ArrayToHex=x;exports.validateWalletPubkey=Y;
|
|
2
|
+
//# sourceMappingURL=challengeAssert-DW0sEUgn.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"challengeAssert-DW0sEUgn.cjs","sources":["../src/tbv/core/primitives/utils/bitcoin.ts","../src/tbv/core/primitives/challengers.ts","../src/tbv/core/utils/fee/constants.ts","../src/tbv/core/utils/transaction/fundPeginTransaction.ts","../src/tbv/core/primitives/psbt/pegin.ts","../src/tbv/core/primitives/psbt/peginInput.ts","../src/tbv/core/primitives/scripts/payout.ts","../src/tbv/core/primitives/psbt/payout.ts","../src/tbv/core/primitives/psbt/depositorPayout.ts","../src/tbv/core/primitives/psbt/noPayout.ts","../src/tbv/core/primitives/psbt/challengeAssert.ts"],"sourcesContent":["/**\n * Bitcoin Utilities\n *\n * Common pure utility functions for Bitcoin operations including:\n * - Public key conversions (x-only format)\n * - Hex string manipulation\n * - Uint8Array conversions and validation\n * - Address derivation and validation\n *\n * All functions are pure (no side effects) and work in Node.js, browsers,\n * and serverless environments.\n *\n * @module primitives/utils/bitcoin\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { Buffer } from \"buffer\";\nimport { initEccLib, networks, payments } from \"bitcoinjs-lib\";\n\nimport type { Network } from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport type { Hex } from \"viem\";\n\n/**\n * Strip \"0x\" prefix from hex string if present.\n *\n * Bitcoin expects plain hex (no \"0x\" prefix), but frontend often uses\n * Ethereum-style \"0x\"-prefixed hex.\n *\n * @param hex - Hex string with or without \"0x\" prefix\n * @returns Hex string without \"0x\" prefix\n */\nexport function stripHexPrefix(hex: string): string {\n return hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n}\n\n/**\n * Ensure \"0x\" prefix on a hex string, returning viem's Hex type.\n *\n * Ethereum/viem APIs expect `0x`-prefixed hex, but Bitcoin tooling\n * typically omits the prefix. This normalises either form.\n *\n * @param hex - Hex string with or without \"0x\" prefix\n * @returns `0x`-prefixed hex string typed as viem Hex\n */\nexport function ensureHexPrefix(hex: string): Hex {\n return hex.startsWith(\"0x\") ? (hex as Hex) : (`0x${hex}` as Hex);\n}\n\n/**\n * Convert hex string to Uint8Array.\n *\n * @param hex - Hex string (with or without 0x prefix)\n * @returns Uint8Array\n * @throws If hex is invalid\n */\nexport function hexToUint8Array(hex: string): Uint8Array {\n const cleanHex = stripHexPrefix(hex);\n if (!isValidHexRaw(cleanHex)) {\n throw new Error(`Invalid hex string: ${hex}`);\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Convert Uint8Array to hex string (without 0x prefix).\n *\n * @param bytes - Uint8Array to convert\n * @returns Hex string without 0x prefix\n */\nexport function uint8ArrayToHex(bytes: Uint8Array): string {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Convert a 33-byte public key to 32-byte x-only format (removes first byte).\n *\n * Used for Taproot/Schnorr signatures which only need the x-coordinate.\n * If the input is already 32 bytes, returns it unchanged.\n *\n * @param pubKey - 33-byte or 32-byte public key\n * @returns 32-byte x-only public key\n */\nexport function toXOnly(pubKey: Uint8Array): Uint8Array {\n return pubKey.length === 32 ? pubKey : pubKey.slice(1, 33);\n}\n\n/**\n * Internal helper: Validate hex string format without stripping prefix\n *\n * @internal\n * @param hex - Hex string (must already have prefix stripped)\n * @returns true if valid hex string\n */\nfunction isValidHexRaw(hex: string): boolean {\n return /^[0-9a-fA-F]*$/.test(hex) && hex.length % 2 === 0;\n}\n\n/**\n * Process and convert a public key to x-only format (32 bytes hex).\n *\n * Handles:\n * - 0x prefix removal\n * - Hex character validation\n * - Length validation\n * - Conversion to x-only format\n *\n * Accepts:\n * - 64 hex chars (32 bytes) - already x-only\n * - 66 hex chars (33 bytes) - compressed pubkey\n * - 130 hex chars (65 bytes) - uncompressed pubkey\n *\n * @param publicKeyHex - Public key in hex format (with or without 0x prefix)\n * @returns X-only public key as 32 bytes hex string (without 0x prefix)\n * @throws If public key format is invalid or contains invalid hex characters\n */\nexport function processPublicKeyToXOnly(publicKeyHex: string): string {\n // Remove '0x' prefix if present\n const cleanHex = stripHexPrefix(publicKeyHex);\n\n // Validate hex characters early to prevent silent failures\n if (!isValidHexRaw(cleanHex)) {\n throw new Error(`Invalid hex characters in public key: ${publicKeyHex}`);\n }\n\n // If already 64 chars (32 bytes), it's already x-only format\n if (cleanHex.length === 64) {\n return cleanHex;\n }\n\n // Validate public key length (should be 66 chars for compressed or 130 for uncompressed)\n if (cleanHex.length !== 66 && cleanHex.length !== 130) {\n throw new Error(\n `Invalid public key length: ${cleanHex.length} (expected 64, 66, or 130 hex chars)`,\n );\n }\n\n const pubkeyBytes = hexToUint8Array(cleanHex);\n return uint8ArrayToHex(toXOnly(pubkeyBytes));\n}\n\n/**\n * Validate hex string format.\n *\n * Checks that the string contains only valid hexadecimal characters (0-9, a-f, A-F)\n * and has an even length (since each byte is represented by 2 hex characters).\n *\n * @param hex - String to validate (with or without 0x prefix)\n * @returns true if valid hex string\n */\nexport function isValidHex(hex: string): boolean {\n const cleanHex = stripHexPrefix(hex);\n return isValidHexRaw(cleanHex);\n}\n\n/**\n * Result of validating a wallet public key against an expected depositor public key.\n */\nexport interface WalletPubkeyValidationResult {\n /** Wallet's raw public key (as returned by wallet, may be compressed) */\n walletPubkeyRaw: string;\n /** Wallet's public key in x-only format (32 bytes, 64 hex chars) */\n walletPubkeyXOnly: string;\n /** The validated depositor public key (x-only format) */\n depositorPubkey: string;\n}\n\n/**\n * Validate that a wallet's public key matches the expected depositor public key.\n *\n * This function:\n * 1. Converts the wallet pubkey to x-only format\n * 2. Uses the expected depositor pubkey if provided, otherwise falls back to wallet pubkey\n * 3. Validates they match (case-insensitive)\n *\n * @param walletPubkeyRaw - Raw public key from wallet (may be compressed 66 chars or x-only 64 chars)\n * @param expectedDepositorPubkey - Expected depositor public key (x-only, optional)\n * @returns Validation result with both pubkey formats\n * @throws If wallet pubkey doesn't match expected depositor pubkey\n */\nexport function validateWalletPubkey(\n walletPubkeyRaw: string,\n expectedDepositorPubkey?: string,\n): WalletPubkeyValidationResult {\n const walletPubkeyXOnly = processPublicKeyToXOnly(walletPubkeyRaw);\n const depositorPubkey = expectedDepositorPubkey ?? walletPubkeyXOnly;\n\n if (walletPubkeyXOnly.toLowerCase() !== depositorPubkey.toLowerCase()) {\n throw new Error(\n `Wallet public key does not match vault depositor. ` +\n `Expected: ${depositorPubkey}, Got: ${walletPubkeyXOnly}. ` +\n `Please connect the wallet that was used to create this vault.`\n );\n }\n\n return { walletPubkeyRaw, walletPubkeyXOnly, depositorPubkey };\n}\n\n// ============================================================================\n// Address derivation and validation\n// ============================================================================\n\nlet eccInitialized = false;\n\nfunction ensureEcc(): void {\n if (!eccInitialized) {\n initEccLib(ecc);\n eccInitialized = true;\n }\n}\n\n/**\n * Map SDK network type to bitcoinjs-lib Network object.\n *\n * @param network - Network type (\"bitcoin\", \"testnet\", \"signet\", \"regtest\")\n * @returns bitcoinjs-lib Network object\n */\nexport function getNetwork(network: Network): networks.Network {\n switch (network) {\n case \"bitcoin\":\n return networks.bitcoin;\n case \"testnet\":\n case \"signet\":\n return networks.testnet;\n case \"regtest\":\n return networks.regtest;\n default:\n throw new Error(`Unknown network: ${network}`);\n }\n}\n\n/**\n * Derive a Taproot (P2TR) address from a public key.\n *\n * @param publicKeyHex - Compressed (66 hex) or x-only (64 hex) public key\n * @param network - Bitcoin network\n * @returns Taproot address (bc1p... / tb1p... / bcrt1p...)\n */\nexport function deriveTaprootAddress(\n publicKeyHex: string,\n network: Network,\n): string {\n ensureEcc();\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(publicKeyHex));\n const { address } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!address) {\n throw new Error(\"Failed to derive taproot address from public key\");\n }\n return address;\n}\n\n/**\n * Derive a Native SegWit (P2WPKH) address from a compressed public key.\n *\n * @param publicKeyHex - Compressed public key (66 hex chars, with or without 0x prefix)\n * @param network - Bitcoin network\n * @returns Native SegWit address (bc1q... / tb1q... / bcrt1q...)\n * @throws If publicKeyHex is not a compressed public key (66 hex chars)\n */\nexport function deriveNativeSegwitAddress(\n publicKeyHex: string,\n network: Network,\n): string {\n const cleanHex = stripHexPrefix(publicKeyHex);\n if (cleanHex.length !== 66) {\n throw new Error(\n `Native SegWit requires a compressed public key (66 hex chars), got ${cleanHex.length}`,\n );\n }\n const { address } = payments.p2wpkh({\n pubkey: Buffer.from(hexToUint8Array(cleanHex)),\n network: getNetwork(network),\n });\n if (!address) {\n throw new Error(\n \"Failed to derive native segwit address from public key\",\n );\n }\n return address;\n}\n\n/**\n * Validate that a BTC address was derived from the given public key.\n *\n * Derives Taproot (P2TR) and Native SegWit (P2WPKH) addresses from the\n * public key and checks if the provided address matches any of them.\n *\n * When the input is an x-only key (64 hex chars), both possible compressed\n * keys (`02` + x and `03` + x) are tried for Native SegWit derivation,\n * since the y-parity is unknown.\n *\n * @param address - BTC address to validate\n * @param publicKeyHex - Public key from the wallet (x-only 64 or compressed 66 hex chars)\n * @param network - Bitcoin network\n * @returns true if the address matches the public key\n */\nexport function isAddressFromPublicKey(\n address: string,\n publicKeyHex: string,\n network: Network,\n): boolean {\n const cleanHex = stripHexPrefix(publicKeyHex);\n\n // P2TR — works with both x-only and compressed keys\n try {\n if (address === deriveTaprootAddress(cleanHex, network)) {\n return true;\n }\n } catch {\n // derivation failed, continue\n }\n\n // Build the list of compressed keys to try for P2WPKH\n const compressedKeys: string[] = [];\n if (cleanHex.length === 66) {\n compressedKeys.push(cleanHex);\n } else if (cleanHex.length === 64) {\n // x-only key — try both even (02) and odd (03) y-parity\n compressedKeys.push(`02${cleanHex}`, `03${cleanHex}`);\n }\n\n for (const key of compressedKeys) {\n try {\n if (address === deriveNativeSegwitAddress(key, network)) {\n return true;\n }\n } catch {\n // derivation failed, continue\n }\n }\n\n return false;\n}\n","/**\n * Challenger counting utilities.\n *\n * Used for UI-level validation (e.g. computing minimum deposit amounts)\n * where the depositor's identity is known. The transaction builders use\n * `vaultKeeperBtcPubkeys.length` to match the VP's current validation.\n */\n\nimport { processPublicKeyToXOnly } from \"./utils/bitcoin\";\n\n/**\n * Normalize a public key to lowercase x-only hex for reliable comparison.\n *\n * Handles `0x` prefixes, compressed (33-byte), and uncompressed (65-byte) keys.\n */\nfunction normalizeKey(key: string): string {\n return processPublicKeyToXOnly(key).toLowerCase();\n}\n\n/**\n * Compute the number of local challengers for a vault.\n *\n * Mirrors the VP's `compute_num_challengers()` logic:\n * local challengers = {vault_provider} ∪ {vault_keepers} − {depositor}\n *\n * Keys are normalized to x-only lowercase hex before comparison, so\n * `0x`-prefixed, compressed, or mixed-case keys are handled correctly.\n *\n * @param vaultProviderPubkey - Vault provider BTC public key\n * @param vaultKeeperPubkeys - Vault keeper BTC public keys\n * @param depositorPubkey - Depositor (claimer) BTC public key\n * @returns Number of local challengers\n */\nexport function computeNumLocalChallengers(\n vaultProviderPubkey: string,\n vaultKeeperPubkeys: string[],\n depositorPubkey: string,\n): number {\n const localSet = new Set<string>();\n localSet.add(normalizeKey(vaultProviderPubkey));\n for (const vk of vaultKeeperPubkeys) {\n localSet.add(normalizeKey(vk));\n }\n localSet.delete(normalizeKey(depositorPubkey));\n return localSet.size;\n}\n","/**\n * Fee calculation constants for Bitcoin transactions.\n * Based on btc-staking-ts values, adapted for vault peg-in transactions.\n */\n\n// P2TR input size in vbytes (42 vbytes non-witness + 16 vbytes witness)\nexport const P2TR_INPUT_SIZE = 58;\n\n// P2TR output size in bytes (largest non-legacy output type)\nexport const MAX_NON_LEGACY_OUTPUT_SIZE = 43;\n\n// Base transaction overhead (version, input/output counts, locktime, SegWit marker)\nexport const TX_BUFFER_SIZE_OVERHEAD = 11;\n\n// Dust threshold: outputs below this may not be relayed\nexport const BTC_DUST_SAT = 546;\n\n/** Pre-computed BigInt dust threshold to avoid repeated conversions in hot paths */\nexport const DUST_THRESHOLD = BigInt(BTC_DUST_SAT);\n\n// Buffer for low fee rate estimation accuracy (when feeRate <= 2 sat/vbyte)\nexport const LOW_RATE_ESTIMATION_ACCURACY_BUFFER = 30;\n\n// Wallet relay fee rate threshold - different buffer fees are used based on this\nexport const WALLET_RELAY_FEE_RATE_THRESHOLD = 2;\n\n// Safety margin: 10% buffer for size variations and fee market volatility\nexport const FEE_SAFETY_MARGIN = 1.1;\n\n/**\n * Adds a buffer to the transaction fee calculation if the fee rate is low.\n *\n * Some wallets have a relayer fee requirement. If the fee rate is <= 2 sat/vbyte,\n * there's a risk the fee might not be sufficient for transaction relay.\n * We add a buffer to ensure the transaction can be relayed.\n *\n * @param feeRate - Fee rate in satoshis per vbyte\n * @returns Buffer amount in satoshis to add to the transaction fee\n */\nexport function rateBasedTxBufferFee(feeRate: number): number {\n return feeRate <= WALLET_RELAY_FEE_RATE_THRESHOLD\n ? LOW_RATE_ESTIMATION_ACCURACY_BUFFER\n : 0;\n}\n\n/**\n * Number of fixed (non-HTLC) outputs in a Pre-PegIn transaction.\n * Currently this is 1 CPFP anchor output.\n */\nexport const PEGIN_FIXED_OUTPUTS = 1;\n\n/**\n * Compute the total number of outputs (before change) in a Pre-PegIn transaction.\n *\n * A Pre-PegIn tx has: N HTLC outputs (one per vault) + fixed outputs (CPFP anchor).\n * This count is used for fee estimation — the change output is handled separately\n * by selectUtxosForPegin when the change amount exceeds the dust threshold.\n *\n * @param vaultCount - Number of vaults in the batch (1 for single-vault)\n * @returns Total output count before change\n */\nexport function peginOutputCount(vaultCount: number): number {\n return vaultCount + PEGIN_FIXED_OUTPUTS;\n}\n\n/**\n * Safety multiplier for split transaction fee validation.\n * The signed PSBT's fee rate and absolute fee must not exceed this multiple\n * of the planned values. 5x accounts for witness estimation variance while\n * catching catastrophic wallet-side overpayment.\n */\nexport const SPLIT_TX_FEE_SAFETY_MULTIPLIER = 5;\n","/**\n * Transaction Funding Utility for Peg-in Transactions\n *\n * This module funds an unfunded transaction template from the SDK by adding\n * UTXO inputs and change outputs, creating a transaction ready for wallet signing.\n *\n * Transaction Flow:\n * 1. SDK buildPeginPsbt() → unfunded transaction (0 inputs, vault + depositor claim outputs)\n * 2. selectUtxosForPegin() → select UTXOs and calculate fees\n * 3. fundPeginTransaction() → add inputs/change, create funded transaction\n *\n * Technical Note:\n * We manually extract the vault output from SDK hex instead of using bitcoinjs-lib\n * parsing because bitcoinjs-lib cannot parse 0-input transactions (even witness format).\n */\n\nimport * as bitcoin from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { DUST_THRESHOLD } from \"../fee/constants\";\nimport type { UTXO } from \"../utxo/selectUtxos\";\n\nexport interface FundPeginTransactionParams {\n /** Unfunded transaction hex from SDK (0 inputs, vault + depositor claim outputs) */\n unfundedTxHex: string;\n /** Selected UTXOs to use as inputs */\n selectedUTXOs: UTXO[];\n /** Change address (from wallet) */\n changeAddress: string;\n /** Change amount in satoshis */\n changeAmount: bigint;\n /** Bitcoin network */\n network: bitcoin.Network;\n}\n\n/** A single parsed output from the unfunded WASM transaction */\ninterface ParsedOutput {\n value: number;\n script: Buffer;\n}\n\n/** Parsed data from an unfunded WASM transaction */\ninterface ParsedUnfundedTx {\n version: number;\n locktime: number;\n outputs: ParsedOutput[];\n}\n\n/**\n * Parses an unfunded transaction hex from WASM.\n *\n * WASM produces witness-format transactions with 0 inputs, which bitcoinjs-lib cannot parse.\n * This function manually extracts the transaction components.\n *\n * Format: [version:4bytes][marker:0x00][flag:0x01][inputs:1byte=0x00][outputCount:1byte]\n * [output1: value:8bytes + scriptLen:1byte + script:N bytes]\n * [output2: ...]\n * [locktime:4bytes]\n *\n * @param unfundedTxHex - Raw transaction hex from WASM\n * @returns Parsed transaction components\n * @throws Error if transaction structure is invalid\n */\nexport function parseUnfundedWasmTransaction(\n unfundedTxHex: string,\n): ParsedUnfundedTx {\n // Check if witness markers are present (0x00 0x01 after version)\n const hasWitnessMarkers = unfundedTxHex.substring(8, 12) === \"0001\";\n const dataOffset = hasWitnessMarkers ? 12 : 8; // Skip version (8) + optional witness markers (4)\n\n // Parse input/output counts\n const inputCount = parseInt(\n unfundedTxHex.substring(dataOffset, dataOffset + 2),\n 16,\n );\n const outputCount = parseInt(\n unfundedTxHex.substring(dataOffset + 2, dataOffset + 4),\n 16,\n );\n\n if (inputCount !== 0) {\n throw new Error(`Expected 0 inputs from WASM, got ${inputCount}`);\n }\n if (outputCount === 0) {\n throw new Error(\"Expected at least 1 output from WASM, got 0\");\n }\n\n // Parse version (first 4 bytes, little-endian)\n const version = Buffer.from(unfundedTxHex.substring(0, 8), \"hex\").readUInt32LE(0);\n\n // Parse locktime (last 4 bytes, little-endian)\n const locktime = Buffer.from(\n unfundedTxHex.substring(unfundedTxHex.length - 8),\n \"hex\",\n ).readUInt32LE(0);\n\n // Parse all outputs sequentially\n const outputs: ParsedOutput[] = [];\n let pos = dataOffset + 4; // position after input/output counts\n\n for (let i = 0; i < outputCount; i++) {\n const valueHex = unfundedTxHex.substring(pos, pos + 16);\n const value = Number(Buffer.from(valueHex, \"hex\").readBigUInt64LE(0));\n pos += 16;\n\n const scriptLen = parseInt(unfundedTxHex.substring(pos, pos + 2), 16);\n pos += 2;\n\n const scriptHex = unfundedTxHex.substring(pos, pos + scriptLen * 2);\n const script = Buffer.from(scriptHex, \"hex\");\n pos += scriptLen * 2;\n\n outputs.push({ value, script });\n }\n\n return { version, locktime, outputs };\n}\n\n/**\n * Funds an unfunded peg-in transaction by adding inputs and change output.\n *\n * Takes an unfunded transaction template (0 inputs, 1 vault output) from the SDK\n * and adds UTXO inputs and a change output to create a funded transaction ready\n * for wallet signing.\n *\n * @param params - Transaction funding parameters\n * @returns Transaction hex string ready for wallet signing\n */\nexport function fundPeginTransaction(\n params: FundPeginTransactionParams,\n): string {\n const { unfundedTxHex, selectedUTXOs, changeAddress, changeAmount, network } =\n params;\n\n // Parse the unfunded transaction from WASM\n const { version, locktime, outputs } =\n parseUnfundedWasmTransaction(unfundedTxHex);\n\n // Create a new transaction with the extracted data\n const tx = new bitcoin.Transaction();\n tx.version = version;\n tx.locktime = locktime;\n\n // Add inputs from selected UTXOs\n for (const utxo of selectedUTXOs) {\n // Bitcoin uses reversed byte order for txid\n const txHash = Buffer.from(utxo.txid, \"hex\").reverse();\n tx.addInput(txHash, utxo.vout);\n }\n\n // Add all WASM outputs (vault output at index 0, depositor claim at index 1, etc.)\n for (const output of outputs) {\n tx.addOutput(output.script, output.value);\n }\n\n // Add change output if above dust threshold\n if (changeAmount > DUST_THRESHOLD) {\n const changeScript = bitcoin.address.toOutputScript(changeAddress, network);\n tx.addOutput(changeScript, Number(changeAmount));\n }\n\n return tx.toHex();\n}\n\n// Re-export getNetwork from the canonical location in primitives\nexport { getNetwork } from \"../../primitives/utils/bitcoin\";\n","/**\n * Pre-PegIn PSBT Builder Primitive\n *\n * This module provides pure functions for building unfunded Pre-PegIn transactions\n * and deriving PegIn transactions from them, using the WASM implementation from\n * @babylonlabs-io/babylon-tbv-rust-wasm.\n *\n * Pre-PegIn Flow:\n * 1. buildPrePeginPsbt() — creates unfunded Pre-PegIn tx (HTLC output)\n * 2. [caller funds Pre-PegIn tx and computes txid]\n * 3. buildPeginTxFromFundedPrePegin() — derives PegIn tx spending the HTLC\n * 4. buildPeginInputPsbt() — PSBT for depositor to sign PegIn HTLC leaf 0 input\n *\n * @module primitives/psbt/pegin\n */\n\nimport {\n createPrePeginTransaction,\n buildPeginTxFromPrePegin,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\n\nimport { parseUnfundedWasmTransaction } from \"../../utils/transaction/fundPeginTransaction\";\n\n/**\n * Parameters for building an unfunded Pre-PegIn PSBT\n */\nexport interface PrePeginParams {\n /** Depositor's BTC public key (x-only, 64-char hex without 0x prefix) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Array of vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Array of universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment(s) (64 hex chars = 32 bytes each) */\n hashlocks: readonly string[];\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Amounts to peg in (satoshis), one per deposit */\n pegInAmounts: readonly bigint[];\n /** Fee rate in sat/vB from contract offchain params */\n feeRate: bigint;\n /** Number of local challengers (from contract params) */\n numLocalChallengers: number;\n /** M in M-of-N council multisig (from contract params) */\n councilQuorum: number;\n /** N in M-of-N council multisig (from contract params) */\n councilSize: number;\n /** Bitcoin network */\n network: Network;\n}\n\n/**\n * Result of building an unfunded Pre-PegIn transaction\n */\nexport interface PrePeginPsbtResult {\n /**\n * Unfunded transaction hex (no inputs, HTLC output + CPFP anchor).\n *\n * The caller is responsible for:\n * - Selecting UTXOs covering totalOutputValue + network fees\n * - Funding the transaction (add inputs and change output)\n * - Computing the funded transaction's txid\n * - Calling buildPeginTxFromFundedPrePegin() with the funded txid\n */\n psbtHex: string;\n /** Sum of all unfunded outputs (HTLC + CPFP anchor) — use this for UTXO selection */\n totalOutputValue: bigint;\n /** HTLC output values in satoshis, one per deposit (each includes peginAmount + depositorClaimValue + minPeginFee) */\n htlcValues: readonly bigint[];\n /** HTLC output scriptPubKeys (hex encoded), one per deposit */\n htlcScriptPubKeys: readonly string[];\n /** HTLC Taproot addresses, one per deposit */\n htlcAddresses: readonly string[];\n /** Pegin amounts in satoshis, one per deposit */\n peginAmounts: readonly bigint[];\n /** Depositor claim value computed by WASM from contract parameters */\n depositorClaimValue: bigint;\n}\n\n/**\n * Parameters for building the PegIn transaction from a funded Pre-PegIn txid\n */\nexport interface BuildPeginTxParams {\n /** Same PrePeginParams used to create the Pre-PegIn transaction */\n prePeginParams: PrePeginParams;\n /** CSV timelock in blocks for the PegIn vault output */\n timelockPegin: number;\n /** Hex-encoded funded Pre-PegIn transaction */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output to spend */\n htlcVout: number;\n}\n\n/**\n * Result of building the PegIn transaction\n */\nexport interface PeginTxResult {\n /** PegIn transaction hex (1 input spending HTLC, 1 vault output) */\n txHex: string;\n /** PegIn transaction ID */\n txid: string;\n /** Vault output scriptPubKey (hex encoded) */\n vaultScriptPubKey: string;\n /** Vault output value in satoshis */\n vaultValue: bigint;\n}\n\n/**\n * Build unfunded Pre-PegIn transaction using WASM.\n *\n * Creates a Bitcoin transaction template with no inputs, an HTLC output, and a\n * CPFP anchor output. The HTLC value is computed internally from the contract\n * parameters — the caller does not need to compute depositorClaimValue separately.\n *\n * @param params - Pre-PegIn parameters\n * @returns Unfunded Pre-PegIn transaction details with HTLC output information\n * @throws If WASM initialization fails or parameters are invalid\n */\nexport async function buildPrePeginPsbt(\n params: PrePeginParams,\n): Promise<PrePeginPsbtResult> {\n const result = await createPrePeginTransaction({\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlocks: [...params.hashlocks],\n timelockRefund: params.timelockRefund,\n pegInAmounts: [...params.pegInAmounts],\n feeRate: params.feeRate,\n numLocalChallengers: params.numLocalChallengers,\n councilQuorum: params.councilQuorum,\n councilSize: params.councilSize,\n network: params.network,\n });\n\n // Parse the unfunded tx to sum all output values (HTLC + CPFP anchor).\n // This is the amount UTXOs must cover before adding network fees.\n const parsed = parseUnfundedWasmTransaction(result.txHex);\n const totalOutputValue = parsed.outputs.reduce(\n (sum, o) => sum + BigInt(o.value),\n 0n,\n );\n\n return {\n psbtHex: result.txHex,\n totalOutputValue,\n htlcValues: result.htlcValues,\n htlcScriptPubKeys: result.htlcScriptPubKeys,\n htlcAddresses: result.htlcAddresses,\n peginAmounts: result.peginAmounts,\n depositorClaimValue: result.depositorClaimValue,\n };\n}\n\n/**\n * Build the PegIn transaction from a funded Pre-PegIn transaction.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output at htlcVout via the\n * hashlock + all-party script (leaf 0).\n *\n * @param params - Build parameters including Pre-PegIn params and funded tx hex\n * @returns PegIn transaction details\n * @throws If WASM initialization fails or parameters are invalid\n */\nexport async function buildPeginTxFromFundedPrePegin(\n params: BuildPeginTxParams,\n): Promise<PeginTxResult> {\n const result = await buildPeginTxFromPrePegin(\n {\n depositorPubkey: params.prePeginParams.depositorPubkey,\n vaultProviderPubkey: params.prePeginParams.vaultProviderPubkey,\n vaultKeeperPubkeys: params.prePeginParams.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.prePeginParams.universalChallengerPubkeys,\n hashlocks: [...params.prePeginParams.hashlocks],\n timelockRefund: params.prePeginParams.timelockRefund,\n pegInAmounts: [...params.prePeginParams.pegInAmounts],\n feeRate: params.prePeginParams.feeRate,\n numLocalChallengers: params.prePeginParams.numLocalChallengers,\n councilQuorum: params.prePeginParams.councilQuorum,\n councilSize: params.prePeginParams.councilSize,\n network: params.prePeginParams.network,\n },\n params.timelockPegin,\n params.fundedPrePeginTxHex,\n params.htlcVout,\n );\n\n return {\n txHex: result.txHex,\n txid: result.txid,\n vaultScriptPubKey: result.vaultScriptPubKey,\n vaultValue: result.vaultValue,\n };\n}\n","/**\n * PegIn Input PSBT Builder\n *\n * Builds the PSBT for the depositor to sign the PegIn transaction's HTLC input\n * (Pre-PegIn HTLC leaf 0 — the hashlock + all-party script).\n *\n * This is the \"Sign Pegin transaction HTLC leaf 0 input\" step in the pre-pegin\n * flow. The depositor signs input 0 of the PegIn transaction,\n * which spends output 0 of the funded Pre-PegIn transaction via script-path.\n *\n * @module primitives/psbt/peginInput\n */\n\nimport {\n getPrePeginHtlcConnectorInfo,\n tapInternalPubkey,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { hexToUint8Array, stripHexPrefix, uint8ArrayToHex } from \"../utils/bitcoin\";\n\n/**\n * Parameters for building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtParams {\n /**\n * PegIn transaction hex (1 input spending Pre-PegIn HTLC output 0).\n * Returned by buildPeginTxFromFundedPrePegin().\n */\n peginTxHex: string;\n /**\n * Funded Pre-PegIn transaction hex.\n * Used to look up the HTLC output that the PegIn input spends.\n */\n fundedPrePeginTxHex: string;\n /** Depositor's BTC public key (x-only, 64-char hex) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment (64 hex chars = 32 bytes) */\n hashlock: string;\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Bitcoin network */\n network: Network;\n}\n\n/**\n * Result of building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtResult {\n /** PSBT hex for the depositor to sign */\n psbtHex: string;\n}\n\n/**\n * Build PSBT for depositor to sign the PegIn transaction's HTLC leaf 0 input.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output (output 0) via the\n * hashlock + all-party script (leaf 0). The depositor provides one of the required\n * signatures; the vault provider and keepers provide theirs separately via the\n * signPeginInput RPC.\n *\n * The PSBT uses Taproot script-path spending:\n * - witnessUtxo: the Pre-PegIn HTLC output\n * - tapLeafScript: hashlock leaf script + control block\n * - tapInternalKey: NUMS unspendable key (BIP-341 nothing-up-my-sleeve)\n *\n * @param params - PegIn input PSBT parameters\n * @returns PSBT hex ready for depositor signing\n * @throws If PegIn tx does not have exactly 1 input\n * @throws If PegIn input does not reference the Pre-PegIn HTLC output\n * @throws If Pre-PegIn tx output 0 is not found\n */\nexport async function buildPeginInputPsbt(\n params: BuildPeginInputPsbtParams,\n): Promise<BuildPeginInputPsbtResult> {\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const fundedPrePeginTxHex = stripHexPrefix(params.fundedPrePeginTxHex);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlock: params.hashlock,\n timelockRefund: params.timelockRefund,\n network: params.network,\n });\n\n const peginTx = Transaction.fromHex(peginTxHex);\n const prePeginTx = Transaction.fromHex(fundedPrePeginTxHex);\n\n if (peginTx.ins.length !== 1) {\n throw new Error(\n `PegIn transaction must have exactly 1 input, got ${peginTx.ins.length}`,\n );\n }\n\n const peginInput = peginTx.ins[0];\n\n // Verify PegIn input 0 spends Pre-PegIn output 0\n const prePeginTxid = prePeginTx.getId();\n const peginInputTxid = uint8ArrayToHex(\n new Uint8Array(peginInput.hash).slice().reverse(),\n );\n\n if (peginInputTxid !== prePeginTxid) {\n throw new Error(\n `PegIn input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${peginInputTxid}`,\n );\n }\n\n const htlcOutput = prePeginTx.outs[peginInput.index];\n if (!htlcOutput) {\n throw new Error(\n `Pre-PegIn output ${peginInput.index} not found ` +\n `(Pre-PegIn has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const hashlockScript = hexToUint8Array(htlcConnector.hashlockScript);\n const hashlockControlBlock = hexToUint8Array(htlcConnector.hashlockControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(peginTx.version);\n psbt.setLocktime(peginTx.locktime);\n\n // Input 0: PegIn input spending Pre-PegIn HTLC output 0 via hashlock leaf (leaf 0).\n // The depositor signs using Taproot script-path spending.\n psbt.addInput({\n hash: peginInput.hash,\n index: peginInput.index,\n sequence: peginInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: 0xc0,\n script: Buffer.from(hashlockScript),\n controlBlock: Buffer.from(hashlockControlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n // sighashType omitted — defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n for (const output of peginTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n}\n\n/**\n * Extract the depositor's Schnorr signature from a signed PegIn input PSBT.\n *\n * Supports both non-finalized PSBTs (tapScriptSig) and finalized PSBTs (witness).\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's x-only public key (64-char hex)\n * @returns 64-byte Schnorr signature (128 hex chars, no sighash flag)\n * @throws If no signature is found for the depositor's key\n */\nexport function extractPeginInputSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n const input = signedPsbt.data.inputs[0];\n\n if (!input) {\n throw new Error(\"PegIn PSBT has no inputs\");\n }\n\n // Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = Buffer.from(\n hexToUint8Array(depositorPubkey),\n );\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(depositorPubkeyBytes)) {\n return extractSchnorrSig(sigEntry.signature);\n }\n }\n\n throw new Error(\n `No PegIn input signature found for depositor pubkey: ${depositorPubkey}`,\n );\n }\n\n // Finalized PSBT — the witness stack order depends on the wallet's finalizer,\n // so we cannot reliably pick the depositor's signature by position. Require\n // the non-finalized tapScriptSig path which identifies signatures by pubkey.\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n throw new Error(\n \"PegIn input PSBT is already finalized. Cannot reliably extract the \" +\n \"depositor signature from the witness stack. Ensure the wallet returns \" +\n \"a non-finalized PSBT with tapScriptSig entries.\",\n );\n }\n\n throw new Error(\n \"No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT\",\n );\n}\n\n/**\n * Finalize a signed PegIn input PSBT and return the depositor-signed transaction hex.\n *\n * The default tapscript finalizer builds the full witness stack [sig, script, controlBlock]\n * that vaultd requires when verifying the depositor signature on-chain.\n *\n * @param signedPsbtHex - Non-finalized signed PSBT hex (returned by wallet with autoFinalized: false)\n * @returns Depositor-signed PegIn transaction hex with full taproot witness stack\n */\nexport function finalizePeginInputPsbt(signedPsbtHex: string): string {\n const psbt = Psbt.fromHex(signedPsbtHex);\n\n // Some wallets (UniSat, OKX) ignore autoFinalized: false and return\n // already-finalized PSBTs. finalizeAllInputs() throws in that case,\n // so fall back to verifying the wallet already finalized all inputs.\n try {\n psbt.finalizeAllInputs();\n } catch (e) {\n const allFinalized = psbt.data.inputs.every(\n (inp) => inp.finalScriptWitness || inp.finalScriptSig,\n );\n if (!allFinalized) {\n throw new Error(\n `PSBT finalization failed and wallet did not auto-finalize: ${e}`,\n );\n }\n }\n\n return psbt.extractTransaction().toHex();\n}\n\n/** Extract and validate a 64-byte Schnorr signature, stripping sighash flag if present. */\nfunction extractSchnorrSig(sig: Uint8Array): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n }\n if (sig.length === 65) {\n return uint8ArrayToHex(new Uint8Array(sig.subarray(0, 64)));\n }\n throw new Error(`Unexpected PegIn input signature length: ${sig.length}`);\n}\n\n","/**\n * Payout Script Generator Primitive\n *\n * This module provides pure functions for generating payout scripts and taproot information\n * by wrapping the WASM implementation from @babylonlabs-io/babylon-tbv-rust-wasm.\n *\n * The payout script is used for signing payout transactions in the vault system.\n * It defines the spending conditions for the vault output, enabling the depositor\n * to authorize payouts during the peg-in flow (Step 3).\n *\n * @remarks\n * This is a low-level primitive. For most use cases, prefer using {@link buildPayoutPsbt}\n * which handles script creation internally. For high-level wallet orchestration, use\n * PayoutManager from the managers module.\n *\n * @see {@link buildPayoutPsbt} - Higher-level function that uses this internally\n *\n * @module primitives/scripts/payout\n */\n\nimport {\n createPayoutConnector,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\n\n/**\n * Parameters for creating a payout script.\n *\n * These parameters define the participants in a vault and are used to generate\n * the taproot script that controls how funds can be spent from the vault.\n */\nexport interface PayoutScriptParams {\n /**\n * Depositor's BTC public key (x-only, 64-char hex without 0x prefix).\n *\n * This is the user depositing BTC into the vault. The depositor must sign\n * payout transactions to authorize fund distribution.\n */\n depositor: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex without 0x prefix).\n *\n * The service provider managing vault operations. Also referred to as\n * \"claimer\" in the WASM layer.\n */\n vaultProvider: string;\n\n /**\n * Array of vault keeper BTC public keys (x-only, 64-char hex without 0x prefix).\n *\n * Vault keepers participate in vault operations and script spending conditions.\n */\n vaultKeepers: string[];\n\n /**\n * Array of universal challenger BTC public keys (x-only, 64-char hex without 0x prefix).\n *\n * These parties can challenge the vault under certain conditions.\n */\n universalChallengers: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Bitcoin network for script generation.\n *\n * Must match the network used for all other vault operations to ensure\n * address encoding compatibility.\n */\n network: Network;\n}\n\n/**\n * Result of creating a payout script.\n *\n * Contains all the taproot-related data needed for constructing and signing\n * payout transactions from the vault.\n */\nexport interface PayoutScriptResult {\n /**\n * The payout script hex used in taproot script path spending.\n *\n * This is the raw script bytes that define the spending conditions,\n * encoded as a hexadecimal string. Used when constructing the\n * tapLeafScript for PSBT signing.\n */\n payoutScript: string;\n\n /**\n * The taproot script hash (leaf hash) for the payout script.\n *\n * This is the tagged hash of the script used in taproot tree construction.\n * Required for computing the control block during script path spending.\n */\n taprootScriptHash: string;\n\n /**\n * The full scriptPubKey for the vault output address.\n *\n * This is the complete output script (OP_1 <32-byte-key>) that should be\n * used when creating the vault output in a peg-in transaction.\n */\n scriptPubKey: string;\n\n /**\n * The vault Bitcoin address derived from the script.\n *\n * A human-readable bech32m address (bc1p... for mainnet, tb1p... for testnet/signet)\n * that can be used to receive funds into the vault.\n */\n address: string;\n}\n\n/**\n * Create payout script and taproot information using WASM.\n *\n * This is a pure function that wraps the Rust WASM implementation.\n * The payout connector generates the necessary taproot scripts and information\n * required for signing payout transactions.\n *\n * @remarks\n * The generated script encodes spending conditions that require signatures from\n * the depositor and vault provider (or liquidators in challenge scenarios).\n * This script is used internally by {@link buildPayoutPsbt}.\n *\n * @param params - Payout script parameters defining vault participants and network\n * @returns Payout script and taproot information for PSBT construction\n *\n * @see {@link buildPayoutPsbt} - Use this for building complete payout PSBTs\n */\nexport async function createPayoutScript(\n params: PayoutScriptParams,\n): Promise<PayoutScriptResult> {\n // Call the WASM wrapper with the correct parameter structure\n const connector = await createPayoutConnector(\n {\n depositor: params.depositor,\n vaultProvider: params.vaultProvider,\n vaultKeepers: params.vaultKeepers,\n universalChallengers: params.universalChallengers,\n timelockPegin: params.timelockPegin,\n },\n params.network,\n );\n\n return {\n payoutScript: connector.payoutScript,\n taprootScriptHash: connector.taprootScriptHash,\n scriptPubKey: connector.scriptPubKey,\n address: connector.address,\n };\n}\n","/**\n * Payout PSBT Builder Primitives\n *\n * This module provides pure functions for building unsigned payout PSBTs and extracting\n * Schnorr signatures from signed PSBTs. It uses WASM-generated scripts from the payout\n * connector and bitcoinjs-lib for PSBT construction.\n *\n * The Payout transaction references the Assert transaction (input 1).\n *\n * @module primitives/psbt/payout\n */\n\nimport {\n type Network,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { Buffer } from \"buffer\";\nimport { initEccLib, payments, Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { createPayoutScript } from \"../scripts/payout\";\nimport {\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\n\n// Initialize ECC library for bitcoinjs-lib\ninitEccLib(ecc);\n\n/**\n * Parameters for building an unsigned Payout PSBT\n *\n * Payout is used in the challenge path after Assert, when the claimer proves validity.\n * Input 1 references the Assert transaction.\n */\nexport interface PayoutParams {\n /**\n * Payout transaction hex (unsigned)\n * This is the transaction that needs to be signed by the depositor\n */\n payoutTxHex: string;\n\n /**\n * Assert transaction hex\n * Payout input 1 references Assert output 0\n */\n assertTxHex: string;\n\n /**\n * Peg-in transaction hex\n * This transaction created the vault output that we're spending\n */\n peginTxHex: string;\n\n /**\n * Depositor's BTC public key (x-only, 64-char hex without 0x prefix)\n */\n depositorBtcPubkey: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex)\n */\n vaultProviderBtcPubkey: string;\n\n /**\n * Vault keeper BTC public keys (x-only, 64-char hex)\n */\n vaultKeeperBtcPubkeys: string[];\n\n /**\n * Universal challenger BTC public keys (x-only, 64-char hex)\n */\n universalChallengerBtcPubkeys: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Bitcoin network\n */\n network: Network;\n}\n\n/**\n * Result of building an unsigned payout PSBT\n */\nexport interface PayoutPsbtResult {\n /**\n * Unsigned PSBT hex ready for signing\n */\n psbtHex: string;\n}\n\n/**\n * Build unsigned Payout PSBT for depositor to sign.\n *\n * Payout is used in the **challenge path** when the claimer proves validity:\n * 1. Vault provider submits Claim transaction\n * 2. Challenge is raised during challenge period\n * 3. Claimer submits Assert transaction to prove validity\n * 4. Payout can be executed (references Assert tx)\n *\n * Payout transactions have the following structure:\n * - Input 0: from PeginTx output0 (signed by depositor)\n * - Input 1: from Assert output0 (NOT signed by depositor)\n *\n * @param params - Payout parameters\n * @returns Unsigned PSBT ready for depositor to sign\n *\n * @throws If payout transaction does not have exactly 2 inputs\n * @throws If input 0 does not reference the pegin transaction\n * @throws If input 1 does not reference the assert transaction\n * @throws If previous output is not found for either input\n */\nexport async function buildPayoutPsbt(\n params: PayoutParams,\n): Promise<PayoutPsbtResult> {\n // Normalize hex inputs (strip 0x prefix if present)\n const payoutTxHex = stripHexPrefix(params.payoutTxHex);\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const assertTxHex = stripHexPrefix(params.assertTxHex);\n\n // Get payout script from WASM\n const payoutConnector = await createPayoutScript({\n depositor: params.depositorBtcPubkey,\n vaultProvider: params.vaultProviderBtcPubkey,\n vaultKeepers: params.vaultKeeperBtcPubkeys,\n universalChallengers: params.universalChallengerBtcPubkeys,\n timelockPegin: params.timelockPegin,\n network: params.network,\n });\n\n const payoutScriptBytes = hexToUint8Array(payoutConnector.payoutScript);\n const controlBlock = computeControlBlock(tapInternalPubkey, payoutScriptBytes);\n\n // Parse transactions\n const payoutTx = Transaction.fromHex(payoutTxHex);\n const peginTx = Transaction.fromHex(peginTxHex);\n const assertTx = Transaction.fromHex(assertTxHex);\n\n // Create PSBT\n const psbt = new Psbt();\n psbt.setVersion(payoutTx.version);\n psbt.setLocktime(payoutTx.locktime);\n\n // PayoutTx has exactly 2 inputs:\n // - Input 0: from PeginTx output0 (signed by depositor using taproot script path)\n // - Input 1: from Assert output0 (signed by claimer/challengers, not depositor)\n //\n // IMPORTANT: For Taproot SIGHASH_DEFAULT (0x00), the sighash commits to ALL inputs'\n // prevouts, not just the one being signed. Therefore, we must include BOTH inputs\n // in the PSBT so the wallet computes the correct sighash that the VP expects.\n\n // Verify payout transaction has expected structure\n if (payoutTx.ins.length !== 2) {\n throw new Error(\n `Payout transaction must have exactly 2 inputs, got ${payoutTx.ins.length}`,\n );\n }\n\n const input0 = payoutTx.ins[0];\n const input1 = payoutTx.ins[1];\n\n // Verify input 0 references the pegin transaction\n const input0Txid = uint8ArrayToHex(\n new Uint8Array(input0.hash).slice().reverse(),\n );\n const peginTxid = peginTx.getId();\n\n if (input0Txid !== peginTxid) {\n throw new Error(\n `Input 0 does not reference pegin transaction. ` +\n `Expected ${peginTxid}, got ${input0Txid}`,\n );\n }\n\n // Verify input 1 references the assert transaction\n const input1Txid = uint8ArrayToHex(\n new Uint8Array(input1.hash).slice().reverse(),\n );\n const expectedInput1Txid = assertTx.getId();\n\n if (input1Txid !== expectedInput1Txid) {\n throw new Error(\n `Input 1 does not reference assert transaction. ` +\n `Expected ${expectedInput1Txid}, got ${input1Txid}`,\n );\n }\n\n const peginPrevOut = peginTx.outs[input0.index];\n if (!peginPrevOut) {\n throw new Error(\n `Previous output not found for input 0 (txid: ${input0Txid}, index: ${input0.index})`,\n );\n }\n\n const input1PrevOut = assertTx.outs[input1.index];\n if (!input1PrevOut) {\n throw new Error(\n `Previous output not found for input 1 (txid: ${input1Txid}, index: ${input1.index})`,\n );\n }\n\n // Input 0: Depositor signs using Taproot script path spend\n // This input includes tapLeafScript for signing\n psbt.addInput({\n hash: input0.hash,\n index: input0.index,\n sequence: input0.sequence,\n witnessUtxo: {\n script: peginPrevOut.script,\n value: peginPrevOut.value,\n },\n tapLeafScript: [\n {\n leafVersion: 0xc0,\n script: Buffer.from(payoutScriptBytes),\n controlBlock: Buffer.from(controlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n // sighashType omitted - defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n // Input 1: From Assert transaction (NOT signed by depositor)\n // We include this with witnessUtxo so the sighash is computed correctly,\n // but we do NOT include tapLeafScript since the depositor doesn't sign it.\n psbt.addInput({\n hash: input1.hash,\n index: input1.index,\n sequence: input1.sequence,\n witnessUtxo: {\n script: input1PrevOut.script,\n value: input1PrevOut.value,\n },\n // No tapLeafScript - depositor doesn't sign this input\n });\n\n // Add outputs\n for (const output of payoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return {\n psbtHex: psbt.toHex(),\n };\n}\n\n/**\n * Extract Schnorr signature from signed payout PSBT.\n *\n * This function supports two cases:\n * 1. Non-finalized PSBT: Extracts from tapScriptSig field\n * 2. Finalized PSBT: Extracts from witness data\n *\n * The signature is returned as a 64-byte hex string (128 hex characters)\n * with any sighash flag byte removed if present.\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's public key (x-only, 64-char hex)\n * @param inputIndex - Input index to extract signature from (default: 0)\n * @returns 64-byte Schnorr signature (128 hex characters, no sighash flag)\n *\n * @throws If no signature is found in the PSBT\n * @throws If the signature has an unexpected length\n */\nexport function extractPayoutSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n inputIndex = 0,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n\n if (inputIndex >= signedPsbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${signedPsbt.data.inputs.length} inputs)`,\n );\n }\n\n const input = signedPsbt.data.inputs[inputIndex];\n\n // Case 1: Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = hexToUint8Array(depositorPubkey);\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(Buffer.from(depositorPubkeyBytes))) {\n return extractSchnorrSig(sigEntry.signature, inputIndex);\n }\n }\n\n throw new Error(\n `No signature found for depositor pubkey: ${depositorPubkey} at input ${inputIndex}`,\n );\n }\n\n // Case 2: Finalized PSBT — extract from finalScriptWitness\n // Taproot script-path witness: [signature, script, controlBlock]\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n const witnessStack = parseWitnessStack(input.finalScriptWitness);\n if (witnessStack.length >= 1) {\n return extractSchnorrSig(witnessStack[0], inputIndex);\n }\n }\n\n throw new Error(\n `No tapScriptSig or finalScriptWitness found in signed PSBT at input ${inputIndex}`,\n );\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature, stripping sighash flag if present.\n * Rejects signatures with sighash types other than SIGHASH_ALL (0x01) to prevent\n * acceptance of signatures that don't commit to all outputs (e.g. SIGHASH_NONE).\n * @internal\n */\nfunction extractSchnorrSig(sig: Uint8Array, inputIndex: number): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n } else if (sig.length === 65) {\n const sighashByte = sig[64];\n if (sighashByte !== Transaction.SIGHASH_ALL) {\n throw new Error(\n `Unexpected sighash type 0x${sighashByte.toString(16).padStart(2, \"0\")} at input ${inputIndex}. Expected SIGHASH_ALL (0x01).`,\n );\n }\n return uint8ArrayToHex(new Uint8Array(sig.subarray(0, 64)));\n }\n throw new Error(\n `Unexpected signature length at input ${inputIndex}: ${sig.length}`,\n );\n}\n\n/**\n * Parse a BIP-141 serialized witness stack into individual stack items.\n * Format: [varint item_count] [varint len, data]...\n * @internal\n */\nfunction parseWitnessStack(witness: Buffer): Buffer[] {\n const items: Buffer[] = [];\n let offset = 0;\n\n const readVarInt = (): number => {\n const first = witness[offset++];\n if (first < 0xfd) return first;\n if (first === 0xfd) {\n const val = witness[offset] | (witness[offset + 1] << 8);\n offset += 2;\n return val;\n }\n if (first === 0xfe) {\n const val =\n witness[offset] |\n (witness[offset + 1] << 8) |\n (witness[offset + 2] << 16) |\n (witness[offset + 3] << 24);\n offset += 4;\n return val;\n }\n // 0xff — 8-byte, won't happen for witness data\n offset += 8;\n return 0;\n };\n\n const count = readVarInt();\n for (let i = 0; i < count; i++) {\n const len = readVarInt();\n items.push(witness.subarray(offset, offset + len) as Buffer);\n offset += len;\n }\n\n return items;\n}\n\n/**\n * Compute control block for Taproot script path spend.\n *\n * For a single script (no tree), the control block format is:\n * [leaf_version | parity] || [internal_key_x_only]\n *\n * The leaf version for Tapscript is 0xc0, and the parity bit indicates\n * whether the output key has an odd or even y-coordinate.\n *\n * @param internalKey - Taproot internal public key (x-only, 32 bytes)\n * @param script - Taproot script to compute control block for\n * @returns Control block buffer\n *\n * @internal\n */\nfunction computeControlBlock(\n internalKey: Uint8Array,\n script: Uint8Array,\n): Uint8Array {\n // Convert to actual Buffer instances for bitcoinjs-lib runtime type checks\n const scriptTree = { output: Buffer.from(script) };\n const payment = payments.p2tr({\n internalPubkey: Buffer.from(internalKey),\n scriptTree,\n });\n\n const outputKey = payment.pubkey;\n if (!outputKey) {\n throw new Error(\"Failed to compute output key\");\n }\n\n // Control block: [leaf_version | parity] || [internal_key_x_only]\n const leafVersion = 0xc0;\n const parity = outputKey[0] === 0x03 ? 1 : 0; // 0x02 = even, 0x03 = odd\n const controlByte = leafVersion | parity;\n\n const result = new Uint8Array(1 + internalKey.length);\n result[0] = controlByte;\n result.set(internalKey, 1);\n return result;\n}\n","/**\n * Depositor Payout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's own Payout transaction\n * (depositor-as-claimer path). The depositor signs input 0 using the\n * payout taproot script from WasmPeginPayoutConnector (PegIn vault UTXO).\n *\n * Input 0 spends PegIn:0 (the vault UTXO) — the same connector used for\n * VP/VK payout signing. The VP verifies this signature using the\n * PeginPayoutConnector's payout script.\n *\n * @module primitives/psbt/depositorPayout\n * @see btc-vault crates/vault/src/sign.rs — verify_depositor_signature / get_payout_tap_leaf_hash\n */\n\nimport {\n type PayoutConnectorParams,\n getPeginPayoutScript,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { Buffer } from \"buffer\";\nimport { initEccLib, payments, Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n hexToUint8Array,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n// Initialize ECC library for bitcoinjs-lib\ninitEccLib(ecc);\n\n/**\n * Parameters for building a depositor Payout PSBT\n */\nexport interface DepositorPayoutParams {\n /** Payout transaction hex (unsigned) from VP */\n payoutTxHex: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the PeginPayout connector (depositor, VP, VKs, UCs, timelock) */\n connectorParams: PayoutConnectorParams;\n}\n\n/**\n * Build unsigned depositor Payout PSBT.\n *\n * The depositor's payout transaction has 2 inputs:\n * - Input 0: PegIn:0 (vault UTXO) — depositor signs using PeginPayoutConnector payout script\n * - Input 1: Assert:0 — NOT signed by depositor\n *\n * @param params - Depositor payout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildDepositorPayoutPsbt(\n params: DepositorPayoutParams,\n): Promise<string> {\n const payoutTxHex = stripHexPrefix(params.payoutTxHex);\n const payoutTx = Transaction.fromHex(payoutTxHex);\n\n // Get payout script from WASM (PeginPayoutConnector — same as VP/VK payout)\n const payoutScriptHex = await getPeginPayoutScript(params.connectorParams);\n const scriptBytes = hexToUint8Array(payoutScriptHex);\n const controlBlock = computeControlBlock(tapInternalPubkey, scriptBytes);\n\n const psbt = new Psbt();\n psbt.setVersion(payoutTx.version);\n psbt.setLocktime(payoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < payoutTx.ins.length; i++) {\n const input = payoutTx.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: 0xc0,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlock),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of payoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/**\n * Compute control block for Taproot script path spend.\n * @internal\n */\nfunction computeControlBlock(\n internalKey: Uint8Array,\n script: Uint8Array,\n): Uint8Array {\n const scriptTree = { output: Buffer.from(script) };\n const payment = payments.p2tr({\n internalPubkey: Buffer.from(internalKey),\n scriptTree,\n });\n\n const outputKey = payment.pubkey;\n if (!outputKey) {\n throw new Error(\"Failed to compute output key\");\n }\n\n const leafVersion = 0xc0;\n const parity = outputKey[0] === 0x03 ? 1 : 0;\n const controlByte = leafVersion | parity;\n\n const result = new Uint8Array(1 + internalKey.length);\n result[0] = controlByte;\n result.set(internalKey, 1);\n return result;\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 getAssertNoPayoutScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n hexToUint8Array,\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: 0xc0,\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 * ChallengeAssert PSBT Builder\n *\n * Builds an unsigned PSBT for a ChallengeAssert transaction\n * (depositor-as-claimer path, per challenger). The ChallengeAssert tx has\n * NUM_UTXOS_FOR_CHALLENGE_ASSERT (3) inputs, each spending a different Assert\n * output segment. The depositor signs ALL inputs, each with its own taproot\n * script derived from the per-segment connector params.\n *\n * @module primitives/psbt/challengeAssert\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — ChallengeAssert connector (NUM_UTXOS_FOR_CHALLENGE_ASSERT=3)\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 hexToUint8Array,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a ChallengeAssert PSBT\n */\nexport interface ChallengeAssertParams {\n /** ChallengeAssert transaction hex (unsigned) from VP */\n challengeAssertTxHex: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP (flat, one per input) */\n prevouts: Array<{ script_pubkey: string; value: number }>;\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 * The ChallengeAssert transaction has 3 inputs (one per Assert output segment).\n * Each input has its own taproot script derived from its connector params.\n * The depositor signs all inputs.\n *\n * @param params - ChallengeAssert parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildChallengeAssertPsbt(\n params: ChallengeAssertParams,\n): Promise<string> {\n const challengeAssertTxHex = stripHexPrefix(params.challengeAssertTxHex);\n const challengeAssertTx = Transaction.fromHex(challengeAssertTxHex);\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 // Get script and control block for each input from WASM\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 // Add all inputs — depositor signs every input\n for (let i = 0; i < challengeAssertTx.ins.length; i++) {\n const input = challengeAssertTx.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 { 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: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n tapLeafScript: [\n {\n leafVersion: 0xc0,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n }\n\n // Add outputs\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":["stripHexPrefix","hex","ensureHexPrefix","hexToUint8Array","cleanHex","isValidHexRaw","bytes","i","uint8ArrayToHex","b","toXOnly","pubKey","processPublicKeyToXOnly","publicKeyHex","pubkeyBytes","isValidHex","validateWalletPubkey","walletPubkeyRaw","expectedDepositorPubkey","walletPubkeyXOnly","depositorPubkey","eccInitialized","ensureEcc","initEccLib","ecc","getNetwork","network","networks","deriveTaprootAddress","xOnly","address","payments","Buffer","deriveNativeSegwitAddress","isAddressFromPublicKey","compressedKeys","key","normalizeKey","computeNumLocalChallengers","vaultProviderPubkey","vaultKeeperPubkeys","localSet","vk","P2TR_INPUT_SIZE","MAX_NON_LEGACY_OUTPUT_SIZE","TX_BUFFER_SIZE_OVERHEAD","BTC_DUST_SAT","DUST_THRESHOLD","LOW_RATE_ESTIMATION_ACCURACY_BUFFER","WALLET_RELAY_FEE_RATE_THRESHOLD","FEE_SAFETY_MARGIN","rateBasedTxBufferFee","feeRate","PEGIN_FIXED_OUTPUTS","peginOutputCount","vaultCount","SPLIT_TX_FEE_SAFETY_MULTIPLIER","parseUnfundedWasmTransaction","unfundedTxHex","dataOffset","inputCount","outputCount","version","locktime","outputs","pos","valueHex","value","scriptLen","scriptHex","script","fundPeginTransaction","params","selectedUTXOs","changeAddress","changeAmount","tx","bitcoin","utxo","txHash","output","changeScript","buildPrePeginPsbt","result","createPrePeginTransaction","totalOutputValue","sum","o","buildPeginTxFromFundedPrePegin","buildPeginTxFromPrePegin","buildPeginInputPsbt","peginTxHex","fundedPrePeginTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","peginTx","Transaction","prePeginTx","peginInput","prePeginTxid","peginInputTxid","htlcOutput","hashlockScript","hashlockControlBlock","psbt","Psbt","tapInternalPubkey","extractPeginInputSignature","signedPsbtHex","input","depositorPubkeyBytes","sigEntry","extractSchnorrSig","finalizePeginInputPsbt","inp","sig","createPayoutScript","connector","createPayoutConnector","buildPayoutPsbt","payoutTxHex","assertTxHex","payoutConnector","payoutScriptBytes","controlBlock","computeControlBlock","payoutTx","assertTx","input0","input1","input0Txid","peginTxid","input1Txid","expectedInput1Txid","peginPrevOut","input1PrevOut","extractPayoutSignature","inputIndex","signedPsbt","witnessStack","parseWitnessStack","sighashByte","witness","items","offset","readVarInt","first","val","count","len","internalKey","scriptTree","outputKey","leafVersion","parity","controlByte","buildDepositorPayoutPsbt","payoutScriptHex","getPeginPayoutScript","scriptBytes","prevout","inputData","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","controlBlockBytes","buildChallengeAssertPsbt","challengeAssertTxHex","challengeAssertTx","scriptInfos","cp","getChallengeAssertScriptInfo"],"mappings":"ocA+BO,SAASA,EAAeC,EAAqB,CAClD,OAAOA,EAAI,WAAW,IAAI,EAAIA,EAAI,MAAM,CAAC,EAAIA,CAC/C,CAWO,SAASC,EAAgBD,EAAkB,CAChD,OAAOA,EAAI,WAAW,IAAI,EAAKA,EAAe,KAAKA,CAAG,EACxD,CASO,SAASE,EAAgBF,EAAyB,CACvD,MAAMG,EAAWJ,EAAeC,CAAG,EACnC,GAAI,CAACI,EAAcD,CAAQ,EACzB,MAAM,IAAI,MAAM,uBAAuBH,CAAG,EAAE,EAE9C,MAAMK,EAAQ,IAAI,WAAWF,EAAS,OAAS,CAAC,EAChD,QAASG,EAAI,EAAGA,EAAIH,EAAS,OAAQG,GAAK,EACxCD,EAAMC,EAAI,CAAC,EAAI,SAASH,EAAS,MAAMG,EAAGA,EAAI,CAAC,EAAG,EAAE,EAEtD,OAAOD,CACT,CAQO,SAASE,EAAgBF,EAA2B,CACzD,OAAO,MAAM,KAAKA,CAAK,EACpB,IAAKG,GAAMA,EAAE,SAAS,EAAE,EAAE,SAAS,EAAG,GAAG,CAAC,EAC1C,KAAK,EAAE,CACZ,CAWO,SAASC,EAAQC,EAAgC,CACtD,OAA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A,CAC7C,EAEF,eAAgBxI,EAAAA,OAAO,KAAK0E,EAAAA,iBAAiB,CAAA,CAC9C,CACH,CAGA,UAAW1B,KAAU2F,EAAkB,KACrCnE,EAAK,UAAU,CACb,OAAQxB,EAAO,OACf,MAAOA,EAAO,KAAA,CACf,EAGH,OAAOwB,EAAK,MAAA,CACd"}
|
|
@@ -6,7 +6,7 @@ import * as A from "@bitcoin-js/tiny-secp256k1-asmjs";
|
|
|
6
6
|
function h(t) {
|
|
7
7
|
return t.startsWith("0x") ? t.slice(2) : t;
|
|
8
8
|
}
|
|
9
|
-
function
|
|
9
|
+
function at(t) {
|
|
10
10
|
return t.startsWith("0x") ? t : `0x${t}`;
|
|
11
11
|
}
|
|
12
12
|
function d(t) {
|
|
@@ -40,11 +40,11 @@ function $(t) {
|
|
|
40
40
|
const e = d(n);
|
|
41
41
|
return x(D(e));
|
|
42
42
|
}
|
|
43
|
-
function
|
|
43
|
+
function lt(t) {
|
|
44
44
|
const n = h(t);
|
|
45
45
|
return B(n);
|
|
46
46
|
}
|
|
47
|
-
function
|
|
47
|
+
function pt(t, n) {
|
|
48
48
|
const e = $(t), o = n ?? e;
|
|
49
49
|
if (e.toLowerCase() !== o.toLowerCase())
|
|
50
50
|
throw new Error(
|
|
@@ -95,7 +95,7 @@ function Y(t, n) {
|
|
|
95
95
|
);
|
|
96
96
|
return o;
|
|
97
97
|
}
|
|
98
|
-
function
|
|
98
|
+
function ft(t, n, e) {
|
|
99
99
|
const o = h(n);
|
|
100
100
|
try {
|
|
101
101
|
if (t === G(o, e))
|
|
@@ -115,18 +115,22 @@ function pt(t, n, e) {
|
|
|
115
115
|
function I(t) {
|
|
116
116
|
return $(t).toLowerCase();
|
|
117
117
|
}
|
|
118
|
-
function
|
|
118
|
+
function ht(t, n, e) {
|
|
119
119
|
const o = /* @__PURE__ */ new Set();
|
|
120
120
|
o.add(I(t));
|
|
121
121
|
for (const r of n)
|
|
122
122
|
o.add(I(r));
|
|
123
123
|
return o.delete(I(e)), o.size;
|
|
124
124
|
}
|
|
125
|
-
const
|
|
126
|
-
function
|
|
125
|
+
const dt = 58, gt = 43, Pt = 11, Q = 546, Z = BigInt(Q), j = 30, J = 2, yt = 1.1;
|
|
126
|
+
function xt(t) {
|
|
127
127
|
return t <= J ? j : 0;
|
|
128
128
|
}
|
|
129
|
-
const
|
|
129
|
+
const tt = 1;
|
|
130
|
+
function kt(t) {
|
|
131
|
+
return t + tt;
|
|
132
|
+
}
|
|
133
|
+
const wt = 5;
|
|
130
134
|
function F(t) {
|
|
131
135
|
const e = t.substring(8, 12) === "0001" ? 12 : 8, o = parseInt(
|
|
132
136
|
t.substring(e, e + 2),
|
|
@@ -154,7 +158,7 @@ function F(t) {
|
|
|
154
158
|
}
|
|
155
159
|
return { version: s, locktime: u, outputs: c };
|
|
156
160
|
}
|
|
157
|
-
function
|
|
161
|
+
function vt(t) {
|
|
158
162
|
const { unfundedTxHex: n, selectedUTXOs: e, changeAddress: o, changeAmount: r, network: s } = t, { version: u, locktime: c, outputs: i } = F(n), p = new U.Transaction();
|
|
159
163
|
p.version = u, p.locktime = c;
|
|
160
164
|
for (const l of e) {
|
|
@@ -169,7 +173,7 @@ function kt(t) {
|
|
|
169
173
|
}
|
|
170
174
|
return p.toHex();
|
|
171
175
|
}
|
|
172
|
-
async function
|
|
176
|
+
async function bt(t) {
|
|
173
177
|
const n = await R({
|
|
174
178
|
depositorPubkey: t.depositorPubkey,
|
|
175
179
|
vaultProviderPubkey: t.vaultProviderPubkey,
|
|
@@ -177,7 +181,7 @@ async function wt(t) {
|
|
|
177
181
|
universalChallengerPubkeys: t.universalChallengerPubkeys,
|
|
178
182
|
hashlocks: [...t.hashlocks],
|
|
179
183
|
timelockRefund: t.timelockRefund,
|
|
180
|
-
|
|
184
|
+
pegInAmounts: [...t.pegInAmounts],
|
|
181
185
|
feeRate: t.feeRate,
|
|
182
186
|
numLocalChallengers: t.numLocalChallengers,
|
|
183
187
|
councilQuorum: t.councilQuorum,
|
|
@@ -190,14 +194,14 @@ async function wt(t) {
|
|
|
190
194
|
return {
|
|
191
195
|
psbtHex: n.txHex,
|
|
192
196
|
totalOutputValue: o,
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
+
htlcValues: n.htlcValues,
|
|
198
|
+
htlcScriptPubKeys: n.htlcScriptPubKeys,
|
|
199
|
+
htlcAddresses: n.htlcAddresses,
|
|
200
|
+
peginAmounts: n.peginAmounts,
|
|
197
201
|
depositorClaimValue: n.depositorClaimValue
|
|
198
202
|
};
|
|
199
203
|
}
|
|
200
|
-
async function
|
|
204
|
+
async function St(t) {
|
|
201
205
|
const n = await W(
|
|
202
206
|
{
|
|
203
207
|
depositorPubkey: t.prePeginParams.depositorPubkey,
|
|
@@ -206,7 +210,7 @@ async function vt(t) {
|
|
|
206
210
|
universalChallengerPubkeys: t.prePeginParams.universalChallengerPubkeys,
|
|
207
211
|
hashlocks: [...t.prePeginParams.hashlocks],
|
|
208
212
|
timelockRefund: t.prePeginParams.timelockRefund,
|
|
209
|
-
|
|
213
|
+
pegInAmounts: [...t.prePeginParams.pegInAmounts],
|
|
210
214
|
feeRate: t.prePeginParams.feeRate,
|
|
211
215
|
numLocalChallengers: t.prePeginParams.numLocalChallengers,
|
|
212
216
|
councilQuorum: t.prePeginParams.councilQuorum,
|
|
@@ -224,7 +228,7 @@ async function vt(t) {
|
|
|
224
228
|
vaultValue: n.vaultValue
|
|
225
229
|
};
|
|
226
230
|
}
|
|
227
|
-
async function
|
|
231
|
+
async function mt(t) {
|
|
228
232
|
const n = h(t.peginTxHex), e = h(t.fundedPrePeginTxHex), o = await K({
|
|
229
233
|
depositorPubkey: t.depositorPubkey,
|
|
230
234
|
vaultProviderPubkey: t.vaultProviderPubkey,
|
|
@@ -276,7 +280,7 @@ async function bt(t) {
|
|
|
276
280
|
});
|
|
277
281
|
return { psbtHex: g.toHex() };
|
|
278
282
|
}
|
|
279
|
-
function
|
|
283
|
+
function Et(t, n) {
|
|
280
284
|
const o = k.fromHex(t).data.inputs[0];
|
|
281
285
|
if (!o)
|
|
282
286
|
throw new Error("PegIn PSBT has no inputs");
|
|
@@ -286,7 +290,7 @@ function St(t, n) {
|
|
|
286
290
|
);
|
|
287
291
|
for (const s of o.tapScriptSig)
|
|
288
292
|
if (s.pubkey.equals(r))
|
|
289
|
-
return
|
|
293
|
+
return et(s.signature);
|
|
290
294
|
throw new Error(
|
|
291
295
|
`No PegIn input signature found for depositor pubkey: ${n}`
|
|
292
296
|
);
|
|
@@ -297,7 +301,7 @@ function St(t, n) {
|
|
|
297
301
|
"No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT"
|
|
298
302
|
);
|
|
299
303
|
}
|
|
300
|
-
function
|
|
304
|
+
function Tt(t) {
|
|
301
305
|
const n = k.fromHex(t);
|
|
302
306
|
try {
|
|
303
307
|
n.finalizeAllInputs();
|
|
@@ -311,14 +315,14 @@ function mt(t) {
|
|
|
311
315
|
}
|
|
312
316
|
return n.extractTransaction().toHex();
|
|
313
317
|
}
|
|
314
|
-
function
|
|
318
|
+
function et(t) {
|
|
315
319
|
if (t.length === 64)
|
|
316
320
|
return x(new Uint8Array(t));
|
|
317
321
|
if (t.length === 65)
|
|
318
322
|
return x(new Uint8Array(t.subarray(0, 64)));
|
|
319
323
|
throw new Error(`Unexpected PegIn input signature length: ${t.length}`);
|
|
320
324
|
}
|
|
321
|
-
async function
|
|
325
|
+
async function nt(t) {
|
|
322
326
|
const n = await N(
|
|
323
327
|
{
|
|
324
328
|
depositor: t.depositor,
|
|
@@ -337,15 +341,15 @@ async function et(t) {
|
|
|
337
341
|
};
|
|
338
342
|
}
|
|
339
343
|
H(A);
|
|
340
|
-
async function
|
|
341
|
-
const n = h(t.payoutTxHex), e = h(t.peginTxHex), o = h(t.assertTxHex), r = await
|
|
344
|
+
async function It(t) {
|
|
345
|
+
const n = h(t.payoutTxHex), e = h(t.peginTxHex), o = h(t.assertTxHex), r = await nt({
|
|
342
346
|
depositor: t.depositorBtcPubkey,
|
|
343
347
|
vaultProvider: t.vaultProviderBtcPubkey,
|
|
344
348
|
vaultKeepers: t.vaultKeeperBtcPubkeys,
|
|
345
349
|
universalChallengers: t.universalChallengerBtcPubkeys,
|
|
346
350
|
timelockPegin: t.timelockPegin,
|
|
347
351
|
network: t.network
|
|
348
|
-
}), s = d(r.payoutScript), u =
|
|
352
|
+
}), s = d(r.payoutScript), u = rt(w, s), c = P.fromHex(n), i = P.fromHex(e), p = P.fromHex(o), l = new k();
|
|
349
353
|
if (l.setVersion(c.version), l.setLocktime(c.locktime), c.ins.length !== 2)
|
|
350
354
|
throw new Error(
|
|
351
355
|
`Payout transaction must have exactly 2 inputs, got ${c.ins.length}`
|
|
@@ -410,7 +414,7 @@ async function Et(t) {
|
|
|
410
414
|
psbtHex: l.toHex()
|
|
411
415
|
};
|
|
412
416
|
}
|
|
413
|
-
function
|
|
417
|
+
function Ht(t, n, e = 0) {
|
|
414
418
|
const o = k.fromHex(t);
|
|
415
419
|
if (e >= o.data.inputs.length)
|
|
416
420
|
throw new Error(
|
|
@@ -427,7 +431,7 @@ function Tt(t, n, e = 0) {
|
|
|
427
431
|
);
|
|
428
432
|
}
|
|
429
433
|
if (r.finalScriptWitness && r.finalScriptWitness.length > 0) {
|
|
430
|
-
const s =
|
|
434
|
+
const s = ot(r.finalScriptWitness);
|
|
431
435
|
if (s.length >= 1)
|
|
432
436
|
return O(s[0], e);
|
|
433
437
|
}
|
|
@@ -450,7 +454,7 @@ function O(t, n) {
|
|
|
450
454
|
`Unexpected signature length at input ${n}: ${t.length}`
|
|
451
455
|
);
|
|
452
456
|
}
|
|
453
|
-
function
|
|
457
|
+
function ot(t) {
|
|
454
458
|
const n = [];
|
|
455
459
|
let e = 0;
|
|
456
460
|
const o = () => {
|
|
@@ -472,7 +476,7 @@ function nt(t) {
|
|
|
472
476
|
}
|
|
473
477
|
return n;
|
|
474
478
|
}
|
|
475
|
-
function
|
|
479
|
+
function rt(t, n) {
|
|
476
480
|
const e = { output: a.from(n) }, r = b.p2tr({
|
|
477
481
|
internalPubkey: a.from(t),
|
|
478
482
|
scriptTree: e
|
|
@@ -483,8 +487,8 @@ function ot(t, n) {
|
|
|
483
487
|
return i[0] = c, i.set(t, 1), i;
|
|
484
488
|
}
|
|
485
489
|
H(A);
|
|
486
|
-
async function
|
|
487
|
-
const n = h(t.payoutTxHex), e = P.fromHex(n), o = await q(t.connectorParams), r = d(o), s =
|
|
490
|
+
async function At(t) {
|
|
491
|
+
const n = h(t.payoutTxHex), e = P.fromHex(n), o = await q(t.connectorParams), r = d(o), s = st(w, r), u = new k();
|
|
488
492
|
u.setVersion(e.version), u.setLocktime(e.locktime);
|
|
489
493
|
for (let c = 0; c < e.ins.length; c++) {
|
|
490
494
|
const i = e.ins[c], p = t.prevouts[c];
|
|
@@ -514,7 +518,7 @@ async function It(t) {
|
|
|
514
518
|
});
|
|
515
519
|
return u.toHex();
|
|
516
520
|
}
|
|
517
|
-
function
|
|
521
|
+
function st(t, n) {
|
|
518
522
|
const e = { output: a.from(n) }, r = b.p2tr({
|
|
519
523
|
internalPubkey: a.from(t),
|
|
520
524
|
scriptTree: e
|
|
@@ -524,7 +528,7 @@ function rt(t, n) {
|
|
|
524
528
|
const s = 192, u = r[0] === 3 ? 1 : 0, c = s | u, i = new Uint8Array(1 + t.length);
|
|
525
529
|
return i[0] = c, i.set(t, 1), i;
|
|
526
530
|
}
|
|
527
|
-
async function
|
|
531
|
+
async function Bt(t) {
|
|
528
532
|
const n = h(t.noPayoutTxHex), e = P.fromHex(n), { noPayoutScript: o, noPayoutControlBlock: r } = await z(
|
|
529
533
|
t.connectorParams,
|
|
530
534
|
t.challengerPubkey
|
|
@@ -558,7 +562,7 @@ async function Ht(t) {
|
|
|
558
562
|
});
|
|
559
563
|
return c.toHex();
|
|
560
564
|
}
|
|
561
|
-
async function
|
|
565
|
+
async function $t(t) {
|
|
562
566
|
const n = h(t.challengeAssertTxHex), e = P.fromHex(n);
|
|
563
567
|
if (t.connectorParamsPerInput.length !== e.ins.length)
|
|
564
568
|
throw new Error(
|
|
@@ -599,41 +603,43 @@ async function At(t) {
|
|
|
599
603
|
return r.toHex();
|
|
600
604
|
}
|
|
601
605
|
export {
|
|
602
|
-
|
|
606
|
+
F as A,
|
|
603
607
|
Q as B,
|
|
608
|
+
vt as C,
|
|
604
609
|
Z as D,
|
|
605
|
-
|
|
610
|
+
V as E,
|
|
611
|
+
yt as F,
|
|
606
612
|
j as L,
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
613
|
+
gt as M,
|
|
614
|
+
dt as P,
|
|
615
|
+
wt as S,
|
|
616
|
+
Pt as T,
|
|
611
617
|
J as W,
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
618
|
+
St as a,
|
|
619
|
+
bt as b,
|
|
620
|
+
ht as c,
|
|
621
|
+
mt as d,
|
|
622
|
+
Et as e,
|
|
623
|
+
Tt as f,
|
|
624
|
+
It as g,
|
|
625
|
+
Ht as h,
|
|
626
|
+
At as i,
|
|
627
|
+
Bt as j,
|
|
628
|
+
$t as k,
|
|
629
|
+
nt as l,
|
|
624
630
|
Y as m,
|
|
625
631
|
G as n,
|
|
626
632
|
d as o,
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
633
|
+
ft as p,
|
|
634
|
+
lt as q,
|
|
635
|
+
at as r,
|
|
630
636
|
$ as s,
|
|
631
637
|
h as t,
|
|
632
638
|
D as u,
|
|
633
639
|
x as v,
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
640
|
+
pt as w,
|
|
641
|
+
xt as x,
|
|
642
|
+
tt as y,
|
|
637
643
|
kt as z
|
|
638
644
|
};
|
|
639
|
-
//# sourceMappingURL=challengeAssert-
|
|
645
|
+
//# sourceMappingURL=challengeAssert-DnnliaRt.js.map
|