@babylonlabs-io/ts-sdk 0.16.2 → 0.17.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-D_k_ADgP.cjs +2 -0
- package/dist/challengeAssert-D_k_ADgP.cjs.map +1 -0
- package/dist/challengeAssert-k5_LWUtO.js +362 -0
- package/dist/challengeAssert-k5_LWUtO.js.map +1 -0
- package/dist/constants-EiyZkXce.cjs +2 -0
- package/dist/constants-EiyZkXce.cjs.map +1 -0
- package/dist/constants-Q7v2O7Ps.js +155 -0
- package/dist/constants-Q7v2O7Ps.js.map +1 -0
- package/dist/errors-DKLboMnq.cjs +2 -0
- package/dist/errors-DKLboMnq.cjs.map +1 -0
- package/dist/errors-KY63mgWT.js +1510 -0
- package/dist/errors-KY63mgWT.js.map +1 -0
- package/dist/fundPeginTransaction-DpwnDslW.js +50 -0
- package/dist/fundPeginTransaction-DpwnDslW.js.map +1 -0
- package/dist/fundPeginTransaction-EbrZzlrh.cjs +2 -0
- package/dist/fundPeginTransaction-EbrZzlrh.cjs.map +1 -0
- package/dist/index-D3z3SZAj.cjs +2 -0
- package/dist/index-D3z3SZAj.cjs.map +1 -0
- package/dist/index-Dw7FAwne.js +913 -0
- package/dist/index-Dw7FAwne.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +98 -74
- package/dist/index.js.map +1 -1
- package/dist/payout-Ce9vSs9e.js +164 -0
- package/dist/payout-Ce9vSs9e.js.map +1 -0
- package/dist/payout-CfsDnjKI.cjs +2 -0
- package/dist/payout-CfsDnjKI.cjs.map +1 -0
- package/dist/psbtInputFields-C0nKn_GD.cjs +2 -0
- package/dist/psbtInputFields-C0nKn_GD.cjs.map +1 -0
- package/dist/psbtInputFields-DO0ELwiv.js +116 -0
- package/dist/psbtInputFields-DO0ELwiv.js.map +1 -0
- package/dist/signAndSubmitPayouts-CAOEAQp9.js +490 -0
- package/dist/signAndSubmitPayouts-CAOEAQp9.js.map +1 -0
- package/dist/signAndSubmitPayouts-CSJmcPQN.cjs +2 -0
- package/dist/signAndSubmitPayouts-CSJmcPQN.cjs.map +1 -0
- package/dist/signing-Deg5lCoC.cjs +2 -0
- package/dist/signing-Deg5lCoC.cjs.map +1 -0
- package/dist/signing-Drwr3bXB.js +16 -0
- package/dist/signing-Drwr3bXB.js.map +1 -0
- package/dist/tbv/core/clients/eth/__tests__/vault-registry-reader.test.d.ts +2 -0
- package/dist/tbv/core/clients/eth/__tests__/vault-registry-reader.test.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/index.d.ts +3 -0
- package/dist/tbv/core/clients/eth/index.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/types.d.ts +37 -0
- package/dist/tbv/core/clients/eth/types.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts +20 -0
- package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -0
- package/dist/tbv/core/clients/index.cjs +2 -0
- package/dist/tbv/core/clients/index.cjs.map +1 -0
- package/dist/tbv/core/clients/index.d.ts +2 -0
- package/dist/tbv/core/clients/index.d.ts.map +1 -1
- package/dist/tbv/core/clients/index.js +26 -0
- package/dist/tbv/core/clients/index.js.map +1 -0
- package/dist/tbv/core/clients/vault-provider/__tests__/json-rpc-client.test.d.ts +2 -0
- package/dist/tbv/core/clients/vault-provider/__tests__/json-rpc-client.test.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/__tests__/validators.test.d.ts +2 -0
- package/dist/tbv/core/clients/vault-provider/__tests__/validators.test.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/api.d.ts +53 -0
- package/dist/tbv/core/clients/vault-provider/api.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/index.d.ts +7 -0
- package/dist/tbv/core/clients/vault-provider/index.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts +90 -0
- package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/types.d.ts +256 -0
- package/dist/tbv/core/clients/vault-provider/types.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/validators.d.ts +30 -0
- package/dist/tbv/core/clients/vault-provider/validators.d.ts.map +1 -0
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.d.ts +1 -0
- package/dist/tbv/core/index.d.ts.map +1 -1
- package/dist/tbv/core/index.js +97 -73
- package/dist/tbv/core/index.js.map +1 -1
- package/dist/tbv/core/primitives/index.cjs +1 -1
- package/dist/tbv/core/primitives/index.d.ts +8 -0
- package/dist/tbv/core/primitives/index.d.ts.map +1 -1
- package/dist/tbv/core/primitives/index.js +26 -24
- package/dist/tbv/core/primitives/index.js.map +1 -1
- package/dist/tbv/core/services/deposit/__tests__/submitWotsPublicKey.test.d.ts +2 -0
- package/dist/tbv/core/services/deposit/__tests__/submitWotsPublicKey.test.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/__tests__/waitForPeginStatus.test.d.ts +2 -0
- package/dist/tbv/core/services/deposit/__tests__/waitForPeginStatus.test.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/index.d.ts +10 -0
- package/dist/tbv/core/services/deposit/index.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/interfaces.d.ts +21 -0
- package/dist/tbv/core/services/deposit/interfaces.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/signAndSubmitPayouts.d.ts +55 -0
- package/dist/tbv/core/services/deposit/signAndSubmitPayouts.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts +21 -0
- package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/submitWotsPublicKey.d.ts +25 -0
- package/dist/tbv/core/services/deposit/submitWotsPublicKey.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/waitForPeginStatus.d.ts +24 -0
- package/dist/tbv/core/services/deposit/waitForPeginStatus.d.ts.map +1 -0
- package/dist/tbv/core/services/index.cjs +2 -0
- package/dist/tbv/core/services/index.cjs.map +1 -0
- package/dist/tbv/core/services/index.d.ts +10 -0
- package/dist/tbv/core/services/index.d.ts.map +1 -0
- package/dist/tbv/core/services/index.js +8 -0
- package/dist/tbv/core/services/index.js.map +1 -0
- package/dist/tbv/core/utils/index.cjs +2 -0
- package/dist/tbv/core/utils/index.cjs.map +1 -0
- package/dist/tbv/core/utils/index.js +30 -0
- package/dist/tbv/core/utils/index.js.map +1 -0
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +97 -73
- package/dist/tbv/index.js.map +1 -1
- package/dist/tbv/integrations/aave/clients/abis/AaveSpoke.abi.json.d.ts +28 -18
- package/dist/tbv/integrations/aave/clients/spoke.d.ts +2 -2
- package/dist/tbv/integrations/aave/clients/spoke.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/constants.d.ts +7 -0
- package/dist/tbv/integrations/aave/constants.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/index.cjs +1 -1
- package/dist/tbv/integrations/aave/index.cjs.map +1 -1
- package/dist/tbv/integrations/aave/index.d.ts +2 -2
- package/dist/tbv/integrations/aave/index.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/index.js +124 -120
- package/dist/tbv/integrations/aave/index.js.map +1 -1
- package/dist/tbv/integrations/aave/types.d.ts +4 -6
- package/dist/tbv/integrations/aave/types.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/utils/aaveConversions.d.ts +10 -1
- package/dist/tbv/integrations/aave/utils/aaveConversions.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/utils/debtUtils.d.ts +0 -1
- package/dist/tbv/integrations/aave/utils/debtUtils.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/utils/index.d.ts +1 -1
- package/dist/tbv/integrations/aave/utils/index.d.ts.map +1 -1
- package/dist/types-D1rYwwCu.js +235 -0
- package/dist/types-D1rYwwCu.js.map +1 -0
- package/dist/types-DEWiqXYp.cjs +2 -0
- package/dist/types-DEWiqXYp.cjs.map +1 -0
- package/package.json +11 -1
- package/dist/challengeAssert-CTajvPAY.cjs +0 -2
- package/dist/challengeAssert-CTajvPAY.cjs.map +0 -1
- package/dist/challengeAssert-DtrQLG0c.js +0 -711
- package/dist/challengeAssert-DtrQLG0c.js.map +0 -1
- package/dist/errors-BeFfs5_J.js +0 -2250
- package/dist/errors-BeFfs5_J.js.map +0 -1
- package/dist/errors-CAFiRPYI.cjs +0 -2
- package/dist/errors-CAFiRPYI.cjs.map +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";const r=require("./constants-EiyZkXce.cjs"),p=require("@babylonlabs-io/babylon-tbv-rust-wasm"),I=require("./fundPeginTransaction-EbrZzlrh.cjs"),a=require("buffer"),d=require("bitcoinjs-lib");function k(e){return r.processPublicKeyToXOnly(e).toLowerCase()}function m(e,t,n){const o=new Set;o.add(k(e));for(const i of t)o.add(k(i));return o.delete(k(n)),o.size}async function S(e){const t=await p.createPrePeginTransaction({depositorPubkey:e.depositorPubkey,vaultProviderPubkey:e.vaultProviderPubkey,vaultKeeperPubkeys:e.vaultKeeperPubkeys,universalChallengerPubkeys:e.universalChallengerPubkeys,hashlocks:[...e.hashlocks],timelockRefund:e.timelockRefund,pegInAmounts:[...e.pegInAmounts],feeRate:e.feeRate,numLocalChallengers:e.numLocalChallengers,councilQuorum:e.councilQuorum,councilSize:e.councilSize,network:e.network}),o=I.parseUnfundedWasmTransaction(t.txHex).outputs.reduce((i,s)=>i+BigInt(s.value),0n);return{psbtHex:t.txHex,totalOutputValue:o,htlcValues:t.htlcValues,htlcScriptPubKeys:t.htlcScriptPubKeys,htlcAddresses:t.htlcAddresses,peginAmounts:t.peginAmounts,depositorClaimValue:t.depositorClaimValue}}async function H(e){const t=await p.buildPeginTxFromPrePegin({depositorPubkey:e.prePeginParams.depositorPubkey,vaultProviderPubkey:e.prePeginParams.vaultProviderPubkey,vaultKeeperPubkeys:e.prePeginParams.vaultKeeperPubkeys,universalChallengerPubkeys:e.prePeginParams.universalChallengerPubkeys,hashlocks:[...e.prePeginParams.hashlocks],timelockRefund:e.prePeginParams.timelockRefund,pegInAmounts:[...e.prePeginParams.pegInAmounts],feeRate:e.prePeginParams.feeRate,numLocalChallengers:e.prePeginParams.numLocalChallengers,councilQuorum:e.prePeginParams.councilQuorum,councilSize:e.prePeginParams.councilSize,network:e.prePeginParams.network},e.timelockPegin,e.fundedPrePeginTxHex,e.htlcVout);return{txHex:t.txHex,txid:t.txid,vaultScriptPubKey:t.vaultScriptPubKey,vaultValue:t.vaultValue}}async function A(e){const t=r.stripHexPrefix(e.peginTxHex),n=r.stripHexPrefix(e.fundedPrePeginTxHex),o=await p.getPrePeginHtlcConnectorInfo({depositorPubkey:e.depositorPubkey,vaultProviderPubkey:e.vaultProviderPubkey,vaultKeeperPubkeys:e.vaultKeeperPubkeys,universalChallengerPubkeys:e.universalChallengerPubkeys,hashlock:e.hashlock,timelockRefund:e.timelockRefund,network:e.network}),i=d.Transaction.fromHex(t),s=d.Transaction.fromHex(n);if(i.ins.length!==1)throw new Error(`PegIn transaction must have exactly 1 input, got ${i.ins.length}`);const l=i.ins[0],c=s.getId(),u=r.uint8ArrayToHex(new Uint8Array(l.hash).slice().reverse());if(u!==c)throw new Error(`PegIn input does not reference the Pre-PegIn transaction. Expected ${c}, got ${u}`);const P=s.outs[l.index];if(!P)throw new Error(`Pre-PegIn output ${l.index} not found (Pre-PegIn has ${s.outs.length} outputs)`);const h=r.hexToUint8Array(o.hashlockScript),f=r.hexToUint8Array(o.hashlockControlBlock),x=new d.Psbt;x.setVersion(i.version),x.setLocktime(i.locktime),x.addInput({hash:l.hash,index:l.index,sequence:l.sequence,witnessUtxo:{script:P.script,value:P.value},tapLeafScript:[{leafVersion:r.TAPSCRIPT_LEAF_VERSION,script:a.Buffer.from(h),controlBlock:a.Buffer.from(f)}],tapInternalKey:a.Buffer.from(p.tapInternalPubkey)});for(const g of i.outs)x.addOutput({script:g.script,value:g.value});return{psbtHex:x.toHex()}}function B(e,t){const o=d.Psbt.fromHex(e).data.inputs[0];if(!o)throw new Error("PegIn PSBT has no inputs");if(o.tapScriptSig&&o.tapScriptSig.length>0){const i=a.Buffer.from(r.hexToUint8Array(t));for(const s of o.tapScriptSig)if(s.pubkey.equals(i))return E(s.signature);throw new Error(`No PegIn input signature found for depositor pubkey: ${t}`)}throw o.finalScriptWitness&&o.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 C(e){const t=d.Psbt.fromHex(e);try{t.finalizeAllInputs()}catch(n){if(!t.data.inputs.every(i=>i.finalScriptWitness||i.finalScriptSig))throw new Error(`PSBT finalization failed and wallet did not auto-finalize: ${n}`)}return t.extractTransaction().toHex()}function E(e){if(e.length===64)return r.uint8ArrayToHex(new Uint8Array(e));if(e.length===65)return r.uint8ArrayToHex(new Uint8Array(e.subarray(0,64)));throw new Error(`Unexpected PegIn input signature length: ${e.length}`)}async function R(e){await p.initWasm();const{prePeginParams:t,fundedPrePeginTxHex:n,htlcVout:o,refundFee:i,hashlock:s}=e,l=new p.WasmPrePeginTx(t.depositorPubkey,t.vaultProviderPubkey,t.vaultKeeperPubkeys,t.universalChallengerPubkeys,[...t.hashlocks],new BigUint64Array(t.pegInAmounts),t.timelockRefund,t.feeRate,t.numLocalChallengers,t.councilQuorum,t.councilSize,t.network);let c=null;try{c=l.fromFundedTransaction(n);const u=c.buildRefundTx(i,o),P=await p.getPrePeginHtlcConnectorInfo({depositorPubkey:t.depositorPubkey,vaultProviderPubkey:t.vaultProviderPubkey,vaultKeeperPubkeys:t.vaultKeeperPubkeys,universalChallengerPubkeys:t.universalChallengerPubkeys,hashlock:s,timelockRefund:t.timelockRefund,network:t.network}),h=n.startsWith("0x")?n.slice(2):n,f=d.Transaction.fromHex(h),x=f.outs[o];if(!x)throw new Error(`HTLC output at vout ${o} not found in funded Pre-PegIn tx (tx has ${f.outs.length} outputs)`);const g=d.Transaction.fromHex(u);if(g.ins.length!==1)throw new Error(`Refund transaction must have exactly 1 input, got ${g.ins.length}`);const y=g.ins[0],v=f.getId(),T=r.uint8ArrayToHex(new Uint8Array(y.hash).slice().reverse());if(T!==v)throw new Error(`Refund input does not reference the Pre-PegIn transaction. Expected ${v}, got ${T}`);if(y.index!==o)throw new Error(`Refund input index ${y.index} does not match expected htlcVout ${o}`);const b=new d.Psbt;b.setVersion(g.version),b.setLocktime(g.locktime),b.addInput({hash:y.hash,index:y.index,sequence:y.sequence,witnessUtxo:{script:x.script,value:x.value},tapLeafScript:[{leafVersion:r.TAPSCRIPT_LEAF_VERSION,script:a.Buffer.from(r.hexToUint8Array(P.refundScript)),controlBlock:a.Buffer.from(r.hexToUint8Array(P.refundControlBlock))}],tapInternalKey:a.Buffer.from(p.tapInternalPubkey)});for(const w of g.outs)b.addOutput({script:w.script,value:w.value});return{psbtHex:b.toHex()}}finally{c==null||c.free(),l.free()}}async function U(e){const t=r.stripHexPrefix(e.payoutTxHex),n=d.Transaction.fromHex(t),{payoutScript:o,payoutControlBlock:i}=await p.getPeginPayoutScriptInfo(e.connectorParams),s=r.hexToUint8Array(o),l=r.hexToUint8Array(i),c=new d.Psbt;c.setVersion(n.version),c.setLocktime(n.locktime);for(let u=0;u<n.ins.length;u++){const P=n.ins[u],h=e.prevouts[u];if(!h)throw new Error(`Missing prevout data for input ${u}`);const f={hash:P.hash,index:P.index,sequence:P.sequence,witnessUtxo:{script:a.Buffer.from(r.hexToUint8Array(r.stripHexPrefix(h.script_pubkey))),value:h.value}};u===0&&(f.tapLeafScript=[{leafVersion:r.TAPSCRIPT_LEAF_VERSION,script:a.Buffer.from(s),controlBlock:a.Buffer.from(l)}],f.tapInternalKey=a.Buffer.from(p.tapInternalPubkey)),c.addInput(f)}for(const u of n.outs)c.addOutput({script:u.script,value:u.value});return c.toHex()}async function V(e){const t=r.stripHexPrefix(e.noPayoutTxHex),n=d.Transaction.fromHex(t),{noPayoutScript:o,noPayoutControlBlock:i}=await p.getAssertNoPayoutScriptInfo(e.connectorParams,e.challengerPubkey),s=r.hexToUint8Array(o),l=r.hexToUint8Array(i),c=new d.Psbt;c.setVersion(n.version),c.setLocktime(n.locktime);for(let u=0;u<n.ins.length;u++){const P=n.ins[u],h=e.prevouts[u];if(!h)throw new Error(`Missing prevout data for input ${u}`);const f={hash:P.hash,index:P.index,sequence:P.sequence,witnessUtxo:{script:a.Buffer.from(r.hexToUint8Array(r.stripHexPrefix(h.script_pubkey))),value:h.value}};u===0&&(f.tapLeafScript=[{leafVersion:r.TAPSCRIPT_LEAF_VERSION,script:a.Buffer.from(s),controlBlock:a.Buffer.from(l)}],f.tapInternalKey=a.Buffer.from(p.tapInternalPubkey)),c.addInput(f)}for(const u of n.outs)c.addOutput({script:u.script,value:u.value});return c.toHex()}async function L(e){const t=r.stripHexPrefix(e.challengeAssertTxHex),n=d.Transaction.fromHex(t);if(e.connectorParamsPerInput.length!==n.ins.length)throw new Error(`Expected ${n.ins.length} connector params, got ${e.connectorParamsPerInput.length}`);const o=await Promise.all(e.connectorParamsPerInput.map(s=>p.getChallengeAssertScriptInfo(s))),i=new d.Psbt;i.setVersion(n.version),i.setLocktime(n.locktime);for(let s=0;s<n.ins.length;s++){const l=n.ins[s],c=e.prevouts[s];if(!c)throw new Error(`Missing prevout data for input ${s}`);const{script:u,controlBlock:P}=o[s],h=r.hexToUint8Array(u),f=r.hexToUint8Array(P);i.addInput({hash:l.hash,index:l.index,sequence:l.sequence,witnessUtxo:{script:a.Buffer.from(r.hexToUint8Array(r.stripHexPrefix(c.script_pubkey))),value:c.value},tapLeafScript:[{leafVersion:r.TAPSCRIPT_LEAF_VERSION,script:a.Buffer.from(h),controlBlock:a.Buffer.from(f)}],tapInternalKey:a.Buffer.from(p.tapInternalPubkey)})}for(const s of n.outs)i.addOutput({script:s.script,value:s.value});return i.toHex()}exports.buildChallengeAssertPsbt=L;exports.buildDepositorPayoutPsbt=U;exports.buildNoPayoutPsbt=V;exports.buildPeginInputPsbt=A;exports.buildPeginTxFromFundedPrePegin=H;exports.buildPrePeginPsbt=S;exports.buildRefundPsbt=R;exports.computeNumLocalChallengers=m;exports.extractPeginInputSignature=B;exports.finalizePeginInputPsbt=C;
|
|
2
|
+
//# sourceMappingURL=challengeAssert-D_k_ADgP.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"challengeAssert-D_k_ADgP.cjs","sources":["../src/tbv/core/primitives/challengers.ts","../src/tbv/core/primitives/psbt/pegin.ts","../src/tbv/core/primitives/psbt/peginInput.ts","../src/tbv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/psbt/depositorPayout.ts","../src/tbv/core/primitives/psbt/noPayout.ts","../src/tbv/core/primitives/psbt/challengeAssert.ts"],"sourcesContent":["/**\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 * 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 { TAPSCRIPT_LEAF_VERSION, 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: TAPSCRIPT_LEAF_VERSION,\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 * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport {\n getPrePeginHtlcConnectorInfo,\n initWasm,\n tapInternalPubkey,\n WasmPrePeginTx,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { TAPSCRIPT_LEAF_VERSION, hexToUint8Array, uint8ArrayToHex } from \"../utils/bitcoin\";\nimport type { PrePeginParams } from \"./pegin\";\n\n/**\n * Parameters for building a refund PSBT\n */\nexport interface BuildRefundPsbtParams {\n /** Same PrePeginParams used when the original Pre-PegIn tx was created */\n prePeginParams: PrePeginParams;\n /** Funded Pre-PegIn transaction hex (the tx whose HTLC output is being refunded) */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output in the Pre-PegIn transaction */\n htlcVout: number;\n /** Transaction fee in satoshis for the refund transaction */\n refundFee: bigint;\n /** SHA256 hash commitment for the HTLC (64 hex chars, no 0x prefix) */\n hashlock: string;\n}\n\n/**\n * Result of building a refund PSBT\n */\nexport interface BuildRefundPsbtResult {\n /** PSBT hex ready for depositor signing */\n psbtHex: string;\n}\n\n/**\n * Build a PSBT for signing the refund transaction.\n *\n * The refund transaction spends the Pre-PegIn HTLC output via leaf 1\n * (the refund script: `<timelockRefund> CSV DROP <depositorPubkey> CHECKSIG`).\n * The PSBT includes the tapLeafScript entry so the depositor's wallet can\n * sign using Taproot script-path spending.\n *\n * The input's sequence is set to `timelockRefund` by the WASM, enforcing\n * the Bitcoin CSV timelock. The refund broadcast will be rejected by the\n * network if the timelock has not yet expired.\n *\n * @param params - Refund PSBT parameters\n * @returns PSBT hex for depositor signing\n * @throws If the HTLC output at htlcVout is not found\n * @throws If the refund transaction does not have exactly 1 input\n */\nexport async function buildRefundPsbt(\n params: BuildRefundPsbtParams,\n): Promise<BuildRefundPsbtResult> {\n await initWasm();\n\n const { prePeginParams, fundedPrePeginTxHex, htlcVout, refundFee, hashlock } =\n params;\n\n const unfundedTx = new WasmPrePeginTx(\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(prePeginParams.pegInAmounts),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n );\n\n let fundedTx: WasmPrePeginTx | null = null;\n try {\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n depositorPubkey: prePeginParams.depositorPubkey,\n vaultProviderPubkey: prePeginParams.vaultProviderPubkey,\n vaultKeeperPubkeys: prePeginParams.vaultKeeperPubkeys,\n universalChallengerPubkeys: prePeginParams.universalChallengerPubkeys,\n hashlock,\n timelockRefund: prePeginParams.timelockRefund,\n network: prePeginParams.network,\n });\n\n const cleanPrePeginHex = fundedPrePeginTxHex.startsWith(\"0x\")\n ? fundedPrePeginTxHex.slice(2)\n : fundedPrePeginTxHex;\n const prePeginTx = Transaction.fromHex(cleanPrePeginHex);\n\n const htlcOutput = prePeginTx.outs[htlcVout];\n if (!htlcOutput) {\n throw new Error(\n `HTLC output at vout ${htlcVout} not found in funded Pre-PegIn tx ` +\n `(tx has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const refundTx = Transaction.fromHex(refundTxHex);\n\n if (refundTx.ins.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 input, got ${refundTx.ins.length}`,\n );\n }\n\n const refundInput = refundTx.ins[0];\n\n // Verify the refund input spends the correct Pre-PegIn HTLC output\n const prePeginTxid = prePeginTx.getId();\n const refundInputTxid = uint8ArrayToHex(\n new Uint8Array(refundInput.hash).slice().reverse(),\n );\n if (refundInputTxid !== prePeginTxid) {\n throw new Error(\n `Refund input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${refundInputTxid}`,\n );\n }\n if (refundInput.index !== htlcVout) {\n throw new Error(\n `Refund input index ${refundInput.index} does not match expected htlcVout ${htlcVout}`,\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(refundTx.version);\n psbt.setLocktime(refundTx.locktime);\n\n psbt.addInput({\n hash: refundInput.hash,\n index: refundInput.index,\n sequence: refundInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hexToUint8Array(htlcConnector.refundScript)),\n controlBlock: Buffer.from(\n hexToUint8Array(htlcConnector.refundControlBlock),\n ),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n\n for (const output of refundTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n } finally {\n fundedTx?.free();\n unfundedTx.free();\n }\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 getPeginPayoutScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\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 and control block from WASM (PeginPayoutConnector)\n const { payoutScript, payoutControlBlock } = await getPeginPayoutScriptInfo(\n params.connectorParams,\n );\n const scriptBytes = hexToUint8Array(payoutScript);\n const controlBlock = hexToUint8Array(payoutControlBlock);\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: TAPSCRIPT_LEAF_VERSION,\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 * 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 TAPSCRIPT_LEAF_VERSION,\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: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n","/**\n * 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 TAPSCRIPT_LEAF_VERSION,\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: TAPSCRIPT_LEAF_VERSION,\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":["normalizeKey","key","processPublicKeyToXOnly","computeNumLocalChallengers","vaultProviderPubkey","vaultKeeperPubkeys","depositorPubkey","localSet","vk","buildPrePeginPsbt","params","result","createPrePeginTransaction","totalOutputValue","parseUnfundedWasmTransaction","sum","o","buildPeginTxFromFundedPrePegin","buildPeginTxFromPrePegin","buildPeginInputPsbt","peginTxHex","stripHexPrefix","fundedPrePeginTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","peginTx","Transaction","prePeginTx","peginInput","prePeginTxid","peginInputTxid","uint8ArrayToHex","htlcOutput","hashlockScript","hexToUint8Array","hashlockControlBlock","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPeginInputSignature","signedPsbtHex","input","depositorPubkeyBytes","sigEntry","extractSchnorrSig","finalizePeginInputPsbt","e","inp","sig","buildRefundPsbt","initWasm","prePeginParams","htlcVout","refundFee","hashlock","unfundedTx","WasmPrePeginTx","fundedTx","refundTxHex","cleanPrePeginHex","refundTx","refundInput","refundInputTxid","buildDepositorPayoutPsbt","payoutTxHex","payoutTx","payoutScript","payoutControlBlock","getPeginPayoutScriptInfo","scriptBytes","controlBlock","i","prevout","inputData","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","controlBlockBytes","buildChallengeAssertPsbt","challengeAssertTxHex","challengeAssertTx","scriptInfos","cp","getChallengeAssertScriptInfo","script"],"mappings":"4MAeA,SAASA,EAAaC,EAAqB,CACzC,OAAOC,EAAAA,wBAAwBD,CAAG,EAAE,YAAA,CACtC,CAgBO,SAASE,EACdC,EACAC,EACAC,EACQ,CACR,MAAMC,MAAe,IACrBA,EAAS,IAAIP,EAAaI,CAAmB,CAAC,EAC9C,UAAWI,KAAMH,EACfE,EAAS,IAAIP,EAAaQ,CAAE,CAAC,EAE/B,OAAAD,EAAS,OAAOP,EAAaM,CAAe,CAAC,EACtCC,EAAS,IAClB,CC4EA,eAAsBE,EACpBC,EAC6B,CAC7B,MAAMC,EAAS,MAAMC,4BAA0B,CAC7C,gBAAiBF,EAAO,gBACxB,oBAAqBA,EAAO,oBAC5B,mBAAoBA,EAAO,mBAC3B,2BAA4BA,EAAO,2BACnC,UAAW,CAAC,GAAGA,EAAO,SAAS,EAC/B,eAAgBA,EAAO,eACvB,aAAc,CAAC,GAAGA,EAAO,YAAY,E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,EAC/BC,EAAUjE,EAAO,SAASgE,CAAC,EAEjC,GAAI,CAACC,EACH,MAAM,IAAI,MAAM,kCAAkCD,CAAC,EAAE,EAGvD,KAAM,CAAE,OAAAgB,EAAQ,aAAAjB,GAAiBc,EAAYb,CAAC,EACxCF,EAActC,EAAAA,gBAAgBwD,CAAM,EACpCP,EAAoBjD,EAAAA,gBAAgBuC,CAAY,EAEtDrC,EAAK,SAAS,CACZ,KAAMQ,EAAM,KACZ,MAAOA,EAAM,MACb,SAAUA,EAAM,SAChB,YAAa,CACX,OAAQL,EAAAA,OAAO,KAAKL,EAAAA,gBAAgBb,EAAAA,eAAesD,EAAQ,aAAa,CAAC,CAAC,EAC1E,MAAOA,EAAQ,KAAA,EAEjB,cAAe,CACb,CACE,YAAarC,EAAAA,uBACb,OAAQC,EAAAA,OAAO,KAAKiC,CAAW,EAC/B,aAAcjC,EAAAA,OAAO,KAAK4C,CAAiB,CAAA,CAC7C,EAEF,eAAgB5C,EAAAA,OAAO,KAAKC,EAAAA,iBAAiB,CAAA,CAC9C,CACH,CAGA,UAAWC,KAAU6C,EAAkB,KACrClD,EAAK,UAAU,CACb,OAAQK,EAAO,OACf,MAAOA,EAAO,KAAA,CACf,EAGH,OAAOL,EAAK,MAAA,CACd"}
|
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
import { p as B, s as g, u as m, h as P, j as b } from "./constants-Q7v2O7Ps.js";
|
|
2
|
+
import { createPrePeginTransaction as A, buildPeginTxFromPrePegin as E, getPrePeginHtlcConnectorInfo as C, tapInternalPubkey as w, initWasm as R, WasmPrePeginTx as V, getPeginPayoutScriptInfo as K, getAssertNoPayoutScriptInfo as $, getChallengeAssertScriptInfo as L } from "@babylonlabs-io/babylon-tbv-rust-wasm";
|
|
3
|
+
import { p as z } from "./fundPeginTransaction-DpwnDslW.js";
|
|
4
|
+
import { Buffer as c } from "buffer";
|
|
5
|
+
import { Transaction as x, Psbt as k } from "bitcoinjs-lib";
|
|
6
|
+
function S(e) {
|
|
7
|
+
return B(e).toLowerCase();
|
|
8
|
+
}
|
|
9
|
+
function Q(e, t, n) {
|
|
10
|
+
const o = /* @__PURE__ */ new Set();
|
|
11
|
+
o.add(S(e));
|
|
12
|
+
for (const r of t)
|
|
13
|
+
o.add(S(r));
|
|
14
|
+
return o.delete(S(n)), o.size;
|
|
15
|
+
}
|
|
16
|
+
async function _(e) {
|
|
17
|
+
const t = await A({
|
|
18
|
+
depositorPubkey: e.depositorPubkey,
|
|
19
|
+
vaultProviderPubkey: e.vaultProviderPubkey,
|
|
20
|
+
vaultKeeperPubkeys: e.vaultKeeperPubkeys,
|
|
21
|
+
universalChallengerPubkeys: e.universalChallengerPubkeys,
|
|
22
|
+
hashlocks: [...e.hashlocks],
|
|
23
|
+
timelockRefund: e.timelockRefund,
|
|
24
|
+
pegInAmounts: [...e.pegInAmounts],
|
|
25
|
+
feeRate: e.feeRate,
|
|
26
|
+
numLocalChallengers: e.numLocalChallengers,
|
|
27
|
+
councilQuorum: e.councilQuorum,
|
|
28
|
+
councilSize: e.councilSize,
|
|
29
|
+
network: e.network
|
|
30
|
+
}), o = z(t.txHex).outputs.reduce(
|
|
31
|
+
(r, i) => r + BigInt(i.value),
|
|
32
|
+
0n
|
|
33
|
+
);
|
|
34
|
+
return {
|
|
35
|
+
psbtHex: t.txHex,
|
|
36
|
+
totalOutputValue: o,
|
|
37
|
+
htlcValues: t.htlcValues,
|
|
38
|
+
htlcScriptPubKeys: t.htlcScriptPubKeys,
|
|
39
|
+
htlcAddresses: t.htlcAddresses,
|
|
40
|
+
peginAmounts: t.peginAmounts,
|
|
41
|
+
depositorClaimValue: t.depositorClaimValue
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
async function D(e) {
|
|
45
|
+
const t = await E(
|
|
46
|
+
{
|
|
47
|
+
depositorPubkey: e.prePeginParams.depositorPubkey,
|
|
48
|
+
vaultProviderPubkey: e.prePeginParams.vaultProviderPubkey,
|
|
49
|
+
vaultKeeperPubkeys: e.prePeginParams.vaultKeeperPubkeys,
|
|
50
|
+
universalChallengerPubkeys: e.prePeginParams.universalChallengerPubkeys,
|
|
51
|
+
hashlocks: [...e.prePeginParams.hashlocks],
|
|
52
|
+
timelockRefund: e.prePeginParams.timelockRefund,
|
|
53
|
+
pegInAmounts: [...e.prePeginParams.pegInAmounts],
|
|
54
|
+
feeRate: e.prePeginParams.feeRate,
|
|
55
|
+
numLocalChallengers: e.prePeginParams.numLocalChallengers,
|
|
56
|
+
councilQuorum: e.prePeginParams.councilQuorum,
|
|
57
|
+
councilSize: e.prePeginParams.councilSize,
|
|
58
|
+
network: e.prePeginParams.network
|
|
59
|
+
},
|
|
60
|
+
e.timelockPegin,
|
|
61
|
+
e.fundedPrePeginTxHex,
|
|
62
|
+
e.htlcVout
|
|
63
|
+
);
|
|
64
|
+
return {
|
|
65
|
+
txHex: t.txHex,
|
|
66
|
+
txid: t.txid,
|
|
67
|
+
vaultScriptPubKey: t.vaultScriptPubKey,
|
|
68
|
+
vaultValue: t.vaultValue
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
async function M(e) {
|
|
72
|
+
const t = g(e.peginTxHex), n = g(e.fundedPrePeginTxHex), o = await C({
|
|
73
|
+
depositorPubkey: e.depositorPubkey,
|
|
74
|
+
vaultProviderPubkey: e.vaultProviderPubkey,
|
|
75
|
+
vaultKeeperPubkeys: e.vaultKeeperPubkeys,
|
|
76
|
+
universalChallengerPubkeys: e.universalChallengerPubkeys,
|
|
77
|
+
hashlock: e.hashlock,
|
|
78
|
+
timelockRefund: e.timelockRefund,
|
|
79
|
+
network: e.network
|
|
80
|
+
}), r = x.fromHex(t), i = x.fromHex(n);
|
|
81
|
+
if (r.ins.length !== 1)
|
|
82
|
+
throw new Error(
|
|
83
|
+
`PegIn transaction must have exactly 1 input, got ${r.ins.length}`
|
|
84
|
+
);
|
|
85
|
+
const l = r.ins[0], u = i.getId(), s = m(
|
|
86
|
+
new Uint8Array(l.hash).slice().reverse()
|
|
87
|
+
);
|
|
88
|
+
if (s !== u)
|
|
89
|
+
throw new Error(
|
|
90
|
+
`PegIn input does not reference the Pre-PegIn transaction. Expected ${u}, got ${s}`
|
|
91
|
+
);
|
|
92
|
+
const a = i.outs[l.index];
|
|
93
|
+
if (!a)
|
|
94
|
+
throw new Error(
|
|
95
|
+
`Pre-PegIn output ${l.index} not found (Pre-PegIn has ${i.outs.length} outputs)`
|
|
96
|
+
);
|
|
97
|
+
const f = P(o.hashlockScript), p = P(o.hashlockControlBlock), d = new k();
|
|
98
|
+
d.setVersion(r.version), d.setLocktime(r.locktime), d.addInput({
|
|
99
|
+
hash: l.hash,
|
|
100
|
+
index: l.index,
|
|
101
|
+
sequence: l.sequence,
|
|
102
|
+
witnessUtxo: {
|
|
103
|
+
script: a.script,
|
|
104
|
+
value: a.value
|
|
105
|
+
},
|
|
106
|
+
tapLeafScript: [
|
|
107
|
+
{
|
|
108
|
+
leafVersion: b,
|
|
109
|
+
script: c.from(f),
|
|
110
|
+
controlBlock: c.from(p)
|
|
111
|
+
}
|
|
112
|
+
],
|
|
113
|
+
tapInternalKey: c.from(w)
|
|
114
|
+
// sighashType omitted — defaults to SIGHASH_DEFAULT (0x00) for Taproot
|
|
115
|
+
});
|
|
116
|
+
for (const h of r.outs)
|
|
117
|
+
d.addOutput({
|
|
118
|
+
script: h.script,
|
|
119
|
+
value: h.value
|
|
120
|
+
});
|
|
121
|
+
return { psbtHex: d.toHex() };
|
|
122
|
+
}
|
|
123
|
+
function j(e, t) {
|
|
124
|
+
const o = k.fromHex(e).data.inputs[0];
|
|
125
|
+
if (!o)
|
|
126
|
+
throw new Error("PegIn PSBT has no inputs");
|
|
127
|
+
if (o.tapScriptSig && o.tapScriptSig.length > 0) {
|
|
128
|
+
const r = c.from(
|
|
129
|
+
P(t)
|
|
130
|
+
);
|
|
131
|
+
for (const i of o.tapScriptSig)
|
|
132
|
+
if (i.pubkey.equals(r))
|
|
133
|
+
return U(i.signature);
|
|
134
|
+
throw new Error(
|
|
135
|
+
`No PegIn input signature found for depositor pubkey: ${t}`
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
throw o.finalScriptWitness && o.finalScriptWitness.length > 0 ? new Error(
|
|
139
|
+
"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."
|
|
140
|
+
) : new Error(
|
|
141
|
+
"No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT"
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
function X(e) {
|
|
145
|
+
const t = k.fromHex(e);
|
|
146
|
+
try {
|
|
147
|
+
t.finalizeAllInputs();
|
|
148
|
+
} catch (n) {
|
|
149
|
+
if (!t.data.inputs.every(
|
|
150
|
+
(r) => r.finalScriptWitness || r.finalScriptSig
|
|
151
|
+
))
|
|
152
|
+
throw new Error(
|
|
153
|
+
`PSBT finalization failed and wallet did not auto-finalize: ${n}`
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
return t.extractTransaction().toHex();
|
|
157
|
+
}
|
|
158
|
+
function U(e) {
|
|
159
|
+
if (e.length === 64)
|
|
160
|
+
return m(new Uint8Array(e));
|
|
161
|
+
if (e.length === 65)
|
|
162
|
+
return m(new Uint8Array(e.subarray(0, 64)));
|
|
163
|
+
throw new Error(`Unexpected PegIn input signature length: ${e.length}`);
|
|
164
|
+
}
|
|
165
|
+
async function G(e) {
|
|
166
|
+
await R();
|
|
167
|
+
const { prePeginParams: t, fundedPrePeginTxHex: n, htlcVout: o, refundFee: r, hashlock: i } = e, l = new V(
|
|
168
|
+
t.depositorPubkey,
|
|
169
|
+
t.vaultProviderPubkey,
|
|
170
|
+
t.vaultKeeperPubkeys,
|
|
171
|
+
t.universalChallengerPubkeys,
|
|
172
|
+
[...t.hashlocks],
|
|
173
|
+
new BigUint64Array(t.pegInAmounts),
|
|
174
|
+
t.timelockRefund,
|
|
175
|
+
t.feeRate,
|
|
176
|
+
t.numLocalChallengers,
|
|
177
|
+
t.councilQuorum,
|
|
178
|
+
t.councilSize,
|
|
179
|
+
t.network
|
|
180
|
+
);
|
|
181
|
+
let u = null;
|
|
182
|
+
try {
|
|
183
|
+
u = l.fromFundedTransaction(n);
|
|
184
|
+
const s = u.buildRefundTx(r, o), a = await C({
|
|
185
|
+
depositorPubkey: t.depositorPubkey,
|
|
186
|
+
vaultProviderPubkey: t.vaultProviderPubkey,
|
|
187
|
+
vaultKeeperPubkeys: t.vaultKeeperPubkeys,
|
|
188
|
+
universalChallengerPubkeys: t.universalChallengerPubkeys,
|
|
189
|
+
hashlock: i,
|
|
190
|
+
timelockRefund: t.timelockRefund,
|
|
191
|
+
network: t.network
|
|
192
|
+
}), f = n.startsWith("0x") ? n.slice(2) : n, p = x.fromHex(f), d = p.outs[o];
|
|
193
|
+
if (!d)
|
|
194
|
+
throw new Error(
|
|
195
|
+
`HTLC output at vout ${o} not found in funded Pre-PegIn tx (tx has ${p.outs.length} outputs)`
|
|
196
|
+
);
|
|
197
|
+
const h = x.fromHex(s);
|
|
198
|
+
if (h.ins.length !== 1)
|
|
199
|
+
throw new Error(
|
|
200
|
+
`Refund transaction must have exactly 1 input, got ${h.ins.length}`
|
|
201
|
+
);
|
|
202
|
+
const y = h.ins[0], I = p.getId(), T = m(
|
|
203
|
+
new Uint8Array(y.hash).slice().reverse()
|
|
204
|
+
);
|
|
205
|
+
if (T !== I)
|
|
206
|
+
throw new Error(
|
|
207
|
+
`Refund input does not reference the Pre-PegIn transaction. Expected ${I}, got ${T}`
|
|
208
|
+
);
|
|
209
|
+
if (y.index !== o)
|
|
210
|
+
throw new Error(
|
|
211
|
+
`Refund input index ${y.index} does not match expected htlcVout ${o}`
|
|
212
|
+
);
|
|
213
|
+
const v = new k();
|
|
214
|
+
v.setVersion(h.version), v.setLocktime(h.locktime), v.addInput({
|
|
215
|
+
hash: y.hash,
|
|
216
|
+
index: y.index,
|
|
217
|
+
sequence: y.sequence,
|
|
218
|
+
witnessUtxo: {
|
|
219
|
+
script: d.script,
|
|
220
|
+
value: d.value
|
|
221
|
+
},
|
|
222
|
+
tapLeafScript: [
|
|
223
|
+
{
|
|
224
|
+
leafVersion: b,
|
|
225
|
+
script: c.from(P(a.refundScript)),
|
|
226
|
+
controlBlock: c.from(
|
|
227
|
+
P(a.refundControlBlock)
|
|
228
|
+
)
|
|
229
|
+
}
|
|
230
|
+
],
|
|
231
|
+
tapInternalKey: c.from(w)
|
|
232
|
+
});
|
|
233
|
+
for (const H of h.outs)
|
|
234
|
+
v.addOutput({
|
|
235
|
+
script: H.script,
|
|
236
|
+
value: H.value
|
|
237
|
+
});
|
|
238
|
+
return { psbtHex: v.toHex() };
|
|
239
|
+
} finally {
|
|
240
|
+
u == null || u.free(), l.free();
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
async function J(e) {
|
|
244
|
+
const t = g(e.payoutTxHex), n = x.fromHex(t), { payoutScript: o, payoutControlBlock: r } = await K(
|
|
245
|
+
e.connectorParams
|
|
246
|
+
), i = P(o), l = P(r), u = new k();
|
|
247
|
+
u.setVersion(n.version), u.setLocktime(n.locktime);
|
|
248
|
+
for (let s = 0; s < n.ins.length; s++) {
|
|
249
|
+
const a = n.ins[s], f = e.prevouts[s];
|
|
250
|
+
if (!f)
|
|
251
|
+
throw new Error(`Missing prevout data for input ${s}`);
|
|
252
|
+
const p = {
|
|
253
|
+
hash: a.hash,
|
|
254
|
+
index: a.index,
|
|
255
|
+
sequence: a.sequence,
|
|
256
|
+
witnessUtxo: {
|
|
257
|
+
script: c.from(P(g(f.script_pubkey))),
|
|
258
|
+
value: f.value
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
s === 0 && (p.tapLeafScript = [
|
|
262
|
+
{
|
|
263
|
+
leafVersion: b,
|
|
264
|
+
script: c.from(i),
|
|
265
|
+
controlBlock: c.from(l)
|
|
266
|
+
}
|
|
267
|
+
], p.tapInternalKey = c.from(w)), u.addInput(p);
|
|
268
|
+
}
|
|
269
|
+
for (const s of n.outs)
|
|
270
|
+
u.addOutput({
|
|
271
|
+
script: s.script,
|
|
272
|
+
value: s.value
|
|
273
|
+
});
|
|
274
|
+
return u.toHex();
|
|
275
|
+
}
|
|
276
|
+
async function Y(e) {
|
|
277
|
+
const t = g(e.noPayoutTxHex), n = x.fromHex(t), { noPayoutScript: o, noPayoutControlBlock: r } = await $(
|
|
278
|
+
e.connectorParams,
|
|
279
|
+
e.challengerPubkey
|
|
280
|
+
), i = P(o), l = P(r), u = new k();
|
|
281
|
+
u.setVersion(n.version), u.setLocktime(n.locktime);
|
|
282
|
+
for (let s = 0; s < n.ins.length; s++) {
|
|
283
|
+
const a = n.ins[s], f = e.prevouts[s];
|
|
284
|
+
if (!f)
|
|
285
|
+
throw new Error(`Missing prevout data for input ${s}`);
|
|
286
|
+
const p = {
|
|
287
|
+
hash: a.hash,
|
|
288
|
+
index: a.index,
|
|
289
|
+
sequence: a.sequence,
|
|
290
|
+
witnessUtxo: {
|
|
291
|
+
script: c.from(P(g(f.script_pubkey))),
|
|
292
|
+
value: f.value
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
s === 0 && (p.tapLeafScript = [
|
|
296
|
+
{
|
|
297
|
+
leafVersion: b,
|
|
298
|
+
script: c.from(i),
|
|
299
|
+
controlBlock: c.from(l)
|
|
300
|
+
}
|
|
301
|
+
], p.tapInternalKey = c.from(w)), u.addInput(p);
|
|
302
|
+
}
|
|
303
|
+
for (const s of n.outs)
|
|
304
|
+
u.addOutput({
|
|
305
|
+
script: s.script,
|
|
306
|
+
value: s.value
|
|
307
|
+
});
|
|
308
|
+
return u.toHex();
|
|
309
|
+
}
|
|
310
|
+
async function Z(e) {
|
|
311
|
+
const t = g(e.challengeAssertTxHex), n = x.fromHex(t);
|
|
312
|
+
if (e.connectorParamsPerInput.length !== n.ins.length)
|
|
313
|
+
throw new Error(
|
|
314
|
+
`Expected ${n.ins.length} connector params, got ${e.connectorParamsPerInput.length}`
|
|
315
|
+
);
|
|
316
|
+
const o = await Promise.all(
|
|
317
|
+
e.connectorParamsPerInput.map((i) => L(i))
|
|
318
|
+
), r = new k();
|
|
319
|
+
r.setVersion(n.version), r.setLocktime(n.locktime);
|
|
320
|
+
for (let i = 0; i < n.ins.length; i++) {
|
|
321
|
+
const l = n.ins[i], u = e.prevouts[i];
|
|
322
|
+
if (!u)
|
|
323
|
+
throw new Error(`Missing prevout data for input ${i}`);
|
|
324
|
+
const { script: s, controlBlock: a } = o[i], f = P(s), p = P(a);
|
|
325
|
+
r.addInput({
|
|
326
|
+
hash: l.hash,
|
|
327
|
+
index: l.index,
|
|
328
|
+
sequence: l.sequence,
|
|
329
|
+
witnessUtxo: {
|
|
330
|
+
script: c.from(P(g(u.script_pubkey))),
|
|
331
|
+
value: u.value
|
|
332
|
+
},
|
|
333
|
+
tapLeafScript: [
|
|
334
|
+
{
|
|
335
|
+
leafVersion: b,
|
|
336
|
+
script: c.from(f),
|
|
337
|
+
controlBlock: c.from(p)
|
|
338
|
+
}
|
|
339
|
+
],
|
|
340
|
+
tapInternalKey: c.from(w)
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
for (const i of n.outs)
|
|
344
|
+
r.addOutput({
|
|
345
|
+
script: i.script,
|
|
346
|
+
value: i.value
|
|
347
|
+
});
|
|
348
|
+
return r.toHex();
|
|
349
|
+
}
|
|
350
|
+
export {
|
|
351
|
+
D as a,
|
|
352
|
+
_ as b,
|
|
353
|
+
Q as c,
|
|
354
|
+
M as d,
|
|
355
|
+
j as e,
|
|
356
|
+
X as f,
|
|
357
|
+
G as g,
|
|
358
|
+
J as h,
|
|
359
|
+
Y as i,
|
|
360
|
+
Z as j
|
|
361
|
+
};
|
|
362
|
+
//# sourceMappingURL=challengeAssert-k5_LWUtO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"challengeAssert-k5_LWUtO.js","sources":["../src/tbv/core/primitives/challengers.ts","../src/tbv/core/primitives/psbt/pegin.ts","../src/tbv/core/primitives/psbt/peginInput.ts","../src/tbv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/psbt/depositorPayout.ts","../src/tbv/core/primitives/psbt/noPayout.ts","../src/tbv/core/primitives/psbt/challengeAssert.ts"],"sourcesContent":["/**\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 * 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 { TAPSCRIPT_LEAF_VERSION, 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: TAPSCRIPT_LEAF_VERSION,\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 * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport {\n getPrePeginHtlcConnectorInfo,\n initWasm,\n tapInternalPubkey,\n WasmPrePeginTx,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { TAPSCRIPT_LEAF_VERSION, hexToUint8Array, uint8ArrayToHex } from \"../utils/bitcoin\";\nimport type { PrePeginParams } from \"./pegin\";\n\n/**\n * Parameters for building a refund PSBT\n */\nexport interface BuildRefundPsbtParams {\n /** Same PrePeginParams used when the original Pre-PegIn tx was created */\n prePeginParams: PrePeginParams;\n /** Funded Pre-PegIn transaction hex (the tx whose HTLC output is being refunded) */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output in the Pre-PegIn transaction */\n htlcVout: number;\n /** Transaction fee in satoshis for the refund transaction */\n refundFee: bigint;\n /** SHA256 hash commitment for the HTLC (64 hex chars, no 0x prefix) */\n hashlock: string;\n}\n\n/**\n * Result of building a refund PSBT\n */\nexport interface BuildRefundPsbtResult {\n /** PSBT hex ready for depositor signing */\n psbtHex: string;\n}\n\n/**\n * Build a PSBT for signing the refund transaction.\n *\n * The refund transaction spends the Pre-PegIn HTLC output via leaf 1\n * (the refund script: `<timelockRefund> CSV DROP <depositorPubkey> CHECKSIG`).\n * The PSBT includes the tapLeafScript entry so the depositor's wallet can\n * sign using Taproot script-path spending.\n *\n * The input's sequence is set to `timelockRefund` by the WASM, enforcing\n * the Bitcoin CSV timelock. The refund broadcast will be rejected by the\n * network if the timelock has not yet expired.\n *\n * @param params - Refund PSBT parameters\n * @returns PSBT hex for depositor signing\n * @throws If the HTLC output at htlcVout is not found\n * @throws If the refund transaction does not have exactly 1 input\n */\nexport async function buildRefundPsbt(\n params: BuildRefundPsbtParams,\n): Promise<BuildRefundPsbtResult> {\n await initWasm();\n\n const { prePeginParams, fundedPrePeginTxHex, htlcVout, refundFee, hashlock } =\n params;\n\n const unfundedTx = new WasmPrePeginTx(\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(prePeginParams.pegInAmounts),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n );\n\n let fundedTx: WasmPrePeginTx | null = null;\n try {\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n depositorPubkey: prePeginParams.depositorPubkey,\n vaultProviderPubkey: prePeginParams.vaultProviderPubkey,\n vaultKeeperPubkeys: prePeginParams.vaultKeeperPubkeys,\n universalChallengerPubkeys: prePeginParams.universalChallengerPubkeys,\n hashlock,\n timelockRefund: prePeginParams.timelockRefund,\n network: prePeginParams.network,\n });\n\n const cleanPrePeginHex = fundedPrePeginTxHex.startsWith(\"0x\")\n ? fundedPrePeginTxHex.slice(2)\n : fundedPrePeginTxHex;\n const prePeginTx = Transaction.fromHex(cleanPrePeginHex);\n\n const htlcOutput = prePeginTx.outs[htlcVout];\n if (!htlcOutput) {\n throw new Error(\n `HTLC output at vout ${htlcVout} not found in funded Pre-PegIn tx ` +\n `(tx has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const refundTx = Transaction.fromHex(refundTxHex);\n\n if (refundTx.ins.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 input, got ${refundTx.ins.length}`,\n );\n }\n\n const refundInput = refundTx.ins[0];\n\n // Verify the refund input spends the correct Pre-PegIn HTLC output\n const prePeginTxid = prePeginTx.getId();\n const refundInputTxid = uint8ArrayToHex(\n new Uint8Array(refundInput.hash).slice().reverse(),\n );\n if (refundInputTxid !== prePeginTxid) {\n throw new Error(\n `Refund input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${refundInputTxid}`,\n );\n }\n if (refundInput.index !== htlcVout) {\n throw new Error(\n `Refund input index ${refundInput.index} does not match expected htlcVout ${htlcVout}`,\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(refundTx.version);\n psbt.setLocktime(refundTx.locktime);\n\n psbt.addInput({\n hash: refundInput.hash,\n index: refundInput.index,\n sequence: refundInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hexToUint8Array(htlcConnector.refundScript)),\n controlBlock: Buffer.from(\n hexToUint8Array(htlcConnector.refundControlBlock),\n ),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n\n for (const output of refundTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n } finally {\n fundedTx?.free();\n unfundedTx.free();\n }\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 getPeginPayoutScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\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 and control block from WASM (PeginPayoutConnector)\n const { payoutScript, payoutControlBlock } = await getPeginPayoutScriptInfo(\n params.connectorParams,\n );\n const scriptBytes = hexToUint8Array(payoutScript);\n const controlBlock = hexToUint8Array(payoutControlBlock);\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: TAPSCRIPT_LEAF_VERSION,\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 * 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 TAPSCRIPT_LEAF_VERSION,\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: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n","/**\n * 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 TAPSCRIPT_LEAF_VERSION,\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: TAPSCRIPT_LEAF_VERSION,\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":["normalizeKey","key","processPublicKeyToXOnly","computeNumLocalChallengers","vaultProviderPubkey","vaultKeeperPubkeys","depositorPubkey","localSet","vk","buildPrePeginPsbt","params","result","createPrePeginTransaction","totalOutputValue","parseUnfundedWasmTransaction","sum","o","buildPeginTxFromFundedPrePegin","buildPeginTxFromPrePegin","buildPeginInputPsbt","peginTxHex","stripHexPrefix","fundedPrePeginTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","peginTx","Transaction","prePeginTx","peginInput","prePeginTxid","peginInputTxid","uint8ArrayToHex","htlcOutput","hashlockScript","hexToUint8Array","hashlockControlBlock","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPeginInputSignature","signedPsbtHex","input","depositorPubkeyBytes","sigEntry","extractSchnorrSig","finalizePeginInputPsbt","e","inp","sig","buildRefundPsbt","initWasm","prePeginParams","htlcVout","refundFee","hashlock","unfundedTx","WasmPrePeginTx","fundedTx","refundTxHex","cleanPrePeginHex","refundTx","refundInput","refundInputTxid","buildDepositorPayoutPsbt","payoutTxHex","payoutTx","payoutScript","payoutControlBlock","getPeginPayoutScriptInfo","scriptBytes","controlBlock","i","prevout","inputData","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","controlBlockBytes","buildChallengeAssertPsbt","challengeAssertTxHex","challengeAssertTx","scriptInfos","cp","getChallengeAssertScriptInfo","script"],"mappings":";;;;;AAeA,SAASA,EAAaC,GAAqB;AACzC,SAAOC,EAAwBD,CAAG,EAAE,YAAA;AACtC;AAgBO,SAASE,EACdC,GACAC,GACAC,GACQ;AACR,QAAMC,wBAAe,IAAA;AACrB,EAAAA,EAAS,IAAIP,EAAaI,CAAmB,CAAC;AAC9C,aAAWI,KAAMH;AACf,IAAAE,EAAS,IAAIP,EAAaQ,CAAE,CAAC;AAE/B,SAAAD,EAAS,OAAOP,EAAaM,CAAe,CAAC,GACtCC,EAAS;AAClB;AC4EA,eAAsBE,EACpBC,GAC6B;AAC7B,QAAMC,IAAS,MAAMC,EAA0B;AAAA,IAC7C,iBAAiBF,EAAO;AAAA,IACxB,qBAAqBA,EAAO;AAAA,IAC5B,oBAAoBA,EAAO;AAAA,IAC3B,4BAA4BA,EAAO;AAAA,IACnC,WAAW,CAAC,GAAGA,EAAO,SAAS;AAAA,IAC/B,gBAAgBA,EAAO;AAAA,IACvB,cAAc,CAAC,GAAGA,EAAO,YAAY;AAAA,IACrC,SAASA,EAAO;AAAA,IAChB,qBAAqBA,EAAO;AAAA,IAC5B,eAAeA,EAAO;AAAA,IACtB,aAAaA,EAAO;AAAA,IACpB,SAASA,EAAO;AAAA,EAAA,CACjB,GAKKG,IADSC,EAA6BH,EAAO,KAAK,EACxB,QAAQ;AAAA,IACtC,CAACI,GAAKC,MAAMD,IAAM,OAAOC,EAAE,KAAK;AAAA,IAChC;AAAA,EAAA;AAGF,SAAO;AAAA,IACL,SAASL,EAAO;AAAA,IAChB,kBAAAE;AAAA,IACA,YAAYF,EAAO;AAAA,IACnB,m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ACf;AAGH,SAAOL,EAAK,MAAA;AACd;"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";const a=require("buffer"),o=require("bitcoinjs-lib"),w=192;function i(e){return e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e}function I(e){return e.startsWith("0x")?e:`0x${e}`}function s(e){const t=i(e);if(!u(t))throw new Error(`Invalid hex string: ${e}`);const n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=parseInt(t.slice(r,r+2),16);return n}function f(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function T(e){return e.length===32?e:e.slice(1,33)}function u(e){return/^[0-9a-fA-F]*$/.test(e)&&e.length%2===0}function E(e){const t=i(e);if(!u(t))throw new Error(`Invalid hex characters in public key: ${e}`);if(t.length===64)return t;if(t.length!==66&&t.length!==130)throw new Error(`Invalid public key length: ${t.length} (expected 64, 66, or 130 hex chars)`);const n=s(t);return f(T(n))}function P(e){const t=i(e);return u(t)}function g(e,t){const n=E(e),r=t??n;if(n.toLowerCase()!==r.toLowerCase())throw new Error(`Wallet public key does not match vault depositor. Expected: ${r}, Got: ${n}. Please connect the wallet that was used to create this vault.`);return{walletPubkeyRaw:e,walletPubkeyXOnly:n,depositorPubkey:r}}function F(){try{o.payments.p2tr({internalPubkey:a.Buffer.alloc(32,1)})}catch(e){if(e instanceof Error&&e.message.includes("No ECC Library provided"))throw new Error('ECC library not initialized. You must call initEccLib(ecc) from "bitcoinjs-lib" before using the SDK. See the ts-sdk README for setup instructions.')}}function l(e){switch(e){case"bitcoin":return o.networks.bitcoin;case"testnet":case"signet":return o.networks.testnet;case"regtest":return o.networks.regtest;default:throw new Error(`Unknown network: ${e}`)}}function _(e,t){F();const n=s(E(e)),{address:r}=o.payments.p2tr({internalPubkey:a.Buffer.from(n),network:l(t)});if(!r)throw new Error("Failed to derive taproot address from public key");return r}function d(e,t){const n=i(e);if(n.length!==66)throw new Error(`Native SegWit requires a compressed public key (66 hex chars), got ${n.length}`);const{address:r}=o.payments.p2wpkh({pubkey:a.Buffer.from(s(n)),network:l(t)});if(!r)throw new Error("Failed to derive native segwit address from public key");return r}function R(e,t,n){const r=i(t);try{if(e===_(r,n))return!0}catch{}const c=[];r.length===66?c.push(r):r.length===64&&c.push(`02${r}`,`03${r}`);for(const p of c)try{if(e===d(p,n))return!0}catch{}return!1}const L=58,O=43,U=11,A=546,b=BigInt(A),h=30,y=2,x=1.1;function k(e){return e<=y?h:0}const S=1;function H(e){return e+S}const C=5;exports.BTC_DUST_SAT=A;exports.DUST_THRESHOLD=b;exports.FEE_SAFETY_MARGIN=x;exports.LOW_RATE_ESTIMATION_ACCURACY_BUFFER=h;exports.MAX_NON_LEGACY_OUTPUT_SIZE=O;exports.P2TR_INPUT_SIZE=L;exports.PEGIN_FIXED_OUTPUTS=S;exports.SPLIT_TX_FEE_SAFETY_MULTIPLIER=C;exports.TAPSCRIPT_LEAF_VERSION=w;exports.TX_BUFFER_SIZE_OVERHEAD=U;exports.WALLET_RELAY_FEE_RATE_THRESHOLD=y;exports.deriveNativeSegwitAddress=d;exports.deriveTaprootAddress=_;exports.ensureHexPrefix=I;exports.getNetwork=l;exports.hexToUint8Array=s;exports.isAddressFromPublicKey=R;exports.isValidHex=P;exports.peginOutputCount=H;exports.processPublicKeyToXOnly=E;exports.rateBasedTxBufferFee=k;exports.stripHexPrefix=i;exports.toXOnly=T;exports.uint8ArrayToHex=f;exports.validateWalletPubkey=g;
|
|
2
|
+
//# sourceMappingURL=constants-EiyZkXce.cjs.map
|