@babylonlabs-io/ts-sdk 3.3.0 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{BTCVaultRegistry.abi-BzNTa_EU.js → BTCVaultRegistry.abi-DnP4UkB5.js} +9 -140
- package/dist/BTCVaultRegistry.abi-DnP4UkB5.js.map +1 -0
- package/dist/{BTCVaultRegistry.abi-BH2-LHxN.cjs → BTCVaultRegistry.abi-DzbfZ9_s.cjs} +2 -2
- package/dist/BTCVaultRegistry.abi-DzbfZ9_s.cjs.map +1 -0
- package/dist/{PayoutManager-xEGvTbhL.js → PayoutManager-BUWP-H-q.js} +3 -3
- package/dist/PayoutManager-BUWP-H-q.js.map +1 -0
- package/dist/{PayoutManager-B1Ev0r7o.cjs → PayoutManager-Dopxq_Jv.cjs} +2 -2
- package/dist/PayoutManager-Dopxq_Jv.cjs.map +1 -0
- package/dist/PeginManager-CMbRRTnr.cjs +2 -0
- package/dist/{PeginManager-Co43rW_x.cjs.map → PeginManager-CMbRRTnr.cjs.map} +1 -1
- package/dist/{PeginManager-BJnUgW8C.js → PeginManager-Cas6_j7t.js} +118 -107
- package/dist/{PeginManager-BJnUgW8C.js.map → PeginManager-Cas6_j7t.js.map} +1 -1
- package/dist/{ProtocolParams.abi-Cv77fsUe.js → ProtocolParams.abi-CuDl7AuC.js} +3 -3
- package/dist/{ProtocolParams.abi-Cv77fsUe.js.map → ProtocolParams.abi-CuDl7AuC.js.map} +1 -1
- package/dist/{ProtocolParams.abi-BgEZaQ2I.cjs → ProtocolParams.abi-DWfIh6VH.cjs} +2 -2
- package/dist/{ProtocolParams.abi-BgEZaQ2I.cjs.map → ProtocolParams.abi-DWfIh6VH.cjs.map} +1 -1
- package/dist/VaultErrors.abi-Dc3UnB_h.js +5 -0
- package/dist/{VaultErrors.abi-Boz4w97c.js.map → VaultErrors.abi-Dc3UnB_h.js.map} +1 -1
- package/dist/VaultErrors.abi-Hjn1CdLs.cjs +2 -0
- package/dist/{VaultErrors.abi-DQ18kM0L.cjs.map → VaultErrors.abi-Hjn1CdLs.cjs.map} +1 -1
- package/dist/buildAndBroadcastReclaim-CVmG3ldA.cjs +2 -0
- package/dist/buildAndBroadcastReclaim-CVmG3ldA.cjs.map +1 -0
- package/dist/{buildAndBroadcastReclaim-CQANDXVJ.js → buildAndBroadcastReclaim-XRWuJWVL.js} +48 -50
- package/dist/buildAndBroadcastReclaim-XRWuJWVL.js.map +1 -0
- package/dist/{challengeAssert-C3eMcM5Y.cjs → challengeAssert-BE6Wm4x1.cjs} +2 -2
- package/dist/challengeAssert-BE6Wm4x1.cjs.map +1 -0
- package/dist/{challengeAssert-B2otuf7y.js → challengeAssert-DUKSjirl.js} +3 -3
- package/dist/challengeAssert-DUKSjirl.js.map +1 -0
- package/dist/constants-BCg6O0PX.cjs +2 -0
- package/dist/constants-BCg6O0PX.cjs.map +1 -0
- package/dist/constants-CmDDuM3L.js +50 -0
- package/dist/constants-CmDDuM3L.js.map +1 -0
- package/dist/{index-BRsWXDlv.js → index-B-9aXMxk.js} +6 -6
- package/dist/{index-BRsWXDlv.js.map → index-B-9aXMxk.js.map} +1 -1
- package/dist/{index-C6avwx1s.cjs → index-Dn7RlsKK.cjs} +2 -2
- package/dist/{index-C6avwx1s.cjs.map → index-Dn7RlsKK.cjs.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +16 -16
- package/dist/pegin-registration-client-DLlaZbsZ.cjs +2 -0
- package/dist/pegin-registration-client-DLlaZbsZ.cjs.map +1 -0
- package/dist/{pegin-registration-client-Cvjk4ILq.js → pegin-registration-client-ZI0k10_3.js} +90 -96
- package/dist/pegin-registration-client-ZI0k10_3.js.map +1 -0
- package/dist/{primeVpAuth-D4UWXQ76.js → primeVpAuth-C-ET0XF4.js} +2 -2
- package/dist/{primeVpAuth-D4UWXQ76.js.map → primeVpAuth-C-ET0XF4.js.map} +1 -1
- package/dist/{primeVpAuth-CXNXYKrh.cjs → primeVpAuth-Ch-ig2My.cjs} +2 -2
- package/dist/{primeVpAuth-CXNXYKrh.cjs.map → primeVpAuth-Ch-ig2My.cjs.map} +1 -1
- package/dist/registration-records-CKc0OVuK.cjs +2 -0
- package/dist/registration-records-CKc0OVuK.cjs.map +1 -0
- package/dist/{registration-records-DJJC2NiO.js → registration-records-D39ApuHS.js} +141 -141
- package/dist/registration-records-D39ApuHS.js.map +1 -0
- package/dist/shared/index.cjs.map +1 -1
- package/dist/shared/index.js.map +1 -1
- package/dist/shared/wallets/interfaces/BitcoinWallet.d.ts +5 -0
- package/dist/shared/wallets/interfaces/BitcoinWallet.d.ts.map +1 -1
- package/dist/{signer-set-reader-GrFe_rsW.cjs → signer-set-reader-CJfV-GDz.cjs} +2 -2
- package/dist/{signer-set-reader-GrFe_rsW.cjs.map → signer-set-reader-CJfV-GDz.cjs.map} +1 -1
- package/dist/{signer-set-reader-CSUe92zE.js → signer-set-reader-DiwLeqik.js} +3 -3
- package/dist/{signer-set-reader-CSUe92zE.js.map → signer-set-reader-DiwLeqik.js.map} +1 -1
- package/dist/tbv/core/clients/eth/index.cjs +1 -1
- package/dist/tbv/core/clients/eth/index.js +4 -4
- package/dist/tbv/core/clients/eth/protocol-params-validation.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/registration-logs-error.d.ts +6 -6
- package/dist/tbv/core/clients/eth/registration-records.d.ts +1 -1
- package/dist/tbv/core/clients/eth/types.d.ts +12 -13
- package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts +1 -1
- package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -1
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +6 -6
- package/dist/tbv/core/clients/vault-provider/status/index.cjs +1 -1
- package/dist/tbv/core/clients/vault-provider/status/index.js +1 -1
- package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts +5 -111
- package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts.map +1 -1
- package/dist/tbv/core/contracts/abis/ProtocolParams.abi.d.ts +2 -2
- package/dist/tbv/core/contracts/abis/vaultErrors.abi.json.d.ts +1 -1
- package/dist/tbv/core/contracts/index.cjs +1 -1
- package/dist/tbv/core/contracts/index.js +3 -3
- package/dist/tbv/core/deposit-terms/__tests__/rebuildDepositTermsCore.test.d.ts +1 -1
- package/dist/tbv/core/deposit-terms/commissionCeiling.d.ts +1 -1
- package/dist/tbv/core/deposit-terms/depositTerms.d.ts +5 -5
- package/dist/tbv/core/deposit-terms/rebuildDepositTermsCore.d.ts.map +1 -1
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +16 -16
- package/dist/tbv/core/managers/PeginManager.d.ts +2 -1
- package/dist/tbv/core/managers/PeginManager.d.ts.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/__tests__/vaultCoreVersion.test.d.ts +1 -1
- package/dist/tbv/core/primitives/index.cjs +1 -1
- package/dist/tbv/core/primitives/index.js +3 -3
- package/dist/tbv/core/primitives/psbt/__tests__/deriveExpectedPeginPayoutScriptPubKey.test.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/constants.d.ts +38 -13
- package/dist/tbv/core/primitives/psbt/constants.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/depositorClaim.d.ts +3 -6
- package/dist/tbv/core/primitives/psbt/depositorClaim.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/pegin.d.ts +3 -5
- package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
- package/dist/tbv/core/recovery/peginParamsCandidates.d.ts +1 -1
- package/dist/tbv/core/recovery/reconstructPeginParams.d.ts.map +1 -1
- package/dist/tbv/core/services/delegated-claim/__tests__/realWasmWatchtowerArtifacts.test.d.ts +2 -2
- package/dist/tbv/core/services/delegated-claim/assembleWatchtowerArtifacts.d.ts +2 -1
- package/dist/tbv/core/services/delegated-claim/assembleWatchtowerArtifacts.d.ts.map +1 -1
- package/dist/tbv/core/services/delegated-claim/deriveClaimerWotsKeypair.d.ts +1 -1
- package/dist/tbv/core/services/delegated-claim/deriveClaimerWotsKeypair.d.ts.map +1 -1
- package/dist/tbv/core/services/delegated-claim/planDelegatedClaimSigning.d.ts +2 -1
- package/dist/tbv/core/services/delegated-claim/planDelegatedClaimSigning.d.ts.map +1 -1
- package/dist/tbv/core/services/delegated-claim/readDelegatedClaimVaultContext.d.ts +1 -1
- package/dist/tbv/core/services/delegated-claim/readDelegatedClaimVaultContext.d.ts.map +1 -1
- package/dist/tbv/core/services/delegated-claim/readWatchtowerArtifacts.d.ts +3 -3
- package/dist/tbv/core/services/delegated-claim/readWatchtowerArtifacts.d.ts.map +1 -1
- package/dist/tbv/core/services/delegated-claim/types.d.ts +5 -6
- package/dist/tbv/core/services/delegated-claim/types.d.ts.map +1 -1
- package/dist/tbv/core/services/deposit/__tests__/signDepositorGraph.realGraph.test.d.ts +3 -3
- package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts.map +1 -1
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.js +2 -2
- package/dist/tbv/core/wasm/index.cjs.map +1 -1
- package/dist/tbv/core/wasm/index.d.ts +8 -11
- package/dist/tbv/core/wasm/index.d.ts.map +1 -1
- package/dist/tbv/core/wasm/index.js.map +1 -1
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +16 -16
- package/dist/toRefundInputs-BSQjDOK9.cjs +2 -0
- package/dist/toRefundInputs-BSQjDOK9.cjs.map +1 -0
- package/dist/{toRefundInputs-Dzw1cteD.js → toRefundInputs-BbbvPb2A.js} +175 -173
- package/dist/toRefundInputs-BbbvPb2A.js.map +1 -0
- package/dist/{types-BC2TGzcp.cjs → types-BnZIbDHb.cjs} +2 -2
- package/dist/types-BnZIbDHb.cjs.map +1 -0
- package/dist/{types-24A9Qoxb.js → types-K_aM5GZO.js} +39 -39
- package/dist/types-K_aM5GZO.js.map +1 -0
- package/dist/{verifyKeyPathSchnorrSignature-IIj3Z2se.js → verifyKeyPathSchnorrSignature-DPXOFOol.js} +2 -2
- package/dist/{verifyKeyPathSchnorrSignature-IIj3Z2se.js.map → verifyKeyPathSchnorrSignature-DPXOFOol.js.map} +1 -1
- package/dist/{verifyKeyPathSchnorrSignature-BRTpEH9X.cjs → verifyKeyPathSchnorrSignature-DcxCojp0.cjs} +2 -2
- package/dist/{verifyKeyPathSchnorrSignature-BRTpEH9X.cjs.map → verifyKeyPathSchnorrSignature-DcxCojp0.cjs.map} +1 -1
- package/dist/verifyScriptPathSchnorrSignature-CgDa9Rcg.cjs +2 -0
- package/dist/verifyScriptPathSchnorrSignature-CgDa9Rcg.cjs.map +1 -0
- package/dist/{verifyScriptPathSchnorrSignature-owu3BfyT.js → verifyScriptPathSchnorrSignature-D-fdi-sG.js} +462 -459
- package/dist/verifyScriptPathSchnorrSignature-D-fdi-sG.js.map +1 -0
- package/package.json +3 -3
- package/dist/BTCVaultRegistry.abi-BH2-LHxN.cjs.map +0 -1
- package/dist/BTCVaultRegistry.abi-BzNTa_EU.js.map +0 -1
- package/dist/PayoutManager-B1Ev0r7o.cjs.map +0 -1
- package/dist/PayoutManager-xEGvTbhL.js.map +0 -1
- package/dist/PeginManager-Co43rW_x.cjs +0 -2
- package/dist/VaultErrors.abi-Boz4w97c.js +0 -5
- package/dist/VaultErrors.abi-DQ18kM0L.cjs +0 -2
- package/dist/buildAndBroadcastReclaim-CQANDXVJ.js.map +0 -1
- package/dist/buildAndBroadcastReclaim-DPk36Uhp.cjs +0 -2
- package/dist/buildAndBroadcastReclaim-DPk36Uhp.cjs.map +0 -1
- package/dist/challengeAssert-B2otuf7y.js.map +0 -1
- package/dist/challengeAssert-C3eMcM5Y.cjs.map +0 -1
- package/dist/constants-CAm10Qwp.cjs +0 -2
- package/dist/constants-CAm10Qwp.cjs.map +0 -1
- package/dist/constants-CvQZuxKv.js +0 -48
- package/dist/constants-CvQZuxKv.js.map +0 -1
- package/dist/pegin-registration-client-CdRyXP3j.cjs +0 -2
- package/dist/pegin-registration-client-CdRyXP3j.cjs.map +0 -1
- package/dist/pegin-registration-client-Cvjk4ILq.js.map +0 -1
- package/dist/registration-records-DJJC2NiO.js.map +0 -1
- package/dist/registration-records-XQMIKjGV.cjs +0 -2
- package/dist/registration-records-XQMIKjGV.cjs.map +0 -1
- package/dist/toRefundInputs-DTuWi--u.cjs +0 -2
- package/dist/toRefundInputs-DTuWi--u.cjs.map +0 -1
- package/dist/toRefundInputs-Dzw1cteD.js.map +0 -1
- package/dist/types-24A9Qoxb.js.map +0 -1
- package/dist/types-BC2TGzcp.cjs.map +0 -1
- package/dist/verifyScriptPathSchnorrSignature-CahYx5Td.cjs +0 -2
- package/dist/verifyScriptPathSchnorrSignature-CahYx5Td.cjs.map +0 -1
- package/dist/verifyScriptPathSchnorrSignature-owu3BfyT.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"challengeAssert-B2otuf7y.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 // Cross-check the reconstructed unfunded template against an independent\n // TypeScript derivation and the funded transaction bytes.\n // If they disagree, the template was reconstructed from the wrong\n // (hashlocks, amounts) vector — signing it would produce a refund\n // that does not spend the on-chain HTLC the depositor expects.\n // This is the explicit invariant the audit recommends: never sign a\n // refund whose template doesn't match the on-chain output bytes.\n const 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 if (actualHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `HTLC scriptPubKey mismatch at vout ${htlcVout}: reconstructed ` +\n `template expects ${expectedHtlcScriptPubKey}, funded tx carries ` +\n `${actualHtlcScriptPubKey}. Refund refused — the (hashlocks, ` +\n `pegInAmounts) vector does not match the on-chain commitment.`,\n );\n }\n\n // Value cross-check (mirrors the script check above): the template's\n // HTLC value — derived by WASM from `pegInAmounts` via the protocol\n // formula — must equal the value the funded tx pays at this output.\n // A caller that hands the full HTLC output value (or any wrong amount)\n // as `pegInAmounts` would inflate the template value and trip this\n // guard, rather than silently signing a refund built from a template\n // that disagrees with the on-chain commitment.\n const actualHtlcValue = BigInt(htlcOutput.value);\n if (actualHtlcValue !== expectedHtlcValue) {\n throw new Error(\n `HTLC value mismatch at vout ${htlcVout}: reconstructed template ` +\n `expects ${expectedHtlcValue} sat, funded tx carries ` +\n `${actualHtlcValue} sat. Refund refused — the pegInAmounts vector ` +\n `does not match the on-chain commitment.`,\n );\n }\n\n const refundTx = Transaction.fromHex(refundTxHex);\n\n if (refundTx.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 v2/v3 PegIn's nVersion-3\n * topology limits no longer constrain its children.\n */\nconst RECLAIM_TX_VERSION = 2;\n\n/**\n * nSequence for every reclaim input: RBF-enabled, no relative timelock. The\n * claim leaf carries no CSV, so this is a fee-bumping signal only.\n */\nconst RECLAIM_INPUT_SEQUENCE = 0xfffffffd;\n\n/**\n * Weight units of the reclaim transaction's skeleton — everything except the\n * inputs. Non-witness `version(4) + inCount(1) + outCount(1) + locktime(4) +\n * output(8 + 1 + 34)` = 53 B × 4, plus the 2 WU SegWit marker and flag.\n */\nconst RECLAIM_SKELETON_WEIGHT_UNITS = 214;\n\n/**\n * Weight units each script-path input adds. Non-witness `outpoint(36) +\n * scriptSigLen(1) + sequence(4)` = 41 B × 4 = 164, plus a witness of\n * `stackCount(1) + sig(1 + 64) + leafScript(1 + 34) + controlBlock(1 + 33)` =\n * 135 WU.\n *\n * Exact rather than conservative: every element is fixed-length here — a\n * 64-byte BIP-340 signature under SIGHASH_DEFAULT, the 34-byte leaf, and a\n * 33-byte control block with no merkle path.\n */\nconst RECLAIM_INPUT_WEIGHT_UNITS = 299;\n\n/** Weight units per virtual byte. */\nconst WEIGHT_UNITS_PER_VBYTE = 4;\n\n/**\n * Virtual size of an N-in/1-out reclaim transaction.\n *\n * `REFUND_VSIZE = 160` does not generalise to N inputs, and\n * `computePeginBaseFeeSats` is wrong for this shape entirely — its\n * `P2TR_INPUT_SIZE = 58` is a *key-path* input and under-fees a script-path\n * spend by roughly a quarter.\n *\n * N=1 → 129 vB; each additional input adds 75 vB.\n */\nexport function reclaimVsize(numInputs: number): number {\n if (!Number.isInteger(numInputs) || numInputs < 1) {\n throw new Error(\n `Reclaim input count must be a positive integer, got ${numInputs}.`,\n );\n }\n return Math.ceil(\n (RECLAIM_SKELETON_WEIGHT_UNITS +\n RECLAIM_INPUT_WEIGHT_UNITS * numInputs) /\n WEIGHT_UNITS_PER_VBYTE,\n );\n}\n\n/** Absolute fee in satoshis for an N-in/1-out reclaim at a given rate. */\nexport function estimateReclaimFeeSats(\n feeRateSatsVb: number,\n numInputs: number,\n): bigint {\n if (!Number.isFinite(feeRateSatsVb) || feeRateSatsVb <= 0) {\n throw new Error(\n `Reclaim fee rate must be a positive number, got ${feeRateSatsVb}.`,\n );\n }\n return BigInt(Math.ceil(feeRateSatsVb * reclaimVsize(numInputs)));\n}\n\n/** One depositor-claim reserve to sweep, with the material to bind it. */\nexport interface ReclaimReserve {\n /**\n * The contract's own copy of the depositor-signed PegIn transaction\n * (`VaultProtocolInfo.depositorSignedPeginTx`). Authoritative: its SegWit\n * txid equals the broadcast PegIn's, and its `outs[1]` carries the reserve's\n * script and value at no extra RPC cost.\n */\n depositorSignedPeginTxHex: string;\n /** Independent chain observation of `peginTxid:1` (esplora UTXO lookup). */\n observed: {\n /**\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;AAA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AAAA,IAAA;AAGjG;AAMA,SAASD,GACP1I,GACa;AACb,QAAM,EAAE,UAAA8H,GAAU,MAAAc,GAAM,iBAAAC,GAAiB,iBAAAC,MAAoB9I;AAC7D,MACE,CAAC,OAAO,UAAU6I,CAAe,KACjCA,IAAkB,KAClBA,KAAmBC;AAEnB,UAAM,IAAI;AAAA,MACR,kBAAkBF,CAAI,qBAAqBC,CAAe,kBAAkBC,IAAkB,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;"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"challengeAssert-C3eMcM5Y.cjs","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 // Cross-check the reconstructed unfunded template against an independent\n // TypeScript derivation and the funded transaction bytes.\n // If they disagree, the template was reconstructed from the wrong\n // (hashlocks, amounts) vector — signing it would produce a refund\n // that does not spend the on-chain HTLC the depositor expects.\n // This is the explicit invariant the audit recommends: never sign a\n // refund whose template doesn't match the on-chain output bytes.\n const 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 if (actualHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `HTLC scriptPubKey mismatch at vout ${htlcVout}: reconstructed ` +\n `template expects ${expectedHtlcScriptPubKey}, funded tx carries ` +\n `${actualHtlcScriptPubKey}. Refund refused — the (hashlocks, ` +\n `pegInAmounts) vector does not match the on-chain commitment.`,\n );\n }\n\n // Value cross-check (mirrors the script check above): the template's\n // HTLC value — derived by WASM from `pegInAmounts` via the protocol\n // formula — must equal the value the funded tx pays at this output.\n // A caller that hands the full HTLC output value (or any wrong amount)\n // as `pegInAmounts` would inflate the template value and trip this\n // guard, rather than silently signing a refund built from a template\n // that disagrees with the on-chain commitment.\n const actualHtlcValue = BigInt(htlcOutput.value);\n if (actualHtlcValue !== expectedHtlcValue) {\n throw new Error(\n `HTLC value mismatch at vout ${htlcVout}: reconstructed template ` +\n `expects ${expectedHtlcValue} sat, funded tx carries ` +\n `${actualHtlcValue} sat. Refund refused — the pegInAmounts vector ` +\n `does not match the on-chain commitment.`,\n );\n }\n\n const refundTx = Transaction.fromHex(refundTxHex);\n\n if (refundTx.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 v2/v3 PegIn's nVersion-3\n * topology limits no longer constrain its children.\n */\nconst RECLAIM_TX_VERSION = 2;\n\n/**\n * nSequence for every reclaim input: RBF-enabled, no relative timelock. The\n * claim leaf carries no CSV, so this is a fee-bumping signal only.\n */\nconst RECLAIM_INPUT_SEQUENCE = 0xfffffffd;\n\n/**\n * Weight units of the reclaim transaction's skeleton — everything except the\n * inputs. Non-witness `version(4) + inCount(1) + outCount(1) + locktime(4) +\n * output(8 + 1 + 34)` = 53 B × 4, plus the 2 WU SegWit marker and flag.\n */\nconst RECLAIM_SKELETON_WEIGHT_UNITS = 214;\n\n/**\n * Weight units each script-path input adds. Non-witness `outpoint(36) +\n * scriptSigLen(1) + sequence(4)` = 41 B × 4 = 164, plus a witness of\n * `stackCount(1) + sig(1 + 64) + leafScript(1 + 34) + controlBlock(1 + 33)` =\n * 135 WU.\n *\n * Exact rather than conservative: every element is fixed-length here — a\n * 64-byte BIP-340 signature under SIGHASH_DEFAULT, the 34-byte leaf, and a\n * 33-byte control block with no merkle path.\n */\nconst RECLAIM_INPUT_WEIGHT_UNITS = 299;\n\n/** Weight units per virtual byte. */\nconst WEIGHT_UNITS_PER_VBYTE = 4;\n\n/**\n * Virtual size of an N-in/1-out reclaim transaction.\n *\n * `REFUND_VSIZE = 160` does not generalise to N inputs, and\n * `computePeginBaseFeeSats` is wrong for this shape entirely — its\n * `P2TR_INPUT_SIZE = 58` is a *key-path* input and under-fees a script-path\n * spend by roughly a quarter.\n *\n * N=1 → 129 vB; each additional input adds 75 vB.\n */\nexport function reclaimVsize(numInputs: number): number {\n if (!Number.isInteger(numInputs) || numInputs < 1) {\n throw new Error(\n `Reclaim input count must be a positive integer, got ${numInputs}.`,\n );\n }\n return Math.ceil(\n (RECLAIM_SKELETON_WEIGHT_UNITS +\n RECLAIM_INPUT_WEIGHT_UNITS * numInputs) /\n WEIGHT_UNITS_PER_VBYTE,\n );\n}\n\n/** Absolute fee in satoshis for an N-in/1-out reclaim at a given rate. */\nexport function estimateReclaimFeeSats(\n feeRateSatsVb: number,\n numInputs: number,\n): bigint {\n if (!Number.isFinite(feeRateSatsVb) || feeRateSatsVb <= 0) {\n throw new Error(\n `Reclaim fee rate must be a positive number, got ${feeRateSatsVb}.`,\n );\n }\n return BigInt(Math.ceil(feeRateSatsVb * reclaimVsize(numInputs)));\n}\n\n/** One depositor-claim reserve to sweep, with the material to bind it. */\nexport interface ReclaimReserve {\n /**\n * The contract's own copy of the depositor-signed PegIn transaction\n * (`VaultProtocolInfo.depositorSignedPeginTx`). Authoritative: its SegWit\n * txid equals the broadcast PegIn's, and its `outs[1]` carries the reserve's\n * script and value at no extra RPC cost.\n */\n depositorSignedPeginTxHex: string;\n /** Independent chain observation of `peginTxid:1` (esplora UTXO lookup). */\n observed: {\n /**\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":"wUAoBMA,GAAW,IAAM,KAAO,GAYvB,SAASC,EACdC,EACAC,EACU,CACV,GAAI,CAAC,MAAM,QAAQD,CAAM,EACvB,MAAM,IAAI,MACR,GAAGC,CAAK,8CAA8C,OAAOD,CAAM,IAAA,EAGvE,GAAIA,EAAO,SAAW,EACpB,MAAM,IAAI,MAAM,GAAGC,CAAK,qBAAqB,EAE/C,OAAAD,EAAO,QAAQ,CAACE,EAAOC,IAAU,CAC/B,GAAI,OAAOD,GAAU,SACnB,MAAM,IAAI,MACR,GAAGD,CAAK,IAAIE,CAAK,2BAA2B,OAAOD,CAAK,2CAAA,EAI5D,GAAIA,GAAS,GACX,MAAM,IAAI,MAAM,GAAGD,CAAK,IAAIE,CAAK,sBAAsBD,CAAK,IAAI,EAElE,GAAIA,EAAQJ,EACV,MAAM,IAAI,MACR,GAAGG,CAAK,IAAIE,CAAK,4BAA4BD,CAAK,2CAAA,CAIxD,CAAC,EACMF,CACT,CCSA,eAAsBI,EACpBC,EACgC,CAChC,KAAM,CAAE,eAAAC,GAAmB,MAAMC,cAAA,EAE3B,CAAE,eAAAC,EAAgB,oBAAAC,EAAqB,SAAAC,EAAU,UAAAC,EAAW,SAAAC,GAChEP,EAYIQ,EAA2BC,EAAAA,wBAC/BN,EAAe,cAAA,EAIXO,EAAa,IAAIT,EACrBE,EAAe,iBACfA,EAAe,gBACfA,EAAe,oBACfA,EAAe,mBACfA,EAAe,2BACf,CAAC,GAAGA,EAAe,SAAS,EAC5B,IAAI,eACFT,EAA0BS,EAAe,aAAc,cAAc,CAAA,EAEvEA,EAAe,eAC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C1CE,EAAAA,kCAAkC,uBAAuBP,CAAI,SAAA,EAItE,MAAMrC,EAAK,IAAInF,cACf,OAAAmF,EAAG,QAAU6C,EAAAA,4BACb7C,EAAG,SAAW8C,EAAAA,6BACd9C,EAAG,SAASuB,EAAS,QAAA,EAAWiB,EAAMO,EAAAA,+BAA+B,EACrE/C,EAAG,UACDrE,EAAAA,OAAO,KAAKwC,EAAAA,gBAAgB1E,EAAO,2BAA2B,CAAC,EAC/DkJ,CAAA,EAEF3C,EAAG,UACDrE,EAAAA,OAAO,KACLwC,kBAAgBnC,EAAAA,2BAA2BvC,EAAO,gBAAgB,CAAC,CAAA,EAErEmJ,EAAAA,kCAAA,EAEK5C,CACT"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const _="6a20";exports.ASSERT_CLAIM_INPUT_INDEX=0;exports.ASSERT_FIRST_CHALLENGER_CONNECTOR_VOUT=1;exports.ASSERT_MARKER_FIRST_VAULT_CORE_VERSION=2;exports.ASSERT_NON_CHALLENGER_OUTPUT_COUNT=2;exports.ASSERT_PAYOUT_OUTPUT_INDEX=0;exports.BPS_DENOMINATOR=1e4;exports.CHALLENGE_ASSERT_ANCHOR_VALUE_SATS=546;exports.CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER=2;exports.CHALLENGE_ASSERT_INPUT_SEQUENCE=4294967295;exports.CHALLENGE_ASSERT_OUTPUT_CONNECTOR_INDEX=0;exports.CHALLENGE_ASSERT_TX_LOCKTIME=0;exports.CHALLENGE_ASSERT_TX_VERSION=3;exports.CLAIM_CONNECTOR_OUTPUT_INDEX=0;exports.CLAIM_PEGIN_INPUT_INDEX=0;exports.DEPOSITOR_PAYOUT_INPUT_COUNT=2;exports.DEPOSITOR_SIGNED_INPUT_COUNT=1;exports.MAX_PAYOUT_SCRIPT_LEN=128;exports.MAX_VP_COMMISSION_BPS_EXCLUSIVE=1e4;exports.NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT=2;exports.NOPAYOUT_ASSERT_INPUT_SEQUENCE=4294967295;exports.NOPAYOUT_INPUT_COUNT=3;exports.NOPAYOUT_TX_LOCKTIME=0;exports.NOPAYOUT_TX_VERSION=2;exports.PAYOUT_ANCHOR_DUST_SATS=546;exports.PAYOUT_ASSERT_INPUT_INDEX=1;exports.PAYOUT_DESTINATION_OUTPUT_INDEX=0;exports.PAYOUT_PEGIN_INPUT_INDEX=0;exports.PAYOUT_TX_LOCKTIME=0;exports.PAYOUT_TX_VERSION=2;exports.PEGIN_INPUT_SEQUENCE=4294967294;exports.PEGIN_TX_LOCKTIME=0;exports.PEGIN_TX_VERSION_CORE_1=2;exports.PEGIN_TX_VERSION_CORE_2_AND_3=3;exports.PEGIN_VAULT_OUTPUT_INDEX=0;exports.PRE_PEGIN_AUTH_OUTPUT_VALUE_SATS=0;exports.PRE_PEGIN_AUTH_SCRIPT_PREFIX=_;exports.PRE_PEGIN_CPFP_VALUE_SATS=546;exports.PRE_PEGIN_MIN_HTLC_OUTPUT_COUNT=1;exports.PRE_PEGIN_TX_LOCKTIME=0;exports.PRE_PEGIN_TX_VERSION=2;exports.REFUND_TX_LOCKTIME=0;exports.REFUND_TX_VERSION=2;exports.VP_CLAIMER_PAYOUT_OUTPUT_COUNT=3;exports.WRONGLY_CHALLENGED_INPUT_INDEX=0;
|
|
2
|
-
//# sourceMappingURL=constants-CAm10Qwp.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"constants-CAm10Qwp.cjs","sources":["../src/tbv/core/primitives/psbt/constants.ts"],"sourcesContent":["/**\n * Protocol invariants for depositor graph transactions.\n *\n * These indices and counts encode the on-chain vault protocol layout\n * (which output of PegIn/Assert each child transaction spends, and how\n * many inputs each transaction has). Consumed by the PSBT builders and\n * the depositor graph signing service; a drift between copies of these\n * values would silently change validation behaviour.\n *\n * @module primitives/psbt/constants\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md\n */\n\n/**\n * Depositor Payout transaction input count.\n * Input 0: PegIn:0 ({@link PAYOUT_PEGIN_INPUT_INDEX}). Input 1: Assert:0\n * ({@link PAYOUT_ASSERT_INPUT_INDEX} carries the signing regimes).\n */\nexport const DEPOSITOR_PAYOUT_INPUT_COUNT = 2;\n\n/**\n * Inputs the depositor signs per Payout / NoPayout PSBT at deposit time:\n * input 0 only. The other inputs are in the SIGHASH_DEFAULT sighash but carry\n * no depositor signature there — the Ledger host expects exactly this many\n * yields, so a drift here re-arms an input the device never signs at deposit\n * time.\n */\nexport const DEPOSITOR_SIGNED_INPUT_COUNT = 1;\n\n/** PegIn vault output index spent by the depositor's Payout input 0. */\nexport const PEGIN_VAULT_OUTPUT_INDEX = 0;\n\n/**\n * Assert output index of the Payout/NoPayout connector, spent by the Payout's\n * input 1 ({@link PAYOUT_ASSERT_INPUT_INDEX} carries the signing regimes) and\n * by every NoPayout's input 0.\n */\nexport const ASSERT_PAYOUT_OUTPUT_INDEX = 0;\n\n/** Payout input that spends the Vault UTXO (PegIn:{@link PEGIN_VAULT_OUTPUT_INDEX}); the depositor signs it in both regimes. */\nexport const PAYOUT_PEGIN_INPUT_INDEX = 0;\n\n/** Payout input that spends the Assert connector (Assert:{@link ASSERT_PAYOUT_OUTPUT_INDEX}); the claimer signs it, which is the depositor only in a delegated claim. */\nexport const PAYOUT_ASSERT_INPUT_INDEX = 1;\n\n/**\n * Claim input that spends the vault's PegIn. A depositor-as-claimer recovery\n * Claim is funded by exactly the PegIn's depositor-claim output\n * (`DEPOSITOR_CLAIM_VOUT = 1` in btc-vault `crates/vault/src/lib.rs:272`, used by\n * `depositor_claim_funding_outpoint` in `crates/vault/src/transactions/claim.rs:119-121`\n * @ ac4954e7); the depositor signs it.\n */\nexport const CLAIM_PEGIN_INPUT_INDEX = 0;\n\n/**\n * Assert input that spends the Claim connector\n * (Claim:{@link CLAIM_CONNECTOR_OUTPUT_INDEX}); the claimer signs it. Matches\n * `CLAIM_ASSERT_INPUT` in btc-vault `crates/vault/src/transactions/assert.rs:56` @ ac4954e7.\n */\nexport const ASSERT_CLAIM_INPUT_INDEX = 0;\n\n/**\n * Claim output the Assert spends. Matches `CLAIM_ASSERT_OUTPUT_INDEX` in\n * btc-vault `crates/vault/src/transactions/claim.rs:25` @ ac4954e7.\n */\nexport const CLAIM_CONNECTOR_OUTPUT_INDEX = 0;\n\n/**\n * WronglyChallenged input that spends the ChallengeAssert connector; the\n * claimer signs it, which is the depositor only in a delegated claim. Matches\n * `CHALLENGE_ASSERT_INPUT` in btc-vault\n * `crates/vault/src/transactions/wrongly_challenged.rs:35`, the input\n * `claimer_signing_psbt` hands the external signer (`:187`) and `sign_claimer`\n * signs natively (`:243`) @ ac4954e7.\n */\nexport const WRONGLY_CHALLENGED_INPUT_INDEX = 0;\n\n/**\n * Dust amount (sats) for the payout CPFP anchor output. Matches `DUST_AMOUNT`\n * in `btc-vault crates/vault/src/lib.rs`.\n */\nexport const PAYOUT_ANCHOR_DUST_SATS = 546;\n\n/** Minimum number of HTLC outputs in a Pre-PegIn transaction. */\nexport const PRE_PEGIN_MIN_HTLC_OUTPUT_COUNT = 1;\n\n/** Canonical value in sats for the optional Pre-PegIn auth output. */\nexport const PRE_PEGIN_AUTH_OUTPUT_VALUE_SATS = 0;\n\n/**\n * Hex prefix for `OP_RETURN PUSH32`. This matches\n * `ScriptBuf::new_op_return(hash)` in\n * `btc-vault crates/vault/src/transactions/prepegin.rs`.\n */\nexport const PRE_PEGIN_AUTH_SCRIPT_PREFIX = \"6a20\";\n\n/**\n * Value in sats for the Pre-PegIn CPFP anchor output. Matches `DUST_AMOUNT`\n * in `btc-vault crates/vault/src/lib.rs`.\n */\nexport const PRE_PEGIN_CPFP_VALUE_SATS = 546;\n\n/**\n * Canonical Pre-PegIn transaction version. Matches `Version::TWO` in\n * `btc-vault crates/vault/src/transactions/prepegin.rs`.\n */\nexport const PRE_PEGIN_TX_VERSION = 2;\n\n/**\n * Canonical Pre-PegIn transaction locktime. Matches `LockTime::ZERO` in\n * `btc-vault crates/vault/src/transactions/prepegin.rs`.\n */\nexport const PRE_PEGIN_TX_LOCKTIME = 0;\n\n/** Vault Core 1 PegIn nVersion from `PegInTx::expected_tx_version`. */\nexport const PEGIN_TX_VERSION_CORE_1 = 2;\n\n/** Vault Core 2 and 3 PegIn nVersion from `PegInTx::expected_tx_version`. */\nexport const PEGIN_TX_VERSION_CORE_2_AND_3 = 3;\n\n/** PegIn locktime from `PegInTx::new_from_prepegin` (`LockTime::ZERO`). */\nexport const PEGIN_TX_LOCKTIME = 0;\n\n/** PegIn input sequence from `PegInTx::new_from_prepegin`. */\nexport const PEGIN_INPUT_SEQUENCE = 0xfffffffe;\n\n/**\n * Refund version and locktime match `WasmPrePeginTx::build_refund_tx`\n * (`Version::TWO`, `LockTime::ZERO`) in `btc-vault crates/vault/src/wasm/api.rs`.\n */\nexport const REFUND_TX_VERSION = 2;\nexport const REFUND_TX_LOCKTIME = 0;\n\n/**\n * Payout transaction literals btc-vault builds deterministically\n * (`crates/vault/src/transactions/payout.rs`: `Version::TWO`,\n * `LockTime::ZERO`). The depositor's signature commits to both, so a\n * VP-supplied payout that deviates would produce a signature over a\n * transaction the protocol never constructs.\n */\nexport const PAYOUT_TX_VERSION = 2;\nexport const PAYOUT_TX_LOCKTIME = 0;\n\n/**\n * Payout output that pays the payout receiver, resolved per claimer role (the\n * depositor's registered script for a VP or depositor claimer, the keeper's\n * for an AVK claimer — btc-vault `tx_graph/graph.rs:100-106` @ ac4954e7).\n * btc-vault has no named constant for the index itself:\n * `build_payout_outputs` (`crates/vault/src/transactions/mod.rs:206`)\n * returns the destination as `output0` in both layouts — `:246`/`:256` with a\n * VP commission, `:266`/`:270` without — and `transactions/payout.rs:153`\n * pushes the CPFP anchor after them @ ac4954e7.\n */\nexport const PAYOUT_DESTINATION_OUTPUT_INDEX = 0;\n\n/** VP-claimer payout output count: [depositor payout, VP commission, CPFP anchor]. */\nexport const VP_CLAIMER_PAYOUT_OUTPUT_COUNT = 3;\n\n/** Depositor/VK-claimer payout output count: [claimer payout, CPFP anchor]. */\nexport const NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT = 2;\n\n/**\n * ChallengeAssert connectors the VP returns per challenger: one for the\n * ChallengeAssertX transaction and one for ChallengeAssertY — two single-input\n * transactions, not a single multi-input one. This is a per-challenger array\n * cardinality, NOT a count of inputs in one transaction.\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md (ChallengeAssertX / ChallengeAssertY)\n */\nexport const CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER = 2;\n\n/**\n * First Assert output holding a per-challenger ChallengeAssert connector.\n * ConnectorX for sorted challenger `i` is at `1 + i`, ConnectorY at\n * `1 + K + i` (K = local + universal challengers), per btc-vault\n * `crates/vault/src/transactions/challenge_assert.rs:165,180` @ b534ff9e.\n */\nexport const ASSERT_FIRST_CHALLENGER_CONNECTOR_VOUT = 1;\n\n/**\n * Assert outputs besides the challenger connectors: output 0 (Payout /\n * NoPayout / CouncilNoPayout connector) and the claimer's CPFP anchor, last\n * (btc-vault `crates/vault/src/transactions/assert.rs:7-13` @ b534ff9e).\n */\nexport const ASSERT_NON_CHALLENGER_OUTPUT_COUNT = 2;\n\n/**\n * First `vaultCoreVersion` whose Assert carries the RFC-008 marker\n * `OP_RETURN` before the anchor. Matches `FIRST_MARKER_CORE_VERSION` in\n * btc-vault `crates/vault/src/assert_marker.rs:48` @ b534ff9e; the graph-v1\n * pin (2c1177ec) predates the marker.\n */\nexport const ASSERT_MARKER_FIRST_VAULT_CORE_VERSION = 2;\n\n/**\n * ChallengeAssertX/Y literals btc-vault builds deterministically\n * (`build_challenge_assert_tx`, `crates/vault/src/transactions/challenge_assert.rs:49-96`\n * @ b534ff9e, identical at the 2c1177ec and 27c0062b pins): nVersion 3 with\n * zero fee, `LockTime::ZERO`, one input at `Sequence::MAX`, and a\n * `DUST_AMOUNT` CPFP anchor to the challenger's BIP-86 key as output 1.\n * Output 0 is the ChallengeAssert output connector, worth the spent Assert\n * output minus the anchor.\n */\nexport const CHALLENGE_ASSERT_TX_VERSION = 3;\nexport const CHALLENGE_ASSERT_TX_LOCKTIME = 0;\nexport const CHALLENGE_ASSERT_INPUT_SEQUENCE = 0xffffffff;\nexport const CHALLENGE_ASSERT_ANCHOR_VALUE_SATS = 546;\n\n/**\n * NoPayout literals from `NoPayoutTx::new`\n * (`crates/vault/src/transactions/nopayout.rs:148-209` @ b534ff9e):\n * `Version::TWO`, `LockTime::ZERO`, Assert:0 at `Sequence::MAX` as input 0,\n * then ChallengeAssertX:0 and ChallengeAssertY:0, each with the\n * `timelockChallengeAssert` CSV as its sequence.\n */\nexport const NOPAYOUT_TX_VERSION = 2;\nexport const NOPAYOUT_TX_LOCKTIME = 0;\nexport const NOPAYOUT_ASSERT_INPUT_SEQUENCE = 0xffffffff;\n\n/** NoPayout input count: Assert:0, ChallengeAssertX:0, ChallengeAssertY:0. */\nexport const NOPAYOUT_INPUT_COUNT = 3;\n\n/** ChallengeAssert output NoPayout spends (`CHALLENGE_ASSERT_OUTPUT_CONNECTOR_INDEX`). */\nexport const CHALLENGE_ASSERT_OUTPUT_CONNECTOR_INDEX = 0;\n\n/**\n * Exclusive upper bound on VP commission (bps). Matches\n * `VPKeyRegistryLogic.sol` (`commissionBps >= 10000` reverts).\n * The minimum is version-locked (`minVpCommissionBps`) and enforced upstream,\n * not here.\n */\nexport const MAX_VP_COMMISSION_BPS_EXCLUSIVE = 10_000;\n\n/**\n * Basis-points denominator for commission math:\n * `floor(value * bps / BPS_DENOMINATOR)`. Numerically equal to\n * {@link MAX_VP_COMMISSION_BPS_EXCLUSIVE} but a distinct concept — tightening\n * the accepted bps range must never change the arithmetic.\n */\nexport const BPS_DENOMINATOR = 10_000;\n\n/**\n * Contract cap on a registered payout/commission scriptPubKey's byte length\n * (`MAX_PAYOUT_ADDRESS_LENGTH`, Constants.sol; empty scripts are rejected at\n * registration, so valid lengths are `[1, 128]`). A measured length outside\n * this range is provably not a registered script.\n */\nexport const MAX_PAYOUT_SCRIPT_LEN = 128;\n"],"names":["PRE_PEGIN_AUTH_SCRIPT_PREFIX"],"mappings":"aA8FO,MAAMA,EAA+B"}
|
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
const _ = 2, E = 1, T = 0, N = 0, s = 0, O = 1, I = 0, P = 0, U = 0, A = 0, S = 546, R = 1, C = 0, a = "6a20", o = 546, t = 2, c = 0, n = 2, L = 3, X = 0, G = 4294967294, D = 2, M = 0, V = 2, H = 0, Y = 0, K = 3, F = 2, e = 2, B = 1, Q = 2, p = 2, r = 3, x = 0, W = 4294967295, b = 546, d = 2, f = 0, g = 4294967295, h = 3, i = 0, j = 1e4, k = 1e4, l = 128;
|
|
2
|
-
export {
|
|
3
|
-
N as A,
|
|
4
|
-
k as B,
|
|
5
|
-
i as C,
|
|
6
|
-
E as D,
|
|
7
|
-
O as E,
|
|
8
|
-
s as F,
|
|
9
|
-
U as G,
|
|
10
|
-
I as H,
|
|
11
|
-
Y as I,
|
|
12
|
-
Q as J,
|
|
13
|
-
e as K,
|
|
14
|
-
p as L,
|
|
15
|
-
j as M,
|
|
16
|
-
d as N,
|
|
17
|
-
t as P,
|
|
18
|
-
D as R,
|
|
19
|
-
K as V,
|
|
20
|
-
A as W,
|
|
21
|
-
M as a,
|
|
22
|
-
f as b,
|
|
23
|
-
h as c,
|
|
24
|
-
g as d,
|
|
25
|
-
b as e,
|
|
26
|
-
r as f,
|
|
27
|
-
x as g,
|
|
28
|
-
W as h,
|
|
29
|
-
B as i,
|
|
30
|
-
l as j,
|
|
31
|
-
c as k,
|
|
32
|
-
R as l,
|
|
33
|
-
C as m,
|
|
34
|
-
a as n,
|
|
35
|
-
o,
|
|
36
|
-
n as p,
|
|
37
|
-
L as q,
|
|
38
|
-
X as r,
|
|
39
|
-
G as s,
|
|
40
|
-
_ as t,
|
|
41
|
-
V as u,
|
|
42
|
-
H as v,
|
|
43
|
-
S as w,
|
|
44
|
-
T as x,
|
|
45
|
-
F as y,
|
|
46
|
-
P as z
|
|
47
|
-
};
|
|
48
|
-
//# sourceMappingURL=constants-CvQZuxKv.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"constants-CvQZuxKv.js","sources":["../src/tbv/core/primitives/psbt/constants.ts"],"sourcesContent":["/**\n * Protocol invariants for depositor graph transactions.\n *\n * These indices and counts encode the on-chain vault protocol layout\n * (which output of PegIn/Assert each child transaction spends, and how\n * many inputs each transaction has). Consumed by the PSBT builders and\n * the depositor graph signing service; a drift between copies of these\n * values would silently change validation behaviour.\n *\n * @module primitives/psbt/constants\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md\n */\n\n/**\n * Depositor Payout transaction input count.\n * Input 0: PegIn:0 ({@link PAYOUT_PEGIN_INPUT_INDEX}). Input 1: Assert:0\n * ({@link PAYOUT_ASSERT_INPUT_INDEX} carries the signing regimes).\n */\nexport const DEPOSITOR_PAYOUT_INPUT_COUNT = 2;\n\n/**\n * Inputs the depositor signs per Payout / NoPayout PSBT at deposit time:\n * input 0 only. The other inputs are in the SIGHASH_DEFAULT sighash but carry\n * no depositor signature there — the Ledger host expects exactly this many\n * yields, so a drift here re-arms an input the device never signs at deposit\n * time.\n */\nexport const DEPOSITOR_SIGNED_INPUT_COUNT = 1;\n\n/** PegIn vault output index spent by the depositor's Payout input 0. */\nexport const PEGIN_VAULT_OUTPUT_INDEX = 0;\n\n/**\n * Assert output index of the Payout/NoPayout connector, spent by the Payout's\n * input 1 ({@link PAYOUT_ASSERT_INPUT_INDEX} carries the signing regimes) and\n * by every NoPayout's input 0.\n */\nexport const ASSERT_PAYOUT_OUTPUT_INDEX = 0;\n\n/** Payout input that spends the Vault UTXO (PegIn:{@link PEGIN_VAULT_OUTPUT_INDEX}); the depositor signs it in both regimes. */\nexport const PAYOUT_PEGIN_INPUT_INDEX = 0;\n\n/** Payout input that spends the Assert connector (Assert:{@link ASSERT_PAYOUT_OUTPUT_INDEX}); the claimer signs it, which is the depositor only in a delegated claim. */\nexport const PAYOUT_ASSERT_INPUT_INDEX = 1;\n\n/**\n * Claim input that spends the vault's PegIn. A depositor-as-claimer recovery\n * Claim is funded by exactly the PegIn's depositor-claim output\n * (`DEPOSITOR_CLAIM_VOUT = 1` in btc-vault `crates/vault/src/lib.rs:272`, used by\n * `depositor_claim_funding_outpoint` in `crates/vault/src/transactions/claim.rs:119-121`\n * @ ac4954e7); the depositor signs it.\n */\nexport const CLAIM_PEGIN_INPUT_INDEX = 0;\n\n/**\n * Assert input that spends the Claim connector\n * (Claim:{@link CLAIM_CONNECTOR_OUTPUT_INDEX}); the claimer signs it. Matches\n * `CLAIM_ASSERT_INPUT` in btc-vault `crates/vault/src/transactions/assert.rs:56` @ ac4954e7.\n */\nexport const ASSERT_CLAIM_INPUT_INDEX = 0;\n\n/**\n * Claim output the Assert spends. Matches `CLAIM_ASSERT_OUTPUT_INDEX` in\n * btc-vault `crates/vault/src/transactions/claim.rs:25` @ ac4954e7.\n */\nexport const CLAIM_CONNECTOR_OUTPUT_INDEX = 0;\n\n/**\n * WronglyChallenged input that spends the ChallengeAssert connector; the\n * claimer signs it, which is the depositor only in a delegated claim. Matches\n * `CHALLENGE_ASSERT_INPUT` in btc-vault\n * `crates/vault/src/transactions/wrongly_challenged.rs:35`, the input\n * `claimer_signing_psbt` hands the external signer (`:187`) and `sign_claimer`\n * signs natively (`:243`) @ ac4954e7.\n */\nexport const WRONGLY_CHALLENGED_INPUT_INDEX = 0;\n\n/**\n * Dust amount (sats) for the payout CPFP anchor output. Matches `DUST_AMOUNT`\n * in `btc-vault crates/vault/src/lib.rs`.\n */\nexport const PAYOUT_ANCHOR_DUST_SATS = 546;\n\n/** Minimum number of HTLC outputs in a Pre-PegIn transaction. */\nexport const PRE_PEGIN_MIN_HTLC_OUTPUT_COUNT = 1;\n\n/** Canonical value in sats for the optional Pre-PegIn auth output. */\nexport const PRE_PEGIN_AUTH_OUTPUT_VALUE_SATS = 0;\n\n/**\n * Hex prefix for `OP_RETURN PUSH32`. This matches\n * `ScriptBuf::new_op_return(hash)` in\n * `btc-vault crates/vault/src/transactions/prepegin.rs`.\n */\nexport const PRE_PEGIN_AUTH_SCRIPT_PREFIX = \"6a20\";\n\n/**\n * Value in sats for the Pre-PegIn CPFP anchor output. Matches `DUST_AMOUNT`\n * in `btc-vault crates/vault/src/lib.rs`.\n */\nexport const PRE_PEGIN_CPFP_VALUE_SATS = 546;\n\n/**\n * Canonical Pre-PegIn transaction version. Matches `Version::TWO` in\n * `btc-vault crates/vault/src/transactions/prepegin.rs`.\n */\nexport const PRE_PEGIN_TX_VERSION = 2;\n\n/**\n * Canonical Pre-PegIn transaction locktime. Matches `LockTime::ZERO` in\n * `btc-vault crates/vault/src/transactions/prepegin.rs`.\n */\nexport const PRE_PEGIN_TX_LOCKTIME = 0;\n\n/** Vault Core 1 PegIn nVersion from `PegInTx::expected_tx_version`. */\nexport const PEGIN_TX_VERSION_CORE_1 = 2;\n\n/** Vault Core 2 and 3 PegIn nVersion from `PegInTx::expected_tx_version`. */\nexport const PEGIN_TX_VERSION_CORE_2_AND_3 = 3;\n\n/** PegIn locktime from `PegInTx::new_from_prepegin` (`LockTime::ZERO`). */\nexport const PEGIN_TX_LOCKTIME = 0;\n\n/** PegIn input sequence from `PegInTx::new_from_prepegin`. */\nexport const PEGIN_INPUT_SEQUENCE = 0xfffffffe;\n\n/**\n * Refund version and locktime match `WasmPrePeginTx::build_refund_tx`\n * (`Version::TWO`, `LockTime::ZERO`) in `btc-vault crates/vault/src/wasm/api.rs`.\n */\nexport const REFUND_TX_VERSION = 2;\nexport const REFUND_TX_LOCKTIME = 0;\n\n/**\n * Payout transaction literals btc-vault builds deterministically\n * (`crates/vault/src/transactions/payout.rs`: `Version::TWO`,\n * `LockTime::ZERO`). The depositor's signature commits to both, so a\n * VP-supplied payout that deviates would produce a signature over a\n * transaction the protocol never constructs.\n */\nexport const PAYOUT_TX_VERSION = 2;\nexport const PAYOUT_TX_LOCKTIME = 0;\n\n/**\n * Payout output that pays the payout receiver, resolved per claimer role (the\n * depositor's registered script for a VP or depositor claimer, the keeper's\n * for an AVK claimer — btc-vault `tx_graph/graph.rs:100-106` @ ac4954e7).\n * btc-vault has no named constant for the index itself:\n * `build_payout_outputs` (`crates/vault/src/transactions/mod.rs:206`)\n * returns the destination as `output0` in both layouts — `:246`/`:256` with a\n * VP commission, `:266`/`:270` without — and `transactions/payout.rs:153`\n * pushes the CPFP anchor after them @ ac4954e7.\n */\nexport const PAYOUT_DESTINATION_OUTPUT_INDEX = 0;\n\n/** VP-claimer payout output count: [depositor payout, VP commission, CPFP anchor]. */\nexport const VP_CLAIMER_PAYOUT_OUTPUT_COUNT = 3;\n\n/** Depositor/VK-claimer payout output count: [claimer payout, CPFP anchor]. */\nexport const NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT = 2;\n\n/**\n * ChallengeAssert connectors the VP returns per challenger: one for the\n * ChallengeAssertX transaction and one for ChallengeAssertY — two single-input\n * transactions, not a single multi-input one. This is a per-challenger array\n * cardinality, NOT a count of inputs in one transaction.\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md (ChallengeAssertX / ChallengeAssertY)\n */\nexport const CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER = 2;\n\n/**\n * First Assert output holding a per-challenger ChallengeAssert connector.\n * ConnectorX for sorted challenger `i` is at `1 + i`, ConnectorY at\n * `1 + K + i` (K = local + universal challengers), per btc-vault\n * `crates/vault/src/transactions/challenge_assert.rs:165,180` @ b534ff9e.\n */\nexport const ASSERT_FIRST_CHALLENGER_CONNECTOR_VOUT = 1;\n\n/**\n * Assert outputs besides the challenger connectors: output 0 (Payout /\n * NoPayout / CouncilNoPayout connector) and the claimer's CPFP anchor, last\n * (btc-vault `crates/vault/src/transactions/assert.rs:7-13` @ b534ff9e).\n */\nexport const ASSERT_NON_CHALLENGER_OUTPUT_COUNT = 2;\n\n/**\n * First `vaultCoreVersion` whose Assert carries the RFC-008 marker\n * `OP_RETURN` before the anchor. Matches `FIRST_MARKER_CORE_VERSION` in\n * btc-vault `crates/vault/src/assert_marker.rs:48` @ b534ff9e; the graph-v1\n * pin (2c1177ec) predates the marker.\n */\nexport const ASSERT_MARKER_FIRST_VAULT_CORE_VERSION = 2;\n\n/**\n * ChallengeAssertX/Y literals btc-vault builds deterministically\n * (`build_challenge_assert_tx`, `crates/vault/src/transactions/challenge_assert.rs:49-96`\n * @ b534ff9e, identical at the 2c1177ec and 27c0062b pins): nVersion 3 with\n * zero fee, `LockTime::ZERO`, one input at `Sequence::MAX`, and a\n * `DUST_AMOUNT` CPFP anchor to the challenger's BIP-86 key as output 1.\n * Output 0 is the ChallengeAssert output connector, worth the spent Assert\n * output minus the anchor.\n */\nexport const CHALLENGE_ASSERT_TX_VERSION = 3;\nexport const CHALLENGE_ASSERT_TX_LOCKTIME = 0;\nexport const CHALLENGE_ASSERT_INPUT_SEQUENCE = 0xffffffff;\nexport const CHALLENGE_ASSERT_ANCHOR_VALUE_SATS = 546;\n\n/**\n * NoPayout literals from `NoPayoutTx::new`\n * (`crates/vault/src/transactions/nopayout.rs:148-209` @ b534ff9e):\n * `Version::TWO`, `LockTime::ZERO`, Assert:0 at `Sequence::MAX` as input 0,\n * then ChallengeAssertX:0 and ChallengeAssertY:0, each with the\n * `timelockChallengeAssert` CSV as its sequence.\n */\nexport const NOPAYOUT_TX_VERSION = 2;\nexport const NOPAYOUT_TX_LOCKTIME = 0;\nexport const NOPAYOUT_ASSERT_INPUT_SEQUENCE = 0xffffffff;\n\n/** NoPayout input count: Assert:0, ChallengeAssertX:0, ChallengeAssertY:0. */\nexport const NOPAYOUT_INPUT_COUNT = 3;\n\n/** ChallengeAssert output NoPayout spends (`CHALLENGE_ASSERT_OUTPUT_CONNECTOR_INDEX`). */\nexport const CHALLENGE_ASSERT_OUTPUT_CONNECTOR_INDEX = 0;\n\n/**\n * Exclusive upper bound on VP commission (bps). Matches\n * `VPKeyRegistryLogic.sol` (`commissionBps >= 10000` reverts).\n * The minimum is version-locked (`minVpCommissionBps`) and enforced upstream,\n * not here.\n */\nexport const MAX_VP_COMMISSION_BPS_EXCLUSIVE = 10_000;\n\n/**\n * Basis-points denominator for commission math:\n * `floor(value * bps / BPS_DENOMINATOR)`. Numerically equal to\n * {@link MAX_VP_COMMISSION_BPS_EXCLUSIVE} but a distinct concept — tightening\n * the accepted bps range must never change the arithmetic.\n */\nexport const BPS_DENOMINATOR = 10_000;\n\n/**\n * Contract cap on a registered payout/commission scriptPubKey's byte length\n * (`MAX_PAYOUT_ADDRESS_LENGTH`, Constants.sol; empty scripts are rejected at\n * registration, so valid lengths are `[1, 128]`). A measured length outside\n * this range is provably not a registered script.\n */\nexport const MAX_PAYOUT_SCRIPT_LEN = 128;\n"],"names":["DEPOSITOR_PAYOUT_INPUT_COUNT","DEPOSITOR_SIGNED_INPUT_COUNT","PEGIN_VAULT_OUTPUT_INDEX","ASSERT_PAYOUT_OUTPUT_INDEX","PAYOUT_PEGIN_INPUT_INDEX","PAYOUT_ASSERT_INPUT_INDEX","CLAIM_PEGIN_INPUT_INDEX","ASSERT_CLAIM_INPUT_INDEX","CLAIM_CONNECTOR_OUTPUT_INDEX","WRONGLY_CHALLENGED_INPUT_INDEX","PAYOUT_ANCHOR_DUST_SATS","PRE_PEGIN_MIN_HTLC_OUTPUT_COUNT","PRE_PEGIN_AUTH_OUTPUT_VALUE_SATS","PRE_PEGIN_AUTH_SCRIPT_PREFIX","PRE_PEGIN_CPFP_VALUE_SATS","PRE_PEGIN_TX_VERSION","PRE_PEGIN_TX_LOCKTIME","PEGIN_TX_VERSION_CORE_1","PEGIN_TX_VERSION_CORE_2_AND_3","PEGIN_TX_LOCKTIME","PEGIN_INPUT_SEQUENCE","REFUND_TX_VERSION","REFUND_TX_LOCKTIME","PAYOUT_TX_VERSION","PAYOUT_TX_LOCKTIME","PAYOUT_DESTINATION_OUTPUT_INDEX","VP_CLAIMER_PAYOUT_OUTPUT_COUNT","NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT","CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER","ASSERT_FIRST_CHALLENGER_CONNECTOR_VOUT","ASSERT_NON_CHALLENGER_OUTPUT_COUNT","ASSERT_MARKER_FIRST_VAULT_CORE_VERSION","CHALLENGE_ASSERT_TX_VERSION","CHALLENGE_ASSERT_TX_LOCKTIME","CHALLENGE_ASSERT_INPUT_SEQUENCE","CHALLENGE_ASSERT_ANCHOR_VALUE_SATS","NOPAYOUT_TX_VERSION","NOPAYOUT_TX_LOCKTIME","NOPAYOUT_ASSERT_INPUT_SEQUENCE","NOPAYOUT_INPUT_COUNT","CHALLENGE_ASSERT_OUTPUT_CONNECTOR_INDEX","MAX_VP_COMMISSION_BPS_EXCLUSIVE","BPS_DENOMINATOR","MAX_PAYOUT_SCRIPT_LEN"],"mappings":"AAkBO,MAAMA,IAA+B,GAS/BC,IAA+B,GAG/BC,IAA2B,GAO3BC,IAA6B,GAG7BC,IAA2B,GAG3BC,IAA4B,GAS5BC,IAA0B,GAO1BC,IAA2B,GAM3BC,IAA+B,GAU/BC,IAAiC,GAMjCC,IAA0B,KAG1BC,IAAkC,GAGlCC,IAAmC,GAOnCC,IAA+B,QAM/BC,IAA4B,KAM5BC,IAAuB,GAMvBC,IAAwB,GAGxBC,IAA0B,GAG1BC,IAAgC,GAGhCC,IAAoB,GAGpBC,IAAuB,YAMvBC,IAAoB,GACpBC,IAAqB,GASrBC,IAAoB,GACpBC,IAAqB,GAYrBC,IAAkC,GAGlCC,IAAiC,GAGjCC,IAAqC,GASrCC,IAA6C,GAQ7CC,IAAyC,GAOzCC,IAAqC,GAQrCC,IAAyC,GAWzCC,IAA8B,GAC9BC,IAA+B,GAC/BC,IAAkC,YAClCC,IAAqC,KASrCC,IAAsB,GACtBC,IAAuB,GACvBC,IAAiC,YAGjCC,IAAuB,GAGvBC,IAA0C,GAQ1CC,IAAkC,KAQlCC,IAAkB,KAQlBC,IAAwB;"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const f=require("viem"),a=require("./BTCVaultRegistry.abi-BH2-LHxN.cjs"),C=require("./BTCVaultRegistryKeyEpochs.abi-CReWFJdu.cjs"),v=require("./constants-CAm10Qwp.cjs"),k=require("./tbv/core/utils/eth/index.cjs"),h=require("./registration-records-XQMIKjGV.cjs"),B=25,S=9999;function w(r){if(!Number.isInteger(r)||r<0||r>=v.MAX_VP_COMMISSION_BPS_EXCLUSIVE)throw new Error(`Quoted commissionBps must be an integer in [0, ${v.MAX_VP_COMMISSION_BPS_EXCLUSIVE}), got ${r}`);return Math.min(r+B,S)}const T=9999;function A(r){return{depositor:r.depositor,depositorBtcPubKey:r.depositorBtcPubKey,amount:r.amount,vaultProvider:r.vaultProvider,status:r.status,applicationEntryPoint:r.applicationEntryPoint,createdAt:r.createdAt}}function y(r){const t=Number(r.offchainParamsVersion);return h.assertValidOffchainParamsVersion(t),{depositorSignedPeginTx:r.depositorSignedPeginTx,universalChallengersVersion:r.universalChallengersVersion,appVaultKeepersVersion:r.appVaultKeepersVersion,offchainParamsVersion:t,verifiedAt:r.verifiedAt,depositorWotsPkHash:r.depositorWotsPkHash,hashlock:r.hashlock,htlcVout:r.htlcVout,depositorPopSignature:r.depositorPopSignature,prePeginTxHash:r.prePeginTxHash,vaultProviderCommissionBps:r.vaultProviderCommissionBps,claimExpiredUntil:r.claimExpiredUntil,vaultCoreVersion:r.vaultCoreVersion}}const _=1n<<64n,$=0n,K=[f.getAbiItem({abi:a.BTCVaultRegistryABI,name:"PegInSubmitted"}),f.getAbiItem({abi:a.BTCVaultRegistryABI,name:"PegInSubmittedV2"})],N=f.getAbiItem({abi:a.BTCVaultRegistryABI,name:"VaultClaimableBy"}),O=7200n;function M(r,t){return r>t?r:t}function H(r,t){return{vaultId:r.vaultId.toLowerCase(),depositor:r.depositor,vaultProvider:r.vaultProvider,amount:r.amount,vaultCoreVersion:r.vaultCoreVersion,universalChallengersVersion:r.universalChallengersVersion,appVaultKeepersVersion:r.appVaultKeepersVersion,proverCircuitVersion:r.proverCircuitVersion,offchainParamsVersion:r.offchainParamsVersion,peginTxHash:r.peginTxHash.toLowerCase(),depositorPayoutScriptPubKey:r.depositorPayoutBtcAddress.toLowerCase(),unsignedPrePeginTx:r.unsignedPrePeginTx,maxAcceptableCommissionBps:r.maxAcceptableCommissionBps,blockNumber:t}}function V(r,t,e){if(r<0n||r>=_)throw new Error(`getBtcVaultProtocolInfo returned ${t}=${r} for vault ${e}, outside the uint64 range — the registry may predate RFC-006`);return r}function x(r,t){return{vpKeyEpoch:V(r.vpKeyEpoch,"vpKeyEpoch",t),appKeeperKeyEpoch:V(r.appKeeperKeyEpoch,"appKeeperKeyEpoch",t),ucKeyEpoch:V(r.ucKeyEpoch,"ucKeyEpoch",t)}}class R{constructor(t,e){this.publicClient=t,this.contractAddress=e}async getVaultProviderGenesisBtcPubKey(t,e){return this.getVaultProviderOperationBtcKeyAtEpoch(t,$,e)}async getVaultProviderOperationBtcKeyAtEpoch(t,e,o){const n=await this.publicClient.readContract({address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getOperationBtcKeyAtEpoch",args:[t,e],blockNumber:o});return h.assertOnChainBtcPubkey(n,`getOperationBtcKeyAtEpoch (vp=${t}, epoch=${e})`)}async getVaultProviderApplication(t,e){return await this.publicClient.readContract({address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getVaultProviderApplication",args:[t],blockNumber:e})}async getCurrentVaultProviderOperationBtcKey(t){const e=await this.publicClient.readContract({address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getCurrentOperationBtcKey",args:[t]});return h.assertOnChainBtcPubkey(e,`getCurrentOperationBtcKey (vp=${t})`)}async getVaultKeyEpochs(t){const e=await this.publicClient.readContract({address:this.contractAddress,abi:C.BTCVaultRegistryKeyEpochsABI,functionName:"getBtcVaultProtocolInfo",args:[t]});return x(e,t)}async getVaultKeyEpochsBatch(t){return t.length===0?[]:(await this.publicClient.multicall({contracts:t.map(o=>({address:this.contractAddress,abi:C.BTCVaultRegistryKeyEpochsABI,functionName:"getBtcVaultProtocolInfo",args:[o]})),allowFailure:!1})).map((o,n)=>x(o,t[n]))}async getVaultBasicInfo(t){const e=await this.publicClient.readContract({address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[t]});return A(e)}async getVaultProtocolInfo(t){const e=await this.publicClient.readContract({address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[t]});return y(e)}async getProtocolInfoBatch(t){return t.length===0?[]:(await this.publicClient.multicall({contracts:t.map(o=>({address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[o]})),allowFailure:!1})).map((o,n)=>{const i=o;if(!i.depositorSignedPeginTx||i.depositorSignedPeginTx==="0x")throw new Error(`Vault ${t[n]} not found on-chain or has no pegin transaction`);return y(i)})}async getPegInFee(t){return await this.publicClient.readContract({address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getPegInFee",args:[t]})}async getVaultProviderCommission(t){const e=await this.publicClient.readContract({address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getVaultProviderCommission",args:[t]});if(!Number.isInteger(e)||e<0||e>T)throw new Error(`getVaultProviderCommission returned ${e} bps for ${t}, outside the protocol range [0, ${T}]`);return e}async getVaultData(t){const[e,o]=await this.publicClient.multicall({contracts:[{address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[t]},{address:this.contractAddress,abi:a.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[t]}],allowFailure:!1}),n=A(e),i=y(o);if(!i.depositorSignedPeginTx||i.depositorSignedPeginTx==="0x")throw new Error(`Vault ${t} not found on-chain or has no pegin transaction`);return{basic:n,protocol:i}}async getRegistrationRecordsAtBlock(t){const e=await this.publicClient.getLogs({address:this.contractAddress,events:K,fromBlock:t,toBlock:t,strict:!0});if(e.length===0)throw new h.RegistrationLogsUnavailableError(t);const o=new Map;for(const n of e){if(n.eventName!=="PegInSubmittedV2")continue;const i=H(n.args,n.blockNumber);if(o.has(i.vaultId))throw new Error(`Expected one PegInSubmittedV2 log for vault ${i.vaultId} at block ${t}, found more than one`);o.set(i.vaultId,i)}if(o.size===0)throw new h.RegistrationLogsUnavailableError(t,`Block ${t} holds ${e.length} PegInSubmitted registration log(s) but no PegInSubmittedV2 log: either the node served a partial answer for block ${t} (retry, preferably another node) or the registry predates the depositor's commission ceiling (vault-contracts-aave-v4 #548) and the ceiling cannot be recovered on-chain`);return[...o.values()]}async getMaxAcceptableCommissionBpsBatch(t,e){if(t.length===0)return[];const o=await this.getRegistrationRecordsAtBlock(e);return t.map(n=>h.findRegistrationRecord(o,n,e).maxAcceptableCommissionBps)}async getVaultClaimableBy(t,e,o){const i=`0x${h.assertOnChainBtcPubkey(e,`getVaultClaimableBy claimer (vault=${t})`)}`,s=t.toLowerCase(),{number:c}=await this.publicClient.getBlock({blockTag:"finalized"});if(c<o)throw new Error(`Finalized block ${c} is below vault ${t}'s registration block ${o}; the registration is not finalized yet, or the node is behind it`);let u=c;for(;;){const l=M(o,u-O+1n),p=await this.publicClient.getLogs({address:this.contractAddress,event:N,args:{vaultId:s,claimerPK:i},fromBlock:l,toBlock:u,strict:!0});if(p.length>1){const d=new Set(p.map(b=>b.transactionHash));if(d.size>1)throw new Error(`Found ${p.length} VaultClaimableBy logs for vault ${t} and claimer ${i} across ${d.size} transactions in blocks ${l}..${u}; a vault is redeemed once, so the node's answer is inconsistent`)}if(p.length>=1){const d=p[0];return{blockNumber:d.blockNumber,claimerPk:h.assertOnChainBtcPubkey(d.args.claimerPK,`VaultClaimableBy.claimerPK (vault=${t})`),peginTxHash:d.args.peginTxHash,vaultCoreVersion:d.args.vaultCoreVersion,proverCircuitVersion:d.args.proverCircuitVersion,offchainParamsVersion:d.args.offchainParamsVersion,universalChallengersVersion:d.args.universalChallengersVersion,appVaultKeepersVersion:d.args.appVaultKeepersVersion}}if(l===o)throw new h.VaultClaimableByNotFoundError(t,i,o,c);u=l-1n}}}const q=0,F=255,L=12e4;function m(r,t){const e=r.startsWith("0x")?r:r.startsWith("0X")?`0x${r.slice(2)}`:`0x${r}`;if(!/^0x(?:[0-9a-fA-F]{2})+$/.test(e))throw new Error(`${t} must be non-empty, even-length hex`);return e}function E(r,t){if(!/^0x[0-9a-fA-F]{64}$/.test(r))throw new Error(`${t} must be a 32-byte hex value`)}const z="0x0000000000000000000000000000000000000000000000000000000000000000";function I(r){if(E(r,"expectedFingerprint"),r.toLowerCase()===z)throw new Error("expectedFingerprint must not be zero: the registry cannot resolve a zero fingerprint, so this submission would always revert")}function U(r){if(!Number.isInteger(r)||r<0||r>F)throw new Error(`htlcVout must be a uint8, got ${r}`)}class W{constructor(t){this.config=t}async registerPeginOnChain(t){const e={...t,popSignature:{...t.popSignature}};this.assertQuotedCommissionPresentWhenRequired(e.quotedCommissionBps),I(e.expectedFingerprint);const o=this.assertPopMatchesEthAccount(e.popSignature),n=this.normalizeBtcPubkey(e.popSignature),i=m(e.popSignature.btcPopSignature,"btcPopSignature"),s=this.normalizeRequest(e,o,n);await this.assertVaultDoesNotExist(s.vaultId,s.peginTxHash);const c=await this.readPeginFee(e.vaultProvider),u=await this.resolveMaxAcceptableCommissionBps(e.vaultProvider,e.quotedCommissionBps),l=f.encodeFunctionData({abi:a.BTCVaultRegistryABI,functionName:"submitPeginRequest",args:[o,n,i,s.unsignedPrePeginTx,s.depositorSignedPeginTx,e.vaultProvider,u,e.hashlock,e.htlcVout,s.payoutScript,e.depositorWotsPkHash,e.expectedFingerprint]});return{ethTxHash:await this.sendAndWait(l,c,!1,o),vaultId:s.vaultId,peginTxHash:s.peginTxHash}}async registerPeginBatchOnChain(t){const e={...t,popSignature:{...t.popSignature},requests:t.requests.map(g=>({...g}))};if(e.requests.length===0)throw new Error("Batch pegin requires at least one request");this.assertQuotedCommissionPresentWhenRequired(e.quotedCommissionBps),I(e.expectedFingerprint);const o=this.assertPopMatchesEthAccount(e.popSignature),n=m(e.unsignedPrePeginTx,"unsignedPrePeginTx"),i=this.normalizeBtcPubkey(e.popSignature),s=m(e.popSignature.btcPopSignature,"btcPopSignature"),c=[],u=[],l=new Set;for(const g of e.requests){const P=this.normalizeRequest({...g,unsignedPrePeginTx:e.unsignedPrePeginTx,vaultProvider:e.vaultProvider,depositorBtcPubkeyRaw:e.depositorBtcPubkeyRaw},o,i);if(l.has(P.vaultId))throw new Error(`Duplicate vault in batch: ${P.vaultId}`);l.add(P.vaultId),c.push({vaultId:P.vaultId,peginTxHash:P.peginTxHash}),u.push({depositorBtcPubKey:i,btcPopSignature:s,unsignedPrePeginTx:n,depositorSignedPeginTx:P.depositorSignedPeginTx,hashlock:g.hashlock,htlcVout:g.htlcVout,referralCode:q,depositorPayoutBtcAddress:P.payoutScript,depositorWotsPkHash:g.depositorWotsPkHash})}for(const g of c)await this.assertVaultDoesNotExist(g.vaultId,g.peginTxHash);const p=await this.readPeginFee(e.vaultProvider),d=await this.resolveMaxAcceptableCommissionBps(e.vaultProvider,e.quotedCommissionBps),b=f.encodeFunctionData({abi:a.BTCVaultRegistryABI,functionName:"submitPeginRequestBatch",args:[o,e.vaultProvider,d,e.expectedFingerprint,u]});return{ethTxHash:await this.sendAndWait(b,p*BigInt(e.requests.length),!0,o),vaults:c}}assertQuotedCommissionPresentWhenRequired(t){if(t===void 0&&this.config.requireQuotedCommissionBps)throw new Error("quotedCommissionBps is required when the wallet approved deposit terms: the registration ceiling must anchor to the approved quote.")}assertPopMatchesEthAccount(t){return this.assertEthAccount(t.depositorEthAddress)}assertEthAccount(t){const e=this.config.ethWallet.account;if(!e)throw new Error("Ethereum wallet account not found");if(!f.isAddressEqual(t,e.address))throw new Error(`Proof of possession was signed for ${t} but the Ethereum wallet is currently connected to ${e.address}. Reconnect the original account or sign a new proof of possession.`);return e.address}normalizeBtcPubkey(t){return`0x${h.assertOnChainBtcPubkey(m(t.depositorBtcPubkey,"Proof of possession BTC pubkey"),"Proof of possession BTC pubkey")}`}normalizeRequest(t,e,o){E(t.hashlock,"hashlock"),E(t.depositorWotsPkHash,"depositorWotsPkHash"),U(t.htlcVout);const n=m(t.unsignedPrePeginTx,"unsignedPrePeginTx"),i=m(t.depositorSignedPeginTx,"depositorSignedPeginTx"),s=h.calculateBtcTxHash(i);return{unsignedPrePeginTx:n,depositorSignedPeginTx:i,payoutScript:h.assertPayoutScriptMatchesPopKey(t.depositorPayoutScriptPubKey,o,t.depositorBtcPubkeyRaw),peginTxHash:s,vaultId:m(h.derivePeginVaultId(s,e),"vaultId")}}async assertVaultDoesNotExist(t,e){if((await this.config.publicClient.readContract({address:this.config.btcVaultRegistry,abi:a.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[t]})).depositor!==f.zeroAddress)throw new Error(`Vault already exists (ID: ${t}, peginTxHash: ${e}). Vault IDs are derived from the pegin transaction hash and depositor address. To create a new vault, use different UTXOs or a different amount to generate a unique transaction.`)}async readPeginFee(t){try{return await this.config.publicClient.readContract({address:this.config.btcVaultRegistry,abi:a.BTCVaultRegistryABI,functionName:"getPegInFee",args:[t]})}catch(e){throw new Error("Failed to query pegin fee from the contract. Please check your network connection and contract address.",{cause:e})}}async resolveMaxAcceptableCommissionBps(t,e){let o;try{o=await new R(this.config.publicClient,this.config.btcVaultRegistry).getVaultProviderCommission(t)}catch(n){throw new Error("Failed to query vault provider commission from the contract. Please check your network connection and contract address.",{cause:n})}if(e!==void 0){if(o>e+B)throw new Error(`Vault provider commission changed since quote: quoted ${e} bps, chain currently reports ${o} bps (allowed drift ${B} bps). Please refresh and try again.`);return w(e)}return w(o)}async sendAndWait(t,e,o,n){let i=this.assertEthAccount(n),s;try{s=await this.config.publicClient.estimateGas({to:this.config.btcVaultRegistry,data:t,value:e,account:i})}catch(l){C.handleContractError(l)}i=this.assertEthAccount(n);let c;try{c=await this.config.ethWallet.sendTransaction({to:this.config.btcVaultRegistry,data:t,value:e,gas:s,account:i,chain:this.config.ethChain})}catch(l){C.handleContractError(l)}const u=await k.waitForTransactionReceiptSmartAware({publicClient:this.config.publicClient,walletAddress:n,hash:c,timeout:this.config.receiptTimeoutMs??L});return u.status==="reverted"&&C.handleContractError(new Error(`${o?"Batch transaction":"Transaction"} reverted. Hash: ${u.transactionHash}. Check a block explorer for details.`)),u.transactionHash}}exports.COMMISSION_BPS_HEADROOM=B;exports.MAX_ACCEPTABLE_COMMISSION_BPS_CAP=S;exports.ViemPeginRegistrationClient=W;exports.ViemVaultRegistryReader=R;exports.capMaxAcceptableCommissionBps=w;
|
|
2
|
-
//# sourceMappingURL=pegin-registration-client-CdRyXP3j.cjs.map
|