@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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types-C1tpDycc.cjs","sources":["../src/tbv/core/clients/eth/contract-address-resolver.ts","../src/tbv/core/clients/eth/operation-key-reader.ts","../src/tbv/core/clients/eth/protocol-params-reader.ts","../src/tbv/core/clients/eth/signer-set-reader.ts","../src/tbv/core/clients/eth/types.ts"],"sourcesContent":["/**\n * Contract Address Resolver\n *\n * Resolves ProtocolParams and ApplicationRegistry contract addresses\n * from the BTCVaultRegistry contract. These addresses are needed to\n * construct the SDK's contract readers.\n *\n * @module clients/eth/contract-address-resolver\n */\n\nimport type { Address, PublicClient } from \"viem\";\n\nimport { BTCVaultRegistryABI } from \"../../contracts/abis/BTCVaultRegistry.abi\";\n\nexport interface ProtocolAddresses {\n /** Address of the ProtocolParams contract */\n protocolParams: Address;\n /** Address of the ApplicationRegistry contract */\n applicationRegistry: Address;\n}\n\n/**\n * Resolve ProtocolParams and ApplicationRegistry addresses from BTCVaultRegistry.\n *\n * Uses a single multicall for atomicity and efficiency.\n *\n * @param publicClient - viem PublicClient instance\n * @param btcVaultRegistryAddress - Address of the BTCVaultRegistry contract\n * @returns Resolved contract addresses\n */\nexport async function resolveProtocolAddresses(\n publicClient: PublicClient,\n btcVaultRegistryAddress: Address,\n): Promise<ProtocolAddresses> {\n const [protocolParams, applicationRegistry] = await publicClient.multicall({\n contracts: [\n {\n address: btcVaultRegistryAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"protocolParams\",\n },\n {\n address: btcVaultRegistryAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"applicationRegistry\",\n },\n ],\n allowFailure: false,\n });\n\n return {\n protocolParams: protocolParams as Address,\n applicationRegistry: applicationRegistry as Address,\n };\n}\n","/**\n * Concrete RFC-006 operation-key reader spanning all three registries.\n *\n * This is an optional utility — callers can use their own implementation of\n * the {@link OperationKeyReader} interface.\n */\n\nimport type { Abi, Address, Hex, PublicClient } from \"viem\";\n\nimport { ApplicationRegistryABI } from \"../../contracts/abis/ApplicationRegistry.abi\";\nimport { BTCVaultRegistryABI } from \"../../contracts/abis/BTCVaultRegistry.abi\";\nimport { ProtocolParamsABI } from \"../../contracts/abis/ProtocolParams.abi\";\nimport type {\n KeyEpochs,\n OperationKeyQuery,\n OperationKeyReader,\n RawOperationKeys,\n RawPayoutScripts,\n} from \"./types\";\n\n/** Addresses of the three registries an operation-key resolution spans. */\nexport interface OperationKeyContracts {\n btcVaultRegistry: Address;\n applicationRegistry: Address;\n protocolParams: Address;\n}\n\n/** One `multicall` entry. Loosely typed because the three ABIs differ. */\ntype Call = {\n address: Address;\n abi: Abi;\n functionName: string;\n args: readonly unknown[];\n};\n\n/**\n * Reject a multicall result that is not one-per-call.\n *\n * Every method here relies on positional alignment between calls and results,\n * so a short array does not fail — it silently hands back `undefined` for the\n * tail entries. Downstream that surfaces as a complaint about whichever\n * operator happens to occupy the missing slot, blaming a participant that is\n * perfectly fine for a read that came back incomplete. Assert the length where\n * the array arrives so the error names the real fault.\n */\nfunction assertMulticallLength(\n actual: number,\n expected: number,\n label: string,\n): void {\n if (actual !== expected) {\n throw new Error(\n `${label}: multicall returned ${actual} results for ${expected} calls, ` +\n `so the results are not roster-aligned; refusing to use them`,\n );\n }\n}\n\n/**\n * Split a flat multicall result into VP / keepers / challengers.\n *\n * Every method below builds its calls in the same order — vault provider\n * first, then keepers in roster order, then challengers in roster order — so\n * the results stay index-aligned with `query.vaultKeepers` /\n * `query.universalChallengers`. That alignment is what lets the resolver pair\n * a resolved key back to its admin address; the sorted key arrays it exposes\n * are derived from those pairs, never the other way round.\n */\nfunction partition<T>(\n results: readonly T[],\n keeperCount: number,\n): { vaultProvider: T; vaultKeepers: T[]; universalChallengers: T[] } {\n return {\n vaultProvider: results[0],\n vaultKeepers: results.slice(1, 1 + keeperCount),\n universalChallengers: results.slice(1 + keeperCount),\n };\n}\n\n/**\n * Reads RFC-006 operation keys and payout scripts.\n *\n * Usage:\n * ```ts\n * const reader = new ViemOperationKeyReader(publicClient, contracts);\n * const keys = await reader.getCurrentOperationKeys(query);\n * ```\n */\nexport class ViemOperationKeyReader implements OperationKeyReader {\n constructor(\n private publicClient: PublicClient,\n private contracts: OperationKeyContracts,\n ) {}\n\n /**\n * One multicall, `allowFailure: false`, so every key in the set is read at\n * the same block. A rotation landing between two separate `eth_call`s would\n * otherwise produce a mixed-epoch key set and a lock no counterparty agrees\n * with.\n */\n private async readAll<T>(\n calls: Call[],\n keeperCount: number,\n challengerCount: number,\n label: string,\n blockNumber?: bigint,\n ) {\n const results = (await this.publicClient.multicall({\n contracts: calls,\n allowFailure: false,\n blockNumber,\n })) as readonly T[];\n\n assertMulticallLength(\n results.length,\n 1 + keeperCount + challengerCount,\n label,\n );\n\n return partition(results, keeperCount);\n }\n\n async getCurrentOperationKeys(\n query: OperationKeyQuery,\n blockNumber?: bigint,\n ): Promise<RawOperationKeys> {\n const calls: Call[] = [\n {\n address: this.contracts.btcVaultRegistry,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getCurrentOperationBtcKey\",\n args: [query.vaultProviderEthAddress],\n },\n ...query.vaultKeepers.map((keeper) => ({\n address: this.contracts.applicationRegistry,\n abi: ApplicationRegistryABI as Abi,\n functionName: \"getCurrentOperationBtcKey\",\n args: [query.applicationEntryPoint, keeper.ethAddress],\n })),\n ...query.universalChallengers.map((challenger) => ({\n address: this.contracts.protocolParams,\n abi: ProtocolParamsABI as Abi,\n functionName: \"getCurrentOperationBtcKey\",\n args: [challenger.ethAddress],\n })),\n ];\n\n return this.readAll<Hex>(\n calls,\n query.vaultKeepers.length,\n query.universalChallengers.length,\n \"getCurrentOperationKeys\",\n blockNumber,\n );\n }\n\n async getOperationKeysAtEpochs(\n query: OperationKeyQuery,\n epochs: KeyEpochs,\n ): Promise<RawOperationKeys> {\n const calls: Call[] = [\n // The VP takes the plain `AtEpoch` variant: it has no membership\n // version, so its genesis (the registration key at version 0) is\n // unambiguous and the contract resolves it internally.\n {\n address: this.contracts.btcVaultRegistry,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getOperationBtcKeyAtEpoch\",\n args: [query.vaultProviderEthAddress, epochs.vpKeyEpoch],\n },\n // Keepers and challengers take `...OrGenesis` with their roster key\n // passed explicitly, because the correct genesis for them is their key\n // in *this vault's frozen membership version*. An operator dropped from\n // the current roster, or listed under a different key in an older\n // version, would otherwise resolve against the wrong genesis.\n ...query.vaultKeepers.map((keeper) => ({\n address: this.contracts.applicationRegistry,\n abi: ApplicationRegistryABI as Abi,\n functionName: \"getOperationBtcKeyAtEpochOrGenesis\",\n args: [\n query.applicationEntryPoint,\n keeper.ethAddress,\n epochs.appKeeperKeyEpoch,\n keeper.btcPubKey,\n ],\n })),\n ...query.universalChallengers.map((challenger) => ({\n address: this.contracts.protocolParams,\n abi: ProtocolParamsABI as Abi,\n functionName: \"getOperationBtcKeyAtEpochOrGenesis\",\n args: [challenger.ethAddress, epochs.ucKeyEpoch, challenger.btcPubKey],\n })),\n ];\n\n return this.readAll<Hex>(\n calls,\n query.vaultKeepers.length,\n query.universalChallengers.length,\n \"getOperationKeysAtEpochs\",\n );\n }\n\n async getPayoutScriptsAtEpochs(\n query: OperationKeyQuery,\n epochs: KeyEpochs,\n ): Promise<RawPayoutScripts> {\n // Universal challengers are never claimers, so they have no payout script\n // and no call here.\n const results = (await this.publicClient.multicall({\n contracts: [\n {\n address: this.contracts.btcVaultRegistry,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getPayoutScriptAtEpoch\",\n args: [query.vaultProviderEthAddress, epochs.vpKeyEpoch],\n },\n ...query.vaultKeepers.map((keeper) => ({\n address: this.contracts.applicationRegistry,\n abi: ApplicationRegistryABI as Abi,\n functionName: \"getPayoutScriptAtEpoch\",\n args: [\n query.applicationEntryPoint,\n keeper.ethAddress,\n epochs.appKeeperKeyEpoch,\n ],\n })),\n ],\n allowFailure: false,\n })) as readonly Hex[];\n\n // Expected length is `1 + keepers`, with no challenger term — see the\n // comment above on why universal challengers have no call here.\n assertMulticallLength(\n results.length,\n 1 + query.vaultKeepers.length,\n \"getPayoutScriptsAtEpochs\",\n );\n\n return {\n vaultProvider: results[0],\n vaultKeepers: [...results.slice(1)],\n };\n }\n}\n","/**\n * Concrete ProtocolParams reader using viem's readContract and multicall.\n *\n * This is an optional utility — callers can use their own implementation\n * of the ProtocolParamsReader interface.\n */\n\nimport type { Abi, Address, Hex, PublicClient } from \"viem\";\n\nimport { ProtocolParamsABI } from \"../../contracts/abis/ProtocolParams.abi\";\nimport {\n assertValidOffchainParamsVersion,\n validateOffchainParams,\n validatePegInConfiguration,\n validateTBVProtocolParams,\n} from \"./protocol-params-validation\";\nimport type {\n AllOffchainParamsData,\n OnSkippedOffchainParamsVersion,\n PegInConfiguration,\n ProtocolParamsReader,\n TBVProtocolParams,\n VersionedOffchainParams,\n} from \"./types\";\n\n/**\n * Maximum value for a Solidity uint16.\n * PeginLogic.sol casts timelockAssert to uint16, so values above this are invalid.\n */\nconst UINT16_MAX = 65535;\n\n\n/**\n * Raw shape viem returns for VersionedOffchainParams struct.\n * viem resolves ABI struct outputs to named objects (not tuples).\n */\ninterface RawOffchainParams {\n timelockAssert: bigint;\n timelockChallengeAssert: bigint;\n securityCouncilKeys: readonly Hex[];\n councilQuorum: number;\n feeRate: bigint;\n babeTotalInstances: number;\n babeInstancesToFinalize: number;\n minVpCommissionBps: number;\n tRefund: number;\n tStale: number;\n minPeginFeeRate: bigint;\n proverCircuitVersion: number;\n minPrepeginDepth: number;\n}\n\n/** Raw shape viem returns for TBVProtocolParams struct. */\ninterface RawTBVParams {\n minimumPegInAmount: bigint;\n maxPegInAmount: bigint;\n pegInAckTimeout: bigint;\n pegInActivationTimeout: bigint;\n maxHtlcOutputCount: number;\n expiredPegInGraceBlocks: bigint;\n}\n\n/** Map viem struct result to VersionedOffchainParams. */\nfunction mapOffchainParams(result: RawOffchainParams): VersionedOffchainParams {\n return {\n timelockAssert: result.timelockAssert,\n timelockChallengeAssert: result.timelockChallengeAssert,\n securityCouncilKeys: [...result.securityCouncilKeys],\n councilQuorum: result.councilQuorum,\n feeRate: result.feeRate,\n babeTotalInstances: result.babeTotalInstances,\n babeInstancesToFinalize: result.babeInstancesToFinalize,\n minVpCommissionBps: result.minVpCommissionBps,\n tRefund: result.tRefund,\n tStale: result.tStale,\n minPeginFeeRate: result.minPeginFeeRate,\n proverCircuitVersion: result.proverCircuitVersion,\n minPrepeginDepth: result.minPrepeginDepth,\n };\n}\n\n/** Map viem struct result to TBVProtocolParams. */\nfunction mapTBVParams(result: RawTBVParams): TBVProtocolParams {\n return {\n minimumPegInAmount: result.minimumPegInAmount,\n maxPegInAmount: result.maxPegInAmount,\n pegInAckTimeout: result.pegInAckTimeout,\n pegInActivationTimeout: result.pegInActivationTimeout,\n maxHtlcOutputCount: result.maxHtlcOutputCount,\n expiredPegInGraceBlocks: result.expiredPegInGraceBlocks,\n };\n}\n\n/**\n * Derive timelockPegin from timelockAssert.\n *\n * Matches PeginLogic.sol: `uint16(timelockAssert)`.\n * The contract validates `timelockAssert <= type(uint16).max` on write,\n * but we enforce the same bound here to reject invalid values early\n * rather than silently truncating.\n *\n * @throws if timelockAssert exceeds uint16 max (65535)\n */\nfunction deriveTimelockPegin(timelockAssert: bigint): number {\n if (timelockAssert > BigInt(UINT16_MAX)) {\n throw new Error(\n `timelockAssert value ${timelockAssert} exceeds uint16 max (${UINT16_MAX})`,\n );\n }\n return Number(timelockAssert);\n}\n\n/**\n * Concrete protocol params reader using viem.\n *\n * Every read method runs the matching validator from\n * `protocol-params-validation` before returning, so callers don't have to\n * remember to validate.\n *\n * Usage:\n * ```ts\n * const reader = new ViemProtocolParamsReader(publicClient, protocolParamsAddress);\n * const config = await reader.getPegInConfiguration();\n * ```\n */\nexport class ViemProtocolParamsReader implements ProtocolParamsReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n async getTBVProtocolParams(): Promise<TBVProtocolParams> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getTBVProtocolParams\",\n })) as RawTBVParams;\n\n const params = mapTBVParams(result);\n validateTBVProtocolParams(params);\n return params;\n }\n\n async getLatestOffchainParams(): Promise<VersionedOffchainParams> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getLatestOffchainParams\",\n })) as RawOffchainParams;\n\n const params = mapOffchainParams(result);\n validateOffchainParams(params);\n return params;\n }\n\n async getOffchainParamsByVersion(\n version: number,\n ): Promise<VersionedOffchainParams> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getOffchainParamsByVersion\",\n args: [version],\n })) as RawOffchainParams;\n\n const params = mapOffchainParams(result);\n validateOffchainParams(params);\n return params;\n }\n\n async getLatestOffchainParamsVersion(): Promise<number> {\n const raw = await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"latestOffchainParamsVersion\",\n });\n const version = Number(raw);\n assertValidOffchainParamsVersion(version);\n return version;\n }\n\n async getTimelockPeginByVersion(version: number): Promise<number> {\n const params = await this.getOffchainParamsByVersion(version);\n return deriveTimelockPegin(params.timelockAssert);\n }\n\n /**\n * Returned as `bigint` with no `Number` narrowing: the registry compares it\n * against `block.number`, so callers must do the same arithmetic the\n * contract does. `0` is the documented \"disabled\" case and is returned as\n * `0n`. A missing getter or a non-bigint payload throws — never coerced to\n * `0`, which would fail open and skip the observation window.\n *\n * @throws If the deployment does not expose `peginActivationDelay()`, or\n * the decoded payload is not a `bigint`.\n */\n async getPeginActivationDelay(): Promise<bigint> {\n const raw: unknown = await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"peginActivationDelay\",\n });\n if (typeof raw !== \"bigint\") {\n throw new Error(\n `Invalid peginActivationDelay from contract: must be a bigint, got ${typeof raw}`,\n );\n }\n return raw;\n }\n\n /**\n * Read TBV protocol params, latest offchain params, and the latest version\n * label atomically via multicall. The version is paired with the params so\n * that a governance update between separate reads cannot let JS build BTC\n * scripts with version N params while the contract registers the vault\n * under version N+1.\n *\n * That guarantee holds only within this multicall. A caller that also reads\n * participant keys — every fresh peg-in build does — must pass the same\n * `blockNumber` here and to those reads, or the two describe different\n * blocks and the pairing above buys nothing across the seam.\n */\n async getPegInConfiguration(\n blockNumber?: bigint,\n ): Promise<PegInConfiguration> {\n const results = await this.publicClient.multicall({\n blockNumber,\n contracts: [\n {\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getTBVProtocolParams\",\n },\n {\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getLatestOffchainParams\",\n },\n {\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"latestOffchainParamsVersion\",\n },\n {\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"activeVaultCoreVersion\",\n },\n ],\n allowFailure: false,\n });\n\n const tbvParams = mapTBVParams(results[0] as RawTBVParams);\n const offchainParams = mapOffchainParams(results[1] as RawOffchainParams);\n const offchainParamsVersion = Number(results[2]);\n const activeVaultCoreVersion = Number(results[3]);\n\n const config: PegInConfiguration = {\n minimumPegInAmount: tbvParams.minimumPegInAmount,\n maxPegInAmount: tbvParams.maxPegInAmount,\n pegInAckTimeout: tbvParams.pegInAckTimeout,\n pegInActivationTimeout: tbvParams.pegInActivationTimeout,\n maxHtlcOutputCount: tbvParams.maxHtlcOutputCount,\n expiredPegInGraceBlocks: tbvParams.expiredPegInGraceBlocks,\n timelockPegin: deriveTimelockPegin(offchainParams.timelockAssert),\n timelockRefund: offchainParams.tRefund,\n minVpCommissionBps: offchainParams.minVpCommissionBps,\n offchainParams,\n offchainParamsVersion,\n activeVaultCoreVersion,\n };\n\n validatePegInConfiguration(config);\n return config;\n }\n\n /**\n * Fetch every historical offchain params version in a single multicall.\n * Iterates 1..latestVersion and calls `getOffchainParamsByVersion` for each.\n * Versions whose payload fails validation are skipped (not included in the\n * returned map) so a single bad historical version doesn't block the\n * lookup of the rest.\n *\n * @param onSkippedVersion - optional observer invoked once per skipped\n * version. Use to log/telemeter without coupling the SDK to a logger.\n */\n async fetchAllOffchainParams(\n onSkippedVersion?: OnSkippedOffchainParamsVersion,\n ): Promise<AllOffchainParamsData> {\n const latestVersion = await this.getLatestOffchainParamsVersion();\n if (latestVersion === 0) {\n return { byVersion: new Map(), latestVersion: 0 };\n }\n\n const versions = Array.from({ length: latestVersion }, (_, i) => i + 1);\n const contracts = versions.map((v) => ({\n address: this.contractAddress,\n abi: ProtocolParamsABI as Abi,\n functionName: \"getOffchainParamsByVersion\" as const,\n args: [v] as const,\n }));\n\n const results = await this.publicClient.multicall({\n contracts,\n allowFailure: false,\n });\n\n const byVersion = new Map<number, VersionedOffchainParams>();\n for (let i = 0; i < versions.length; i++) {\n const params = mapOffchainParams(results[i] as RawOffchainParams);\n try {\n validateOffchainParams(params);\n byVersion.set(versions[i], params);\n } catch (error) {\n // A malformed historical version mustn't block lookup of the rest.\n // Surface the skip to the caller's observer if one was supplied.\n onSkippedVersion?.(\n versions[i],\n error instanceof Error ? error : new Error(String(error)),\n );\n }\n }\n\n return { byVersion, latestVersion };\n }\n}\n","/**\n * Concrete signer-set readers for vault keepers and universal challengers.\n *\n * These are optional utilities — callers can use their own implementations\n * of the VaultKeeperReader and UniversalChallengerReader interfaces.\n */\n\nimport type { Address, Hex, PublicClient } from \"viem\";\n\nimport { ApplicationRegistryABI } from \"../../contracts/abis/ApplicationRegistry.abi\";\nimport { ProtocolParamsABI } from \"../../contracts/abis/ProtocolParams.abi\";\nimport type {\n AddressBTCKeyPair,\n UniversalChallengerReader,\n VaultKeeperReader,\n} from \"./types\";\n\n/** Map viem tuple array to AddressBTCKeyPair[]. */\nfunction mapKeyPairs(\n result: readonly { ethAddress: Address; btcPubKey: Hex }[],\n): AddressBTCKeyPair[] {\n return result.map((pair) => ({\n ethAddress: pair.ethAddress,\n btcPubKey: pair.btcPubKey,\n }));\n}\n\n/**\n * Both key-epoch getters return `uint64` and feed the peg-in config\n * fingerprint, where the contract encodes them as `uint64`. A `Number`\n * narrowing would silently truncate above 2^53 and produce a fingerprint the\n * registry cannot reproduce, so the payload is asserted to be a `bigint` and\n * carried as one — never coerced, never defaulted.\n */\nfunction assertKeyEpoch(raw: unknown, label: string): bigint {\n if (typeof raw !== \"bigint\") {\n throw new Error(\n `Invalid ${label} from contract: must be a bigint, got ${typeof raw}`,\n );\n }\n return raw;\n}\n\n/**\n * Reads vault keepers from the ApplicationRegistry contract.\n *\n * Usage:\n * ```ts\n * const reader = new ViemVaultKeeperReader(publicClient, applicationRegistryAddress);\n * const keepers = await reader.getCurrentVaultKeepers(appEntryPoint);\n * ```\n */\nexport class ViemVaultKeeperReader implements VaultKeeperReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n async getVaultKeepersByVersion(\n appEntryPoint: Address,\n version: number,\n blockNumber?: bigint,\n ): Promise<AddressBTCKeyPair[]> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ApplicationRegistryABI,\n functionName: \"getVaultKeepersByVersion\",\n args: [appEntryPoint, version],\n blockNumber,\n })) as readonly { ethAddress: Address; btcPubKey: Hex }[];\n\n return mapKeyPairs(result);\n }\n\n async getCurrentVaultKeepers(\n appEntryPoint: Address,\n ): Promise<AddressBTCKeyPair[]> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ApplicationRegistryABI,\n functionName: \"getCurrentVaultKeepers\",\n args: [appEntryPoint],\n })) as readonly { ethAddress: Address; btcPubKey: Hex }[];\n\n return mapKeyPairs(result);\n }\n\n async getCurrentVaultKeepersVersion(\n appEntryPoint: Address,\n blockNumber?: bigint,\n ): Promise<number> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ApplicationRegistryABI,\n functionName: \"getCurrentVaultKeepersVersion\",\n args: [appEntryPoint],\n blockNumber,\n })) as number;\n\n return result;\n }\n\n async getCurrentAppKeeperKeyEpoch(\n appEntryPoint: Address,\n blockNumber?: bigint,\n ): Promise<bigint> {\n const raw: unknown = await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ApplicationRegistryABI,\n functionName: \"appKeeperKeyEpochCurrent\",\n args: [appEntryPoint],\n blockNumber,\n });\n\n return assertKeyEpoch(raw, \"appKeeperKeyEpochCurrent\");\n }\n}\n\n/**\n * Reads universal challengers from the ProtocolParams contract.\n *\n * Usage:\n * ```ts\n * const reader = new ViemUniversalChallengerReader(publicClient, protocolParamsAddress);\n * const challengers = await reader.getCurrentUniversalChallengers();\n * ```\n */\nexport class ViemUniversalChallengerReader implements UniversalChallengerReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n async getUniversalChallengersByVersion(\n version: number,\n blockNumber?: bigint,\n ): Promise<AddressBTCKeyPair[]> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getUniversalChallengersByVersion\",\n args: [version],\n blockNumber,\n })) as readonly { ethAddress: Address; btcPubKey: Hex }[];\n\n return mapKeyPairs(result);\n }\n\n async getCurrentUniversalChallengers(): Promise<AddressBTCKeyPair[]> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getCurrentUniversalChallengers\",\n })) as readonly { ethAddress: Address; btcPubKey: Hex }[];\n\n return mapKeyPairs(result);\n }\n\n async getLatestUniversalChallengersVersion(\n blockNumber?: bigint,\n ): Promise<number> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"latestUniversalChallengersVersion\",\n blockNumber,\n })) as number;\n\n return result;\n }\n\n async getCurrentUcKeyEpoch(blockNumber?: bigint): Promise<bigint> {\n const raw: unknown = await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"ucKeyEpochCurrent\",\n blockNumber,\n });\n\n return assertKeyEpoch(raw, \"ucKeyEpochCurrent\");\n }\n}\n","/**\n * Types and interfaces for ETH contract readers.\n *\n * These are optional utilities — callers can use them or build their own.\n * Core service functions never import from this module.\n */\n\nimport type { Address, Hex } from \"viem\";\n\n// ============================================================================\n// Vault Registry Types\n// ============================================================================\n\ndeclare const onChainBtcPubkeyBrand: unique symbol;\n\n/**\n * 64-char lowercase hex (no `0x`) x-only BTC pubkey sourced from an on-chain\n * registry. Minted only by `assertOnChainBtcPubkey`, which is the shared\n * validator behind both producers:\n * {@link VaultRegistryReader.getVaultProviderGenesisBtcPubKey} (the fixed\n * registration key) and {@link OperationKeyReader} (RFC-006 operation keys,\n * resolved current or at a vault's frozen epoch).\n *\n * @stability frozen\n */\nexport type OnChainBtcPubkey = string & {\n readonly [onChainBtcPubkeyBrand]: true;\n};\n\n/**\n * Mirrors `IBTCVaultRegistry.BTCVaultStatus` in BTCVaultRegistry.sol exactly.\n * Use this when consuming `status` from `getVaultBasicInfo` /\n * `getBtcVaultBasicInfo`.\n *\n * Do NOT confuse with the app-side `ContractStatus` enum\n * (`services/deposit/peginState.ts`) — that one is for the indexer and\n * extends this with values 5-7, reassigning 4 to LIQUIDATED. Reading an\n * on-chain status through `ContractStatus[n]` for labels will mislabel\n * Expired(4) as LIQUIDATED.\n */\nexport enum OnChainBtcVaultStatus {\n PENDING = 0,\n VERIFIED = 1,\n ACTIVE = 2,\n REDEEMED = 3,\n EXPIRED = 4,\n}\n\n/** Basic vault info from BTCVaultRegistry.getBtcVaultBasicInfo */\nexport interface VaultBasicInfo {\n depositor: Address;\n depositorBtcPubKey: Hex;\n amount: bigint;\n vaultProvider: Address;\n status: number;\n applicationEntryPoint: Address;\n createdAt: bigint;\n}\n\n/** Protocol info from BTCVaultRegistry.getBtcVaultProtocolInfo */\nexport interface VaultProtocolInfo {\n depositorSignedPeginTx: Hex;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n offchainParamsVersion: number;\n /**\n * ETH block number stamped at the Pending→Verified transition.\n * Compared against `block.number` (inclusive:\n * `block.number >= verifiedAt + peginActivationDelay`), never a unix timestamp.\n */\n verifiedAt: bigint;\n depositorWotsPkHash: Hex;\n hashlock: Hex;\n htlcVout: number;\n depositorPopSignature: Hex;\n prePeginTxHash: Hex;\n vaultProviderCommissionBps: number;\n /** Vault core version (uint16) stamped at registration. VP-side gating only — see #1690. */\n vaultCoreVersion: number;\n}\n\n/** Combined vault data (basic + protocol) */\nexport interface VaultData {\n basic: VaultBasicInfo;\n protocol: VaultProtocolInfo;\n}\n\n/**\n * RFC-006 operation-key epochs a vault froze at `submitPeginRequest`.\n *\n * Each registry keeps a monotonic epoch counter that every key/payout setter\n * pre-increments. A vault stamps the counters live at its creation, and every\n * participant resolves \"which key did this vault bond?\" by asking the registry\n * for the key whose appended version is the latest stamped `<=` this epoch. A\n * rotation after the vault was created therefore never moves its keys.\n *\n * `uint64` — kept as `bigint` end-to-end and passed straight back to the\n * `...AtEpoch` getters, never narrowed through `Number`.\n *\n * Only ever read through {@link VaultRegistryReader.getVaultKeyEpochs}, which\n * uses the extended ABI. See `BTCVaultRegistryKeyEpochs.abi.ts` for why that\n * read is quarantined to its own ABI.\n */\nexport interface KeyEpochs {\n vpKeyEpoch: bigint;\n appKeeperKeyEpoch: bigint;\n ucKeyEpoch: bigint;\n}\n\n/** Interface for reading vault data from the BTCVaultRegistry contract. */\nexport interface VaultRegistryReader {\n getVaultBasicInfo(vaultId: Hex): Promise<VaultBasicInfo>;\n getVaultProtocolInfo(vaultId: Hex): Promise<VaultProtocolInfo>;\n getProtocolInfoBatch(vaultIds: readonly Hex[]): Promise<VaultProtocolInfo[]>;\n getVaultData(vaultId: Hex): Promise<VaultData>;\n /**\n * Read a vault provider's *genesis* (registration) BTC key — the key bonded\n * at version 0, which never moves when the operator rotates.\n *\n * Used only as the genesis fallback for epoch-based resolution and as a\n * candidate when cross-checking an indexer hint. Never the key to build a\n * Bitcoin lock with; that comes from `OperationKeyReader`.\n *\n * Resolves via `getOperationBtcKeyAtEpoch` at epoch 0, so it requires an\n * RFC-006 registry — as does every caller.\n */\n getVaultProviderGenesisBtcPubKey(\n vpAddress: Address,\n blockNumber?: bigint,\n ): Promise<OnChainBtcPubkey>;\n /** Read the protocol pegin fee (in wei) for a given vault provider. */\n getPegInFee(vaultProvider: Address): Promise<bigint>;\n /**\n * Read a vault provider's current commission in basis points.\n *\n * Validates the contract-enforced `[0, 9999]` range — an out-of-range\n * value signals a wrong contract address or ABI drift, not a real rate.\n */\n getVaultProviderCommission(vaultProvider: Address): Promise<number>;\n /**\n * Read a vault's frozen RFC-006 key epochs.\n *\n * Uses the extended `getBtcVaultProtocolInfo` ABI. Against a registry whose\n * `BTCVaultProtocolInfo` struct is not extended this returns silent garbage\n * for a populated vault rather than throwing, so it must only be called\n * against an RFC-006 registry — a deployment invariant, not something this\n * call can detect. A registry missing the operation-key getters altogether is\n * the safer case: key resolution reverts downstream and these epochs are never\n * used. See `BTCVaultRegistryKeyEpochs.abi.ts`.\n */\n getVaultKeyEpochs(vaultId: Hex): Promise<KeyEpochs>;\n /** {@link getVaultKeyEpochs} for many vaults in one multicall. */\n getVaultKeyEpochsBatch(vaultIds: readonly Hex[]): Promise<KeyEpochs[]>;\n /**\n * Read a vault provider's *current* RFC-006 operation BTC key — the key its\n * server signs auth tokens with. Falls back to the registration key when the\n * provider has never rotated.\n */\n getCurrentVaultProviderOperationBtcKey(\n vpAddress: Address,\n ): Promise<OnChainBtcPubkey>;\n /**\n * Read the depositor's commission ceiling (`maxAcceptableCommissionBps`)\n * for vaults registered in the same block `createdAt`, from their\n * `PegInSubmittedV2` logs, in `vaultIds` order. The contract discards the\n * ceiling after bound-checking it, so the log is its only on-chain source.\n *\n * @throws {RegistrationLogsUnavailableError} (transient, retry) when the\n * node answers with no registration logs for the block at all.\n * @throws when a vault has only its `PegInSubmitted` log (a registration\n * that predates the V2 event), none, or more than one V2 log.\n */\n getMaxAcceptableCommissionBpsBatch(\n vaultIds: readonly Hex[],\n createdAt: bigint,\n ): Promise<number[]>;\n /**\n * Read the application entry point a vault provider is registered for.\n *\n * The peg-in submit path resolves this internally and uses it to pick the\n * keeper roster, the roster version and the keeper key epoch a deposit is\n * bonded to. Pass `blockNumber` when the result will shape a Bitcoin lock,\n * so it describes the same block as the roster reads that follow it.\n */\n getVaultProviderApplication(\n vpAddress: Address,\n blockNumber?: bigint,\n ): Promise<Address>;\n}\n\n// ============================================================================\n// Protocol Params Types (from IProtocolParams.sol)\n// ============================================================================\n\n/**\n * TBV protocol parameters from the ProtocolParams contract.\n * Matches Solidity struct `IProtocolParams.TBVProtocolParams` exactly.\n *\n * All uint64 amounts use bigint (satoshi values can exceed 2^53).\n * uint8 uses number (bounded, max 255).\n */\nexport interface TBVProtocolParams {\n minimumPegInAmount: bigint;\n maxPegInAmount: bigint;\n pegInAckTimeout: bigint;\n pegInActivationTimeout: bigint;\n maxHtlcOutputCount: number;\n /**\n * Number of blocks added to the activation deadline as a grace window\n * during which a depositor may still reclaim an expired pegin via the\n * HTLC preimage. Source: `IProtocolParams.TBVProtocolParams.expiredPegInGraceBlocks`.\n */\n expiredPegInGraceBlocks: bigint;\n}\n\n/**\n * Versioned offchain parameters from the ProtocolParams contract.\n * Matches Solidity struct `IProtocolParams.VersionedOffchainParams` exactly.\n *\n * bigint for: uint256 timelocks, uint64 fee rates/amounts.\n * number for: uint8/uint16/uint32 fields (bounded, safe for JS arithmetic).\n */\nexport interface VersionedOffchainParams {\n timelockAssert: bigint;\n timelockChallengeAssert: bigint;\n securityCouncilKeys: Hex[];\n councilQuorum: number;\n feeRate: bigint;\n babeTotalInstances: number;\n babeInstancesToFinalize: number;\n minVpCommissionBps: number;\n tRefund: number;\n tStale: number;\n minPeginFeeRate: bigint;\n proverCircuitVersion: number;\n minPrepeginDepth: number;\n}\n\n/**\n * Combined peg-in configuration read atomically via multicall.\n * Prevents TOCTOU inconsistency if governance updates params between reads.\n */\nexport interface PegInConfiguration {\n minimumPegInAmount: bigint;\n maxPegInAmount: bigint;\n pegInAckTimeout: bigint;\n pegInActivationTimeout: bigint;\n maxHtlcOutputCount: number;\n expiredPegInGraceBlocks: bigint;\n timelockPegin: number;\n timelockRefund: number;\n minVpCommissionBps: number;\n offchainParams: VersionedOffchainParams;\n /**\n * Version label paired atomically with `offchainParams`.\n * Read in the same multicall as the params struct so that, if a parameter\n * update lands between separate reads, the script-construction code and\n * the version label stay consistent.\n */\n offchainParamsVersion: number;\n /**\n * Currently-active vault core (tx-graph) version\n * (`ProtocolParams.activeVaultCoreVersion()`, uint16 ≥ 1). Stamped onto\n * every new vault at peg-in submission; fresh deposits must build this\n * graph version. Read in the same multicall so a governance version bump\n * can't land between reading the params and reading the version.\n */\n activeVaultCoreVersion: number;\n}\n\n/**\n * All offchain params snapshots indexed by version, plus the latest version\n * number known when the snapshot was taken. Used by consumers that need to\n * resolve any historical version (e.g. signing for an existing vault locked\n * to an older version).\n */\nexport interface AllOffchainParamsData {\n byVersion: Map<number, VersionedOffchainParams>;\n latestVersion: number;\n}\n\n/**\n * Optional observer invoked by `fetchAllOffchainParams` when a historical\n * version fails validation. Called once per skipped version so callers can\n * log/telemeter without coupling the SDK to a specific logger.\n */\nexport type OnSkippedOffchainParamsVersion = (\n version: number,\n error: Error,\n) => void;\n\n/** Interface for reading protocol parameters from the ProtocolParams contract. */\nexport interface ProtocolParamsReader {\n getTBVProtocolParams(): Promise<TBVProtocolParams>;\n getOffchainParamsByVersion(version: number): Promise<VersionedOffchainParams>;\n getLatestOffchainParams(): Promise<VersionedOffchainParams>;\n getLatestOffchainParamsVersion(): Promise<number>;\n getTimelockPeginByVersion(version: number): Promise<number>;\n /**\n * Pass `blockNumber` when the result will shape a Bitcoin lock, so this\n * multicall and the participant-key reads describe the same block. Omit it\n * for display-only reads, where a slightly stale value is harmless.\n */\n getPegInConfiguration(blockNumber?: bigint): Promise<PegInConfiguration>;\n /**\n * Observation window enforced between a vault's final ACK and its\n * activation, in ETH blocks measured from `verifiedAt`. `0` disables it.\n *\n * Deliberately its own read rather than a field on\n * {@link PegInConfiguration}: the parameter is absent from deployments that\n * predate it, so folding it into the shared multicall would make every\n * protocol-param read fail wherever it is missing.\n *\n * @throws If the deployment does not expose `peginActivationDelay()`, or\n * the decoded payload is not a `bigint`.\n */\n getPeginActivationDelay(): Promise<bigint>;\n fetchAllOffchainParams(\n onSkippedVersion?: OnSkippedOffchainParamsVersion,\n ): Promise<AllOffchainParamsData>;\n}\n\n// ============================================================================\n// Signer-Set Types (from BTCVaultTypes.sol)\n// ============================================================================\n\n/**\n * Matches Solidity struct `BTCVaultTypes.AddressBTCKeyPair` exactly.\n * Used for vault keepers and universal challengers.\n */\nexport interface AddressBTCKeyPair {\n ethAddress: Address;\n btcPubKey: Hex;\n}\n\n/**\n * Interface for reading vault keepers from the ApplicationRegistry contract.\n *\n * The reads used to build a peg-in — here and on the sibling reader interfaces\n * — take an optional `blockNumber` that pins them to one block instead of\n * `latest`. Omitting it, the historical behaviour, is correct for every read\n * that resolves against a vault's already-frozen epochs, because those are\n * immutable once stamped. It is NOT correct for a fresh peg-in build: the\n * participant keys, roster versions and protocol params that shape the Bitcoin\n * lock must all describe the same block, or the lock commits to a mixture of\n * chain states that never existed at once. See\n * `services/deposit/validateOnChainParticipantKeys`.\n *\n * The `getCurrent*` roster reads are the exception and take no block. Nothing\n * on the build path uses them — it resolves rosters by version instead — so\n * they were left alone rather than given a pin no caller would pass.\n */\nexport interface VaultKeeperReader {\n getVaultKeepersByVersion(\n appEntryPoint: Address,\n version: number,\n blockNumber?: bigint,\n ): Promise<AddressBTCKeyPair[]>;\n getCurrentVaultKeepers(appEntryPoint: Address): Promise<AddressBTCKeyPair[]>;\n getCurrentVaultKeepersVersion(\n appEntryPoint: Address,\n blockNumber?: bigint,\n ): Promise<number>;\n /**\n * Read the application's current vault-keeper operation-key epoch.\n *\n * One counter for the whole application, bumped by any keeper's\n * operation-key or payout-script append. The peg-in config fingerprint\n * commits to it in place of the N resolved keeper keys, so it must be read\n * at the same block as the roster it labels. Returned as `bigint`; the\n * contract encodes it as `uint64` and a `Number` would truncate.\n */\n getCurrentAppKeeperKeyEpoch(\n appEntryPoint: Address,\n blockNumber?: bigint,\n ): Promise<bigint>;\n}\n\n/** Interface for reading universal challengers from the ProtocolParams contract. */\nexport interface UniversalChallengerReader {\n getUniversalChallengersByVersion(\n version: number,\n blockNumber?: bigint,\n ): Promise<AddressBTCKeyPair[]>;\n getCurrentUniversalChallengers(): Promise<AddressBTCKeyPair[]>;\n getLatestUniversalChallengersVersion(blockNumber?: bigint): Promise<number>;\n /**\n * Read the protocol's current universal-challenger operation-key epoch.\n *\n * The challenger-axis counterpart to\n * {@link VaultKeeperReader.getCurrentAppKeeperKeyEpoch}: one protocol-wide\n * counter the fingerprint commits to in place of the M resolved challenger\n * keys. Returned as `bigint` for the same `uint64` reason.\n */\n getCurrentUcKeyEpoch(blockNumber?: bigint): Promise<bigint>;\n}\n\n// ============================================================================\n// RFC-006 Operation-Key Types\n// ============================================================================\n\n/**\n * The participants whose operation keys are being resolved, and the roster\n * they are resolved against.\n *\n * A roster entry's `ethAddress` is the operator's **admin** address — the\n * lookup key for its key history — and its `btcPubKey` is the operator's\n * **genesis** key. Both are needed: the `...AtEpochOrGenesis` getters take the\n * roster key explicitly because the correct genesis for a keeper/challenger is\n * its key in the vault's *frozen membership version*, which an operator that\n * was later dropped from the roster no longer has a current entry for.\n */\nexport interface OperationKeyQuery {\n vaultProviderEthAddress: Address;\n /**\n * The VP's genesis (registration) key, from\n * {@link VaultRegistryReader.getVaultProviderGenesisBtcPubKey}.\n *\n * The VP has no roster entry to carry a genesis key the way keepers and\n * challengers do, so it is supplied here. Every call site already reads it:\n * it is what the indexer hint is compared against, and what makes the VP's\n * `rotated` flag mean the same thing as everyone else's.\n */\n vaultProviderGenesisBtcPubkey: Hex;\n applicationEntryPoint: Address;\n /** Keeper roster at the membership version being resolved against. */\n vaultKeepers: readonly AddressBTCKeyPair[];\n /** Challenger roster at the membership version being resolved against. */\n universalChallengers: readonly AddressBTCKeyPair[];\n}\n\n/** Raw registry-returned operation keys, index-aligned with the query rosters. */\nexport interface RawOperationKeys {\n vaultProvider: Hex;\n vaultKeepers: Hex[];\n universalChallengers: Hex[];\n}\n\n/**\n * Registry-returned payout scriptPubKeys, index-aligned with the query\n * rosters. `universalChallengers` has no counterpart: a UC is never a claimer,\n * so it has no payout script.\n */\nexport interface RawPayoutScripts {\n vaultProvider: Hex;\n vaultKeepers: Hex[];\n}\n\n/**\n * Reads RFC-006 operation keys and payout scripts across all three registries\n * (BTCVaultRegistry, ApplicationRegistry, ProtocolParams).\n *\n * Every method resolves the whole participant set in a **single** multicall so\n * the keys are pinned to one block. That atomicity is load-bearing: a rotation\n * landing between two `eth_call`s would yield a self-inconsistent key set that\n * builds a lock no counterparty agrees with.\n */\nexport interface OperationKeyReader {\n /**\n * Resolve every participant's *current* operation key.\n *\n * Used for new peg-ins and for the VP auth pin. Needs no epoch read at all —\n * each registry's `getCurrentOperationBtcKey` resolves its own genesis\n * fallback, so an operator that never rotated yields its registration key.\n */\n getCurrentOperationKeys(\n query: OperationKeyQuery,\n blockNumber?: bigint,\n ): Promise<RawOperationKeys>;\n /**\n * Resolve every participant's operation key bonded at a vault's frozen\n * epochs. Used for every existing-vault path (resume, payout, refund).\n */\n getOperationKeysAtEpochs(\n query: OperationKeyQuery,\n epochs: KeyEpochs,\n ): Promise<RawOperationKeys>;\n /**\n * Resolve the VP's commission payout script and each keeper's payout script\n * at a vault's frozen epochs.\n *\n * The registry backfills BIP-86 P2TR of the epoch's operation key for any\n * operator that never called `setPayoutScript`, so this returns byte-identical\n * results to local BIP-86 derivation until an operator registers a custom\n * script.\n */\n getPayoutScriptsAtEpochs(\n query: OperationKeyQuery,\n epochs: KeyEpochs,\n ): Promise<RawPayoutScripts>;\n}\n"],"names":["resolveProtocolAddresses","publicClient","btcVaultRegistryAddress","protocolParams","applicationRegistry","BTCVaultRegistryABI","assertMulticallLength","actual","expected","label","partition","results","keeperCount","ViemOperationKeyReader","contracts","calls","challengerCount","blockNumber","query","keeper","ApplicationRegistryABI","challenger","ProtocolParamsABI","epochs","UINT16_MAX","mapOffchainParams","result","mapTBVParams","deriveTimelockPegin","timelockAssert","ViemProtocolParamsReader","contractAddress","params","validateTBVProtocolParams","validateOffchainParams","version","raw","assertValidOffchainParamsVersion","tbvParams","offchainParams","offchainParamsVersion","activeVaultCoreVersion","config","validatePegInConfiguration","onSkippedVersion","latestVersion","versions","_","i","v","byVersion","error","mapKeyPairs","pair","assertKeyEpoch","ViemVaultKeeperReader","appEntryPoint","ViemUniversalChallengerReader","OnChainBtcVaultStatus"],"mappings":"yKA8BA,eAAsBA,EACpBC,EACAC,EAC4B,CAC5B,KAAM,CAACC,EAAgBC,CAAmB,EAAI,MAAMH,EAAa,UAAU,CACzE,UAAW,CACT,CACE,QAASC,EACT,IAAKG,EAAAA,oBACL,aAAc,gBAAA,EAEhB,CACE,QAASH,EACT,IAAKG,EA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A9B,EACA,KAAA,gBAAA8B,CACP,CAEH,MAAM,iCACJI,EACAlB,EAC8B,CAC9B,MAAMS,EAAU,MAAM,KAAK,aAAa,aAAa,CACnD,QAAS,KAAK,gBACd,IAAKJ,EAAAA,kBACL,aAAc,mCACd,KAAM,CAACa,CAAO,EACd,YAAAlB,CAAA,CACD,EAED,OAAOmC,EAAY1B,CAAM,CAC3B,CAEA,MAAM,gCAA+D,CACnE,MAAMA,EAAU,MAAM,KAAK,aAAa,aAAa,CACnD,QAAS,KAAK,gBACd,IAAKJ,EAAAA,kBACL,aAAc,gCAAA,CACf,EAED,OAAO8B,EAAY1B,CAAM,CAC3B,CAEA,MAAM,qCACJT,EACiB,CAQjB,OAPgB,MAAM,KAAK,aAAa,aAAa,CACnD,QAAS,KAAK,gBACd,IAAKK,EAAAA,kBACL,aAAc,oCACd,YAAAL,CAAA,CACD,CAGH,CAEA,MAAM,qBAAqBA,EAAuC,CAChE,MAAMmB,EAAe,MAAM,KAAK,aAAa,aAAa,CACxD,QAAS,KAAK,gBACd,IAAKd,EAAAA,kBACL,aAAc,oBACd,YAAAL,CAAA,CACD,EAED,OAAOqC,EAAelB,EAAK,mBAAmB,CAChD,CACF,CC7IO,IAAKsB,GAAAA,IACVA,EAAAA,EAAA,QAAU,CAAA,EAAV,UACAA,EAAAA,EAAA,SAAW,CAAA,EAAX,WACAA,EAAAA,EAAA,OAAS,CAAA,EAAT,SACAA,EAAAA,EAAA,SAAW,CAAA,EAAX,WACAA,EAAAA,EAAA,QAAU,CAAA,EAAV,UALUA,IAAAA,GAAA,CAAA,CAAA"}
|
|
1
|
+
{"version":3,"file":"types-BuxreSq4.cjs","sources":["../src/tbv/core/clients/eth/contract-address-resolver.ts","../src/tbv/core/clients/eth/operation-key-reader.ts","../src/tbv/core/clients/eth/protocol-params-reader.ts","../src/tbv/core/clients/eth/signer-set-reader.ts","../src/tbv/core/clients/eth/types.ts"],"sourcesContent":["/**\n * Contract Address Resolver\n *\n * Resolves ProtocolParams and ApplicationRegistry contract addresses\n * from the BTCVaultRegistry contract. These addresses are needed to\n * construct the SDK's contract readers.\n *\n * @module clients/eth/contract-address-resolver\n */\n\nimport type { Address, PublicClient } from \"viem\";\n\nimport { BTCVaultRegistryABI } from \"../../contracts/abis/BTCVaultRegistry.abi\";\n\nexport interface ProtocolAddresses {\n /** Address of the ProtocolParams contract */\n protocolParams: Address;\n /** Address of the ApplicationRegistry contract */\n applicationRegistry: Address;\n}\n\n/**\n * Resolve ProtocolParams and ApplicationRegistry addresses from BTCVaultRegistry.\n *\n * Uses a single multicall for atomicity and efficiency.\n *\n * @param publicClient - viem PublicClient instance\n * @param btcVaultRegistryAddress - Address of the BTCVaultRegistry contract\n * @returns Resolved contract addresses\n */\nexport async function resolveProtocolAddresses(\n publicClient: PublicClient,\n btcVaultRegistryAddress: Address,\n): Promise<ProtocolAddresses> {\n const [protocolParams, applicationRegistry] = await publicClient.multicall({\n contracts: [\n {\n address: btcVaultRegistryAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"protocolParams\",\n },\n {\n address: btcVaultRegistryAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"applicationRegistry\",\n },\n ],\n allowFailure: false,\n });\n\n return {\n protocolParams: protocolParams as Address,\n applicationRegistry: applicationRegistry as Address,\n };\n}\n","/**\n * Concrete RFC-006 operation-key reader spanning all three registries.\n *\n * This is an optional utility — callers can use their own implementation of\n * the {@link OperationKeyReader} interface.\n */\n\nimport type { Abi, Address, Hex, PublicClient } from \"viem\";\n\nimport { ApplicationRegistryABI } from \"../../contracts/abis/ApplicationRegistry.abi\";\nimport { BTCVaultRegistryABI } from \"../../contracts/abis/BTCVaultRegistry.abi\";\nimport { ProtocolParamsABI } from \"../../contracts/abis/ProtocolParams.abi\";\nimport type {\n KeyEpochs,\n OperationKeyQuery,\n OperationKeyReader,\n RawOperationKeys,\n RawPayoutScripts,\n} from \"./types\";\n\n/** Addresses of the three registries an operation-key resolution spans. */\nexport interface OperationKeyContracts {\n btcVaultRegistry: Address;\n applicationRegistry: Address;\n protocolParams: Address;\n}\n\n/** One `multicall` entry. Loosely typed because the three ABIs differ. */\ntype Call = {\n address: Address;\n abi: Abi;\n functionName: string;\n args: readonly unknown[];\n};\n\n/**\n * Reject a multicall result that is not one-per-call.\n *\n * Every method here relies on positional alignment between calls and results,\n * so a short array does not fail — it silently hands back `undefined` for the\n * tail entries. Downstream that surfaces as a complaint about whichever\n * operator happens to occupy the missing slot, blaming a participant that is\n * perfectly fine for a read that came back incomplete. Assert the length where\n * the array arrives so the error names the real fault.\n */\nfunction assertMulticallLength(\n actual: number,\n expected: number,\n label: string,\n): void {\n if (actual !== expected) {\n throw new Error(\n `${label}: multicall returned ${actual} results for ${expected} calls, ` +\n `so the results are not roster-aligned; refusing to use them`,\n );\n }\n}\n\n/**\n * Split a flat multicall result into VP / keepers / challengers.\n *\n * Every method below builds its calls in the same order — vault provider\n * first, then keepers in roster order, then challengers in roster order — so\n * the results stay index-aligned with `query.vaultKeepers` /\n * `query.universalChallengers`. That alignment is what lets the resolver pair\n * a resolved key back to its admin address; the sorted key arrays it exposes\n * are derived from those pairs, never the other way round.\n */\nfunction partition<T>(\n results: readonly T[],\n keeperCount: number,\n): { vaultProvider: T; vaultKeepers: T[]; universalChallengers: T[] } {\n return {\n vaultProvider: results[0],\n vaultKeepers: results.slice(1, 1 + keeperCount),\n universalChallengers: results.slice(1 + keeperCount),\n };\n}\n\n/**\n * Reads RFC-006 operation keys and payout scripts.\n *\n * Usage:\n * ```ts\n * const reader = new ViemOperationKeyReader(publicClient, contracts);\n * const keys = await reader.getCurrentOperationKeys(query);\n * ```\n */\nexport class ViemOperationKeyReader implements OperationKeyReader {\n constructor(\n private publicClient: PublicClient,\n private contracts: OperationKeyContracts,\n ) {}\n\n /**\n * One multicall, `allowFailure: false`, so every key in the set is read at\n * the same block. A rotation landing between two separate `eth_call`s would\n * otherwise produce a mixed-epoch key set and a lock no counterparty agrees\n * with.\n */\n private async readAll<T>(\n calls: Call[],\n keeperCount: number,\n challengerCount: number,\n label: string,\n blockNumber?: bigint,\n ) {\n const results = (await this.publicClient.multicall({\n contracts: calls,\n allowFailure: false,\n blockNumber,\n })) as readonly T[];\n\n assertMulticallLength(\n results.length,\n 1 + keeperCount + challengerCount,\n label,\n );\n\n return partition(results, keeperCount);\n }\n\n async getCurrentOperationKeys(\n query: OperationKeyQuery,\n blockNumber?: bigint,\n ): Promise<RawOperationKeys> {\n const calls: Call[] = [\n {\n address: this.contracts.btcVaultRegistry,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getCurrentOperationBtcKey\",\n args: [query.vaultProviderEthAddress],\n },\n ...query.vaultKeepers.map((keeper) => ({\n address: this.contracts.applicationRegistry,\n abi: ApplicationRegistryABI as Abi,\n functionName: \"getCurrentOperationBtcKey\",\n args: [query.applicationEntryPoint, keeper.ethAddress],\n })),\n ...query.universalChallengers.map((challenger) => ({\n address: this.contracts.protocolParams,\n abi: ProtocolParamsABI as Abi,\n functionName: \"getCurrentOperationBtcKey\",\n args: [challenger.ethAddress],\n })),\n ];\n\n return this.readAll<Hex>(\n calls,\n query.vaultKeepers.length,\n query.universalChallengers.length,\n \"getCurrentOperationKeys\",\n blockNumber,\n );\n }\n\n async getOperationKeysAtEpochs(\n query: OperationKeyQuery,\n epochs: KeyEpochs,\n ): Promise<RawOperationKeys> {\n const calls: Call[] = [\n // The VP takes the plain `AtEpoch` variant: it has no membership\n // version, so its genesis (the registration key at version 0) is\n // unambiguous and the contract resolves it internally.\n {\n address: this.contracts.btcVaultRegistry,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getOperationBtcKeyAtEpoch\",\n args: [query.vaultProviderEthAddress, epochs.vpKeyEpoch],\n },\n // Keepers and challengers take `...OrGenesis` with their roster key\n // passed explicitly, because the correct genesis for them is their key\n // in *this vault's frozen membership version*. An operator dropped from\n // the current roster, or listed under a different key in an older\n // version, would otherwise resolve against the wrong genesis.\n ...query.vaultKeepers.map((keeper) => ({\n address: this.contracts.applicationRegistry,\n abi: ApplicationRegistryABI as Abi,\n functionName: \"getOperationBtcKeyAtEpochOrGenesis\",\n args: [\n query.applicationEntryPoint,\n keeper.ethAddress,\n epochs.appKeeperKeyEpoch,\n keeper.btcPubKey,\n ],\n })),\n ...query.universalChallengers.map((challenger) => ({\n address: this.contracts.protocolParams,\n abi: ProtocolParamsABI as Abi,\n functionName: \"getOperationBtcKeyAtEpochOrGenesis\",\n args: [challenger.ethAddress, epochs.ucKeyEpoch, challenger.btcPubKey],\n })),\n ];\n\n return this.readAll<Hex>(\n calls,\n query.vaultKeepers.length,\n query.universalChallengers.length,\n \"getOperationKeysAtEpochs\",\n );\n }\n\n async getPayoutScriptsAtEpochs(\n query: OperationKeyQuery,\n epochs: KeyEpochs,\n ): Promise<RawPayoutScripts> {\n // Universal challengers are never claimers, so they have no payout script\n // and no call here.\n const results = (await this.publicClient.multicall({\n contracts: [\n {\n address: this.contracts.btcVaultRegistry,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getPayoutScriptAtEpoch\",\n args: [query.vaultProviderEthAddress, epochs.vpKeyEpoch],\n },\n ...query.vaultKeepers.map((keeper) => ({\n address: this.contracts.applicationRegistry,\n abi: ApplicationRegistryABI as Abi,\n functionName: \"getPayoutScriptAtEpoch\",\n args: [\n query.applicationEntryPoint,\n keeper.ethAddress,\n epochs.appKeeperKeyEpoch,\n ],\n })),\n ],\n allowFailure: false,\n })) as readonly Hex[];\n\n // Expected length is `1 + keepers`, with no challenger term — see the\n // comment above on why universal challengers have no call here.\n assertMulticallLength(\n results.length,\n 1 + query.vaultKeepers.length,\n \"getPayoutScriptsAtEpochs\",\n );\n\n return {\n vaultProvider: results[0],\n vaultKeepers: [...results.slice(1)],\n };\n }\n}\n","/**\n * Concrete ProtocolParams reader using viem's readContract and multicall.\n *\n * This is an optional utility — callers can use their own implementation\n * of the ProtocolParamsReader interface.\n */\n\nimport type { Abi, Address, Hex, PublicClient } from \"viem\";\n\nimport { ProtocolParamsABI } from \"../../contracts/abis/ProtocolParams.abi\";\nimport {\n assertValidOffchainParamsVersion,\n validateOffchainParams,\n validatePegInConfiguration,\n validateTBVProtocolParams,\n} from \"./protocol-params-validation\";\nimport type {\n AllOffchainParamsData,\n OnSkippedOffchainParamsVersion,\n PegInConfiguration,\n ProtocolParamsReader,\n TBVProtocolParams,\n VersionedOffchainParams,\n} from \"./types\";\n\n/**\n * Maximum value for a Solidity uint16.\n * PeginLogic.sol casts timelockAssert to uint16, so values above this are invalid.\n */\nconst UINT16_MAX = 65535;\n\n\n/**\n * Raw shape viem returns for VersionedOffchainParams struct.\n * viem resolves ABI struct outputs to named objects (not tuples).\n */\ninterface RawOffchainParams {\n timelockAssert: bigint;\n timelockChallengeAssert: bigint;\n securityCouncilKeys: readonly Hex[];\n councilQuorum: number;\n feeRate: bigint;\n babeTotalInstances: number;\n babeInstancesToFinalize: number;\n minVpCommissionBps: number;\n tRefund: number;\n tStale: number;\n minPeginFeeRate: bigint;\n proverCircuitVersion: number;\n minPrepeginDepth: number;\n}\n\n/** Raw shape viem returns for TBVProtocolParams struct. */\ninterface RawTBVParams {\n minimumPegInAmount: bigint;\n maxPegInAmount: bigint;\n pegInAckTimeout: bigint;\n pegInActivationTimeout: bigint;\n maxHtlcOutputCount: number;\n expiredPegInGraceBlocks: bigint;\n}\n\n/** Map viem struct result to VersionedOffchainParams. */\nfunction mapOffchainParams(result: RawOffchainParams): VersionedOffchainParams {\n return {\n timelockAssert: result.timelockAssert,\n timelockChallengeAssert: result.timelockChallengeAssert,\n securityCouncilKeys: [...result.securityCouncilKeys],\n councilQuorum: result.councilQuorum,\n feeRate: result.feeRate,\n babeTotalInstances: result.babeTotalInstances,\n babeInstancesToFinalize: result.babeInstancesToFinalize,\n minVpCommissionBps: result.minVpCommissionBps,\n tRefund: result.tRefund,\n tStale: result.tStale,\n minPeginFeeRate: result.minPeginFeeRate,\n proverCircuitVersion: result.proverCircuitVersion,\n minPrepeginDepth: result.minPrepeginDepth,\n };\n}\n\n/** Map viem struct result to TBVProtocolParams. */\nfunction mapTBVParams(result: RawTBVParams): TBVProtocolParams {\n return {\n minimumPegInAmount: result.minimumPegInAmount,\n maxPegInAmount: result.maxPegInAmount,\n pegInAckTimeout: result.pegInAckTimeout,\n pegInActivationTimeout: result.pegInActivationTimeout,\n maxHtlcOutputCount: result.maxHtlcOutputCount,\n expiredPegInGraceBlocks: result.expiredPegInGraceBlocks,\n };\n}\n\n/**\n * Derive timelockPegin from timelockAssert.\n *\n * Matches PeginLogic.sol: `uint16(timelockAssert)`.\n * The contract validates `timelockAssert <= type(uint16).max` on write,\n * but we enforce the same bound here to reject invalid values early\n * rather than silently truncating.\n *\n * @throws if timelockAssert exceeds uint16 max (65535)\n */\nfunction deriveTimelockPegin(timelockAssert: bigint): number {\n if (timelockAssert > BigInt(UINT16_MAX)) {\n throw new Error(\n `timelockAssert value ${timelockAssert} exceeds uint16 max (${UINT16_MAX})`,\n );\n }\n return Number(timelockAssert);\n}\n\n/**\n * Concrete protocol params reader using viem.\n *\n * Every read method runs the matching validator from\n * `protocol-params-validation` before returning, so callers don't have to\n * remember to validate.\n *\n * Usage:\n * ```ts\n * const reader = new ViemProtocolParamsReader(publicClient, protocolParamsAddress);\n * const config = await reader.getPegInConfiguration();\n * ```\n */\nexport class ViemProtocolParamsReader implements ProtocolParamsReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n async getTBVProtocolParams(): Promise<TBVProtocolParams> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getTBVProtocolParams\",\n })) as RawTBVParams;\n\n const params = mapTBVParams(result);\n validateTBVProtocolParams(params);\n return params;\n }\n\n async getLatestOffchainParams(): Promise<VersionedOffchainParams> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getLatestOffchainParams\",\n })) as RawOffchainParams;\n\n const params = mapOffchainParams(result);\n validateOffchainParams(params);\n return params;\n }\n\n async getOffchainParamsByVersion(\n version: number,\n ): Promise<VersionedOffchainParams> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getOffchainParamsByVersion\",\n args: [version],\n })) as RawOffchainParams;\n\n const params = mapOffchainParams(result);\n validateOffchainParams(params);\n return params;\n }\n\n async getLatestOffchainParamsVersion(): Promise<number> {\n const raw = await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"latestOffchainParamsVersion\",\n });\n const version = Number(raw);\n assertValidOffchainParamsVersion(version);\n return version;\n }\n\n async getTimelockPeginByVersion(version: number): Promise<number> {\n const params = await this.getOffchainParamsByVersion(version);\n return deriveTimelockPegin(params.timelockAssert);\n }\n\n /**\n * Returned as `bigint` with no `Number` narrowing: the registry compares it\n * against `block.number`, so callers must do the same arithmetic the\n * contract does. `0` is the documented \"disabled\" case and is returned as\n * `0n`. A missing getter or a non-bigint payload throws — never coerced to\n * `0`, which would fail open and skip the observation window.\n *\n * @throws If the deployment does not expose `peginActivationDelay()`, or\n * the decoded payload is not a `bigint`.\n */\n async getPeginActivationDelay(): Promise<bigint> {\n const raw: unknown = await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"peginActivationDelay\",\n });\n if (typeof raw !== \"bigint\") {\n throw new Error(\n `Invalid peginActivationDelay from contract: must be a bigint, got ${typeof raw}`,\n );\n }\n return raw;\n }\n\n /**\n * Read TBV protocol params, latest offchain params, and the latest version\n * label atomically via multicall. The version is paired with the params so\n * that a governance update between separate reads cannot let JS build BTC\n * scripts with version N params while the contract registers the vault\n * under version N+1.\n *\n * That guarantee holds only within this multicall. A caller that also reads\n * participant keys — every fresh peg-in build does — must pass the same\n * `blockNumber` here and to those reads, or the two describe different\n * blocks and the pairing above buys nothing across the seam.\n */\n async getPegInConfiguration(\n blockNumber?: bigint,\n ): Promise<PegInConfiguration> {\n const results = await this.publicClient.multicall({\n blockNumber,\n contracts: [\n {\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getTBVProtocolParams\",\n },\n {\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getLatestOffchainParams\",\n },\n {\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"latestOffchainParamsVersion\",\n },\n {\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"activeVaultCoreVersion\",\n },\n ],\n allowFailure: false,\n });\n\n const tbvParams = mapTBVParams(results[0] as RawTBVParams);\n const offchainParams = mapOffchainParams(results[1] as RawOffchainParams);\n const offchainParamsVersion = Number(results[2]);\n const activeVaultCoreVersion = Number(results[3]);\n\n const config: PegInConfiguration = {\n minimumPegInAmount: tbvParams.minimumPegInAmount,\n maxPegInAmount: tbvParams.maxPegInAmount,\n pegInAckTimeout: tbvParams.pegInAckTimeout,\n pegInActivationTimeout: tbvParams.pegInActivationTimeout,\n maxHtlcOutputCount: tbvParams.maxHtlcOutputCount,\n expiredPegInGraceBlocks: tbvParams.expiredPegInGraceBlocks,\n timelockPegin: deriveTimelockPegin(offchainParams.timelockAssert),\n timelockRefund: offchainParams.tRefund,\n minVpCommissionBps: offchainParams.minVpCommissionBps,\n offchainParams,\n offchainParamsVersion,\n activeVaultCoreVersion,\n };\n\n validatePegInConfiguration(config);\n return config;\n }\n\n /**\n * Fetch every historical offchain params version in a single multicall.\n * Iterates 1..latestVersion and calls `getOffchainParamsByVersion` for each.\n * Versions whose payload fails validation are skipped (not included in the\n * returned map) so a single bad historical version doesn't block the\n * lookup of the rest.\n *\n * @param onSkippedVersion - optional observer invoked once per skipped\n * version. Use to log/telemeter without coupling the SDK to a logger.\n */\n async fetchAllOffchainParams(\n onSkippedVersion?: OnSkippedOffchainParamsVersion,\n ): Promise<AllOffchainParamsData> {\n const latestVersion = await this.getLatestOffchainParamsVersion();\n if (latestVersion === 0) {\n return { byVersion: new Map(), latestVersion: 0 };\n }\n\n const versions = Array.from({ length: latestVersion }, (_, i) => i + 1);\n const contracts = versions.map((v) => ({\n address: this.contractAddress,\n abi: ProtocolParamsABI as Abi,\n functionName: \"getOffchainParamsByVersion\" as const,\n args: [v] as const,\n }));\n\n const results = await this.publicClient.multicall({\n contracts,\n allowFailure: false,\n });\n\n const byVersion = new Map<number, VersionedOffchainParams>();\n for (let i = 0; i < versions.length; i++) {\n const params = mapOffchainParams(results[i] as RawOffchainParams);\n try {\n validateOffchainParams(params);\n byVersion.set(versions[i], params);\n } catch (error) {\n // A malformed historical version mustn't block lookup of the rest.\n // Surface the skip to the caller's observer if one was supplied.\n onSkippedVersion?.(\n versions[i],\n error instanceof Error ? error : new Error(String(error)),\n );\n }\n }\n\n return { byVersion, latestVersion };\n }\n}\n","/**\n * Concrete signer-set readers for vault keepers and universal challengers.\n *\n * These are optional utilities — callers can use their own implementations\n * of the VaultKeeperReader and UniversalChallengerReader interfaces.\n */\n\nimport type { Address, Hex, PublicClient } from \"viem\";\n\nimport { ApplicationRegistryABI } from \"../../contracts/abis/ApplicationRegistry.abi\";\nimport { ProtocolParamsABI } from \"../../contracts/abis/ProtocolParams.abi\";\nimport type {\n AddressBTCKeyPair,\n UniversalChallengerReader,\n VaultKeeperReader,\n} from \"./types\";\n\n/** Map viem tuple array to AddressBTCKeyPair[]. */\nfunction mapKeyPairs(\n result: readonly { ethAddress: Address; btcPubKey: Hex }[],\n): AddressBTCKeyPair[] {\n return result.map((pair) => ({\n ethAddress: pair.ethAddress,\n btcPubKey: pair.btcPubKey,\n }));\n}\n\n/**\n * Both key-epoch getters return `uint64` and feed the peg-in config\n * fingerprint, where the contract encodes them as `uint64`. A `Number`\n * narrowing would silently truncate above 2^53 and produce a fingerprint the\n * registry cannot reproduce, so the payload is asserted to be a `bigint` and\n * carried as one — never coerced, never defaulted.\n */\nfunction assertKeyEpoch(raw: unknown, label: string): bigint {\n if (typeof raw !== \"bigint\") {\n throw new Error(\n `Invalid ${label} from contract: must be a bigint, got ${typeof raw}`,\n );\n }\n return raw;\n}\n\n/**\n * Reads vault keepers from the ApplicationRegistry contract.\n *\n * Usage:\n * ```ts\n * const reader = new ViemVaultKeeperReader(publicClient, applicationRegistryAddress);\n * const keepers = await reader.getCurrentVaultKeepers(appEntryPoint);\n * ```\n */\nexport class ViemVaultKeeperReader implements VaultKeeperReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n async getVaultKeepersByVersion(\n appEntryPoint: Address,\n version: number,\n blockNumber?: bigint,\n ): Promise<AddressBTCKeyPair[]> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ApplicationRegistryABI,\n functionName: \"getVaultKeepersByVersion\",\n args: [appEntryPoint, version],\n blockNumber,\n })) as readonly { ethAddress: Address; btcPubKey: Hex }[];\n\n return mapKeyPairs(result);\n }\n\n async getCurrentVaultKeepers(\n appEntryPoint: Address,\n ): Promise<AddressBTCKeyPair[]> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ApplicationRegistryABI,\n functionName: \"getCurrentVaultKeepers\",\n args: [appEntryPoint],\n })) as readonly { ethAddress: Address; btcPubKey: Hex }[];\n\n return mapKeyPairs(result);\n }\n\n async getCurrentVaultKeepersVersion(\n appEntryPoint: Address,\n blockNumber?: bigint,\n ): Promise<number> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ApplicationRegistryABI,\n functionName: \"getCurrentVaultKeepersVersion\",\n args: [appEntryPoint],\n blockNumber,\n })) as number;\n\n return result;\n }\n\n async getCurrentAppKeeperKeyEpoch(\n appEntryPoint: Address,\n blockNumber?: bigint,\n ): Promise<bigint> {\n const raw: unknown = await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ApplicationRegistryABI,\n functionName: \"appKeeperKeyEpochCurrent\",\n args: [appEntryPoint],\n blockNumber,\n });\n\n return assertKeyEpoch(raw, \"appKeeperKeyEpochCurrent\");\n }\n}\n\n/**\n * Reads universal challengers from the ProtocolParams contract.\n *\n * Usage:\n * ```ts\n * const reader = new ViemUniversalChallengerReader(publicClient, protocolParamsAddress);\n * const challengers = await reader.getCurrentUniversalChallengers();\n * ```\n */\nexport class ViemUniversalChallengerReader implements UniversalChallengerReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n async getUniversalChallengersByVersion(\n version: number,\n blockNumber?: bigint,\n ): Promise<AddressBTCKeyPair[]> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getUniversalChallengersByVersion\",\n args: [version],\n blockNumber,\n })) as readonly { ethAddress: Address; btcPubKey: Hex }[];\n\n return mapKeyPairs(result);\n }\n\n async getCurrentUniversalChallengers(): Promise<AddressBTCKeyPair[]> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getCurrentUniversalChallengers\",\n })) as readonly { ethAddress: Address; btcPubKey: Hex }[];\n\n return mapKeyPairs(result);\n }\n\n async getLatestUniversalChallengersVersion(\n blockNumber?: bigint,\n ): Promise<number> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"latestUniversalChallengersVersion\",\n blockNumber,\n })) as number;\n\n return result;\n }\n\n async getCurrentUcKeyEpoch(blockNumber?: bigint): Promise<bigint> {\n const raw: unknown = await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"ucKeyEpochCurrent\",\n blockNumber,\n });\n\n return assertKeyEpoch(raw, \"ucKeyEpochCurrent\");\n }\n}\n","/**\n * Types and interfaces for ETH contract readers.\n *\n * These are optional utilities — callers can use them or build their own.\n * Core service functions never import from this module.\n */\n\nimport type { Address, Hex } from \"viem\";\n\n// ============================================================================\n// Vault Registry Types\n// ============================================================================\n\ndeclare const onChainBtcPubkeyBrand: unique symbol;\n\n/**\n * 64-char lowercase hex (no `0x`) x-only BTC pubkey sourced from an on-chain\n * registry. Minted only by `assertOnChainBtcPubkey`, which is the shared\n * validator behind both producers:\n * {@link VaultRegistryReader.getVaultProviderGenesisBtcPubKey} (the fixed\n * registration key) and {@link OperationKeyReader} (RFC-006 operation keys,\n * resolved current or at a vault's frozen epoch).\n *\n * @stability frozen\n */\nexport type OnChainBtcPubkey = string & {\n readonly [onChainBtcPubkeyBrand]: true;\n};\n\n/**\n * Mirrors `IBTCVaultRegistry.BTCVaultStatus` in BTCVaultRegistry.sol exactly.\n * Use this when consuming `status` from `getVaultBasicInfo` /\n * `getBtcVaultBasicInfo`.\n *\n * Do NOT confuse with the app-side `ContractStatus` enum\n * (`services/deposit/peginState.ts`) — that one is for the indexer and\n * extends this with values 5-7, reassigning 4 to LIQUIDATED. Reading an\n * on-chain status through `ContractStatus[n]` for labels will mislabel\n * Expired(4) as LIQUIDATED.\n */\nexport enum OnChainBtcVaultStatus {\n PENDING = 0,\n VERIFIED = 1,\n ACTIVE = 2,\n REDEEMED = 3,\n EXPIRED = 4,\n}\n\n/** Basic vault info from BTCVaultRegistry.getBtcVaultBasicInfo */\nexport interface VaultBasicInfo {\n depositor: Address;\n depositorBtcPubKey: Hex;\n amount: bigint;\n vaultProvider: Address;\n status: number;\n applicationEntryPoint: Address;\n createdAt: bigint;\n}\n\n/** Protocol info from BTCVaultRegistry.getBtcVaultProtocolInfo */\nexport interface VaultProtocolInfo {\n depositorSignedPeginTx: Hex;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n offchainParamsVersion: number;\n /**\n * ETH block number stamped at the Pending→Verified transition.\n * Compared against `block.number` (inclusive:\n * `block.number >= verifiedAt + peginActivationDelay`), never a unix timestamp.\n */\n verifiedAt: bigint;\n depositorWotsPkHash: Hex;\n hashlock: Hex;\n htlcVout: number;\n depositorPopSignature: Hex;\n prePeginTxHash: Hex;\n vaultProviderCommissionBps: number;\n /** Vault core version (uint16) stamped at registration. VP-side gating only — see #1690. */\n vaultCoreVersion: number;\n}\n\n/** Combined vault data (basic + protocol) */\nexport interface VaultData {\n basic: VaultBasicInfo;\n protocol: VaultProtocolInfo;\n}\n\n/**\n * RFC-006 operation-key epochs a vault froze at `submitPeginRequest`.\n *\n * Each registry keeps a monotonic epoch counter that every key/payout setter\n * pre-increments. A vault stamps the counters live at its creation, and every\n * participant resolves \"which key did this vault bond?\" by asking the registry\n * for the key whose appended version is the latest stamped `<=` this epoch. A\n * rotation after the vault was created therefore never moves its keys.\n *\n * `uint64` — kept as `bigint` end-to-end and passed straight back to the\n * `...AtEpoch` getters, never narrowed through `Number`.\n *\n * Only ever read through {@link VaultRegistryReader.getVaultKeyEpochs}, which\n * uses the extended ABI. See `BTCVaultRegistryKeyEpochs.abi.ts` for why that\n * read is quarantined to its own ABI.\n */\nexport interface KeyEpochs {\n vpKeyEpoch: bigint;\n appKeeperKeyEpoch: bigint;\n ucKeyEpoch: bigint;\n}\n\n/** Interface for reading vault data from the BTCVaultRegistry contract. */\nexport interface VaultRegistryReader {\n getVaultBasicInfo(vaultId: Hex): Promise<VaultBasicInfo>;\n getVaultProtocolInfo(vaultId: Hex): Promise<VaultProtocolInfo>;\n getProtocolInfoBatch(vaultIds: readonly Hex[]): Promise<VaultProtocolInfo[]>;\n getVaultData(vaultId: Hex): Promise<VaultData>;\n /**\n * Read a vault provider's *genesis* (registration) BTC key — the key bonded\n * at version 0, which never moves when the operator rotates.\n *\n * Used only as the genesis fallback for epoch-based resolution and as a\n * candidate when cross-checking an indexer hint. Never the key to build a\n * Bitcoin lock with; that comes from `OperationKeyReader`.\n *\n * Resolves via `getOperationBtcKeyAtEpoch` at epoch 0, so it requires an\n * RFC-006 registry — as does every caller.\n */\n getVaultProviderGenesisBtcPubKey(\n vpAddress: Address,\n blockNumber?: bigint,\n ): Promise<OnChainBtcPubkey>;\n /** Read the protocol pegin fee (in wei) for a given vault provider. */\n getPegInFee(vaultProvider: Address): Promise<bigint>;\n /**\n * Read a vault provider's current commission in basis points.\n *\n * Validates the contract-enforced `[0, 9999]` range — an out-of-range\n * value signals a wrong contract address or ABI drift, not a real rate.\n */\n getVaultProviderCommission(vaultProvider: Address): Promise<number>;\n /**\n * Read a vault's frozen RFC-006 key epochs.\n *\n * Uses the extended `getBtcVaultProtocolInfo` ABI. Against a registry whose\n * `BTCVaultProtocolInfo` struct is not extended this returns silent garbage\n * for a populated vault rather than throwing, so it must only be called\n * against an RFC-006 registry — a deployment invariant, not something this\n * call can detect. A registry missing the operation-key getters altogether is\n * the safer case: key resolution reverts downstream and these epochs are never\n * used. See `BTCVaultRegistryKeyEpochs.abi.ts`.\n */\n getVaultKeyEpochs(vaultId: Hex): Promise<KeyEpochs>;\n /** {@link getVaultKeyEpochs} for many vaults in one multicall. */\n getVaultKeyEpochsBatch(vaultIds: readonly Hex[]): Promise<KeyEpochs[]>;\n /**\n * Read a vault provider's *current* RFC-006 operation BTC key — the key its\n * server signs auth tokens with. Falls back to the registration key when the\n * provider has never rotated.\n */\n getCurrentVaultProviderOperationBtcKey(\n vpAddress: Address,\n ): Promise<OnChainBtcPubkey>;\n /**\n * Read the depositor's commission ceiling (`maxAcceptableCommissionBps`)\n * for vaults registered in the same block `createdAt`, from their\n * `PegInSubmittedV2` logs, in `vaultIds` order. The contract discards the\n * ceiling after bound-checking it, so the log is its only on-chain source.\n *\n * @throws {RegistrationLogsUnavailableError} (transient, retry) when the\n * node answers with no registration logs for the block at all.\n * @throws when a vault has only its `PegInSubmitted` log (a registration\n * that predates the V2 event), none, or more than one V2 log.\n */\n getMaxAcceptableCommissionBpsBatch(\n vaultIds: readonly Hex[],\n createdAt: bigint,\n ): Promise<number[]>;\n /**\n * Read the application entry point a vault provider is registered for.\n *\n * The peg-in submit path resolves this internally and uses it to pick the\n * keeper roster, the roster version and the keeper key epoch a deposit is\n * bonded to. Pass `blockNumber` when the result will shape a Bitcoin lock,\n * so it describes the same block as the roster reads that follow it.\n */\n getVaultProviderApplication(\n vpAddress: Address,\n blockNumber?: bigint,\n ): Promise<Address>;\n}\n\n// ============================================================================\n// Protocol Params Types (from IProtocolParams.sol)\n// ============================================================================\n\n/**\n * TBV protocol parameters from the ProtocolParams contract.\n * Matches Solidity struct `IProtocolParams.TBVProtocolParams` exactly.\n *\n * All uint64 amounts use bigint (satoshi values can exceed 2^53).\n * uint8 uses number (bounded, max 255).\n */\nexport interface TBVProtocolParams {\n minimumPegInAmount: bigint;\n maxPegInAmount: bigint;\n pegInAckTimeout: bigint;\n pegInActivationTimeout: bigint;\n maxHtlcOutputCount: number;\n /**\n * Number of blocks added to the activation deadline as a grace window\n * during which a depositor may still reclaim an expired pegin via the\n * HTLC preimage. Source: `IProtocolParams.TBVProtocolParams.expiredPegInGraceBlocks`.\n */\n expiredPegInGraceBlocks: bigint;\n}\n\n/**\n * Versioned offchain parameters from the ProtocolParams contract.\n * Matches Solidity struct `IProtocolParams.VersionedOffchainParams` exactly.\n *\n * bigint for: uint256 timelocks, uint64 fee rates/amounts.\n * number for: uint8/uint16/uint32 fields (bounded, safe for JS arithmetic).\n */\nexport interface VersionedOffchainParams {\n timelockAssert: bigint;\n timelockChallengeAssert: bigint;\n securityCouncilKeys: Hex[];\n councilQuorum: number;\n feeRate: bigint;\n babeTotalInstances: number;\n babeInstancesToFinalize: number;\n minVpCommissionBps: number;\n tRefund: number;\n tStale: number;\n minPeginFeeRate: bigint;\n proverCircuitVersion: number;\n minPrepeginDepth: number;\n}\n\n/**\n * Combined peg-in configuration read atomically via multicall.\n * Prevents TOCTOU inconsistency if governance updates params between reads.\n */\nexport interface PegInConfiguration {\n minimumPegInAmount: bigint;\n maxPegInAmount: bigint;\n pegInAckTimeout: bigint;\n pegInActivationTimeout: bigint;\n maxHtlcOutputCount: number;\n expiredPegInGraceBlocks: bigint;\n timelockPegin: number;\n timelockRefund: number;\n minVpCommissionBps: number;\n offchainParams: VersionedOffchainParams;\n /**\n * Version label paired atomically with `offchainParams`.\n * Read in the same multicall as the params struct so that, if a parameter\n * update lands between separate reads, the script-construction code and\n * the version label stay consistent.\n */\n offchainParamsVersion: number;\n /**\n * Currently-active vault core (tx-graph) version\n * (`ProtocolParams.activeVaultCoreVersion()`, uint16 ≥ 1). Stamped onto\n * every new vault at peg-in submission; fresh deposits must build this\n * graph version. Read in the same multicall so a governance version bump\n * can't land between reading the params and reading the version.\n */\n activeVaultCoreVersion: number;\n}\n\n/**\n * All offchain params snapshots indexed by version, plus the latest version\n * number known when the snapshot was taken. Used by consumers that need to\n * resolve any historical version (e.g. signing for an existing vault locked\n * to an older version).\n */\nexport interface AllOffchainParamsData {\n byVersion: Map<number, VersionedOffchainParams>;\n latestVersion: number;\n}\n\n/**\n * Optional observer invoked by `fetchAllOffchainParams` when a historical\n * version fails validation. Called once per skipped version so callers can\n * log/telemeter without coupling the SDK to a specific logger.\n */\nexport type OnSkippedOffchainParamsVersion = (\n version: number,\n error: Error,\n) => void;\n\n/** Interface for reading protocol parameters from the ProtocolParams contract. */\nexport interface ProtocolParamsReader {\n getTBVProtocolParams(): Promise<TBVProtocolParams>;\n getOffchainParamsByVersion(version: number): Promise<VersionedOffchainParams>;\n getLatestOffchainParams(): Promise<VersionedOffchainParams>;\n getLatestOffchainParamsVersion(): Promise<number>;\n getTimelockPeginByVersion(version: number): Promise<number>;\n /**\n * Pass `blockNumber` when the result will shape a Bitcoin lock, so this\n * multicall and the participant-key reads describe the same block. Omit it\n * for display-only reads, where a slightly stale value is harmless.\n */\n getPegInConfiguration(blockNumber?: bigint): Promise<PegInConfiguration>;\n /**\n * Observation window enforced between a vault's final ACK and its\n * activation, in ETH blocks measured from `verifiedAt`. `0` disables it.\n *\n * Deliberately its own read rather than a field on\n * {@link PegInConfiguration}: the parameter is absent from deployments that\n * predate it, so folding it into the shared multicall would make every\n * protocol-param read fail wherever it is missing.\n *\n * @throws If the deployment does not expose `peginActivationDelay()`, or\n * the decoded payload is not a `bigint`.\n */\n getPeginActivationDelay(): Promise<bigint>;\n fetchAllOffchainParams(\n onSkippedVersion?: OnSkippedOffchainParamsVersion,\n ): Promise<AllOffchainParamsData>;\n}\n\n// ============================================================================\n// Signer-Set Types (from BTCVaultTypes.sol)\n// ============================================================================\n\n/**\n * Matches Solidity struct `BTCVaultTypes.AddressBTCKeyPair` exactly.\n * Used for vault keepers and universal challengers.\n */\nexport interface AddressBTCKeyPair {\n ethAddress: Address;\n btcPubKey: Hex;\n}\n\n/**\n * Interface for reading vault keepers from the ApplicationRegistry contract.\n *\n * The reads used to build a peg-in — here and on the sibling reader interfaces\n * — take an optional `blockNumber` that pins them to one block instead of\n * `latest`. Omitting it, the historical behaviour, is correct for every read\n * that resolves against a vault's already-frozen epochs, because those are\n * immutable once stamped. It is NOT correct for a fresh peg-in build: the\n * participant keys, roster versions and protocol params that shape the Bitcoin\n * lock must all describe the same block, or the lock commits to a mixture of\n * chain states that never existed at once. See\n * `services/deposit/validateOnChainParticipantKeys`.\n *\n * The `getCurrent*` roster reads are the exception and take no block. Nothing\n * on the build path uses them — it resolves rosters by version instead — so\n * they were left alone rather than given a pin no caller would pass.\n */\nexport interface VaultKeeperReader {\n getVaultKeepersByVersion(\n appEntryPoint: Address,\n version: number,\n blockNumber?: bigint,\n ): Promise<AddressBTCKeyPair[]>;\n getCurrentVaultKeepers(appEntryPoint: Address): Promise<AddressBTCKeyPair[]>;\n getCurrentVaultKeepersVersion(\n appEntryPoint: Address,\n blockNumber?: bigint,\n ): Promise<number>;\n /**\n * Read the application's current vault-keeper operation-key epoch.\n *\n * One counter for the whole application, bumped by any keeper's\n * operation-key or payout-script append. The peg-in config fingerprint\n * commits to it in place of the N resolved keeper keys, so it must be read\n * at the same block as the roster it labels. Returned as `bigint`; the\n * contract encodes it as `uint64` and a `Number` would truncate.\n */\n getCurrentAppKeeperKeyEpoch(\n appEntryPoint: Address,\n blockNumber?: bigint,\n ): Promise<bigint>;\n}\n\n/** Interface for reading universal challengers from the ProtocolParams contract. */\nexport interface UniversalChallengerReader {\n getUniversalChallengersByVersion(\n version: number,\n blockNumber?: bigint,\n ): Promise<AddressBTCKeyPair[]>;\n getCurrentUniversalChallengers(): Promise<AddressBTCKeyPair[]>;\n getLatestUniversalChallengersVersion(blockNumber?: bigint): Promise<number>;\n /**\n * Read the protocol's current universal-challenger operation-key epoch.\n *\n * The challenger-axis counterpart to\n * {@link VaultKeeperReader.getCurrentAppKeeperKeyEpoch}: one protocol-wide\n * counter the fingerprint commits to in place of the M resolved challenger\n * keys. Returned as `bigint` for the same `uint64` reason.\n */\n getCurrentUcKeyEpoch(blockNumber?: bigint): Promise<bigint>;\n}\n\n// ============================================================================\n// RFC-006 Operation-Key Types\n// ============================================================================\n\n/**\n * The participants whose operation keys are being resolved, and the roster\n * they are resolved against.\n *\n * A roster entry's `ethAddress` is the operator's **admin** address — the\n * lookup key for its key history — and its `btcPubKey` is the operator's\n * **genesis** key. Both are needed: the `...AtEpochOrGenesis` getters take the\n * roster key explicitly because the correct genesis for a keeper/challenger is\n * its key in the vault's *frozen membership version*, which an operator that\n * was later dropped from the roster no longer has a current entry for.\n */\nexport interface OperationKeyQuery {\n vaultProviderEthAddress: Address;\n /**\n * The VP's genesis (registration) key, from\n * {@link VaultRegistryReader.getVaultProviderGenesisBtcPubKey}.\n *\n * The VP has no roster entry to carry a genesis key the way keepers and\n * challengers do, so it is supplied here. Every call site already reads it:\n * it is what the indexer hint is compared against, and what makes the VP's\n * `rotated` flag mean the same thing as everyone else's.\n */\n vaultProviderGenesisBtcPubkey: Hex;\n applicationEntryPoint: Address;\n /** Keeper roster at the membership version being resolved against. */\n vaultKeepers: readonly AddressBTCKeyPair[];\n /** Challenger roster at the membership version being resolved against. */\n universalChallengers: readonly AddressBTCKeyPair[];\n}\n\n/** Raw registry-returned operation keys, index-aligned with the query rosters. */\nexport interface RawOperationKeys {\n vaultProvider: Hex;\n vaultKeepers: Hex[];\n universalChallengers: Hex[];\n}\n\n/**\n * Registry-returned payout scriptPubKeys, index-aligned with the query\n * rosters. `universalChallengers` has no counterpart: a UC is never a claimer,\n * so it has no payout script.\n */\nexport interface RawPayoutScripts {\n vaultProvider: Hex;\n vaultKeepers: Hex[];\n}\n\n/**\n * Reads RFC-006 operation keys and payout scripts across all three registries\n * (BTCVaultRegistry, ApplicationRegistry, ProtocolParams).\n *\n * Every method resolves the whole participant set in a **single** multicall so\n * the keys are pinned to one block. That atomicity is load-bearing: a rotation\n * landing between two `eth_call`s would yield a self-inconsistent key set that\n * builds a lock no counterparty agrees with.\n */\nexport interface OperationKeyReader {\n /**\n * Resolve every participant's *current* operation key.\n *\n * Used for new peg-ins and for the VP auth pin. Needs no epoch read at all —\n * each registry's `getCurrentOperationBtcKey` resolves its own genesis\n * fallback, so an operator that never rotated yields its registration key.\n */\n getCurrentOperationKeys(\n query: OperationKeyQuery,\n blockNumber?: bigint,\n ): Promise<RawOperationKeys>;\n /**\n * Resolve every participant's operation key bonded at a vault's frozen\n * epochs. Used for every existing-vault path (resume, payout, refund).\n */\n getOperationKeysAtEpochs(\n query: OperationKeyQuery,\n epochs: KeyEpochs,\n ): Promise<RawOperationKeys>;\n /**\n * Resolve the VP's commission payout script and each keeper's payout script\n * at a vault's frozen epochs.\n *\n * The registry backfills BIP-86 P2TR of the epoch's operation key for any\n * operator that never called `setPayoutScript`, so this returns byte-identical\n * results to local BIP-86 derivation until an operator registers a custom\n * script.\n */\n getPayoutScriptsAtEpochs(\n query: OperationKeyQuery,\n epochs: KeyEpochs,\n ): Promise<RawPayoutScripts>;\n}\n"],"names":["resolveProtocolAddresses","publicClient","btcVaultRegistryAddress","protocolParams","applicationRegistry","BTCVaultRegistryABI","assertMulticallLength","actual","expected","label","partition","results","keeperCount","ViemOperationKeyReader","contracts","calls","challengerCount","blockNumber","query","keeper","ApplicationRegistryABI","challenger","ProtocolParamsABI","epochs","UINT16_MAX","mapOffchainParams","result","mapTBVParams","deriveTimelockPegin","timelockAssert","ViemProtocolParamsReader","contractAddress","params","validateTBVProtocolParams","validateOffchainParams","version","raw","assertValidOffchainParamsVersion","tbvParams","offchainParams","offchainParamsVersion","activeVaultCoreVersion","config","validatePegInConfiguration","onSkippedVersion","latestVersion","versions","_","i","v","byVersion","error","mapKeyPairs","pair","assertKeyEpoch","ViemVaultKeeperReader","appEntryPoint","ViemUniversalChallengerReader","OnChainBtcVaultStatus"],"mappings":"yKA8BA,eAAsBA,EACpBC,EACAC,EAC4B,CAC5B,KAAM,CAACC,EAAgBC,CAAmB,EAAI,MAAMH,EAAa,UAAU,CACzE,UAAW,CACT,CACE,QAASC,EACT,IAAKG,EAAAA,oBACL,aAAc,gBAAA,EAEhB,CACE,QAASH,EACT,IAAKG,EAAAA,oBACL,aAAc,qBAAA,CAChB,EAEF,aAAc,EAAA,CACf,EAED,MAAO,CACL,eAAAF,EACA,oBAAAC,CAAA,CAEJ,CCTA,SAASE,EACPC,EACAC,EACAC,EACM,CACN,GAAIF,IAAWC,EACb,MAAM,IAAI,MACR,GAAGC,CAAK,wBAAwBF,CAAM,gBAAgBC,CAAQ,qEAAA,CAIpE,CAYA,SAASE,EACPC,EACAC,EACoE,CACpE,MAAO,CACL,cAAeD,EAAQ,CAAC,EACxB,aAAcA,EAAQ,MAAM,EAAG,EAAIC,CAAW,EAC9C,qBAAsBD,EAAQ,MAAM,EAAIC,CAAW,CAAA,CAEvD,CAWO,MAAMC,CAAqD,CAChE,YACUZ,EACAa,EACR,CAFQ,KAAA,aAAAb,EACA,KAAA,UAAAa,CACP,CAQH,MAAc,QACZC,EACAH,EACAI,EACAP,EACAQ,EACA,CACA,MAAMN,EAAW,MAAM,KAAK,aAAa,UAAU,CACjD,UAAWI,EACX,aAAc,GACd,YAAAE,CAAA,CACD,EAED,OAAAX,EACEK,EAAQ,OACR,EAAIC,EAAcI,EAClBP,CAAA,EAGKC,EAAUC,EAASC,CAAW,CACvC,CAEA,MAAM,wBACJM,EACAD,EAC2B,CAC3B,MAAMF,EAAgB,CACpB,CACE,QAAS,KAAK,UAAU,iBACxB,IAAKV,EAAAA,oBACL,aAAc,4BACd,KAAM,CAACa,EAAM,uBAAuB,CAAA,EAEtC,GAAGA,EAAM,aAAa,IAAKC,IAAY,CACrC,QAAS,KAAK,UAAU,oBACxB,IAAKC,EAAAA,uBACL,aAAc,4BACd,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A"}
|
package/dist/{verifyKeyPathSchnorrSignature-BVtNwgK6.js → verifyKeyPathSchnorrSignature-BQHNhRj6.js}
RENAMED
|
@@ -2,7 +2,7 @@ import { Transaction as g, Psbt as P, crypto as R, script as y, payments as A }
|
|
|
2
2
|
import { Buffer as l } from "buffer";
|
|
3
3
|
import { getPrePeginHtlcConnectorInfo as K, tapInternalPubkey as W } from "./tbv/core/wasm/index.js";
|
|
4
4
|
import { s as w, u as v, T as C, h as _ } from "./bitcoin-C-TuHb-v.js";
|
|
5
|
-
import { l as U } from "./verifyScriptPathSchnorrSignature-
|
|
5
|
+
import { l as U } from "./verifyScriptPathSchnorrSignature-CpjSTfMj.js";
|
|
6
6
|
import * as T from "@bitcoin-js/tiny-secp256k1-asmjs";
|
|
7
7
|
async function ft(t) {
|
|
8
8
|
const r = w(t.peginTxHex), n = w(t.fundedPrePeginTxHex);
|
|
@@ -357,4 +357,4 @@ export {
|
|
|
357
357
|
pt as e,
|
|
358
358
|
lt as f
|
|
359
359
|
};
|
|
360
|
-
//# sourceMappingURL=verifyKeyPathSchnorrSignature-
|
|
360
|
+
//# sourceMappingURL=verifyKeyPathSchnorrSignature-BQHNhRj6.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"verifyKeyPathSchnorrSignature-BVtNwgK6.js","sources":["../src/tbv/core/primitives/psbt/peginInput.ts","../src/tbv/core/utils/witness/witnessStack.ts","../src/tbv/core/primitives/psbt/verifyP2wpkhEcdsaSignature.ts","../src/tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature.ts"],"sourcesContent":["/**\n * PegIn Input PSBT Builder\n *\n * Builds the PSBT for the depositor to sign the PegIn transaction's HTLC input\n * (Pre-PegIn HTLC leaf 0 — the hashlock + all-party script).\n *\n * This is the \"Sign Pegin transaction HTLC leaf 0 input\" step in the pre-pegin\n * flow. The depositor signs input 0 of the PegIn transaction,\n * which spends output 0 of the funded Pre-PegIn transaction via script-path.\n *\n * @module primitives/psbt/peginInput\n */\n\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\nimport {\n getPrePeginHtlcConnectorInfo,\n tapInternalPubkey,\n type Network,\n} from \"../../wasm\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\n\nimport { deriveExpectedPrePeginHtlc } from \"./assertWasmPeginSizing\";\n\n/**\n * Parameters for building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtParams {\n /**\n * Vault core (tx-graph) version the Pre-PegIn was built with. Must match\n * the version passed to buildPrePeginPsbt() so the HTLC connector scripts\n * are derived for the same graph.\n */\n vaultCoreVersion: number;\n /**\n * PegIn transaction hex (1 input spending Pre-PegIn HTLC output 0).\n * Returned by buildPeginTxFromFundedPrePegin().\n */\n peginTxHex: string;\n /**\n * Funded Pre-PegIn transaction hex.\n * Used to look up the HTLC output that the PegIn input spends.\n */\n fundedPrePeginTxHex: string;\n /** Depositor's BTC public key (x-only, 64-char hex) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment (64 hex chars = 32 bytes) */\n hashlock: string;\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Bitcoin network */\n network: Network;\n}\n\n/**\n * Result of building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtResult {\n /** PSBT hex for the depositor to sign */\n psbtHex: string;\n}\n\n/**\n * Build PSBT for depositor to sign the PegIn transaction's HTLC leaf 0 input.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output (output 0) via the\n * hashlock + all-party script (leaf 0). The depositor provides one of the required\n * signatures; the vault provider and keepers provide theirs separately via the\n * signPeginInput RPC.\n *\n * The PSBT uses Taproot script-path spending:\n * - witnessUtxo: the Pre-PegIn HTLC output\n * - tapLeafScript: hashlock leaf script + control block\n * - tapInternalKey: NUMS unspendable key (BIP-341 nothing-up-my-sleeve)\n *\n * @param params - PegIn input PSBT parameters\n * @returns PSBT hex ready for depositor signing\n * @throws If PegIn tx does not have exactly 1 input\n * @throws If PegIn input does not reference the Pre-PegIn HTLC output\n * @throws If Pre-PegIn tx output 0 is not found\n */\nexport async function buildPeginInputPsbt(\n params: BuildPeginInputPsbtParams,\n): Promise<BuildPeginInputPsbtResult> {\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const fundedPrePeginTxHex = stripHexPrefix(params.fundedPrePeginTxHex);\n\n // Keep the facade's graph-version and input checks. Do not use its scripts\n // or control block as signing data.\n await getPrePeginHtlcConnectorInfo({\n txGraphVersion: params.vaultCoreVersion,\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlock: params.hashlock,\n timelockRefund: params.timelockRefund,\n network: params.network,\n });\n const expectedHtlc = deriveExpectedPrePeginHtlc(params, params.hashlock);\n\n const peginTx = Transaction.fromHex(peginTxHex);\n const prePeginTx = Transaction.fromHex(fundedPrePeginTxHex);\n\n if (peginTx.ins.length !== 1) {\n throw new Error(\n `PegIn transaction must have exactly 1 input, got ${peginTx.ins.length}`,\n );\n }\n\n const peginInput = peginTx.ins[0];\n\n // Verify PegIn input 0 spends Pre-PegIn output 0\n const prePeginTxid = prePeginTx.getId();\n const peginInputTxid = uint8ArrayToHex(\n new Uint8Array(peginInput.hash).slice().reverse(),\n );\n\n if (peginInputTxid !== prePeginTxid) {\n throw new Error(\n `PegIn input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${peginInputTxid}`,\n );\n }\n\n const htlcOutput = prePeginTx.outs[peginInput.index];\n if (!htlcOutput) {\n throw new Error(\n `Pre-PegIn output ${peginInput.index} not found ` +\n `(Pre-PegIn has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n if (!expectedHtlc.scriptPubKey.equals(htlcOutput.script)) {\n throw new Error(\n \"PegIn HTLC taptree mismatch: the independent 2-leaf tree does not \" +\n \"reproduce the funded Pre-PegIn HTLC scriptPubKey; refusing to sign.\",\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(peginTx.version);\n psbt.setLocktime(peginTx.locktime);\n\n // Input 0: PegIn input spending Pre-PegIn HTLC output 0 via hashlock leaf (leaf 0).\n // The depositor signs using Taproot script-path spending. bitcoinjs\n // re-verifies leaf-in-tree consistency (control block vs tapMerkleRoot)\n // inside addInput — a second independent check.\n psbt.addInput({\n hash: peginInput.hash,\n index: peginInput.index,\n sequence: peginInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: expectedHtlc.hashlockScript,\n controlBlock: expectedHtlc.hashlockControlBlock,\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n tapMerkleRoot: expectedHtlc.tapMerkleRoot,\n // sighashType omitted — defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n for (const output of peginTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n}\n\n/**\n * Extract the depositor's Schnorr signature from a signed PegIn input PSBT.\n *\n * Supports non-finalized PSBTs with tapScriptSig entries. Finalized PSBTs are\n * rejected because the witness stack does not reliably identify the depositor\n * signature by public key.\n *\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Signatures with an appended sighash byte\n * are rejected rather than stripped.\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's x-only public key (64-char hex)\n * @returns 64-byte Schnorr signature (128 hex chars, no sighash flag)\n * @throws If no signature is found for the depositor's key\n */\nexport function extractPeginInputSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n const input = signedPsbt.data.inputs[0];\n\n if (!input) {\n throw new Error(\"PegIn PSBT has no inputs\");\n }\n\n // Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = Buffer.from(hexToUint8Array(depositorPubkey));\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(depositorPubkeyBytes)) {\n return extractSchnorrSig(sigEntry.signature);\n }\n }\n\n throw new Error(\n `No PegIn input signature found for depositor pubkey: ${depositorPubkey}`,\n );\n }\n\n // Finalized PSBT — the witness stack order depends on the wallet's finalizer,\n // so we cannot reliably pick the depositor's signature by position. Require\n // the non-finalized tapScriptSig path which identifies signatures by pubkey.\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n throw new Error(\n \"PegIn input PSBT is already finalized. Cannot reliably extract the \" +\n \"depositor signature from the witness stack. Ensure the wallet returns \" +\n \"a non-finalized PSBT with tapScriptSig entries.\",\n );\n }\n\n throw new Error(\n \"No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT\",\n );\n}\n\n/**\n * Finalize a signed PegIn input PSBT and return the depositor-signed transaction hex.\n *\n * The default tapscript finalizer builds the full witness stack [sig, script, controlBlock]\n * that vaultd requires when verifying the depositor signature on-chain.\n *\n * @param signedPsbtHex - Non-finalized signed PSBT hex (returned by wallet with autoFinalized: false)\n * @returns Depositor-signed PegIn transaction hex with full taproot witness stack\n */\nexport function finalizePeginInputPsbt(signedPsbtHex: string): string {\n const psbt = Psbt.fromHex(signedPsbtHex);\n\n // Some wallets (UniSat, OKX) ignore autoFinalized: false and return\n // already-finalized PSBTs. finalizeAllInputs() throws in that case,\n // so fall back to verifying the wallet already finalized all inputs.\n try {\n psbt.finalizeAllInputs();\n } catch (e) {\n const allFinalized = psbt.data.inputs.every(\n (inp) => inp.finalScriptWitness || inp.finalScriptSig,\n );\n if (!allFinalized) {\n throw new Error(\n `PSBT finalization failed and wallet did not auto-finalize: ${e}`,\n );\n }\n }\n\n return psbt.extractTransaction().toHex();\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature.\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Reject 65-byte signatures instead of\n * stripping the sighash byte because it changes the signed Taproot message.\n * @internal\n */\nexport function extractSchnorrSig(sig: Uint8Array): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n }\n if (sig.length === 65) {\n throw new Error(\n `Unexpected sighash byte 0x${sig[64].toString(16).padStart(2, \"0\")} in PegIn input signature. ` +\n \"Expected implicit SIGHASH_DEFAULT as a 64-byte signature.\",\n );\n }\n throw new Error(`Unexpected PegIn input signature length: ${sig.length}`);\n}\n","/**\n * Consensus witness-stack decoding, shared by every module that reads a\n * witness we did not build.\n *\n * Two independent decoders drifted apart before this existed: one accepted\n * non-minimal CompactSize encodings, the other rejected them. vaultd decodes\n * with rust-bitcoin, whose `VarInt::consensus_decode`\n * (0.32.8 `consensus/encode.rs:493-522`) returns `NonMinimalVarInt` for a 0xfd\n * carrying < 0xfd and a 0xfe carrying < 0x10000 — so the strict reading is the\n * only one that matches what the network will accept.\n *\n * @module tbv/core/utils/witness/witnessStack\n */\n\n/** CompactSize discriminators; 0xff (u64) is out of range for a witness. */\nconst COMPACT_SIZE_UINT16_PREFIX = 0xfd;\nconst COMPACT_SIZE_UINT32_PREFIX = 0xfe;\nconst COMPACT_SIZE_UINT16_BYTES = 3;\nconst COMPACT_SIZE_UINT32_BYTES = 5;\nconst COMPACT_SIZE_UINT16_MIN_VALUE = 0xfd;\nconst COMPACT_SIZE_UINT32_MIN_VALUE = 0x10000;\n\n/**\n * Decode a consensus-encoded witness stack: item count, then (len, bytes)*.\n *\n * @param witness - The consensus-encoded witness bytes.\n * @param subject - Names the witness in error messages (e.g. \"finalScriptWitness\").\n * @returns The stack items, as views over `witness`.\n * @throws If the encoding is truncated, non-minimal, out of range, or leaves\n * trailing bytes.\n */\nexport function decodeWitnessStack(\n witness: Uint8Array,\n subject: string,\n): Uint8Array[] {\n let offset = 0;\n\n const readCompactSize = (): number => {\n if (offset >= witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const first = witness[offset];\n if (first < COMPACT_SIZE_UINT16_PREFIX) {\n offset += 1;\n return first;\n }\n if (first === COMPACT_SIZE_UINT16_PREFIX) {\n if (offset + COMPACT_SIZE_UINT16_BYTES > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const value = witness[offset + 1] | (witness[offset + 2] << 8);\n if (value < COMPACT_SIZE_UINT16_MIN_VALUE) {\n throw new Error(`${subject} has a non-minimal length encoding`);\n }\n offset += COMPACT_SIZE_UINT16_BYTES;\n return value;\n }\n if (first === COMPACT_SIZE_UINT32_PREFIX) {\n if (offset + COMPACT_SIZE_UINT32_BYTES > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const value =\n (witness[offset + 1] |\n (witness[offset + 2] << 8) |\n (witness[offset + 3] << 16) |\n (witness[offset + 4] << 24)) >>>\n 0;\n if (value < COMPACT_SIZE_UINT32_MIN_VALUE) {\n throw new Error(`${subject} has a non-minimal length encoding`);\n }\n offset += COMPACT_SIZE_UINT32_BYTES;\n return value;\n }\n throw new Error(`${subject} carries an out-of-range item length`);\n };\n\n const count = readCompactSize();\n const items: Uint8Array[] = [];\n for (let i = 0; i < count; i++) {\n const len = readCompactSize();\n if (offset + len > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n items.push(witness.subarray(offset, offset + len));\n offset += len;\n }\n if (offset !== witness.length) {\n throw new Error(`${subject} has trailing bytes`);\n }\n return items;\n}\n","/**\n * Far-side verification of P2WPKH ECDSA signatures a wallet returned, over\n * the PSBT we requested (trusted prevouts) — the Native SegWit sibling of\n * `verifyKeyPathSchnorrSignature`. Reference: btc-vault\n * `crates/btc-wallet-remote/src/client.rs:945-1000\n * verify_finalized_p2wpkh_spend`. The wallet's success/finalization is\n * never trusted on its own (CLAUDE.md §8): prevout script and value come\n * from the PSBT we built; only the signature bytes come from the wallet.\n *\n * @module tbv/core/primitives/psbt/verifyP2wpkhEcdsaSignature\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport {\n crypto as bcrypto,\n script as bscript,\n payments,\n Psbt,\n Transaction,\n} from \"bitcoinjs-lib\";\n\nimport { Buffer } from \"buffer\";\n\nimport { decodeWitnessStack } from \"../../utils/witness/witnessStack\";\n\n// P2WPKH scriptPubKey is exactly `OP_0 OP_PUSHBYTES_20 <20-byte key hash>`\n// (BIP-141 witness program v0, 20 bytes).\nconst P2WPKH_SCRIPT_LEN = 22;\nconst OP_0 = 0x00;\nconst OP_PUSHBYTES_20 = 0x14;\nconst P2WPKH_PROGRAM_START = 2;\n\n/** SEC1 compressed pubkey (client.rs:959: \"expected a 33-byte compressed key\"). */\nconst COMPRESSED_PUBKEY_BYTES = 33;\n/** Consensus P2WPKH witness: exactly [signature, pubkey] (client.rs:951-957). */\nconst P2WPKH_WITNESS_ITEMS = 2;\n\n/** Only claim P2WPKH: 22-byte scriptPubKey starting `OP_0 PUSH20`. */\nexport function isP2wpkhScript(\n script: Uint8Array | undefined,\n): script is Uint8Array {\n return (\n script !== undefined &&\n script.length === P2WPKH_SCRIPT_LEN &&\n script[0] === OP_0 &&\n script[1] === OP_PUSHBYTES_20\n );\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((byte, i) => byte === b[i]);\n}\n\n/** The `[signature, pubkey]` pair of a finalized P2WPKH witness (client.rs:951-957). */\nfunction decodeP2wpkhWitness(\n finalScriptWitness: Uint8Array,\n inputIndex: number,\n): { signature: Uint8Array; pubkey: Uint8Array } {\n const items = decodeWitnessStack(finalScriptWitness, \"finalScriptWitness\");\n if (items.length !== P2WPKH_WITNESS_ITEMS) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a finalized P2WPKH witness must have ` +\n `exactly 2 items [signature, pubkey], got ${items.length}.`,\n );\n }\n return { signature: items[0], pubkey: items[1] };\n}\n\nexport interface AssertReturnedP2wpkhSignatureParams {\n /** Hex of the PSBT we built and sent (trusted prevout script/value). NOT the wallet's. */\n requestedPsbtHex: string;\n /** The wallet-returned PSBT input carrying the signature material. */\n returnedInput: {\n partialSig?: Array<{ pubkey: Uint8Array; signature: Uint8Array }>;\n finalScriptWitness?: Uint8Array;\n };\n /** Index of the input the signature is for. */\n inputIndex: number;\n}\n\n/**\n * Assert that the returned input carries a valid P2WPKH ECDSA signature\n * over the BIP-143 sighash of `requestedPsbtHex` input `inputIndex`:\n * `partialSig` (BIP-174: the value is the exact witness-stack signature\n * bytes, the key its pubkey), or the finalized 2-item witness — and when\n * both are present they must be the same bytes.\n *\n * @throws If the requested input is not a P2WPKH spend, no signature was\n * returned, a finalized witness disagrees with its `partialSig`,\n * or any check of `verify_finalized_p2wpkh_spend` fails.\n */\nexport function assertReturnedP2wpkhSignature(\n params: AssertReturnedP2wpkhSignatureParams,\n): void {\n const { requestedPsbtHex, returnedInput, inputIndex } = params;\n\n const partials = returnedInput.partialSig;\n // Consensus allows exactly one signature in a P2WPKH witness, so a second\n // partialSig entry is ambiguous tampering, not a fallback to pick from.\n if (partials !== undefined && partials.length > 1) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a P2WPKH input must carry at most one ` +\n `partial signature, got ${partials.length}.`,\n );\n }\n const partial = partials?.[0];\n const witness = returnedInput.finalScriptWitness\n ? decodeP2wpkhWitness(returnedInput.finalScriptWitness, inputIndex)\n : undefined;\n\n // Both fields can be present, and the consumers broadcast the WITNESS\n // bytes — so the two must agree, not just one of them verify (same\n // rationale as the tapKeySig/witness agreement check).\n if (\n partial &&\n witness &&\n (!bytesEqual(partial.signature, witness.signature) ||\n !bytesEqual(partial.pubkey, witness.pubkey))\n ) {\n throw new Error(\n `Returned PSBT input ${inputIndex} finalized witness does not match its partialSig.`,\n );\n }\n\n const material = partial ?? witness;\n if (!material) {\n throw new Error(\n `Returned PSBT input ${inputIndex} carries no P2WPKH signature ` +\n `(no partialSig, not finalized).`,\n );\n }\n\n assertP2wpkhEcdsaSignature(\n requestedPsbtHex,\n material.signature,\n material.pubkey,\n inputIndex,\n );\n}\n\n/**\n * The crypto core, mirroring `verify_finalized_p2wpkh_spend` check by\n * check: pubkey shape and curve membership, hash160(pubkey) == witness\n * program, strict-DER + SIGHASH_ALL-only signature, ECDSA over the\n * BIP-143 sighash recomputed from the REQUESTED prevout.\n */\nfunction assertP2wpkhEcdsaSignature(\n requestedPsbtHex: string,\n encodedSignature: Uint8Array,\n pubkey: Uint8Array,\n inputIndex: number,\n): void {\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (inputIndex < 0 || inputIndex >= psbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${psbt.data.inputs.length} inputs).`,\n );\n }\n const prevout = psbt.data.inputs[inputIndex].witnessUtxo;\n if (!prevout || !isP2wpkhScript(prevout.script)) {\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is not a P2WPKH input.`,\n );\n }\n\n // Pubkey: exactly 33 bytes (client.rs:959-965) and a parseable curve\n // point, as PublicKey::from_slice (client.rs:966-968).\n if (pubkey.length !== COMPRESSED_PUBKEY_BYTES) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey must be 33 bytes, ` +\n `got ${pubkey.length}.`,\n );\n }\n if (!ecc.isPointCompressed(pubkey)) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey is not a valid secp256k1 point.`,\n );\n }\n\n // hash160(pubkey) must equal the prevout's witness program — what\n // consensus checks (client.rs:970-977).\n const program = prevout.script.subarray(\n P2WPKH_PROGRAM_START,\n P2WPKH_SCRIPT_LEN,\n );\n if (!bytesEqual(bcrypto.hash160(Buffer.from(pubkey)), program)) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey does not hash to the ` +\n `prevout's witness program.`,\n );\n }\n\n // Strict-DER decode with defined-hashtype gate — the accept set of\n // ecdsa::Signature::from_slice / EcdsaSighashType::from_standard\n // (client.rs:978-980) — then SIGHASH_ALL exactly (client.rs:981-987).\n let decoded: { signature: Buffer; hashType: number };\n try {\n decoded = bscript.signature.decode(Buffer.from(encodedSignature));\n } catch (e) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature is not DER with a ` +\n `defined sighash byte: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n // decode tolerates non-minimal integers (bip66.js never bounds lenR/lenS at 33;\n // fromDER truncates, script_signature.js:29-35) that libsecp's strict consensus\n // parse rejects (secp256k1-sys ecdsa_impl.h:127-136) — require the unique\n // minimal encoding by re-encoding and byte-comparing.\n if (\n !bscript.signature\n .encode(decoded.signature, decoded.hashType)\n .equals(Buffer.from(encodedSignature))\n ) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature is not canonical DER.`,\n );\n }\n if (decoded.hashType !== Transaction.SIGHASH_ALL) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature has sighash type ` +\n `0x${decoded.hashType.toString(16)} (expected SIGHASH_ALL).`,\n );\n }\n\n // BIP-143 sighash over the REQUESTED prevout value with the standard\n // P2WPKH scriptCode built from the witness program (client.rs:988-991;\n // scriptCode template per bitcoinjs-lib's own P2WPKH signer,\n // `src/psbt.js:1245-1255`).\n const scriptCode = payments.p2pkh({ hash: Buffer.from(program) }).output;\n if (!scriptCode) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: could not build the P2WPKH scriptCode.`,\n );\n }\n const tx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());\n const sighash = tx.hashForWitnessV0(\n inputIndex,\n scriptCode,\n prevout.value,\n decoded.hashType,\n );\n\n // strict=true rejects high-S, as libsecp256k1's verify_ecdsa does\n // (client.rs:992-999; secp256k1 crate `ecdsa/mod.rs:194`). ecc.verify\n // throws on out-of-range r/s — that is a failed verification here.\n let verifies = false;\n try {\n verifies = ecc.verify(sighash, pubkey, decoded.signature, true);\n } catch {\n verifies = false;\n }\n if (!verifies) {\n throw new Error(\n `P2WPKH signature for input ${inputIndex} does not verify against the ` +\n `requested PSBT's prevout. The wallet may have signed a different ` +\n `transaction or key.`,\n );\n }\n}\n","/**\n * Far-side verification of Taproot KEY-PATH Schnorr signatures a wallet\n * returned, over the PSBT we requested (trusted prevouts) — the key-path twin\n * of `assertScriptPathSchnorrSignature`. Reference: btc-vault\n * `crates/btc-wallet-remote/src/client.rs check_signatures_valid` (output key taken\n * from the prevout scriptPubKey, all prevouts committed). The wallet's\n * success/finalization is never trusted on its own (CLAUDE.md §8).\n * `assertReturnedKeyPathSignatures` additionally dispatches P2WPKH-funded\n * inputs to `verifyP2wpkhEcdsaSignature` (client.rs's\n * `verify_finalized_p2wpkh_spend` sibling), so a Native SegWit software\n * wallet's signatures no longer pass through unchecked.\n *\n * Why verify against the *requested* PSBT: `assertPsbtUnsignedTxMatches` pins\n * the unsigned transaction but deliberately skips per-input metadata, so a\n * wallet could rewrite `witnessUtxo` in its response and make a wrong-message\n * signature self-validate. Prevout scripts and values therefore come from the\n * PSBT we built; only the signature bytes come from the wallet.\n *\n * @module tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { Buffer } from \"buffer\";\n\nimport { decodeWitnessStack } from \"../../utils/witness/witnessStack\";\nimport { hexToUint8Array, stripHexPrefix } from \"../utils/bitcoin\";\nimport {\n assertReturnedP2wpkhSignature,\n isP2wpkhScript,\n} from \"./verifyP2wpkhEcdsaSignature\";\n\nconst SCHNORR_SIG_BYTES = 64;\nconst SIGHASH_DEFAULT = Transaction.SIGHASH_DEFAULT; // 0x00\nconst SIGHASH_ALL = Transaction.SIGHASH_ALL; // 0x01\n\n// P2TR scriptPubKey is exactly `OP_1 OP_PUSHBYTES_32 <32-byte output key>`.\nconst P2TR_SCRIPT_LEN = 34;\nconst OP_1 = 0x51;\nconst OP_PUSHBYTES_32 = 0x20;\nconst P2TR_OUTPUT_KEY_OFFSET = 2;\n\nfunction isP2trScript(script: Uint8Array | undefined): script is Uint8Array {\n return (\n script !== undefined &&\n script.length === P2TR_SCRIPT_LEN &&\n script[0] === OP_1 &&\n script[1] === OP_PUSHBYTES_32\n );\n}\n\n/** BIP-341: 64 bytes ⇒ SIGHASH_DEFAULT; 65 bytes ⇒ the trailing byte is the hash type (we accept ALL only). */\nfunction splitHashType(\n sig: Uint8Array,\n inputIndex: number,\n): { signature: Uint8Array; hashType: number } {\n if (sig.length === SCHNORR_SIG_BYTES) {\n return { signature: sig, hashType: SIGHASH_DEFAULT };\n }\n if (\n sig.length === SCHNORR_SIG_BYTES + 1 &&\n sig[SCHNORR_SIG_BYTES] === SIGHASH_ALL\n ) {\n return {\n signature: sig.subarray(0, SCHNORR_SIG_BYTES),\n hashType: SIGHASH_ALL,\n };\n }\n throw new Error(\n `Key-path signature for input ${inputIndex} must be 64 bytes (SIGHASH_DEFAULT) or ` +\n `65 bytes ending in 0x01 (SIGHASH_ALL), got ${sig.length}.`,\n );\n}\n\nexport interface AssertKeyPathSchnorrSignatureParams {\n /** Hex of the PSBT we built and sent (trusted prevout scripts/values). NOT the wallet's. */\n requestedPsbtHex: string;\n /** 64- or 65-byte signature, hex. */\n signatureHex: string;\n /** Index of the input the signature is for. */\n inputIndex: number;\n}\n\n/**\n * Assert that `signatureHex` is a valid BIP-340 Schnorr signature over the\n * Taproot key-path sighash of `requestedPsbtHex` input `inputIndex`, under the\n * tweaked output key taken from that input's prevout scriptPubKey.\n *\n * @throws If the input is not a key-path P2TR spend, the requested PSBT lacks\n * the prevout data needed to recompute the sighash, or the signature\n * does not verify.\n */\nexport function assertKeyPathSchnorrSignature(\n params: AssertKeyPathSchnorrSignatureParams,\n): void {\n const { requestedPsbtHex, signatureHex, inputIndex } = params;\n\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (inputIndex < 0 || inputIndex >= psbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${psbt.data.inputs.length} inputs).`,\n );\n }\n\n if (!isKeyPathEligible(psbt.data.inputs[inputIndex])) {\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is not a key-path P2TR input.`,\n );\n }\n\n // Taproot's sighash commits to every input's prevout (script + value), so all\n // inputs must carry a witnessUtxo. A missing one is a build error, not a\n // value we can default — fail loudly.\n const prevOutScripts: Buffer[] = [];\n const values: number[] = [];\n for (let i = 0; i < psbt.data.inputs.length; i++) {\n const prevout = psbt.data.inputs[i].witnessUtxo;\n if (!prevout) {\n throw new Error(\n `Cannot verify signature: input ${i} of the requested PSBT has no witnessUtxo ` +\n `(required to recompute the Taproot sighash).`,\n );\n }\n prevOutScripts.push(prevout.script);\n values.push(prevout.value);\n }\n\n const { signature, hashType } = splitHashType(\n hexToUint8Array(stripHexPrefix(signatureHex)),\n inputIndex,\n );\n\n const tx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());\n const sighash = tx.hashForWitnessV1(\n inputIndex,\n prevOutScripts,\n values,\n hashType,\n );\n\n // Key-path signatures verify against the TWEAKED output key = the prevout's\n // witness program.\n const outputKey = prevOutScripts[inputIndex].subarray(P2TR_OUTPUT_KEY_OFFSET);\n\n if (!ecc.verifySchnorr(sighash, outputKey, signature)) {\n throw new Error(\n `Key-path Schnorr signature for input ${inputIndex} does not verify against the ` +\n `requested PSBT's prevout (output key ${Buffer.from(outputKey).toString(\"hex\")}). ` +\n `The wallet may have signed a different transaction or key.`,\n );\n }\n}\n\n/**\n * A key-path P2TR input: an internal key, no script-path material, and a\n * taproot prevout. Script-path inputs are the script-path verifier's job.\n */\nfunction isKeyPathEligible(input: {\n tapInternalKey?: Uint8Array;\n tapLeafScript?: unknown;\n tapMerkleRoot?: Uint8Array;\n witnessUtxo?: { script: Uint8Array };\n}): boolean {\n return (\n input.tapInternalKey !== undefined &&\n input.tapLeafScript === undefined &&\n input.tapMerkleRoot === undefined &&\n isP2trScript(input.witnessUtxo?.script)\n );\n}\n\n/**\n * The lone stack item of a finalized key-path witness. An annex would add a\n * second item, but Bitcoin Core rejects annexes as nonstandard\n * (`src/policy/policy.cpp:327-329`), so such a spend could never broadcast.\n */\nfunction singleWitnessItem(\n finalScriptWitness: Uint8Array,\n inputIndex: number,\n): Uint8Array {\n const items = decodeWitnessStack(finalScriptWitness, \"finalScriptWitness\");\n if (items.length !== 1) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a finalized key-path witness must have ` +\n `exactly one item, got ${items.length}.`,\n );\n }\n return items[0];\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((byte, i) => byte === b[i]);\n}\n\nexport interface AssertReturnedKeyPathSignaturesParams {\n /** PSBT we built locally and asked the wallet to sign. */\n requestedPsbtHex: string;\n /** PSBT the wallet returned after signing. */\n returnedPsbtHex: string;\n}\n\n/**\n * Verify every key-path-eligible and P2WPKH input of the REQUESTED PSBT\n * against what the wallet RETURNED. Key-path: `tapKeySig`, or the single\n * finalized witness item for wallets that auto-finalize — and when both are\n * present they must be the same bytes. P2WPKH: `partialSig`, or the finalized\n * 2-item witness, verified as ECDSA over the BIP-143 sighash\n * ({@link assertReturnedP2wpkhSignature}); a failure throws but the input is\n * NOT counted. Any other input type (script-path, P2WSH, ...) throws — no\n * verifier here covers it, so it cannot be treated as verified.\n *\n * @returns How many inputs were verified KEY-PATH. A caller that knows every\n * input is taproot key-path (e.g. an approval wallet) must assert\n * this equals its input count — P2WPKH inputs never count toward it,\n * so that gate stays exact.\n * @throws If the input counts differ, an input is neither key-path P2TR nor\n * P2WPKH, an eligible input carries no signature, a finalized witness\n * disagrees with its `tapKeySig`/`partialSig`, or any signature does\n * not verify.\n */\nexport function assertReturnedKeyPathSignatures(\n params: AssertReturnedKeyPathSignaturesParams,\n): number {\n const { requestedPsbtHex, returnedPsbtHex } = params;\n\n const requested = Psbt.fromHex(requestedPsbtHex);\n const returned = Psbt.fromHex(returnedPsbtHex);\n\n if (returned.data.inputs.length !== requested.data.inputs.length) {\n throw new Error(\n `Returned PSBT input count ${returned.data.inputs.length} differs from the ` +\n `requested ${requested.data.inputs.length}.`,\n );\n }\n\n let verified = 0;\n requested.data.inputs.forEach((input, inputIndex) => {\n const returnedInput = returned.data.inputs[inputIndex];\n\n if (!isKeyPathEligible(input)) {\n // Native SegWit funding inputs get the ECDSA check.\n if (isP2wpkhScript(input.witnessUtxo?.script)) {\n assertReturnedP2wpkhSignature({\n requestedPsbtHex,\n returnedInput,\n inputIndex,\n });\n return;\n }\n // No verifier exists for any other type — fail closed like btc-vault's\n // check_signatures_valid rather than silently reporting it checked.\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is neither key-path P2TR ` +\n `nor P2WPKH; refusing to treat it as verified.`,\n );\n }\n verified++;\n\n const tapKeySig = returnedInput.tapKeySig;\n const witnessSig = returnedInput.finalScriptWitness\n ? singleWitnessItem(returnedInput.finalScriptWitness, inputIndex)\n : undefined;\n\n // Both fields can be present, and the consumers broadcast the WITNESS\n // bytes — so the two must agree, not just one of them verify. Matches\n // btc-vault `crates/btc-wallet-remote/src/client.rs:1053-1072,1102-1121`,\n // which checks each independently.\n if (tapKeySig && witnessSig && !bytesEqual(tapKeySig, witnessSig)) {\n throw new Error(\n `Returned PSBT input ${inputIndex} finalized witness does not match its tapKeySig.`,\n );\n }\n\n const sig = tapKeySig ?? witnessSig;\n if (!sig) {\n throw new Error(\n `Returned PSBT input ${inputIndex} carries no key-path signature ` +\n `(no tapKeySig, not finalized).`,\n );\n }\n\n assertKeyPathSchnorrSignature({\n requestedPsbtHex,\n signatureHex: Buffer.from(sig).toString(\"hex\"),\n inputIndex,\n });\n });\n\n return verified;\n}\n"],"names":["buildPeginInputPsbt","params","peginTxHex","stripHexPrefix","fundedPrePeginTxHex","getPrePeginHtlcConnectorInfo","expectedHtlc","deriveExpectedPrePeginHtlc","peginTx","Transaction","prePeginTx","peginInput","prePeginTxid","peginInputTxid","uint8ArrayToHex","htlcOutput","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPeginInputSignature","signedPsbtHex","depositorPubkey","input","depositorPubkeyBytes","hexToUint8Array","sigEntry","extractSchnorrSig","finalizePeginInputPsbt","e","inp","sig","COMPACT_SIZE_UINT16_PREFIX","COMPACT_SIZE_UINT32_PREFIX","COMPACT_SIZE_UINT16_BYTES","COMPACT_SIZE_UINT32_BYTES","COMPACT_SIZE_UINT16_MIN_VALUE","COMPACT_SIZE_UINT32_MIN_VALUE","decodeWitnessStack","witness","subject","offset","readCompactSize","first","value","count","items","i","len","P2WPKH_SCRIPT_LEN","OP_0","OP_PUSHBYTES_20","P2WPKH_PROGRAM_START","COMPRESSED_PUBKEY_BYTES","P2WPKH_WITNESS_ITEMS","isP2wpkhScript","script","bytesEqual","a","b","byte","decodeP2wpkhWitness","finalScriptWitness","inputIndex","assertReturnedP2wpkhSignature","requestedPsbtHex","returnedInput","partials","partial","material","assertP2wpkhEcdsaSignature","encodedSignature","pubkey","prevout","ecc","program","bcrypto","decoded","bscript","scriptCode","payments","sighash","verifies","SCHNORR_SIG_BYTES","SIGHASH_DEFAULT","SIGHASH_ALL","P2TR_SCRIPT_LEN","OP_1","OP_PUSHBYTES_32","P2TR_OUTPUT_KEY_OFFSET","isP2trScript","splitHashType","assertKeyPathSchnorrSignature","signatureHex","isKeyPathEligible","prevOutScripts","values","signature","hashType","outputKey","_a","singleWitnessItem","assertReturnedKeyPathSignatures","returnedPsbtHex","requested","returned","verified","tapKeySig","witnessSig"],"mappings":";;;;;;AA4FA,eAAsBA,GACpBC,GACoC;AACpC,QAAMC,IAAaC,EAAeF,EAAO,UAAU,GAC7CG,IAAsBD,EAAeF,EAAO,mBAAmB;AAIrE,QAAMI,EAA6B;AAAA,IACjC,gBAAgBJ,EAAO;AAAA,IACvB,iBAAiB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witness/witnessStack.ts","../src/tbv/core/primitives/psbt/verifyP2wpkhEcdsaSignature.ts","../src/tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature.ts"],"sourcesContent":["/**\n * PegIn Input PSBT Builder\n *\n * Builds the PSBT for the depositor to sign the PegIn transaction's HTLC input\n * (Pre-PegIn HTLC leaf 0 — the hashlock + all-party script).\n *\n * This is the \"Sign Pegin transaction HTLC leaf 0 input\" step in the pre-pegin\n * flow. The depositor signs input 0 of the PegIn transaction,\n * which spends output 0 of the funded Pre-PegIn transaction via script-path.\n *\n * @module primitives/psbt/peginInput\n */\n\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\nimport {\n getPrePeginHtlcConnectorInfo,\n tapInternalPubkey,\n type Network,\n} from \"../../wasm\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\n\nimport { deriveExpectedPrePeginHtlc } from \"./assertWasmPeginSizing\";\n\n/**\n * Parameters for building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtParams {\n /**\n * Vault core (tx-graph) version the Pre-PegIn was built with. Must match\n * the version passed to buildPrePeginPsbt() so the HTLC connector scripts\n * are derived for the same graph.\n */\n vaultCoreVersion: number;\n /**\n * PegIn transaction hex (1 input spending Pre-PegIn HTLC output 0).\n * Returned by buildPeginTxFromFundedPrePegin().\n */\n peginTxHex: string;\n /**\n * Funded Pre-PegIn transaction hex.\n * Used to look up the HTLC output that the PegIn input spends.\n */\n fundedPrePeginTxHex: string;\n /** Depositor's BTC public key (x-only, 64-char hex) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment (64 hex chars = 32 bytes) */\n hashlock: string;\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Bitcoin network */\n network: Network;\n}\n\n/**\n * Result of building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtResult {\n /** PSBT hex for the depositor to sign */\n psbtHex: string;\n}\n\n/**\n * Build PSBT for depositor to sign the PegIn transaction's HTLC leaf 0 input.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output (output 0) via the\n * hashlock + all-party script (leaf 0). The depositor provides one of the required\n * signatures; the vault provider and keepers provide theirs separately via the\n * signPeginInput RPC.\n *\n * The PSBT uses Taproot script-path spending:\n * - witnessUtxo: the Pre-PegIn HTLC output\n * - tapLeafScript: hashlock leaf script + control block\n * - tapInternalKey: NUMS unspendable key (BIP-341 nothing-up-my-sleeve)\n *\n * @param params - PegIn input PSBT parameters\n * @returns PSBT hex ready for depositor signing\n * @throws If PegIn tx does not have exactly 1 input\n * @throws If PegIn input does not reference the Pre-PegIn HTLC output\n * @throws If Pre-PegIn tx output 0 is not found\n */\nexport async function buildPeginInputPsbt(\n params: BuildPeginInputPsbtParams,\n): Promise<BuildPeginInputPsbtResult> {\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const fundedPrePeginTxHex = stripHexPrefix(params.fundedPrePeginTxHex);\n\n // Keep the facade's graph-version and input checks. Do not use its scripts\n // or control block as signing data.\n await getPrePeginHtlcConnectorInfo({\n txGraphVersion: params.vaultCoreVersion,\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlock: params.hashlock,\n timelockRefund: params.timelockRefund,\n network: params.network,\n });\n const expectedHtlc = deriveExpectedPrePeginHtlc(params, params.hashlock);\n\n const peginTx = Transaction.fromHex(peginTxHex);\n const prePeginTx = Transaction.fromHex(fundedPrePeginTxHex);\n\n if (peginTx.ins.length !== 1) {\n throw new Error(\n `PegIn transaction must have exactly 1 input, got ${peginTx.ins.length}`,\n );\n }\n\n const peginInput = peginTx.ins[0];\n\n // Verify PegIn input 0 spends Pre-PegIn output 0\n const prePeginTxid = prePeginTx.getId();\n const peginInputTxid = uint8ArrayToHex(\n new Uint8Array(peginInput.hash).slice().reverse(),\n );\n\n if (peginInputTxid !== prePeginTxid) {\n throw new Error(\n `PegIn input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${peginInputTxid}`,\n );\n }\n\n const htlcOutput = prePeginTx.outs[peginInput.index];\n if (!htlcOutput) {\n throw new Error(\n `Pre-PegIn output ${peginInput.index} not found ` +\n `(Pre-PegIn has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n if (!expectedHtlc.scriptPubKey.equals(htlcOutput.script)) {\n throw new Error(\n \"PegIn HTLC taptree mismatch: the independent 2-leaf tree does not \" +\n \"reproduce the funded Pre-PegIn HTLC scriptPubKey; refusing to sign.\",\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(peginTx.version);\n psbt.setLocktime(peginTx.locktime);\n\n // Input 0: PegIn input spending Pre-PegIn HTLC output 0 via hashlock leaf (leaf 0).\n // The depositor signs using Taproot script-path spending. bitcoinjs\n // re-verifies leaf-in-tree consistency (control block vs tapMerkleRoot)\n // inside addInput — a second independent check.\n psbt.addInput({\n hash: peginInput.hash,\n index: peginInput.index,\n sequence: peginInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: expectedHtlc.hashlockScript,\n controlBlock: expectedHtlc.hashlockControlBlock,\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n tapMerkleRoot: expectedHtlc.tapMerkleRoot,\n // sighashType omitted — defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n for (const output of peginTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n}\n\n/**\n * Extract the depositor's Schnorr signature from a signed PegIn input PSBT.\n *\n * Supports non-finalized PSBTs with tapScriptSig entries. Finalized PSBTs are\n * rejected because the witness stack does not reliably identify the depositor\n * signature by public key.\n *\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Signatures with an appended sighash byte\n * are rejected rather than stripped.\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's x-only public key (64-char hex)\n * @returns 64-byte Schnorr signature (128 hex chars, no sighash flag)\n * @throws If no signature is found for the depositor's key\n */\nexport function extractPeginInputSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n const input = signedPsbt.data.inputs[0];\n\n if (!input) {\n throw new Error(\"PegIn PSBT has no inputs\");\n }\n\n // Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = Buffer.from(hexToUint8Array(depositorPubkey));\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(depositorPubkeyBytes)) {\n return extractSchnorrSig(sigEntry.signature);\n }\n }\n\n throw new Error(\n `No PegIn input signature found for depositor pubkey: ${depositorPubkey}`,\n );\n }\n\n // Finalized PSBT — the witness stack order depends on the wallet's finalizer,\n // so we cannot reliably pick the depositor's signature by position. Require\n // the non-finalized tapScriptSig path which identifies signatures by pubkey.\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n throw new Error(\n \"PegIn input PSBT is already finalized. Cannot reliably extract the \" +\n \"depositor signature from the witness stack. Ensure the wallet returns \" +\n \"a non-finalized PSBT with tapScriptSig entries.\",\n );\n }\n\n throw new Error(\n \"No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT\",\n );\n}\n\n/**\n * Finalize a signed PegIn input PSBT and return the depositor-signed transaction hex.\n *\n * The default tapscript finalizer builds the full witness stack [sig, script, controlBlock]\n * that vaultd requires when verifying the depositor signature on-chain.\n *\n * @param signedPsbtHex - Non-finalized signed PSBT hex (returned by wallet with autoFinalized: false)\n * @returns Depositor-signed PegIn transaction hex with full taproot witness stack\n */\nexport function finalizePeginInputPsbt(signedPsbtHex: string): string {\n const psbt = Psbt.fromHex(signedPsbtHex);\n\n // Some wallets (UniSat, OKX) ignore autoFinalized: false and return\n // already-finalized PSBTs. finalizeAllInputs() throws in that case,\n // so fall back to verifying the wallet already finalized all inputs.\n try {\n psbt.finalizeAllInputs();\n } catch (e) {\n const allFinalized = psbt.data.inputs.every(\n (inp) => inp.finalScriptWitness || inp.finalScriptSig,\n );\n if (!allFinalized) {\n throw new Error(\n `PSBT finalization failed and wallet did not auto-finalize: ${e}`,\n );\n }\n }\n\n return psbt.extractTransaction().toHex();\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature.\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Reject 65-byte signatures instead of\n * stripping the sighash byte because it changes the signed Taproot message.\n * @internal\n */\nexport function extractSchnorrSig(sig: Uint8Array): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n }\n if (sig.length === 65) {\n throw new Error(\n `Unexpected sighash byte 0x${sig[64].toString(16).padStart(2, \"0\")} in PegIn input signature. ` +\n \"Expected implicit SIGHASH_DEFAULT as a 64-byte signature.\",\n );\n }\n throw new Error(`Unexpected PegIn input signature length: ${sig.length}`);\n}\n","/**\n * Consensus witness-stack decoding, shared by every module that reads a\n * witness we did not build.\n *\n * Two independent decoders drifted apart before this existed: one accepted\n * non-minimal CompactSize encodings, the other rejected them. vaultd decodes\n * with rust-bitcoin, whose `VarInt::consensus_decode`\n * (0.32.8 `consensus/encode.rs:493-522`) returns `NonMinimalVarInt` for a 0xfd\n * carrying < 0xfd and a 0xfe carrying < 0x10000 — so the strict reading is the\n * only one that matches what the network will accept.\n *\n * @module tbv/core/utils/witness/witnessStack\n */\n\n/** CompactSize discriminators; 0xff (u64) is out of range for a witness. */\nconst COMPACT_SIZE_UINT16_PREFIX = 0xfd;\nconst COMPACT_SIZE_UINT32_PREFIX = 0xfe;\nconst COMPACT_SIZE_UINT16_BYTES = 3;\nconst COMPACT_SIZE_UINT32_BYTES = 5;\nconst COMPACT_SIZE_UINT16_MIN_VALUE = 0xfd;\nconst COMPACT_SIZE_UINT32_MIN_VALUE = 0x10000;\n\n/**\n * Decode a consensus-encoded witness stack: item count, then (len, bytes)*.\n *\n * @param witness - The consensus-encoded witness bytes.\n * @param subject - Names the witness in error messages (e.g. \"finalScriptWitness\").\n * @returns The stack items, as views over `witness`.\n * @throws If the encoding is truncated, non-minimal, out of range, or leaves\n * trailing bytes.\n */\nexport function decodeWitnessStack(\n witness: Uint8Array,\n subject: string,\n): Uint8Array[] {\n let offset = 0;\n\n const readCompactSize = (): number => {\n if (offset >= witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const first = witness[offset];\n if (first < COMPACT_SIZE_UINT16_PREFIX) {\n offset += 1;\n return first;\n }\n if (first === COMPACT_SIZE_UINT16_PREFIX) {\n if (offset + COMPACT_SIZE_UINT16_BYTES > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const value = witness[offset + 1] | (witness[offset + 2] << 8);\n if (value < COMPACT_SIZE_UINT16_MIN_VALUE) {\n throw new Error(`${subject} has a non-minimal length encoding`);\n }\n offset += COMPACT_SIZE_UINT16_BYTES;\n return value;\n }\n if (first === COMPACT_SIZE_UINT32_PREFIX) {\n if (offset + COMPACT_SIZE_UINT32_BYTES > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const value =\n (witness[offset + 1] |\n (witness[offset + 2] << 8) |\n (witness[offset + 3] << 16) |\n (witness[offset + 4] << 24)) >>>\n 0;\n if (value < COMPACT_SIZE_UINT32_MIN_VALUE) {\n throw new Error(`${subject} has a non-minimal length encoding`);\n }\n offset += COMPACT_SIZE_UINT32_BYTES;\n return value;\n }\n throw new Error(`${subject} carries an out-of-range item length`);\n };\n\n const count = readCompactSize();\n const items: Uint8Array[] = [];\n for (let i = 0; i < count; i++) {\n const len = readCompactSize();\n if (offset + len > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n items.push(witness.subarray(offset, offset + len));\n offset += len;\n }\n if (offset !== witness.length) {\n throw new Error(`${subject} has trailing bytes`);\n }\n return items;\n}\n","/**\n * Far-side verification of P2WPKH ECDSA signatures a wallet returned, over\n * the PSBT we requested (trusted prevouts) — the Native SegWit sibling of\n * `verifyKeyPathSchnorrSignature`. Reference: btc-vault\n * `crates/btc-wallet-remote/src/client.rs:945-1000\n * verify_finalized_p2wpkh_spend`. The wallet's success/finalization is\n * never trusted on its own (CLAUDE.md §8): prevout script and value come\n * from the PSBT we built; only the signature bytes come from the wallet.\n *\n * @module tbv/core/primitives/psbt/verifyP2wpkhEcdsaSignature\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport {\n crypto as bcrypto,\n script as bscript,\n payments,\n Psbt,\n Transaction,\n} from \"bitcoinjs-lib\";\n\nimport { Buffer } from \"buffer\";\n\nimport { decodeWitnessStack } from \"../../utils/witness/witnessStack\";\n\n// P2WPKH scriptPubKey is exactly `OP_0 OP_PUSHBYTES_20 <20-byte key hash>`\n// (BIP-141 witness program v0, 20 bytes).\nconst P2WPKH_SCRIPT_LEN = 22;\nconst OP_0 = 0x00;\nconst OP_PUSHBYTES_20 = 0x14;\nconst P2WPKH_PROGRAM_START = 2;\n\n/** SEC1 compressed pubkey (client.rs:959: \"expected a 33-byte compressed key\"). */\nconst COMPRESSED_PUBKEY_BYTES = 33;\n/** Consensus P2WPKH witness: exactly [signature, pubkey] (client.rs:951-957). */\nconst P2WPKH_WITNESS_ITEMS = 2;\n\n/** Only claim P2WPKH: 22-byte scriptPubKey starting `OP_0 PUSH20`. */\nexport function isP2wpkhScript(\n script: Uint8Array | undefined,\n): script is Uint8Array {\n return (\n script !== undefined &&\n script.length === P2WPKH_SCRIPT_LEN &&\n script[0] === OP_0 &&\n script[1] === OP_PUSHBYTES_20\n );\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((byte, i) => byte === b[i]);\n}\n\n/** The `[signature, pubkey]` pair of a finalized P2WPKH witness (client.rs:951-957). */\nfunction decodeP2wpkhWitness(\n finalScriptWitness: Uint8Array,\n inputIndex: number,\n): { signature: Uint8Array; pubkey: Uint8Array } {\n const items = decodeWitnessStack(finalScriptWitness, \"finalScriptWitness\");\n if (items.length !== P2WPKH_WITNESS_ITEMS) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a finalized P2WPKH witness must have ` +\n `exactly 2 items [signature, pubkey], got ${items.length}.`,\n );\n }\n return { signature: items[0], pubkey: items[1] };\n}\n\nexport interface AssertReturnedP2wpkhSignatureParams {\n /** Hex of the PSBT we built and sent (trusted prevout script/value). NOT the wallet's. */\n requestedPsbtHex: string;\n /** The wallet-returned PSBT input carrying the signature material. */\n returnedInput: {\n partialSig?: Array<{ pubkey: Uint8Array; signature: Uint8Array }>;\n finalScriptWitness?: Uint8Array;\n };\n /** Index of the input the signature is for. */\n inputIndex: number;\n}\n\n/**\n * Assert that the returned input carries a valid P2WPKH ECDSA signature\n * over the BIP-143 sighash of `requestedPsbtHex` input `inputIndex`:\n * `partialSig` (BIP-174: the value is the exact witness-stack signature\n * bytes, the key its pubkey), or the finalized 2-item witness — and when\n * both are present they must be the same bytes.\n *\n * @throws If the requested input is not a P2WPKH spend, no signature was\n * returned, a finalized witness disagrees with its `partialSig`,\n * or any check of `verify_finalized_p2wpkh_spend` fails.\n */\nexport function assertReturnedP2wpkhSignature(\n params: AssertReturnedP2wpkhSignatureParams,\n): void {\n const { requestedPsbtHex, returnedInput, inputIndex } = params;\n\n const partials = returnedInput.partialSig;\n // Consensus allows exactly one signature in a P2WPKH witness, so a second\n // partialSig entry is ambiguous tampering, not a fallback to pick from.\n if (partials !== undefined && partials.length > 1) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a P2WPKH input must carry at most one ` +\n `partial signature, got ${partials.length}.`,\n );\n }\n const partial = partials?.[0];\n const witness = returnedInput.finalScriptWitness\n ? decodeP2wpkhWitness(returnedInput.finalScriptWitness, inputIndex)\n : undefined;\n\n // Both fields can be present, and the consumers broadcast the WITNESS\n // bytes — so the two must agree, not just one of them verify (same\n // rationale as the tapKeySig/witness agreement check).\n if (\n partial &&\n witness &&\n (!bytesEqual(partial.signature, witness.signature) ||\n !bytesEqual(partial.pubkey, witness.pubkey))\n ) {\n throw new Error(\n `Returned PSBT input ${inputIndex} finalized witness does not match its partialSig.`,\n );\n }\n\n const material = partial ?? witness;\n if (!material) {\n throw new Error(\n `Returned PSBT input ${inputIndex} carries no P2WPKH signature ` +\n `(no partialSig, not finalized).`,\n );\n }\n\n assertP2wpkhEcdsaSignature(\n requestedPsbtHex,\n material.signature,\n material.pubkey,\n inputIndex,\n );\n}\n\n/**\n * The crypto core, mirroring `verify_finalized_p2wpkh_spend` check by\n * check: pubkey shape and curve membership, hash160(pubkey) == witness\n * program, strict-DER + SIGHASH_ALL-only signature, ECDSA over the\n * BIP-143 sighash recomputed from the REQUESTED prevout.\n */\nfunction assertP2wpkhEcdsaSignature(\n requestedPsbtHex: string,\n encodedSignature: Uint8Array,\n pubkey: Uint8Array,\n inputIndex: number,\n): void {\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (inputIndex < 0 || inputIndex >= psbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${psbt.data.inputs.length} inputs).`,\n );\n }\n const prevout = psbt.data.inputs[inputIndex].witnessUtxo;\n if (!prevout || !isP2wpkhScript(prevout.script)) {\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is not a P2WPKH input.`,\n );\n }\n\n // Pubkey: exactly 33 bytes (client.rs:959-965) and a parseable curve\n // point, as PublicKey::from_slice (client.rs:966-968).\n if (pubkey.length !== COMPRESSED_PUBKEY_BYTES) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey must be 33 bytes, ` +\n `got ${pubkey.length}.`,\n );\n }\n if (!ecc.isPointCompressed(pubkey)) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey is not a valid secp256k1 point.`,\n );\n }\n\n // hash160(pubkey) must equal the prevout's witness program — what\n // consensus checks (client.rs:970-977).\n const program = prevout.script.subarray(\n P2WPKH_PROGRAM_START,\n P2WPKH_SCRIPT_LEN,\n );\n if (!bytesEqual(bcrypto.hash160(Buffer.from(pubkey)), program)) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey does not hash to the ` +\n `prevout's witness program.`,\n );\n }\n\n // Strict-DER decode with defined-hashtype gate — the accept set of\n // ecdsa::Signature::from_slice / EcdsaSighashType::from_standard\n // (client.rs:978-980) — then SIGHASH_ALL exactly (client.rs:981-987).\n let decoded: { signature: Buffer; hashType: number };\n try {\n decoded = bscript.signature.decode(Buffer.from(encodedSignature));\n } catch (e) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature is not DER with a ` +\n `defined sighash byte: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n // decode tolerates non-minimal integers (bip66.js never bounds lenR/lenS at 33;\n // fromDER truncates, script_signature.js:29-35) that libsecp's strict consensus\n // parse rejects (secp256k1-sys ecdsa_impl.h:127-136) — require the unique\n // minimal encoding by re-encoding and byte-comparing.\n if (\n !bscript.signature\n .encode(decoded.signature, decoded.hashType)\n .equals(Buffer.from(encodedSignature))\n ) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature is not canonical DER.`,\n );\n }\n if (decoded.hashType !== Transaction.SIGHASH_ALL) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature has sighash type ` +\n `0x${decoded.hashType.toString(16)} (expected SIGHASH_ALL).`,\n );\n }\n\n // BIP-143 sighash over the REQUESTED prevout value with the standard\n // P2WPKH scriptCode built from the witness program (client.rs:988-991;\n // scriptCode template per bitcoinjs-lib's own P2WPKH signer,\n // `src/psbt.js:1245-1255`).\n const scriptCode = payments.p2pkh({ hash: Buffer.from(program) }).output;\n if (!scriptCode) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: could not build the P2WPKH scriptCode.`,\n );\n }\n const tx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());\n const sighash = tx.hashForWitnessV0(\n inputIndex,\n scriptCode,\n prevout.value,\n decoded.hashType,\n );\n\n // strict=true rejects high-S, as libsecp256k1's verify_ecdsa does\n // (client.rs:992-999; secp256k1 crate `ecdsa/mod.rs:194`). ecc.verify\n // throws on out-of-range r/s — that is a failed verification here.\n let verifies = false;\n try {\n verifies = ecc.verify(sighash, pubkey, decoded.signature, true);\n } catch {\n verifies = false;\n }\n if (!verifies) {\n throw new Error(\n `P2WPKH signature for input ${inputIndex} does not verify against the ` +\n `requested PSBT's prevout. The wallet may have signed a different ` +\n `transaction or key.`,\n );\n }\n}\n","/**\n * Far-side verification of Taproot KEY-PATH Schnorr signatures a wallet\n * returned, over the PSBT we requested (trusted prevouts) — the key-path twin\n * of `assertScriptPathSchnorrSignature`. Reference: btc-vault\n * `crates/btc-wallet-remote/src/client.rs check_signatures_valid` (output key taken\n * from the prevout scriptPubKey, all prevouts committed). The wallet's\n * success/finalization is never trusted on its own (CLAUDE.md §8).\n * `assertReturnedKeyPathSignatures` additionally dispatches P2WPKH-funded\n * inputs to `verifyP2wpkhEcdsaSignature` (client.rs's\n * `verify_finalized_p2wpkh_spend` sibling), so a Native SegWit software\n * wallet's signatures no longer pass through unchecked.\n *\n * Why verify against the *requested* PSBT: `assertPsbtUnsignedTxMatches` pins\n * the unsigned transaction but deliberately skips per-input metadata, so a\n * wallet could rewrite `witnessUtxo` in its response and make a wrong-message\n * signature self-validate. Prevout scripts and values therefore come from the\n * PSBT we built; only the signature bytes come from the wallet.\n *\n * @module tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { Buffer } from \"buffer\";\n\nimport { decodeWitnessStack } from \"../../utils/witness/witnessStack\";\nimport { hexToUint8Array, stripHexPrefix } from \"../utils/bitcoin\";\nimport {\n assertReturnedP2wpkhSignature,\n isP2wpkhScript,\n} from \"./verifyP2wpkhEcdsaSignature\";\n\nconst SCHNORR_SIG_BYTES = 64;\nconst SIGHASH_DEFAULT = Transaction.SIGHASH_DEFAULT; // 0x00\nconst SIGHASH_ALL = Transaction.SIGHASH_ALL; // 0x01\n\n// P2TR scriptPubKey is exactly `OP_1 OP_PUSHBYTES_32 <32-byte output key>`.\nconst P2TR_SCRIPT_LEN = 34;\nconst OP_1 = 0x51;\nconst OP_PUSHBYTES_32 = 0x20;\nconst P2TR_OUTPUT_KEY_OFFSET = 2;\n\nfunction isP2trScript(script: Uint8Array | undefined): script is Uint8Array {\n return (\n script !== undefined &&\n script.length === P2TR_SCRIPT_LEN &&\n script[0] === OP_1 &&\n script[1] === OP_PUSHBYTES_32\n );\n}\n\n/** BIP-341: 64 bytes ⇒ SIGHASH_DEFAULT; 65 bytes ⇒ the trailing byte is the hash type (we accept ALL only). */\nfunction splitHashType(\n sig: Uint8Array,\n inputIndex: number,\n): { signature: Uint8Array; hashType: number } {\n if (sig.length === SCHNORR_SIG_BYTES) {\n return { signature: sig, hashType: SIGHASH_DEFAULT };\n }\n if (\n sig.length === SCHNORR_SIG_BYTES + 1 &&\n sig[SCHNORR_SIG_BYTES] === SIGHASH_ALL\n ) {\n return {\n signature: sig.subarray(0, SCHNORR_SIG_BYTES),\n hashType: SIGHASH_ALL,\n };\n }\n throw new Error(\n `Key-path signature for input ${inputIndex} must be 64 bytes (SIGHASH_DEFAULT) or ` +\n `65 bytes ending in 0x01 (SIGHASH_ALL), got ${sig.length}.`,\n );\n}\n\nexport interface AssertKeyPathSchnorrSignatureParams {\n /** Hex of the PSBT we built and sent (trusted prevout scripts/values). NOT the wallet's. */\n requestedPsbtHex: string;\n /** 64- or 65-byte signature, hex. */\n signatureHex: string;\n /** Index of the input the signature is for. */\n inputIndex: number;\n}\n\n/**\n * Assert that `signatureHex` is a valid BIP-340 Schnorr signature over the\n * Taproot key-path sighash of `requestedPsbtHex` input `inputIndex`, under the\n * tweaked output key taken from that input's prevout scriptPubKey.\n *\n * @throws If the input is not a key-path P2TR spend, the requested PSBT lacks\n * the prevout data needed to recompute the sighash, or the signature\n * does not verify.\n */\nexport function assertKeyPathSchnorrSignature(\n params: AssertKeyPathSchnorrSignatureParams,\n): void {\n const { requestedPsbtHex, signatureHex, inputIndex } = params;\n\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (inputIndex < 0 || inputIndex >= psbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${psbt.data.inputs.length} inputs).`,\n );\n }\n\n if (!isKeyPathEligible(psbt.data.inputs[inputIndex])) {\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is not a key-path P2TR input.`,\n );\n }\n\n // Taproot's sighash commits to every input's prevout (script + value), so all\n // inputs must carry a witnessUtxo. A missing one is a build error, not a\n // value we can default — fail loudly.\n const prevOutScripts: Buffer[] = [];\n const values: number[] = [];\n for (let i = 0; i < psbt.data.inputs.length; i++) {\n const prevout = psbt.data.inputs[i].witnessUtxo;\n if (!prevout) {\n throw new Error(\n `Cannot verify signature: input ${i} of the requested PSBT has no witnessUtxo ` +\n `(required to recompute the Taproot sighash).`,\n );\n }\n prevOutScripts.push(prevout.script);\n values.push(prevout.value);\n }\n\n const { signature, hashType } = splitHashType(\n hexToUint8Array(stripHexPrefix(signatureHex)),\n inputIndex,\n );\n\n const tx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());\n const sighash = tx.hashForWitnessV1(\n inputIndex,\n prevOutScripts,\n values,\n hashType,\n );\n\n // Key-path signatures verify against the TWEAKED output key = the prevout's\n // witness program.\n const outputKey = prevOutScripts[inputIndex].subarray(P2TR_OUTPUT_KEY_OFFSET);\n\n if (!ecc.verifySchnorr(sighash, outputKey, signature)) {\n throw new Error(\n `Key-path Schnorr signature for input ${inputIndex} does not verify against the ` +\n `requested PSBT's prevout (output key ${Buffer.from(outputKey).toString(\"hex\")}). ` +\n `The wallet may have signed a different transaction or key.`,\n );\n }\n}\n\n/**\n * A key-path P2TR input: an internal key, no script-path material, and a\n * taproot prevout. Script-path inputs are the script-path verifier's job.\n */\nfunction isKeyPathEligible(input: {\n tapInternalKey?: Uint8Array;\n tapLeafScript?: unknown;\n tapMerkleRoot?: Uint8Array;\n witnessUtxo?: { script: Uint8Array };\n}): boolean {\n return (\n input.tapInternalKey !== undefined &&\n input.tapLeafScript === undefined &&\n input.tapMerkleRoot === undefined &&\n isP2trScript(input.witnessUtxo?.script)\n );\n}\n\n/**\n * The lone stack item of a finalized key-path witness. An annex would add a\n * second item, but Bitcoin Core rejects annexes as nonstandard\n * (`src/policy/policy.cpp:327-329`), so such a spend could never broadcast.\n */\nfunction singleWitnessItem(\n finalScriptWitness: Uint8Array,\n inputIndex: number,\n): Uint8Array {\n const items = decodeWitnessStack(finalScriptWitness, \"finalScriptWitness\");\n if (items.length !== 1) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a finalized key-path witness must have ` +\n `exactly one item, got ${items.length}.`,\n );\n }\n return items[0];\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((byte, i) => byte === b[i]);\n}\n\nexport interface AssertReturnedKeyPathSignaturesParams {\n /** PSBT we built locally and asked the wallet to sign. */\n requestedPsbtHex: string;\n /** PSBT the wallet returned after signing. */\n returnedPsbtHex: string;\n}\n\n/**\n * Verify every key-path-eligible and P2WPKH input of the REQUESTED PSBT\n * against what the wallet RETURNED. Key-path: `tapKeySig`, or the single\n * finalized witness item for wallets that auto-finalize — and when both are\n * present they must be the same bytes. P2WPKH: `partialSig`, or the finalized\n * 2-item witness, verified as ECDSA over the BIP-143 sighash\n * ({@link assertReturnedP2wpkhSignature}); a failure throws but the input is\n * NOT counted. Any other input type (script-path, P2WSH, ...) throws — no\n * verifier here covers it, so it cannot be treated as verified.\n *\n * @returns How many inputs were verified KEY-PATH. A caller that knows every\n * input is taproot key-path (e.g. an approval wallet) must assert\n * this equals its input count — P2WPKH inputs never count toward it,\n * so that gate stays exact.\n * @throws If the input counts differ, an input is neither key-path P2TR nor\n * P2WPKH, an eligible input carries no signature, a finalized witness\n * disagrees with its `tapKeySig`/`partialSig`, or any signature does\n * not verify.\n */\nexport function assertReturnedKeyPathSignatures(\n params: AssertReturnedKeyPathSignaturesParams,\n): number {\n const { requestedPsbtHex, returnedPsbtHex } = params;\n\n const requested = Psbt.fromHex(requestedPsbtHex);\n const returned = Psbt.fromHex(returnedPsbtHex);\n\n if (returned.data.inputs.length !== requested.data.inputs.length) {\n throw new Error(\n `Returned PSBT input count ${returned.data.inputs.length} differs from the ` +\n `requested ${requested.data.inputs.length}.`,\n );\n }\n\n let verified = 0;\n requested.data.inputs.forEach((input, inputIndex) => {\n const returnedInput = returned.data.inputs[inputIndex];\n\n if (!isKeyPathEligible(input)) {\n // Native SegWit funding inputs get the ECDSA check.\n if (isP2wpkhScript(input.witnessUtxo?.script)) {\n assertReturnedP2wpkhSignature({\n requestedPsbtHex,\n returnedInput,\n inputIndex,\n });\n return;\n }\n // No verifier exists for any other type — fail closed like btc-vault's\n // check_signatures_valid rather than silently reporting it checked.\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is neither key-path P2TR ` +\n `nor P2WPKH; refusing to treat it as verified.`,\n );\n }\n verified++;\n\n const tapKeySig = returnedInput.tapKeySig;\n const witnessSig = returnedInput.finalScriptWitness\n ? singleWitnessItem(returnedInput.finalScriptWitness, inputIndex)\n : undefined;\n\n // Both fields can be present, and the consumers broadcast the WITNESS\n // bytes — so the two must agree, not just one of them verify. Matches\n // btc-vault `crates/btc-wallet-remote/src/client.rs:1053-1072,1102-1121`,\n // which checks each independently.\n if (tapKeySig && witnessSig && !bytesEqual(tapKeySig, witnessSig)) {\n throw new Error(\n `Returned PSBT input ${inputIndex} finalized witness does not match its tapKeySig.`,\n );\n }\n\n const sig = tapKeySig ?? witnessSig;\n if (!sig) {\n throw new Error(\n `Returned PSBT input ${inputIndex} carries no key-path signature ` +\n `(no tapKeySig, not finalized).`,\n );\n }\n\n assertKeyPathSchnorrSignature({\n requestedPsbtHex,\n signatureHex: Buffer.from(sig).toString(\"hex\"),\n inputIndex,\n });\n });\n\n return verified;\n}\n"],"names":["buildPeginInputPsbt","params","peginTxHex","stripHexPrefix","fundedPrePeginTxHex","getPrePeginHtlcConnectorInfo","expectedHtlc","deriveExpectedPrePeginHtlc","peginTx","Transaction","prePeginTx","peginInput","prePeginTxid","peginInputTxid","uint8ArrayToHex","htlcOutput","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPeginInputSignature","signedPsbtHex","depositorPubkey","input","depositorPubkeyBytes","hexToUint8Array","sigEntry","extractSchnorrSig","finalizePeginInputPsbt","e","inp","sig","COMPACT_SIZE_UINT16_PREFIX","COMPACT_SIZE_UINT32_PREFIX","COMPACT_SIZE_UINT16_BYTES","COMPACT_SIZE_UINT32_BYTES","COMPACT_SIZE_UINT16_MIN_VALUE","COMPACT_SIZE_UINT32_MIN_VALUE","decodeWitnessStack","witness","subject","offset","readCompactSize","first","value","count","items","i","len","P2WPKH_SCRIPT_LEN","OP_0","OP_PUSHBYTES_20","P2WPKH_PROGRAM_START","COMPRESSED_PUBKEY_BYTES","P2WPKH_WITNESS_ITEMS","isP2wpkhScript","script","bytesEqual","a","b","byte","decodeP2wpkhWitness","finalScriptWitness","inputIndex","assertReturnedP2wpkhSignature","requestedPsbtHex","returnedInput","partials","partial","material","assertP2wpkhEcdsaSignature","encodedSignature","pubkey","prevout","ecc","program","bcrypto","decoded","bscript","scriptCode","payments","sighash","verifies","SCHNORR_SIG_BYTES","SIGHASH_DEFAULT","SIGHASH_ALL","P2TR_SCRIPT_LEN","OP_1","OP_PUSHBYTES_32","P2TR_OUTPUT_KEY_OFFSET","isP2trScript","splitHashType","assertKeyPathSchnorrSignature","signatureHex","isKeyPathEligible","prevOutScripts","values","signature","hashType","outputKey","_a","singleWitnessItem","assertReturnedKeyPathSignatures","returnedPsbtHex","requested","returned","verified","tapKeySig","witnessSig"],"mappings":";;;;;;AA4FA,eAAsBA,GACpBC,GACoC;AACpC,QAAMC,IAAaC,EAAeF,EAAO,UAAU,GAC7CG,IAAsBD,EAAeF,EAAO,mBAAmB;AAIrE,QAAMI,EAA6B;AAAA,IACjC,gBAAgBJ,EAAO;AAAA,IACvB,iBAAiBA,EAAO;AAAA,IACxB,qBAAqBA,EAAO;AAAA,IAC5B,oBAAoBA,EAAO;AAAA,IAC3B,4BAA4BA,EAAO;AAAA,IACnC,UAAUA,EAAO;AAAA,IACjB,gBAAgBA,EAAO;AAAA,IACvB,SAASA,EAAO;AAAA,EAAA,CACjB;AACD,QAAMK,IAAeC,EAA2BN,GAAQA,EAAO,QAAQ,GAEjEO,IAAUC,EAAY,QAAQP,CAAU,GACxCQ,IAAaD,EAAY,QAAQL,CAAmB;AAE1D,MAAII,EAAQ,IAAI,WAAW;AACzB,UAAM,IAAI;AAAA,MACR,oDAAoDA,EAAQ,IAAI,MAAM;AAAA,IAAA;AAI1E,QAAMG,IAAaH,EAAQ,IAAI,CAAC,GAG1BI,IAAeF,EAAW,MAAA,GAC1BG,IAAiBC;AAAA,IACrB,IAAI,WAAWH,EAAW,IAAI,EAAE,MAAA,EAAQ,QAAA;AAAA,EAAQ;AAGlD,MAAIE,MAAmBD;AACrB,UAAM,IAAI;AAAA,MACR,sEACcA,CAAY,SAASC,CAAc;AAAA,IAAA;AAIrD,QAAME,IAAaL,EAAW,KAAKC,EAAW,KAAK;AACnD,MAAI,CAACI;AACH,UAAM,IAAI;AAAA,MACR,oBAAoBJ,EAAW,KAAK,6BAChBD,EAAW,KAAK,MAAM;AAAA,IAAA;AAI9C,MAAI,CAACJ,EAAa,aAAa,OAAOS,EAAW,MAAM;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E,KAAaC;AACzB,QAAI,CAAC7E;AACH,YAAM,IAAI;AAAA,QACR,uBAAuBgC,CAAU;AAAA,MAAA;AAKrC,IAAA6B,GAA8B;AAAA,MAC5B,kBAAA3B;AAAA,MACA,cAAchD,EAAO,KAAKc,CAAG,EAAE,SAAS,KAAK;AAAA,MAC7C,YAAAgC;AAAA,IAAA,CACD;AAAA,EACH,CAAC,GAEM2C;AACT;"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";const u=require("bitcoinjs-lib"),g=require("buffer"),E=require("./tbv/core/wasm/index.cjs"),P=require("./bitcoin-D-O2GjbC.cjs"),k=require("./verifyScriptPathSchnorrSignature-DaRqvEgW.cjs"),B=require("@bitcoin-js/tiny-secp256k1-asmjs");function R(t){const r=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const e=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,e.get?e:{enumerable:!0,get:()=>t[n]})}}return r.default=t,Object.freeze(r)}const w=R(B);async function A(t){const r=P.stripHexPrefix(t.peginTxHex),n=P.stripHexPrefix(t.fundedPrePeginTxHex);await E.getPrePeginHtlcConnectorInfo({txGraphVersion:t.vaultCoreVersion,depositorPubkey:t.depositorPubkey,vaultProviderPubkey:t.vaultProviderPubkey,vaultKeeperPubkeys:t.vaultKeeperPubkeys,universalChallengerPubkeys:t.universalChallengerPubkeys,hashlock:t.hashlock,timelockRefund:t.timelockRefund,network:t.network});const e=k.deriveExpectedPrePeginHtlc(t,t.hashlock),i=u.Transaction.fromHex(r),a=u.Transaction.fromHex(n);if(i.ins.length!==1)throw new Error(`PegIn transaction must have exactly 1 input, got ${i.ins.length}`);const s=i.ins[0],o=a.getId(),h=P.uint8ArrayToHex(new Uint8Array(s.hash).slice().reverse());if(h!==o)throw new Error(`PegIn input does not reference the Pre-PegIn transaction. Expected ${o}, got ${h}`);const l=a.outs[s.index];if(!l)throw new Error(`Pre-PegIn output ${s.index} not found (Pre-PegIn has ${a.outs.length} outputs)`);if(!e.scriptPubKey.equals(l.script))throw new Error("PegIn HTLC taptree mismatch: the independent 2-leaf tree does not reproduce the funded Pre-PegIn HTLC scriptPubKey; refusing to sign.");const c=new u.Psbt;c.setVersion(i.version),c.setLocktime(i.locktime),c.addInput({hash:s.hash,index:s.index,sequence:s.sequence,witnessUtxo:{script:l.script,value:l.value},tapLeafScript:[{leafVersion:P.TAPSCRIPT_LEAF_VERSION,script:e.hashlockScript,controlBlock:e.hashlockControlBlock}],tapInternalKey:g.Buffer.from(E.tapInternalPubkey),tapMerkleRoot:e.tapMerkleRoot});for(const f of i.outs)c.addOutput({script:f.script,value:f.value});return{psbtHex:c.toHex()}}function K(t,r){const e=u.Psbt.fromHex(t).data.inputs[0];if(!e)throw new Error("PegIn PSBT has no inputs");if(e.tapScriptSig&&e.tapScriptSig.length>0){const i=g.Buffer.from(P.hexToUint8Array(r));for(const a of e.tapScriptSig)if(a.pubkey.equals(i))return C(a.signature);throw new Error(`No PegIn input signature found for depositor pubkey: ${r}`)}throw e.finalScriptWitness&&e.finalScriptWitness.length>0?new Error("PegIn input PSBT is already finalized. Cannot reliably extract the depositor signature from the witness stack. Ensure the wallet returns a non-finalized PSBT with tapScriptSig entries."):new Error("No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT")}function W(t){const r=u.Psbt.fromHex(t);try{r.finalizeAllInputs()}catch(n){if(!r.data.inputs.every(i=>i.finalScriptWitness||i.finalScriptSig))throw new Error(`PSBT finalization failed and wallet did not auto-finalize: ${n}`)}return r.extractTransaction().toHex()}function C(t){if(t.length===64)return P.uint8ArrayToHex(new Uint8Array(t));throw t.length===65?new Error(`Unexpected sighash byte 0x${t[64].toString(16).padStart(2,"0")} in PegIn input signature. Expected implicit SIGHASH_DEFAULT as a 64-byte signature.`):new Error(`Unexpected PegIn input signature length: ${t.length}`)}const H=253,U=254,b=3,x=5,q=253,L=65536;function y(t,r){let n=0;const e=()=>{if(n>=t.length)throw new Error(`${r} is truncated`);const s=t[n];if(s<H)return n+=1,s;if(s===H){if(n+b>t.length)throw new Error(`${r} is truncated`);const o=t[n+1]|t[n+2]<<8;if(o<q)throw new Error(`${r} has a non-minimal length encoding`);return n+=b,o}if(s===U){if(n+x>t.length)throw new Error(`${r} is truncated`);const o=(t[n+1]|t[n+2]<<8|t[n+3]<<16|t[n+4]<<24)>>>0;if(o<L)throw new Error(`${r} has a non-minimal length encoding`);return n+=x,o}throw new Error(`${r} carries an out-of-range item length`)},i=e(),a=[];for(let s=0;s<i;s++){const o=e();if(n+o>t.length)throw new Error(`${r} is truncated`);a.push(t.subarray(n,n+o)),n+=o}if(n!==t.length)throw new Error(`${r} has trailing bytes`);return a}const v=22,O=0,z=20,M=2,N=33,F=2;function $(t){return t!==void 0&&t.length===v&&t[0]===O&&t[1]===z}function T(t,r){return t.length===r.length&&t.every((n,e)=>n===r[e])}function G(t,r){const n=y(t,"finalScriptWitness");if(n.length!==F)throw new Error(`Returned PSBT input ${r}: a finalized P2WPKH witness must have exactly 2 items [signature, pubkey], got ${n.length}.`);return{signature:n[0],pubkey:n[1]}}function D(t){const{requestedPsbtHex:r,returnedInput:n,inputIndex:e}=t,i=n.partialSig;if(i!==void 0&&i.length>1)throw new Error(`Returned PSBT input ${e}: a P2WPKH input must carry at most one partial signature, got ${i.length}.`);const a=i==null?void 0:i[0],s=n.finalScriptWitness?G(n.finalScriptWitness,e):void 0;if(a&&s&&(!T(a.signature,s.signature)||!T(a.pubkey,s.pubkey)))throw new Error(`Returned PSBT input ${e} finalized witness does not match its partialSig.`);const o=a??s;if(!o)throw new Error(`Returned PSBT input ${e} carries no P2WPKH signature (no partialSig, not finalized).`);V(r,o.signature,o.pubkey,e)}function V(t,r,n,e){const i=u.Psbt.fromHex(t);if(e<0||e>=i.data.inputs.length)throw new Error(`Input index ${e} out of range (${i.data.inputs.length} inputs).`);const a=i.data.inputs[e].witnessUtxo;if(!a||!$(a.script))throw new Error(`Input ${e} of the requested PSBT is not a P2WPKH input.`);if(n.length!==N)throw new Error(`Returned PSBT input ${e}: P2WPKH pubkey must be 33 bytes, got ${n.length}.`);if(!w.isPointCompressed(n))throw new Error(`Returned PSBT input ${e}: P2WPKH pubkey is not a valid secp256k1 point.`);const s=a.script.subarray(M,v);if(!T(u.crypto.hash160(g.Buffer.from(n)),s))throw new Error(`Returned PSBT input ${e}: P2WPKH pubkey does not hash to the prevout's witness program.`);let o;try{o=u.script.signature.decode(g.Buffer.from(r))}catch(p){throw new Error(`Returned PSBT input ${e}: P2WPKH signature is not DER with a defined sighash byte: ${p instanceof Error?p.message:String(p)}`)}if(!u.script.signature.encode(o.signature,o.hashType).equals(g.Buffer.from(r)))throw new Error(`Returned PSBT input ${e}: P2WPKH signature is not canonical DER.`);if(o.hashType!==u.Transaction.SIGHASH_ALL)throw new Error(`Returned PSBT input ${e}: P2WPKH signature has sighash type 0x${o.hashType.toString(16)} (expected SIGHASH_ALL).`);const h=u.payments.p2pkh({hash:g.Buffer.from(s)}).output;if(!h)throw new Error(`Returned PSBT input ${e}: could not build the P2WPKH scriptCode.`);const c=u.Transaction.fromBuffer(i.data.globalMap.unsignedTx.toBuffer()).hashForWitnessV0(e,h,a.value,o.hashType);let f=!1;try{f=w.verify(c,n,o.signature,!0)}catch{f=!1}if(!f)throw new Error(`P2WPKH signature for input ${e} does not verify against the requested PSBT's prevout. The wallet may have signed a different transaction or key.`)}const d=64,Y=u.Transaction.SIGHASH_DEFAULT,_=u.Transaction.SIGHASH_ALL,Z=34,X=81,J=32,Q=2;function j(t){return t!==void 0&&t.length===Z&&t[0]===X&&t[1]===J}function tt(t,r){if(t.length===d)return{signature:t,hashType:Y};if(t.length===d+1&&t[d]===_)return{signature:t.subarray(0,d),hashType:_};throw new Error(`Key-path signature for input ${r} must be 64 bytes (SIGHASH_DEFAULT) or 65 bytes ending in 0x01 (SIGHASH_ALL), got ${t.length}.`)}function m(t){const{requestedPsbtHex:r,signatureHex:n,inputIndex:e}=t,i=u.Psbt.fromHex(r);if(e<0||e>=i.data.inputs.length)throw new Error(`Input index ${e} out of range (${i.data.inputs.length} inputs).`);if(!I(i.data.inputs[e]))throw new Error(`Input ${e} of the requested PSBT is not a key-path P2TR input.`);const a=[],s=[];for(let p=0;p<i.data.inputs.length;p++){const S=i.data.inputs[p].witnessUtxo;if(!S)throw new Error(`Cannot verify signature: input ${p} of the requested PSBT has no witnessUtxo (required to recompute the Taproot sighash).`);a.push(S.script),s.push(S.value)}const{signature:o,hashType:h}=tt(P.hexToUint8Array(P.stripHexPrefix(n)),e),c=u.Transaction.fromBuffer(i.data.globalMap.unsignedTx.toBuffer()).hashForWitnessV1(e,a,s,h),f=a[e].subarray(Q);if(!w.verifySchnorr(c,f,o))throw new Error(`Key-path Schnorr signature for input ${e} does not verify against the requested PSBT's prevout (output key ${g.Buffer.from(f).toString("hex")}). The wallet may have signed a different transaction or key.`)}function I(t){var r;return t.tapInternalKey!==void 0&&t.tapLeafScript===void 0&&t.tapMerkleRoot===void 0&&j((r=t.witnessUtxo)==null?void 0:r.script)}function et(t,r){const n=y(t,"finalScriptWitness");if(n.length!==1)throw new Error(`Returned PSBT input ${r}: a finalized key-path witness must have exactly one item, got ${n.length}.`);return n[0]}function nt(t,r){return t.length===r.length&&t.every((n,e)=>n===r[e])}function rt(t){const{requestedPsbtHex:r,returnedPsbtHex:n}=t,e=u.Psbt.fromHex(r),i=u.Psbt.fromHex(n);if(i.data.inputs.length!==e.data.inputs.length)throw new Error(`Returned PSBT input count ${i.data.inputs.length} differs from the requested ${e.data.inputs.length}.`);let a=0;return e.data.inputs.forEach((s,o)=>{var p;const h=i.data.inputs[o];if(!I(s)){if($((p=s.witnessUtxo)==null?void 0:p.script)){D({requestedPsbtHex:r,returnedInput:h,inputIndex:o});return}throw new Error(`Input ${o} of the requested PSBT is neither key-path P2TR nor P2WPKH; refusing to treat it as verified.`)}a++;const l=h.tapKeySig,c=h.finalScriptWitness?et(h.finalScriptWitness,o):void 0;if(l&&c&&!nt(l,c))throw new Error(`Returned PSBT input ${o} finalized witness does not match its tapKeySig.`);const f=l??c;if(!f)throw new Error(`Returned PSBT input ${o} carries no key-path signature (no tapKeySig, not finalized).`);m({requestedPsbtHex:r,signatureHex:g.Buffer.from(f).toString("hex"),inputIndex:o})}),a}exports.assertKeyPathSchnorrSignature=m;exports.assertReturnedKeyPathSignatures=rt;exports.buildPeginInputPsbt=A;exports.decodeWitnessStack=y;exports.extractPeginInputSignature=K;exports.finalizePeginInputPsbt=W;
|
|
2
|
-
//# sourceMappingURL=verifyKeyPathSchnorrSignature-
|
|
1
|
+
"use strict";const u=require("bitcoinjs-lib"),g=require("buffer"),E=require("./tbv/core/wasm/index.cjs"),P=require("./bitcoin-D-O2GjbC.cjs"),k=require("./verifyScriptPathSchnorrSignature-BKZihCjk.cjs"),B=require("@bitcoin-js/tiny-secp256k1-asmjs");function R(t){const r=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const e=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,e.get?e:{enumerable:!0,get:()=>t[n]})}}return r.default=t,Object.freeze(r)}const w=R(B);async function A(t){const r=P.stripHexPrefix(t.peginTxHex),n=P.stripHexPrefix(t.fundedPrePeginTxHex);await E.getPrePeginHtlcConnectorInfo({txGraphVersion:t.vaultCoreVersion,depositorPubkey:t.depositorPubkey,vaultProviderPubkey:t.vaultProviderPubkey,vaultKeeperPubkeys:t.vaultKeeperPubkeys,universalChallengerPubkeys:t.universalChallengerPubkeys,hashlock:t.hashlock,timelockRefund:t.timelockRefund,network:t.network});const e=k.deriveExpectedPrePeginHtlc(t,t.hashlock),i=u.Transaction.fromHex(r),a=u.Transaction.fromHex(n);if(i.ins.length!==1)throw new Error(`PegIn transaction must have exactly 1 input, got ${i.ins.length}`);const s=i.ins[0],o=a.getId(),h=P.uint8ArrayToHex(new Uint8Array(s.hash).slice().reverse());if(h!==o)throw new Error(`PegIn input does not reference the Pre-PegIn transaction. Expected ${o}, got ${h}`);const l=a.outs[s.index];if(!l)throw new Error(`Pre-PegIn output ${s.index} not found (Pre-PegIn has ${a.outs.length} outputs)`);if(!e.scriptPubKey.equals(l.script))throw new Error("PegIn HTLC taptree mismatch: the independent 2-leaf tree does not reproduce the funded Pre-PegIn HTLC scriptPubKey; refusing to sign.");const c=new u.Psbt;c.setVersion(i.version),c.setLocktime(i.locktime),c.addInput({hash:s.hash,index:s.index,sequence:s.sequence,witnessUtxo:{script:l.script,value:l.value},tapLeafScript:[{leafVersion:P.TAPSCRIPT_LEAF_VERSION,script:e.hashlockScript,controlBlock:e.hashlockControlBlock}],tapInternalKey:g.Buffer.from(E.tapInternalPubkey),tapMerkleRoot:e.tapMerkleRoot});for(const f of i.outs)c.addOutput({script:f.script,value:f.value});return{psbtHex:c.toHex()}}function K(t,r){const e=u.Psbt.fromHex(t).data.inputs[0];if(!e)throw new Error("PegIn PSBT has no inputs");if(e.tapScriptSig&&e.tapScriptSig.length>0){const i=g.Buffer.from(P.hexToUint8Array(r));for(const a of e.tapScriptSig)if(a.pubkey.equals(i))return C(a.signature);throw new Error(`No PegIn input signature found for depositor pubkey: ${r}`)}throw e.finalScriptWitness&&e.finalScriptWitness.length>0?new Error("PegIn input PSBT is already finalized. Cannot reliably extract the depositor signature from the witness stack. Ensure the wallet returns a non-finalized PSBT with tapScriptSig entries."):new Error("No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT")}function W(t){const r=u.Psbt.fromHex(t);try{r.finalizeAllInputs()}catch(n){if(!r.data.inputs.every(i=>i.finalScriptWitness||i.finalScriptSig))throw new Error(`PSBT finalization failed and wallet did not auto-finalize: ${n}`)}return r.extractTransaction().toHex()}function C(t){if(t.length===64)return P.uint8ArrayToHex(new Uint8Array(t));throw t.length===65?new Error(`Unexpected sighash byte 0x${t[64].toString(16).padStart(2,"0")} in PegIn input signature. Expected implicit SIGHASH_DEFAULT as a 64-byte signature.`):new Error(`Unexpected PegIn input signature length: ${t.length}`)}const H=253,U=254,b=3,x=5,q=253,L=65536;function y(t,r){let n=0;const e=()=>{if(n>=t.length)throw new Error(`${r} is truncated`);const s=t[n];if(s<H)return n+=1,s;if(s===H){if(n+b>t.length)throw new Error(`${r} is truncated`);const o=t[n+1]|t[n+2]<<8;if(o<q)throw new Error(`${r} has a non-minimal length encoding`);return n+=b,o}if(s===U){if(n+x>t.length)throw new Error(`${r} is truncated`);const o=(t[n+1]|t[n+2]<<8|t[n+3]<<16|t[n+4]<<24)>>>0;if(o<L)throw new Error(`${r} has a non-minimal length encoding`);return n+=x,o}throw new Error(`${r} carries an out-of-range item length`)},i=e(),a=[];for(let s=0;s<i;s++){const o=e();if(n+o>t.length)throw new Error(`${r} is truncated`);a.push(t.subarray(n,n+o)),n+=o}if(n!==t.length)throw new Error(`${r} has trailing bytes`);return a}const v=22,O=0,z=20,M=2,N=33,F=2;function $(t){return t!==void 0&&t.length===v&&t[0]===O&&t[1]===z}function T(t,r){return t.length===r.length&&t.every((n,e)=>n===r[e])}function G(t,r){const n=y(t,"finalScriptWitness");if(n.length!==F)throw new Error(`Returned PSBT input ${r}: a finalized P2WPKH witness must have exactly 2 items [signature, pubkey], got ${n.length}.`);return{signature:n[0],pubkey:n[1]}}function D(t){const{requestedPsbtHex:r,returnedInput:n,inputIndex:e}=t,i=n.partialSig;if(i!==void 0&&i.length>1)throw new Error(`Returned PSBT input ${e}: a P2WPKH input must carry at most one partial signature, got ${i.length}.`);const a=i==null?void 0:i[0],s=n.finalScriptWitness?G(n.finalScriptWitness,e):void 0;if(a&&s&&(!T(a.signature,s.signature)||!T(a.pubkey,s.pubkey)))throw new Error(`Returned PSBT input ${e} finalized witness does not match its partialSig.`);const o=a??s;if(!o)throw new Error(`Returned PSBT input ${e} carries no P2WPKH signature (no partialSig, not finalized).`);V(r,o.signature,o.pubkey,e)}function V(t,r,n,e){const i=u.Psbt.fromHex(t);if(e<0||e>=i.data.inputs.length)throw new Error(`Input index ${e} out of range (${i.data.inputs.length} inputs).`);const a=i.data.inputs[e].witnessUtxo;if(!a||!$(a.script))throw new Error(`Input ${e} of the requested PSBT is not a P2WPKH input.`);if(n.length!==N)throw new Error(`Returned PSBT input ${e}: P2WPKH pubkey must be 33 bytes, got ${n.length}.`);if(!w.isPointCompressed(n))throw new Error(`Returned PSBT input ${e}: P2WPKH pubkey is not a valid secp256k1 point.`);const s=a.script.subarray(M,v);if(!T(u.crypto.hash160(g.Buffer.from(n)),s))throw new Error(`Returned PSBT input ${e}: P2WPKH pubkey does not hash to the prevout's witness program.`);let o;try{o=u.script.signature.decode(g.Buffer.from(r))}catch(p){throw new Error(`Returned PSBT input ${e}: P2WPKH signature is not DER with a defined sighash byte: ${p instanceof Error?p.message:String(p)}`)}if(!u.script.signature.encode(o.signature,o.hashType).equals(g.Buffer.from(r)))throw new Error(`Returned PSBT input ${e}: P2WPKH signature is not canonical DER.`);if(o.hashType!==u.Transaction.SIGHASH_ALL)throw new Error(`Returned PSBT input ${e}: P2WPKH signature has sighash type 0x${o.hashType.toString(16)} (expected SIGHASH_ALL).`);const h=u.payments.p2pkh({hash:g.Buffer.from(s)}).output;if(!h)throw new Error(`Returned PSBT input ${e}: could not build the P2WPKH scriptCode.`);const c=u.Transaction.fromBuffer(i.data.globalMap.unsignedTx.toBuffer()).hashForWitnessV0(e,h,a.value,o.hashType);let f=!1;try{f=w.verify(c,n,o.signature,!0)}catch{f=!1}if(!f)throw new Error(`P2WPKH signature for input ${e} does not verify against the requested PSBT's prevout. The wallet may have signed a different transaction or key.`)}const d=64,Y=u.Transaction.SIGHASH_DEFAULT,_=u.Transaction.SIGHASH_ALL,Z=34,X=81,J=32,Q=2;function j(t){return t!==void 0&&t.length===Z&&t[0]===X&&t[1]===J}function tt(t,r){if(t.length===d)return{signature:t,hashType:Y};if(t.length===d+1&&t[d]===_)return{signature:t.subarray(0,d),hashType:_};throw new Error(`Key-path signature for input ${r} must be 64 bytes (SIGHASH_DEFAULT) or 65 bytes ending in 0x01 (SIGHASH_ALL), got ${t.length}.`)}function m(t){const{requestedPsbtHex:r,signatureHex:n,inputIndex:e}=t,i=u.Psbt.fromHex(r);if(e<0||e>=i.data.inputs.length)throw new Error(`Input index ${e} out of range (${i.data.inputs.length} inputs).`);if(!I(i.data.inputs[e]))throw new Error(`Input ${e} of the requested PSBT is not a key-path P2TR input.`);const a=[],s=[];for(let p=0;p<i.data.inputs.length;p++){const S=i.data.inputs[p].witnessUtxo;if(!S)throw new Error(`Cannot verify signature: input ${p} of the requested PSBT has no witnessUtxo (required to recompute the Taproot sighash).`);a.push(S.script),s.push(S.value)}const{signature:o,hashType:h}=tt(P.hexToUint8Array(P.stripHexPrefix(n)),e),c=u.Transaction.fromBuffer(i.data.globalMap.unsignedTx.toBuffer()).hashForWitnessV1(e,a,s,h),f=a[e].subarray(Q);if(!w.verifySchnorr(c,f,o))throw new Error(`Key-path Schnorr signature for input ${e} does not verify against the requested PSBT's prevout (output key ${g.Buffer.from(f).toString("hex")}). The wallet may have signed a different transaction or key.`)}function I(t){var r;return t.tapInternalKey!==void 0&&t.tapLeafScript===void 0&&t.tapMerkleRoot===void 0&&j((r=t.witnessUtxo)==null?void 0:r.script)}function et(t,r){const n=y(t,"finalScriptWitness");if(n.length!==1)throw new Error(`Returned PSBT input ${r}: a finalized key-path witness must have exactly one item, got ${n.length}.`);return n[0]}function nt(t,r){return t.length===r.length&&t.every((n,e)=>n===r[e])}function rt(t){const{requestedPsbtHex:r,returnedPsbtHex:n}=t,e=u.Psbt.fromHex(r),i=u.Psbt.fromHex(n);if(i.data.inputs.length!==e.data.inputs.length)throw new Error(`Returned PSBT input count ${i.data.inputs.length} differs from the requested ${e.data.inputs.length}.`);let a=0;return e.data.inputs.forEach((s,o)=>{var p;const h=i.data.inputs[o];if(!I(s)){if($((p=s.witnessUtxo)==null?void 0:p.script)){D({requestedPsbtHex:r,returnedInput:h,inputIndex:o});return}throw new Error(`Input ${o} of the requested PSBT is neither key-path P2TR nor P2WPKH; refusing to treat it as verified.`)}a++;const l=h.tapKeySig,c=h.finalScriptWitness?et(h.finalScriptWitness,o):void 0;if(l&&c&&!nt(l,c))throw new Error(`Returned PSBT input ${o} finalized witness does not match its tapKeySig.`);const f=l??c;if(!f)throw new Error(`Returned PSBT input ${o} carries no key-path signature (no tapKeySig, not finalized).`);m({requestedPsbtHex:r,signatureHex:g.Buffer.from(f).toString("hex"),inputIndex:o})}),a}exports.assertKeyPathSchnorrSignature=m;exports.assertReturnedKeyPathSignatures=rt;exports.buildPeginInputPsbt=A;exports.decodeWitnessStack=y;exports.extractPeginInputSignature=K;exports.finalizePeginInputPsbt=W;
|
|
2
|
+
//# sourceMappingURL=verifyKeyPathSchnorrSignature-Gm9EmZkx.cjs.map
|