@babylonlabs-io/ts-sdk 0.33.0 → 0.33.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{PeginManager-DUMF84XK.cjs → PeginManager-D2pBM0E-.cjs} +2 -2
- package/dist/{PeginManager-DUMF84XK.cjs.map → PeginManager-D2pBM0E-.cjs.map} +1 -1
- package/dist/{PeginManager-BMrWtTji.js → PeginManager-LeGYbRN2.js} +3 -3
- package/dist/{PeginManager-BMrWtTji.js.map → PeginManager-LeGYbRN2.js.map} +1 -1
- package/dist/{buildAndBroadcastRefund-6pR681fI.cjs → buildAndBroadcastRefund-BXjYAqdb.cjs} +2 -2
- package/dist/{buildAndBroadcastRefund-6pR681fI.cjs.map → buildAndBroadcastRefund-BXjYAqdb.cjs.map} +1 -1
- package/dist/{buildAndBroadcastRefund-Ba56IKL7.js → buildAndBroadcastRefund-CK8MbGQh.js} +2 -2
- package/dist/{buildAndBroadcastRefund-Ba56IKL7.js.map → buildAndBroadcastRefund-CK8MbGQh.js.map} +1 -1
- package/dist/challengeAssert-06GLZtV8.cjs +2 -0
- package/dist/challengeAssert-06GLZtV8.cjs.map +1 -0
- package/dist/{challengeAssert-DSlCIBoT.js → challengeAssert-KGVKQh0J.js} +64 -70
- package/dist/challengeAssert-KGVKQh0J.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +4 -4
- package/dist/{noPayout-DohtepqZ.js → noPayout-BmMd4NNH.js} +44 -50
- package/dist/{noPayout-DohtepqZ.js.map → noPayout-BmMd4NNH.js.map} +1 -1
- package/dist/noPayout-Bp2TYA_X.cjs +2 -0
- package/dist/{noPayout-CDhbGn_B.cjs.map → noPayout-Bp2TYA_X.cjs.map} +1 -1
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +4 -4
- package/dist/tbv/core/primitives/index.cjs +1 -1
- package/dist/tbv/core/primitives/index.js +2 -2
- package/dist/tbv/core/primitives/psbt/__tests__/peginInput.test.d.ts +3 -3
- package/dist/tbv/core/primitives/psbt/payout.d.ts +3 -2
- package/dist/tbv/core/primitives/psbt/payout.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/peginInput.d.ts +11 -5
- package/dist/tbv/core/primitives/psbt/peginInput.d.ts.map +1 -1
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.js +1 -1
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +4 -4
- package/package.json +1 -1
- package/dist/challengeAssert-DSlCIBoT.js.map +0 -1
- package/dist/challengeAssert-DuhkzZG-.cjs +0 -2
- package/dist/challengeAssert-DuhkzZG-.cjs.map +0 -1
- package/dist/noPayout-CDhbGn_B.cjs +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"noPayout-CDhbGn_B.cjs","sources":["../src/tbv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/scripts/payout.ts","../src/tbv/core/primitives/psbt/payout.ts","../src/tbv/core/primitives/psbt/noPayout.ts"],"sourcesContent":["/**\n * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport {\n 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 * Payout Script Generator Primitive\n *\n * This module provides pure functions for generating payout scripts and taproot information\n * by wrapping the WASM implementation from @babylonlabs-io/babylon-tbv-rust-wasm.\n *\n * The payout script is used for signing payout transactions in the vault system.\n * It defines the spending conditions for the vault output, enabling the depositor\n * to authorize payouts during the peg-in flow (Step 3).\n *\n * @remarks\n * This is a low-level primitive. For most use cases, prefer using {@link buildPayoutPsbt}\n * which handles script creation internally. For high-level wallet orchestration, use\n * PayoutManager from the managers module.\n *\n * @see {@link buildPayoutPsbt} - Higher-level function that uses this internally\n *\n * @module primitives/scripts/payout\n */\n\nimport {\n createPayoutConnector,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\n\n/**\n * Parameters for creating a payout script.\n *\n * These parameters define the participants in a vault and are used to generate\n * the taproot script that controls how funds can be spent from the vault.\n */\nexport interface PayoutScriptParams {\n /**\n * Depositor's BTC public key (x-only, 64-char hex without 0x prefix).\n *\n * This is the user depositing BTC into the vault. The depositor must sign\n * payout transactions to authorize fund distribution.\n */\n depositor: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex without 0x prefix).\n *\n * The service provider managing vault operations. Also referred to as\n * \"claimer\" in the WASM layer.\n */\n vaultProvider: string;\n\n /**\n * Array of vault keeper BTC public keys (x-only, 64-char hex without 0x prefix).\n *\n * Vault keepers participate in vault operations and script spending conditions.\n */\n vaultKeepers: string[];\n\n /**\n * Array of universal challenger BTC public keys (x-only, 64-char hex without 0x prefix).\n *\n * These parties can challenge the vault under certain conditions.\n */\n universalChallengers: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Bitcoin network for script generation.\n *\n * Must match the network used for all other vault operations to ensure\n * address encoding compatibility.\n */\n network: Network;\n}\n\n/**\n * Result of creating a payout script.\n *\n * Contains all the taproot-related data needed for constructing and signing\n * payout transactions from the vault.\n */\nexport interface PayoutScriptResult {\n /**\n * The payout script hex used in taproot script path spending.\n *\n * This is the raw script bytes that define the spending conditions,\n * encoded as a hexadecimal string. Used when constructing the\n * tapLeafScript for PSBT signing.\n */\n payoutScript: string;\n\n /**\n * The taproot script hash (leaf hash) for the payout script.\n *\n * This is the tagged hash of the script used in taproot tree construction.\n * Required for computing the control block during script path spending.\n */\n taprootScriptHash: string;\n\n /**\n * The full scriptPubKey for the vault output address.\n *\n * This is the complete output script (OP_1 <32-byte-key>) that should be\n * used when creating the vault output in a peg-in transaction.\n */\n scriptPubKey: string;\n\n /**\n * The vault Bitcoin address derived from the script.\n *\n * A human-readable bech32m address (bc1p... for mainnet, tb1p... for testnet/signet)\n * that can be used to receive funds into the vault.\n */\n address: string;\n\n /**\n * Serialized control block for Taproot script path spend (hex encoded).\n *\n * Computed by the Rust WASM PeginPayoutConnector. Used directly in\n * tapLeafScript when building payout PSBTs.\n */\n payoutControlBlock: string;\n}\n\n/**\n * Create payout script and taproot information using WASM.\n *\n * This is a pure function that wraps the Rust WASM implementation.\n * The payout connector generates the necessary taproot scripts and information\n * required for signing payout transactions.\n *\n * @remarks\n * The generated script encodes spending conditions that require signatures from\n * the depositor and vault provider (or liquidators in challenge scenarios).\n * This script is used internally by {@link buildPayoutPsbt}.\n *\n * @param params - Payout script parameters defining vault participants and network\n * @returns Payout script and taproot information for PSBT construction\n *\n * @see {@link buildPayoutPsbt} - Use this for building complete payout PSBTs\n */\nexport async function createPayoutScript(\n params: PayoutScriptParams,\n): Promise<PayoutScriptResult> {\n // Call the WASM wrapper with the correct parameter structure\n const connector = await createPayoutConnector(\n {\n depositor: params.depositor,\n vaultProvider: params.vaultProvider,\n vaultKeepers: params.vaultKeepers,\n universalChallengers: params.universalChallengers,\n timelockPegin: params.timelockPegin,\n },\n params.network,\n );\n\n return {\n payoutScript: connector.payoutScript,\n taprootScriptHash: connector.taprootScriptHash,\n scriptPubKey: connector.scriptPubKey,\n address: connector.address,\n payoutControlBlock: connector.payoutControlBlock,\n };\n}\n","/**\n * Payout PSBT Builder Primitives\n *\n * This module provides pure functions for building unsigned payout PSBTs and extracting\n * Schnorr signatures from signed PSBTs. It uses WASM-generated scripts from the payout\n * connector and bitcoinjs-lib for PSBT construction.\n *\n * The Payout transaction references the Assert transaction (input 1).\n *\n * @module primitives/psbt/payout\n */\n\nimport {\n type Network,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { createPayoutScript } from \"../scripts/payout\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n isValidHex,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\n\n/**\n * Number of items in a Taproot script-path spend witness stack for a\n * single-signature script: [signature, script, controlBlock].\n *\n * The current payout script requires exactly one depositor signature. If the\n * protocol evolves to require multiple signatures in the payout script, this\n * invariant and the finalized-PSBT extraction path must be revisited because\n * the first witness item would no longer necessarily be the depositor's.\n */\nconst TAPROOT_SINGLE_SIG_WITNESS_STACK_SIZE = 3;\n\n/**\n * Parameters for building an unsigned Payout PSBT\n *\n * Payout is used in the challenge path after Assert, when the claimer proves validity.\n * Input 1 references the Assert transaction.\n */\nexport interface PayoutParams {\n /**\n * Payout transaction hex (unsigned)\n * This is the transaction that needs to be signed by the depositor\n */\n payoutTxHex: string;\n\n /**\n * Assert transaction hex\n * Payout input 1 references Assert output 0\n */\n assertTxHex: string;\n\n /**\n * Peg-in transaction hex\n * This transaction created the vault output that we're spending\n */\n peginTxHex: string;\n\n /**\n * Depositor's BTC public key (x-only, 64-char hex without 0x prefix)\n */\n depositorBtcPubkey: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex)\n */\n vaultProviderBtcPubkey: string;\n\n /**\n * Vault keeper BTC public keys (x-only, 64-char hex)\n */\n vaultKeeperBtcPubkeys: string[];\n\n /**\n * Universal challenger BTC public keys (x-only, 64-char hex)\n */\n universalChallengerBtcPubkeys: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Bitcoin network\n */\n network: Network;\n}\n\n/**\n * Result of building an unsigned payout PSBT\n */\nexport interface PayoutPsbtResult {\n /**\n * Unsigned PSBT hex ready for signing\n */\n psbtHex: string;\n}\n\n/**\n * Build unsigned Payout PSBT for depositor to sign.\n *\n * Payout is used in the **challenge path** when the claimer proves validity:\n * 1. Vault provider submits Claim transaction\n * 2. Challenge is raised during challenge period\n * 3. Claimer submits Assert transaction to prove validity\n * 4. Payout can be executed (references Assert tx)\n *\n * Payout transactions have the following structure:\n * - Input 0: from PeginTx output0 (signed by depositor)\n * - Input 1: from Assert output0 (NOT signed by depositor)\n *\n * @param params - Payout parameters\n * @returns Unsigned PSBT ready for depositor to sign\n *\n * @throws If payout transaction does not have exactly 2 inputs\n * @throws If input 0 does not reference the pegin transaction\n * @throws If input 1 does not reference the assert transaction\n * @throws If previous output is not found for either input\n */\nexport async function buildPayoutPsbt(\n params: PayoutParams,\n): Promise<PayoutPsbtResult> {\n // Normalize hex inputs (strip 0x prefix if present)\n const payoutTxHex = stripHexPrefix(params.payoutTxHex);\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const assertTxHex = stripHexPrefix(params.assertTxHex);\n\n // Get payout script from WASM\n const payoutConnector = await createPayoutScript({\n depositor: params.depositorBtcPubkey,\n vaultProvider: params.vaultProviderBtcPubkey,\n vaultKeepers: params.vaultKeeperBtcPubkeys,\n universalChallengers: params.universalChallengerBtcPubkeys,\n timelockPegin: params.timelockPegin,\n network: params.network,\n });\n\n const payoutScriptBytes = hexToUint8Array(payoutConnector.payoutScript);\n const controlBlock = hexToUint8Array(payoutConnector.payoutControlBlock);\n\n // Parse transactions\n const payoutTx = Transaction.fromHex(payoutTxHex);\n const peginTx = Transaction.fromHex(peginTxHex);\n const assertTx = Transaction.fromHex(assertTxHex);\n\n // Create PSBT\n const psbt = new Psbt();\n psbt.setVersion(payoutTx.version);\n psbt.setLocktime(payoutTx.locktime);\n\n // PayoutTx has exactly 2 inputs:\n // - Input 0: from PeginTx output0 (signed by depositor using taproot script path)\n // - Input 1: from Assert output0 (signed by claimer/challengers, not depositor)\n //\n // IMPORTANT: For Taproot SIGHASH_DEFAULT (0x00), the sighash commits to ALL inputs'\n // prevouts, not just the one being signed. Therefore, we must include BOTH inputs\n // in the PSBT so the wallet computes the correct sighash that the VP expects.\n\n // Verify payout transaction has expected structure\n if (payoutTx.ins.length !== 2) {\n throw new Error(\n `Payout transaction must have exactly 2 inputs, got ${payoutTx.ins.length}`,\n );\n }\n\n const input0 = payoutTx.ins[0];\n const input1 = payoutTx.ins[1];\n\n // Verify input 0 references the pegin transaction\n const input0Txid = uint8ArrayToHex(\n new Uint8Array(input0.hash).slice().reverse(),\n );\n const peginTxid = peginTx.getId();\n\n if (input0Txid !== peginTxid) {\n throw new Error(\n `Input 0 does not reference pegin transaction. ` +\n `Expected ${peginTxid}, got ${input0Txid}`,\n );\n }\n\n // Verify input 1 references the assert transaction\n const input1Txid = uint8ArrayToHex(\n new Uint8Array(input1.hash).slice().reverse(),\n );\n const expectedInput1Txid = assertTx.getId();\n\n if (input1Txid !== expectedInput1Txid) {\n throw new Error(\n `Input 1 does not reference assert transaction. ` +\n `Expected ${expectedInput1Txid}, got ${input1Txid}`,\n );\n }\n\n const peginPrevOut = peginTx.outs[input0.index];\n if (!peginPrevOut) {\n throw new Error(\n `Previous output not found for input 0 (txid: ${input0Txid}, index: ${input0.index})`,\n );\n }\n\n const input1PrevOut = assertTx.outs[input1.index];\n if (!input1PrevOut) {\n throw new Error(\n `Previous output not found for input 1 (txid: ${input1Txid}, index: ${input1.index})`,\n );\n }\n\n // Input 0: Depositor signs using Taproot script path spend\n // This input includes tapLeafScript for signing\n psbt.addInput({\n hash: input0.hash,\n index: input0.index,\n sequence: input0.sequence,\n witnessUtxo: {\n script: peginPrevOut.script,\n value: peginPrevOut.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(payoutScriptBytes),\n controlBlock: Buffer.from(controlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n // sighashType omitted - defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n // Input 1: From Assert transaction (NOT signed by depositor)\n // We include this with witnessUtxo so the sighash is computed correctly,\n // but we do NOT include tapLeafScript since the depositor doesn't sign it.\n psbt.addInput({\n hash: input1.hash,\n index: input1.index,\n sequence: input1.sequence,\n witnessUtxo: {\n script: input1PrevOut.script,\n value: input1PrevOut.value,\n },\n // No tapLeafScript - depositor doesn't sign this input\n });\n\n // Add outputs\n for (const output of payoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return {\n psbtHex: psbt.toHex(),\n };\n}\n\n/**\n * Validate that a payout transaction's largest output pays to the registered\n * depositor payout scriptPubKey.\n *\n * Prevents a malicious vault provider from substituting the payout destination\n * (or routing funds through a dust output to the correct address while sending\n * the actual value to an attacker-controlled script).\n *\n * @param payoutTxHex - Raw payout transaction hex\n * @param registeredPayoutScriptPubKey - On-chain registered scriptPubKey (hex, with or without 0x prefix)\n * @throws If scriptPubKey is invalid hex\n * @throws If the transaction has no outputs\n * @throws If the largest output does not pay to the registered scriptPubKey\n */\nexport function assertPayoutOutputMatchesRegistered(\n payoutTxHex: string,\n registeredPayoutScriptPubKey: string,\n): void {\n if (!isValidHex(registeredPayoutScriptPubKey)) {\n throw new Error(\"Invalid registeredPayoutScriptPubKey: not valid hex\");\n }\n\n const expectedScript = Buffer.from(\n stripHexPrefix(registeredPayoutScriptPubKey),\n \"hex\",\n );\n const payoutTx = Transaction.fromHex(stripHexPrefix(payoutTxHex));\n\n if (payoutTx.outs.length === 0) {\n throw new Error(\"Payout transaction has no outputs\");\n }\n\n const largestOutput = payoutTx.outs.reduce((max, output) =>\n output.value > max.value ? output : max,\n );\n\n if (!largestOutput.script.equals(expectedScript)) {\n throw new Error(\n \"Payout transaction does not pay to the registered depositor payout address\",\n );\n }\n}\n\n/**\n * Extract Schnorr signature from signed payout PSBT.\n *\n * This function supports two cases:\n * 1. Non-finalized PSBT: Extracts from tapScriptSig field\n * 2. Finalized PSBT: Extracts from witness data\n *\n * The signature is returned as a 64-byte hex string (128 hex characters)\n * with any sighash flag byte removed if present.\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's public key (x-only, 64-char hex)\n * @param inputIndex - Input index to extract signature from (default: 0)\n * @returns 64-byte Schnorr signature (128 hex characters, no sighash flag)\n *\n * @throws If no signature is found in the PSBT\n * @throws If the signature has an unexpected length\n */\nexport function extractPayoutSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n inputIndex = 0,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n\n if (inputIndex >= signedPsbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${signedPsbt.data.inputs.length} inputs)`,\n );\n }\n\n const input = signedPsbt.data.inputs[inputIndex];\n\n // Case 1: Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = hexToUint8Array(depositorPubkey);\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(Buffer.from(depositorPubkeyBytes))) {\n return extractSchnorrSig(sigEntry.signature, inputIndex);\n }\n }\n\n throw new Error(\n `No signature found for depositor pubkey: ${depositorPubkey} at input ${inputIndex}`,\n );\n }\n\n // Case 2: Finalized PSBT — extract from finalScriptWitness\n // Taproot single-signature script-path witness: [signature, script, controlBlock].\n // Enforce the exact stack size so that if a wallet produces an unexpected\n // finalization (e.g. a multi-signature stack, an annex, or malformed data),\n // we fail loudly instead of silently returning witnessStack[0] which may\n // not be the depositor's signature.\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n const witnessStack = parseWitnessStack(input.finalScriptWitness);\n if (witnessStack.length !== TAPROOT_SINGLE_SIG_WITNESS_STACK_SIZE) {\n throw new Error(\n `Unexpected finalized witness stack size at input ${inputIndex}: ` +\n `expected ${TAPROOT_SINGLE_SIG_WITNESS_STACK_SIZE} items (signature, script, controlBlock), ` +\n `got ${witnessStack.length}`,\n );\n }\n return extractSchnorrSig(witnessStack[0], inputIndex);\n }\n\n throw new Error(\n `No tapScriptSig or finalScriptWitness found in signed PSBT at input ${inputIndex}`,\n );\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature, stripping sighash flag if present.\n * Rejects signatures with sighash types other than SIGHASH_ALL (0x01) to prevent\n * acceptance of signatures that don't commit to all outputs (e.g. SIGHASH_NONE).\n * @internal\n */\nfunction extractSchnorrSig(sig: Uint8Array, inputIndex: number): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n } else if (sig.length === 65) {\n const sighashByte = sig[64];\n if (sighashByte !== Transaction.SIGHASH_ALL) {\n throw new Error(\n `Unexpected sighash type 0x${sighashByte.toString(16).padStart(2, \"0\")} at input ${inputIndex}. Expected SIGHASH_ALL (0x01).`,\n );\n }\n return uint8ArrayToHex(new Uint8Array(sig.subarray(0, 64)));\n }\n throw new Error(\n `Unexpected signature length at input ${inputIndex}: ${sig.length}`,\n );\n}\n\n/**\n * Parse a BIP-141 serialized witness stack into individual stack items.\n * Format: [varint item_count] [varint len, data]...\n *\n * Throws on malformed input (truncated buffer, 8-byte varints, or trailing\n * bytes) so callers never receive silently-corrupted witness items.\n * @internal\n */\nfunction parseWitnessStack(witness: Buffer): Buffer[] {\n const items: Buffer[] = [];\n let offset = 0;\n\n const requireBytes = (n: number): void => {\n if (offset + n > witness.length) {\n throw new Error(\n `Malformed witness data: need ${n} byte(s) at offset ${offset}, only ${witness.length - offset} remaining`,\n );\n }\n };\n\n const readVarInt = (): number => {\n requireBytes(1);\n const first = witness[offset++];\n if (first < 0xfd) return first;\n if (first === 0xfd) {\n requireBytes(2);\n const val = (witness[offset] | (witness[offset + 1] << 8)) >>> 0;\n offset += 2;\n return val;\n }\n if (first === 0xfe) {\n requireBytes(4);\n const val =\n (witness[offset] |\n (witness[offset + 1] << 8) |\n (witness[offset + 2] << 16) |\n (witness[offset + 3] << 24)) >>>\n 0;\n offset += 4;\n return val;\n }\n // 0xff — 8-byte varint. Not used for witness sizes in practice and JS\n // numbers cannot represent all 64-bit values exactly, so reject rather\n // than risk silent truncation.\n throw new Error(\n `Malformed witness data: 8-byte varint (0xff) not supported at offset ${offset - 1}`,\n );\n };\n\n const count = readVarInt();\n for (let i = 0; i < count; i++) {\n const len = readVarInt();\n requireBytes(len);\n items.push(Buffer.from(witness.subarray(offset, offset + len)));\n offset += len;\n }\n\n if (offset !== witness.length) {\n throw new Error(\n `Malformed witness data: ${witness.length - offset} trailing byte(s) after parsing ${count} item(s)`,\n );\n }\n\n return items;\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 type Network,\n getAssertNoPayoutScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction, payments } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n getNetwork,\n hexToUint8Array,\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a NoPayout PSBT\n */\nexport interface NoPayoutParams {\n /** NoPayout transaction hex (unsigned) from VP */\n noPayoutTxHex: string;\n /** Challenger's x-only public key (hex encoded) */\n challengerPubkey: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/**\n * Validate that a NoPayout transaction pays to the challenger via the\n * protocol-defined output structure: a single BIP-86 P2TR output derived from\n * the challenger's x-only pubkey.\n *\n * Mirrors `assertPayoutOutputMatchesRegistered` for the NoPayout path, where\n * the sink is fixed by the protocol rather than read from on-chain registration\n * (see `crates/vault/src/transactions/nopayout.rs::NoPayoutTx::new`).\n *\n * @param noPayoutTxHex - Raw NoPayout transaction hex\n * @param challengerPubkey - Challenger's x-only public key (hex)\n * @param network - Bitcoin network used to derive the P2TR scriptPubKey\n * @throws If the transaction does not have exactly one output\n * @throws If the single output's scriptPubKey does not equal the BIP-86 P2TR\n * scriptPubKey for the challenger\n */\nexport function assertNoPayoutOutputMatchesChallenger(\n noPayoutTxHex: string,\n challengerPubkey: string,\n network: Network,\n): void {\n const tx = Transaction.fromHex(stripHexPrefix(noPayoutTxHex));\n\n if (tx.outs.length !== 1) {\n throw new Error(\n `NoPayout transaction must have exactly 1 output, got ${tx.outs.length}`,\n );\n }\n\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(challengerPubkey));\n const { output: expectedScript } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!expectedScript) {\n throw new Error(\n \"Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation\",\n );\n }\n\n if (!tx.outs[0].script.equals(expectedScript)) {\n throw new Error(\n \"NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address\",\n );\n }\n}\n"],"names":["buildRefundPsbt","params","initWasm","prePeginParams","fundedPrePeginTxHex","htlcVout","refundFee","hashlock","unfundedTx","WasmPrePeginTx","fundedTx","refundTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","cleanPrePeginHex","prePeginTx","Transaction","htlcOutput","refundTx","refundInput","prePeginTxid","refundInputTxid","uint8ArrayToHex","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","hexToUint8Array","tapInternalPubkey","output","createPayoutScript","connector","createPayoutConnector","TAPROOT_SINGLE_SIG_WITNESS_STACK_SIZE","buildPayoutPsbt","payoutTxHex","stripHexPrefix","peginTxHex","assertTxHex","payoutConnector","payoutScriptBytes","controlBlock","payoutTx","peginTx","assertTx","input0","input1","input0Txid","peginTxid","input1Txid","expectedInput1Txid","peginPrevOut","input1PrevOut","assertPayoutOutputMatchesRegistered","registeredPayoutScriptPubKey","isValidHex","expectedScript","max","extractPayoutSignature","signedPsbtHex","depositorPubkey","inputIndex","signedPsbt","input","depositorPubkeyBytes","sigEntry","extractSchnorrSig","witnessStack","parseWitnessStack","sig","sighashByte","witness","items","offset","requireBytes","n","readVarInt","first","val","count","i","len","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","prevout","inputData","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","payments","getNetwork"],"mappings":"yJAkEA,eAAsBA,EACpBC,EACgC,CAChC,MAAMC,WAAA,EAEN,KAAM,CAAE,eAAAC,EAAgB,oBAAAC,EAAqB,SAAAC,EAAU,UAAAC,EAAW,SAAAC,GAChEN,EAEIO,EAAa,IAAIC,EAAAA,eACrBN,EAAe,gBACfA,EAAe,oBACfA,EAAe,mBACfA,EAAe,2BACf,CAAC,GAAGA,EAAe,SAAS,EAC5B,IAAI,eAAeA,EAAe,YAAY,EAC9CA,EAAe,eACfA,EAAe,QACfA,EAAe,oBACfA,EAAe,cACfA,EAAe,YACfA,EAAe,OAAA,EAGjB,IAAIO,EAAkC,KACtC,GAAI,CACFA,EAAWF,EAAW,sBAAsBJ,CAAmB,EAE/D,MAAMO,EAAcD,EAAS,cAAcJ,EAAWD,CAAQ,EAExDO,EAAgB,MAAMC,+BAA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IAAI,MACR,kFAAA,CAGN"}
|
|
1
|
+
{"version":3,"file":"noPayout-Bp2TYA_X.cjs","sources":["../src/tbv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/scripts/payout.ts","../src/tbv/core/primitives/psbt/payout.ts","../src/tbv/core/primitives/psbt/noPayout.ts"],"sourcesContent":["/**\n * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport {\n 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 * Payout Script Generator Primitive\n *\n * This module provides pure functions for generating payout scripts and taproot information\n * by wrapping the WASM implementation from @babylonlabs-io/babylon-tbv-rust-wasm.\n *\n * The payout script is used for signing payout transactions in the vault system.\n * It defines the spending conditions for the vault output, enabling the depositor\n * to authorize payouts during the peg-in flow (Step 3).\n *\n * @remarks\n * This is a low-level primitive. For most use cases, prefer using {@link buildPayoutPsbt}\n * which handles script creation internally. For high-level wallet orchestration, use\n * PayoutManager from the managers module.\n *\n * @see {@link buildPayoutPsbt} - Higher-level function that uses this internally\n *\n * @module primitives/scripts/payout\n */\n\nimport {\n createPayoutConnector,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\n\n/**\n * Parameters for creating a payout script.\n *\n * These parameters define the participants in a vault and are used to generate\n * the taproot script that controls how funds can be spent from the vault.\n */\nexport interface PayoutScriptParams {\n /**\n * Depositor's BTC public key (x-only, 64-char hex without 0x prefix).\n *\n * This is the user depositing BTC into the vault. The depositor must sign\n * payout transactions to authorize fund distribution.\n */\n depositor: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex without 0x prefix).\n *\n * The service provider managing vault operations. Also referred to as\n * \"claimer\" in the WASM layer.\n */\n vaultProvider: string;\n\n /**\n * Array of vault keeper BTC public keys (x-only, 64-char hex without 0x prefix).\n *\n * Vault keepers participate in vault operations and script spending conditions.\n */\n vaultKeepers: string[];\n\n /**\n * Array of universal challenger BTC public keys (x-only, 64-char hex without 0x prefix).\n *\n * These parties can challenge the vault under certain conditions.\n */\n universalChallengers: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Bitcoin network for script generation.\n *\n * Must match the network used for all other vault operations to ensure\n * address encoding compatibility.\n */\n network: Network;\n}\n\n/**\n * Result of creating a payout script.\n *\n * Contains all the taproot-related data needed for constructing and signing\n * payout transactions from the vault.\n */\nexport interface PayoutScriptResult {\n /**\n * The payout script hex used in taproot script path spending.\n *\n * This is the raw script bytes that define the spending conditions,\n * encoded as a hexadecimal string. Used when constructing the\n * tapLeafScript for PSBT signing.\n */\n payoutScript: string;\n\n /**\n * The taproot script hash (leaf hash) for the payout script.\n *\n * This is the tagged hash of the script used in taproot tree construction.\n * Required for computing the control block during script path spending.\n */\n taprootScriptHash: string;\n\n /**\n * The full scriptPubKey for the vault output address.\n *\n * This is the complete output script (OP_1 <32-byte-key>) that should be\n * used when creating the vault output in a peg-in transaction.\n */\n scriptPubKey: string;\n\n /**\n * The vault Bitcoin address derived from the script.\n *\n * A human-readable bech32m address (bc1p... for mainnet, tb1p... for testnet/signet)\n * that can be used to receive funds into the vault.\n */\n address: string;\n\n /**\n * Serialized control block for Taproot script path spend (hex encoded).\n *\n * Computed by the Rust WASM PeginPayoutConnector. Used directly in\n * tapLeafScript when building payout PSBTs.\n */\n payoutControlBlock: string;\n}\n\n/**\n * Create payout script and taproot information using WASM.\n *\n * This is a pure function that wraps the Rust WASM implementation.\n * The payout connector generates the necessary taproot scripts and information\n * required for signing payout transactions.\n *\n * @remarks\n * The generated script encodes spending conditions that require signatures from\n * the depositor and vault provider (or liquidators in challenge scenarios).\n * This script is used internally by {@link buildPayoutPsbt}.\n *\n * @param params - Payout script parameters defining vault participants and network\n * @returns Payout script and taproot information for PSBT construction\n *\n * @see {@link buildPayoutPsbt} - Use this for building complete payout PSBTs\n */\nexport async function createPayoutScript(\n params: PayoutScriptParams,\n): Promise<PayoutScriptResult> {\n // Call the WASM wrapper with the correct parameter structure\n const connector = await createPayoutConnector(\n {\n depositor: params.depositor,\n vaultProvider: params.vaultProvider,\n vaultKeepers: params.vaultKeepers,\n universalChallengers: params.universalChallengers,\n timelockPegin: params.timelockPegin,\n },\n params.network,\n );\n\n return {\n payoutScript: connector.payoutScript,\n taprootScriptHash: connector.taprootScriptHash,\n scriptPubKey: connector.scriptPubKey,\n address: connector.address,\n payoutControlBlock: connector.payoutControlBlock,\n };\n}\n","/**\n * Payout PSBT Builder Primitives\n *\n * This module provides pure functions for building unsigned payout PSBTs and extracting\n * Schnorr signatures from signed PSBTs. It uses WASM-generated scripts from the payout\n * connector and bitcoinjs-lib for PSBT construction.\n *\n * The Payout transaction references the Assert transaction (input 1).\n *\n * @module primitives/psbt/payout\n */\n\nimport {\n type Network,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { createPayoutScript } from \"../scripts/payout\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n isValidHex,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\n\n/**\n * Number of items in a Taproot script-path spend witness stack for a\n * single-signature script: [signature, script, controlBlock].\n *\n * The current payout script requires exactly one depositor signature. If the\n * protocol evolves to require multiple signatures in the payout script, this\n * invariant and the finalized-PSBT extraction path must be revisited because\n * the first witness item would no longer necessarily be the depositor's.\n */\nconst TAPROOT_SINGLE_SIG_WITNESS_STACK_SIZE = 3;\n\n/**\n * Parameters for building an unsigned Payout PSBT\n *\n * Payout is used in the challenge path after Assert, when the claimer proves validity.\n * Input 1 references the Assert transaction.\n */\nexport interface PayoutParams {\n /**\n * Payout transaction hex (unsigned)\n * This is the transaction that needs to be signed by the depositor\n */\n payoutTxHex: string;\n\n /**\n * Assert transaction hex\n * Payout input 1 references Assert output 0\n */\n assertTxHex: string;\n\n /**\n * Peg-in transaction hex\n * This transaction created the vault output that we're spending\n */\n peginTxHex: string;\n\n /**\n * Depositor's BTC public key (x-only, 64-char hex without 0x prefix)\n */\n depositorBtcPubkey: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex)\n */\n vaultProviderBtcPubkey: string;\n\n /**\n * Vault keeper BTC public keys (x-only, 64-char hex)\n */\n vaultKeeperBtcPubkeys: string[];\n\n /**\n * Universal challenger BTC public keys (x-only, 64-char hex)\n */\n universalChallengerBtcPubkeys: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Bitcoin network\n */\n network: Network;\n}\n\n/**\n * Result of building an unsigned payout PSBT\n */\nexport interface PayoutPsbtResult {\n /**\n * Unsigned PSBT hex ready for signing\n */\n psbtHex: string;\n}\n\n/**\n * Build unsigned Payout PSBT for depositor to sign.\n *\n * Payout is used in the **challenge path** when the claimer proves validity:\n * 1. Vault provider submits Claim transaction\n * 2. Challenge is raised during challenge period\n * 3. Claimer submits Assert transaction to prove validity\n * 4. Payout can be executed (references Assert tx)\n *\n * Payout transactions have the following structure:\n * - Input 0: from PeginTx output0 (signed by depositor)\n * - Input 1: from Assert output0 (NOT signed by depositor)\n *\n * @param params - Payout parameters\n * @returns Unsigned PSBT ready for depositor to sign\n *\n * @throws If payout transaction does not have exactly 2 inputs\n * @throws If input 0 does not reference the pegin transaction\n * @throws If input 1 does not reference the assert transaction\n * @throws If previous output is not found for either input\n */\nexport async function buildPayoutPsbt(\n params: PayoutParams,\n): Promise<PayoutPsbtResult> {\n // Normalize hex inputs (strip 0x prefix if present)\n const payoutTxHex = stripHexPrefix(params.payoutTxHex);\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const assertTxHex = stripHexPrefix(params.assertTxHex);\n\n // Get payout script from WASM\n const payoutConnector = await createPayoutScript({\n depositor: params.depositorBtcPubkey,\n vaultProvider: params.vaultProviderBtcPubkey,\n vaultKeepers: params.vaultKeeperBtcPubkeys,\n universalChallengers: params.universalChallengerBtcPubkeys,\n timelockPegin: params.timelockPegin,\n network: params.network,\n });\n\n const payoutScriptBytes = hexToUint8Array(payoutConnector.payoutScript);\n const controlBlock = hexToUint8Array(payoutConnector.payoutControlBlock);\n\n // Parse transactions\n const payoutTx = Transaction.fromHex(payoutTxHex);\n const peginTx = Transaction.fromHex(peginTxHex);\n const assertTx = Transaction.fromHex(assertTxHex);\n\n // Create PSBT\n const psbt = new Psbt();\n psbt.setVersion(payoutTx.version);\n psbt.setLocktime(payoutTx.locktime);\n\n // PayoutTx has exactly 2 inputs:\n // - Input 0: from PeginTx output0 (signed by depositor using taproot script path)\n // - Input 1: from Assert output0 (signed by claimer/challengers, not depositor)\n //\n // IMPORTANT: For Taproot SIGHASH_DEFAULT (0x00), the sighash commits to ALL inputs'\n // prevouts, not just the one being signed. Therefore, we must include BOTH inputs\n // in the PSBT so the wallet computes the correct sighash that the VP expects.\n\n // Verify payout transaction has expected structure\n if (payoutTx.ins.length !== 2) {\n throw new Error(\n `Payout transaction must have exactly 2 inputs, got ${payoutTx.ins.length}`,\n );\n }\n\n const input0 = payoutTx.ins[0];\n const input1 = payoutTx.ins[1];\n\n // Verify input 0 references the pegin transaction\n const input0Txid = uint8ArrayToHex(\n new Uint8Array(input0.hash).slice().reverse(),\n );\n const peginTxid = peginTx.getId();\n\n if (input0Txid !== peginTxid) {\n throw new Error(\n `Input 0 does not reference pegin transaction. ` +\n `Expected ${peginTxid}, got ${input0Txid}`,\n );\n }\n\n // Verify input 1 references the assert transaction\n const input1Txid = uint8ArrayToHex(\n new Uint8Array(input1.hash).slice().reverse(),\n );\n const expectedInput1Txid = assertTx.getId();\n\n if (input1Txid !== expectedInput1Txid) {\n throw new Error(\n `Input 1 does not reference assert transaction. ` +\n `Expected ${expectedInput1Txid}, got ${input1Txid}`,\n );\n }\n\n const peginPrevOut = peginTx.outs[input0.index];\n if (!peginPrevOut) {\n throw new Error(\n `Previous output not found for input 0 (txid: ${input0Txid}, index: ${input0.index})`,\n );\n }\n\n const input1PrevOut = assertTx.outs[input1.index];\n if (!input1PrevOut) {\n throw new Error(\n `Previous output not found for input 1 (txid: ${input1Txid}, index: ${input1.index})`,\n );\n }\n\n // Input 0: Depositor signs using Taproot script path spend\n // This input includes tapLeafScript for signing\n psbt.addInput({\n hash: input0.hash,\n index: input0.index,\n sequence: input0.sequence,\n witnessUtxo: {\n script: peginPrevOut.script,\n value: peginPrevOut.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(payoutScriptBytes),\n controlBlock: Buffer.from(controlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n // sighashType omitted - defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n // Input 1: From Assert transaction (NOT signed by depositor)\n // We include this with witnessUtxo so the sighash is computed correctly,\n // but we do NOT include tapLeafScript since the depositor doesn't sign it.\n psbt.addInput({\n hash: input1.hash,\n index: input1.index,\n sequence: input1.sequence,\n witnessUtxo: {\n script: input1PrevOut.script,\n value: input1PrevOut.value,\n },\n // No tapLeafScript - depositor doesn't sign this input\n });\n\n // Add outputs\n for (const output of payoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return {\n psbtHex: psbt.toHex(),\n };\n}\n\n/**\n * Validate that a payout transaction's largest output pays to the registered\n * depositor payout scriptPubKey.\n *\n * Prevents a malicious vault provider from substituting the payout destination\n * (or routing funds through a dust output to the correct address while sending\n * the actual value to an attacker-controlled script).\n *\n * @param payoutTxHex - Raw payout transaction hex\n * @param registeredPayoutScriptPubKey - On-chain registered scriptPubKey (hex, with or without 0x prefix)\n * @throws If scriptPubKey is invalid hex\n * @throws If the transaction has no outputs\n * @throws If the largest output does not pay to the registered scriptPubKey\n */\nexport function assertPayoutOutputMatchesRegistered(\n payoutTxHex: string,\n registeredPayoutScriptPubKey: string,\n): void {\n if (!isValidHex(registeredPayoutScriptPubKey)) {\n throw new Error(\"Invalid registeredPayoutScriptPubKey: not valid hex\");\n }\n\n const expectedScript = Buffer.from(\n stripHexPrefix(registeredPayoutScriptPubKey),\n \"hex\",\n );\n const payoutTx = Transaction.fromHex(stripHexPrefix(payoutTxHex));\n\n if (payoutTx.outs.length === 0) {\n throw new Error(\"Payout transaction has no outputs\");\n }\n\n const largestOutput = payoutTx.outs.reduce((max, output) =>\n output.value > max.value ? output : max,\n );\n\n if (!largestOutput.script.equals(expectedScript)) {\n throw new Error(\n \"Payout transaction does not pay to the registered depositor payout address\",\n );\n }\n}\n\n/**\n * Extract Schnorr signature from signed payout PSBT.\n *\n * This function supports two cases:\n * 1. Non-finalized PSBT: Extracts from tapScriptSig field\n * 2. Finalized PSBT: Extracts from witness data\n *\n * The signature is returned as a 64-byte hex string (128 hex characters).\n * Payout signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte.\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's public key (x-only, 64-char hex)\n * @param inputIndex - Input index to extract signature from (default: 0)\n * @returns 64-byte Schnorr signature (128 hex characters, no sighash flag)\n *\n * @throws If no signature is found in the PSBT\n * @throws If the signature has an unexpected length\n */\nexport function extractPayoutSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n inputIndex = 0,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n\n if (inputIndex >= signedPsbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${signedPsbt.data.inputs.length} inputs)`,\n );\n }\n\n const input = signedPsbt.data.inputs[inputIndex];\n\n // Case 1: Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = hexToUint8Array(depositorPubkey);\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(Buffer.from(depositorPubkeyBytes))) {\n return extractSchnorrSig(sigEntry.signature, inputIndex);\n }\n }\n\n throw new Error(\n `No signature found for depositor pubkey: ${depositorPubkey} at input ${inputIndex}`,\n );\n }\n\n // Case 2: Finalized PSBT — extract from finalScriptWitness\n // Taproot single-signature script-path witness: [signature, script, controlBlock].\n // Enforce the exact stack size so that if a wallet produces an unexpected\n // finalization (e.g. a multi-signature stack, an annex, or malformed data),\n // we fail loudly instead of silently returning witnessStack[0] which may\n // not be the depositor's signature.\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n const witnessStack = parseWitnessStack(input.finalScriptWitness);\n if (witnessStack.length !== TAPROOT_SINGLE_SIG_WITNESS_STACK_SIZE) {\n throw new Error(\n `Unexpected finalized witness stack size at input ${inputIndex}: ` +\n `expected ${TAPROOT_SINGLE_SIG_WITNESS_STACK_SIZE} items (signature, script, controlBlock), ` +\n `got ${witnessStack.length}`,\n );\n }\n return extractSchnorrSig(witnessStack[0], inputIndex);\n }\n\n throw new Error(\n `No tapScriptSig or finalScriptWitness found in signed PSBT at input ${inputIndex}`,\n );\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature.\n * Rejects 65-byte signatures because the appended sighash byte changes the\n * Taproot message being signed; stripping it would produce an unverifiable\n * SIGHASH_DEFAULT signature.\n * @internal\n */\nfunction extractSchnorrSig(sig: Uint8Array, inputIndex: number): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n }\n if (sig.length === 65) {\n throw new Error(\n `Unexpected sighash byte 0x${sig[64].toString(16).padStart(2, \"0\")} at input ${inputIndex}. ` +\n \"Expected implicit SIGHASH_DEFAULT as a 64-byte signature.\",\n );\n }\n throw new Error(\n `Unexpected signature length at input ${inputIndex}: ${sig.length}`,\n );\n}\n\n/**\n * Parse a BIP-141 serialized witness stack into individual stack items.\n * Format: [varint item_count] [varint len, data]...\n *\n * Throws on malformed input (truncated buffer, 8-byte varints, or trailing\n * bytes) so callers never receive silently-corrupted witness items.\n * @internal\n */\nfunction parseWitnessStack(witness: Buffer): Buffer[] {\n const items: Buffer[] = [];\n let offset = 0;\n\n const requireBytes = (n: number): void => {\n if (offset + n > witness.length) {\n throw new Error(\n `Malformed witness data: need ${n} byte(s) at offset ${offset}, only ${witness.length - offset} remaining`,\n );\n }\n };\n\n const readVarInt = (): number => {\n requireBytes(1);\n const first = witness[offset++];\n if (first < 0xfd) return first;\n if (first === 0xfd) {\n requireBytes(2);\n const val = (witness[offset] | (witness[offset + 1] << 8)) >>> 0;\n offset += 2;\n return val;\n }\n if (first === 0xfe) {\n requireBytes(4);\n const val =\n (witness[offset] |\n (witness[offset + 1] << 8) |\n (witness[offset + 2] << 16) |\n (witness[offset + 3] << 24)) >>>\n 0;\n offset += 4;\n return val;\n }\n // 0xff — 8-byte varint. Not used for witness sizes in practice and JS\n // numbers cannot represent all 64-bit values exactly, so reject rather\n // than risk silent truncation.\n throw new Error(\n `Malformed witness data: 8-byte varint (0xff) not supported at offset ${offset - 1}`,\n );\n };\n\n const count = readVarInt();\n for (let i = 0; i < count; i++) {\n const len = readVarInt();\n requireBytes(len);\n items.push(Buffer.from(witness.subarray(offset, offset + len)));\n offset += len;\n }\n\n if (offset !== witness.length) {\n throw new Error(\n `Malformed witness data: ${witness.length - offset} trailing byte(s) after parsing ${count} item(s)`,\n );\n }\n\n return items;\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 type Network,\n getAssertNoPayoutScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction, payments } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n getNetwork,\n hexToUint8Array,\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a NoPayout PSBT\n */\nexport interface NoPayoutParams {\n /** NoPayout transaction hex (unsigned) from VP */\n noPayoutTxHex: string;\n /** Challenger's x-only public key (hex encoded) */\n challengerPubkey: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/**\n * Validate that a NoPayout transaction pays to the challenger via the\n * protocol-defined output structure: a single BIP-86 P2TR output derived from\n * the challenger's x-only pubkey.\n *\n * Mirrors `assertPayoutOutputMatchesRegistered` for the NoPayout path, where\n * the sink is fixed by the protocol rather than read from on-chain registration\n * (see `crates/vault/src/transactions/nopayout.rs::NoPayoutTx::new`).\n *\n * @param noPayoutTxHex - Raw NoPayout transaction hex\n * @param challengerPubkey - Challenger's x-only public key (hex)\n * @param network - Bitcoin network used to derive the P2TR scriptPubKey\n * @throws If the transaction does not have exactly one output\n * @throws If the single output's scriptPubKey does not equal the BIP-86 P2TR\n * scriptPubKey for the challenger\n */\nexport function assertNoPayoutOutputMatchesChallenger(\n noPayoutTxHex: string,\n challengerPubkey: string,\n network: Network,\n): void {\n const tx = Transaction.fromHex(stripHexPrefix(noPayoutTxHex));\n\n if (tx.outs.length !== 1) {\n throw new Error(\n `NoPayout transaction must have exactly 1 output, got ${tx.outs.length}`,\n );\n }\n\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(challengerPubkey));\n const { output: expectedScript } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!expectedScript) {\n throw new Error(\n \"Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation\",\n );\n }\n\n if (!tx.outs[0].script.equals(expectedScript)) {\n throw new Error(\n \"NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address\",\n );\n }\n}\n"],"names":["buildRefundPsbt","params","initWasm","prePeginParams","fundedPrePeginTxHex","htlcVout","refundFee","hashlock","unfundedTx","WasmPrePeginTx","fundedTx","refundTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","cleanPrePeginHex","prePeginTx","Transaction","htlcOutput","refundTx","refundInput","prePeginTxid","refundInputTxid","uint8ArrayToHex","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","hexToUint8Array","tapInternalPubkey","output","createPayoutScript","connector","createPayoutConnector","TAPROOT_SINGLE_SIG_WITNESS_STACK_SIZE","buildPayoutPsbt","payoutTxHex","stripHexPrefix","peginTxHex","assertTxHex","payoutConnector","payoutScriptBytes","controlBlock","payoutTx","peginTx","assertTx","input0","input1","input0Txid","peginTxid","input1Txid","expectedInput1Txid","peginPrevOut","input1PrevOut","assertPayoutOutputMatchesRegistered","registeredPayoutScriptPubKey","isValidHex","expectedScript","max","extractPayoutSignature","signedPsbtHex","depositorPubkey","inputIndex","signedPsbt","input","depositorPubkeyBytes","sigEntry","extractSchnorrSig","witnessStack","parseWitnessStack","sig","witness","items","offset","requireBytes","n","readVarInt","first","val","count","i","len","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","prevout","inputData","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","payments","getNetwork"],"mappings":"yJAkEA,eAAsBA,EACpBC,EACgC,CAChC,MAAMC,WAAA,EAEN,KAAM,CAAE,eAAAC,EAAgB,oBAAAC,EAAqB,SAAAC,EAAU,UAAAC,EAAW,SAAAC,GAChEN,EAEIO,EAAa,IAAIC,EAAAA,eACrBN,EAAe,gBACfA,EAAe,oBACfA,EAAe,mBACfA,EAAe,2BACf,CAAC,GAAGA,EAAe,SAAS,EAC5B,IAAI,eAAeA,EAAe,YAAY,EAC9CA,EAAe,eACfA,EAAe,QACfA,EAAe,oBACfA,EAAe,cACfA,EAAe,YACfA,EAAe,OAAA,EAGjB,IAAIO,EAAkC,KACtC,GAAI,CACFA,EAAWF,EAAW,sBAAsBJ,CAAmB,EAE/D,MAAMO,EAAcD,EAAS,cAAcJ,EAAWD,CAAQ,EAExDO,EAAgB,MAAMC,+BAA6B,CACvD,gBAAiBV,EAAe,gBAChC,oBAAqBA,EAAe,oBACpC,mBAAoBA,EAAe,mBACnC,2BAA4BA,EAAe,2BAC3C,SAAAI,EACA,eAAgBJ,EAAe,eAC/B,QAASA,EAAe,OAAA,CACzB,EAEKW,EAAmBV,EAAoB,WAAW,IAAI,EACxDA,EAAoB,MAAM,CAAC,EAC3BA,EACEW,EAAaC,EAAAA,YAAY,QAAQF,CAAgB,EAEjDG,EAAaF,EAAW,KAAKV,CAAQ,EAC3C,GAAI,CAACY,EACH,MAAM,IAAI,MACR,uBAAuBZ,CAAQ,6CAClBU,EAAW,KAAK,MAAM,WAAA,EAIvC,MAAMG,EAAWF,EAAAA,YAAY,QAAQL,CAAW,EAEhD,GAAIO,EAAS,IAAI,SAAW,EAC1B,MAAM,IAAI,MACR,qDAA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AAON,EAAK,MAAA,CACd,CAkBO,SAASoE,EACdT,EACAU,EACAC,EACM,CACN,MAAMC,EAAK9E,EAAAA,YAAY,QAAQoB,EAAAA,eAAe8C,CAAa,CAAC,EAE5D,GAAIY,EAAG,KAAK,SAAW,EACrB,MAAM,IAAI,MACR,wDAAwDA,EAAG,KAAK,MAAM,EAAA,EAI1E,MAAMC,EAAQpE,EAAAA,gBAAgBqE,EAAAA,wBAAwBJ,CAAgB,CAAC,EACjE,CAAE,OAAQpC,GAAmByC,EAAAA,SAAS,KAAK,CAC/C,eAAgBvE,EAAAA,OAAO,KAAKqE,CAAK,EACjC,QAASG,EAAAA,WAAWL,CAAO,CAAA,CAC5B,EACD,GAAI,CAACrC,EACH,MAAM,IAAI,MACR,qFAAA,EAIJ,GAAI,CAACsC,EAAG,KAAK,CAAC,EAAE,OAAO,OAAOtC,CAAc,EAC1C,MAAM,IAAI,MACR,kFAAA,CAGN"}
|
package/dist/tbv/core/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("../../challengeAssert-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("../../challengeAssert-06GLZtV8.cjs"),P=require("@babylonlabs-io/babylon-tbv-rust-wasm"),u=require("../../noPayout-Bp2TYA_X.cjs"),i=require("../../bitcoin-EYBKDtEW.cjs"),l=require("../../signing-DHSXjhLM.cjs"),d=require("../../validation-u8W7Lp2x.cjs"),t=require("../../buildAndBroadcastRefund-BXjYAqdb.cjs"),a=require("../../fundPeginTransaction-DaWoYCgO.cjs"),o=require("../../psbtInputFields-BLi7Ta-T.cjs"),r=require("../../PeginManager-D2pBM0E-.cjs"),e=require("../../vault-registry-reader-DdUgC5IF.cjs"),s=require("../../types-C2IUB0Jd.cjs");exports.buildChallengeAssertPsbt=n.buildChallengeAssertPsbt;exports.buildDepositorPayoutPsbt=n.buildDepositorPayoutPsbt;exports.buildPeginInputPsbt=n.buildPeginInputPsbt;exports.buildPeginTxFromFundedPrePegin=n.buildPeginTxFromFundedPrePegin;exports.buildPrePeginPsbt=n.buildPrePeginPsbt;exports.computeNumLocalChallengers=n.computeNumLocalChallengers;exports.extractPeginInputSignature=n.extractPeginInputSignature;exports.finalizePeginInputPsbt=n.finalizePeginInputPsbt;Object.defineProperty(exports,"computeMinClaimValue",{enumerable:!0,get:()=>P.computeMinClaimValue});Object.defineProperty(exports,"deriveVaultId",{enumerable:!0,get:()=>P.deriveVaultId});exports.assertPayoutOutputMatchesRegistered=u.assertPayoutOutputMatchesRegistered;exports.buildNoPayoutPsbt=u.buildNoPayoutPsbt;exports.buildPayoutPsbt=u.buildPayoutPsbt;exports.buildRefundPsbt=u.buildRefundPsbt;exports.createPayoutScript=u.createPayoutScript;exports.extractPayoutSignature=u.extractPayoutSignature;exports.deriveNativeSegwitAddress=i.deriveNativeSegwitAddress;exports.deriveTaprootAddress=i.deriveTaprootAddress;exports.ensureHexPrefix=i.ensureHexPrefix;exports.formatSatoshisToBtc=i.formatSatoshisToBtc;exports.getNetwork=i.getNetwork;exports.hexToUint8Array=i.hexToUint8Array;exports.isAddressFromPublicKey=i.isAddressFromPublicKey;exports.isValidHex=i.isValidHex;exports.processPublicKeyToXOnly=i.processPublicKeyToXOnly;exports.stripHexPrefix=i.stripHexPrefix;exports.toXOnly=i.toXOnly;exports.uint8ArrayToHex=i.uint8ArrayToHex;exports.validateWalletPubkey=i.validateWalletPubkey;exports.ContractStatus=l.ContractStatus;exports.PeginAction=l.PeginAction;exports.canPerformAction=l.canPerformAction;exports.createTaprootScriptPathSignOptions=l.createTaprootScriptPathSignOptions;exports.getPeginProtocolState=l.getPeginProtocolState;exports.BITCOIN_ADDRESS_RE=d.BITCOIN_ADDRESS_RE;exports.HEX_RE=d.HEX_RE;exports.KNOWN_SCRIPT_PREFIXES=d.KNOWN_SCRIPT_PREFIXES;exports.MAX_REASONABLE_FEE_SATS=d.MAX_REASONABLE_FEE_SATS;exports.TXID_RE=d.TXID_RE;exports.BIP68NotMatureError=t.BIP68NotMatureError;exports.ClaimerPegoutStatusValue=t.ClaimerPegoutStatusValue;exports.PayoutManager=t.PayoutManager;exports.REFUND_VSIZE=t.REFUND_VSIZE;exports.activateVault=t.activateVault;exports.buildAndBroadcastRefund=t.buildAndBroadcastRefund;exports.computeHashlock=t.computeHashlock;exports.estimateRefundFeeSats=t.estimateRefundFeeSats;exports.isDepositAmountValid=t.isDepositAmountValid;exports.isPegoutTerminalStatus=t.isPegoutTerminalStatus;exports.isRecognizedPegoutStatus=t.isRecognizedPegoutStatus;exports.runDepositorPresignFlow=t.runDepositorPresignFlow;exports.signDepositorGraph=t.signDepositorGraph;exports.submitWotsPublicKey=t.submitWotsPublicKey;exports.validateDepositAmount=t.validateDepositAmount;exports.validateMultiVaultDepositInputs=t.validateMultiVaultDepositInputs;exports.validateProviderSelection=t.validateProviderSelection;exports.validateRemainingCapacity=t.validateRemainingCapacity;exports.validateSecretAgainstHashlock=t.validateSecretAgainstHashlock;exports.validateVaultAmounts=t.validateVaultAmounts;exports.validateVaultProviderPubkey=t.validateVaultProviderPubkey;exports.waitForPeginStatus=t.waitForPeginStatus;exports.BTC_DUST_SAT=a.BTC_DUST_SAT;exports.DUST_THRESHOLD=a.DUST_THRESHOLD;exports.FEE_SAFETY_MARGIN=a.FEE_SAFETY_MARGIN;exports.LOW_RATE_ESTIMATION_ACCURACY_BUFFER=a.LOW_RATE_ESTIMATION_ACCURACY_BUFFER;exports.MAX_NON_LEGACY_OUTPUT_SIZE=a.MAX_NON_LEGACY_OUTPUT_SIZE;exports.P2TR_INPUT_SIZE=a.P2TR_INPUT_SIZE;exports.PEGIN_AUTH_ANCHOR_OUTPUTS=a.PEGIN_AUTH_ANCHOR_OUTPUTS;exports.PEGIN_FIXED_OUTPUTS=a.PEGIN_FIXED_OUTPUTS;exports.SPLIT_TX_FEE_SAFETY_MULTIPLIER=a.SPLIT_TX_FEE_SAFETY_MULTIPLIER;exports.TX_BUFFER_SIZE_OVERHEAD=a.TX_BUFFER_SIZE_OVERHEAD;exports.WALLET_RELAY_FEE_RATE_THRESHOLD=a.WALLET_RELAY_FEE_RATE_THRESHOLD;exports.fundPeginTransaction=a.fundPeginTransaction;exports.parseUnfundedWasmTransaction=a.parseUnfundedWasmTransaction;exports.peginOutputCount=a.peginOutputCount;exports.rateBasedTxBufferFee=a.rateBasedTxBufferFee;exports.BitcoinScriptType=o.BitcoinScriptType;exports.UtxoNotAvailableError=o.UtxoNotAvailableError;exports.assertUtxosAvailable=o.assertUtxosAvailable;exports.calculateBtcTxHash=o.calculateBtcTxHash;exports.collectReservedUtxoRefs=o.collectReservedUtxoRefs;exports.extractInputsFromTransaction=o.extractInputsFromTransaction;exports.getDustThreshold=o.getDustThreshold;exports.getPsbtInputFields=o.getPsbtInputFields;exports.getScriptType=o.getScriptType;exports.selectUtxosForDeposit=o.selectUtxosForDeposit;exports.selectUtxosForPegin=o.selectUtxosForPegin;exports.shouldAddChangeOutput=o.shouldAddChangeOutput;exports.validateUtxosAvailable=o.validateUtxosAvailable;exports.CONTRACT_ERRORS=r.CONTRACT_ERRORS;exports.PeginManager=r.PeginManager;exports.VAULT_APP_NAME=r.VAULT_APP_NAME;exports.buildFundingOutpointsCommitment=r.buildFundingOutpointsCommitment;exports.buildVaultContext=r.buildVaultContext;exports.computeWotsBlockPublicKeysHash=r.computeWotsBlockPublicKeysHash;exports.deriveVaultRoot=r.deriveVaultRoot;exports.deriveWotsBlocksFromSeed=r.deriveWotsBlocksFromSeed;exports.expandAuthAnchor=r.expandAuthAnchor;exports.expandHashlockSecret=r.expandHashlockSecret;exports.expandWotsSeed=r.expandWotsSeed;exports.extractErrorData=r.extractErrorData;exports.getContractErrorMessage=r.getContractErrorMessage;exports.handleContractError=r.handleContractError;exports.isKnownContractError=r.isKnownContractError;exports.isWotsMismatchError=r.isWotsMismatchError;exports.parseFundingOutpointsFromTx=r.parseFundingOutpointsFromTx;exports.ApplicationRegistryABI=e.ApplicationRegistryABI;exports.MEMPOOL_API_URLS=e.MEMPOOL_API_URLS;exports.ProtocolParamsABI=e.ProtocolParamsABI;exports.ServerIdentityError=e.ServerIdentityError;exports.VaultProviderRpcClient=e.VaultProviderRpcClient;exports.ViemProtocolParamsReader=e.ViemProtocolParamsReader;exports.ViemUniversalChallengerReader=e.ViemUniversalChallengerReader;exports.ViemVaultKeeperReader=e.ViemVaultKeeperReader;exports.ViemVaultRegistryReader=e.ViemVaultRegistryReader;exports.VpResponseValidationError=e.VpResponseValidationError;exports.VpTokenRegistry=e.VpTokenRegistry;exports.createAuthenticatedVpClient=e.createAuthenticatedVpClient;exports.getAddressTxs=e.getAddressTxs;exports.getAddressUtxos=e.getAddressUtxos;exports.getMempoolApiUrl=e.getMempoolApiUrl;exports.getNetworkFees=e.getNetworkFees;exports.getTxHex=e.getTxHex;exports.getTxInfo=e.getTxInfo;exports.getUtxoInfo=e.getUtxoInfo;exports.primeVpTokenRegistry=e.primeVpTokenRegistry;exports.pushTx=e.pushTx;exports.resolveProtocolAddresses=e.resolveProtocolAddresses;exports.validateRequestDepositorClaimerArtifactsResponse=e.validateRequestDepositorClaimerArtifactsResponse;exports.verifyServerIdentity=e.verifyServerIdentity;exports.vpTokenRegistry=e.vpTokenRegistry;exports.BTCVaultRegistryABI=s.BTCVaultRegistryABI;exports.DaemonStatus=s.DaemonStatus;exports.JSON_RPC_ERROR_CODES=s.JSON_RPC_ERROR_CODES;exports.JsonRpcClient=s.JsonRpcClient;exports.JsonRpcError=s.JsonRpcError;exports.POST_WOTS_STATUSES=s.POST_WOTS_STATUSES;exports.PRE_DEPOSITOR_SIGNATURES_STATES=s.PRE_DEPOSITOR_SIGNATURES_STATES;exports.RpcErrorCode=s.RpcErrorCode;exports.VP_TERMINAL_STATUSES=s.VP_TERMINAL_STATUSES;exports.VP_TRANSIENT_STATUSES=s.VP_TRANSIENT_STATUSES;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/tbv/core/index.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { h as e, g as t, d as r, a as o, b as i, c as n, e as l, f as u } from "../../challengeAssert-
|
|
1
|
+
import { h as e, g as t, d as r, a as o, b as i, c as n, e as l, f as u } from "../../challengeAssert-KGVKQh0J.js";
|
|
2
2
|
import { computeMinClaimValue as P, deriveVaultId as p } from "@babylonlabs-io/babylon-tbv-rust-wasm";
|
|
3
|
-
import { a as T, d as S, c as E, b as A, f as R, e as g } from "../../noPayout-
|
|
3
|
+
import { a as T, d as S, c as E, b as A, f as R, e as g } from "../../noPayout-BmMd4NNH.js";
|
|
4
4
|
import { d as m, a as x, e as b, f as I, g as f, h as C, i as v, b as U, p as O, s as V, t as F, u as h, v as y } from "../../bitcoin-0_T6KJON.js";
|
|
5
5
|
import { C as D, P as B, a as M, c as H, g as L } from "../../signing-BZigafm0.js";
|
|
6
6
|
import { B as W, H as X, K, M as w, T as G } from "../../validation-CxqROCno.js";
|
|
7
|
-
import { B as J, C as Z, P as j, R as q, a as z, m as Q, h as $, n as aa, i as sa, l as ea, k as ta, r as ra, b as oa, s as ia, v as na, g as la, d as ua, c as da, j as Pa, e as pa, f as ca, w as Ta } from "../../buildAndBroadcastRefund-
|
|
7
|
+
import { B as J, C as Z, P as j, R as q, a as z, m as Q, h as $, n as aa, i as sa, l as ea, k as ta, r as ra, b as oa, s as ia, v as na, g as la, d as ua, c as da, j as Pa, e as pa, f as ca, w as Ta } from "../../buildAndBroadcastRefund-CK8MbGQh.js";
|
|
8
8
|
import { B as Ea, D as Aa, F as Ra, L as ga, M as _a, P as ma, b as xa, a as ba, S as Ia, T as fa, W as Ca, f as va, c as Ua, p as Oa, r as Va } from "../../fundPeginTransaction-oV-dNJOU.js";
|
|
9
9
|
import { B as ha, U as ya, a as Na, f as Da, c as Ba, e as Ma, g as Ha, i as La, h as ka, s as Wa, b as Xa, d as Ka, v as wa } from "../../psbtInputFields-DPCFHgGd.js";
|
|
10
|
-
import { C as Ya, P as Ja, V as Za, k as ja, l as qa, c as za, m as Qa, d as $a, b as as, f as ss, j as es, e as ts, g as rs, h as os, i as is, a as ns, p as ls } from "../../PeginManager-
|
|
10
|
+
import { C as Ya, P as Ja, V as Za, k as ja, l as qa, c as za, m as Qa, d as $a, b as as, f as ss, j as es, e as ts, g as rs, h as os, i as is, a as ns, p as ls } from "../../PeginManager-LeGYbRN2.js";
|
|
11
11
|
import { A as ds, M as Ps, P as ps, S as cs, V as Ts, n as Ss, o as Es, q as As, s as Rs, h as gs, j as _s, l as ms, g as xs, a as bs, b as Is, c as fs, d as Cs, e as vs, f as Us, m as Os, p as Vs, r as Fs, v as hs, i as ys, k as Ns } from "../../vault-registry-reader-BeIEh62N.js";
|
|
12
12
|
import { B as Bs, D as Ms, b as Hs, J as Ls, a as ks, d as Ws, P as Xs, R as Ks, c as ws, V as Gs } from "../../types-D1o_3Q__.js";
|
|
13
13
|
export {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("../../../challengeAssert-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("../../../challengeAssert-06GLZtV8.cjs"),r=require("@babylonlabs-io/babylon-tbv-rust-wasm"),i=require("../../../noPayout-Bp2TYA_X.cjs"),e=require("../../../bitcoin-EYBKDtEW.cjs");exports.buildChallengeAssertPsbt=t.buildChallengeAssertPsbt;exports.buildDepositorPayoutPsbt=t.buildDepositorPayoutPsbt;exports.buildPeginInputPsbt=t.buildPeginInputPsbt;exports.buildPeginTxFromFundedPrePegin=t.buildPeginTxFromFundedPrePegin;exports.buildPrePeginPsbt=t.buildPrePeginPsbt;exports.computeNumLocalChallengers=t.computeNumLocalChallengers;exports.extractPeginInputSignature=t.extractPeginInputSignature;exports.finalizePeginInputPsbt=t.finalizePeginInputPsbt;Object.defineProperty(exports,"computeMinClaimValue",{enumerable:!0,get:()=>r.computeMinClaimValue});Object.defineProperty(exports,"deriveVaultId",{enumerable:!0,get:()=>r.deriveVaultId});exports.assertPayoutOutputMatchesRegistered=i.assertPayoutOutputMatchesRegistered;exports.buildNoPayoutPsbt=i.buildNoPayoutPsbt;exports.buildPayoutPsbt=i.buildPayoutPsbt;exports.buildRefundPsbt=i.buildRefundPsbt;exports.createPayoutScript=i.createPayoutScript;exports.extractPayoutSignature=i.extractPayoutSignature;exports.deriveNativeSegwitAddress=e.deriveNativeSegwitAddress;exports.deriveTaprootAddress=e.deriveTaprootAddress;exports.ensureHexPrefix=e.ensureHexPrefix;exports.formatSatoshisToBtc=e.formatSatoshisToBtc;exports.hexToUint8Array=e.hexToUint8Array;exports.isAddressFromPublicKey=e.isAddressFromPublicKey;exports.isValidHex=e.isValidHex;exports.processPublicKeyToXOnly=e.processPublicKeyToXOnly;exports.stripHexPrefix=e.stripHexPrefix;exports.toXOnly=e.toXOnly;exports.uint8ArrayToHex=e.uint8ArrayToHex;exports.validateWalletPubkey=e.validateWalletPubkey;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { h as s, g as t, d as i, a as r, b as u, c as o, e as d, f as P } from "../../../challengeAssert-
|
|
1
|
+
import { h as s, g as t, d as i, a as r, b as u, c as o, e as d, f as P } from "../../../challengeAssert-KGVKQh0J.js";
|
|
2
2
|
import { computeMinClaimValue as b, deriveVaultId as n } from "@babylonlabs-io/babylon-tbv-rust-wasm";
|
|
3
|
-
import { a as c, d as x, c as g, b as y, f, e as m } from "../../../noPayout-
|
|
3
|
+
import { a as c, d as x, c as g, b as y, f, e as m } from "../../../noPayout-BmMd4NNH.js";
|
|
4
4
|
import { d as v, a as A, e as T, f as S, h as H, i as I, b as C, p as F, s as N, t as O, u as V, v as K } from "../../../bitcoin-0_T6KJON.js";
|
|
5
5
|
export {
|
|
6
6
|
c as assertPayoutOutputMatchesRegistered,
|
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
* Tests for extractPeginInputSignature sighash validation
|
|
3
3
|
*
|
|
4
4
|
* Verifies that the signature extraction correctly validates sighash types,
|
|
5
|
-
* accepting implicit SIGHASH_DEFAULT (64-byte sig)
|
|
6
|
-
*
|
|
7
|
-
*
|
|
5
|
+
* accepting implicit SIGHASH_DEFAULT (64-byte sig) while rejecting signatures
|
|
6
|
+
* with appended sighash bytes. Per BIP-341, the sighash byte changes the
|
|
7
|
+
* Taproot message, so it must not be stripped.
|
|
8
8
|
*/
|
|
9
9
|
export {};
|
|
10
10
|
//# sourceMappingURL=peginInput.test.d.ts.map
|
|
@@ -99,8 +99,9 @@ export declare function assertPayoutOutputMatchesRegistered(payoutTxHex: string,
|
|
|
99
99
|
* 1. Non-finalized PSBT: Extracts from tapScriptSig field
|
|
100
100
|
* 2. Finalized PSBT: Extracts from witness data
|
|
101
101
|
*
|
|
102
|
-
* The signature is returned as a 64-byte hex string (128 hex characters)
|
|
103
|
-
*
|
|
102
|
+
* The signature is returned as a 64-byte hex string (128 hex characters).
|
|
103
|
+
* Payout signatures must use implicit Taproot SIGHASH_DEFAULT, which is
|
|
104
|
+
* encoded by omitting the sighash byte.
|
|
104
105
|
*
|
|
105
106
|
* @param signedPsbtHex - Signed PSBT hex
|
|
106
107
|
* @param depositorPubkey - Depositor's public key (x-only, 64-char hex)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"payout.d.ts","sourceRoot":"","sources":["../../../../../src/tbv/core/primitives/psbt/payout.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EACL,KAAK,OAAO,EAEb,MAAM,uCAAuC,CAAC;AAuB/C;;;;;GAKG;AACH,MAAM,WAAW,YAAY;IAC3B;;;OAGG;IACH,WAAW,EAAE,MAAM,CAAC;IAEpB;;;OAGG;IACH,WAAW,EAAE,MAAM,CAAC;IAEpB;;;OAGG;IACH,UAAU,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,kBAAkB,EAAE,MAAM,CAAC;IAE3B;;OAEG;IACH,sBAAsB,EAAE,MAAM,CAAC;IAE/B;;OAEG;IACH,qBAAqB,EAAE,MAAM,EAAE,CAAC;IAEhC;;OAEG;IACH,6BAA6B,EAAE,MAAM,EAAE,CAAC;IAExC;;OAEG;IACH,aAAa,EAAE,MAAM,CAAC;IAEtB;;OAEG;IACH,OAAO,EAAE,OAAO,CAAC;CAClB;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAsB,eAAe,CACnC,MAAM,EAAE,YAAY,GACnB,OAAO,CAAC,gBAAgB,CAAC,CAqI3B;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,mCAAmC,CACjD,WAAW,EAAE,MAAM,EACnB,4BAA4B,EAAE,MAAM,GACnC,IAAI,CAwBN;AAED
|
|
1
|
+
{"version":3,"file":"payout.d.ts","sourceRoot":"","sources":["../../../../../src/tbv/core/primitives/psbt/payout.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EACL,KAAK,OAAO,EAEb,MAAM,uCAAuC,CAAC;AAuB/C;;;;;GAKG;AACH,MAAM,WAAW,YAAY;IAC3B;;;OAGG;IACH,WAAW,EAAE,MAAM,CAAC;IAEpB;;;OAGG;IACH,WAAW,EAAE,MAAM,CAAC;IAEpB;;;OAGG;IACH,UAAU,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,kBAAkB,EAAE,MAAM,CAAC;IAE3B;;OAEG;IACH,sBAAsB,EAAE,MAAM,CAAC;IAE/B;;OAEG;IACH,qBAAqB,EAAE,MAAM,EAAE,CAAC;IAEhC;;OAEG;IACH,6BAA6B,EAAE,MAAM,EAAE,CAAC;IAExC;;OAEG;IACH,aAAa,EAAE,MAAM,CAAC;IAEtB;;OAEG;IACH,OAAO,EAAE,OAAO,CAAC;CAClB;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAsB,eAAe,CACnC,MAAM,EAAE,YAAY,GACnB,OAAO,CAAC,gBAAgB,CAAC,CAqI3B;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,mCAAmC,CACjD,WAAW,EAAE,MAAM,EACnB,4BAA4B,EAAE,MAAM,GACnC,IAAI,CAwBN;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,sBAAsB,CACpC,aAAa,EAAE,MAAM,EACrB,eAAe,EAAE,MAAM,EACvB,UAAU,SAAI,GACb,MAAM,CA+CR"}
|
|
@@ -58,7 +58,13 @@ export declare function buildPeginInputPsbt(params: BuildPeginInputPsbtParams):
|
|
|
58
58
|
/**
|
|
59
59
|
* Extract the depositor's Schnorr signature from a signed PegIn input PSBT.
|
|
60
60
|
*
|
|
61
|
-
* Supports
|
|
61
|
+
* Supports non-finalized PSBTs with tapScriptSig entries. Finalized PSBTs are
|
|
62
|
+
* rejected because the witness stack does not reliably identify the depositor
|
|
63
|
+
* signature by public key.
|
|
64
|
+
*
|
|
65
|
+
* PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is
|
|
66
|
+
* encoded by omitting the sighash byte. Signatures with an appended sighash byte
|
|
67
|
+
* are rejected rather than stripped.
|
|
62
68
|
*
|
|
63
69
|
* @param signedPsbtHex - Signed PSBT hex
|
|
64
70
|
* @param depositorPubkey - Depositor's x-only public key (64-char hex)
|
|
@@ -77,10 +83,10 @@ export declare function extractPeginInputSignature(signedPsbtHex: string, deposi
|
|
|
77
83
|
*/
|
|
78
84
|
export declare function finalizePeginInputPsbt(signedPsbtHex: string): string;
|
|
79
85
|
/**
|
|
80
|
-
* Extract and validate a 64-byte Schnorr signature
|
|
81
|
-
*
|
|
82
|
-
*
|
|
83
|
-
*
|
|
86
|
+
* Extract and validate a 64-byte Schnorr signature.
|
|
87
|
+
* PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is
|
|
88
|
+
* encoded by omitting the sighash byte. Reject 65-byte signatures instead of
|
|
89
|
+
* stripping the sighash byte because it changes the signed Taproot message.
|
|
84
90
|
* @internal
|
|
85
91
|
*/
|
|
86
92
|
export declare function extractSchnorrSig(sig: Uint8Array): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"peginInput.d.ts","sourceRoot":"","sources":["../../../../../src/tbv/core/primitives/psbt/peginInput.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAGL,KAAK,OAAO,EACb,MAAM,uCAAuC,CAAC;AAK/C;;GAEG;AACH,MAAM,WAAW,yBAAyB;IACxC;;;OAGG;IACH,UAAU,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,mBAAmB,EAAE,MAAM,CAAC;IAC5B,uDAAuD;IACvD,eAAe,EAAE,MAAM,CAAC;IACxB,4DAA4D;IAC5D,mBAAmB,EAAE,MAAM,CAAC;IAC5B,yDAAyD;IACzD,kBAAkB,EAAE,MAAM,EAAE,CAAC;IAC7B,iEAAiE;IACjE,0BAA0B,EAAE,MAAM,EAAE,CAAC;IACrC,uDAAuD;IACvD,QAAQ,EAAE,MAAM,CAAC;IACjB,sDAAsD;IACtD,cAAc,EAAE,MAAM,CAAC;IACvB,sBAAsB;IACtB,OAAO,EAAE,OAAO,CAAC;CAClB;AAED;;GAEG;AACH,MAAM,WAAW,yBAAyB;IACxC,yCAAyC;IACzC,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAsB,mBAAmB,CACvC,MAAM,EAAE,yBAAyB,GAChC,OAAO,CAAC,yBAAyB,CAAC,CAkFpC;AAED
|
|
1
|
+
{"version":3,"file":"peginInput.d.ts","sourceRoot":"","sources":["../../../../../src/tbv/core/primitives/psbt/peginInput.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAGL,KAAK,OAAO,EACb,MAAM,uCAAuC,CAAC;AAK/C;;GAEG;AACH,MAAM,WAAW,yBAAyB;IACxC;;;OAGG;IACH,UAAU,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,mBAAmB,EAAE,MAAM,CAAC;IAC5B,uDAAuD;IACvD,eAAe,EAAE,MAAM,CAAC;IACxB,4DAA4D;IAC5D,mBAAmB,EAAE,MAAM,CAAC;IAC5B,yDAAyD;IACzD,kBAAkB,EAAE,MAAM,EAAE,CAAC;IAC7B,iEAAiE;IACjE,0BAA0B,EAAE,MAAM,EAAE,CAAC;IACrC,uDAAuD;IACvD,QAAQ,EAAE,MAAM,CAAC;IACjB,sDAAsD;IACtD,cAAc,EAAE,MAAM,CAAC;IACvB,sBAAsB;IACtB,OAAO,EAAE,OAAO,CAAC;CAClB;AAED;;GAEG;AACH,MAAM,WAAW,yBAAyB;IACxC,yCAAyC;IACzC,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAsB,mBAAmB,CACvC,MAAM,EAAE,yBAAyB,GAChC,OAAO,CAAC,yBAAyB,CAAC,CAkFpC;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,0BAA0B,CACxC,aAAa,EAAE,MAAM,EACrB,eAAe,EAAE,MAAM,GACtB,MAAM,CAuCR;AAED;;;;;;;;GAQG;AACH,wBAAgB,sBAAsB,CAAC,aAAa,EAAE,MAAM,GAAG,MAAM,CAoBpE;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,UAAU,GAAG,MAAM,CAWzD"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("../../../buildAndBroadcastRefund-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("../../../buildAndBroadcastRefund-BXjYAqdb.cjs"),e=require("../../../signing-DHSXjhLM.cjs");exports.BIP68NotMatureError=t.BIP68NotMatureError;exports.ClaimerPegoutStatusValue=t.ClaimerPegoutStatusValue;exports.REFUND_VSIZE=t.REFUND_VSIZE;exports.activateVault=t.activateVault;exports.buildAndBroadcastRefund=t.buildAndBroadcastRefund;exports.computeHashlock=t.computeHashlock;exports.estimateRefundFeeSats=t.estimateRefundFeeSats;exports.isDepositAmountValid=t.isDepositAmountValid;exports.isPegoutTerminalStatus=t.isPegoutTerminalStatus;exports.isRecognizedPegoutStatus=t.isRecognizedPegoutStatus;exports.runDepositorPresignFlow=t.runDepositorPresignFlow;exports.signDepositorGraph=t.signDepositorGraph;exports.submitWotsPublicKey=t.submitWotsPublicKey;exports.validateDepositAmount=t.validateDepositAmount;exports.validateMultiVaultDepositInputs=t.validateMultiVaultDepositInputs;exports.validateProviderSelection=t.validateProviderSelection;exports.validateRemainingCapacity=t.validateRemainingCapacity;exports.validateSecretAgainstHashlock=t.validateSecretAgainstHashlock;exports.validateVaultAmounts=t.validateVaultAmounts;exports.validateVaultProviderPubkey=t.validateVaultProviderPubkey;exports.waitForPeginStatus=t.waitForPeginStatus;exports.ContractStatus=e.ContractStatus;exports.PeginAction=e.PeginAction;exports.canPerformAction=e.canPerformAction;exports.getPeginProtocolState=e.getPeginProtocolState;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { B as s, C as e, R as i, a as o, m as r, h as u, n as l, i as n, l as d, k as c, r as P, b as g, s as m, v as p, g as v, d as S, c as A, j as V, e as f, f as D, w as R } from "../../../buildAndBroadcastRefund-
|
|
1
|
+
import { B as s, C as e, R as i, a as o, m as r, h as u, n as l, i as n, l as d, k as c, r as P, b as g, s as m, v as p, g as v, d as S, c as A, j as V, e as f, f as D, w as R } from "../../../buildAndBroadcastRefund-CK8MbGQh.js";
|
|
2
2
|
import { C, P as h, a as k, g as F } from "../../../signing-BZigafm0.js";
|
|
3
3
|
export {
|
|
4
4
|
s as BIP68NotMatureError,
|
package/dist/tbv/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("../challengeAssert-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("../challengeAssert-06GLZtV8.cjs"),P=require("@babylonlabs-io/babylon-tbv-rust-wasm"),u=require("../noPayout-Bp2TYA_X.cjs"),i=require("../bitcoin-EYBKDtEW.cjs"),l=require("../signing-DHSXjhLM.cjs"),d=require("../validation-u8W7Lp2x.cjs"),t=require("../buildAndBroadcastRefund-BXjYAqdb.cjs"),a=require("../fundPeginTransaction-DaWoYCgO.cjs"),o=require("../psbtInputFields-BLi7Ta-T.cjs"),r=require("../PeginManager-D2pBM0E-.cjs"),e=require("../vault-registry-reader-DdUgC5IF.cjs"),s=require("../types-C2IUB0Jd.cjs");exports.buildChallengeAssertPsbt=n.buildChallengeAssertPsbt;exports.buildDepositorPayoutPsbt=n.buildDepositorPayoutPsbt;exports.buildPeginInputPsbt=n.buildPeginInputPsbt;exports.buildPeginTxFromFundedPrePegin=n.buildPeginTxFromFundedPrePegin;exports.buildPrePeginPsbt=n.buildPrePeginPsbt;exports.computeNumLocalChallengers=n.computeNumLocalChallengers;exports.extractPeginInputSignature=n.extractPeginInputSignature;exports.finalizePeginInputPsbt=n.finalizePeginInputPsbt;Object.defineProperty(exports,"computeMinClaimValue",{enumerable:!0,get:()=>P.computeMinClaimValue});Object.defineProperty(exports,"deriveVaultId",{enumerable:!0,get:()=>P.deriveVaultId});exports.assertPayoutOutputMatchesRegistered=u.assertPayoutOutputMatchesRegistered;exports.buildNoPayoutPsbt=u.buildNoPayoutPsbt;exports.buildPayoutPsbt=u.buildPayoutPsbt;exports.buildRefundPsbt=u.buildRefundPsbt;exports.createPayoutScript=u.createPayoutScript;exports.extractPayoutSignature=u.extractPayoutSignature;exports.deriveNativeSegwitAddress=i.deriveNativeSegwitAddress;exports.deriveTaprootAddress=i.deriveTaprootAddress;exports.ensureHexPrefix=i.ensureHexPrefix;exports.formatSatoshisToBtc=i.formatSatoshisToBtc;exports.getNetwork=i.getNetwork;exports.hexToUint8Array=i.hexToUint8Array;exports.isAddressFromPublicKey=i.isAddressFromPublicKey;exports.isValidHex=i.isValidHex;exports.processPublicKeyToXOnly=i.processPublicKeyToXOnly;exports.stripHexPrefix=i.stripHexPrefix;exports.toXOnly=i.toXOnly;exports.uint8ArrayToHex=i.uint8ArrayToHex;exports.validateWalletPubkey=i.validateWalletPubkey;exports.ContractStatus=l.ContractStatus;exports.PeginAction=l.PeginAction;exports.canPerformAction=l.canPerformAction;exports.createTaprootScriptPathSignOptions=l.createTaprootScriptPathSignOptions;exports.getPeginProtocolState=l.getPeginProtocolState;exports.BITCOIN_ADDRESS_RE=d.BITCOIN_ADDRESS_RE;exports.HEX_RE=d.HEX_RE;exports.KNOWN_SCRIPT_PREFIXES=d.KNOWN_SCRIPT_PREFIXES;exports.MAX_REASONABLE_FEE_SATS=d.MAX_REASONABLE_FEE_SATS;exports.TXID_RE=d.TXID_RE;exports.BIP68NotMatureError=t.BIP68NotMatureError;exports.ClaimerPegoutStatusValue=t.ClaimerPegoutStatusValue;exports.PayoutManager=t.PayoutManager;exports.REFUND_VSIZE=t.REFUND_VSIZE;exports.activateVault=t.activateVault;exports.buildAndBroadcastRefund=t.buildAndBroadcastRefund;exports.computeHashlock=t.computeHashlock;exports.estimateRefundFeeSats=t.estimateRefundFeeSats;exports.isDepositAmountValid=t.isDepositAmountValid;exports.isPegoutTerminalStatus=t.isPegoutTerminalStatus;exports.isRecognizedPegoutStatus=t.isRecognizedPegoutStatus;exports.runDepositorPresignFlow=t.runDepositorPresignFlow;exports.signDepositorGraph=t.signDepositorGraph;exports.submitWotsPublicKey=t.submitWotsPublicKey;exports.validateDepositAmount=t.validateDepositAmount;exports.validateMultiVaultDepositInputs=t.validateMultiVaultDepositInputs;exports.validateProviderSelection=t.validateProviderSelection;exports.validateRemainingCapacity=t.validateRemainingCapacity;exports.validateSecretAgainstHashlock=t.validateSecretAgainstHashlock;exports.validateVaultAmounts=t.validateVaultAmounts;exports.validateVaultProviderPubkey=t.validateVaultProviderPubkey;exports.waitForPeginStatus=t.waitForPeginStatus;exports.BTC_DUST_SAT=a.BTC_DUST_SAT;exports.DUST_THRESHOLD=a.DUST_THRESHOLD;exports.FEE_SAFETY_MARGIN=a.FEE_SAFETY_MARGIN;exports.LOW_RATE_ESTIMATION_ACCURACY_BUFFER=a.LOW_RATE_ESTIMATION_ACCURACY_BUFFER;exports.MAX_NON_LEGACY_OUTPUT_SIZE=a.MAX_NON_LEGACY_OUTPUT_SIZE;exports.P2TR_INPUT_SIZE=a.P2TR_INPUT_SIZE;exports.PEGIN_AUTH_ANCHOR_OUTPUTS=a.PEGIN_AUTH_ANCHOR_OUTPUTS;exports.PEGIN_FIXED_OUTPUTS=a.PEGIN_FIXED_OUTPUTS;exports.SPLIT_TX_FEE_SAFETY_MULTIPLIER=a.SPLIT_TX_FEE_SAFETY_MULTIPLIER;exports.TX_BUFFER_SIZE_OVERHEAD=a.TX_BUFFER_SIZE_OVERHEAD;exports.WALLET_RELAY_FEE_RATE_THRESHOLD=a.WALLET_RELAY_FEE_RATE_THRESHOLD;exports.fundPeginTransaction=a.fundPeginTransaction;exports.parseUnfundedWasmTransaction=a.parseUnfundedWasmTransaction;exports.peginOutputCount=a.peginOutputCount;exports.rateBasedTxBufferFee=a.rateBasedTxBufferFee;exports.BitcoinScriptType=o.BitcoinScriptType;exports.UtxoNotAvailableError=o.UtxoNotAvailableError;exports.assertUtxosAvailable=o.assertUtxosAvailable;exports.calculateBtcTxHash=o.calculateBtcTxHash;exports.collectReservedUtxoRefs=o.collectReservedUtxoRefs;exports.extractInputsFromTransaction=o.extractInputsFromTransaction;exports.getDustThreshold=o.getDustThreshold;exports.getPsbtInputFields=o.getPsbtInputFields;exports.getScriptType=o.getScriptType;exports.selectUtxosForDeposit=o.selectUtxosForDeposit;exports.selectUtxosForPegin=o.selectUtxosForPegin;exports.shouldAddChangeOutput=o.shouldAddChangeOutput;exports.validateUtxosAvailable=o.validateUtxosAvailable;exports.CONTRACT_ERRORS=r.CONTRACT_ERRORS;exports.PeginManager=r.PeginManager;exports.VAULT_APP_NAME=r.VAULT_APP_NAME;exports.buildFundingOutpointsCommitment=r.buildFundingOutpointsCommitment;exports.buildVaultContext=r.buildVaultContext;exports.computeWotsBlockPublicKeysHash=r.computeWotsBlockPublicKeysHash;exports.deriveVaultRoot=r.deriveVaultRoot;exports.deriveWotsBlocksFromSeed=r.deriveWotsBlocksFromSeed;exports.expandAuthAnchor=r.expandAuthAnchor;exports.expandHashlockSecret=r.expandHashlockSecret;exports.expandWotsSeed=r.expandWotsSeed;exports.extractErrorData=r.extractErrorData;exports.getContractErrorMessage=r.getContractErrorMessage;exports.handleContractError=r.handleContractError;exports.isKnownContractError=r.isKnownContractError;exports.isWotsMismatchError=r.isWotsMismatchError;exports.parseFundingOutpointsFromTx=r.parseFundingOutpointsFromTx;exports.ApplicationRegistryABI=e.ApplicationRegistryABI;exports.MEMPOOL_API_URLS=e.MEMPOOL_API_URLS;exports.ProtocolParamsABI=e.ProtocolParamsABI;exports.ServerIdentityError=e.ServerIdentityError;exports.VaultProviderRpcClient=e.VaultProviderRpcClient;exports.ViemProtocolParamsReader=e.ViemProtocolParamsReader;exports.ViemUniversalChallengerReader=e.ViemUniversalChallengerReader;exports.ViemVaultKeeperReader=e.ViemVaultKeeperReader;exports.ViemVaultRegistryReader=e.ViemVaultRegistryReader;exports.VpResponseValidationError=e.VpResponseValidationError;exports.VpTokenRegistry=e.VpTokenRegistry;exports.createAuthenticatedVpClient=e.createAuthenticatedVpClient;exports.getAddressTxs=e.getAddressTxs;exports.getAddressUtxos=e.getAddressUtxos;exports.getMempoolApiUrl=e.getMempoolApiUrl;exports.getNetworkFees=e.getNetworkFees;exports.getTxHex=e.getTxHex;exports.getTxInfo=e.getTxInfo;exports.getUtxoInfo=e.getUtxoInfo;exports.primeVpTokenRegistry=e.primeVpTokenRegistry;exports.pushTx=e.pushTx;exports.resolveProtocolAddresses=e.resolveProtocolAddresses;exports.validateRequestDepositorClaimerArtifactsResponse=e.validateRequestDepositorClaimerArtifactsResponse;exports.verifyServerIdentity=e.verifyServerIdentity;exports.vpTokenRegistry=e.vpTokenRegistry;exports.BTCVaultRegistryABI=s.BTCVaultRegistryABI;exports.DaemonStatus=s.DaemonStatus;exports.JSON_RPC_ERROR_CODES=s.JSON_RPC_ERROR_CODES;exports.JsonRpcClient=s.JsonRpcClient;exports.JsonRpcError=s.JsonRpcError;exports.POST_WOTS_STATUSES=s.POST_WOTS_STATUSES;exports.PRE_DEPOSITOR_SIGNATURES_STATES=s.PRE_DEPOSITOR_SIGNATURES_STATES;exports.RpcErrorCode=s.RpcErrorCode;exports.VP_TERMINAL_STATUSES=s.VP_TERMINAL_STATUSES;exports.VP_TRANSIENT_STATUSES=s.VP_TRANSIENT_STATUSES;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/tbv/index.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { h as e, g as t, d as r, a as o, b as i, c as n, e as l, f as u } from "../challengeAssert-
|
|
1
|
+
import { h as e, g as t, d as r, a as o, b as i, c as n, e as l, f as u } from "../challengeAssert-KGVKQh0J.js";
|
|
2
2
|
import { computeMinClaimValue as P, deriveVaultId as p } from "@babylonlabs-io/babylon-tbv-rust-wasm";
|
|
3
|
-
import { a as T, d as S, c as E, b as A, f as R, e as g } from "../noPayout-
|
|
3
|
+
import { a as T, d as S, c as E, b as A, f as R, e as g } from "../noPayout-BmMd4NNH.js";
|
|
4
4
|
import { d as m, a as x, e as b, f as I, g as f, h as C, i as v, b as U, p as O, s as V, t as F, u as h, v as y } from "../bitcoin-0_T6KJON.js";
|
|
5
5
|
import { C as D, P as B, a as M, c as H, g as L } from "../signing-BZigafm0.js";
|
|
6
6
|
import { B as W, H as X, K, M as w, T as G } from "../validation-CxqROCno.js";
|
|
7
|
-
import { B as J, C as Z, P as j, R as q, a as z, m as Q, h as $, n as aa, i as sa, l as ea, k as ta, r as ra, b as oa, s as ia, v as na, g as la, d as ua, c as da, j as Pa, e as pa, f as ca, w as Ta } from "../buildAndBroadcastRefund-
|
|
7
|
+
import { B as J, C as Z, P as j, R as q, a as z, m as Q, h as $, n as aa, i as sa, l as ea, k as ta, r as ra, b as oa, s as ia, v as na, g as la, d as ua, c as da, j as Pa, e as pa, f as ca, w as Ta } from "../buildAndBroadcastRefund-CK8MbGQh.js";
|
|
8
8
|
import { B as Ea, D as Aa, F as Ra, L as ga, M as _a, P as ma, b as xa, a as ba, S as Ia, T as fa, W as Ca, f as va, c as Ua, p as Oa, r as Va } from "../fundPeginTransaction-oV-dNJOU.js";
|
|
9
9
|
import { B as ha, U as ya, a as Na, f as Da, c as Ba, e as Ma, g as Ha, i as La, h as ka, s as Wa, b as Xa, d as Ka, v as wa } from "../psbtInputFields-DPCFHgGd.js";
|
|
10
|
-
import { C as Ya, P as Ja, V as Za, k as ja, l as qa, c as za, m as Qa, d as $a, b as as, f as ss, j as es, e as ts, g as rs, h as os, i as is, a as ns, p as ls } from "../PeginManager-
|
|
10
|
+
import { C as Ya, P as Ja, V as Za, k as ja, l as qa, c as za, m as Qa, d as $a, b as as, f as ss, j as es, e as ts, g as rs, h as os, i as is, a as ns, p as ls } from "../PeginManager-LeGYbRN2.js";
|
|
11
11
|
import { A as ds, M as Ps, P as ps, S as cs, V as Ts, n as Ss, o as Es, q as As, s as Rs, h as gs, j as _s, l as ms, g as xs, a as bs, b as Is, c as fs, d as Cs, e as vs, f as Us, m as Os, p as Vs, r as Fs, v as hs, i as ys, k as Ns } from "../vault-registry-reader-BeIEh62N.js";
|
|
12
12
|
import { B as Bs, D as Ms, b as Hs, J as Ls, a as ks, d as Ws, P as Xs, R as Ks, c as ws, V as Gs } from "../types-D1o_3Q__.js";
|
|
13
13
|
export {
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"challengeAssert-DSlCIBoT.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/constants.ts","../src/tbv/core/primitives/psbt/depositorPayout.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 buildPeginTxFromPrePegin,\n createPrePeginTransaction,\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 * Optional 32-byte `SHA256(auth_anchor)` commitment (64-char hex, no\n * `0x` prefix). If provided, the Pre-PegIn tx will include an\n * `OP_RETURN <PUSH32 authAnchorHash>` output at vout =\n * `hashlocks.length`, binding the depositor's bearer-token\n * `auth_anchor` preimage to this Pre-PegIn.\n */\n authAnchorHash?: string;\n}\n\n/**\n * Byte length of an `auth_anchor_hash` commitment when encoded as a\n * lowercase hex string (32 bytes → 64 hex chars).\n */\nconst AUTH_ANCHOR_HASH_HEX_LEN = 64;\n\nconst HEX_PATTERN = /^[0-9a-fA-F]+$/;\n\n/**\n * Result of building an unfunded Pre-PegIn transaction\n */\nexport interface PrePeginPsbtResult {\n /**\n * Unfunded transaction hex (no inputs, HTLC outputs + optional\n * auth-anchor OP_RETURN + 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 * - Calling buildPeginTxFromFundedPrePegin() with the funded tx hex\n */\n psbtHex: string;\n /** Sum of all unfunded outputs — 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 * Vout index of the auth-anchor `OP_RETURN` output if one was\n * included (i.e. `authAnchorHash` was provided), or `null` if not.\n * Always equals `htlcValues.length` when present.\n */\n authAnchorVout: number | null;\n}\n\n/**\n * Parameters for building the PegIn transaction from a funded Pre-PegIn tx\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 authAnchorHash = normalizeAuthAnchorHash(params.authAnchorHash);\n\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 authAnchorHash,\n });\n\n // Parse the unfunded tx to sum all output values\n // (HTLCs + optional OP_RETURN + CPFP anchor). This is the amount\n // 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 // The WASM places the OP_RETURN commitment immediately after the\n // HTLC outputs when authAnchorHash is provided.\n const authAnchorVout =\n authAnchorHash !== undefined ? result.htlcValues.length : null;\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 authAnchorVout,\n };\n}\n\n/**\n * Validate and normalize an `authAnchorHash` hex string before passing\n * it to the WASM boundary. WASM expects exactly 64 lowercase hex chars.\n */\nfunction normalizeAuthAnchorHash(\n value: string | undefined,\n): string | undefined {\n if (value === undefined) return undefined;\n const cleaned =\n value.startsWith(\"0x\") || value.startsWith(\"0X\") ? value.slice(2) : value;\n if (\n cleaned.length !== AUTH_ANCHOR_HASH_HEX_LEN ||\n !HEX_PATTERN.test(cleaned)\n ) {\n throw new Error(\n `authAnchorHash must be 32-byte hex (${AUTH_ANCHOR_HASH_HEX_LEN} chars, no 0x prefix); got length ${cleaned.length}`,\n );\n }\n return cleaned.toLowerCase();\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 // WASM reconstructs the Pre-PegIn template from these params to\n // decode the funded tx. Must pass `authAnchorHash` (normalized\n // identically to buildPrePeginPsbt) so the reconstruction matches\n // the original outputs, including the OP_RETURN at vout =\n // hashlocks.length.\n const result = await buildPeginTxFromPrePegin(\n {\n depositorPubkey: params.prePeginParams.depositorPubkey,\n vaultProviderPubkey: params.prePeginParams.vaultProviderPubkey,\n vaultKeeperPubkeys: params.prePeginParams.vaultKeeperPubkeys,\n universalChallengerPubkeys:\n 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 authAnchorHash: normalizeAuthAnchorHash(\n params.prePeginParams.authAnchorHash,\n ),\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/**\n * Extract and validate a 64-byte Schnorr signature, stripping sighash flag if present.\n * Accepts 64-byte sigs (implicit SIGHASH_DEFAULT) and 65-byte sigs with\n * SIGHASH_ALL (0x01). Rejects all other sighash types including 0x00, which\n * is consensus-invalid per BIP-342 when explicitly appended.\n * @internal\n */\nexport function extractSchnorrSig(sig: Uint8Array): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n }\n if (sig.length === 65) {\n const sighashByte = sig[64];\n // Only accept SIGHASH_ALL (0x01). Per BIP-342, SIGHASH_DEFAULT is signaled\n // by omitting the sighash byte (64-byte sig). A 65-byte sig with byte 64\n // set to 0x00 is consensus-invalid: Bitcoin Core rejects it with\n // SCRIPT_ERR_SCHNORR_SIG_HASHTYPE. Accepting 0x00 here would let\n // extractPeginInputSignature succeed (stripping the byte) while\n // finalizePeginInputPsbt passes the raw 65-byte sig into the witness,\n // producing a BTC transaction that can never confirm.\n if (sighashByte !== Transaction.SIGHASH_ALL) {\n throw new Error(\n `Unexpected sighash type 0x${sighashByte.toString(16).padStart(2, \"0\")} in PegIn input signature. ` +\n `Expected SIGHASH_DEFAULT (64-byte sig) or SIGHASH_ALL (0x01).`,\n );\n }\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 * Protocol invariants for depositor graph transactions.\n *\n * These indices and counts encode the on-chain vault protocol layout\n * (which output of PegIn/Assert each child transaction spends, and how\n * many inputs each transaction has). Consumed by the PSBT builders and\n * the depositor graph signing service; a drift between copies of these\n * values would silently change validation behaviour.\n *\n * @module primitives/psbt/constants\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md\n */\n\n/**\n * Depositor Payout transaction input count.\n * Input 0: PegIn:0 (signed). Input 1: Assert:0 (in sighash, not signed).\n */\nexport const DEPOSITOR_PAYOUT_INPUT_COUNT = 2;\n\n/** PegIn vault output index spent by the depositor's Payout input 0. */\nexport const PEGIN_VAULT_OUTPUT_INDEX = 0;\n\n/** Payout input index bound to the graph Assert tx (NOT signed). */\nexport const PAYOUT_ASSERT_INPUT_INDEX = 1;\n\n/** Assert output index spent by the depositor's Payout input 1 (NOT signed). */\nexport const ASSERT_PAYOUT_OUTPUT_INDEX = 0;\n\n/** Assert output index spent by NoPayout input 0 (signed). */\nexport const ASSERT_NOPAYOUT_OUTPUT_INDEX = 0;\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 inputTxidHex,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\nimport {\n ASSERT_PAYOUT_OUTPUT_INDEX,\n DEPOSITOR_PAYOUT_INPUT_COUNT,\n PEGIN_VAULT_OUTPUT_INDEX,\n} from \"./constants\";\n\n/**\n * Parameters for building a depositor Payout PSBT\n */\nexport interface DepositorPayoutParams {\n /** Payout transaction hex (unsigned) */\n payoutTxHex: string;\n /** Authoritative PegIn transaction hex — input 0 must spend PegIn:0 */\n peginTxHex: string;\n /** Authoritative Assert transaction hex — input 1 must spend Assert:0 */\n assertTxHex: string;\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 * Both inputs must be present in the PSBT because Taproot SIGHASH_DEFAULT\n * commits to all input prevouts. Prevout script_pubkey/value are derived\n * from the authoritative parent transactions, not trusted from external input.\n *\n * @param params - Depositor payout parameters\n * @returns Unsigned PSBT hex ready for signing\n *\n * @throws If the payout transaction does not have exactly 2 inputs\n * @throws If input 0 does not reference peginTxHex at output index 0\n * @throws If input 1 does not reference assertTxHex at output index 0\n */\nexport async function buildDepositorPayoutPsbt(\n params: DepositorPayoutParams,\n): Promise<string> {\n const payoutTx = Transaction.fromHex(stripHexPrefix(params.payoutTxHex));\n const peginTx = Transaction.fromHex(stripHexPrefix(params.peginTxHex));\n const assertTx = Transaction.fromHex(stripHexPrefix(params.assertTxHex));\n\n if (payoutTx.ins.length !== DEPOSITOR_PAYOUT_INPUT_COUNT) {\n throw new Error(\n `Depositor Payout transaction must have exactly ${DEPOSITOR_PAYOUT_INPUT_COUNT} inputs, got ${payoutTx.ins.length}`,\n );\n }\n\n const input0 = payoutTx.ins[0];\n const input1 = payoutTx.ins[1];\n\n const input0Txid = inputTxidHex(input0);\n const peginTxid = peginTx.getId();\n if (input0Txid !== peginTxid || input0.index !== PEGIN_VAULT_OUTPUT_INDEX) {\n throw new Error(\n `Depositor Payout input 0 must spend PegIn:${PEGIN_VAULT_OUTPUT_INDEX}. ` +\n `Expected ${peginTxid}:${PEGIN_VAULT_OUTPUT_INDEX}, got ${input0Txid}:${input0.index}`,\n );\n }\n\n const input1Txid = inputTxidHex(input1);\n const assertTxid = assertTx.getId();\n if (input1Txid !== assertTxid || input1.index !== ASSERT_PAYOUT_OUTPUT_INDEX) {\n throw new Error(\n `Depositor Payout input 1 must spend Assert:${ASSERT_PAYOUT_OUTPUT_INDEX}. ` +\n `Expected ${assertTxid}:${ASSERT_PAYOUT_OUTPUT_INDEX}, got ${input1Txid}:${input1.index}`,\n );\n }\n\n const peginPrevOut = peginTx.outs[input0.index];\n const assertPrevOut = assertTx.outs[input1.index];\n\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 psbt.addInput({\n hash: input0.hash,\n index: input0.index,\n sequence: input0.sequence,\n witnessUtxo: {\n script: peginPrevOut.script,\n value: peginPrevOut.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n\n psbt.addInput({\n hash: input1.hash,\n index: input1.index,\n sequence: input1.sequence,\n witnessUtxo: {\n script: assertPrevOut.script,\n value: assertPrevOut.value,\n },\n });\n\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 * 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 inputTxidHex,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a ChallengeAssert PSBT\n */\nexport interface ChallengeAssertParams {\n /** ChallengeAssert transaction hex (unsigned) */\n challengeAssertTxHex: string;\n /** Authoritative Assert transaction hex — every input must spend an Assert output */\n assertTxHex: string;\n /** Per-input connector params (one per input/segment, determines the taproot script) */\n connectorParamsPerInput: ChallengeAssertConnectorParams[];\n}\n\n/**\n * Build unsigned ChallengeAssert PSBT.\n *\n * 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. Every prevout is derived from the\n * authoritative Assert transaction, never trusted from external input.\n *\n * @param params - ChallengeAssert parameters\n * @returns Unsigned PSBT hex ready for signing\n *\n * @throws If the number of connector params does not match the number of inputs\n * @throws If any input does not reference assertTxHex\n * @throws If any referenced Assert output is missing\n * @throws If two inputs reference the same Assert output index\n */\nexport async function buildChallengeAssertPsbt(\n params: ChallengeAssertParams,\n): Promise<string> {\n const challengeAssertTx = Transaction.fromHex(\n stripHexPrefix(params.challengeAssertTxHex),\n );\n const assertTx = Transaction.fromHex(stripHexPrefix(params.assertTxHex));\n const assertTxid = assertTx.getId();\n\n if (params.connectorParamsPerInput.length !== challengeAssertTx.ins.length) {\n throw new Error(\n `Expected ${challengeAssertTx.ins.length} connector params, got ${params.connectorParamsPerInput.length}`,\n );\n }\n\n const seenAssertOutputs = new Set<number>();\n for (let i = 0; i < challengeAssertTx.ins.length; i++) {\n const input = challengeAssertTx.ins[i];\n const inputTxid = inputTxidHex(input);\n if (inputTxid !== assertTxid) {\n throw new Error(\n `ChallengeAssert input ${i} must spend an Assert output. ` +\n `Expected txid ${assertTxid}, got ${inputTxid}`,\n );\n }\n if (!assertTx.outs[input.index]) {\n throw new Error(\n `Assert output ${input.index} not found for ChallengeAssert input ${i} (txid: ${assertTxid})`,\n );\n }\n if (seenAssertOutputs.has(input.index)) {\n throw new Error(\n `ChallengeAssert input ${i} duplicates Assert output index ${input.index}`,\n );\n }\n seenAssertOutputs.add(input.index);\n }\n\n const scriptInfos = await Promise.all(\n params.connectorParamsPerInput.map((cp) => getChallengeAssertScriptInfo(cp)),\n );\n\n const psbt = new Psbt();\n psbt.setVersion(challengeAssertTx.version);\n psbt.setLocktime(challengeAssertTx.locktime);\n\n for (let i = 0; i < challengeAssertTx.ins.length; i++) {\n const input = challengeAssertTx.ins[i];\n const assertPrevOut = assertTx.outs[input.index];\n\n const { script, controlBlock } = scriptInfos[i];\n const scriptBytes = hexToUint8Array(script);\n const controlBlockBytes = hexToUint8Array(controlBlock);\n\n psbt.addInput({\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: assertPrevOut.script,\n value: assertPrevOut.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n }\n\n for (const output of challengeAssertTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n"],"names":["normalizeKey","key","processPublicKeyToXOnly","computeNumLocalChallengers","vaultProviderPubkey","vaultKeeperPubkeys","depositorPubkey","localSet","vk","AUTH_ANCHOR_HASH_HEX_LEN","HEX_PATTERN","buildPrePeginPsbt","params","authAnchorHash","normalizeAuthAnchorHash","result","createPrePeginTransaction","totalOutputValue","parseUnfundedWasmTransaction","sum","authAnchorVout","value","cleaned","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","sighashByte","DEPOSITOR_PAYOUT_INPUT_COUNT","PEGIN_VAULT_OUTPUT_INDEX","ASSERT_PAYOUT_OUTPUT_INDEX","buildDepositorPayoutPsbt","payoutTx","assertTx","input0","input1","input0Txid","inputTxidHex","peginTxid","input1Txid","assertTxid","peginPrevOut","assertPrevOut","payoutScript","payoutControlBlock","getPeginPayoutScriptInfo","scriptBytes","controlBlock","buildChallengeAssertPsbt","challengeAssertTx","seenAssertOutputs","i","inputTxid","scriptInfos","cp","getChallengeAssertScriptInfo","script","controlBlockBytes"],"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;ACqBA,MAAME,IAA2B,IAE3BC,IAAc;AA2EpB,eAAsBC,EACpBC,GAC6B;AAC7B,QAAMC,IAAiBC,EAAwBF,EAAO,cAAc,GAE9DG,IAAS,MAAMC,EAA0B;AAAA,IAC7C,iBAAiBJ,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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