@babylonlabs-io/ts-sdk 6.0.0 → 6.0.2
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/{PayoutManager-BHeiLQ1j.js → PayoutManager-3-MzBVLj.js} +2 -2
- package/dist/{PayoutManager-BHeiLQ1j.js.map → PayoutManager-3-MzBVLj.js.map} +1 -1
- package/dist/{PayoutManager-B5nR0x1t.cjs → PayoutManager-PQqeqX41.cjs} +2 -2
- package/dist/{PayoutManager-B5nR0x1t.cjs.map → PayoutManager-PQqeqX41.cjs.map} +1 -1
- package/dist/{PeginManager-6ghglb4r.cjs → PeginManager-D_ZUfbIy.cjs} +2 -2
- package/dist/{PeginManager-6ghglb4r.cjs.map → PeginManager-D_ZUfbIy.cjs.map} +1 -1
- package/dist/{PeginManager-CXNqbgA4.js → PeginManager-m3IlM4wS.js} +4 -4
- package/dist/{PeginManager-CXNqbgA4.js.map → PeginManager-m3IlM4wS.js.map} +1 -1
- package/dist/{buildAndBroadcastReclaim-CXOMHHgK.cjs → buildAndBroadcastReclaim-CMjlyooo.cjs} +2 -2
- package/dist/{buildAndBroadcastReclaim-CXOMHHgK.cjs.map → buildAndBroadcastReclaim-CMjlyooo.cjs.map} +1 -1
- package/dist/{buildAndBroadcastReclaim-Bs_zdDGN.js → buildAndBroadcastReclaim-D8l-QJWo.js} +4 -4
- package/dist/{buildAndBroadcastReclaim-Bs_zdDGN.js.map → buildAndBroadcastReclaim-D8l-QJWo.js.map} +1 -1
- package/dist/{challengeAssert-CuX_8Twt.cjs → challengeAssert-DlzX_kjF.cjs} +2 -2
- package/dist/{challengeAssert-CuX_8Twt.cjs.map → challengeAssert-DlzX_kjF.cjs.map} +1 -1
- package/dist/{challengeAssert-D_lRvsO0.js → challengeAssert-hpOHGPXX.js} +2 -2
- package/dist/{challengeAssert-D_lRvsO0.js.map → challengeAssert-hpOHGPXX.js.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +307 -305
- package/dist/index.js.map +1 -1
- package/dist/peginState-B4t_PDgj.cjs.map +1 -1
- package/dist/peginState-CXdbSit3.js.map +1 -1
- package/dist/signer-set-reader-CNEfzwuA.cjs +2 -0
- package/dist/signer-set-reader-CNEfzwuA.cjs.map +1 -0
- package/dist/{signer-set-reader-DiwLeqik.js → signer-set-reader-Csz8RXQi.js} +6 -5
- package/dist/signer-set-reader-Csz8RXQi.js.map +1 -0
- package/dist/tbv/core/clients/eth/__tests__/contract-address-resolver.test.d.ts +2 -0
- package/dist/tbv/core/clients/eth/__tests__/contract-address-resolver.test.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/contract-address-resolver.d.ts +3 -1
- package/dist/tbv/core/clients/eth/contract-address-resolver.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/index.cjs +1 -1
- package/dist/tbv/core/clients/eth/index.js +1 -1
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +1 -1
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +305 -303
- package/dist/tbv/core/index.js.map +1 -1
- package/dist/tbv/core/managers/index.cjs +1 -1
- package/dist/tbv/core/managers/index.js +2 -2
- package/dist/tbv/core/primitives/index.cjs +1 -1
- package/dist/tbv/core/primitives/index.d.ts +5 -0
- package/dist/tbv/core/primitives/index.d.ts.map +1 -1
- package/dist/tbv/core/primitives/index.js +31 -29
- package/dist/tbv/core/primitives/index.js.map +1 -1
- package/dist/tbv/core/primitives/psbt/__tests__/signetPeginHashlockSpend.fixture.d.ts +19 -0
- package/dist/tbv/core/primitives/psbt/__tests__/signetPeginHashlockSpend.fixture.d.ts.map +1 -0
- package/dist/tbv/core/primitives/psbt/__tests__/verifyPeginHashlockSpend.test.d.ts +9 -0
- package/dist/tbv/core/primitives/psbt/__tests__/verifyPeginHashlockSpend.test.d.ts.map +1 -0
- package/dist/tbv/core/primitives/psbt/verifyPeginHashlockSpend.d.ts +73 -0
- package/dist/tbv/core/primitives/psbt/verifyPeginHashlockSpend.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/peginState.d.ts +16 -5
- package/dist/tbv/core/services/deposit/peginState.d.ts.map +1 -1
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.js +2 -2
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +305 -303
- package/dist/tbv/index.js.map +1 -1
- package/dist/{toRefundInputs-Cl4KgzIc.js → toRefundInputs-D5tx3eeA.js} +4 -4
- package/dist/{toRefundInputs-Cl4KgzIc.js.map → toRefundInputs-D5tx3eeA.js.map} +1 -1
- package/dist/{toRefundInputs-DyIgmGJq.cjs → toRefundInputs-Df6eRITl.cjs} +2 -2
- package/dist/{toRefundInputs-DyIgmGJq.cjs.map → toRefundInputs-Df6eRITl.cjs.map} +1 -1
- package/dist/{verifyKeyPathSchnorrSignature-BVrAmVL3.cjs → verifyKeyPathSchnorrSignature-B7Za6aa1.cjs} +2 -2
- package/dist/{verifyKeyPathSchnorrSignature-BVrAmVL3.cjs.map → verifyKeyPathSchnorrSignature-B7Za6aa1.cjs.map} +1 -1
- package/dist/{verifyKeyPathSchnorrSignature-CIE3jlVt.js → verifyKeyPathSchnorrSignature-dw7xhm5Y.js} +2 -2
- package/dist/{verifyKeyPathSchnorrSignature-CIE3jlVt.js.map → verifyKeyPathSchnorrSignature-dw7xhm5Y.js.map} +1 -1
- package/dist/verifyPeginHashlockSpend-CdTFR2K6.js +167 -0
- package/dist/verifyPeginHashlockSpend-CdTFR2K6.js.map +1 -0
- package/dist/verifyPeginHashlockSpend-CisfqMuT.cjs +2 -0
- package/dist/verifyPeginHashlockSpend-CisfqMuT.cjs.map +1 -0
- package/dist/{verifyScriptPathSchnorrSignature-DLNGgm4j.js → verifyScriptPathSchnorrSignature-BVGPEZXW.js} +9 -8
- package/dist/{verifyScriptPathSchnorrSignature-DLNGgm4j.js.map → verifyScriptPathSchnorrSignature-BVGPEZXW.js.map} +1 -1
- package/dist/{verifyScriptPathSchnorrSignature-BHskbJJx.cjs → verifyScriptPathSchnorrSignature-p3sVoWQi.cjs} +2 -2
- package/dist/{verifyScriptPathSchnorrSignature-BHskbJJx.cjs.map → verifyScriptPathSchnorrSignature-p3sVoWQi.cjs.map} +1 -1
- package/package.json +1 -1
- package/dist/signer-set-reader-CJfV-GDz.cjs +0 -2
- package/dist/signer-set-reader-CJfV-GDz.cjs.map +0 -1
- package/dist/signer-set-reader-DiwLeqik.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"challengeAssert-D_lRvsO0.js","sources":["../src/tbv/core/wasm/value-guards.ts","../src/tbv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/psbt/reclaim.ts","../src/tbv/core/primitives/psbt/finalizeScriptPathWithSignatures.ts","../src/tbv/core/primitives/psbt/noPayout.ts","../src/tbv/core/primitives/psbt/challengeAssert.ts"],"sourcesContent":["/**\n * Runtime guard for satoshi amounts crossing into the WASM FFI boundary.\n *\n * `new BigUint64Array(values)` is the only way satoshi amounts are handed to\n * the constructor, and a runtime cast (`as readonly bigint[]`) lets a caller\n * pass a non-bigint or non-positive element that `BigUint64Array` would either\n * reject cryptically or, in its length-arg form, silently zero-fill. Values\n * above the u64 maximum are worse still: `BigUint64Array` wraps them mod 2^64\n * without complaint, turning an oversized amount into a small one.\n * {@link assertPositiveBigintArray} validates such inputs before the\n * typed-array construction.\n *\n * Mirrors the `assertPositiveBigintArray` half of `value-guards.ts` in\n * `@babylonlabs-io/babylon-tbv-rust-wasm`; that one function is pinned to the\n * engine's source copy by `__tests__/value-guards.test.ts`. The engine's other\n * guard, `assertWasmBigint`, has no counterpart here: the engine applies it to\n * its own WASM return values before they reach this package.\n */\n\n/** Largest value BigUint64Array stores without wrapping mod 2^64 (2^64 − 1). */\nconst U64_MAX = (1n << 64n) - 1n;\n\n/**\n * Assert a value is a non-empty array of strictly-positive `bigint`s and return\n * it narrowed, ready to feed into `new BigUint64Array(...)`.\n *\n * @param values - The candidate array of satoshi amounts.\n * @param label - Human-readable name used in the thrown error.\n * @throws If `values` is not an array, is empty, or contains any element that is\n * not a `bigint`, is not strictly greater than 0, or exceeds the u64 maximum\n * (which `BigUint64Array` would otherwise wrap mod 2^64).\n */\nexport function assertPositiveBigintArray(\n values: unknown,\n label: string,\n): bigint[] {\n if (!Array.isArray(values)) {\n throw new Error(\n `${label} must be an array of positive bigints (got ${typeof values}).`,\n );\n }\n if (values.length === 0) {\n throw new Error(`${label} must not be empty.`);\n }\n values.forEach((value, index) => {\n if (typeof value !== \"bigint\") {\n throw new Error(\n `${label}[${index}] must be a bigint (got ${typeof value}); ` +\n `refusing to feed it into satoshi math.`,\n );\n }\n if (value <= 0n) {\n throw new Error(`${label}[${index}] must be > 0 (got ${value}).`);\n }\n if (value > U64_MAX) {\n throw new Error(\n `${label}[${index}] must fit in a u64 (got ${value}); ` +\n `refusing to feed it into satoshi math.`,\n );\n }\n });\n return values as bigint[];\n}\n","/**\n * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\nimport { loadTbvWasm, tapInternalPubkey } from \"../../wasm\";\nimport { assertPositiveBigintArray } from \"../../wasm/value-guards\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport { deriveExpectedPrePeginHtlc } from \"./assertWasmPeginSizing\";\nimport { REFUND_TX_LOCKTIME, REFUND_TX_VERSION } from \"./constants\";\nimport { normalizeAuthAnchorHash, type PrePeginParams } from \"./pegin\";\n\n/**\n * Parameters for building a refund PSBT\n */\nexport interface BuildRefundPsbtParams {\n /** Same PrePeginParams used when the original Pre-PegIn tx was created */\n prePeginParams: PrePeginParams;\n /** Funded Pre-PegIn transaction hex (the tx whose HTLC output is being refunded) */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output in the Pre-PegIn transaction */\n htlcVout: number;\n /** Transaction fee in satoshis for the refund transaction */\n refundFee: bigint;\n /** SHA256 hash commitment for the HTLC (64 hex chars, no 0x prefix) */\n hashlock: string;\n}\n\n/**\n * Result of building a refund PSBT\n */\nexport interface BuildRefundPsbtResult {\n /** PSBT hex ready for depositor signing */\n psbtHex: string;\n}\n\n/**\n * Build a PSBT for signing the refund transaction.\n *\n * The refund transaction spends the Pre-PegIn HTLC output via leaf 1\n * (the refund script: `<depositorPubkey> OP_CHECKSIGVERIFY <timelockRefund>\n * OP_CHECKSEQUENCEVERIFY` — btc-vault `connectors/prepegin_htlc.rs`\n * `generate_refund_script`).\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 const { WasmPrePeginTx } = await loadTbvWasm();\n\n const { prePeginParams, fundedPrePeginTxHex, htlcVout, refundFee, hashlock } =\n params;\n\n // The 14th positional arg `auth_anchor_hash` is `Option<String>` in\n // the Rust WASM constructor (the 9th arg `min_pegin_fee_rate` requires\n // the two-rate constructor from btc-vault #1930). Production peg-ins\n // (PeginManager) always commit an OP_RETURN <PUSH32 SHA256(authAnchor)>\n // output at `vout = hashlocks.length`; the unfunded template must\n // include it so `fromFundedTransaction` aligns with the funded tx.\n // Normalize identically to the peg-in primitives (`0x` strip,\n // lowercase, length/charset validation) so a direct primitive caller\n // reusing successful peg-in params doesn't hand unnormalized bytes to\n // WASM. Pass `undefined` for legacy non-auth-anchored Pre-PegIns.\n const normalizedAuthAnchorHash = normalizeAuthAnchorHash(\n prePeginParams.authAnchorHash,\n );\n // Reconstruct the template under the same graph version the Pre-PegIn\n // was originally built with (the vault's stamped vaultCoreVersion).\n const unfundedTx = new WasmPrePeginTx(\n prePeginParams.vaultCoreVersion,\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(\n assertPositiveBigintArray(prePeginParams.pegInAmounts, \"pegInAmounts\"),\n ),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.minPeginFeeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n normalizedAuthAnchorHash,\n );\n\n let fundedTx: typeof unfundedTx | null = null;\n try {\n // Two cross-checks bind the rebuilt HTLC before anything is signed.\n // First, the WASM template against an independent TypeScript derivation:\n // a disagreement means the engine diverged, or that the caller's\n // `hashlock` differs from `prePeginParams.hashlocks[htlcVout]` (the\n // template reads the array, the derivation reads `hashlock`). Then\n // (below) that scriptPubKey against the funded tx's output: a\n // disagreement there means the params do not describe the HTLC on chain,\n // and signing would produce a refund that cannot spend it. Never sign a\n // refund whose template does not match the on-chain output bytes.\n const wasmHtlcScriptPubKey = unfundedTx\n .getHtlcScriptPubKey(htlcVout)\n .toLowerCase();\n const expectedHtlc = deriveExpectedPrePeginHtlc(prePeginParams, hashlock);\n const expectedHtlcScriptPubKey = expectedHtlc.scriptPubKey.toString(\"hex\");\n if (wasmHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `WASM HTLC scriptPubKey ${wasmHtlcScriptPubKey} does not match the ` +\n `independently derived scriptPubKey ${expectedHtlcScriptPubKey}.`,\n );\n }\n // The reconstructed template's HTLC output value at `htlcVout`,\n // sized by WASM from the supplied `pegInAmounts` via the protocol\n // formula `htlcValue = peginAmount + depositorClaimValue + p2aAnchorValue + minPeginFee`.\n // Captured before `fromFundedTransaction` to bind it to the value the\n // funded tx actually carries (see the cross-check below).\n const expectedHtlcValue = unfundedTx.getHtlcValue(htlcVout);\n\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const cleanPrePeginHex = fundedPrePeginTxHex.startsWith(\"0x\")\n ? fundedPrePeginTxHex.slice(2)\n : fundedPrePeginTxHex;\n const prePeginTx = Transaction.fromHex(cleanPrePeginHex);\n\n const htlcOutput = prePeginTx.outs[htlcVout];\n if (!htlcOutput) {\n throw new Error(\n `HTLC output at vout ${htlcVout} not found in funded Pre-PegIn tx ` +\n `(tx has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const actualHtlcScriptPubKey = uint8ArrayToHex(\n new Uint8Array(htlcOutput.script),\n ).toLowerCase();\n // The scriptPubKey commits to the depositor key, the participant keys, the\n // hashlock and timelockRefund. A wrong depositor key is refused earlier,\n // at `fromFundedTransaction`'s CPFP anchor check, and amounts have their\n // own value check below. The message names the other inputs, plus a\n // funded tx that is not this vault's Pre-PegIn: nothing upstream binds\n // the funded tx to the vault, so a stale one reaches this check.\n if (actualHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `HTLC scriptPubKey mismatch at vout ${htlcVout}: reconstructed ` +\n `template expects ${expectedHtlcScriptPubKey}, funded tx carries ` +\n `${actualHtlcScriptPubKey}. Refund refused — the rebuilt HTLC does ` +\n `not commit to the funded output. Check the participant keys ` +\n `first: the vault provider, vault keeper and universal challenger ` +\n `keys must be the operation keys at the vault's frozen epochs ` +\n `(readRefundPrePeginContext, or readStampedParticipantKeys), not ` +\n `roster, indexer or current keys. Then check the hashlock at this ` +\n `vout and timelockRefund, and that the funded transaction is this ` +\n `vault's Pre-PegIn (its txid must equal the vault's on-chain ` +\n `prePeginTxHash).`,\n );\n }\n\n // Value cross-check (mirrors the script check above): the template's\n // HTLC value — derived by WASM from `pegInAmounts` via the protocol\n // formula — must equal the value the funded tx pays at this output.\n // A caller that hands the full HTLC output value (or any wrong amount)\n // as `pegInAmounts` would inflate the template value and trip this\n // guard, rather than silently signing a refund built from a template\n // that disagrees with the on-chain commitment.\n const actualHtlcValue = BigInt(htlcOutput.value);\n if (actualHtlcValue !== expectedHtlcValue) {\n throw new Error(\n `HTLC value mismatch at vout ${htlcVout}: reconstructed template ` +\n `expects ${expectedHtlcValue} sat, funded tx carries ` +\n `${actualHtlcValue} sat. Refund refused — the pegInAmounts vector ` +\n `does not match the on-chain commitment.`,\n );\n }\n\n const refundTx = Transaction.fromHex(refundTxHex);\n\n if (refundTx.version !== REFUND_TX_VERSION) {\n throw new Error(\n `Refund transaction version ${refundTx.version} does not match ` +\n `protocol version ${REFUND_TX_VERSION}.`,\n );\n }\n if (refundTx.locktime !== REFUND_TX_LOCKTIME) {\n throw new Error(\n `Refund transaction locktime ${refundTx.locktime} does not match ` +\n `protocol locktime ${REFUND_TX_LOCKTIME}.`,\n );\n }\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 if (refundInput.sequence !== prePeginParams.timelockRefund) {\n throw new Error(\n `Refund input sequence ${refundInput.sequence} does not match ` +\n `timelockRefund ${prePeginParams.timelockRefund}.`,\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: expectedHtlc.refundScript,\n controlBlock: expectedHtlc.refundControlBlock,\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n tapMerkleRoot: expectedHtlc.tapMerkleRoot,\n });\n\n // Output side: pin the single refund output to the depositor's own\n // BIP-86 P2TR address, mirroring the input-side pinning above. WASM\n // builds the refund output from the refund leaf's depositor key, so a\n // correct template always pays exactly one output back to the depositor.\n // Asserting it here means a malformed template (or a tampered WASM)\n // cannot redirect the reclaimed funds to a script the depositor does\n // not control.\n if (refundTx.outs.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 output, got ${refundTx.outs.length}`,\n );\n }\n const refundOutput = refundTx.outs[0];\n const expectedDepositorScriptPubKey = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(prePeginParams.depositorPubkey),\n ).toLowerCase();\n const actualRefundOutputScriptPubKey = uint8ArrayToHex(\n new Uint8Array(refundOutput.script),\n ).toLowerCase();\n if (actualRefundOutputScriptPubKey !== expectedDepositorScriptPubKey) {\n throw new Error(\n `Refund output scriptPubKey ${actualRefundOutputScriptPubKey} does not ` +\n `match the depositor's BIP-86 address ${expectedDepositorScriptPubKey}. ` +\n `Refund refused — the reclaimed funds would not return to the depositor.`,\n );\n }\n\n // Value: the single refund output must return the full HTLC value minus\n // exactly the requested fee. The refund is 1-in/1-out (asserted above), so\n // a value below `htlcValue - refundFee` means WASM applied a larger fee\n // than requested — the difference would be burned as miner fee. Pin it so\n // the depositor reclaims the expected amount, not a silently reduced one.\n const expectedRefundOutputValue = actualHtlcValue - refundFee;\n if (BigInt(refundOutput.value) !== expectedRefundOutputValue) {\n throw new Error(\n `Refund output value ${BigInt(refundOutput.value)} sat does not equal ` +\n `the HTLC value ${actualHtlcValue} sat minus the requested fee ` +\n `${refundFee} sat (expected ${expectedRefundOutputValue} sat). ` +\n `Refund refused — the reclaimed amount would be burned as excess fee.`,\n );\n }\n\n psbt.addOutput({\n script: refundOutput.script,\n value: refundOutput.value,\n });\n\n return { psbtHex: psbt.toHex() };\n } finally {\n fundedTx?.free();\n unfundedTx.free();\n }\n}\n","/**\n * Reclaim PSBT Builder Primitive\n *\n * Builds an unsigned PSBT that sweeps the depositor-claim reserve — PegIn\n * vout 1 — back to the depositor's own BIP-86 address.\n *\n * The reserve funds the depositor's `claim_tx`, their recourse if the vault\n * provider fails during peg-out. When the vault provider claims instead and\n * the depositor withdraws normally, nothing ever spends it. This primitive is\n * the only thing in the repository that can.\n *\n * Spend path: the single `<depositor> OP_CHECKSIG` tapleaf (see\n * ./depositorClaim). No timelock, no counterparty signature — the depositor's\n * Schnorr signature alone. That is also why the *caller* must gate: this\n * builder will happily sweep a reserve whose vault is still live, which would\n * permanently void the depositor's pre-signed recourse graph. Eligibility is\n * enforced upstream, in the service.\n *\n * @module primitives/psbt/reclaim\n */\n\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { DUST_THRESHOLD } from \"../../utils/fee/constants\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport {\n PEGIN_DEPOSITOR_CLAIM_VOUT,\n deriveDepositorClaimDescriptor,\n} from \"./depositorClaim\";\n\n/**\n * nVersion for the reclaim transaction. Plain v2, not TRUC: the reserve is only\n * offered once its PegIn is deeply confirmed, so the PegIn's nVersion-3\n * topology limits no longer constrain its children.\n */\nconst RECLAIM_TX_VERSION = 2;\n\n/**\n * nSequence for every reclaim input: RBF-enabled, no relative timelock. The\n * claim leaf carries no CSV, so this is a fee-bumping signal only.\n */\nconst RECLAIM_INPUT_SEQUENCE = 0xfffffffd;\n\n/**\n * Weight units of the reclaim transaction's skeleton — everything except the\n * inputs. Non-witness `version(4) + inCount(1) + outCount(1) + locktime(4) +\n * output(8 + 1 + 34)` = 53 B × 4, plus the 2 WU SegWit marker and flag.\n */\nconst RECLAIM_SKELETON_WEIGHT_UNITS = 214;\n\n/**\n * Weight units each script-path input adds. Non-witness `outpoint(36) +\n * scriptSigLen(1) + sequence(4)` = 41 B × 4 = 164, plus a witness of\n * `stackCount(1) + sig(1 + 64) + leafScript(1 + 34) + controlBlock(1 + 33)` =\n * 135 WU.\n *\n * Exact rather than conservative: every element is fixed-length here — a\n * 64-byte BIP-340 signature under SIGHASH_DEFAULT, the 34-byte leaf, and a\n * 33-byte control block with no merkle path.\n */\nconst RECLAIM_INPUT_WEIGHT_UNITS = 299;\n\n/** Weight units per virtual byte. */\nconst WEIGHT_UNITS_PER_VBYTE = 4;\n\n/**\n * Virtual size of an N-in/1-out reclaim transaction.\n *\n * `REFUND_VSIZE = 160` does not generalise to N inputs, and\n * `computePeginBaseFeeSats` is wrong for this shape entirely — its\n * `P2TR_INPUT_SIZE = 58` is a *key-path* input and under-fees a script-path\n * spend by roughly a quarter.\n *\n * N=1 → 129 vB; each additional input adds 75 vB.\n */\nexport function reclaimVsize(numInputs: number): number {\n if (!Number.isInteger(numInputs) || numInputs < 1) {\n throw new Error(\n `Reclaim input count must be a positive integer, got ${numInputs}.`,\n );\n }\n return Math.ceil(\n (RECLAIM_SKELETON_WEIGHT_UNITS +\n RECLAIM_INPUT_WEIGHT_UNITS * numInputs) /\n WEIGHT_UNITS_PER_VBYTE,\n );\n}\n\n/** Absolute fee in satoshis for an N-in/1-out reclaim at a given rate. */\nexport function estimateReclaimFeeSats(\n feeRateSatsVb: number,\n numInputs: number,\n): bigint {\n if (!Number.isFinite(feeRateSatsVb) || feeRateSatsVb <= 0) {\n throw new Error(\n `Reclaim fee rate must be a positive number, got ${feeRateSatsVb}.`,\n );\n }\n return BigInt(Math.ceil(feeRateSatsVb * reclaimVsize(numInputs)));\n}\n\n/** One depositor-claim reserve to sweep, with the material to bind it. */\nexport interface ReclaimReserve {\n /**\n * The contract's own copy of the depositor-signed PegIn transaction\n * (`VaultProtocolInfo.depositorSignedPeginTx`). Authoritative: its SegWit\n * txid equals the broadcast PegIn's, and its `outs[1]` carries the reserve's\n * script and value at no extra RPC cost.\n */\n depositorSignedPeginTxHex: string;\n /** Independent chain observation of `peginTxid:1` (esplora UTXO lookup). */\n observed: {\n /**\n * The outpoint the caller actually issued its chain lookup against, so the\n * observation below can be tied to the input this builder adds.\n *\n * Without it the script and value binds prove only that *some* UTXO has\n * this shape — the claim script is a pure function of the depositor key and\n * so is byte-identical across every vault they own, and the value is a pure\n * function of protocol parameters. Neither distinguishes one of the\n * depositor's vaults from another.\n *\n * Txid in display order, 64 hex chars, with or without `0x` prefix.\n */\n txid: string;\n /** Vout the lookup was issued against. Must be the claim vout. */\n vout: number;\n /** scriptPubKey hex, with or without `0x` prefix. */\n scriptPubKey: string;\n /** Output value in satoshis. */\n value: bigint;\n };\n /**\n * The reserve value recomputed from this vault's protocol parameters via\n * `computeMinClaimValue`. Bound so a doctored PegIn that agrees with itself\n * and with a compromised indexer still fails.\n */\n expectedValue: bigint;\n}\n\nexport interface BuildReclaimPsbtParams {\n /**\n * The **connected wallet's live** x-only pubkey, 64-char hex. Never the\n * indexer's `depositorBtcPubkey`: re-deriving from the live key is what\n * proves the wallet about to sign is the wallet that can spend, and rejects\n * the wrong-wallet case with an error instead of an unspendable broadcast.\n */\n depositorPubkey: string;\n /**\n * Reserves to sweep. An array so batching several vaults into one\n * transaction is a later change rather than a rewrite; today the app passes\n * exactly one.\n */\n inputs: ReclaimReserve[];\n /** Absolute fee in satoshis. The caller sizes it; see `reclaimVsize`. */\n feeSats: bigint;\n}\n\nexport interface BuildReclaimPsbtResult {\n /** PSBT hex ready for depositor signing. */\n psbtHex: string;\n /** Value of the single output — what the depositor actually receives. */\n outputValue: bigint;\n /** Sum of the swept reserves, before fee. */\n totalInputValue: bigint;\n}\n\n/**\n * Build the N-in/1-out reclaim PSBT.\n *\n * Every input is bound three ways before it reaches the PSBT: the contract's\n * PegIn bytes, the chain observation, and a JS re-derivation from the live\n * wallet key must agree on both script and value. Any disagreement throws.\n * The observation must also name the outpoint it was taken from, since script\n * and value alone repeat across all of a depositor's vaults.\n *\n * Binding the input to the *vault* that was asked for is a further step, and\n * it belongs to the service: it needs the vault id derivation, which is async.\n * See `services/reclaim/buildAndBroadcastReclaim`.\n *\n * @throws If `inputs` is empty, the fee is non-positive, any input fails its\n * outpoint, script or value bind, or the resulting output would be at or\n * below dust.\n */\nexport function buildReclaimPsbt(\n params: BuildReclaimPsbtParams,\n): BuildReclaimPsbtResult {\n const { depositorPubkey, inputs, feeSats } = params;\n\n if (inputs.length === 0) {\n throw new Error(\"Reclaim requires at least one input; got none.\");\n }\n if (feeSats <= 0n) {\n throw new Error(\n `Reclaim fee must be positive, got ${feeSats} sat. Refusing to build a ` +\n `transaction that would not relay.`,\n );\n }\n\n // One derivation, reused for every input's bind and for the destination.\n const descriptor = deriveDepositorClaimDescriptor(depositorPubkey);\n const expectedScriptPubKey = uint8ArrayToHex(\n new Uint8Array(descriptor.scriptPubKey),\n ).toLowerCase();\n\n const psbt = new Psbt();\n psbt.setVersion(RECLAIM_TX_VERSION);\n psbt.setLocktime(0);\n\n let totalInputValue = 0n;\n const seenOutpoints = new Set<string>();\n\n inputs.forEach((input, i) => {\n const peginTx = Transaction.fromHex(\n stripHexPrefix(input.depositorSignedPeginTxHex),\n );\n const peginTxid = peginTx.getId();\n\n const claimOut = peginTx.outs[PEGIN_DEPOSITOR_CLAIM_VOUT];\n if (!claimOut) {\n throw new Error(\n `PegIn ${peginTxid} has no output at vout ` +\n `${PEGIN_DEPOSITOR_CLAIM_VOUT} (tx has ${peginTx.outs.length}); ` +\n `there is no depositor-claim reserve to reclaim.`,\n );\n }\n\n // Bind 0: the observation is of *this* outpoint. Everything below compares\n // a script and a value, both of which repeat across every vault this\n // depositor owns under the same protocol parameters — so without this the\n // remaining binds cannot tell one of their vaults from another, and a\n // caller that resolved the wrong vault would sweep it with every check\n // passing. The independent source is the PegIn the PSBT is built from; the\n // esplora response cannot serve here because `getUtxoInfo` echoes back the\n // txid and vout it was called with rather than reading them from the body.\n const observedTxid = stripHexPrefix(input.observed.txid).toLowerCase();\n if (observedTxid !== peginTxid) {\n throw new Error(\n `Input ${i}: the observation is of ${observedTxid}, but this input ` +\n `spends PegIn ${peginTxid}. Reclaim refused — the reserve that was ` +\n `looked up is not the one being swept.`,\n );\n }\n if (input.observed.vout !== PEGIN_DEPOSITOR_CLAIM_VOUT) {\n throw new Error(\n `Input ${i}: the observation is of vout ${input.observed.vout}, but ` +\n `the depositor-claim reserve is at vout ` +\n `${PEGIN_DEPOSITOR_CLAIM_VOUT}. Reclaim refused.`,\n );\n }\n\n // Bind 1: the contract's PegIn bytes against the JS re-derivation from the\n // live wallet key. This is the assertion that proves the connected wallet\n // can actually spend the output we are about to sign for.\n const contractScriptPubKey = uint8ArrayToHex(\n new Uint8Array(claimOut.script),\n ).toLowerCase();\n if (contractScriptPubKey !== expectedScriptPubKey) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} pays ` +\n `${contractScriptPubKey}, but the connected wallet's depositor-claim ` +\n `script is ${expectedScriptPubKey}. Reclaim refused — this reserve ` +\n `belongs to a different wallet.`,\n );\n }\n\n // Bind 2: the independent chain observation must agree with both.\n const observedScriptPubKey = stripHexPrefix(\n input.observed.scriptPubKey,\n ).toLowerCase();\n if (observedScriptPubKey !== expectedScriptPubKey) {\n throw new Error(\n `Input ${i}: the observed UTXO ${peginTxid}:${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `pays ${observedScriptPubKey}, expected ${expectedScriptPubKey}. ` +\n `Reclaim refused — chain state disagrees with the contract's PegIn.`,\n );\n }\n\n // Value bind, same three ways.\n const contractValue = BigInt(claimOut.value);\n if (contractValue !== input.observed.value) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `carries ${contractValue} sat, but the observed UTXO carries ` +\n `${input.observed.value} sat. Reclaim refused.`,\n );\n }\n if (contractValue !== input.expectedValue) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `carries ${contractValue} sat, but this vault's parameters compute a ` +\n `depositor-claim value of ${input.expectedValue} sat. Reclaim refused.`,\n );\n }\n\n // A batch that names the same vault twice would otherwise double-count the\n // swept total and then fail deep inside bitcoinjs. Reject it here, where\n // the message can say which input is the duplicate.\n const outpoint = `${peginTxid}:${PEGIN_DEPOSITOR_CLAIM_VOUT}`;\n if (seenOutpoints.has(outpoint)) {\n throw new Error(\n `Input ${i} repeats outpoint ${outpoint}, which is already being ` +\n `swept by an earlier input. Reclaim refused.`,\n );\n }\n seenOutpoints.add(outpoint);\n\n totalInputValue += contractValue;\n\n psbt.addInput({\n hash: peginTxid,\n index: PEGIN_DEPOSITOR_CLAIM_VOUT,\n sequence: RECLAIM_INPUT_SEQUENCE,\n witnessUtxo: { script: claimOut.script, value: claimOut.value },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: descriptor.leafScript,\n controlBlock: descriptor.controlBlock,\n },\n ],\n tapInternalKey: descriptor.internalKey,\n });\n });\n\n if (feeSats >= totalInputValue) {\n throw new Error(\n `Reclaim fee ${feeSats} sat is not less than the swept total ` +\n `${totalInputValue} sat. Refusing to build a transaction with no output.`,\n );\n }\n\n const outputValue = totalInputValue - feeSats;\n if (outputValue <= DUST_THRESHOLD) {\n throw new Error(\n `Reclaim output ${outputValue} sat is at or below the dust threshold ` +\n `${DUST_THRESHOLD} sat. The reserve is not at risk — it stays where it ` +\n `is until fee rates fall.`,\n );\n }\n\n const destination = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(depositorPubkey),\n );\n psbt.addOutput({\n script: Buffer.from(hexToUint8Array(destination)),\n value: Number(outputValue),\n });\n\n return { psbtHex: psbt.toHex(), outputValue, totalInputValue };\n}\n","/**\n * Finalize a Taproot script-path spend from the PSBT *we* built, using only the\n * verified signatures the wallet returned.\n *\n * Why this exists. The obvious shape — hand the wallet's PSBT to\n * `finalizeAllInputs()` — puts wallet-controlled bytes on the trust path even\n * when the signature itself has been verified.\n * `assertPsbtUnsignedTxMatches` deliberately pins only the unsigned\n * transaction and skips per-input metadata, so `tapLeafScript`, `controlBlock`\n * and `tapKeySig` all survive from the wallet's response untouched. And\n * bitcoinjs-lib checks key-spend first (`src/psbt.js`, `_finalizeTaprootInput`:\n * \"Check key spend first. Increased privacy and reduced block space.\"), so a\n * returned `tapKeySig` wins outright and `tapScriptSig` is never consulted.\n * Every output the depositor-claim reserve and the HTLC refund spend from uses\n * a NUMS internal key, so the resulting key-path witness cannot satisfy the\n * script — the transaction is rejected at broadcast, after a wallet prompt the\n * depositor cannot make sense of.\n *\n * Verifying and then discarding the wallet's PSBT closes that off structurally\n * rather than detecting it afterwards, and it makes the code match what\n * `verifyScriptPathSchnorrSignature` already documents: \"only the 64-byte\n * signature comes from the wallet\".\n *\n * @module tbv/core/primitives/psbt/finalizeScriptPathWithSignatures\n */\n\nimport { Psbt } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { X_ONLY_PUBKEY_HEX_LEN } from \"../../utils/validation\";\nimport {\n SCHNORR_SIG_HEX_LEN,\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\nimport { computeTapLeafHash } from \"../utils/taproot\";\n\nexport interface FinalizeScriptPathWithSignaturesParams {\n /**\n * Hex of the PSBT built locally and sent to the wallet — the sole source of\n * every per-input field. NOT the wallet-returned PSBT.\n */\n requestedPsbtHex: string;\n /**\n * Verified 64-byte Schnorr signatures, one per input, index-aligned with the\n * PSBT's inputs. Each must already have passed\n * `assertScriptPathSchnorrSignature` — this function does not re-verify them,\n * it only decides which bytes are allowed to reach the witness.\n */\n signaturesHex: readonly string[];\n /** X-only pubkey (64 hex chars) the signatures are attributed to. */\n signerXOnlyPubkeyHex: string;\n}\n\n/**\n * Attach `signaturesHex` to the locally built PSBT's script-path inputs,\n * finalize, and return the extracted transaction hex.\n *\n * @throws If the signature count does not match the input count, any signature\n * or the signer key is malformed, any input does not carry exactly one\n * tapscript leaf at the expected leaf version, any input already carries a\n * key-path signature, or bitcoinjs-lib cannot finalize.\n */\nexport function finalizeScriptPathWithSignatures(\n params: FinalizeScriptPathWithSignaturesParams,\n): string {\n const { requestedPsbtHex, signaturesHex, signerXOnlyPubkeyHex } = params;\n\n const signerXOnly = stripHexPrefix(signerXOnlyPubkeyHex);\n if (signerXOnly.length !== X_ONLY_PUBKEY_HEX_LEN) {\n throw new Error(\n `Signer x-only pubkey must be ${X_ONLY_PUBKEY_HEX_LEN} hex chars ` +\n `(32 bytes), got ${signerXOnly.length}.`,\n );\n }\n const signerPubkey = Buffer.from(hexToUint8Array(signerXOnly));\n\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (signaturesHex.length !== psbt.data.inputs.length) {\n throw new Error(\n `Cannot finalize: got ${signaturesHex.length} signature(s) for ` +\n `${psbt.data.inputs.length} input(s). Every input must be signed — ` +\n `refusing to broadcast a partially signed transaction.`,\n );\n }\n\n psbt.data.inputs.forEach((input, inputIndex) => {\n // Our own builders never produce a key-path signature for these spends.\n // If one is present the PSBT is not the one we built, which would defeat\n // the whole point of finalizing locally.\n if (input.tapKeySig) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} of the locally built PSBT ` +\n `carries a key-path signature. These outputs are script-path only.`,\n );\n }\n\n const tapLeafScripts = input.tapLeafScript;\n if (!tapLeafScripts || tapLeafScripts.length !== 1) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} must have exactly one ` +\n `tapLeafScript, got ${tapLeafScripts?.length ?? 0}.`,\n );\n }\n const leaf = tapLeafScripts[0];\n if (leaf.leafVersion !== TAPSCRIPT_LEAF_VERSION) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} tapLeafScript has leaf version ` +\n `0x${leaf.leafVersion.toString(16)}, expected ` +\n `0x${TAPSCRIPT_LEAF_VERSION.toString(16)}.`,\n );\n }\n\n const signatureRaw = stripHexPrefix(signaturesHex[inputIndex]);\n if (signatureRaw.length !== SCHNORR_SIG_HEX_LEN) {\n throw new Error(\n `Signature for input ${inputIndex} must be ${SCHNORR_SIG_HEX_LEN} hex ` +\n `chars (64 bytes), got ${signatureRaw.length}.`,\n );\n }\n\n psbt.updateInput(inputIndex, {\n tapScriptSig: [\n {\n pubkey: signerPubkey,\n leafHash: computeTapLeafHash(leaf.leafVersion, leaf.script),\n signature: Buffer.from(hexToUint8Array(signatureRaw)),\n },\n ],\n });\n });\n\n // With no tapKeySig anywhere, bitcoinjs takes the script-path branch for\n // every input and builds `[signature, leafScript, controlBlock]` from the\n // leaf we supplied.\n psbt.finalizeAllInputs();\n\n return psbt.extractTransaction().toHex();\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 \"../../wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction, payments } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n getNetwork,\n hexToUint8Array,\n inputTxidHex,\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\nimport {\n ASSERT_PAYOUT_OUTPUT_INDEX,\n CHALLENGE_ASSERT_OUTPUT_CONNECTOR_INDEX,\n NOPAYOUT_ASSERT_INPUT_SEQUENCE,\n NOPAYOUT_INPUT_COUNT,\n NOPAYOUT_TX_LOCKTIME,\n NOPAYOUT_TX_VERSION,\n} from \"./constants\";\n\n/** Largest `timelockChallengeAssert` the protocol accepts (a Rust `NonZeroU16`). */\nconst MAX_TIMELOCK_CHALLENGE_ASSERT = 0xffff;\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}], used verbatim — derive them from the parent txs */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/**\n * Validate that a NoPayout transaction pays to the challenger via the\n * protocol-defined output structure: a single BIP-86 P2TR output derived from\n * the challenger's x-only pubkey.\n *\n * Mirrors the per-role payout output validation now inlined in\n * `buildPayoutPsbt` for the NoPayout path, where the sink is fixed by the\n * protocol rather than read from on-chain registration\n * (see `crates/vault/src/transactions/nopayout.rs::NoPayoutTx::new`).\n *\n * @param noPayoutTxHex - Raw NoPayout transaction hex\n * @param challengerPubkey - Challenger's x-only public key (hex)\n * @param network - Bitcoin network used to derive the P2TR scriptPubKey\n * @throws If the transaction does not have exactly one output\n * @throws If the single output's scriptPubKey does not equal the BIP-86 P2TR\n * scriptPubKey for the challenger\n */\nexport function assertNoPayoutOutputMatchesChallenger(\n noPayoutTxHex: string,\n challengerPubkey: string,\n network: Network,\n): void {\n const tx = Transaction.fromHex(stripHexPrefix(noPayoutTxHex));\n\n if (tx.outs.length !== 1) {\n throw new Error(\n `NoPayout transaction must have exactly 1 output, got ${tx.outs.length}`,\n );\n }\n\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(challengerPubkey));\n const { output: expectedScript } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!expectedScript) {\n throw new Error(\n \"Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation\",\n );\n }\n\n if (!tx.outs[0].script.equals(expectedScript)) {\n throw new Error(\n \"NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address\",\n );\n }\n}\n\n/**\n * Parameters for {@link assertCanonicalNoPayoutShape}\n */\nexport interface AssertCanonicalNoPayoutShapeParams {\n /** The NoPayout transaction the VP supplied */\n noPayoutTx: Transaction;\n /** Authoritative Assert txid (display hex) */\n assertTxid: string;\n /** Canonical ChallengeAssertX txid (display hex) */\n challengeAssertXTxid: string;\n /** Canonical ChallengeAssertY txid (display hex) */\n challengeAssertYTxid: string;\n /** ChallengeAssert CSV timelock in blocks (offchain param `timelockChallengeAssert`) */\n timelockChallengeAssert: number;\n /** Values of Assert:0, ChallengeAssertX:0 and ChallengeAssertY:0, in input order */\n prevoutValues: readonly [number, number, number];\n}\n\n/**\n * Require a VP-supplied NoPayout to have the shape btc-vault `NoPayoutTx::new`\n * builds over the canonical parents\n * (`crates/vault/src/transactions/nopayout.rs:148-209` @ b534ff9e): version 2,\n * locktime 0, and exactly the inputs Assert:0, ChallengeAssertX:0 and\n * ChallengeAssertY:0, in that order, with sequences `0xffffffff`, `t`, `t`.\n *\n * The depositor's signature commits to every one of these fields. The\n * challenge window itself is enforced by the ChallengeAssert output connector's\n * NoPayout leaf (`<challenger> CHECKSIGVERIFY <t> CSV`), which the txid binding\n * of both parents pins: a NoPayout with a shorter or disabled sequence, or\n * below version 2, fails that CSV and is invalid rather than early. Pinning the\n * inputs, sequences, version and locktime to btc-vault's layout keeps the\n * signature on a NoPayout that satisfies that CSV. The output value is not\n * pinned to btc-vault's (the inputs minus its fee); it is only required not to\n * exceed the inputs, since a larger output could never be valid. The output\n * script is checked by {@link assertNoPayoutOutputMatchesChallenger}.\n *\n * @param params - The supplied NoPayout and the authoritative parents\n * @throws If any input, sequence, version or locktime differs from the\n * canonical layout, the timelock is not a valid relative timelock, or the\n * output value exceeds the inputs\n */\nexport function assertCanonicalNoPayoutShape(\n params: AssertCanonicalNoPayoutShapeParams,\n): void {\n const { noPayoutTx, timelockChallengeAssert } = params;\n if (\n !Number.isInteger(timelockChallengeAssert) ||\n timelockChallengeAssert < 1 ||\n timelockChallengeAssert > MAX_TIMELOCK_CHALLENGE_ASSERT\n ) {\n throw new Error(\n `timelockChallengeAssert must be an integer in 1..${MAX_TIMELOCK_CHALLENGE_ASSERT}, got ${timelockChallengeAssert}`,\n );\n }\n if (noPayoutTx.version !== NOPAYOUT_TX_VERSION) {\n throw new Error(\n `NoPayout version must be ${NOPAYOUT_TX_VERSION}, got ${noPayoutTx.version}`,\n );\n }\n if (noPayoutTx.locktime !== NOPAYOUT_TX_LOCKTIME) {\n throw new Error(\n `NoPayout locktime must be ${NOPAYOUT_TX_LOCKTIME}, got ${noPayoutTx.locktime}`,\n );\n }\n if (noPayoutTx.ins.length !== NOPAYOUT_INPUT_COUNT) {\n throw new Error(\n `NoPayout must have exactly ${NOPAYOUT_INPUT_COUNT} inputs, got ${noPayoutTx.ins.length}`,\n );\n }\n\n const expectedInputs = [\n {\n label: \"Assert\",\n txid: params.assertTxid,\n vout: ASSERT_PAYOUT_OUTPUT_INDEX,\n sequence: NOPAYOUT_ASSERT_INPUT_SEQUENCE,\n },\n {\n label: \"ChallengeAssertX\",\n txid: params.challengeAssertXTxid,\n vout: CHALLENGE_ASSERT_OUTPUT_CONNECTOR_INDEX,\n sequence: timelockChallengeAssert,\n },\n {\n label: \"ChallengeAssertY\",\n txid: params.challengeAssertYTxid,\n vout: CHALLENGE_ASSERT_OUTPUT_CONNECTOR_INDEX,\n sequence: timelockChallengeAssert,\n },\n ];\n expectedInputs.forEach((expected, i) => {\n const input = noPayoutTx.ins[i];\n const txid = inputTxidHex(input);\n if (txid !== expected.txid || input.index !== expected.vout) {\n throw new Error(\n `NoPayout input ${i} must spend ${expected.label} ${expected.txid}:${expected.vout}, got ${txid}:${input.index}`,\n );\n }\n if (input.sequence !== expected.sequence) {\n throw new Error(\n `NoPayout input ${i} (${expected.label}) sequence must be ${expected.sequence}, got ${input.sequence}`,\n );\n }\n });\n\n const inputValue = params.prevoutValues.reduce((sum, v) => sum + v, 0);\n const outputValue = noPayoutTx.outs.reduce((sum, out) => sum + out.value, 0);\n if (outputValue > inputValue) {\n throw new Error(\n `NoPayout output value ${outputValue} exceeds its inputs (${inputValue} sats)`,\n );\n }\n}\n","/**\n * ChallengeAssert PSBT Builder\n *\n * Builds an unsigned PSBT for a ChallengeAssert transaction. ChallengeAssert\n * is split across two single-input transactions — ChallengeAssertX (spends the\n * challenger's ConnectorX Assert output) and ChallengeAssertY (spends\n * ConnectorY). This builder handles one such transaction.\n *\n * The protocol collects no claimer signature on ChallengeAssert — the\n * challenger signs it at broadcast (btc-vault `tx_graph/challenger.rs`). The\n * PSBT builder exists for tooling that reconstructs the graph; it is not on\n * the depositor presign path (`signDepositorGraph` signs Payout + NoPayout\n * only). {@link assertChallengeAssertIsCanonical} is on that path: NoPayout\n * spends output 0 of both ChallengeAsserts, so they are bound before signing.\n *\n * @module primitives/psbt/challengeAssert\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — ChallengeAssertX / ChallengeAssertY\n */\n\nimport {\n type ChallengeAssertConnectorParams,\n getChallengeAssertScriptInfo,\n tapInternalPubkey,\n} from \"../../wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n hexToUint8Array,\n inputTxidHex,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\nimport {\n ASSERT_FIRST_CHALLENGER_CONNECTOR_VOUT,\n CHALLENGE_ASSERT_ANCHOR_VALUE_SATS,\n CHALLENGE_ASSERT_INPUT_SEQUENCE,\n CHALLENGE_ASSERT_TX_LOCKTIME,\n CHALLENGE_ASSERT_TX_VERSION,\n} from \"./constants\";\n\n/**\n * Parameters for building a ChallengeAssert PSBT\n */\nexport interface ChallengeAssertParams {\n /** ChallengeAssert transaction hex (unsigned) */\n challengeAssertTxHex: string;\n /** Authoritative Assert transaction hex — every input must spend an Assert output */\n assertTxHex: string;\n /** Per-input connector params (one per input/segment, determines the taproot script) */\n connectorParamsPerInput: ChallengeAssertConnectorParams[];\n}\n\n/**\n * Build unsigned ChallengeAssert PSBT.\n *\n * Each input has its own taproot script derived from its connector params; the\n * number of connector params must match the transaction's input count.\n * Every prevout is derived from the authoritative\n * Assert transaction, never trusted from external input.\n *\n * @param params - ChallengeAssert parameters\n * @returns Unsigned PSBT hex ready for signing\n *\n * @throws If the number of connector params does not match the number of inputs\n * @throws If any input does not reference assertTxHex\n * @throws If any referenced Assert output is missing\n * @throws If two inputs reference the same Assert output index\n */\nexport async function buildChallengeAssertPsbt(\n params: ChallengeAssertParams,\n): Promise<string> {\n const challengeAssertTx = Transaction.fromHex(\n stripHexPrefix(params.challengeAssertTxHex),\n );\n const assertTx = Transaction.fromHex(stripHexPrefix(params.assertTxHex));\n const assertTxid = assertTx.getId();\n\n if (params.connectorParamsPerInput.length !== challengeAssertTx.ins.length) {\n throw new Error(\n `Expected ${challengeAssertTx.ins.length} connector params, got ${params.connectorParamsPerInput.length}`,\n );\n }\n\n const seenAssertOutputs = new Set<number>();\n for (let i = 0; i < challengeAssertTx.ins.length; i++) {\n const input = challengeAssertTx.ins[i];\n const inputTxid = inputTxidHex(input);\n if (inputTxid !== assertTxid) {\n throw new Error(\n `ChallengeAssert input ${i} must spend an Assert output. ` +\n `Expected txid ${assertTxid}, got ${inputTxid}`,\n );\n }\n if (!assertTx.outs[input.index]) {\n throw new Error(\n `Assert output ${input.index} not found for ChallengeAssert input ${i} (txid: ${assertTxid})`,\n );\n }\n if (seenAssertOutputs.has(input.index)) {\n throw new Error(\n `ChallengeAssert input ${i} duplicates Assert output index ${input.index}`,\n );\n }\n seenAssertOutputs.add(input.index);\n }\n\n const scriptInfos = await Promise.all(\n params.connectorParamsPerInput.map((cp) => getChallengeAssertScriptInfo(cp)),\n );\n\n const psbt = new Psbt();\n psbt.setVersion(challengeAssertTx.version);\n psbt.setLocktime(challengeAssertTx.locktime);\n\n for (let i = 0; i < challengeAssertTx.ins.length; i++) {\n const input = challengeAssertTx.ins[i];\n const assertPrevOut = assertTx.outs[input.index];\n\n const { script, controlBlock } = scriptInfos[i];\n const scriptBytes = hexToUint8Array(script);\n const controlBlockBytes = hexToUint8Array(controlBlock);\n\n psbt.addInput({\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: assertPrevOut.script,\n value: assertPrevOut.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n }\n\n for (const output of challengeAssertTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/** Which of a challenger's two ChallengeAssert transactions. */\nexport type ChallengeAssertHalf = \"X\" | \"Y\";\n\n/**\n * Parameters for {@link assertChallengeAssertIsCanonical}\n */\nexport interface AssertChallengeAssertIsCanonicalParams {\n /** The ChallengeAssertX or ChallengeAssertY transaction the VP supplied */\n challengeAssertTx: Transaction;\n /** Authoritative Assert transaction, already bound to the depositor's Claim */\n assertTx: Transaction;\n /** Which half `challengeAssertTx` claims to be */\n half: ChallengeAssertHalf;\n /** The challenger's index in the hex-sorted local ∪ universal challenger set */\n challengerIndex: number;\n /** Number of local plus universal challengers (K) */\n challengerCount: number;\n /** The challenger's x-only public key (hex) */\n challengerPubkey: string;\n /** ChallengeAssert output connector scriptPubKey for this challenger (hex) */\n outputConnectorScriptPubKey: string;\n}\n\n/**\n * Require a VP-supplied ChallengeAssertX/Y to be exactly the transaction\n * btc-vault builds for this challenger from the authoritative Assert.\n *\n * NoPayout spends output 0 of both ChallengeAsserts, and the depositor's\n * NoPayout signature commits to their txids. The protocol collects no claimer\n * signature on a ChallengeAssert, so that commitment is all that forces a\n * challenger to broadcast the canonical one. A parent that does not spend this\n * Assert, or whose output 0 is not the timelocked connector, would let a\n * colluding challenger spend Assert:0 through NoPayout without the dispute\n * that the claimer can answer with WronglyChallenged.\n *\n * The transaction is fully determined by the Assert, the challenger's sorted\n * index and the connector script, so it is rebuilt here and compared by txid,\n * which covers every non-witness byte.\n *\n * @param params - The supplied transaction and the authoritative inputs\n * @throws If the challenger index is out of range, the Assert lacks the\n * connector output, or the supplied transaction is not the canonical one\n */\nexport function assertChallengeAssertIsCanonical(\n params: AssertChallengeAssertIsCanonicalParams,\n): void {\n const expectedTxid = buildCanonicalChallengeAssertTx(params).getId();\n const suppliedTxid = params.challengeAssertTx.getId();\n if (suppliedTxid !== expectedTxid) {\n throw new Error(\n `ChallengeAssert${params.half} (challenger ${params.challengerPubkey}) is not the ` +\n `canonical transaction for this Assert: expected txid ${expectedTxid}, got ${suppliedTxid}`,\n );\n }\n}\n\n/**\n * Mirror btc-vault `construct_challenge_assert` + `build_challenge_assert_tx`\n * (`crates/vault/src/transactions/challenge_assert.rs:49-96,147-221` @ b534ff9e).\n */\nfunction buildCanonicalChallengeAssertTx(\n params: AssertChallengeAssertIsCanonicalParams,\n): Transaction {\n const { assertTx, half, challengerIndex, challengerCount } = params;\n if (\n !Number.isInteger(challengerIndex) ||\n challengerIndex < 0 ||\n challengerIndex >= challengerCount\n ) {\n throw new Error(\n `ChallengeAssert${half} challenger index ${challengerIndex} is outside 0..${challengerCount - 1}`,\n );\n }\n const vout =\n ASSERT_FIRST_CHALLENGER_CONNECTOR_VOUT +\n (half === \"Y\" ? challengerCount : 0) +\n challengerIndex;\n const connectorOutput = assertTx.outs[vout];\n if (!connectorOutput) {\n throw new Error(\n `Assert has no output ${vout} for the ChallengeAssert${half} of challenger index ${challengerIndex}`,\n );\n }\n const outputConnectorValue =\n connectorOutput.value - CHALLENGE_ASSERT_ANCHOR_VALUE_SATS;\n if (outputConnectorValue < 0) {\n throw new Error(\n `Assert output ${vout} (${connectorOutput.value} sats) cannot fund the ` +\n `${CHALLENGE_ASSERT_ANCHOR_VALUE_SATS}-sat ChallengeAssert${half} anchor`,\n );\n }\n\n const tx = new Transaction();\n tx.version = CHALLENGE_ASSERT_TX_VERSION;\n tx.locktime = CHALLENGE_ASSERT_TX_LOCKTIME;\n tx.addInput(assertTx.getHash(), vout, CHALLENGE_ASSERT_INPUT_SEQUENCE);\n tx.addOutput(\n Buffer.from(hexToUint8Array(params.outputConnectorScriptPubKey)),\n outputConnectorValue,\n );\n tx.addOutput(\n Buffer.from(\n hexToUint8Array(deriveBip86ScriptPubKeyHex(params.challengerPubkey)),\n ),\n CHALLENGE_ASSERT_ANCHOR_VALUE_SATS,\n );\n return tx;\n}\n"],"names":["U64_MAX","assertPositiveBigintArray","values","label","value","index","buildRefundPsbt","params","WasmPrePeginTx","loadTbvWasm","prePeginParams","fundedPrePeginTxHex","htlcVout","refundFee","hashlock","normalizedAuthAnchorHash","normalizeAuthAnchorHash","unfundedTx","fundedTx","wasmHtlcScriptPubKey","expectedHtlc","deriveExpectedPrePeginHtlc","expectedHtlcScriptPubKey","expectedHtlcValue","refundTxHex","cleanPrePeginHex","prePeginTx","Transaction","htlcOutput","actualHtlcScriptPubKey","uint8ArrayToHex","actualHtlcValue","refundTx","REFUND_TX_VERSION","REFUND_TX_LOCKTIME","refundInput","prePeginTxid","refundInputTxid","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","refundOutput","expectedDepositorScriptPubKey","stripHexPrefix","deriveBip86ScriptPubKeyHex","actualRefundOutputScriptPubKey","expectedRefundOutputValue","RECLAIM_TX_VERSION","RECLAIM_INPUT_SEQUENCE","RECLAIM_SKELETON_WEIGHT_UNITS","RECLAIM_INPUT_WEIGHT_UNITS","WEIGHT_UNITS_PER_VBYTE","reclaimVsize","numInputs","estimateReclaimFeeSats","feeRateSatsVb","buildReclaimPsbt","depositorPubkey","inputs","feeSats","descriptor","deriveDepositorClaimDescriptor","expectedScriptPubKey","totalInputValue","seenOutpoints","input","i","peginTx","peginTxid","claimOut","PEGIN_DEPOSITOR_CLAIM_VOUT","observedTxid","contractScriptPubKey","observedScriptPubKey","contractValue","outpoint","outputValue","DUST_THRESHOLD","destination","hexToUint8Array","finalizeScriptPathWithSignatures","requestedPsbtHex","signaturesHex","signerXOnlyPubkeyHex","signerXOnly","X_ONLY_PUBKEY_HEX_LEN","signerPubkey","inputIndex","tapLeafScripts","leaf","signatureRaw","SCHNORR_SIG_HEX_LEN","computeTapLeafHash","MAX_TIMELOCK_CHALLENGE_ASSERT","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","prevout","inputData","output","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","expectedScript","payments","getNetwork","assertCanonicalNoPayoutShape","timelockChallengeAssert","NOPAYOUT_TX_VERSION","NOPAYOUT_TX_LOCKTIME","NOPAYOUT_INPUT_COUNT","ASSERT_PAYOUT_OUTPUT_INDEX","NOPAYOUT_ASSERT_INPUT_SEQUENCE","CHALLENGE_ASSERT_OUTPUT_CONNECTOR_INDEX","expected","txid","inputTxidHex","inputValue","sum","v","out","buildChallengeAssertPsbt","challengeAssertTx","assertTx","assertTxid","seenAssertOutputs","inputTxid","scriptInfos","cp","getChallengeAssertScriptInfo","assertPrevOut","script","controlBlock","assertChallengeAssertIsCanonical","expectedTxid","buildCanonicalChallengeAssertTx","suppliedTxid","half","challengerIndex","challengerCount","vout","ASSERT_FIRST_CHALLENGER_CONNECTOR_VOUT","connectorOutput","outputConnectorValue","CHALLENGE_ASSERT_ANCHOR_VALUE_SATS","CHALLENGE_ASSERT_TX_VERSION","CHALLENGE_ASSERT_TX_LOCKTIME","CHALLENGE_ASSERT_INPUT_SEQUENCE"],"mappings":";;;;;;;;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bv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/psbt/reclaim.ts","../src/tbv/core/primitives/psbt/finalizeScriptPathWithSignatures.ts","../src/tbv/core/primitives/psbt/noPayout.ts","../src/tbv/core/primitives/psbt/challengeAssert.ts"],"sourcesContent":["/**\n * Runtime guard for satoshi amounts crossing into the WASM FFI boundary.\n *\n * `new BigUint64Array(values)` is the only way satoshi amounts are handed to\n * the constructor, and a runtime cast (`as readonly bigint[]`) lets a caller\n * pass a non-bigint or non-positive element that `BigUint64Array` would either\n * reject cryptically or, in its length-arg form, silently zero-fill. Values\n * above the u64 maximum are worse still: `BigUint64Array` wraps them mod 2^64\n * without complaint, turning an oversized amount into a small one.\n * {@link assertPositiveBigintArray} validates such inputs before the\n * typed-array construction.\n *\n * Mirrors the `assertPositiveBigintArray` half of `value-guards.ts` in\n * `@babylonlabs-io/babylon-tbv-rust-wasm`; that one function is pinned to the\n * engine's source copy by `__tests__/value-guards.test.ts`. The engine's other\n * guard, `assertWasmBigint`, has no counterpart here: the engine applies it to\n * its own WASM return values before they reach this package.\n */\n\n/** Largest value BigUint64Array stores without wrapping mod 2^64 (2^64 − 1). */\nconst U64_MAX = (1n << 64n) - 1n;\n\n/**\n * Assert a value is a non-empty array of strictly-positive `bigint`s and return\n * it narrowed, ready to feed into `new BigUint64Array(...)`.\n *\n * @param values - The candidate array of satoshi amounts.\n * @param label - Human-readable name used in the thrown error.\n * @throws If `values` is not an array, is empty, or contains any element that is\n * not a `bigint`, is not strictly greater than 0, or exceeds the u64 maximum\n * (which `BigUint64Array` would otherwise wrap mod 2^64).\n */\nexport function assertPositiveBigintArray(\n values: unknown,\n label: string,\n): bigint[] {\n if (!Array.isArray(values)) {\n throw new Error(\n `${label} must be an array of positive bigints (got ${typeof values}).`,\n );\n }\n if (values.length === 0) {\n throw new Error(`${label} must not be empty.`);\n }\n values.forEach((value, index) => {\n if (typeof value !== \"bigint\") {\n throw new Error(\n `${label}[${index}] must be a bigint (got ${typeof value}); ` +\n `refusing to feed it into satoshi math.`,\n );\n }\n if (value <= 0n) {\n throw new Error(`${label}[${index}] must be > 0 (got ${value}).`);\n }\n if (value > U64_MAX) {\n throw new Error(\n `${label}[${index}] must fit in a u64 (got ${value}); ` +\n `refusing to feed it into satoshi math.`,\n );\n }\n });\n return values as bigint[];\n}\n","/**\n * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\nimport { loadTbvWasm, tapInternalPubkey } from \"../../wasm\";\nimport { assertPositiveBigintArray } from \"../../wasm/value-guards\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport { deriveExpectedPrePeginHtlc } from \"./assertWasmPeginSizing\";\nimport { REFUND_TX_LOCKTIME, REFUND_TX_VERSION } from \"./constants\";\nimport { normalizeAuthAnchorHash, type PrePeginParams } from \"./pegin\";\n\n/**\n * Parameters for building a refund PSBT\n */\nexport interface BuildRefundPsbtParams {\n /** Same PrePeginParams used when the original Pre-PegIn tx was created */\n prePeginParams: PrePeginParams;\n /** Funded Pre-PegIn transaction hex (the tx whose HTLC output is being refunded) */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output in the Pre-PegIn transaction */\n htlcVout: number;\n /** Transaction fee in satoshis for the refund transaction */\n refundFee: bigint;\n /** SHA256 hash commitment for the HTLC (64 hex chars, no 0x prefix) */\n hashlock: string;\n}\n\n/**\n * Result of building a refund PSBT\n */\nexport interface BuildRefundPsbtResult {\n /** PSBT hex ready for depositor signing */\n psbtHex: string;\n}\n\n/**\n * Build a PSBT for signing the refund transaction.\n *\n * The refund transaction spends the Pre-PegIn HTLC output via leaf 1\n * (the refund script: `<depositorPubkey> OP_CHECKSIGVERIFY <timelockRefund>\n * OP_CHECKSEQUENCEVERIFY` — btc-vault `connectors/prepegin_htlc.rs`\n * `generate_refund_script`).\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 const { WasmPrePeginTx } = await loadTbvWasm();\n\n const { prePeginParams, fundedPrePeginTxHex, htlcVout, refundFee, hashlock } =\n params;\n\n // The 14th positional arg `auth_anchor_hash` is `Option<String>` in\n // the Rust WASM constructor (the 9th arg `min_pegin_fee_rate` requires\n // the two-rate constructor from btc-vault #1930). Production peg-ins\n // (PeginManager) always commit an OP_RETURN <PUSH32 SHA256(authAnchor)>\n // output at `vout = hashlocks.length`; the unfunded template must\n // include it so `fromFundedTransaction` aligns with the funded tx.\n // Normalize identically to the peg-in primitives (`0x` strip,\n // lowercase, length/charset validation) so a direct primitive caller\n // reusing successful peg-in params doesn't hand unnormalized bytes to\n // WASM. Pass `undefined` for legacy non-auth-anchored Pre-PegIns.\n const normalizedAuthAnchorHash = normalizeAuthAnchorHash(\n prePeginParams.authAnchorHash,\n );\n // Reconstruct the template under the same graph version the Pre-PegIn\n // was originally built with (the vault's stamped vaultCoreVersion).\n const unfundedTx = new WasmPrePeginTx(\n prePeginParams.vaultCoreVersion,\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(\n assertPositiveBigintArray(prePeginParams.pegInAmounts, \"pegInAmounts\"),\n ),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.minPeginFeeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n normalizedAuthAnchorHash,\n );\n\n let fundedTx: typeof unfundedTx | null = null;\n try {\n // Two cross-checks bind the rebuilt HTLC before anything is signed.\n // First, the WASM template against an independent TypeScript derivation:\n // a disagreement means the engine diverged, or that the caller's\n // `hashlock` differs from `prePeginParams.hashlocks[htlcVout]` (the\n // template reads the array, the derivation reads `hashlock`). Then\n // (below) that scriptPubKey against the funded tx's output: a\n // disagreement there means the params do not describe the HTLC on chain,\n // and signing would produce a refund that cannot spend it. Never sign a\n // refund whose template does not match the on-chain output bytes.\n const wasmHtlcScriptPubKey = unfundedTx\n .getHtlcScriptPubKey(htlcVout)\n .toLowerCase();\n const expectedHtlc = deriveExpectedPrePeginHtlc(prePeginParams, hashlock);\n const expectedHtlcScriptPubKey = expectedHtlc.scriptPubKey.toString(\"hex\");\n if (wasmHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `WASM HTLC scriptPubKey ${wasmHtlcScriptPubKey} does not match the ` +\n `independently derived scriptPubKey ${expectedHtlcScriptPubKey}.`,\n );\n }\n // The reconstructed template's HTLC output value at `htlcVout`,\n // sized by WASM from the supplied `pegInAmounts` via the protocol\n // formula `htlcValue = peginAmount + depositorClaimValue + p2aAnchorValue + minPeginFee`.\n // Captured before `fromFundedTransaction` to bind it to the value the\n // funded tx actually carries (see the cross-check below).\n const expectedHtlcValue = unfundedTx.getHtlcValue(htlcVout);\n\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const cleanPrePeginHex = fundedPrePeginTxHex.startsWith(\"0x\")\n ? fundedPrePeginTxHex.slice(2)\n : fundedPrePeginTxHex;\n const prePeginTx = Transaction.fromHex(cleanPrePeginHex);\n\n const htlcOutput = prePeginTx.outs[htlcVout];\n if (!htlcOutput) {\n throw new Error(\n `HTLC output at vout ${htlcVout} not found in funded Pre-PegIn tx ` +\n `(tx has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const actualHtlcScriptPubKey = uint8ArrayToHex(\n new Uint8Array(htlcOutput.script),\n ).toLowerCase();\n // The scriptPubKey commits to the depositor key, the participant keys, the\n // hashlock and timelockRefund. A wrong depositor key is refused earlier,\n // at `fromFundedTransaction`'s CPFP anchor check, and amounts have their\n // own value check below. The message names the other inputs, plus a\n // funded tx that is not this vault's Pre-PegIn: nothing upstream binds\n // the funded tx to the vault, so a stale one reaches this check.\n if (actualHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `HTLC scriptPubKey mismatch at vout ${htlcVout}: reconstructed ` +\n `template expects ${expectedHtlcScriptPubKey}, funded tx carries ` +\n `${actualHtlcScriptPubKey}. Refund refused — the rebuilt HTLC does ` +\n `not commit to the funded output. Check the participant keys ` +\n `first: the vault provider, vault keeper and universal challenger ` +\n `keys must be the operation keys at the vault's frozen epochs ` +\n `(readRefundPrePeginContext, or readStampedParticipantKeys), not ` +\n `roster, indexer or current keys. Then check the hashlock at this ` +\n `vout and timelockRefund, and that the funded transaction is this ` +\n `vault's Pre-PegIn (its txid must equal the vault's on-chain ` +\n `prePeginTxHash).`,\n );\n }\n\n // Value cross-check (mirrors the script check above): the template's\n // HTLC value — derived by WASM from `pegInAmounts` via the protocol\n // formula — must equal the value the funded tx pays at this output.\n // A caller that hands the full HTLC output value (or any wrong amount)\n // as `pegInAmounts` would inflate the template value and trip this\n // guard, rather than silently signing a refund built from a template\n // that disagrees with the on-chain commitment.\n const actualHtlcValue = BigInt(htlcOutput.value);\n if (actualHtlcValue !== expectedHtlcValue) {\n throw new Error(\n `HTLC value mismatch at vout ${htlcVout}: reconstructed template ` +\n `expects ${expectedHtlcValue} sat, funded tx carries ` +\n `${actualHtlcValue} sat. Refund refused — the pegInAmounts vector ` +\n `does not match the on-chain commitment.`,\n );\n }\n\n const refundTx = Transaction.fromHex(refundTxHex);\n\n if (refundTx.version !== REFUND_TX_VERSION) {\n throw new Error(\n `Refund transaction version ${refundTx.version} does not match ` +\n `protocol version ${REFUND_TX_VERSION}.`,\n );\n }\n if (refundTx.locktime !== REFUND_TX_LOCKTIME) {\n throw new Error(\n `Refund transaction locktime ${refundTx.locktime} does not match ` +\n `protocol locktime ${REFUND_TX_LOCKTIME}.`,\n );\n }\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 if (refundInput.sequence !== prePeginParams.timelockRefund) {\n throw new Error(\n `Refund input sequence ${refundInput.sequence} does not match ` +\n `timelockRefund ${prePeginParams.timelockRefund}.`,\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: expectedHtlc.refundScript,\n controlBlock: expectedHtlc.refundControlBlock,\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n tapMerkleRoot: expectedHtlc.tapMerkleRoot,\n });\n\n // Output side: pin the single refund output to the depositor's own\n // BIP-86 P2TR address, mirroring the input-side pinning above. WASM\n // builds the refund output from the refund leaf's depositor key, so a\n // correct template always pays exactly one output back to the depositor.\n // Asserting it here means a malformed template (or a tampered WASM)\n // cannot redirect the reclaimed funds to a script the depositor does\n // not control.\n if (refundTx.outs.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 output, got ${refundTx.outs.length}`,\n );\n }\n const refundOutput = refundTx.outs[0];\n const expectedDepositorScriptPubKey = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(prePeginParams.depositorPubkey),\n ).toLowerCase();\n const actualRefundOutputScriptPubKey = uint8ArrayToHex(\n new Uint8Array(refundOutput.script),\n ).toLowerCase();\n if (actualRefundOutputScriptPubKey !== expectedDepositorScriptPubKey) {\n throw new Error(\n `Refund output scriptPubKey ${actualRefundOutputScriptPubKey} does not ` +\n `match the depositor's BIP-86 address ${expectedDepositorScriptPubKey}. ` +\n `Refund refused — the reclaimed funds would not return to the depositor.`,\n );\n }\n\n // Value: the single refund output must return the full HTLC value minus\n // exactly the requested fee. The refund is 1-in/1-out (asserted above), so\n // a value below `htlcValue - refundFee` means WASM applied a larger fee\n // than requested — the difference would be burned as miner fee. Pin it so\n // the depositor reclaims the expected amount, not a silently reduced one.\n const expectedRefundOutputValue = actualHtlcValue - refundFee;\n if (BigInt(refundOutput.value) !== expectedRefundOutputValue) {\n throw new Error(\n `Refund output value ${BigInt(refundOutput.value)} sat does not equal ` +\n `the HTLC value ${actualHtlcValue} sat minus the requested fee ` +\n `${refundFee} sat (expected ${expectedRefundOutputValue} sat). ` +\n `Refund refused — the reclaimed amount would be burned as excess fee.`,\n );\n }\n\n psbt.addOutput({\n script: refundOutput.script,\n value: refundOutput.value,\n });\n\n return { psbtHex: psbt.toHex() };\n } finally {\n fundedTx?.free();\n unfundedTx.free();\n }\n}\n","/**\n * Reclaim PSBT Builder Primitive\n *\n * Builds an unsigned PSBT that sweeps the depositor-claim reserve — PegIn\n * vout 1 — back to the depositor's own BIP-86 address.\n *\n * The reserve funds the depositor's `claim_tx`, their recourse if the vault\n * provider fails during peg-out. When the vault provider claims instead and\n * the depositor withdraws normally, nothing ever spends it. This primitive is\n * the only thing in the repository that can.\n *\n * Spend path: the single `<depositor> OP_CHECKSIG` tapleaf (see\n * ./depositorClaim). No timelock, no counterparty signature — the depositor's\n * Schnorr signature alone. That is also why the *caller* must gate: this\n * builder will happily sweep a reserve whose vault is still live, which would\n * permanently void the depositor's pre-signed recourse graph. Eligibility is\n * enforced upstream, in the service.\n *\n * @module primitives/psbt/reclaim\n */\n\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { DUST_THRESHOLD } from \"../../utils/fee/constants\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport {\n PEGIN_DEPOSITOR_CLAIM_VOUT,\n deriveDepositorClaimDescriptor,\n} from \"./depositorClaim\";\n\n/**\n * nVersion for the reclaim transaction. Plain v2, not TRUC: the reserve is only\n * offered once its PegIn is deeply confirmed, so the PegIn's nVersion-3\n * topology limits no longer constrain its children.\n */\nconst RECLAIM_TX_VERSION = 2;\n\n/**\n * nSequence for every reclaim input: RBF-enabled, no relative timelock. The\n * claim leaf carries no CSV, so this is a fee-bumping signal only.\n */\nconst RECLAIM_INPUT_SEQUENCE = 0xfffffffd;\n\n/**\n * Weight units of the reclaim transaction's skeleton — everything except the\n * inputs. Non-witness `version(4) + inCount(1) + outCount(1) + locktime(4) +\n * output(8 + 1 + 34)` = 53 B × 4, plus the 2 WU SegWit marker and flag.\n */\nconst RECLAIM_SKELETON_WEIGHT_UNITS = 214;\n\n/**\n * Weight units each script-path input adds. Non-witness `outpoint(36) +\n * scriptSigLen(1) + sequence(4)` = 41 B × 4 = 164, plus a witness of\n * `stackCount(1) + sig(1 + 64) + leafScript(1 + 34) + controlBlock(1 + 33)` =\n * 135 WU.\n *\n * Exact rather than conservative: every element is fixed-length here — a\n * 64-byte BIP-340 signature under SIGHASH_DEFAULT, the 34-byte leaf, and a\n * 33-byte control block with no merkle path.\n */\nconst RECLAIM_INPUT_WEIGHT_UNITS = 299;\n\n/** Weight units per virtual byte. */\nconst WEIGHT_UNITS_PER_VBYTE = 4;\n\n/**\n * Virtual size of an N-in/1-out reclaim transaction.\n *\n * `REFUND_VSIZE = 160` does not generalise to N inputs, and\n * `computePeginBaseFeeSats` is wrong for this shape entirely — its\n * `P2TR_INPUT_SIZE = 58` is a *key-path* input and under-fees a script-path\n * spend by roughly a quarter.\n *\n * N=1 → 129 vB; each additional input adds 75 vB.\n */\nexport function reclaimVsize(numInputs: number): number {\n if (!Number.isInteger(numInputs) || numInputs < 1) {\n throw new Error(\n `Reclaim input count must be a positive integer, got ${numInputs}.`,\n );\n }\n return Math.ceil(\n (RECLAIM_SKELETON_WEIGHT_UNITS +\n RECLAIM_INPUT_WEIGHT_UNITS * numInputs) /\n WEIGHT_UNITS_PER_VBYTE,\n );\n}\n\n/** Absolute fee in satoshis for an N-in/1-out reclaim at a given rate. */\nexport function estimateReclaimFeeSats(\n feeRateSatsVb: number,\n numInputs: number,\n): bigint {\n if (!Number.isFinite(feeRateSatsVb) || feeRateSatsVb <= 0) {\n throw new Error(\n `Reclaim fee rate must be a positive number, got ${feeRateSatsVb}.`,\n );\n }\n return BigInt(Math.ceil(feeRateSatsVb * reclaimVsize(numInputs)));\n}\n\n/** One depositor-claim reserve to sweep, with the material to bind it. */\nexport interface ReclaimReserve {\n /**\n * The contract's own copy of the depositor-signed PegIn transaction\n * (`VaultProtocolInfo.depositorSignedPeginTx`). Authoritative: its SegWit\n * txid equals the broadcast PegIn's, and its `outs[1]` carries the reserve's\n * script and value at no extra RPC cost.\n */\n depositorSignedPeginTxHex: string;\n /** Independent chain observation of `peginTxid:1` (esplora UTXO lookup). */\n observed: {\n /**\n * The outpoint the caller actually issued its chain lookup against, so the\n * observation below can be tied to the input this builder adds.\n *\n * Without it the script and value binds prove only that *some* UTXO has\n * this shape — the claim script is a pure function of the depositor key and\n * so is byte-identical across every vault they own, and the value is a pure\n * function of protocol parameters. Neither distinguishes one of the\n * depositor's vaults from another.\n *\n * Txid in display order, 64 hex chars, with or without `0x` prefix.\n */\n txid: string;\n /** Vout the lookup was issued against. Must be the claim vout. */\n vout: number;\n /** scriptPubKey hex, with or without `0x` prefix. */\n scriptPubKey: string;\n /** Output value in satoshis. */\n value: bigint;\n };\n /**\n * The reserve value recomputed from this vault's protocol parameters via\n * `computeMinClaimValue`. Bound so a doctored PegIn that agrees with itself\n * and with a compromised indexer still fails.\n */\n expectedValue: bigint;\n}\n\nexport interface BuildReclaimPsbtParams {\n /**\n * The **connected wallet's live** x-only pubkey, 64-char hex. Never the\n * indexer's `depositorBtcPubkey`: re-deriving from the live key is what\n * proves the wallet about to sign is the wallet that can spend, and rejects\n * the wrong-wallet case with an error instead of an unspendable broadcast.\n */\n depositorPubkey: string;\n /**\n * Reserves to sweep. An array so batching several vaults into one\n * transaction is a later change rather than a rewrite; today the app passes\n * exactly one.\n */\n inputs: ReclaimReserve[];\n /** Absolute fee in satoshis. The caller sizes it; see `reclaimVsize`. */\n feeSats: bigint;\n}\n\nexport interface BuildReclaimPsbtResult {\n /** PSBT hex ready for depositor signing. */\n psbtHex: string;\n /** Value of the single output — what the depositor actually receives. */\n outputValue: bigint;\n /** Sum of the swept reserves, before fee. */\n totalInputValue: bigint;\n}\n\n/**\n * Build the N-in/1-out reclaim PSBT.\n *\n * Every input is bound three ways before it reaches the PSBT: the contract's\n * PegIn bytes, the chain observation, and a JS re-derivation from the live\n * wallet key must agree on both script and value. Any disagreement throws.\n * The observation must also name the outpoint it was taken from, since script\n * and value alone repeat across all of a depositor's vaults.\n *\n * Binding the input to the *vault* that was asked for is a further step, and\n * it belongs to the service: it needs the vault id derivation, which is async.\n * See `services/reclaim/buildAndBroadcastReclaim`.\n *\n * @throws If `inputs` is empty, the fee is non-positive, any input fails its\n * outpoint, script or value bind, or the resulting output would be at or\n * below dust.\n */\nexport function buildReclaimPsbt(\n params: BuildReclaimPsbtParams,\n): BuildReclaimPsbtResult {\n const { depositorPubkey, inputs, feeSats } = params;\n\n if (inputs.length === 0) {\n throw new Error(\"Reclaim requires at least one input; got none.\");\n }\n if (feeSats <= 0n) {\n throw new Error(\n `Reclaim fee must be positive, got ${feeSats} sat. Refusing to build a ` +\n `transaction that would not relay.`,\n );\n }\n\n // One derivation, reused for every input's bind and for the destination.\n const descriptor = deriveDepositorClaimDescriptor(depositorPubkey);\n const expectedScriptPubKey = uint8ArrayToHex(\n new Uint8Array(descriptor.scriptPubKey),\n ).toLowerCase();\n\n const psbt = new Psbt();\n psbt.setVersion(RECLAIM_TX_VERSION);\n psbt.setLocktime(0);\n\n let totalInputValue = 0n;\n const seenOutpoints = new Set<string>();\n\n inputs.forEach((input, i) => {\n const peginTx = Transaction.fromHex(\n stripHexPrefix(input.depositorSignedPeginTxHex),\n );\n const peginTxid = peginTx.getId();\n\n const claimOut = peginTx.outs[PEGIN_DEPOSITOR_CLAIM_VOUT];\n if (!claimOut) {\n throw new Error(\n `PegIn ${peginTxid} has no output at vout ` +\n `${PEGIN_DEPOSITOR_CLAIM_VOUT} (tx has ${peginTx.outs.length}); ` +\n `there is no depositor-claim reserve to reclaim.`,\n );\n }\n\n // Bind 0: the observation is of *this* outpoint. Everything below compares\n // a script and a value, both of which repeat across every vault this\n // depositor owns under the same protocol parameters — so without this the\n // remaining binds cannot tell one of their vaults from another, and a\n // caller that resolved the wrong vault would sweep it with every check\n // passing. The independent source is the PegIn the PSBT is built from; the\n // esplora response cannot serve here because `getUtxoInfo` echoes back the\n // txid and vout it was called with rather than reading them from the body.\n const observedTxid = stripHexPrefix(input.observed.txid).toLowerCase();\n if (observedTxid !== peginTxid) {\n throw new Error(\n `Input ${i}: the observation is of ${observedTxid}, but this input ` +\n `spends PegIn ${peginTxid}. Reclaim refused — the reserve that was ` +\n `looked up is not the one being swept.`,\n );\n }\n if (input.observed.vout !== PEGIN_DEPOSITOR_CLAIM_VOUT) {\n throw new Error(\n `Input ${i}: the observation is of vout ${input.observed.vout}, but ` +\n `the depositor-claim reserve is at vout ` +\n `${PEGIN_DEPOSITOR_CLAIM_VOUT}. Reclaim refused.`,\n );\n }\n\n // Bind 1: the contract's PegIn bytes against the JS re-derivation from the\n // live wallet key. This is the assertion that proves the connected wallet\n // can actually spend the output we are about to sign for.\n const contractScriptPubKey = uint8ArrayToHex(\n new Uint8Array(claimOut.script),\n ).toLowerCase();\n if (contractScriptPubKey !== expectedScriptPubKey) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} pays ` +\n `${contractScriptPubKey}, but the connected wallet's depositor-claim ` +\n `script is ${expectedScriptPubKey}. Reclaim refused — this reserve ` +\n `belongs to a different wallet.`,\n );\n }\n\n // Bind 2: the independent chain observation must agree with both.\n const observedScriptPubKey = stripHexPrefix(\n input.observed.scriptPubKey,\n ).toLowerCase();\n if (observedScriptPubKey !== expectedScriptPubKey) {\n throw new Error(\n `Input ${i}: the observed UTXO ${peginTxid}:${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `pays ${observedScriptPubKey}, expected ${expectedScriptPubKey}. ` +\n `Reclaim refused — chain state disagrees with the contract's PegIn.`,\n );\n }\n\n // Value bind, same three ways.\n const contractValue = BigInt(claimOut.value);\n if (contractValue !== input.observed.value) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `carries ${contractValue} sat, but the observed UTXO carries ` +\n `${input.observed.value} sat. Reclaim refused.`,\n );\n }\n if (contractValue !== input.expectedValue) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `carries ${contractValue} sat, but this vault's parameters compute a ` +\n `depositor-claim value of ${input.expectedValue} sat. Reclaim refused.`,\n );\n }\n\n // A batch that names the same vault twice would otherwise double-count the\n // swept total and then fail deep inside bitcoinjs. Reject it here, where\n // the message can say which input is the duplicate.\n const outpoint = `${peginTxid}:${PEGIN_DEPOSITOR_CLAIM_VOUT}`;\n if (seenOutpoints.has(outpoint)) {\n throw new Error(\n `Input ${i} repeats outpoint ${outpoint}, which is already being ` +\n `swept by an earlier input. Reclaim refused.`,\n );\n }\n seenOutpoints.add(outpoint);\n\n totalInputValue += contractValue;\n\n psbt.addInput({\n hash: peginTxid,\n index: PEGIN_DEPOSITOR_CLAIM_VOUT,\n sequence: RECLAIM_INPUT_SEQUENCE,\n witnessUtxo: { script: claimOut.script, value: claimOut.value },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: descriptor.leafScript,\n controlBlock: descriptor.controlBlock,\n },\n ],\n tapInternalKey: descriptor.internalKey,\n });\n });\n\n if (feeSats >= totalInputValue) {\n throw new Error(\n `Reclaim fee ${feeSats} sat is not less than the swept total ` +\n `${totalInputValue} sat. Refusing to build a transaction with no output.`,\n );\n }\n\n const outputValue = totalInputValue - feeSats;\n if (outputValue <= DUST_THRESHOLD) {\n throw new Error(\n `Reclaim output ${outputValue} sat is at or below the dust threshold ` +\n `${DUST_THRESHOLD} sat. The reserve is not at risk — it stays where it ` +\n `is until fee rates fall.`,\n );\n }\n\n const destination = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(depositorPubkey),\n );\n psbt.addOutput({\n script: Buffer.from(hexToUint8Array(destination)),\n value: Number(outputValue),\n });\n\n return { psbtHex: psbt.toHex(), outputValue, totalInputValue };\n}\n","/**\n * Finalize a Taproot script-path spend from the PSBT *we* built, using only the\n * verified signatures the wallet returned.\n *\n * Why this exists. The obvious shape — hand the wallet's PSBT to\n * `finalizeAllInputs()` — puts wallet-controlled bytes on the trust path even\n * when the signature itself has been verified.\n * `assertPsbtUnsignedTxMatches` deliberately pins only the unsigned\n * transaction and skips per-input metadata, so `tapLeafScript`, `controlBlock`\n * and `tapKeySig` all survive from the wallet's response untouched. And\n * bitcoinjs-lib checks key-spend first (`src/psbt.js`, `_finalizeTaprootInput`:\n * \"Check key spend first. Increased privacy and reduced block space.\"), so a\n * returned `tapKeySig` wins outright and `tapScriptSig` is never consulted.\n * Every output the depositor-claim reserve and the HTLC refund spend from uses\n * a NUMS internal key, so the resulting key-path witness cannot satisfy the\n * script — the transaction is rejected at broadcast, after a wallet prompt the\n * depositor cannot make sense of.\n *\n * Verifying and then discarding the wallet's PSBT closes that off structurally\n * rather than detecting it afterwards, and it makes the code match what\n * `verifyScriptPathSchnorrSignature` already documents: \"only the 64-byte\n * signature comes from the wallet\".\n *\n * @module tbv/core/primitives/psbt/finalizeScriptPathWithSignatures\n */\n\nimport { Psbt } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { X_ONLY_PUBKEY_HEX_LEN } from \"../../utils/validation\";\nimport {\n SCHNORR_SIG_HEX_LEN,\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\nimport { computeTapLeafHash } from \"../utils/taproot\";\n\nexport interface FinalizeScriptPathWithSignaturesParams {\n /**\n * Hex of the PSBT built locally and sent to the wallet — the sole source of\n * every per-input field. NOT the wallet-returned PSBT.\n */\n requestedPsbtHex: string;\n /**\n * Verified 64-byte Schnorr signatures, one per input, index-aligned with the\n * PSBT's inputs. Each must already have passed\n * `assertScriptPathSchnorrSignature` — this function does not re-verify them,\n * it only decides which bytes are allowed to reach the witness.\n */\n signaturesHex: readonly string[];\n /** X-only pubkey (64 hex chars) the signatures are attributed to. */\n signerXOnlyPubkeyHex: string;\n}\n\n/**\n * Attach `signaturesHex` to the locally built PSBT's script-path inputs,\n * finalize, and return the extracted transaction hex.\n *\n * @throws If the signature count does not match the input count, any signature\n * or the signer key is malformed, any input does not carry exactly one\n * tapscript leaf at the expected leaf version, any input already carries a\n * key-path signature, or bitcoinjs-lib cannot finalize.\n */\nexport function finalizeScriptPathWithSignatures(\n params: FinalizeScriptPathWithSignaturesParams,\n): string {\n const { requestedPsbtHex, signaturesHex, signerXOnlyPubkeyHex } = params;\n\n const signerXOnly = stripHexPrefix(signerXOnlyPubkeyHex);\n if (signerXOnly.length !== X_ONLY_PUBKEY_HEX_LEN) {\n throw new Error(\n `Signer x-only pubkey must be ${X_ONLY_PUBKEY_HEX_LEN} hex chars ` +\n `(32 bytes), got ${signerXOnly.length}.`,\n );\n }\n const signerPubkey = Buffer.from(hexToUint8Array(signerXOnly));\n\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (signaturesHex.length !== psbt.data.inputs.length) {\n throw new Error(\n `Cannot finalize: got ${signaturesHex.length} signature(s) for ` +\n `${psbt.data.inputs.length} input(s). Every input must be signed — ` +\n `refusing to broadcast a partially signed transaction.`,\n );\n }\n\n psbt.data.inputs.forEach((input, inputIndex) => {\n // Our own builders never produce a key-path signature for these spends.\n // If one is present the PSBT is not the one we built, which would defeat\n // the whole point of finalizing locally.\n if (input.tapKeySig) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} of the locally built PSBT ` +\n `carries a key-path signature. These outputs are script-path only.`,\n );\n }\n\n const tapLeafScripts = input.tapLeafScript;\n if (!tapLeafScripts || tapLeafScripts.length !== 1) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} must have exactly one ` +\n `tapLeafScript, got ${tapLeafScripts?.length ?? 0}.`,\n );\n }\n const leaf = tapLeafScripts[0];\n if (leaf.leafVersion !== TAPSCRIPT_LEAF_VERSION) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} tapLeafScript has leaf version ` +\n `0x${leaf.leafVersion.toString(16)}, expected ` +\n `0x${TAPSCRIPT_LEAF_VERSION.toString(16)}.`,\n );\n }\n\n const signatureRaw = stripHexPrefix(signaturesHex[inputIndex]);\n if (signatureRaw.length !== SCHNORR_SIG_HEX_LEN) {\n throw new Error(\n `Signature for input ${inputIndex} must be ${SCHNORR_SIG_HEX_LEN} hex ` +\n `chars (64 bytes), got ${signatureRaw.length}.`,\n );\n }\n\n psbt.updateInput(inputIndex, {\n tapScriptSig: [\n {\n pubkey: signerPubkey,\n leafHash: computeTapLeafHash(leaf.leafVersion, leaf.script),\n signature: Buffer.from(hexToUint8Array(signatureRaw)),\n },\n ],\n });\n });\n\n // With no tapKeySig anywhere, bitcoinjs takes the script-path branch for\n // every input and builds `[signature, leafScript, controlBlock]` from the\n // leaf we supplied.\n psbt.finalizeAllInputs();\n\n return psbt.extractTransaction().toHex();\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 \"../../wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction, payments } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n getNetwork,\n hexToUint8Array,\n inputTxidHex,\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\nimport {\n ASSERT_PAYOUT_OUTPUT_INDEX,\n CHALLENGE_ASSERT_OUTPUT_CONNECTOR_INDEX,\n NOPAYOUT_ASSERT_INPUT_SEQUENCE,\n NOPAYOUT_INPUT_COUNT,\n NOPAYOUT_TX_LOCKTIME,\n NOPAYOUT_TX_VERSION,\n} from \"./constants\";\n\n/** Largest `timelockChallengeAssert` the protocol accepts (a Rust `NonZeroU16`). */\nconst MAX_TIMELOCK_CHALLENGE_ASSERT = 0xffff;\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}], used verbatim — derive them from the parent txs */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/**\n * Validate that a NoPayout transaction pays to the challenger via the\n * protocol-defined output structure: a single BIP-86 P2TR output derived from\n * the challenger's x-only pubkey.\n *\n * Mirrors the per-role payout output validation now inlined in\n * `buildPayoutPsbt` for the NoPayout path, where the sink is fixed by the\n * protocol rather than read from on-chain registration\n * (see `crates/vault/src/transactions/nopayout.rs::NoPayoutTx::new`).\n *\n * @param noPayoutTxHex - Raw NoPayout transaction hex\n * @param challengerPubkey - Challenger's x-only public key (hex)\n * @param network - Bitcoin network used to derive the P2TR scriptPubKey\n * @throws If the transaction does not have exactly one output\n * @throws If the single output's scriptPubKey does not equal the BIP-86 P2TR\n * scriptPubKey for the challenger\n */\nexport function assertNoPayoutOutputMatchesChallenger(\n noPayoutTxHex: string,\n challengerPubkey: string,\n network: Network,\n): void {\n const tx = Transaction.fromHex(stripHexPrefix(noPayoutTxHex));\n\n if (tx.outs.length !== 1) {\n throw new Error(\n `NoPayout transaction must have exactly 1 output, got ${tx.outs.length}`,\n );\n }\n\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(challengerPubkey));\n const { output: expectedScript } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!expectedScript) {\n throw new Error(\n \"Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation\",\n );\n }\n\n if (!tx.outs[0].script.equals(expectedScript)) {\n throw new Error(\n \"NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address\",\n );\n }\n}\n\n/**\n * Parameters for {@link assertCanonicalNoPayoutShape}\n */\nexport interface AssertCanonicalNoPayoutShapeParams {\n /** The NoPayout transaction the VP supplied */\n noPayoutTx: Transaction;\n /** Authoritative Assert txid (display hex) */\n assertTxid: string;\n /** Canonical ChallengeAssertX txid (display hex) */\n challengeAssertXTxid: string;\n /** Canonical ChallengeAssertY txid (display hex) */\n challengeAssertYTxid: string;\n /** ChallengeAssert CSV timelock in blocks (offchain param `timelockChallengeAssert`) */\n timelockChallengeAssert: number;\n /** Values of Assert:0, ChallengeAssertX:0 and ChallengeAssertY:0, in input order */\n prevoutValues: readonly [number, number, number];\n}\n\n/**\n * Require a VP-supplied NoPayout to have the shape btc-vault `NoPayoutTx::new`\n * builds over the canonical parents\n * (`crates/vault/src/transactions/nopayout.rs:148-209` @ b534ff9e): version 2,\n * locktime 0, and exactly the inputs Assert:0, ChallengeAssertX:0 and\n * ChallengeAssertY:0, in that order, with sequences `0xffffffff`, `t`, `t`.\n *\n * The depositor's signature commits to every one of these fields. The\n * challenge window itself is enforced by the ChallengeAssert output connector's\n * NoPayout leaf (`<challenger> CHECKSIGVERIFY <t> CSV`), which the txid binding\n * of both parents pins: a NoPayout with a shorter or disabled sequence, or\n * below version 2, fails that CSV and is invalid rather than early. Pinning the\n * inputs, sequences, version and locktime to btc-vault's layout keeps the\n * signature on a NoPayout that satisfies that CSV. The output value is not\n * pinned to btc-vault's (the inputs minus its fee); it is only required not to\n * exceed the inputs, since a larger output could never be valid. The output\n * script is checked by {@link assertNoPayoutOutputMatchesChallenger}.\n *\n * @param params - The supplied NoPayout and the authoritative parents\n * @throws If any input, sequence, version or locktime differs from the\n * canonical layout, the timelock is not a valid relative timelock, or the\n * output value exceeds the inputs\n */\nexport function assertCanonicalNoPayoutShape(\n params: AssertCanonicalNoPayoutShapeParams,\n): void {\n const { noPayoutTx, timelockChallengeAssert } = params;\n if (\n !Number.isInteger(timelockChallengeAssert) ||\n timelockChallengeAssert < 1 ||\n timelockChallengeAssert > MAX_TIMELOCK_CHALLENGE_ASSERT\n ) {\n throw new Error(\n `timelockChallengeAssert must be an integer in 1..${MAX_TIMELOCK_CHALLENGE_ASSERT}, got ${timelockChallengeAssert}`,\n );\n }\n if (noPayoutTx.version !== NOPAYOUT_TX_VERSION) {\n throw new Error(\n `NoPayout version must be ${NOPAYOUT_TX_VERSION}, got ${noPayoutTx.version}`,\n );\n }\n if (noPayoutTx.locktime !== NOPAYOUT_TX_LOCKTIME) {\n throw new Error(\n `NoPayout locktime must be ${NOPAYOUT_TX_LOCKTIME}, got ${noPayoutTx.locktime}`,\n );\n }\n if (noPayoutTx.ins.length !== NOPAYOUT_INPUT_COUNT) {\n throw new Error(\n `NoPayout must have exactly ${NOPAYOUT_INPUT_COUNT} inputs, got ${noPayoutTx.ins.length}`,\n );\n }\n\n const expectedInputs = [\n {\n label: \"Assert\",\n txid: params.assertTxid,\n vout: ASSERT_PAYOUT_OUTPUT_INDEX,\n sequence: NOPAYOUT_ASSERT_INPUT_SEQUENCE,\n },\n {\n label: \"ChallengeAssertX\",\n txid: params.challengeAssertXTxid,\n vout: CHALLENGE_ASSERT_OUTPUT_CONNECTOR_INDEX,\n sequence: timelockChallengeAssert,\n },\n {\n label: \"ChallengeAssertY\",\n txid: params.challengeAssertYTxid,\n vout: CHALLENGE_ASSERT_OUTPUT_CONNECTOR_INDEX,\n sequence: timelockChallengeAssert,\n },\n ];\n expectedInputs.forEach((expected, i) => {\n const input = noPayoutTx.ins[i];\n const txid = inputTxidHex(input);\n if (txid !== expected.txid || input.index !== expected.vout) {\n throw new Error(\n `NoPayout input ${i} must spend ${expected.label} ${expected.txid}:${expected.vout}, got ${txid}:${input.index}`,\n );\n }\n if (input.sequence !== expected.sequence) {\n throw new Error(\n `NoPayout input ${i} (${expected.label}) sequence must be ${expected.sequence}, got ${input.sequence}`,\n );\n }\n });\n\n const inputValue = params.prevoutValues.reduce((sum, v) => sum + v, 0);\n const outputValue = noPayoutTx.outs.reduce((sum, out) => sum + out.value, 0);\n if (outputValue > inputValue) {\n throw new Error(\n `NoPayout output value ${outputValue} exceeds its inputs (${inputValue} sats)`,\n );\n }\n}\n","/**\n * ChallengeAssert PSBT Builder\n *\n * Builds an unsigned PSBT for a ChallengeAssert transaction. ChallengeAssert\n * is split across two single-input transactions — ChallengeAssertX (spends the\n * challenger's ConnectorX Assert output) and ChallengeAssertY (spends\n * ConnectorY). This builder handles one such transaction.\n *\n * The protocol collects no claimer signature on ChallengeAssert — the\n * challenger signs it at broadcast (btc-vault `tx_graph/challenger.rs`). The\n * PSBT builder exists for tooling that reconstructs the graph; it is not on\n * the depositor presign path (`signDepositorGraph` signs Payout + NoPayout\n * only). {@link assertChallengeAssertIsCanonical} is on that path: NoPayout\n * spends output 0 of both ChallengeAsserts, so they are bound before signing.\n *\n * @module primitives/psbt/challengeAssert\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — ChallengeAssertX / ChallengeAssertY\n */\n\nimport {\n type ChallengeAssertConnectorParams,\n getChallengeAssertScriptInfo,\n tapInternalPubkey,\n} from \"../../wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n hexToUint8Array,\n inputTxidHex,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\nimport {\n ASSERT_FIRST_CHALLENGER_CONNECTOR_VOUT,\n CHALLENGE_ASSERT_ANCHOR_VALUE_SATS,\n CHALLENGE_ASSERT_INPUT_SEQUENCE,\n CHALLENGE_ASSERT_TX_LOCKTIME,\n CHALLENGE_ASSERT_TX_VERSION,\n} from \"./constants\";\n\n/**\n * Parameters for building a ChallengeAssert PSBT\n */\nexport interface ChallengeAssertParams {\n /** ChallengeAssert transaction hex (unsigned) */\n challengeAssertTxHex: string;\n /** Authoritative Assert transaction hex — every input must spend an Assert output */\n assertTxHex: string;\n /** Per-input connector params (one per input/segment, determines the taproot script) */\n connectorParamsPerInput: ChallengeAssertConnectorParams[];\n}\n\n/**\n * Build unsigned ChallengeAssert PSBT.\n *\n * Each input has its own taproot script derived from its connector params; the\n * number of connector params must match the transaction's input count.\n * Every prevout is derived from the authoritative\n * Assert transaction, never trusted from external input.\n *\n * @param params - ChallengeAssert parameters\n * @returns Unsigned PSBT hex ready for signing\n *\n * @throws If the number of connector params does not match the number of inputs\n * @throws If any input does not reference assertTxHex\n * @throws If any referenced Assert output is missing\n * @throws If two inputs reference the same Assert output index\n */\nexport async function buildChallengeAssertPsbt(\n params: ChallengeAssertParams,\n): Promise<string> {\n const challengeAssertTx = Transaction.fromHex(\n stripHexPrefix(params.challengeAssertTxHex),\n );\n const assertTx = Transaction.fromHex(stripHexPrefix(params.assertTxHex));\n const assertTxid = assertTx.getId();\n\n if (params.connectorParamsPerInput.length !== challengeAssertTx.ins.length) {\n throw new Error(\n `Expected ${challengeAssertTx.ins.length} connector params, got ${params.connectorParamsPerInput.length}`,\n );\n }\n\n const seenAssertOutputs = new Set<number>();\n for (let i = 0; i < challengeAssertTx.ins.length; i++) {\n const input = challengeAssertTx.ins[i];\n const inputTxid = inputTxidHex(input);\n if (inputTxid !== assertTxid) {\n throw new Error(\n `ChallengeAssert input ${i} must spend an Assert output. ` +\n `Expected txid ${assertTxid}, got ${inputTxid}`,\n );\n }\n if (!assertTx.outs[input.index]) {\n throw new Error(\n `Assert output ${input.index} not found for ChallengeAssert input ${i} (txid: ${assertTxid})`,\n );\n }\n if (seenAssertOutputs.has(input.index)) {\n throw new Error(\n `ChallengeAssert input ${i} duplicates Assert output index ${input.index}`,\n );\n }\n seenAssertOutputs.add(input.index);\n }\n\n const scriptInfos = await Promise.all(\n params.connectorParamsPerInput.map((cp) => getChallengeAssertScriptInfo(cp)),\n );\n\n const psbt = new Psbt();\n psbt.setVersion(challengeAssertTx.version);\n psbt.setLocktime(challengeAssertTx.locktime);\n\n for (let i = 0; i < challengeAssertTx.ins.length; i++) {\n const input = challengeAssertTx.ins[i];\n const assertPrevOut = assertTx.outs[input.index];\n\n const { script, controlBlock } = scriptInfos[i];\n const scriptBytes = hexToUint8Array(script);\n const controlBlockBytes = hexToUint8Array(controlBlock);\n\n psbt.addInput({\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: assertPrevOut.script,\n value: assertPrevOut.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n }\n\n for (const output of challengeAssertTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/** Which of a challenger's two ChallengeAssert transactions. */\nexport type ChallengeAssertHalf = \"X\" | \"Y\";\n\n/**\n * Parameters for {@link assertChallengeAssertIsCanonical}\n */\nexport interface AssertChallengeAssertIsCanonicalParams {\n /** The ChallengeAssertX or ChallengeAssertY transaction the VP supplied */\n challengeAssertTx: Transaction;\n /** Authoritative Assert transaction, already bound to the depositor's Claim */\n assertTx: Transaction;\n /** Which half `challengeAssertTx` claims to be */\n half: ChallengeAssertHalf;\n /** The challenger's index in the hex-sorted local ∪ universal challenger set */\n challengerIndex: number;\n /** Number of local plus universal challengers (K) */\n challengerCount: number;\n /** The challenger's x-only public key (hex) */\n challengerPubkey: string;\n /** ChallengeAssert output connector scriptPubKey for this challenger (hex) */\n outputConnectorScriptPubKey: string;\n}\n\n/**\n * Require a VP-supplied ChallengeAssertX/Y to be exactly the transaction\n * btc-vault builds for this challenger from the authoritative Assert.\n *\n * NoPayout spends output 0 of both ChallengeAsserts, and the depositor's\n * NoPayout signature commits to their txids. The protocol collects no claimer\n * signature on a ChallengeAssert, so that commitment is all that forces a\n * challenger to broadcast the canonical one. A parent that does not spend this\n * Assert, or whose output 0 is not the timelocked connector, would let a\n * colluding challenger spend Assert:0 through NoPayout without the dispute\n * that the claimer can answer with WronglyChallenged.\n *\n * The transaction is fully determined by the Assert, the challenger's sorted\n * index and the connector script, so it is rebuilt here and compared by txid,\n * which covers every non-witness byte.\n *\n * @param params - The supplied transaction and the authoritative inputs\n * @throws If the challenger index is out of range, the Assert lacks the\n * connector output, or the supplied transaction is not the canonical one\n */\nexport function assertChallengeAssertIsCanonical(\n params: AssertChallengeAssertIsCanonicalParams,\n): void {\n const expectedTxid = buildCanonicalChallengeAssertTx(params).getId();\n const suppliedTxid = params.challengeAssertTx.getId();\n if (suppliedTxid !== expectedTxid) {\n throw new Error(\n `ChallengeAssert${params.half} (challenger ${params.challengerPubkey}) is not the ` +\n `canonical transaction for this Assert: expected txid ${expectedTxid}, got ${suppliedTxid}`,\n );\n }\n}\n\n/**\n * Mirror btc-vault `construct_challenge_assert` + `build_challenge_assert_tx`\n * (`crates/vault/src/transactions/challenge_assert.rs:49-96,147-221` @ b534ff9e).\n */\nfunction buildCanonicalChallengeAssertTx(\n params: AssertChallengeAssertIsCanonicalParams,\n): Transaction {\n const { assertTx, half, challengerIndex, challengerCount } = params;\n if (\n !Number.isInteger(challengerIndex) ||\n challengerIndex < 0 ||\n challengerIndex >= challengerCount\n ) {\n throw new Error(\n `ChallengeAssert${half} challenger index ${challengerIndex} is outside 0..${challengerCount - 1}`,\n );\n }\n const vout =\n ASSERT_FIRST_CHALLENGER_CONNECTOR_VOUT +\n (half === \"Y\" ? challengerCount : 0) +\n challengerIndex;\n const connectorOutput = assertTx.outs[vout];\n if (!connectorOutput) {\n throw new Error(\n `Assert has no output ${vout} for the ChallengeAssert${half} of challenger index ${challengerIndex}`,\n );\n }\n const outputConnectorValue =\n connectorOutput.value - CHALLENGE_ASSERT_ANCHOR_VALUE_SATS;\n if (outputConnectorValue < 0) {\n throw new Error(\n `Assert output ${vout} (${connectorOutput.value} sats) cannot fund the ` +\n `${CHALLENGE_ASSERT_ANCHOR_VALUE_SATS}-sat ChallengeAssert${half} anchor`,\n );\n }\n\n const tx = new Transaction();\n tx.version = CHALLENGE_ASSERT_TX_VERSION;\n tx.locktime = CHALLENGE_ASSERT_TX_LOCKTIME;\n tx.addInput(assertTx.getHash(), vout, CHALLENGE_ASSERT_INPUT_SEQUENCE);\n tx.addOutput(\n Buffer.from(hexToUint8Array(params.outputConnectorScriptPubKey)),\n outputConnectorValue,\n );\n tx.addOutput(\n Buffer.from(\n hexToUint8Array(deriveBip86ScriptPubKeyHex(params.challengerPubkey)),\n ),\n CHALLENGE_ASSERT_ANCHOR_VALUE_SATS,\n );\n return tx;\n}\n"],"names":["U64_MAX","assertPositiveBigintArray","values","label","value","index","buildRefundPsbt","params","WasmPrePeginTx","loadTbvWasm","prePeginParams","fundedPrePeginTxHex","htlcVout","refundFee","hashlock","normalizedAuthAnchorHash","normalizeAuthAnchorHash","unfundedTx","fundedTx","wasmHtlcScriptPubKey","expectedHtlc","deriveExpectedPrePeginHtlc","expectedHtlcScriptPubKey","expectedHtlcValue","refundTxHex","cleanPrePeginHex","prePeginTx","Transaction","htlcOutput","actualHtlcScriptPubKey","uint8ArrayToHex","actualHtlcValue","refundTx","REFUND_TX_VERSION","REFUND_TX_LOCKTIME","refundInput","prePeginTxid","refundInputTxid","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","refundOutput","expectedDepositorScriptPubKey","stripHexPrefix","deriveBip86ScriptPubKeyHex","actualRefundOutputScriptPubKey","expectedRefundOutputValue","RECLAIM_TX_VERSION","RECLAIM_INPUT_SEQUENCE","RECLAIM_SKELETON_WEIGHT_UNITS","RECLAIM_INPUT_WEIGHT_UNITS","WEIGHT_UNITS_PER_VBYTE","reclaimVsize","numInputs","estimateReclaimFeeSats","feeRateSatsVb","buildReclaimPsbt","depositorPubkey","inputs","feeSats","descriptor","deriveDepositorClaimDescriptor","expectedScriptPubKey","totalInputValue","seenOutpoints","input","i","peginTx","peginTxid","claimOut","PEGIN_DEPOSITOR_CLAIM_VOUT","observedTxid","contractScriptPubKey","observedScriptPubKey","contractValue","outpoint","outputValue","DUST_THRESHOLD","destination","hexToUint8Array","finalizeScriptPathWithSignatures","requestedPsbtHex","signaturesHex","signerXOnlyPubkeyHex","signerXOnly","X_ONLY_PUBKEY_HEX_LEN","signerPubkey","inputIndex","tapLeafScripts","leaf","signatureRaw","SCHNORR_SIG_HEX_LEN","computeTapLeafHash","MAX_TIMELOCK_CHALLENGE_ASSERT","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","prevout","inputData","output","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","expectedScript","payments","getNetwork","assertCanonicalNoPayoutShape","timelockChallengeAssert","NOPAYOUT_TX_VERSION","NOPAYOUT_TX_LOCKTIME","NOPAYOUT_INPUT_COUNT","ASSERT_PAYOUT_OUTPUT_INDEX","NOPAYOUT_ASSERT_INPUT_SEQUENCE","CHALLENGE_ASSERT_OUTPUT_CONNECTOR_INDEX","expected","txid","inputTxidHex","inputValue","sum","v","out","buildChallengeAssertPsbt","challengeAssertTx","assertTx","assertTxid","seenAssertOutputs","inputTxid","scriptInfos","cp","getChallengeAssertScriptInfo","assertPrevOut","script","controlBlock","assertChallengeAssertIsCanonical","expectedTxid","buildCanonicalChallengeAssertTx","suppliedTxid","half","challengerIndex","challengerCount","vout","ASSERT_FIRST_CHALLENGER_CONNECTOR_VOUT","connectorOutput","outputConnectorValue","CHALLENGE_ASSERT_ANCHOR_VALUE_SATS","CHALLENGE_ASSERT_TX_VERSION","CHALLENGE_ASSERT_TX_LOCKTIME","CHALLENGE_ASSERT_INPUT_SEQUENCE"],"mappings":";;;;;;;;AAoBA,MAAMA,MAAW,MAAM,OAAO;AAYvB,SAASC,GACdC,GACAC,GACU;AACV,MAAI,CAAC,MAAM,QAAQD,CAAM;AACvB,UAAM,IAAI;AAAA,MACR,GAAGC,CAAK,8CAA8C,OAAOD,CAAM;AAAA,IAAA;AAGvE,MAAIA,EAAO,WAAW;AACpB,UAAM,IAAI,MAAM,GAAGC,CAAK,qBAAqB;AAE/C,SAAAD,EAAO,QAAQ,CAACE,GAAOC,MAAU;AAC/B,QAAI,OAAOD,KAAU;AACnB,YAAM,IAAI;AAAA,QACR,GAAGD,CAAK,IAAIE,CAAK,2BAA2B,OAAOD,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CAAC;AAAA,IAAA;AAGnG,QAAMC,IACJC,MACCJ,MAAS,MAAME,IAAkB,KAClCD,GACII,IAAkBnB,EAAS,KAAKiB,CAAI;AAC1C,MAAI,CAACE;AACH,UAAM,IAAI;AAAA,MACR,wBAAwBF,CAAI,2BAA2BH,CAAI,wBAAwBC,CAAe;AAAA,IAAA;AAGtG,QAAMK,IACJD,EAAgB,QAAQE;AAC1B,MAAID,IAAuB;AACzB,UAAM,IAAI;AAAA,MACR,iBAAiBH,CAAI,KAAKE,EAAgB,KAAK,0BAC1CE,CAAkC,uBAAuBP,CAAI;AAAA,IAAA;AAItE,QAAMrC,IAAK,IAAInF,EAAA;AACf,SAAAmF,EAAG,UAAU6C,IACb7C,EAAG,WAAW8C,IACd9C,EAAG,SAASuB,EAAS,QAAA,GAAWiB,GAAMO,EAA+B,GACrE/C,EAAG;AAAA,IACDrE,EAAO,KAAKwC,EAAgB1E,EAAO,2BAA2B,CAAC;AAAA,IAC/DkJ;AAAA,EAAA,GAEF3C,EAAG;AAAA,IACDrE,EAAO;AAAA,MACLwC,EAAgBnC,EAA2BvC,EAAO,gBAAgB,CAAC;AAAA,IAAA;AAAA,IAErEmJ;AAAA,EAAA,GAEK5C;AACT;"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./verifyScriptPathSchnorrSignature-BHskbJJx.cjs"),O=require("./secp256k1-DDHQ1_za.cjs"),o=require("./tbv/core/wasm/index.cjs"),R=require("./verifyKeyPathSchnorrSignature-BVrAmVL3.cjs"),E=require("./challengeAssert-CuX_8Twt.cjs"),r=require("./bitcoin-D-O2GjbC.cjs"),y=require("./abortSignals-msbmbqFe.cjs"),I=require("./signing-DvISftFk.cjs"),d=require("./validation-C6XTfZak.cjs"),F=require("./tbv/core/utils/eth/index.cjs"),_=require("./PeginManager-6ghglb4r.cjs"),P=require("./PayoutManager-B5nR0x1t.cjs"),s=require("./tbv/core/clients/mempool/index.cjs"),u=require("./registration-records-CKc0OVuK.cjs"),C=require("./signer-set-reader-CJfV-GDz.cjs"),A=require("./pegin-registration-client-DOb-Iznp.cjs"),h=require("./types-BnZIbDHb.cjs"),N=require("./ApplicationRegistry.abi-sMiTWmnL.cjs"),V=require("./BTCVaultRegistry.abi-DzbfZ9_s.cjs"),l=require("./BTCVaultRegistryKeyEpochs.abi-CReWFJdu.cjs"),M=require("./ProtocolParams.abi-DWfIh6VH.cjs"),b=require("./VaultErrors.abi-Hjn1CdLs.cjs"),v=require("./buildVaultContextInputForClaim-9XZaqIiw.cjs"),S=require("./deriveVaultRoot-C3uqnJto.cjs"),D=require("./parseFundingOutpoints-C_-PT9BT.cjs"),B=require("./shared/index.cjs"),U=require("./btcTxHash-CGb5BqFL.cjs"),c=require("./psbtInputFields-BrV_ZfL_.cjs"),i=require("./fundPeginTransaction-54-Rwb2k.cjs"),T=require("./reservation-D9ftyiwP.cjs"),m=require("./index-Dn7RlsKK.cjs"),a=require("./state-C4WoNCy1.cjs"),p=require("./primeVpAuth-Ch-ig2My.cjs"),t=require("./toRefundInputs-DyIgmGJq.cjs"),e=require("./buildAndBroadcastReclaim-CXOMHHgK.cjs"),g=require("./peginState-B4t_PDgj.cjs");exports.PEGIN_DEPOSITOR_CLAIM_VOUT=n.PEGIN_DEPOSITOR_CLAIM_VOUT;exports.PsbtSubstitutionError=n.PsbtSubstitutionError;exports.assertPsbtUnsignedTxMatches=n.assertPsbtUnsignedTxMatches;exports.assertScriptPathSchnorrSignature=n.assertScriptPathSchnorrSignature;exports.buildPayoutPsbt=n.buildPayoutPsbt;exports.buildPeginTxFromFundedPrePegin=n.buildPeginTxFromFundedPrePegin;exports.buildPrePeginPsbt=n.buildPrePeginPsbt;exports.computeNumLocalChallengers=n.computeNumLocalChallengers;exports.createPayoutScript=n.createPayoutScript;exports.deriveDepositorClaimDescriptor=n.deriveDepositorClaimDescriptor;exports.deriveDepositorClaimScriptPubKey=n.deriveDepositorClaimScriptPubKey;exports.extractPayoutSignature=n.extractPayoutSignature;exports.assertValidVaultCoreVersion=O.assertValidVaultCoreVersion;exports.attachFinalizedAssert=o.attachFinalizedAssert;exports.computeMinClaimValue=o.computeMinClaimValue;exports.computeMinPeginFee=o.computeMinPeginFee;exports.deriveVaultId=o.deriveVaultId;exports.expandAuthAnchor=o.expandAuthAnchor;exports.expandHashlockSecret=o.expandHashlockSecret;exports.expandWotsSeed=o.expandWotsSeed;exports.finalizePayout=o.finalizePayout;exports.finalizeWronglyChallenged=o.finalizeWronglyChallenged;exports.peginP2aAnchorOutput=o.peginP2aAnchorOutput;exports.pinPegoutProof=o.pinPegoutProof;exports.supportedTxGraphVersions=o.supportedTxGraphVersions;exports.validatePeginP2aAnchor=o.validatePeginP2aAnchor;exports.assertKeyPathSchnorrSignature=R.assertKeyPathSchnorrSignature;exports.assertReturnedKeyPathSignatures=R.assertReturnedKeyPathSignatures;exports.buildPeginInputPsbt=R.buildPeginInputPsbt;exports.extractPeginInputSignature=R.extractPeginInputSignature;exports.finalizePeginInputPsbt=R.finalizePeginInputPsbt;exports.buildChallengeAssertPsbt=E.buildChallengeAssertPsbt;exports.buildNoPayoutPsbt=E.buildNoPayoutPsbt;exports.buildReclaimPsbt=E.buildReclaimPsbt;exports.buildRefundPsbt=E.buildRefundPsbt;exports.estimateReclaimFeeSats=E.estimateReclaimFeeSats;exports.finalizeScriptPathWithSignatures=E.finalizeScriptPathWithSignatures;exports.reclaimVsize=E.reclaimVsize;exports.canonicalizeBtcPubkey=r.canonicalizeBtcPubkey;exports.deriveBip86ScriptPubKeyHex=r.deriveBip86ScriptPubKeyHex;exports.deriveNativeSegwitAddress=r.deriveNativeSegwitAddress;exports.deriveTaprootAddress=r.deriveTaprootAddress;exports.ensureHexPrefix=r.ensureHexPrefix;exports.formatSatoshisToBtc=r.formatSatoshisToBtc;exports.getNetwork=r.getNetwork;exports.getSortedXOnlyPubkeys=r.getSortedXOnlyPubkeys;exports.hexToUint8Array=r.hexToUint8Array;exports.isAddressFromPublicKey=r.isAddressFromPublicKey;exports.isValidHex=r.isValidHex;exports.processPublicKeyToXOnly=r.processPublicKeyToXOnly;exports.stripHexPrefix=r.stripHexPrefix;exports.toXOnly=r.toXOnly;exports.uint8ArrayToHex=r.uint8ArrayToHex;exports.validateWalletPubkey=r.validateWalletPubkey;exports.combineAbortSignals=y.combineAbortSignals;exports.createTaprootScriptPathSignOptions=I.createTaprootScriptPathSignOptions;exports.createTaprootScriptPathSignOptionsForInput=I.createTaprootScriptPathSignOptionsForInput;exports.BITCOIN_ADDRESS_RE=d.BITCOIN_ADDRESS_RE;exports.COMPRESSED_PUBKEY_HEX_LEN=d.COMPRESSED_PUBKEY_HEX_LEN;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.X_ONLY_PUBKEY_HEX_LEN=d.X_ONLY_PUBKEY_HEX_LEN;exports.waitForTransactionReceiptSmartAware=F.waitForTransactionReceiptSmartAware;exports.PeginManager=_.PeginManager;exports.buildDepositTerms=_.buildDepositTerms;exports.computeWotsBlockPublicKeysHash=_.computeWotsBlockPublicKeysHash;exports.deriveWotsBlocksFromSeed=_.deriveWotsBlocksFromSeed;exports.ensurePrePeginTermsApproval=_.ensurePrePeginTermsApproval;exports.PayoutManager=P.PayoutManager;exports.computeHashlock=P.computeHashlock;exports.forwardDepositApproval=P.forwardDepositApproval;exports.requireChangeAddress=P.requireChangeAddress;exports.supportsDepositApproval=P.supportsDepositApproval;exports.validateSecretAgainstHashlock=P.validateSecretAgainstHashlock;exports.MEMPOOL_API_URLS=s.MEMPOOL_API_URLS;exports.MempoolNotFoundError=s.MempoolNotFoundError;exports.getAddressTxs=s.getAddressTxs;exports.getAddressUtxos=s.getAddressUtxos;exports.getMempoolApiUrl=s.getMempoolApiUrl;exports.getNetworkFees=s.getNetworkFees;exports.getOutspend=s.getOutspend;exports.getTipHeight=s.getTipHeight;exports.getTxHex=s.getTxHex;exports.getTxInfo=s.getTxInfo;exports.getUtxoInfo=s.getUtxoInfo;exports.pushTx=s.pushTx;exports.RegistrationLogsUnavailableError=u.RegistrationLogsUnavailableError;exports.VaultClaimableByNotFoundError=u.VaultClaimableByNotFoundError;exports.assertOnChainBtcPubkey=u.assertOnChainBtcPubkey;exports.assertRegisteredPayoutScriptBounds=u.assertRegisteredPayoutScriptBounds;exports.derivePeginVaultId=u.derivePeginVaultId;exports.findRegistrationRecord=u.findRegistrationRecord;exports.isRegistrationLogsUnavailableError=u.isRegistrationLogsUnavailableError;exports.isVaultClaimableByNotFoundError=u.isVaultClaimableByNotFoundError;exports.registrationPrePeginTxHash=u.registrationPrePeginTxHash;exports.validateOffchainParams=u.validateOffchainParams;exports.validatePegInConfiguration=u.validatePegInConfiguration;exports.validateTBVProtocolParams=u.validateTBVProtocolParams;exports.ViemOperationKeyReader=C.ViemOperationKeyReader;exports.ViemUniversalChallengerReader=C.ViemUniversalChallengerReader;exports.ViemVaultKeeperReader=C.ViemVaultKeeperReader;exports.resolveProtocolAddresses=C.resolveProtocolAddresses;exports.COMMISSION_BPS_HEADROOM=A.COMMISSION_BPS_HEADROOM;exports.MAX_ACCEPTABLE_COMMISSION_BPS_CAP=A.MAX_ACCEPTABLE_COMMISSION_BPS_CAP;exports.ViemPeginRegistrationClient=A.ViemPeginRegistrationClient;exports.ViemVaultRegistryReader=A.ViemVaultRegistryReader;exports.capMaxAcceptableCommissionBps=A.capMaxAcceptableCommissionBps;exports.OnChainBtcVaultStatus=h.OnChainBtcVaultStatus;exports.ViemProtocolParamsReader=h.ViemProtocolParamsReader;exports.ApplicationRegistryABI=N.ApplicationRegistryABI;exports.BTCVaultRegistryABI=V.BTCVaultRegistryABI;exports.BTCVaultRegistryKeyEpochsABI=l.BTCVaultRegistryKeyEpochsABI;exports.CONTRACT_ERRORS=l.CONTRACT_ERRORS;exports.EMPTY_REVERT_MESSAGE=l.EMPTY_REVERT_MESSAGE;exports.PEGIN_FINGERPRINT_CHANGED_SELECTOR=l.PEGIN_FINGERPRINT_CHANGED_SELECTOR;exports.PeginFingerprintChangedError=l.PeginFingerprintChangedError;exports.extractErrorData=l.extractErrorData;exports.getContractErrorMessage=l.getContractErrorMessage;exports.handleContractError=l.handleContractError;exports.isKnownContractError=l.isKnownContractError;exports.isPeginFingerprintChangedError=l.isPeginFingerprintChangedError;exports.ProtocolParamsABI=M.ProtocolParamsABI;exports.VAULT_ERROR_ABI=b.VAULT_ERROR_ABI;exports.buildVaultContextInputForClaim=v.buildVaultContextInputForClaim;exports.VAULT_APP_NAME=S.VAULT_APP_NAME;exports.buildFundingOutpointsCommitment=S.buildFundingOutpointsCommitment;exports.buildVaultContext=S.buildVaultContext;exports.deriveVaultRoot=S.deriveVaultRoot;exports.forwardDeriveContextHash=S.forwardDeriveContextHash;exports.parseFundingOutpointsFromTx=D.parseFundingOutpointsFromTx;exports.BitcoinNetworks=B.BitcoinNetworks;exports.calculateBtcTxHash=U.calculateBtcTxHash;exports.BitcoinScriptType=c.BitcoinScriptType;exports.applyChangeOutputPolicy=c.applyChangeOutputPolicy;exports.computeChangeOutputFeeSats=c.computeChangeOutputFeeSats;exports.computeMaxDeposit=c.computeMaxDeposit;exports.computePeginBaseFeeSats=c.computePeginBaseFeeSats;exports.getDustThreshold=c.getDustThreshold;exports.getPsbtInputFields=c.getPsbtInputFields;exports.getScriptType=c.getScriptType;exports.selectUtxosForPegin=c.selectUtxosForPegin;exports.shouldAddChangeOutput=c.shouldAddChangeOutput;exports.BTC_DUST_SAT=i.BTC_DUST_SAT;exports.DUST_THRESHOLD=i.DUST_THRESHOLD;exports.LOW_RATE_ESTIMATION_ACCURACY_BUFFER=i.LOW_RATE_ESTIMATION_ACCURACY_BUFFER;exports.MAX_NON_LEGACY_OUTPUT_SIZE=i.MAX_NON_LEGACY_OUTPUT_SIZE;exports.MAX_REASONABLE_PEGIN_VBYTES=i.MAX_REASONABLE_PEGIN_VBYTES;exports.P2TR_INPUT_SIZE=i.P2TR_INPUT_SIZE;exports.PEGIN_AUTH_ANCHOR_OUTPUTS=i.PEGIN_AUTH_ANCHOR_OUTPUTS;exports.PEGIN_FIXED_OUTPUTS=i.PEGIN_FIXED_OUTPUTS;exports.SPLIT_TX_FEE_SAFETY_MULTIPLIER=i.SPLIT_TX_FEE_SAFETY_MULTIPLIER;exports.TX_BUFFER_SIZE_OVERHEAD=i.TX_BUFFER_SIZE_OVERHEAD;exports.WALLET_RELAY_FEE_RATE_THRESHOLD=i.WALLET_RELAY_FEE_RATE_THRESHOLD;exports.fundPeginTransaction=i.fundPeginTransaction;exports.parseUnfundedWasmTransaction=i.parseUnfundedWasmTransaction;exports.peginOutputCount=i.peginOutputCount;exports.rateBasedTxBufferFee=i.rateBasedTxBufferFee;exports.UtxoNotAvailableError=T.UtxoNotAvailableError;exports.assertUtxosAvailable=T.assertUtxosAvailable;exports.extractInputsFromTransaction=T.extractInputsFromTransaction;exports.findOverlappingPendingVaults=T.findOverlappingPendingVaults;exports.validateUtxosAvailable=T.validateUtxosAvailable;exports.VaultProviderRpcClient=m.VaultProviderRpcClient;exports.VpResponseValidationError=m.VpResponseValidationError;exports.batchPollByProvider=m.batchPollByProvider;exports.isUnrecognizedDaemonStatusError=m.isUnrecognizedDaemonStatusError;exports.validateRequestDepositorClaimerArtifactsResponse=m.validateRequestDepositorClaimerArtifactsResponse;exports.AUTH_REJECTED_RPC_CODE=a.AUTH_REJECTED_RPC_CODE;exports.ClaimerPegoutStatusValue=a.ClaimerPegoutStatusValue;exports.DaemonStatus=a.DaemonStatus;exports.JSON_RPC_ERROR_CODES=a.JSON_RPC_ERROR_CODES;exports.JsonRpcClient=a.JsonRpcClient;exports.JsonRpcError=a.JsonRpcError;exports.POST_WOTS_STATUSES=a.POST_WOTS_STATUSES;exports.PRE_DEPOSITOR_SIGNATURES_STATES=a.PRE_DEPOSITOR_SIGNATURES_STATES;exports.RpcErrorCode=a.RpcErrorCode;exports.VP_BATCH_MAX_SIZE=a.VP_BATCH_MAX_SIZE;exports.VP_TERMINAL_FAILURE_STATUSES=a.VP_TERMINAL_FAILURE_STATUSES;exports.VP_TRANSIENT_STATUSES=a.VP_TRANSIENT_STATUSES;exports.isAuthRejectedError=a.isAuthRejectedError;exports.isPegoutTerminalStatus=a.isPegoutTerminalStatus;exports.isRecognizedPegoutStatus=a.isRecognizedPegoutStatus;exports.ServerIdentityError=p.ServerIdentityError;exports.VpTokenRegistry=p.VpTokenRegistry;exports.createAuthenticatedVpClient=p.createAuthenticatedVpClient;exports.primeVpTokenRegistry=p.primeVpTokenRegistry;exports.verifyServerIdentity=p.verifyServerIdentity;exports.vpTokenRegistry=p.vpTokenRegistry;exports.DEPOSIT_TERMS_REJECTED_ERROR_NAME=t.DEPOSIT_TERMS_REJECTED_ERROR_NAME;exports.DepositTermsRejectedError=t.DepositTermsRejectedError;exports.PEGIN_FINGERPRINT_DOMAIN=t.PEGIN_FINGERPRINT_DOMAIN;exports.PEGIN_FINGERPRINT_DOMAIN_PREIMAGE=t.PEGIN_FINGERPRINT_DOMAIN_PREIMAGE;exports.PeginFingerprintInputError=t.PeginFingerprintInputError;exports.PeginParamsAmbiguousError=t.PeginParamsAmbiguousError;exports.PeginParamsIncompleteSpaceError=t.PeginParamsIncompleteSpaceError;exports.PeginParamsNotFoundError=t.PeginParamsNotFoundError;exports.PeginSizingIntegrityError=t.PeginSizingIntegrityError;exports.UnanchoredPrePeginError=t.UnanchoredPrePeginError;exports.VaultRootMismatchError=t.VaultRootMismatchError;exports.assertClaimBatchHomogeneous=t.assertClaimBatchHomogeneous;exports.buildPeginParamsCandidates=t.buildPeginParamsCandidates;exports.computeFundedPrePeginFee=t.computeFundedPrePeginFee;exports.computePeginFingerprint=t.computePeginFingerprint;exports.deriveHashlocksFromPrePegin=t.deriveHashlocksFromPrePegin;exports.describePeginParamsCandidate=t.describePeginParamsCandidate;exports.describeUnresolvedVersion=t.describeUnresolvedVersion;exports.encodePeginFingerprintPreimage=t.encodePeginFingerprintPreimage;exports.isDepositTermsRejectedError=t.isDepositTermsRejectedError;exports.isPeginFingerprintInputError=t.isPeginFingerprintInputError;exports.isWotsMismatchError=t.isWotsMismatchError;exports.orderClaimBatchByHtlcVout=t.orderClaimBatchByHtlcVout;exports.rebuildDepositTermsCore=t.rebuildDepositTermsCore;exports.rebuildDepositTermsForClaim=t.rebuildDepositTermsForClaim;exports.reconstructPeginParams=t.reconstructPeginParams;exports.selectSiblingRegistrations=t.selectSiblingRegistrations;exports.toRefundInputs=t.toRefundInputs;exports.ApplicationEntryPointMismatchError=e.ApplicationEntryPointMismatchError;exports.ArtifactsVaultMismatchError=e.ArtifactsVaultMismatchError;exports.AssertBindingError=e.AssertBindingError;exports.BIP68NotMatureError=e.BIP68NotMatureError;exports.ChallengerSetMismatchError=e.ChallengerSetMismatchError;exports.DELEGATED_CLAIM_TX_GRAPH_VERSION=e.DELEGATED_CLAIM_TX_GRAPH_VERSION;exports.DelegatedClaimSigningIncompleteError=e.DelegatedClaimSigningIncompleteError;exports.GraphFingerprintError=e.GraphFingerprintError;exports.PEGIN_ETH_CONFIRMATIONS=e.PEGIN_ETH_CONFIRMATIONS;exports.ParticipantKeyDriftError=e.ParticipantKeyDriftError;exports.PayoutDestinationError=e.PayoutDestinationError;exports.PayoutInputLeafError=e.PayoutInputLeafError;exports.PeginRegistrationMissingError=e.PeginRegistrationMissingError;exports.PeginRegistrationNotFinalError=e.PeginRegistrationNotFinalError;exports.RECLAIM_MAX_FEE_FRACTION_DENOMINATOR=e.RECLAIM_MAX_FEE_FRACTION_DENOMINATOR;exports.RECLAIM_MAX_FEE_FRACTION_NUMERATOR=e.RECLAIM_MAX_FEE_FRACTION_NUMERATOR;exports.RECLAIM_MAX_FEE_RATE_SATS_VB=e.RECLAIM_MAX_FEE_RATE_SATS_VB;exports.RECLAIM_WARN_FEE_FRACTION_NUMERATOR=e.RECLAIM_WARN_FEE_FRACTION_NUMERATOR;exports.REFUND_MAX_FEE_FRACTION_DENOMINATOR=e.REFUND_MAX_FEE_FRACTION_DENOMINATOR;exports.REFUND_MAX_FEE_FRACTION_NUMERATOR=e.REFUND_MAX_FEE_FRACTION_NUMERATOR;exports.REFUND_MAX_FEE_RATE_SATS_VB=e.REFUND_MAX_FEE_RATE_SATS_VB;exports.REFUND_VSIZE=e.REFUND_VSIZE;exports.ReclaimUneconomicalError=e.ReclaimUneconomicalError;exports.RefundBroadcastRejectedError=e.RefundBroadcastRejectedError;exports.RegisteredVaultVersionMismatchError=e.RegisteredVaultVersionMismatchError;exports.SigningPlanMismatchError=e.SigningPlanMismatchError;exports.UnsupportedPayoutScriptError=e.UnsupportedPayoutScriptError;exports.VaultIdBindingError=e.VaultIdBindingError;exports.activateVault=e.activateVault;exports.activateVaultAndRedeem=e.activateVaultAndRedeem;exports.assembleWatchtowerArtifacts=e.assembleWatchtowerArtifacts;exports.assembleWatchtowerArtifactsFromSignatures=e.assembleWatchtowerArtifactsFromSignatures;exports.assertArtifactsUsableForVault=e.assertArtifactsUsableForVault;exports.assertAssertBindsClaimAndPayout=e.assertAssertBindsClaimAndPayout;exports.assertChallengerSetMatchesVault=e.assertChallengerSetMatchesVault;exports.assertClaimSpendsVault=e.assertClaimSpendsVault;exports.assertPayoutPaysRegisteredScript=e.assertPayoutPaysRegisteredScript;exports.assertReturnedGraphMatchesFingerprint=e.assertReturnedGraphMatchesFingerprint;exports.assertStandardPayoutScriptsAtEpochs=e.assertStandardPayoutScriptsAtEpochs;exports.assertTermsMatchVault=e.assertTermsMatchVault;exports.assertVaultProviderHintAccepted=e.assertVaultProviderHintAccepted;exports.buildAndBroadcastReclaim=e.buildAndBroadcastReclaim;exports.buildAndBroadcastRefund=e.buildAndBroadcastRefund;exports.claimExpiredVault=e.claimExpiredVault;exports.copyAssertConnectorLeaf=e.copyAssertConnectorLeaf;exports.deriveClaimerWotsKeypair=e.deriveClaimerWotsKeypair;exports.estimateRefundFeeSats=e.estimateRefundFeeSats;exports.fingerprintReturnedGraph=e.fingerprintReturnedGraph;exports.isApplicationEntryPointMismatchError=e.isApplicationEntryPointMismatchError;exports.isDepositAmountValid=e.isDepositAmountValid;exports.isHintAccepted=e.isHintAccepted;exports.isParticipantKeyDriftError=e.isParticipantKeyDriftError;exports.isPeginRegistrationMissingError=e.isPeginRegistrationMissingError;exports.isPeginRegistrationNotFinalError=e.isPeginRegistrationNotFinalError;exports.isRegisteredVaultVersionMismatchError=e.isRegisteredVaultVersionMismatchError;exports.isUnsupportedPayoutScriptError=e.isUnsupportedPayoutScriptError;exports.matchKeyHint=e.matchKeyHint;exports.matchKeySetHint=e.matchKeySetHint;exports.planDelegatedClaimSigning=e.planDelegatedClaimSigning;exports.readDelegatedClaimVaultContext=e.readDelegatedClaimVaultContext;exports.readRefundPrePeginContext=e.readRefundPrePeginContext;exports.readStampedParticipantKeys=e.readStampedParticipantKeys;exports.resolveCurrentParticipantKeys=e.resolveCurrentParticipantKeys;exports.resolveParticipantKeysAtEpochs=e.resolveParticipantKeysAtEpochs;exports.runDepositorPresignFlow=e.runDepositorPresignFlow;exports.signDelegatedClaimPlan=e.signDelegatedClaimPlan;exports.signDepositorGraph=e.signDepositorGraph;exports.submitWotsPublicKey=e.submitWotsPublicKey;exports.summarizeWatchtowerArtifacts=e.summarizeWatchtowerArtifacts;exports.validateDepositAmount=e.validateDepositAmount;exports.validateMultiVaultDepositInputs=e.validateMultiVaultDepositInputs;exports.validateOnChainParticipantKeys=e.validateOnChainParticipantKeys;exports.validateProviderSelection=e.validateProviderSelection;exports.validateRemainingCapacity=e.validateRemainingCapacity;exports.validateVaultAmounts=e.validateVaultAmounts;exports.validateVaultProviderPubkey=e.validateVaultProviderPubkey;exports.verifyRegisteredParticipantKeys=e.verifyRegisteredParticipantKeys;exports.verifyRegisteredVaultVersions=e.verifyRegisteredVaultVersions;exports.waitForPeginRegistrationDepth=e.waitForPeginRegistrationDepth;exports.waitForPeginStatus=e.waitForPeginStatus;exports.ContractStatus=g.ContractStatus;exports.PeginAction=g.PeginAction;exports.activationDeadlineBlocksRemaining=g.activationDeadlineBlocksRemaining;exports.canPerformAction=g.canPerformAction;exports.getPeginProtocolState=g.getPeginProtocolState;exports.isActivationDeadlinePassedOnChain=g.isActivationDeadlinePassedOnChain;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./verifyScriptPathSchnorrSignature-p3sVoWQi.cjs"),O=require("./secp256k1-DDHQ1_za.cjs"),o=require("./tbv/core/wasm/index.cjs"),R=require("./verifyKeyPathSchnorrSignature-B7Za6aa1.cjs"),E=require("./challengeAssert-DlzX_kjF.cjs"),y=require("./verifyPeginHashlockSpend-CisfqMuT.cjs"),r=require("./bitcoin-D-O2GjbC.cjs"),F=require("./abortSignals-msbmbqFe.cjs"),I=require("./signing-DvISftFk.cjs"),d=require("./validation-C6XTfZak.cjs"),N=require("./tbv/core/utils/eth/index.cjs"),_=require("./PeginManager-D_ZUfbIy.cjs"),P=require("./PayoutManager-PQqeqX41.cjs"),s=require("./tbv/core/clients/mempool/index.cjs"),l=require("./registration-records-CKc0OVuK.cjs"),C=require("./signer-set-reader-CNEfzwuA.cjs"),A=require("./pegin-registration-client-DOb-Iznp.cjs"),h=require("./types-BnZIbDHb.cjs"),V=require("./ApplicationRegistry.abi-sMiTWmnL.cjs"),M=require("./BTCVaultRegistry.abi-DzbfZ9_s.cjs"),u=require("./BTCVaultRegistryKeyEpochs.abi-CReWFJdu.cjs"),b=require("./ProtocolParams.abi-DWfIh6VH.cjs"),v=require("./VaultErrors.abi-Hjn1CdLs.cjs"),D=require("./buildVaultContextInputForClaim-9XZaqIiw.cjs"),S=require("./deriveVaultRoot-C3uqnJto.cjs"),B=require("./parseFundingOutpoints-C_-PT9BT.cjs"),U=require("./shared/index.cjs"),f=require("./btcTxHash-CGb5BqFL.cjs"),c=require("./psbtInputFields-BrV_ZfL_.cjs"),i=require("./fundPeginTransaction-54-Rwb2k.cjs"),T=require("./reservation-D9ftyiwP.cjs"),m=require("./index-Dn7RlsKK.cjs"),a=require("./state-C4WoNCy1.cjs"),p=require("./primeVpAuth-Ch-ig2My.cjs"),t=require("./toRefundInputs-Df6eRITl.cjs"),e=require("./buildAndBroadcastReclaim-CMjlyooo.cjs"),g=require("./peginState-B4t_PDgj.cjs");exports.PEGIN_DEPOSITOR_CLAIM_VOUT=n.PEGIN_DEPOSITOR_CLAIM_VOUT;exports.PsbtSubstitutionError=n.PsbtSubstitutionError;exports.assertPsbtUnsignedTxMatches=n.assertPsbtUnsignedTxMatches;exports.assertScriptPathSchnorrSignature=n.assertScriptPathSchnorrSignature;exports.buildPayoutPsbt=n.buildPayoutPsbt;exports.buildPeginTxFromFundedPrePegin=n.buildPeginTxFromFundedPrePegin;exports.buildPrePeginPsbt=n.buildPrePeginPsbt;exports.computeNumLocalChallengers=n.computeNumLocalChallengers;exports.createPayoutScript=n.createPayoutScript;exports.deriveDepositorClaimDescriptor=n.deriveDepositorClaimDescriptor;exports.deriveDepositorClaimScriptPubKey=n.deriveDepositorClaimScriptPubKey;exports.extractPayoutSignature=n.extractPayoutSignature;exports.assertValidVaultCoreVersion=O.assertValidVaultCoreVersion;exports.attachFinalizedAssert=o.attachFinalizedAssert;exports.computeMinClaimValue=o.computeMinClaimValue;exports.computeMinPeginFee=o.computeMinPeginFee;exports.deriveVaultId=o.deriveVaultId;exports.expandAuthAnchor=o.expandAuthAnchor;exports.expandHashlockSecret=o.expandHashlockSecret;exports.expandWotsSeed=o.expandWotsSeed;exports.finalizePayout=o.finalizePayout;exports.finalizeWronglyChallenged=o.finalizeWronglyChallenged;exports.peginP2aAnchorOutput=o.peginP2aAnchorOutput;exports.pinPegoutProof=o.pinPegoutProof;exports.supportedTxGraphVersions=o.supportedTxGraphVersions;exports.validatePeginP2aAnchor=o.validatePeginP2aAnchor;exports.assertKeyPathSchnorrSignature=R.assertKeyPathSchnorrSignature;exports.assertReturnedKeyPathSignatures=R.assertReturnedKeyPathSignatures;exports.buildPeginInputPsbt=R.buildPeginInputPsbt;exports.extractPeginInputSignature=R.extractPeginInputSignature;exports.finalizePeginInputPsbt=R.finalizePeginInputPsbt;exports.buildChallengeAssertPsbt=E.buildChallengeAssertPsbt;exports.buildNoPayoutPsbt=E.buildNoPayoutPsbt;exports.buildReclaimPsbt=E.buildReclaimPsbt;exports.buildRefundPsbt=E.buildRefundPsbt;exports.estimateReclaimFeeSats=E.estimateReclaimFeeSats;exports.finalizeScriptPathWithSignatures=E.finalizeScriptPathWithSignatures;exports.reclaimVsize=E.reclaimVsize;exports.verifyPeginHashlockSpend=y.verifyPeginHashlockSpend;exports.canonicalizeBtcPubkey=r.canonicalizeBtcPubkey;exports.deriveBip86ScriptPubKeyHex=r.deriveBip86ScriptPubKeyHex;exports.deriveNativeSegwitAddress=r.deriveNativeSegwitAddress;exports.deriveTaprootAddress=r.deriveTaprootAddress;exports.ensureHexPrefix=r.ensureHexPrefix;exports.formatSatoshisToBtc=r.formatSatoshisToBtc;exports.getNetwork=r.getNetwork;exports.getSortedXOnlyPubkeys=r.getSortedXOnlyPubkeys;exports.hexToUint8Array=r.hexToUint8Array;exports.isAddressFromPublicKey=r.isAddressFromPublicKey;exports.isValidHex=r.isValidHex;exports.processPublicKeyToXOnly=r.processPublicKeyToXOnly;exports.stripHexPrefix=r.stripHexPrefix;exports.toXOnly=r.toXOnly;exports.uint8ArrayToHex=r.uint8ArrayToHex;exports.validateWalletPubkey=r.validateWalletPubkey;exports.combineAbortSignals=F.combineAbortSignals;exports.createTaprootScriptPathSignOptions=I.createTaprootScriptPathSignOptions;exports.createTaprootScriptPathSignOptionsForInput=I.createTaprootScriptPathSignOptionsForInput;exports.BITCOIN_ADDRESS_RE=d.BITCOIN_ADDRESS_RE;exports.COMPRESSED_PUBKEY_HEX_LEN=d.COMPRESSED_PUBKEY_HEX_LEN;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.X_ONLY_PUBKEY_HEX_LEN=d.X_ONLY_PUBKEY_HEX_LEN;exports.waitForTransactionReceiptSmartAware=N.waitForTransactionReceiptSmartAware;exports.PeginManager=_.PeginManager;exports.buildDepositTerms=_.buildDepositTerms;exports.computeWotsBlockPublicKeysHash=_.computeWotsBlockPublicKeysHash;exports.deriveWotsBlocksFromSeed=_.deriveWotsBlocksFromSeed;exports.ensurePrePeginTermsApproval=_.ensurePrePeginTermsApproval;exports.PayoutManager=P.PayoutManager;exports.computeHashlock=P.computeHashlock;exports.forwardDepositApproval=P.forwardDepositApproval;exports.requireChangeAddress=P.requireChangeAddress;exports.supportsDepositApproval=P.supportsDepositApproval;exports.validateSecretAgainstHashlock=P.validateSecretAgainstHashlock;exports.MEMPOOL_API_URLS=s.MEMPOOL_API_URLS;exports.MempoolNotFoundError=s.MempoolNotFoundError;exports.getAddressTxs=s.getAddressTxs;exports.getAddressUtxos=s.getAddressUtxos;exports.getMempoolApiUrl=s.getMempoolApiUrl;exports.getNetworkFees=s.getNetworkFees;exports.getOutspend=s.getOutspend;exports.getTipHeight=s.getTipHeight;exports.getTxHex=s.getTxHex;exports.getTxInfo=s.getTxInfo;exports.getUtxoInfo=s.getUtxoInfo;exports.pushTx=s.pushTx;exports.RegistrationLogsUnavailableError=l.RegistrationLogsUnavailableError;exports.VaultClaimableByNotFoundError=l.VaultClaimableByNotFoundError;exports.assertOnChainBtcPubkey=l.assertOnChainBtcPubkey;exports.assertRegisteredPayoutScriptBounds=l.assertRegisteredPayoutScriptBounds;exports.derivePeginVaultId=l.derivePeginVaultId;exports.findRegistrationRecord=l.findRegistrationRecord;exports.isRegistrationLogsUnavailableError=l.isRegistrationLogsUnavailableError;exports.isVaultClaimableByNotFoundError=l.isVaultClaimableByNotFoundError;exports.registrationPrePeginTxHash=l.registrationPrePeginTxHash;exports.validateOffchainParams=l.validateOffchainParams;exports.validatePegInConfiguration=l.validatePegInConfiguration;exports.validateTBVProtocolParams=l.validateTBVProtocolParams;exports.ViemOperationKeyReader=C.ViemOperationKeyReader;exports.ViemUniversalChallengerReader=C.ViemUniversalChallengerReader;exports.ViemVaultKeeperReader=C.ViemVaultKeeperReader;exports.resolveProtocolAddresses=C.resolveProtocolAddresses;exports.COMMISSION_BPS_HEADROOM=A.COMMISSION_BPS_HEADROOM;exports.MAX_ACCEPTABLE_COMMISSION_BPS_CAP=A.MAX_ACCEPTABLE_COMMISSION_BPS_CAP;exports.ViemPeginRegistrationClient=A.ViemPeginRegistrationClient;exports.ViemVaultRegistryReader=A.ViemVaultRegistryReader;exports.capMaxAcceptableCommissionBps=A.capMaxAcceptableCommissionBps;exports.OnChainBtcVaultStatus=h.OnChainBtcVaultStatus;exports.ViemProtocolParamsReader=h.ViemProtocolParamsReader;exports.ApplicationRegistryABI=V.ApplicationRegistryABI;exports.BTCVaultRegistryABI=M.BTCVaultRegistryABI;exports.BTCVaultRegistryKeyEpochsABI=u.BTCVaultRegistryKeyEpochsABI;exports.CONTRACT_ERRORS=u.CONTRACT_ERRORS;exports.EMPTY_REVERT_MESSAGE=u.EMPTY_REVERT_MESSAGE;exports.PEGIN_FINGERPRINT_CHANGED_SELECTOR=u.PEGIN_FINGERPRINT_CHANGED_SELECTOR;exports.PeginFingerprintChangedError=u.PeginFingerprintChangedError;exports.extractErrorData=u.extractErrorData;exports.getContractErrorMessage=u.getContractErrorMessage;exports.handleContractError=u.handleContractError;exports.isKnownContractError=u.isKnownContractError;exports.isPeginFingerprintChangedError=u.isPeginFingerprintChangedError;exports.ProtocolParamsABI=b.ProtocolParamsABI;exports.VAULT_ERROR_ABI=v.VAULT_ERROR_ABI;exports.buildVaultContextInputForClaim=D.buildVaultContextInputForClaim;exports.VAULT_APP_NAME=S.VAULT_APP_NAME;exports.buildFundingOutpointsCommitment=S.buildFundingOutpointsCommitment;exports.buildVaultContext=S.buildVaultContext;exports.deriveVaultRoot=S.deriveVaultRoot;exports.forwardDeriveContextHash=S.forwardDeriveContextHash;exports.parseFundingOutpointsFromTx=B.parseFundingOutpointsFromTx;exports.BitcoinNetworks=U.BitcoinNetworks;exports.calculateBtcTxHash=f.calculateBtcTxHash;exports.BitcoinScriptType=c.BitcoinScriptType;exports.applyChangeOutputPolicy=c.applyChangeOutputPolicy;exports.computeChangeOutputFeeSats=c.computeChangeOutputFeeSats;exports.computeMaxDeposit=c.computeMaxDeposit;exports.computePeginBaseFeeSats=c.computePeginBaseFeeSats;exports.getDustThreshold=c.getDustThreshold;exports.getPsbtInputFields=c.getPsbtInputFields;exports.getScriptType=c.getScriptType;exports.selectUtxosForPegin=c.selectUtxosForPegin;exports.shouldAddChangeOutput=c.shouldAddChangeOutput;exports.BTC_DUST_SAT=i.BTC_DUST_SAT;exports.DUST_THRESHOLD=i.DUST_THRESHOLD;exports.LOW_RATE_ESTIMATION_ACCURACY_BUFFER=i.LOW_RATE_ESTIMATION_ACCURACY_BUFFER;exports.MAX_NON_LEGACY_OUTPUT_SIZE=i.MAX_NON_LEGACY_OUTPUT_SIZE;exports.MAX_REASONABLE_PEGIN_VBYTES=i.MAX_REASONABLE_PEGIN_VBYTES;exports.P2TR_INPUT_SIZE=i.P2TR_INPUT_SIZE;exports.PEGIN_AUTH_ANCHOR_OUTPUTS=i.PEGIN_AUTH_ANCHOR_OUTPUTS;exports.PEGIN_FIXED_OUTPUTS=i.PEGIN_FIXED_OUTPUTS;exports.SPLIT_TX_FEE_SAFETY_MULTIPLIER=i.SPLIT_TX_FEE_SAFETY_MULTIPLIER;exports.TX_BUFFER_SIZE_OVERHEAD=i.TX_BUFFER_SIZE_OVERHEAD;exports.WALLET_RELAY_FEE_RATE_THRESHOLD=i.WALLET_RELAY_FEE_RATE_THRESHOLD;exports.fundPeginTransaction=i.fundPeginTransaction;exports.parseUnfundedWasmTransaction=i.parseUnfundedWasmTransaction;exports.peginOutputCount=i.peginOutputCount;exports.rateBasedTxBufferFee=i.rateBasedTxBufferFee;exports.UtxoNotAvailableError=T.UtxoNotAvailableError;exports.assertUtxosAvailable=T.assertUtxosAvailable;exports.extractInputsFromTransaction=T.extractInputsFromTransaction;exports.findOverlappingPendingVaults=T.findOverlappingPendingVaults;exports.validateUtxosAvailable=T.validateUtxosAvailable;exports.VaultProviderRpcClient=m.VaultProviderRpcClient;exports.VpResponseValidationError=m.VpResponseValidationError;exports.batchPollByProvider=m.batchPollByProvider;exports.isUnrecognizedDaemonStatusError=m.isUnrecognizedDaemonStatusError;exports.validateRequestDepositorClaimerArtifactsResponse=m.validateRequestDepositorClaimerArtifactsResponse;exports.AUTH_REJECTED_RPC_CODE=a.AUTH_REJECTED_RPC_CODE;exports.ClaimerPegoutStatusValue=a.ClaimerPegoutStatusValue;exports.DaemonStatus=a.DaemonStatus;exports.JSON_RPC_ERROR_CODES=a.JSON_RPC_ERROR_CODES;exports.JsonRpcClient=a.JsonRpcClient;exports.JsonRpcError=a.JsonRpcError;exports.POST_WOTS_STATUSES=a.POST_WOTS_STATUSES;exports.PRE_DEPOSITOR_SIGNATURES_STATES=a.PRE_DEPOSITOR_SIGNATURES_STATES;exports.RpcErrorCode=a.RpcErrorCode;exports.VP_BATCH_MAX_SIZE=a.VP_BATCH_MAX_SIZE;exports.VP_TERMINAL_FAILURE_STATUSES=a.VP_TERMINAL_FAILURE_STATUSES;exports.VP_TRANSIENT_STATUSES=a.VP_TRANSIENT_STATUSES;exports.isAuthRejectedError=a.isAuthRejectedError;exports.isPegoutTerminalStatus=a.isPegoutTerminalStatus;exports.isRecognizedPegoutStatus=a.isRecognizedPegoutStatus;exports.ServerIdentityError=p.ServerIdentityError;exports.VpTokenRegistry=p.VpTokenRegistry;exports.createAuthenticatedVpClient=p.createAuthenticatedVpClient;exports.primeVpTokenRegistry=p.primeVpTokenRegistry;exports.verifyServerIdentity=p.verifyServerIdentity;exports.vpTokenRegistry=p.vpTokenRegistry;exports.DEPOSIT_TERMS_REJECTED_ERROR_NAME=t.DEPOSIT_TERMS_REJECTED_ERROR_NAME;exports.DepositTermsRejectedError=t.DepositTermsRejectedError;exports.PEGIN_FINGERPRINT_DOMAIN=t.PEGIN_FINGERPRINT_DOMAIN;exports.PEGIN_FINGERPRINT_DOMAIN_PREIMAGE=t.PEGIN_FINGERPRINT_DOMAIN_PREIMAGE;exports.PeginFingerprintInputError=t.PeginFingerprintInputError;exports.PeginParamsAmbiguousError=t.PeginParamsAmbiguousError;exports.PeginParamsIncompleteSpaceError=t.PeginParamsIncompleteSpaceError;exports.PeginParamsNotFoundError=t.PeginParamsNotFoundError;exports.PeginSizingIntegrityError=t.PeginSizingIntegrityError;exports.UnanchoredPrePeginError=t.UnanchoredPrePeginError;exports.VaultRootMismatchError=t.VaultRootMismatchError;exports.assertClaimBatchHomogeneous=t.assertClaimBatchHomogeneous;exports.buildPeginParamsCandidates=t.buildPeginParamsCandidates;exports.computeFundedPrePeginFee=t.computeFundedPrePeginFee;exports.computePeginFingerprint=t.computePeginFingerprint;exports.deriveHashlocksFromPrePegin=t.deriveHashlocksFromPrePegin;exports.describePeginParamsCandidate=t.describePeginParamsCandidate;exports.describeUnresolvedVersion=t.describeUnresolvedVersion;exports.encodePeginFingerprintPreimage=t.encodePeginFingerprintPreimage;exports.isDepositTermsRejectedError=t.isDepositTermsRejectedError;exports.isPeginFingerprintInputError=t.isPeginFingerprintInputError;exports.isWotsMismatchError=t.isWotsMismatchError;exports.orderClaimBatchByHtlcVout=t.orderClaimBatchByHtlcVout;exports.rebuildDepositTermsCore=t.rebuildDepositTermsCore;exports.rebuildDepositTermsForClaim=t.rebuildDepositTermsForClaim;exports.reconstructPeginParams=t.reconstructPeginParams;exports.selectSiblingRegistrations=t.selectSiblingRegistrations;exports.toRefundInputs=t.toRefundInputs;exports.ApplicationEntryPointMismatchError=e.ApplicationEntryPointMismatchError;exports.ArtifactsVaultMismatchError=e.ArtifactsVaultMismatchError;exports.AssertBindingError=e.AssertBindingError;exports.BIP68NotMatureError=e.BIP68NotMatureError;exports.ChallengerSetMismatchError=e.ChallengerSetMismatchError;exports.DELEGATED_CLAIM_TX_GRAPH_VERSION=e.DELEGATED_CLAIM_TX_GRAPH_VERSION;exports.DelegatedClaimSigningIncompleteError=e.DelegatedClaimSigningIncompleteError;exports.GraphFingerprintError=e.GraphFingerprintError;exports.PEGIN_ETH_CONFIRMATIONS=e.PEGIN_ETH_CONFIRMATIONS;exports.ParticipantKeyDriftError=e.ParticipantKeyDriftError;exports.PayoutDestinationError=e.PayoutDestinationError;exports.PayoutInputLeafError=e.PayoutInputLeafError;exports.PeginRegistrationMissingError=e.PeginRegistrationMissingError;exports.PeginRegistrationNotFinalError=e.PeginRegistrationNotFinalError;exports.RECLAIM_MAX_FEE_FRACTION_DENOMINATOR=e.RECLAIM_MAX_FEE_FRACTION_DENOMINATOR;exports.RECLAIM_MAX_FEE_FRACTION_NUMERATOR=e.RECLAIM_MAX_FEE_FRACTION_NUMERATOR;exports.RECLAIM_MAX_FEE_RATE_SATS_VB=e.RECLAIM_MAX_FEE_RATE_SATS_VB;exports.RECLAIM_WARN_FEE_FRACTION_NUMERATOR=e.RECLAIM_WARN_FEE_FRACTION_NUMERATOR;exports.REFUND_MAX_FEE_FRACTION_DENOMINATOR=e.REFUND_MAX_FEE_FRACTION_DENOMINATOR;exports.REFUND_MAX_FEE_FRACTION_NUMERATOR=e.REFUND_MAX_FEE_FRACTION_NUMERATOR;exports.REFUND_MAX_FEE_RATE_SATS_VB=e.REFUND_MAX_FEE_RATE_SATS_VB;exports.REFUND_VSIZE=e.REFUND_VSIZE;exports.ReclaimUneconomicalError=e.ReclaimUneconomicalError;exports.RefundBroadcastRejectedError=e.RefundBroadcastRejectedError;exports.RegisteredVaultVersionMismatchError=e.RegisteredVaultVersionMismatchError;exports.SigningPlanMismatchError=e.SigningPlanMismatchError;exports.UnsupportedPayoutScriptError=e.UnsupportedPayoutScriptError;exports.VaultIdBindingError=e.VaultIdBindingError;exports.activateVault=e.activateVault;exports.activateVaultAndRedeem=e.activateVaultAndRedeem;exports.assembleWatchtowerArtifacts=e.assembleWatchtowerArtifacts;exports.assembleWatchtowerArtifactsFromSignatures=e.assembleWatchtowerArtifactsFromSignatures;exports.assertArtifactsUsableForVault=e.assertArtifactsUsableForVault;exports.assertAssertBindsClaimAndPayout=e.assertAssertBindsClaimAndPayout;exports.assertChallengerSetMatchesVault=e.assertChallengerSetMatchesVault;exports.assertClaimSpendsVault=e.assertClaimSpendsVault;exports.assertPayoutPaysRegisteredScript=e.assertPayoutPaysRegisteredScript;exports.assertReturnedGraphMatchesFingerprint=e.assertReturnedGraphMatchesFingerprint;exports.assertStandardPayoutScriptsAtEpochs=e.assertStandardPayoutScriptsAtEpochs;exports.assertTermsMatchVault=e.assertTermsMatchVault;exports.assertVaultProviderHintAccepted=e.assertVaultProviderHintAccepted;exports.buildAndBroadcastReclaim=e.buildAndBroadcastReclaim;exports.buildAndBroadcastRefund=e.buildAndBroadcastRefund;exports.claimExpiredVault=e.claimExpiredVault;exports.copyAssertConnectorLeaf=e.copyAssertConnectorLeaf;exports.deriveClaimerWotsKeypair=e.deriveClaimerWotsKeypair;exports.estimateRefundFeeSats=e.estimateRefundFeeSats;exports.fingerprintReturnedGraph=e.fingerprintReturnedGraph;exports.isApplicationEntryPointMismatchError=e.isApplicationEntryPointMismatchError;exports.isDepositAmountValid=e.isDepositAmountValid;exports.isHintAccepted=e.isHintAccepted;exports.isParticipantKeyDriftError=e.isParticipantKeyDriftError;exports.isPeginRegistrationMissingError=e.isPeginRegistrationMissingError;exports.isPeginRegistrationNotFinalError=e.isPeginRegistrationNotFinalError;exports.isRegisteredVaultVersionMismatchError=e.isRegisteredVaultVersionMismatchError;exports.isUnsupportedPayoutScriptError=e.isUnsupportedPayoutScriptError;exports.matchKeyHint=e.matchKeyHint;exports.matchKeySetHint=e.matchKeySetHint;exports.planDelegatedClaimSigning=e.planDelegatedClaimSigning;exports.readDelegatedClaimVaultContext=e.readDelegatedClaimVaultContext;exports.readRefundPrePeginContext=e.readRefundPrePeginContext;exports.readStampedParticipantKeys=e.readStampedParticipantKeys;exports.resolveCurrentParticipantKeys=e.resolveCurrentParticipantKeys;exports.resolveParticipantKeysAtEpochs=e.resolveParticipantKeysAtEpochs;exports.runDepositorPresignFlow=e.runDepositorPresignFlow;exports.signDelegatedClaimPlan=e.signDelegatedClaimPlan;exports.signDepositorGraph=e.signDepositorGraph;exports.submitWotsPublicKey=e.submitWotsPublicKey;exports.summarizeWatchtowerArtifacts=e.summarizeWatchtowerArtifacts;exports.validateDepositAmount=e.validateDepositAmount;exports.validateMultiVaultDepositInputs=e.validateMultiVaultDepositInputs;exports.validateOnChainParticipantKeys=e.validateOnChainParticipantKeys;exports.validateProviderSelection=e.validateProviderSelection;exports.validateRemainingCapacity=e.validateRemainingCapacity;exports.validateVaultAmounts=e.validateVaultAmounts;exports.validateVaultProviderPubkey=e.validateVaultProviderPubkey;exports.verifyRegisteredParticipantKeys=e.verifyRegisteredParticipantKeys;exports.verifyRegisteredVaultVersions=e.verifyRegisteredVaultVersions;exports.waitForPeginRegistrationDepth=e.waitForPeginRegistrationDepth;exports.waitForPeginStatus=e.waitForPeginStatus;exports.ContractStatus=g.ContractStatus;exports.PeginAction=g.PeginAction;exports.activationDeadlineBlocksRemaining=g.activationDeadlineBlocksRemaining;exports.canPerformAction=g.canPerformAction;exports.getPeginProtocolState=g.getPeginProtocolState;exports.isActivationDeadlinePassedOnChain=g.isActivationDeadlinePassedOnChain;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|