@babylonlabs-io/ts-sdk 0.79.1 → 1.1.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/README.md +11 -5
- package/dist/{signPsbtsWithFallback-f7QLp0q8.js → PayoutManager-CHTOwj0E.js} +26 -26
- package/dist/PayoutManager-CHTOwj0E.js.map +1 -0
- package/dist/PayoutManager-CpfQjtL0.cjs +2 -0
- package/dist/PayoutManager-CpfQjtL0.cjs.map +1 -0
- package/dist/PeginManager-6tjlGd0t.cjs +2 -0
- package/dist/PeginManager-6tjlGd0t.cjs.map +1 -0
- package/dist/{PeginManager-BXlh3ar0.js → PeginManager-DEldv_Ro.js} +23 -22
- package/dist/PeginManager-DEldv_Ro.js.map +1 -0
- package/dist/buildAndBroadcastReclaim-BwT6Jxp5.cjs +2 -0
- package/dist/buildAndBroadcastReclaim-BwT6Jxp5.cjs.map +1 -0
- package/dist/buildAndBroadcastReclaim-CqO2DoP8.js +1919 -0
- package/dist/buildAndBroadcastReclaim-CqO2DoP8.js.map +1 -0
- package/dist/challengeAssert-Cp_GeRg8.js.map +1 -1
- package/dist/challengeAssert-Z7_YULBb.cjs.map +1 -1
- package/dist/deriveVaultRoot-BwbXmN0x.js +79 -0
- package/dist/deriveVaultRoot-BwbXmN0x.js.map +1 -0
- package/dist/deriveVaultRoot-DvhkHzNb.cjs +2 -0
- package/dist/deriveVaultRoot-DvhkHzNb.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +286 -268
- package/dist/index.js.map +1 -1
- package/dist/noPayout-DAWBQ0eG.cjs +2 -0
- package/dist/noPayout-DAWBQ0eG.cjs.map +1 -0
- package/dist/{noPayout-DiGr4eas.js → noPayout-qBXWKwav.js} +3 -3
- package/dist/noPayout-qBXWKwav.js.map +1 -0
- package/dist/onChainBtcPubkey-BXry_CM4.cjs +2 -0
- package/dist/onChainBtcPubkey-BXry_CM4.cjs.map +1 -0
- package/dist/onChainBtcPubkey-C1WqyxPM.js +159 -0
- package/dist/onChainBtcPubkey-C1WqyxPM.js.map +1 -0
- package/dist/parseFundingOutpoints-C_-PT9BT.cjs +2 -0
- package/dist/parseFundingOutpoints-C_-PT9BT.cjs.map +1 -0
- package/dist/parseFundingOutpoints-GSM-IaaK.js +17 -0
- package/dist/parseFundingOutpoints-GSM-IaaK.js.map +1 -0
- package/dist/{pegin-registration-client-pcczkzMg.js → pegin-registration-client-1sZ-74UC.js} +260 -383
- package/dist/pegin-registration-client-1sZ-74UC.js.map +1 -0
- package/dist/pegin-registration-client-BNV44jzw.cjs +2 -0
- package/dist/pegin-registration-client-BNV44jzw.cjs.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 +6 -3
- package/dist/shared/wallets/interfaces/BitcoinWallet.d.ts.map +1 -1
- package/dist/signing-3l5Aqd-H.cjs +2 -0
- package/dist/signing-3l5Aqd-H.cjs.map +1 -0
- package/dist/signing-Dhr2t0Z6.js +39 -0
- package/dist/signing-Dhr2t0Z6.js.map +1 -0
- package/dist/tbv/core/clients/eth/index.cjs +1 -1
- package/dist/tbv/core/clients/eth/index.js +8 -8
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +8 -8
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.d.ts +1 -1
- package/dist/tbv/core/index.js +284 -266
- package/dist/tbv/core/index.js.map +1 -1
- package/dist/tbv/core/managers/PayoutManager.d.ts +1 -1
- package/dist/tbv/core/managers/PeginManager.d.ts +1 -1
- package/dist/tbv/core/managers/index.cjs +1 -1
- package/dist/tbv/core/managers/index.js +2 -2
- package/dist/tbv/core/primitives/index.cjs +1 -1
- package/dist/tbv/core/primitives/index.d.ts +1 -1
- package/dist/tbv/core/primitives/index.js +3 -3
- package/dist/tbv/core/primitives/psbt/__tests__/assertPeginTxShape.test.d.ts +5 -3
- package/dist/tbv/core/primitives/psbt/__tests__/assertPeginTxShape.test.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/__tests__/deriveExpectedPeginPayoutScriptPubKey.test.d.ts +8 -0
- package/dist/tbv/core/primitives/psbt/__tests__/deriveExpectedPeginPayoutScriptPubKey.test.d.ts.map +1 -0
- package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts +6 -0
- package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/challengeAssert.d.ts +2 -2
- package/dist/tbv/core/primitives/psbt/challengeAssert.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/noPayout.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/noPayout.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/payout.d.ts +13 -7
- package/dist/tbv/core/primitives/psbt/payout.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/pegin.d.ts +4 -1
- package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
- package/dist/tbv/core/recovery/recoveryErrors.d.ts +1 -1
- package/dist/tbv/core/services/delegated-claim/__tests__/assembleWatchtowerArtifacts.test.d.ts +15 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/assembleWatchtowerArtifacts.test.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/deriveClaimerWotsKeypair.test.d.ts +11 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/deriveClaimerWotsKeypair.test.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/readWatchtowerArtifacts.test.d.ts +10 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/readWatchtowerArtifacts.test.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/vaultIdBinding.test.d.ts +10 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/vaultIdBinding.test.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/wotsKeypair.golden.test.d.ts +11 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/wotsKeypair.golden.test.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/assembleWatchtowerArtifacts.d.ts +46 -0
- package/dist/tbv/core/services/delegated-claim/assembleWatchtowerArtifacts.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/challengerBinding.d.ts +72 -0
- package/dist/tbv/core/services/delegated-claim/challengerBinding.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/deriveClaimerWotsKeypair.d.ts +63 -0
- package/dist/tbv/core/services/delegated-claim/deriveClaimerWotsKeypair.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/index.d.ts +55 -0
- package/dist/tbv/core/services/delegated-claim/index.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/payoutBinding.d.ts +65 -0
- package/dist/tbv/core/services/delegated-claim/payoutBinding.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/readWatchtowerArtifacts.d.ts +70 -0
- package/dist/tbv/core/services/delegated-claim/readWatchtowerArtifacts.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/types.d.ts +105 -0
- package/dist/tbv/core/services/delegated-claim/types.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/vaultIdBinding.d.ts +44 -0
- package/dist/tbv/core/services/delegated-claim/vaultIdBinding.d.ts.map +1 -0
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.d.ts +1 -0
- package/dist/tbv/core/services/index.d.ts.map +1 -1
- package/dist/tbv/core/services/index.js +73 -56
- package/dist/tbv/core/services/index.js.map +1 -1
- package/dist/tbv/core/utils/index.cjs +1 -1
- package/dist/tbv/core/utils/index.js +44 -43
- package/dist/tbv/core/utils/signing.d.ts +24 -0
- package/dist/tbv/core/utils/signing.d.ts.map +1 -1
- package/dist/tbv/core/vault-secrets/__tests__/context.golden.test.d.ts +4 -4
- package/dist/tbv/core/vault-secrets/__tests__/context.test.d.ts +1 -2
- package/dist/tbv/core/vault-secrets/__tests__/context.test.d.ts.map +1 -1
- package/dist/tbv/core/vault-secrets/__tests__/deriveContextHash.vectors.test.d.ts +40 -0
- package/dist/tbv/core/vault-secrets/__tests__/deriveContextHash.vectors.test.d.ts.map +1 -0
- package/dist/tbv/core/vault-secrets/context.d.ts +2 -2
- package/dist/tbv/core/vault-secrets/deriveVaultRoot.d.ts +5 -6
- package/dist/tbv/core/vault-secrets/deriveVaultRoot.d.ts.map +1 -1
- package/dist/tbv/core/vault-secrets/index.cjs +1 -1
- package/dist/tbv/core/vault-secrets/index.d.ts +2 -2
- package/dist/tbv/core/vault-secrets/index.js +9 -8
- package/dist/tbv/core/vault-secrets/index.js.map +1 -1
- package/dist/tbv/core/wasm/index.cjs +1 -1
- package/dist/tbv/core/wasm/index.cjs.map +1 -1
- package/dist/tbv/core/wasm/index.d.ts +113 -14
- package/dist/tbv/core/wasm/index.d.ts.map +1 -1
- package/dist/tbv/core/wasm/index.js +180 -94
- package/dist/tbv/core/wasm/index.js.map +1 -1
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +284 -266
- package/dist/tbv/index.js.map +1 -1
- package/dist/tbv/integrations/aave/types.d.ts +1 -1
- package/dist/testing/MockBitcoinWallet.d.ts +1 -1
- package/dist/testing/index.cjs.map +1 -1
- package/dist/testing/index.js.map +1 -1
- package/dist/toRefundInputs-BaN9XluU.cjs +2 -0
- package/dist/toRefundInputs-BaN9XluU.cjs.map +1 -0
- package/dist/{toRefundInputs-9inv4Ai4.js → toRefundInputs-mtuuYezp.js} +24 -23
- package/dist/toRefundInputs-mtuuYezp.js.map +1 -0
- package/dist/{types-B9YhlXe8.js → types-BdCEoANP.js} +2 -2
- package/dist/{types-B9YhlXe8.js.map → types-BdCEoANP.js.map} +1 -1
- package/dist/{types-C1tpDycc.cjs → types-BuxreSq4.cjs} +2 -2
- package/dist/{types-C1tpDycc.cjs.map → types-BuxreSq4.cjs.map} +1 -1
- package/dist/{verifyKeyPathSchnorrSignature-BVtNwgK6.js → verifyKeyPathSchnorrSignature-BQHNhRj6.js} +2 -2
- package/dist/{verifyKeyPathSchnorrSignature-BVtNwgK6.js.map → verifyKeyPathSchnorrSignature-BQHNhRj6.js.map} +1 -1
- package/dist/{verifyKeyPathSchnorrSignature-BjB8Znly.cjs → verifyKeyPathSchnorrSignature-Gm9EmZkx.cjs} +2 -2
- package/dist/{verifyKeyPathSchnorrSignature-BjB8Znly.cjs.map → verifyKeyPathSchnorrSignature-Gm9EmZkx.cjs.map} +1 -1
- package/dist/verifyScriptPathSchnorrSignature-BKZihCjk.cjs +2 -0
- package/dist/verifyScriptPathSchnorrSignature-BKZihCjk.cjs.map +1 -0
- package/dist/{verifyScriptPathSchnorrSignature-D_epga4j.js → verifyScriptPathSchnorrSignature-CpjSTfMj.js} +371 -330
- package/dist/verifyScriptPathSchnorrSignature-CpjSTfMj.js.map +1 -0
- package/package.json +3 -3
- package/dist/PeginManager-BXlh3ar0.js.map +0 -1
- package/dist/PeginManager-BuVSknB0.cjs +0 -2
- package/dist/PeginManager-BuVSknB0.cjs.map +0 -1
- package/dist/buildAndBroadcastReclaim-N9dXH9dm.cjs +0 -2
- package/dist/buildAndBroadcastReclaim-N9dXH9dm.cjs.map +0 -1
- package/dist/buildAndBroadcastReclaim-O6z9kvc4.js +0 -1545
- package/dist/buildAndBroadcastReclaim-O6z9kvc4.js.map +0 -1
- package/dist/noPayout-4RZB2g1e.cjs +0 -2
- package/dist/noPayout-4RZB2g1e.cjs.map +0 -1
- package/dist/noPayout-DiGr4eas.js.map +0 -1
- package/dist/onChainBtcPubkey-BbxRrbvg.cjs +0 -2
- package/dist/onChainBtcPubkey-BbxRrbvg.cjs.map +0 -1
- package/dist/onChainBtcPubkey-C-6UWpD8.js +0 -34
- package/dist/onChainBtcPubkey-C-6UWpD8.js.map +0 -1
- package/dist/parseFundingOutpoints-B4iQeX6q.cjs +0 -2
- package/dist/parseFundingOutpoints-B4iQeX6q.cjs.map +0 -1
- package/dist/parseFundingOutpoints-BQWvINfm.js +0 -93
- package/dist/parseFundingOutpoints-BQWvINfm.js.map +0 -1
- package/dist/pegin-registration-client-CZgcU2_0.cjs +0 -2
- package/dist/pegin-registration-client-CZgcU2_0.cjs.map +0 -1
- package/dist/pegin-registration-client-pcczkzMg.js.map +0 -1
- package/dist/signPsbtsWithFallback-DtwzL5AA.cjs +0 -2
- package/dist/signPsbtsWithFallback-DtwzL5AA.cjs.map +0 -1
- package/dist/signPsbtsWithFallback-f7QLp0q8.js.map +0 -1
- package/dist/signing-BJ3X66b-.cjs +0 -2
- package/dist/signing-BJ3X66b-.cjs.map +0 -1
- package/dist/signing-Cm-McVR2.js +0 -22
- package/dist/signing-Cm-McVR2.js.map +0 -1
- package/dist/toRefundInputs-9inv4Ai4.js.map +0 -1
- package/dist/toRefundInputs-DitGWAnz.cjs +0 -2
- package/dist/toRefundInputs-DitGWAnz.cjs.map +0 -1
- package/dist/verifyScriptPathSchnorrSignature-D_epga4j.js.map +0 -1
- package/dist/verifyScriptPathSchnorrSignature-DaRqvEgW.cjs +0 -2
- package/dist/verifyScriptPathSchnorrSignature-DaRqvEgW.cjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"noPayout-4RZB2g1e.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"],"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 { loadRawTbvWasm, 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 loadRawTbvWasm();\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 + 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 processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a NoPayout PSBT\n */\nexport interface NoPayoutParams {\n /** NoPayout transaction hex (unsigned) from VP */\n noPayoutTxHex: string;\n /** Challenger's x-only public key (hex encoded) */\n challengerPubkey: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/**\n * Validate that a NoPayout transaction pays to the challenger via the\n * protocol-defined output structure: a single BIP-86 P2TR output derived from\n * the challenger's x-only pubkey.\n *\n * Mirrors 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"],"names":["U64_MAX","assertPositiveBigintArray","values","label","value","index","buildRefundPsbt","params","WasmPrePeginTx","loadRawTbvWasm","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","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","prevout","inputData","output","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","expectedScript","payments","getNetwork"],"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,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BAAwBJ,CAAgB,CAAC,EACjE,CAAE,OAAQK,GAAmBC,EAAAA,SAAS,KAAK,CAC/C,eAAgBxE,EAAAA,OAAO,KAAKqE,CAAK,EACjC,QAASI,EAAAA,WAAWN,CAAO,CAAA,CAC5B,EACD,GAAI,CAACI,EACH,MAAM,IAAI,MACR,qFAAA,EAIJ,GAAI,CAACH,EAAG,KAAK,CAAC,EAAE,OAAO,OAAOG,CAAc,EAC1C,MAAM,IAAI,MACR,kFAAA,CAGN"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"noPayout-DiGr4eas.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"],"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 { loadRawTbvWasm, 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 loadRawTbvWasm();\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 + 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 processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a NoPayout PSBT\n */\nexport interface NoPayoutParams {\n /** NoPayout transaction hex (unsigned) from VP */\n noPayoutTxHex: string;\n /** Challenger's x-only public key (hex encoded) */\n challengerPubkey: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/**\n * Validate that a NoPayout transaction pays to the challenger via the\n * protocol-defined output structure: a single BIP-86 P2TR output derived from\n * the challenger's x-only pubkey.\n *\n * Mirrors 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"],"names":["U64_MAX","assertPositiveBigintArray","values","label","value","index","buildRefundPsbt","params","WasmPrePeginTx","loadRawTbvWasm","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","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","prevout","inputData","output","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","expectedScript","payments","getNetwork"],"mappings":";;;;;;;;AAoBA,MAAMA,KAAW,MAAM,OAAO;AAYvB,SAASC,GACdC,GACAC,GACU;AACV,MAAI,CAAC,MAAM,QAAQD,CAAM;AACvB,UAAM,IAAI;AAAA,MACR,GAAGC,CAAK,8CAA8C,OAAOD,CAAM;AAAA,IAAA;AAGvE,MAAIA,EAAO,WAAW;AACpB,UAAM,IAAI,MAAM,GAAGC,CAAK,qBAAqB;AAE/C,SAAAD,EAAO,QAAQ,CAACE,GAAOC,MAAU;AAC/B,QAAI,OAAOD,KAAU;AACnB,YAAM,IAAI;AAAA,QACR,GAAGD,CAAK,IAAIE,CAAK,2BAA2B,OAAOD,CAAK;AAAA,MAAA;AAI5D,QAAIA,KAAS;AACX,YAAM,IAAI,MAAM,GAAGD,CAAK,IAAIE,CAAK,sBAAsBD,CAAK,IAAI;AAElE,QAAIA,IAAQJ;AACV,YAAM,IAAI;AAAA,QACR,GAA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AOnE,EAAK,MAAA;AACd;AAmBO,SAASoE,GACdV,GACAW,GACAC,GACM;AACN,QAAMC,IAAKlF,EAAY,QAAQkB,EAAemD,CAAa,CAAC;AAE5D,MAAIa,EAAG,KAAK,WAAW;AACrB,UAAM,IAAI;AAAA,MACR,wDAAwDA,EAAG,KAAK,MAAM;AAAA,IAAA;AAI1E,QAAMC,IAAQ7B,EAAgB8B,EAAwBJ,CAAgB,CAAC,GACjE,EAAE,QAAQK,MAAmBC,EAAS,KAAK;AAAA,IAC/C,gBAAgBxE,EAAO,KAAKqE,CAAK;AAAA,IACjC,SAASI,EAAWN,CAAO;AAAA,EAAA,CAC5B;AACD,MAAI,CAACI;AACH,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAIJ,MAAI,CAACH,EAAG,KAAK,CAAC,EAAE,OAAO,OAAOG,CAAc;AAC1C,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAGN;"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const r=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,s=7n;function i(c,f,e){let n=1n,t=c%e,o=f;for(;o>0n;)(o&1n)===1n&&(n=n*t%e),t=t*t%e,o>>=1n;return n}function u(c){const f=BigInt(`0x${c}`);if(f>=r)return!1;const n=(f*f%r*f%r+s)%r,t=i(n,r+1n>>2n,r);return t*t%r===n}function a(c,f){const e=c.toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(e))throw new Error(`${f} returned an unexpected value (length ${e.length}, prefix "${e.slice(0,2)}")`);const n=e.slice(2);if(!u(n))throw new Error(`${f} returned a value that is not on the secp256k1 curve`);return n}exports.assertOnChainBtcPubkey=a;
|
|
2
|
-
//# sourceMappingURL=onChainBtcPubkey-BbxRrbvg.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"onChainBtcPubkey-BbxRrbvg.cjs","sources":["../src/tbv/core/clients/eth/onChainBtcPubkey.ts"],"sourcesContent":["/**\n * The single validator that mints {@link OnChainBtcPubkey}.\n *\n * Extracted from `ViemVaultRegistryReader.getVaultProviderGenesisBtcPubKey` so that\n * RFC-006 operation-key resolution can produce branded keys through exactly\n * the same checks, rather than casting past the brand. Every producer of an\n * `OnChainBtcPubkey` must go through here.\n */\n\nimport type { Hex } from \"viem\";\n\nimport type { OnChainBtcPubkey } from \"./types\";\n\n/** secp256k1's base-field prime, `2^256 - 2^32 - 977`. */\nconst SECP256K1_FIELD_PRIME =\n 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn;\n\n/** secp256k1's curve coefficient `b`, from `y^2 = x^3 + b`. */\nconst SECP256K1_CURVE_B = 7n;\n\n/** Modular exponentiation without a crypto-library dependency. */\nfunction modPow(base: bigint, exponent: bigint, modulus: bigint): bigint {\n let result = 1n;\n let factor = base % modulus;\n let remaining = exponent;\n\n while (remaining > 0n) {\n if ((remaining & 1n) === 1n) {\n result = (result * factor) % modulus;\n }\n factor = (factor * factor) % modulus;\n remaining >>= 1n;\n }\n\n return result;\n}\n\n/**\n * secp256k1's field prime is congruent to 3 mod 4, so an x-coordinate is on\n * the curve iff `(x^3 + 7)^((p + 1) / 4)` squares back to `x^3 + 7` modulo\n * p. This is the same curve-membership condition used by x-only key parsers;\n * it deliberately does not merely validate length/range.\n * `x^3 + 7` cannot be zero because `-7` is not a cubic residue in this field,\n * so the zero square-root edge case is unreachable.\n */\nfunction isSecp256k1XCoordinate(value: string): boolean {\n const x = BigInt(`0x${value}`);\n if (x >= SECP256K1_FIELD_PRIME) return false;\n\n const xCubed =\n (((x * x) % SECP256K1_FIELD_PRIME) * x) % SECP256K1_FIELD_PRIME;\n const curveValue = (xCubed + SECP256K1_CURVE_B) % SECP256K1_FIELD_PRIME;\n const y = modPow(\n curveValue,\n (SECP256K1_FIELD_PRIME + 1n) >> 2n,\n SECP256K1_FIELD_PRIME,\n );\n\n return (y * y) % SECP256K1_FIELD_PRIME === curveValue;\n}\n\n/**\n * Validate a registry-returned `bytes32` as an x-only BTC pubkey and mint the\n * brand. Checks length, hex form, and secp256k1 curve membership. Returns\n * 64-char lowercase hex without the `0x` prefix.\n *\n * `label` identifies the read site in error messages (e.g.\n * `getOperationBtcKeyAtEpoch (vp=0x…, epoch=0)`), so a failure names which\n * participant and which getter produced it.\n *\n * A zero hash fails the curve check, so an unregistered operator or an epoch\n * with no bonded key surfaces as an error rather than a silent all-zero key.\n */\nexport function assertOnChainBtcPubkey(\n value: Hex,\n label: string,\n): OnChainBtcPubkey {\n const lowered = value.toLowerCase();\n if (!/^0x[0-9a-f]{64}$/.test(lowered)) {\n throw new Error(\n `${label} returned an unexpected value (length ${lowered.length}, prefix \"${lowered.slice(0, 2)}\")`,\n );\n }\n const stripped = lowered.slice(2);\n if (!isSecp256k1XCoordinate(stripped)) {\n throw new Error(\n `${label} returned a value that is not on the secp256k1 curve`,\n );\n }\n return stripped as OnChainBtcPubkey;\n}\n"],"names":["SECP256K1_FIELD_PRIME","SECP256K1_CURVE_B","modPow","base","exponent","modulus","result","factor","remaining","isSecp256k1XCoordinate","value","x","curveValue","y","assertOnChainBtcPubkey","label","lowered","stripped"],"mappings":"aAcA,MAAMA,EACJ,oEAGIC,EAAoB,GAG1B,SAASC,EAAOC,EAAcC,EAAkBC,EAAyB,CACvE,IAAIC,EAAS,GACTC,EAASJ,EAAOE,EAChBG,EAAYJ,EAEhB,KAAOI,EAAY,KACZA,EAAY,MAAQ,KACvBF,EAAUA,EAASC,EAAUF,GAE/BE,EAAUA,EAASA,EAAUF,EAC7BG,IAAc,GAGhB,OAAOF,CACT,CAUA,SAASG,EAAuBC,EAAwB,CACtD,MAAMC,EAAI,OAAO,KAAKD,CAAK,EAAE,EAC7B,GAAIC,GAAKX,EAAuB,MAAO,GAIvC,MAAMY,GADDD,EAAIA,EAAKX,EAAyBW,EAAKX,EACfC,GAAqBD,EAC5Ca,EAAIX,EACRU,EACCZ,EAAwB,IAAO,GAChCA,CAAA,EAGF,OAAQa,EAAIA,EAAKb,IAA0BY,CAC7C,CAcO,SAASE,EACdJ,EACAK,EACkB,CAClB,MAAMC,EAAUN,EAAM,YAAA,EACtB,GAAI,CAAC,mBAAmB,KAAKM,CAAO,EAClC,MAAM,IAAI,MACR,GAAGD,CAAK,yCAAyCC,EAAQ,MAAM,aAAaA,EAAQ,MAAM,EAAG,CAAC,CAAC,IAAA,EAGnG,MAAMC,EAAWD,EAAQ,MAAM,CAAC,EAChC,GAAI,CAACP,EAAuBQ,CAAQ,EAClC,MAAM,IAAI,MACR,GAAGF,CAAK,sDAAA,EAGZ,OAAOE,CACT"}
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
const r = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn, i = 7n;
|
|
2
|
-
function s(o, f, e) {
|
|
3
|
-
let n = 1n, t = o % e, c = f;
|
|
4
|
-
for (; c > 0n; )
|
|
5
|
-
(c & 1n) === 1n && (n = n * t % e), t = t * t % e, c >>= 1n;
|
|
6
|
-
return n;
|
|
7
|
-
}
|
|
8
|
-
function a(o) {
|
|
9
|
-
const f = BigInt(`0x${o}`);
|
|
10
|
-
if (f >= r) return !1;
|
|
11
|
-
const n = (f * f % r * f % r + i) % r, t = s(
|
|
12
|
-
n,
|
|
13
|
-
r + 1n >> 2n,
|
|
14
|
-
r
|
|
15
|
-
);
|
|
16
|
-
return t * t % r === n;
|
|
17
|
-
}
|
|
18
|
-
function u(o, f) {
|
|
19
|
-
const e = o.toLowerCase();
|
|
20
|
-
if (!/^0x[0-9a-f]{64}$/.test(e))
|
|
21
|
-
throw new Error(
|
|
22
|
-
`${f} returned an unexpected value (length ${e.length}, prefix "${e.slice(0, 2)}")`
|
|
23
|
-
);
|
|
24
|
-
const n = e.slice(2);
|
|
25
|
-
if (!a(n))
|
|
26
|
-
throw new Error(
|
|
27
|
-
`${f} returned a value that is not on the secp256k1 curve`
|
|
28
|
-
);
|
|
29
|
-
return n;
|
|
30
|
-
}
|
|
31
|
-
export {
|
|
32
|
-
u as a
|
|
33
|
-
};
|
|
34
|
-
//# sourceMappingURL=onChainBtcPubkey-C-6UWpD8.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"onChainBtcPubkey-C-6UWpD8.js","sources":["../src/tbv/core/clients/eth/onChainBtcPubkey.ts"],"sourcesContent":["/**\n * The single validator that mints {@link OnChainBtcPubkey}.\n *\n * Extracted from `ViemVaultRegistryReader.getVaultProviderGenesisBtcPubKey` so that\n * RFC-006 operation-key resolution can produce branded keys through exactly\n * the same checks, rather than casting past the brand. Every producer of an\n * `OnChainBtcPubkey` must go through here.\n */\n\nimport type { Hex } from \"viem\";\n\nimport type { OnChainBtcPubkey } from \"./types\";\n\n/** secp256k1's base-field prime, `2^256 - 2^32 - 977`. */\nconst SECP256K1_FIELD_PRIME =\n 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn;\n\n/** secp256k1's curve coefficient `b`, from `y^2 = x^3 + b`. */\nconst SECP256K1_CURVE_B = 7n;\n\n/** Modular exponentiation without a crypto-library dependency. */\nfunction modPow(base: bigint, exponent: bigint, modulus: bigint): bigint {\n let result = 1n;\n let factor = base % modulus;\n let remaining = exponent;\n\n while (remaining > 0n) {\n if ((remaining & 1n) === 1n) {\n result = (result * factor) % modulus;\n }\n factor = (factor * factor) % modulus;\n remaining >>= 1n;\n }\n\n return result;\n}\n\n/**\n * secp256k1's field prime is congruent to 3 mod 4, so an x-coordinate is on\n * the curve iff `(x^3 + 7)^((p + 1) / 4)` squares back to `x^3 + 7` modulo\n * p. This is the same curve-membership condition used by x-only key parsers;\n * it deliberately does not merely validate length/range.\n * `x^3 + 7` cannot be zero because `-7` is not a cubic residue in this field,\n * so the zero square-root edge case is unreachable.\n */\nfunction isSecp256k1XCoordinate(value: string): boolean {\n const x = BigInt(`0x${value}`);\n if (x >= SECP256K1_FIELD_PRIME) return false;\n\n const xCubed =\n (((x * x) % SECP256K1_FIELD_PRIME) * x) % SECP256K1_FIELD_PRIME;\n const curveValue = (xCubed + SECP256K1_CURVE_B) % SECP256K1_FIELD_PRIME;\n const y = modPow(\n curveValue,\n (SECP256K1_FIELD_PRIME + 1n) >> 2n,\n SECP256K1_FIELD_PRIME,\n );\n\n return (y * y) % SECP256K1_FIELD_PRIME === curveValue;\n}\n\n/**\n * Validate a registry-returned `bytes32` as an x-only BTC pubkey and mint the\n * brand. Checks length, hex form, and secp256k1 curve membership. Returns\n * 64-char lowercase hex without the `0x` prefix.\n *\n * `label` identifies the read site in error messages (e.g.\n * `getOperationBtcKeyAtEpoch (vp=0x…, epoch=0)`), so a failure names which\n * participant and which getter produced it.\n *\n * A zero hash fails the curve check, so an unregistered operator or an epoch\n * with no bonded key surfaces as an error rather than a silent all-zero key.\n */\nexport function assertOnChainBtcPubkey(\n value: Hex,\n label: string,\n): OnChainBtcPubkey {\n const lowered = value.toLowerCase();\n if (!/^0x[0-9a-f]{64}$/.test(lowered)) {\n throw new Error(\n `${label} returned an unexpected value (length ${lowered.length}, prefix \"${lowered.slice(0, 2)}\")`,\n );\n }\n const stripped = lowered.slice(2);\n if (!isSecp256k1XCoordinate(stripped)) {\n throw new Error(\n `${label} returned a value that is not on the secp256k1 curve`,\n );\n }\n return stripped as OnChainBtcPubkey;\n}\n"],"names":["SECP256K1_FIELD_PRIME","SECP256K1_CURVE_B","modPow","base","exponent","modulus","result","factor","remaining","isSecp256k1XCoordinate","value","x","curveValue","y","assertOnChainBtcPubkey","label","lowered","stripped"],"mappings":"AAcA,MAAMA,IACJ,qEAGIC,IAAoB;AAG1B,SAASC,EAAOC,GAAcC,GAAkBC,GAAyB;AACvE,MAAIC,IAAS,IACTC,IAASJ,IAAOE,GAChBG,IAAYJ;AAEhB,SAAOI,IAAY;AACjB,KAAKA,IAAY,QAAQ,OACvBF,IAAUA,IAASC,IAAUF,IAE/BE,IAAUA,IAASA,IAAUF,GAC7BG,MAAc;AAGhB,SAAOF;AACT;AAUA,SAASG,EAAuBC,GAAwB;AACtD,QAAMC,IAAI,OAAO,KAAKD,CAAK,EAAE;AAC7B,MAAIC,KAAKX,EAAuB,QAAO;AAIvC,QAAMY,KADDD,IAAIA,IAAKX,IAAyBW,IAAKX,IACfC,KAAqBD,GAC5Ca,IAAIX;AAAA,IACRU;AAAA,IACCZ,IAAwB,MAAO;AAAA,IAChCA;AAAA,EAAA;AAGF,SAAQa,IAAIA,IAAKb,MAA0BY;AAC7C;AAcO,SAASE,EACdJ,GACAK,GACkB;AAClB,QAAMC,IAAUN,EAAM,YAAA;AACtB,MAAI,CAAC,mBAAmB,KAAKM,CAAO;AAClC,UAAM,IAAI;AAAA,MACR,GAAGD,CAAK,yCAAyCC,EAAQ,MAAM,aAAaA,EAAQ,MAAM,GAAG,CAAC,CAAC;AAAA,IAAA;AAGnG,QAAMC,IAAWD,EAAQ,MAAM,CAAC;AAChC,MAAI,CAACP,EAAuBQ,CAAQ;AAClC,UAAM,IAAI;AAAA,MACR,GAAGF,CAAK;AAAA,IAAA;AAGZ,SAAOE;AACT;"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const l=require("./bitcoin-D-O2GjbC.cjs"),x=require("./sha2-DI0-0SHr.cjs"),y=require("bitcoinjs-lib"),b=require("buffer"),i=32,u=32,c=36,m=32,s=4,v=s+i+s+m;function a(t,n,r){t[n]=r>>>24&255,t[n+1]=r>>>16&255,t[n+2]=r>>>8&255,t[n+3]=r&255}function O(t){if(t.txid.length!==u)throw new Error(`outpoint.txid must be exactly ${u} bytes, got ${t.txid.length}`);if(!Number.isInteger(t.vout)||t.vout<0||t.vout>4294967295)throw new Error(`outpoint.vout must be a u32, got ${t.vout}`);const n=new Uint8Array(c);return n.set(t.txid,0),a(n,u,t.vout),n}function h(t,n){const r=Math.min(t.length,n.length);for(let e=0;e<r;e++)if(t[e]!==n[e])return t[e]-n[e];return t.length-n.length}function f(t){if(t.length===0)throw new Error("buildFundingOutpointsCommitment: outpoints must be non-empty");const n=t.map(O);n.sort(h);for(let e=1;e<n.length;e++)if(h(n[e-1],n[e])===0)throw new Error("buildFundingOutpointsCommitment: duplicate outpoint detected");const r=new Uint8Array(n.length*c);for(let e=0;e<n.length;e++)r.set(n[e],e*c);return x.sha256(r)}function E(t){if(t.depositorBtcPubkey.length!==i)throw new Error(`vaultContext: depositorBtcPubkey must be exactly ${i} bytes, got ${t.depositorBtcPubkey.length}`);const n=f(t.fundingOutpoints),r=new Uint8Array(v);let e=0;return a(r,e,i),e+=s,r.set(t.depositorBtcPubkey,e),e+=i,a(r,e,m),e+=s,r.set(n,e),r}const g="babylon-btc-vault",w=32,d=w*2,_=/^[0-9a-f]+$/;function T(t){const n=t.deriveContextHash;return typeof n=="function"?{deriveContextHash:(r,e)=>n.call(t,r,e)}:{}}async function p(t,n){const r=E(n),e=l.uint8ArrayToHex(r),o=await t.deriveContextHash(g,e);if(typeof o!="string")throw new Error(`deriveVaultRoot: wallet must return a string, got ${typeof o}`);if(o.length!==d)throw new Error(`deriveVaultRoot: wallet must return a ${d}-character hex string (${w} bytes), got length ${o.length}`);if(!_.test(o))throw new Error("deriveVaultRoot: wallet must return lowercase hex per derive-context-hash.md §2.1; got value with non-lowercase or non-hex characters");return l.hexToUint8Array(o)}function C(t){if(!t)throw new Error("Pre-pegin transaction hex is empty");const n=t.startsWith("0x")?t.slice(2):t,r=y.Transaction.fromHex(n);if(r.ins.length===0)throw new Error("Pre-pegin transaction has no inputs");return r.ins.map(e=>({txid:Uint8Array.from(b.Buffer.from(e.hash).reverse()),vout:e.index}))}exports.VAULT_APP_NAME=g;exports.buildFundingOutpointsCommitment=f;exports.buildVaultContext=E;exports.deriveVaultRoot=p;exports.forwardDeriveContextHash=T;exports.parseFundingOutpointsFromTx=C;
|
|
2
|
-
//# sourceMappingURL=parseFundingOutpoints-B4iQeX6q.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"parseFundingOutpoints-B4iQeX6q.cjs","sources":["../src/tbv/core/vault-secrets/context.ts","../src/tbv/core/vault-secrets/deriveVaultRoot.ts","../src/tbv/core/vault-secrets/parseFundingOutpoints.ts"],"sourcesContent":["/**\n * Canonical `vaultContext` byte encoding per\n * `derive-vault-secrets.md` §2.3.\n *\n * ```\n * vaultContext :=\n * I2OSP(32, 4) || depositorBtcPubkey // 32B x-only\n * || I2OSP(32, 4) || fundingOutpointsCommitment // 32B SHA-256\n * ```\n *\n * `fundingOutpointsCommitment` is SHA-256 over the canonically-sorted\n * funding outpoints of the Pre-PegIn transaction, serialized as\n * `txid (32B display/RPC order) || vout (4B u32 big-endian)` per\n * outpoint. Sorting by 36-byte lex order makes the commitment\n * invariant under tx-level input reordering, so same-inputs RBF and\n * reorg rebroadcasts yield the same context.\n *\n * @module vault-secrets/context\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\n\nconst DEPOSITOR_PUBKEY_SIZE = 32;\nconst TXID_SIZE = 32;\nconst OUTPOINT_SIZE = 36;\nconst COMMITMENT_SIZE = 32;\nconst FIELD_LEN_PREFIX_SIZE = 4;\nconst VAULT_CONTEXT_SIZE =\n FIELD_LEN_PREFIX_SIZE +\n DEPOSITOR_PUBKEY_SIZE +\n FIELD_LEN_PREFIX_SIZE +\n COMMITMENT_SIZE;\n\nexport interface FundingOutpoint {\n /**\n * Bitcoin txid in **display / RPC order** (byte-reversed from the\n * internal little-endian wire form used when hashing a raw tx).\n */\n txid: Uint8Array;\n /** Output index within the referenced transaction (u32). */\n vout: number;\n}\n\nexport interface VaultContextInput {\n /** Depositor's x-only BTC public key (32 bytes). */\n depositorBtcPubkey: Uint8Array;\n /** Funding outpoints of the Pre-PegIn transaction. MUST be non-empty. */\n fundingOutpoints: readonly FundingOutpoint[];\n}\n\nfunction writeUint32BE(out: Uint8Array, offset: number, value: number): void {\n out[offset] = (value >>> 24) & 0xff;\n out[offset + 1] = (value >>> 16) & 0xff;\n out[offset + 2] = (value >>> 8) & 0xff;\n out[offset + 3] = value & 0xff;\n}\n\nfunction serializeOutpoint(outpoint: FundingOutpoint): Uint8Array {\n if (outpoint.txid.length !== TXID_SIZE) {\n throw new Error(\n `outpoint.txid must be exactly ${TXID_SIZE} bytes, got ${outpoint.txid.length}`,\n );\n }\n if (\n !Number.isInteger(outpoint.vout) ||\n outpoint.vout < 0 ||\n outpoint.vout > 0xffffffff\n ) {\n throw new Error(`outpoint.vout must be a u32, got ${outpoint.vout}`);\n }\n const out = new Uint8Array(OUTPOINT_SIZE);\n out.set(outpoint.txid, 0);\n writeUint32BE(out, TXID_SIZE, outpoint.vout);\n return out;\n}\n\nfunction compareBytes(a: Uint8Array, b: Uint8Array): number {\n const len = Math.min(a.length, b.length);\n for (let i = 0; i < len; i++) {\n if (a[i] !== b[i]) return a[i] - b[i];\n }\n return a.length - b.length;\n}\n\n/**\n * Compute SHA-256 over canonically-sorted funding outpoints.\n *\n * Outpoints are serialized as 36-byte `txid || vout_BE`, sorted\n * ascending lexicographically, concatenated, then hashed.\n *\n * @stability frozen — on-chain-binding. Any change to layout, sort\n * order, or serialization is a hard fork; existing deposits would no\n * longer match their committed `depositorWotsPkHash`.\n *\n * @throws If `outpoints` is empty or contains duplicates.\n */\nexport function buildFundingOutpointsCommitment(\n outpoints: readonly FundingOutpoint[],\n): Uint8Array {\n if (outpoints.length === 0) {\n throw new Error(\n \"buildFundingOutpointsCommitment: outpoints must be non-empty\",\n );\n }\n const serialized = outpoints.map(serializeOutpoint);\n serialized.sort(compareBytes);\n\n for (let i = 1; i < serialized.length; i++) {\n if (compareBytes(serialized[i - 1], serialized[i]) === 0) {\n throw new Error(\n \"buildFundingOutpointsCommitment: duplicate outpoint detected\",\n );\n }\n }\n\n const flat = new Uint8Array(serialized.length * OUTPOINT_SIZE);\n for (let i = 0; i < serialized.length; i++) {\n flat.set(serialized[i], i * OUTPOINT_SIZE);\n }\n return sha256(flat);\n}\n\n/**\n * Build the canonical `vaultContext` byte string fed into the wallet's\n * `deriveContextHash` (or a locally-implemented equivalent on the\n * app side).\n *\n * Output length is always 72 bytes.\n *\n * @stability frozen — on-chain-binding. The 72-byte layout is the\n * input to `deriveContextHash`; any change rotates the vault root and\n * therefore every WOTS key, hashlock secret, and auth anchor derived\n * from it. Existing deposits cannot be recovered after a layout change.\n */\nexport function buildVaultContext(input: VaultContextInput): Uint8Array {\n if (input.depositorBtcPubkey.length !== DEPOSITOR_PUBKEY_SIZE) {\n throw new Error(\n `vaultContext: depositorBtcPubkey must be exactly ${DEPOSITOR_PUBKEY_SIZE} bytes, got ${input.depositorBtcPubkey.length}`,\n );\n }\n const commitment = buildFundingOutpointsCommitment(input.fundingOutpoints);\n\n const out = new Uint8Array(VAULT_CONTEXT_SIZE);\n let offset = 0;\n\n writeUint32BE(out, offset, DEPOSITOR_PUBKEY_SIZE);\n offset += FIELD_LEN_PREFIX_SIZE;\n out.set(input.depositorBtcPubkey, offset);\n offset += DEPOSITOR_PUBKEY_SIZE;\n\n writeUint32BE(out, offset, COMMITMENT_SIZE);\n offset += FIELD_LEN_PREFIX_SIZE;\n out.set(commitment, offset);\n\n return out;\n}\n","/**\n * Vault-root derivation via the wallet's `deriveContextHash` API.\n *\n * Implements the canonical root source from `derive-vault-secrets.md`\n * §2.2:\n *\n * ```\n * rootDerivation = deriveContextHash(\"babylon-btc-vault\", hex(vaultContext))\n * ```\n *\n * The 32-byte output is fed directly into the {@link expandAuthAnchor},\n * {@link expandHashlockSecret}, and {@link expandWotsSeed} functions in\n * this module.\n *\n * @module vault-secrets/deriveVaultRoot\n */\n\nimport { hexToUint8Array, uint8ArrayToHex } from \"../primitives/utils/bitcoin\";\n\nimport { buildVaultContext, type VaultContextInput } from \"./context\";\n\n/**\n * The fixed `appName` passed to the wallet's `deriveContextHash` for\n * Babylon vault derivations. The wallet displays this in its approval\n * dialog. Defined by `derive-vault-secrets.md` §2.2 — must not be\n * changed without coordinating a spec revision and a downstream\n * migration plan, as it provides app-level domain separation across\n * applications using the same wallet.\n */\nexport const VAULT_APP_NAME = \"babylon-btc-vault\";\n\n/** Expected length of the wallet output in bytes per spec §2.1. */\nconst ROOT_OUTPUT_BYTES = 32;\n\n/** Expected length of the wallet output in lowercase hex chars. */\nconst ROOT_OUTPUT_HEX_LEN = ROOT_OUTPUT_BYTES * 2;\n\nconst LOWERCASE_HEX_RE = /^[0-9a-f]+$/;\n\n/**\n * Minimal structural shape for the wallet capability needed by this\n * helper. Typed against the method directly so callers can pass any\n * value that implements `deriveContextHash` — `BitcoinWallet` from\n * this SDK, `IBTCProvider` from `@babylonlabs-io/wallet-connector`,\n * or a test mock — without depending on the rest of either interface.\n */\nexport interface DeriveContextHashCapableWallet {\n deriveContextHash(appName: string, context: string): Promise<string>;\n}\n\n/** Forward the deriveContextHash capability only when the wallet actually has it,\n * so seam guards (ensurePrePeginTermsApproval) can fire their typed error instead\n * of a mid-ceremony TypeError. */\nexport function forwardDeriveContextHash(\n wallet: Partial<DeriveContextHashCapableWallet>,\n): Partial<DeriveContextHashCapableWallet> {\n // Captured before the closure so the narrowing survives it. The property\n // read cannot be narrowed across a closure boundary, which is what forced\n // the non-null assertion this replaces; forwarding is otherwise unchanged.\n const deriveContextHash = wallet.deriveContextHash;\n return typeof deriveContextHash === \"function\"\n ? {\n deriveContextHash: (appName, context) =>\n deriveContextHash.call(wallet, appName, context),\n }\n : {};\n}\n\n/**\n * Derive the 32-byte vault root from a wallet by encoding the\n * canonical {@link VaultContextInput} and forwarding to\n * `wallet.deriveContextHash`.\n *\n * Validates the wallet's output strictly: must be exactly 64\n * lowercase hex characters per `derive-context-hash.md` §2.1. A\n * conformant wallet always satisfies this, but we re-check at the\n * SDK boundary so a non-conformant wallet (or a wallet returning a\n * malformed value through a buggy adapter) fails loud here rather\n * than producing silently-wrong derived secrets downstream.\n *\n * The helper itself produces only valid spec inputs (`appName` is\n * the hardcoded `VAULT_APP_NAME`; `context` is hex of the 72-byte\n * `vaultContext`, always 144 chars lowercase), so input-side\n * validation is unnecessary.\n *\n * @param wallet - Any value implementing `deriveContextHash`.\n * @param input - The canonical {@link VaultContextInput} that\n * uniquely identifies the vault. Encoded by\n * {@link buildVaultContext} into a 72-byte structure\n * before being hex-encoded for the wallet.\n * @stability frozen — on-chain-binding. The pair (`VAULT_APP_NAME`,\n * `vaultContext` encoding) is the wallet's input space; changing\n * either rotates the root and invalidates every secret derived from\n * it. `VAULT_APP_NAME` is fixed by `derive-vault-secrets.md` §2.2\n * and must never change without a coordinated spec revision.\n *\n * @returns 32-byte root suitable for {@link expandAuthAnchor},\n * {@link expandHashlockSecret}, {@link expandWotsSeed}.\n * @throws If the wallet returns a non-64-char or non-lowercase-hex\n * string. Errors from the wallet (user rejection,\n * method-not-supported, etc.) propagate unchanged.\n */\nexport async function deriveVaultRoot(\n wallet: DeriveContextHashCapableWallet,\n input: VaultContextInput,\n): Promise<Uint8Array> {\n const vaultContext = buildVaultContext(input);\n const contextHex = uint8ArrayToHex(vaultContext);\n\n const rootHex = await wallet.deriveContextHash(VAULT_APP_NAME, contextHex);\n\n if (typeof rootHex !== \"string\") {\n throw new Error(\n `deriveVaultRoot: wallet must return a string, got ${typeof rootHex}`,\n );\n }\n if (rootHex.length !== ROOT_OUTPUT_HEX_LEN) {\n throw new Error(\n `deriveVaultRoot: wallet must return a ${ROOT_OUTPUT_HEX_LEN}-character hex string (${ROOT_OUTPUT_BYTES} bytes), got length ${rootHex.length}`,\n );\n }\n if (!LOWERCASE_HEX_RE.test(rootHex)) {\n throw new Error(\n \"deriveVaultRoot: wallet must return lowercase hex per derive-context-hash.md §2.1; got value with non-lowercase or non-hex characters\",\n );\n }\n\n return hexToUint8Array(rootHex);\n}\n","/**\n * Parse a Pre-PegIn transaction's inputs into the vault-context\n * `fundingOutpoints` shape consumed by `deriveVaultRoot`. Reverses\n * the prev-txid bytes from wire-internal little-endian to display\n * order so the derivation is byte-for-byte identical to the\n * deposit-time computation.\n *\n * @module vault-secrets/parseFundingOutpoints\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport type { FundingOutpoint } from \"./context\";\n\nexport function parseFundingOutpointsFromTx(\n unsignedTxHex: string,\n): FundingOutpoint[] {\n if (!unsignedTxHex) {\n throw new Error(\"Pre-pegin transaction hex is empty\");\n }\n const cleanHex = unsignedTxHex.startsWith(\"0x\")\n ? unsignedTxHex.slice(2)\n : unsignedTxHex;\n const tx = Transaction.fromHex(cleanHex);\n if (tx.ins.length === 0) {\n throw new Error(\"Pre-pegin transaction has no inputs\");\n }\n return tx.ins.map((input) => ({\n txid: Uint8Array.from(Buffer.from(input.hash).reverse()),\n vout: input.index,\n }));\n}\n"],"names":["DEPOSITOR_PUBKEY_SIZE","TXID_SIZE","OUTPOINT_SIZE","COMMITMENT_SIZE","FIELD_LEN_PREFIX_SIZE","VAULT_CONTEXT_SIZE","writeUint32BE","out","offset","value","serializeOutpoint","outpoint","compareBytes","a","b","len","i","buildFundingOutpointsCommitment","outpoints","serialized","flat","sha256","buildVaultContext","input","commitment","VAULT_APP_NAME","ROOT_OUTPUT_BYTES","ROOT_OUTPUT_HEX_LEN","LOWERCASE_HEX_RE","forwardDeriveContextHash","wallet","deriveContextHash","appName","context","deriveVaultRoot","vaultContext","contextHex","uint8ArrayToHex","rootHex","hexToUint8Array","parseFundingOutpointsFromTx","unsignedTxHex","cleanHex","tx","Transaction","Buffer"],"mappings":"uIAsBMA,EAAwB,GACxBC,EAAY,GACZC,EAAgB,GAChBC,EAAkB,GAClBC,EAAwB,EACxBC,EACJD,EACAJ,EACAI,EACAD,EAmBF,SAASG,EAAcC,EAAiBC,EAAgBC,EAAqB,CAC3EF,EAAIC,CAAM,EAAKC,IAAU,GAAM,IAC/BF,EAAIC,EAAS,CAAC,EAAKC,IAAU,GAAM,IACnCF,EAAIC,EAAS,CAAC,EAAKC,IAAU,EAAK,IAClCF,EAAIC,EAAS,CAAC,EAAIC,EAAQ,GAC5B,CAEA,SAASC,EAAkBC,EAAuC,CAChE,GAAIA,EAAS,KAAK,SAAWV,EAC3B,MAAM,IAAI,MACR,iCAAiCA,CAAS,eAAeU,EAAS,KAAK,MAAM,E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EAEvD,OAAOA,EAAG,IAAI,IAAKpB,IAAW,CAC5B,KAAM,WAAW,KAAKsB,EAAAA,OAAO,KAAKtB,EAAM,IAAI,EAAE,SAAS,EACvD,KAAMA,EAAM,KAAA,EACZ,CACJ"}
|
|
@@ -1,93 +0,0 @@
|
|
|
1
|
-
import { u as d, h as E } from "./bitcoin-C-TuHb-v.js";
|
|
2
|
-
import { s as w } from "./sha2-CLpQd0Rd.js";
|
|
3
|
-
import { Transaction as g } from "bitcoinjs-lib";
|
|
4
|
-
import { Buffer as x } from "buffer";
|
|
5
|
-
const i = 32, a = 32, c = 36, m = 32, s = 4, y = s + i + s + m;
|
|
6
|
-
function u(t, r, n) {
|
|
7
|
-
t[r] = n >>> 24 & 255, t[r + 1] = n >>> 16 & 255, t[r + 2] = n >>> 8 & 255, t[r + 3] = n & 255;
|
|
8
|
-
}
|
|
9
|
-
function p(t) {
|
|
10
|
-
if (t.txid.length !== a)
|
|
11
|
-
throw new Error(
|
|
12
|
-
`outpoint.txid must be exactly ${a} bytes, got ${t.txid.length}`
|
|
13
|
-
);
|
|
14
|
-
if (!Number.isInteger(t.vout) || t.vout < 0 || t.vout > 4294967295)
|
|
15
|
-
throw new Error(`outpoint.vout must be a u32, got ${t.vout}`);
|
|
16
|
-
const r = new Uint8Array(c);
|
|
17
|
-
return r.set(t.txid, 0), u(r, a, t.vout), r;
|
|
18
|
-
}
|
|
19
|
-
function h(t, r) {
|
|
20
|
-
const n = Math.min(t.length, r.length);
|
|
21
|
-
for (let e = 0; e < n; e++)
|
|
22
|
-
if (t[e] !== r[e]) return t[e] - r[e];
|
|
23
|
-
return t.length - r.length;
|
|
24
|
-
}
|
|
25
|
-
function v(t) {
|
|
26
|
-
if (t.length === 0)
|
|
27
|
-
throw new Error(
|
|
28
|
-
"buildFundingOutpointsCommitment: outpoints must be non-empty"
|
|
29
|
-
);
|
|
30
|
-
const r = t.map(p);
|
|
31
|
-
r.sort(h);
|
|
32
|
-
for (let e = 1; e < r.length; e++)
|
|
33
|
-
if (h(r[e - 1], r[e]) === 0)
|
|
34
|
-
throw new Error(
|
|
35
|
-
"buildFundingOutpointsCommitment: duplicate outpoint detected"
|
|
36
|
-
);
|
|
37
|
-
const n = new Uint8Array(r.length * c);
|
|
38
|
-
for (let e = 0; e < r.length; e++)
|
|
39
|
-
n.set(r[e], e * c);
|
|
40
|
-
return w(n);
|
|
41
|
-
}
|
|
42
|
-
function O(t) {
|
|
43
|
-
if (t.depositorBtcPubkey.length !== i)
|
|
44
|
-
throw new Error(
|
|
45
|
-
`vaultContext: depositorBtcPubkey must be exactly ${i} bytes, got ${t.depositorBtcPubkey.length}`
|
|
46
|
-
);
|
|
47
|
-
const r = v(t.fundingOutpoints), n = new Uint8Array(y);
|
|
48
|
-
let e = 0;
|
|
49
|
-
return u(n, e, i), e += s, n.set(t.depositorBtcPubkey, e), e += i, u(n, e, m), e += s, n.set(r, e), n;
|
|
50
|
-
}
|
|
51
|
-
const _ = "babylon-btc-vault", f = 32, l = f * 2, T = /^[0-9a-f]+$/;
|
|
52
|
-
function I(t) {
|
|
53
|
-
const r = t.deriveContextHash;
|
|
54
|
-
return typeof r == "function" ? {
|
|
55
|
-
deriveContextHash: (n, e) => r.call(t, n, e)
|
|
56
|
-
} : {};
|
|
57
|
-
}
|
|
58
|
-
async function A(t, r) {
|
|
59
|
-
const n = O(r), e = d(n), o = await t.deriveContextHash(_, e);
|
|
60
|
-
if (typeof o != "string")
|
|
61
|
-
throw new Error(
|
|
62
|
-
`deriveVaultRoot: wallet must return a string, got ${typeof o}`
|
|
63
|
-
);
|
|
64
|
-
if (o.length !== l)
|
|
65
|
-
throw new Error(
|
|
66
|
-
`deriveVaultRoot: wallet must return a ${l}-character hex string (${f} bytes), got length ${o.length}`
|
|
67
|
-
);
|
|
68
|
-
if (!T.test(o))
|
|
69
|
-
throw new Error(
|
|
70
|
-
"deriveVaultRoot: wallet must return lowercase hex per derive-context-hash.md §2.1; got value with non-lowercase or non-hex characters"
|
|
71
|
-
);
|
|
72
|
-
return E(o);
|
|
73
|
-
}
|
|
74
|
-
function R(t) {
|
|
75
|
-
if (!t)
|
|
76
|
-
throw new Error("Pre-pegin transaction hex is empty");
|
|
77
|
-
const r = t.startsWith("0x") ? t.slice(2) : t, n = g.fromHex(r);
|
|
78
|
-
if (n.ins.length === 0)
|
|
79
|
-
throw new Error("Pre-pegin transaction has no inputs");
|
|
80
|
-
return n.ins.map((e) => ({
|
|
81
|
-
txid: Uint8Array.from(x.from(e.hash).reverse()),
|
|
82
|
-
vout: e.index
|
|
83
|
-
}));
|
|
84
|
-
}
|
|
85
|
-
export {
|
|
86
|
-
_ as V,
|
|
87
|
-
O as a,
|
|
88
|
-
v as b,
|
|
89
|
-
A as d,
|
|
90
|
-
I as f,
|
|
91
|
-
R as p
|
|
92
|
-
};
|
|
93
|
-
//# sourceMappingURL=parseFundingOutpoints-BQWvINfm.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"parseFundingOutpoints-BQWvINfm.js","sources":["../src/tbv/core/vault-secrets/context.ts","../src/tbv/core/vault-secrets/deriveVaultRoot.ts","../src/tbv/core/vault-secrets/parseFundingOutpoints.ts"],"sourcesContent":["/**\n * Canonical `vaultContext` byte encoding per\n * `derive-vault-secrets.md` §2.3.\n *\n * ```\n * vaultContext :=\n * I2OSP(32, 4) || depositorBtcPubkey // 32B x-only\n * || I2OSP(32, 4) || fundingOutpointsCommitment // 32B SHA-256\n * ```\n *\n * `fundingOutpointsCommitment` is SHA-256 over the canonically-sorted\n * funding outpoints of the Pre-PegIn transaction, serialized as\n * `txid (32B display/RPC order) || vout (4B u32 big-endian)` per\n * outpoint. Sorting by 36-byte lex order makes the commitment\n * invariant under tx-level input reordering, so same-inputs RBF and\n * reorg rebroadcasts yield the same context.\n *\n * @module vault-secrets/context\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\n\nconst DEPOSITOR_PUBKEY_SIZE = 32;\nconst TXID_SIZE = 32;\nconst OUTPOINT_SIZE = 36;\nconst COMMITMENT_SIZE = 32;\nconst FIELD_LEN_PREFIX_SIZE = 4;\nconst VAULT_CONTEXT_SIZE =\n FIELD_LEN_PREFIX_SIZE +\n DEPOSITOR_PUBKEY_SIZE +\n FIELD_LEN_PREFIX_SIZE +\n COMMITMENT_SIZE;\n\nexport interface FundingOutpoint {\n /**\n * Bitcoin txid in **display / RPC order** (byte-reversed from the\n * internal little-endian wire form used when hashing a raw tx).\n */\n txid: Uint8Array;\n /** Output index within the referenced transaction (u32). */\n vout: number;\n}\n\nexport interface VaultContextInput {\n /** Depositor's x-only BTC public key (32 bytes). */\n depositorBtcPubkey: Uint8Array;\n /** Funding outpoints of the Pre-PegIn transaction. MUST be non-empty. */\n fundingOutpoints: readonly FundingOutpoint[];\n}\n\nfunction writeUint32BE(out: Uint8Array, offset: number, value: number): void {\n out[offset] = (value >>> 24) & 0xff;\n out[offset + 1] = (value >>> 16) & 0xff;\n out[offset + 2] = (value >>> 8) & 0xff;\n out[offset + 3] = value & 0xff;\n}\n\nfunction serializeOutpoint(outpoint: FundingOutpoint): Uint8Array {\n if (outpoint.txid.length !== TXID_SIZE) {\n throw new Error(\n `outpoint.txid must be exactly ${TXID_SIZE} bytes, got ${outpoint.txid.length}`,\n );\n }\n if (\n !Number.isInteger(outpoint.vout) ||\n outpoint.vout < 0 ||\n outpoint.vout > 0xffffffff\n ) {\n throw new Error(`outpoint.vout must be a u32, got ${outpoint.vout}`);\n }\n const out = new Uint8Array(OUTPOINT_SIZE);\n out.set(outpoint.txid, 0);\n writeUint32BE(out, TXID_SIZE, outpoint.vout);\n return out;\n}\n\nfunction compareBytes(a: Uint8Array, b: Uint8Array): number {\n const len = Math.min(a.length, b.length);\n for (let i = 0; i < len; i++) {\n if (a[i] !== b[i]) return a[i] - b[i];\n }\n return a.length - b.length;\n}\n\n/**\n * Compute SHA-256 over canonically-sorted funding outpoints.\n *\n * Outpoints are serialized as 36-byte `txid || vout_BE`, sorted\n * ascending lexicographically, concatenated, then hashed.\n *\n * @stability frozen — on-chain-binding. Any change to layout, sort\n * order, or serialization is a hard fork; existing deposits would no\n * longer match their committed `depositorWotsPkHash`.\n *\n * @throws If `outpoints` is empty or contains duplicates.\n */\nexport function buildFundingOutpointsCommitment(\n outpoints: readonly FundingOutpoint[],\n): Uint8Array {\n if (outpoints.length === 0) {\n throw new Error(\n \"buildFundingOutpointsCommitment: outpoints must be non-empty\",\n );\n }\n const serialized = outpoints.map(serializeOutpoint);\n serialized.sort(compareBytes);\n\n for (let i = 1; i < serialized.length; i++) {\n if (compareBytes(serialized[i - 1], serialized[i]) === 0) {\n throw new Error(\n \"buildFundingOutpointsCommitment: duplicate outpoint detected\",\n );\n }\n }\n\n const flat = new Uint8Array(serialized.length * OUTPOINT_SIZE);\n for (let i = 0; i < serialized.length; i++) {\n flat.set(serialized[i], i * OUTPOINT_SIZE);\n }\n return sha256(flat);\n}\n\n/**\n * Build the canonical `vaultContext` byte string fed into the wallet's\n * `deriveContextHash` (or a locally-implemented equivalent on the\n * app side).\n *\n * Output length is always 72 bytes.\n *\n * @stability frozen — on-chain-binding. The 72-byte layout is the\n * input to `deriveContextHash`; any change rotates the vault root and\n * therefore every WOTS key, hashlock secret, and auth anchor derived\n * from it. Existing deposits cannot be recovered after a layout change.\n */\nexport function buildVaultContext(input: VaultContextInput): Uint8Array {\n if (input.depositorBtcPubkey.length !== DEPOSITOR_PUBKEY_SIZE) {\n throw new Error(\n `vaultContext: depositorBtcPubkey must be exactly ${DEPOSITOR_PUBKEY_SIZE} bytes, got ${input.depositorBtcPubkey.length}`,\n );\n }\n const commitment = buildFundingOutpointsCommitment(input.fundingOutpoints);\n\n const out = new Uint8Array(VAULT_CONTEXT_SIZE);\n let offset = 0;\n\n writeUint32BE(out, offset, DEPOSITOR_PUBKEY_SIZE);\n offset += FIELD_LEN_PREFIX_SIZE;\n out.set(input.depositorBtcPubkey, offset);\n offset += DEPOSITOR_PUBKEY_SIZE;\n\n writeUint32BE(out, offset, COMMITMENT_SIZE);\n offset += FIELD_LEN_PREFIX_SIZE;\n out.set(commitment, offset);\n\n return out;\n}\n","/**\n * Vault-root derivation via the wallet's `deriveContextHash` API.\n *\n * Implements the canonical root source from `derive-vault-secrets.md`\n * §2.2:\n *\n * ```\n * rootDerivation = deriveContextHash(\"babylon-btc-vault\", hex(vaultContext))\n * ```\n *\n * The 32-byte output is fed directly into the {@link expandAuthAnchor},\n * {@link expandHashlockSecret}, and {@link expandWotsSeed} functions in\n * this module.\n *\n * @module vault-secrets/deriveVaultRoot\n */\n\nimport { hexToUint8Array, uint8ArrayToHex } from \"../primitives/utils/bitcoin\";\n\nimport { buildVaultContext, type VaultContextInput } from \"./context\";\n\n/**\n * The fixed `appName` passed to the wallet's `deriveContextHash` for\n * Babylon vault derivations. The wallet displays this in its approval\n * dialog. Defined by `derive-vault-secrets.md` §2.2 — must not be\n * changed without coordinating a spec revision and a downstream\n * migration plan, as it provides app-level domain separation across\n * applications using the same wallet.\n */\nexport const VAULT_APP_NAME = \"babylon-btc-vault\";\n\n/** Expected length of the wallet output in bytes per spec §2.1. */\nconst ROOT_OUTPUT_BYTES = 32;\n\n/** Expected length of the wallet output in lowercase hex chars. */\nconst ROOT_OUTPUT_HEX_LEN = ROOT_OUTPUT_BYTES * 2;\n\nconst LOWERCASE_HEX_RE = /^[0-9a-f]+$/;\n\n/**\n * Minimal structural shape for the wallet capability needed by this\n * helper. Typed against the method directly so callers can pass any\n * value that implements `deriveContextHash` — `BitcoinWallet` from\n * this SDK, `IBTCProvider` from `@babylonlabs-io/wallet-connector`,\n * or a test mock — without depending on the rest of either interface.\n */\nexport interface DeriveContextHashCapableWallet {\n deriveContextHash(appName: string, context: string): Promise<string>;\n}\n\n/** Forward the deriveContextHash capability only when the wallet actually has it,\n * so seam guards (ensurePrePeginTermsApproval) can fire their typed error instead\n * of a mid-ceremony TypeError. */\nexport function forwardDeriveContextHash(\n wallet: Partial<DeriveContextHashCapableWallet>,\n): Partial<DeriveContextHashCapableWallet> {\n // Captured before the closure so the narrowing survives it. The property\n // read cannot be narrowed across a closure boundary, which is what forced\n // the non-null assertion this replaces; forwarding is otherwise unchanged.\n const deriveContextHash = wallet.deriveContextHash;\n return typeof deriveContextHash === \"function\"\n ? {\n deriveContextHash: (appName, context) =>\n deriveContextHash.call(wallet, appName, context),\n }\n : {};\n}\n\n/**\n * Derive the 32-byte vault root from a wallet by encoding the\n * canonical {@link VaultContextInput} and forwarding to\n * `wallet.deriveContextHash`.\n *\n * Validates the wallet's output strictly: must be exactly 64\n * lowercase hex characters per `derive-context-hash.md` §2.1. A\n * conformant wallet always satisfies this, but we re-check at the\n * SDK boundary so a non-conformant wallet (or a wallet returning a\n * malformed value through a buggy adapter) fails loud here rather\n * than producing silently-wrong derived secrets downstream.\n *\n * The helper itself produces only valid spec inputs (`appName` is\n * the hardcoded `VAULT_APP_NAME`; `context` is hex of the 72-byte\n * `vaultContext`, always 144 chars lowercase), so input-side\n * validation is unnecessary.\n *\n * @param wallet - Any value implementing `deriveContextHash`.\n * @param input - The canonical {@link VaultContextInput} that\n * uniquely identifies the vault. Encoded by\n * {@link buildVaultContext} into a 72-byte structure\n * before being hex-encoded for the wallet.\n * @stability frozen — on-chain-binding. The pair (`VAULT_APP_NAME`,\n * `vaultContext` encoding) is the wallet's input space; changing\n * either rotates the root and invalidates every secret derived from\n * it. `VAULT_APP_NAME` is fixed by `derive-vault-secrets.md` §2.2\n * and must never change without a coordinated spec revision.\n *\n * @returns 32-byte root suitable for {@link expandAuthAnchor},\n * {@link expandHashlockSecret}, {@link expandWotsSeed}.\n * @throws If the wallet returns a non-64-char or non-lowercase-hex\n * string. Errors from the wallet (user rejection,\n * method-not-supported, etc.) propagate unchanged.\n */\nexport async function deriveVaultRoot(\n wallet: DeriveContextHashCapableWallet,\n input: VaultContextInput,\n): Promise<Uint8Array> {\n const vaultContext = buildVaultContext(input);\n const contextHex = uint8ArrayToHex(vaultContext);\n\n const rootHex = await wallet.deriveContextHash(VAULT_APP_NAME, contextHex);\n\n if (typeof rootHex !== \"string\") {\n throw new Error(\n `deriveVaultRoot: wallet must return a string, got ${typeof rootHex}`,\n );\n }\n if (rootHex.length !== ROOT_OUTPUT_HEX_LEN) {\n throw new Error(\n `deriveVaultRoot: wallet must return a ${ROOT_OUTPUT_HEX_LEN}-character hex string (${ROOT_OUTPUT_BYTES} bytes), got length ${rootHex.length}`,\n );\n }\n if (!LOWERCASE_HEX_RE.test(rootHex)) {\n throw new Error(\n \"deriveVaultRoot: wallet must return lowercase hex per derive-context-hash.md §2.1; got value with non-lowercase or non-hex characters\",\n );\n }\n\n return hexToUint8Array(rootHex);\n}\n","/**\n * Parse a Pre-PegIn transaction's inputs into the vault-context\n * `fundingOutpoints` shape consumed by `deriveVaultRoot`. Reverses\n * the prev-txid bytes from wire-internal little-endian to display\n * order so the derivation is byte-for-byte identical to the\n * deposit-time computation.\n *\n * @module vault-secrets/parseFundingOutpoints\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport type { FundingOutpoint } from \"./context\";\n\nexport function parseFundingOutpointsFromTx(\n unsignedTxHex: string,\n): FundingOutpoint[] {\n if (!unsignedTxHex) {\n throw new Error(\"Pre-pegin transaction hex is empty\");\n }\n const cleanHex = unsignedTxHex.startsWith(\"0x\")\n ? unsignedTxHex.slice(2)\n : unsignedTxHex;\n const tx = Transaction.fromHex(cleanHex);\n if (tx.ins.length === 0) {\n throw new Error(\"Pre-pegin transaction has no inputs\");\n }\n return tx.ins.map((input) => ({\n txid: Uint8Array.from(Buffer.from(input.hash).reverse()),\n vout: input.index,\n }));\n}\n"],"names":["DEPOSITOR_PUBKEY_SIZE","TXID_SIZE","OUTPOINT_SIZE","COMMITMENT_SIZE","FIELD_LEN_PREFIX_SIZE","VAULT_CONTEXT_SIZE","writeUint32BE","out","offset","value","serializeOutpoint","outpoint","compareBytes","a","b","len","i","buildFundingOutpointsCommitment","outpoints","serialized","flat","sha256","buildVaultContext","input","commitment","VAULT_APP_NAME","ROOT_OUTPUT_BYTES","ROOT_OUTPUT_HEX_LEN","LOWERCASE_HEX_RE","forwardDeriveContextHash","wallet","deriveContextHash","appName","context","deriveVaultRoot","vaultContext","contextHex","uint8ArrayToHex","rootHex","hexToUint8Array","parseFundingOutpointsFromTx","unsignedTxHex","cleanHex","tx","Transaction","Buffer"],"mappings":";;;;AAsBA,MAAMA,IAAwB,IACxBC,IAAY,IACZC,IAAgB,IAChBC,IAAkB,IAClBC,IAAwB,GACxBC,IACJD,IACAJ,IACAI,IACAD;AAmBF,SAASG,EAAcC,GAAiBC,GAAgBC,GAAqB;AAC3E,EAAAF,EAAIC,CAAM,IAAKC,MAAU,KAAM,KAC/BF,EAAIC,IAAS,CAAC,IAAKC,MAAU,KAAM,KACnCF,EAAIC,IAAS,CAAC,IAAKC,MAAU,IAAK,KAClCF,EAAIC,IAAS,CAAC,IAAIC,IAAQ;AAC5B;AAEA,SAASC,EAAkBC,GAAuC;AAChE,MAAIA,EAAS,KAAK,WAAWV;AAC3B,UAAM,IAAI;AAAA,MACR,iCAAiCA,CAAS,eAAeU,EAAS,KAAK,MAAM;AAAA,IAAA;AAGjF,MACE,CAAC,OAAO,UAAUA,EAAS,IAAI,KAC/BA,EAAS,OAAO,KAChBA,EAAS,OAAO;AAEhB,UAAM,IAAI,MAAM,oCAAoCA,EAAS,IAAI,EAAE;AAErE,QAAMJ,IAAM,IAAI,WAAWL,CAAa;AACxC,SAAAK,EAAI,IAAII,EAAS,MAAM,CAAC,GACxBL,EAAcC,GAAKN,GAAWU,EAAS,IAAI,GACpCJ;AACT;AAEA,SAASK,EAAaC,GAAeC,GAAuB;AAC1D,QAAMC,IAAM,KAAK,IAAIF,EAAE,QAAQC,EAAE,MAAM;AACvC,WAASE,IAAI,GAAGA,IAAID,GAAKC;AACvB,QAAIH,EAAEG,CAAC,MAAMF,EAAEE,CAAC,EAAG,QAAOH,EAAEG,CAAC,IAAIF,EAAEE,CAAC;AAEtC,SAAOH,EAAE,SA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,CAAO;AAAA,EAAA,IAEnD,CAAA;AACN;AAoCA,eAAsBC,EACpBJ,GACAP,GACqB;AACrB,QAAMY,IAAeb,EAAkBC,CAAK,GACtCa,IAAaC,EAAgBF,CAAY,GAEzCG,IAAU,MAAMR,EAAO,kBAAkBL,GAAgBW,CAAU;AAEzE,MAAI,OAAOE,KAAY;AACrB,UAAM,IAAI;AAAA,MACR,qDAAqD,OAAOA,CAAO;AAAA,IAAA;AAGvE,MAAIA,EAAQ,WAAWX;AACrB,UAAM,IAAI;AAAA,MACR,yCAAyCA,CAAmB,0BAA0BD,CAAiB,uBAAuBY,EAAQ,MAAM;AAAA,IAAA;AAGhJ,MAAI,CAACV,EAAiB,KAAKU,CAAO;AAChC,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAIJ,SAAOC,EAAgBD,CAAO;AAChC;ACjHO,SAASE,EACdC,GACmB;AACnB,MAAI,CAACA;AACH,UAAM,IAAI,MAAM,oCAAoC;AAEtD,QAAMC,IAAWD,EAAc,WAAW,IAAI,IAC1CA,EAAc,MAAM,CAAC,IACrBA,GACEE,IAAKC,EAAY,QAAQF,CAAQ;AACvC,MAAIC,EAAG,IAAI,WAAW;AACpB,UAAM,IAAI,MAAM,qCAAqC;AAEvD,SAAOA,EAAG,IAAI,IAAI,CAACpB,OAAW;AAAA,IAC5B,MAAM,WAAW,KAAKsB,EAAO,KAAKtB,EAAM,IAAI,EAAE,SAAS;AAAA,IACvD,MAAMA,EAAM;AAAA,EAAA,EACZ;AACJ;"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var gt=Object.defineProperty;var pt=(t,e,n)=>e in t?gt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var B=(t,e,n)=>pt(t,typeof e!="symbol"?e+"":e,n);const b=require("viem"),p=require("./BTCVaultRegistry.abi-BQ5tFNSu.cjs"),I=require("./BTCVaultRegistryKeyEpochs.abi-DCJnzKer.cjs"),A=require("./constants-BTZdyOuk.cjs"),ft=require("./tbv/core/utils/eth/index.cjs"),x=require("./onChainBtcPubkey-BbxRrbvg.cjs"),C=require("./secp256k1-DDHQ1_za.cjs"),f=require("./sha2-DI0-0SHr.cjs"),V=25,z=9999;function _(t){if(!Number.isInteger(t)||t<0||t>=A.MAX_VP_COMMISSION_BPS_EXCLUSIVE)throw new Error(`Quoted commissionBps must be an integer in [0, ${A.MAX_VP_COMMISSION_BPS_EXCLUSIVE}), got ${t}`);return Math.min(t+V,z)}const mt=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),G=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),Pt=G.map(t=>(9*t+5)%16),Q=(()=>{const n=[[G],[Pt]];for(let o=0;o<4;o++)for(let i of n)i.push(i[o].map(a=>mt[a]));return n})(),Y=Q[0],j=Q[1],J=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(t=>Uint8Array.from(t)),bt=Y.map((t,e)=>t.map(n=>J[e][n])),yt=j.map((t,e)=>t.map(n=>J[e][n])),Ct=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),wt=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function M(t,e,n,o){return t===0?e^n^o:t===1?e&n|~e&o:t===2?(e|~n)^o:t===3?e&o|n&~o:e^(n|~o)}const T=new Uint32Array(16);class Bt extends f.HashMD{constructor(){super(64,20,8,!0);B(this,"h0",1732584193);B(this,"h1",-271733879);B(this,"h2",-1732584194);B(this,"h3",271733878);B(this,"h4",-1009589776)}get(){const{h0:n,h1:o,h2:i,h3:a,h4:c}=this;return[n,o,i,a,c]}set(n,o,i,a,c){this.h0=n|0,this.h1=o|0,this.h2=i|0,this.h3=a|0,this.h4=c|0}process(n,o){for(let r=0;r<16;r++,o+=4)T[r]=n.getUint32(o,!0);let i=this.h0|0,a=i,c=this.h1|0,h=c,d=this.h2|0,g=d,m=this.h3|0,y=m,s=this.h4|0,l=s;for(let r=0;r<5;r++){const u=4-r,w=Ct[r],ct=wt[r],ut=Y[r],ht=j[r],lt=bt[r],dt=yt[r];for(let P=0;P<16;P++){const $=f.rotl(i+M(r,c,d,m)+T[ut[P]]+w,lt[P])+s|0;i=s,s=m,m=f.rotl(d,10)|0,d=c,c=$}for(let P=0;P<16;P++){const $=f.rotl(a+M(u,h,g,y)+T[ht[P]]+ct,dt[P])+l|0;a=l,l=y,y=f.rotl(g,10)|0,g=h,h=$}}this.set(this.h1+d+y|0,this.h2+m+l|0,this.h3+s+a|0,this.h4+i+h|0,this.h0+c+g|0)}roundClean(){f.clean(T)}destroy(){this.destroyed=!0,f.clean(this.buffer),this.set(0,0,0,0,0)}}const Z=f.createHasher(()=>new Bt),Et="5120",N="0014",It=20,K=33,xt=65,Tt=2,At=3,Vt=4;function tt(t,e){const n=t.startsWith("0x")||t.startsWith("0X")?t.slice(2):t;if(!/^(?:[0-9a-fA-F]{2})+$/.test(n))throw new Error(`${e} must be non-empty, even-length hex`);return`0x${n.toLowerCase()}`}function vt(t){const e=f.hexToBytes(t),n=C.schnorr.utils.lift_x(BigInt(`0x${t}`)),o=C.schnorr.utils.bytesToNumberBE(C.schnorr.utils.taggedHash("TapTweak",e));if(o>=C.secp256k1.CURVE.n)throw new Error("Proof of possession BTC pubkey has an invalid TapTweak");const i=o===0n?n:n.add(C.schnorr.Point.BASE.multiply(o));return`0x${Et}${f.bytesToHex(C.schnorr.utils.pointToBytes(i))}`}function $t(t){const e=tt(t,"depositorBtcPubkeyRaw"),n=f.hexToBytes(e.slice(2));if(n.length===32)return{xOnlyPubkey:x.assertOnChainBtcPubkey(e,"Payout BTC pubkey")};const o=n.length===K&&(n[0]===Tt||n[0]===At),i=n.length===xt&&n[0]===Vt;if(!o&&!i)throw new Error("depositorBtcPubkeyRaw must be x-only, compressed, or uncompressed");try{C.secp256k1.Point.fromBytes(n)}catch{throw new Error("depositorBtcPubkeyRaw is not a valid BTC pubkey")}return{xOnlyPubkey:f.bytesToHex(n.subarray(1,K)),compressedPubkey:o?n:void 0}}function St(t){return`0x${N}${f.bytesToHex(Z(f.sha256(t)))}`}function Rt(t,e,n){const o=tt(t,"depositorPayoutScriptPubKey");if((o.length-2)/2>A.MAX_PAYOUT_SCRIPT_LEN)throw new Error(`depositorPayoutScriptPubKey exceeds ${A.MAX_PAYOUT_SCRIPT_LEN} bytes`);const i=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e,a=x.assertOnChainBtcPubkey(`0x${i}`,"Proof of possession BTC pubkey"),c=$t(n);if(c.xOnlyPubkey!==a)throw new Error("depositorBtcPubkeyRaw does not match the proof of possession BTC pubkey");if(o===vt(a))return o;if(o.startsWith(`0x${N}`)&&o.length===2+N.length+It*2){if(!c.compressedPubkey)throw new Error("A P2WPKH payout requires a compressed BTC pubkey");if(o===St(c.compressedPubkey))return o}throw new Error("depositorPayoutScriptPubKey does not match the proof of possession BTC pubkey")}function kt(t,e){const n=t.startsWith("0x")?t.slice(2):t;if(n.length===0||n.length%2!==0)throw new Error(`${e} must be non-empty, even-length hex`);if(!/^[0-9a-fA-F]+$/.test(n))throw new Error(`${e} contains non-hex characters`);const o=new Uint8Array(n.length/2);for(let i=0;i<o.length;i++)o[i]=Number.parseInt(n.slice(i*2,i*2+2),16);return o}function _t(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function Nt(t){const e=new Uint8Array(t.reduce((o,i)=>o+i.length,0));let n=0;for(const o of t)e.set(o,n),n+=o.length;return e}function Ot(t){let e=0;const n=(s,l)=>{if(!Number.isSafeInteger(s)||s<0)throw new Error(`Invalid ${l} length ${s}`);if(e+s>t.length)throw new Error(`Truncated Bitcoin transaction while reading ${l}`);const r=t.slice(e,e+s);return e+=s,r},o=(s,l)=>{const r=n(s,l);let u=0n;for(let w=r.length-1;w>=0;w--)u=u<<8n|BigInt(r[w]);return u},i=s=>{const l=e,r=n(1,s)[0];let u;if(r<253)u=BigInt(r);else if(r===253){if(u=o(2,s),u<0xfdn)throw new Error(`Non-canonical ${s}`)}else if(r===254){if(u=o(4,s),u<=0xffffn)throw new Error(`Non-canonical ${s}`)}else if(u=o(8,s),u<=0xffffffffn)throw new Error(`Non-canonical ${s}`);if(u>BigInt(Number.MAX_SAFE_INTEGER))throw new Error(`${s} exceeds JavaScript's safe integer range`);return{encoded:t.slice(l,e),value:Number(u)}},a=n(4,"version"),c=t[e]===0&&t[e+1]===1;c&&(e+=2);const h=i("input count"),d=[];for(let s=0;s<h.value;s++){const l=e;n(32,`input ${s} previous transaction hash`),n(4,`input ${s} previous output index`);const r=i(`input ${s} script length`);n(r.value,`input ${s} script`),n(4,`input ${s} sequence`),d.push(t.slice(l,e))}const g=i("output count"),m=[];for(let s=0;s<g.value;s++){const l=e;n(8,`output ${s} value`);const r=i(`output ${s} script length`);n(r.value,`output ${s} script`),m.push(t.slice(l,e))}if(c){let s=!1;for(let l=0;l<h.value;l++){const r=i(`input ${l} witness item count`);s||(s=r.value>0);for(let u=0;u<r.value;u++){const w=i(`input ${l} witness item ${u} length`);n(w.value,`input ${l} witness item ${u}`)}}if(!s)throw new Error("Bitcoin transaction has superfluous witness marker")}const y=n(4,"locktime");if(e!==t.length)throw new Error(`Bitcoin transaction has ${t.length-e} trailing byte(s)`);return Nt([a,h.encoded,...d,g.encoded,...m,y])}function et(t){const e=Ot(kt(t,"transactionHex")),n=f.sha256(f.sha256(e));return n.reverse(),`0x${_t(n)}`}function nt(t,e){const n=t.startsWith("0x")?t:`0x${t}`;if(!/^0x[0-9a-fA-F]{64}$/.test(n))throw new Error("peginTxHash must be a 32-byte hex value");const o=e.startsWith("0x")?e:`0x${e}`;if(!b.isAddress(o,{strict:!0}))throw new Error(`Invalid depositor Ethereum address: ${e}`);return b.keccak256(b.encodeAbiParameters([{type:"bytes32"},{type:"address"}],[n,o])).slice(2)}const S=65535,F=1e4,v=4294967295,q=255;function ot(t){if(!Number.isInteger(t)||t<0||t>v)throw new Error(`Invalid offchainParamsVersion from contract: must be a uint32, got ${t}`)}function it(t){const e=[];if(t.timelockAssert<=0n&&e.push(`timelockAssert must be positive, got ${t.timelockAssert}`),t.timelockAssert>BigInt(S)&&e.push(`timelockAssert ${t.timelockAssert} exceeds uint16 max (${S})`),t.timelockChallengeAssert<=0n&&e.push(`timelockChallengeAssert must be positive, got ${t.timelockChallengeAssert}`),t.tRefund<=0&&e.push(`tRefund must be positive, got ${t.tRefund}`),t.tStale<=0&&e.push(`tStale must be positive, got ${t.tStale}`),t.securityCouncilKeys.length===0&&e.push("securityCouncilKeys must not be empty"),t.councilQuorum<=0&&e.push(`councilQuorum must be positive, got ${t.councilQuorum}`),t.councilQuorum>t.securityCouncilKeys.length&&e.push(`councilQuorum (${t.councilQuorum}) exceeds securityCouncilKeys count (${t.securityCouncilKeys.length})`),t.feeRate<=0n&&e.push(`feeRate must be positive, got ${t.feeRate}`),t.minPeginFeeRate<=0n&&e.push(`minPeginFeeRate must be positive, got ${t.minPeginFeeRate}`),(!Number.isInteger(t.proverCircuitVersion)||t.proverCircuitVersion<0||t.proverCircuitVersion>S)&&e.push(`proverCircuitVersion must be a uint16, got ${t.proverCircuitVersion}`),(!Number.isInteger(t.minPrepeginDepth)||t.minPrepeginDepth<=0||t.minPrepeginDepth>v)&&e.push(`minPrepeginDepth must be a uint32 in [1, ${v}], got ${t.minPrepeginDepth}`),t.babeTotalInstances<=0&&e.push(`babeTotalInstances must be positive, got ${t.babeTotalInstances}`),t.babeInstancesToFinalize<=0&&e.push(`babeInstancesToFinalize must be positive, got ${t.babeInstancesToFinalize}`),t.babeInstancesToFinalize>t.babeTotalInstances&&e.push(`babeInstancesToFinalize (${t.babeInstancesToFinalize}) exceeds babeTotalInstances (${t.babeTotalInstances})`),(t.minVpCommissionBps<0||t.minVpCommissionBps>F)&&e.push(`minVpCommissionBps must be in [0, ${F}], got ${t.minVpCommissionBps}`),e.length>0)throw new Error(`Invalid offchain protocol parameters: ${e.join("; ")}`)}function st(t){const e=[];if(t.minimumPegInAmount<=0n&&e.push(`minimumPegInAmount must be positive, got ${t.minimumPegInAmount}`),t.maxPegInAmount<t.minimumPegInAmount&&e.push(`maxPegInAmount (${t.maxPegInAmount}) must be >= minimumPegInAmount (${t.minimumPegInAmount})`),t.pegInAckTimeout<=0n&&e.push(`pegInAckTimeout must be positive, got ${t.pegInAckTimeout}`),t.pegInActivationTimeout<=0n&&e.push(`pegInActivationTimeout must be positive, got ${t.pegInActivationTimeout}`),(!Number.isInteger(t.maxHtlcOutputCount)||t.maxHtlcOutputCount<=0||t.maxHtlcOutputCount>q)&&e.push(`maxHtlcOutputCount must be an integer in [1, ${q}], got ${t.maxHtlcOutputCount}`),(typeof t.expiredPegInGraceBlocks!="bigint"||t.expiredPegInGraceBlocks<=0n)&&e.push(`expiredPegInGraceBlocks must be a positive bigint, got ${t.expiredPegInGraceBlocks}`),e.length>0)throw new Error(`Invalid TBV protocol parameters: ${e.join("; ")}`)}function Ht(t){if(st(t),it(t.offchainParams),!Number.isInteger(t.offchainParamsVersion)||t.offchainParamsVersion<0||t.offchainParamsVersion>v)throw new Error(`Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${t.offchainParamsVersion}`);C.assertValidVaultCoreVersion(t.activeVaultCoreVersion,"ProtocolParams.activeVaultCoreVersion()")}const rt="RegistrationLogsUnavailableError";class H extends Error{constructor(n){super(`The Ethereum node returned no registration logs for block ${n}, which holds a vault registration; the node may not have indexed that block yet. Try again.`);B(this,"blockNumber");this.name=rt,this.blockNumber=n}}function Mt(t){return t instanceof H?!0:typeof t!="object"||t===null?!1:t.name===rt}const U=9999;function L(t){return{depositor:t.depositor,depositorBtcPubKey:t.depositorBtcPubKey,amount:t.amount,vaultProvider:t.vaultProvider,status:t.status,applicationEntryPoint:t.applicationEntryPoint,createdAt:t.createdAt}}function R(t){const e=Number(t.offchainParamsVersion);return ot(e),{depositorSignedPeginTx:t.depositorSignedPeginTx,universalChallengersVersion:t.universalChallengersVersion,appVaultKeepersVersion:t.appVaultKeepersVersion,offchainParamsVersion:e,verifiedAt:t.verifiedAt,depositorWotsPkHash:t.depositorWotsPkHash,hashlock:t.hashlock,htlcVout:t.htlcVout,depositorPopSignature:t.depositorPopSignature,prePeginTxHash:t.prePeginTxHash,vaultProviderCommissionBps:t.vaultProviderCommissionBps,vaultCoreVersion:t.vaultCoreVersion}}const Kt=1n<<64n,W=0n,Ft=[b.getAbiItem({abi:p.BTCVaultRegistryABI,name:"PegInSubmitted"}),b.getAbiItem({abi:p.BTCVaultRegistryABI,name:"PegInSubmittedV2"})];function k(t,e,n){if(t<0n||t>=Kt)throw new Error(`getBtcVaultProtocolInfo returned ${e}=${t} for vault ${n}, outside the uint64 range — the registry may predate RFC-006`);return t}function D(t,e){return{vpKeyEpoch:k(t.vpKeyEpoch,"vpKeyEpoch",e),appKeeperKeyEpoch:k(t.appKeeperKeyEpoch,"appKeeperKeyEpoch",e),ucKeyEpoch:k(t.ucKeyEpoch,"ucKeyEpoch",e)}}class at{constructor(e,n){this.publicClient=e,this.contractAddress=n}async getVaultProviderGenesisBtcPubKey(e,n){const o=await this.publicClient.readContract({address:this.contractAddress,abi:p.BTCVaultRegistryABI,functionName:"getOperationBtcKeyAtEpoch",args:[e,W],blockNumber:n});return x.assertOnChainBtcPubkey(o,`getOperationBtcKeyAtEpoch (vp=${e}, epoch=${W})`)}async getVaultProviderApplication(e,n){return await this.publicClient.readContract({address:this.contractAddress,abi:p.BTCVaultRegistryABI,functionName:"getVaultProviderApplication",args:[e],blockNumber:n})}async getCurrentVaultProviderOperationBtcKey(e){const n=await this.publicClient.readContract({address:this.contractAddress,abi:p.BTCVaultRegistryABI,functionName:"getCurrentOperationBtcKey",args:[e]});return x.assertOnChainBtcPubkey(n,`getCurrentOperationBtcKey (vp=${e})`)}async getVaultKeyEpochs(e){const n=await this.publicClient.readContract({address:this.contractAddress,abi:I.BTCVaultRegistryKeyEpochsABI,functionName:"getBtcVaultProtocolInfo",args:[e]});return D(n,e)}async getVaultKeyEpochsBatch(e){return e.length===0?[]:(await this.publicClient.multicall({contracts:e.map(o=>({address:this.contractAddress,abi:I.BTCVaultRegistryKeyEpochsABI,functionName:"getBtcVaultProtocolInfo",args:[o]})),allowFailure:!1})).map((o,i)=>D(o,e[i]))}async getVaultBasicInfo(e){const n=await this.publicClient.readContract({address:this.contractAddress,abi:p.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[e]});return L(n)}async getVaultProtocolInfo(e){const n=await this.publicClient.readContract({address:this.contractAddress,abi:p.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[e]});return R(n)}async getProtocolInfoBatch(e){return e.length===0?[]:(await this.publicClient.multicall({contracts:e.map(o=>({address:this.contractAddress,abi:p.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[o]})),allowFailure:!1})).map((o,i)=>{const a=o;if(!a.depositorSignedPeginTx||a.depositorSignedPeginTx==="0x")throw new Error(`Vault ${e[i]} not found on-chain or has no pegin transaction`);return R(a)})}async getPegInFee(e){return await this.publicClient.readContract({address:this.contractAddress,abi:p.BTCVaultRegistryABI,functionName:"getPegInFee",args:[e]})}async getVaultProviderCommission(e){const n=await this.publicClient.readContract({address:this.contractAddress,abi:p.BTCVaultRegistryABI,functionName:"getVaultProviderCommission",args:[e]});if(!Number.isInteger(n)||n<0||n>U)throw new Error(`getVaultProviderCommission returned ${n} bps for ${e}, outside the protocol range [0, ${U}]`);return n}async getVaultData(e){const[n,o]=await this.publicClient.multicall({contracts:[{address:this.contractAddress,abi:p.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[e]},{address:this.contractAddress,abi:p.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[e]}],allowFailure:!1}),i=L(n),a=R(o);if(!a.depositorSignedPeginTx||a.depositorSignedPeginTx==="0x")throw new Error(`Vault ${e} not found on-chain or has no pegin transaction`);return{basic:i,protocol:a}}async getMaxAcceptableCommissionBpsBatch(e,n){if(e.length===0)return[];const o=await this.publicClient.getLogs({address:this.contractAddress,events:Ft,fromBlock:n,toBlock:n,strict:!0});if(o.length===0)throw new H(n);return e.map(i=>{const a=i.toLowerCase();let c=!1;const h=[];for(const d of o)d.args.vaultId.toLowerCase()===a&&(c=!0,d.eventName==="PegInSubmittedV2"&&h.push(d.args.maxAcceptableCommissionBps));if(h.length===1)return h[0];throw h.length>1?new Error(`Expected one PegInSubmittedV2 log for vault ${i} at block ${n}, found ${h.length} PegInSubmittedV2 logs`):c?new Error(`Vault ${i} was registered before the registry emitted the depositor's commission ceiling (no PegInSubmittedV2 log at block ${n}), so the ceiling cannot be recovered on-chain`):new Error(`Vault ${i} has no registration log at its on-chain registration block ${n}`)})}}const qt=0,Ut=255,Lt=12e4;function E(t,e){const n=t.startsWith("0x")?t:t.startsWith("0X")?`0x${t.slice(2)}`:`0x${t}`;if(!/^0x(?:[0-9a-fA-F]{2})+$/.test(n))throw new Error(`${e} must be non-empty, even-length hex`);return n}function O(t,e){if(!/^0x[0-9a-fA-F]{64}$/.test(t))throw new Error(`${e} must be a 32-byte hex value`)}const Wt="0x0000000000000000000000000000000000000000000000000000000000000000";function X(t){if(O(t,"expectedFingerprint"),t.toLowerCase()===Wt)throw new Error("expectedFingerprint must not be zero: the registry cannot resolve a zero fingerprint, so this submission would always revert")}function Dt(t){if(!Number.isInteger(t)||t<0||t>Ut)throw new Error(`htlcVout must be a uint8, got ${t}`)}class Xt{constructor(e){this.config=e}async registerPeginOnChain(e){const n={...e,popSignature:{...e.popSignature}};this.assertQuotedCommissionPresentWhenRequired(n.quotedCommissionBps),X(n.expectedFingerprint);const o=this.assertPopMatchesEthAccount(n.popSignature),i=this.normalizeBtcPubkey(n.popSignature),a=E(n.popSignature.btcPopSignature,"btcPopSignature"),c=this.normalizeRequest(n,o,i);await this.assertVaultDoesNotExist(c.vaultId,c.peginTxHash);const h=await this.readPeginFee(n.vaultProvider),d=await this.resolveMaxAcceptableCommissionBps(n.vaultProvider,n.quotedCommissionBps),g=b.encodeFunctionData({abi:p.BTCVaultRegistryABI,functionName:"submitPeginRequest",args:[o,i,a,c.unsignedPrePeginTx,c.depositorSignedPeginTx,n.vaultProvider,d,n.hashlock,n.htlcVout,c.payoutScript,n.depositorWotsPkHash,n.expectedFingerprint]});return{ethTxHash:await this.sendAndWait(g,h,!1,o),vaultId:c.vaultId,peginTxHash:c.peginTxHash}}async registerPeginBatchOnChain(e){const n={...e,popSignature:{...e.popSignature},requests:e.requests.map(r=>({...r}))};if(n.requests.length===0)throw new Error("Batch pegin requires at least one request");this.assertQuotedCommissionPresentWhenRequired(n.quotedCommissionBps),X(n.expectedFingerprint);const o=this.assertPopMatchesEthAccount(n.popSignature),i=E(n.unsignedPrePeginTx,"unsignedPrePeginTx"),a=this.normalizeBtcPubkey(n.popSignature),c=E(n.popSignature.btcPopSignature,"btcPopSignature"),h=[],d=[],g=new Set;for(const r of n.requests){const u=this.normalizeRequest({...r,unsignedPrePeginTx:n.unsignedPrePeginTx,vaultProvider:n.vaultProvider,depositorBtcPubkeyRaw:n.depositorBtcPubkeyRaw},o,a);if(g.has(u.vaultId))throw new Error(`Duplicate vault in batch: ${u.vaultId}`);g.add(u.vaultId),h.push({vaultId:u.vaultId,peginTxHash:u.peginTxHash}),d.push({depositorBtcPubKey:a,btcPopSignature:c,unsignedPrePeginTx:i,depositorSignedPeginTx:u.depositorSignedPeginTx,hashlock:r.hashlock,htlcVout:r.htlcVout,referralCode:qt,depositorPayoutBtcAddress:u.payoutScript,depositorWotsPkHash:r.depositorWotsPkHash})}for(const r of h)await this.assertVaultDoesNotExist(r.vaultId,r.peginTxHash);const m=await this.readPeginFee(n.vaultProvider),y=await this.resolveMaxAcceptableCommissionBps(n.vaultProvider,n.quotedCommissionBps),s=b.encodeFunctionData({abi:p.BTCVaultRegistryABI,functionName:"submitPeginRequestBatch",args:[o,n.vaultProvider,y,n.expectedFingerprint,d]});return{ethTxHash:await this.sendAndWait(s,m*BigInt(n.requests.length),!0,o),vaults:h}}assertQuotedCommissionPresentWhenRequired(e){if(e===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(e){return this.assertEthAccount(e.depositorEthAddress)}assertEthAccount(e){const n=this.config.ethWallet.account;if(!n)throw new Error("Ethereum wallet account not found");if(!b.isAddressEqual(e,n.address))throw new Error(`Proof of possession was signed for ${e} but the Ethereum wallet is currently connected to ${n.address}. Reconnect the original account or sign a new proof of possession.`);return n.address}normalizeBtcPubkey(e){return`0x${x.assertOnChainBtcPubkey(E(e.depositorBtcPubkey,"Proof of possession BTC pubkey"),"Proof of possession BTC pubkey")}`}normalizeRequest(e,n,o){O(e.hashlock,"hashlock"),O(e.depositorWotsPkHash,"depositorWotsPkHash"),Dt(e.htlcVout);const i=E(e.unsignedPrePeginTx,"unsignedPrePeginTx"),a=E(e.depositorSignedPeginTx,"depositorSignedPeginTx"),c=et(a);return{unsignedPrePeginTx:i,depositorSignedPeginTx:a,payoutScript:Rt(e.depositorPayoutScriptPubKey,o,e.depositorBtcPubkeyRaw),peginTxHash:c,vaultId:E(nt(c,n),"vaultId")}}async assertVaultDoesNotExist(e,n){if((await this.config.publicClient.readContract({address:this.config.btcVaultRegistry,abi:p.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[e]})).depositor!==b.zeroAddress)throw new Error(`Vault already exists (ID: ${e}, peginTxHash: ${n}). 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(e){try{return await this.config.publicClient.readContract({address:this.config.btcVaultRegistry,abi:p.BTCVaultRegistryABI,functionName:"getPegInFee",args:[e]})}catch(n){throw new Error("Failed to query pegin fee from the contract. Please check your network connection and contract address.",{cause:n})}}async resolveMaxAcceptableCommissionBps(e,n){let o;try{o=await new at(this.config.publicClient,this.config.btcVaultRegistry).getVaultProviderCommission(e)}catch(i){throw new Error("Failed to query vault provider commission from the contract. Please check your network connection and contract address.",{cause:i})}if(n!==void 0){if(o>n+V)throw new Error(`Vault provider commission changed since quote: quoted ${n} bps, chain currently reports ${o} bps (allowed drift ${V} bps). Please refresh and try again.`);return _(n)}return _(o)}async sendAndWait(e,n,o,i){let a=this.assertEthAccount(i),c;try{c=await this.config.publicClient.estimateGas({to:this.config.btcVaultRegistry,data:e,value:n,account:a})}catch(g){I.handleContractError(g)}a=this.assertEthAccount(i);let h;try{h=await this.config.ethWallet.sendTransaction({to:this.config.btcVaultRegistry,data:e,value:n,gas:c,account:a,chain:this.config.ethChain})}catch(g){I.handleContractError(g)}const d=await ft.waitForTransactionReceiptSmartAware({publicClient:this.config.publicClient,walletAddress:i,hash:h,timeout:this.config.receiptTimeoutMs??Lt});return d.status==="reverted"&&I.handleContractError(new Error(`${o?"Batch transaction":"Transaction"} reverted. Hash: ${d.transactionHash}. Check a block explorer for details.`)),d.transactionHash}}exports.COMMISSION_BPS_HEADROOM=V;exports.MAX_ACCEPTABLE_COMMISSION_BPS_CAP=z;exports.RegistrationLogsUnavailableError=H;exports.ViemPeginRegistrationClient=Xt;exports.ViemVaultRegistryReader=at;exports.assertValidOffchainParamsVersion=ot;exports.calculateBtcTxHash=et;exports.capMaxAcceptableCommissionBps=_;exports.derivePeginVaultId=nt;exports.isRegistrationLogsUnavailableError=Mt;exports.ripemd160=Z;exports.validateOffchainParams=it;exports.validatePegInConfiguration=Ht;exports.validateTBVProtocolParams=st;
|
|
2
|
-
//# sourceMappingURL=pegin-registration-client-CZgcU2_0.cjs.map
|