@babylonlabs-io/ts-sdk 0.71.0 → 0.71.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/dist/PeginManager-Bn8FxM35.cjs +2 -0
  2. package/dist/{PeginManager-BIKAnZ-X.cjs.map → PeginManager-Bn8FxM35.cjs.map} +1 -1
  3. package/dist/{PeginManager-Byvmccdd.js → PeginManager-C3ojNTlv.js} +6 -6
  4. package/dist/{PeginManager-Byvmccdd.js.map → PeginManager-C3ojNTlv.js.map} +1 -1
  5. package/dist/{buildAndBroadcastReclaim-C0TdwO2M.js → buildAndBroadcastReclaim-YvWDRAN8.js} +492 -489
  6. package/dist/{buildAndBroadcastReclaim-C0TdwO2M.js.map → buildAndBroadcastReclaim-YvWDRAN8.js.map} +1 -1
  7. package/dist/buildAndBroadcastReclaim-zfjDI5__.cjs +2 -0
  8. package/dist/{buildAndBroadcastReclaim-kRx7-o2y.cjs.map → buildAndBroadcastReclaim-zfjDI5__.cjs.map} +1 -1
  9. package/dist/index.cjs +1 -1
  10. package/dist/index.js +227 -226
  11. package/dist/{mempoolApi-CRNMOsbC.js → mempoolApi-CKD_IbrM.js} +32 -33
  12. package/dist/mempoolApi-CKD_IbrM.js.map +1 -0
  13. package/dist/mempoolApi-DronQ5xn.cjs +2 -0
  14. package/dist/mempoolApi-DronQ5xn.cjs.map +1 -0
  15. package/dist/noPayout-DpGRzidi.js +353 -0
  16. package/dist/noPayout-DpGRzidi.js.map +1 -0
  17. package/dist/noPayout-zEifyecV.cjs +2 -0
  18. package/dist/noPayout-zEifyecV.cjs.map +1 -0
  19. package/dist/{primeVpAuth-tEXx9TGx.cjs → primeVpAuth-Cjq6qFHq.cjs} +2 -2
  20. package/dist/primeVpAuth-Cjq6qFHq.cjs.map +1 -0
  21. package/dist/{primeVpAuth-D1qbOkhb.js → primeVpAuth-tLRjdHwZ.js} +2 -2
  22. package/dist/primeVpAuth-tLRjdHwZ.js.map +1 -0
  23. package/dist/{signPsbtsWithFallback-BjXdnI0X.js → signPsbtsWithFallback-CCFTzE0o.js} +3 -3
  24. package/dist/{signPsbtsWithFallback-BjXdnI0X.js.map → signPsbtsWithFallback-CCFTzE0o.js.map} +1 -1
  25. package/dist/{signPsbtsWithFallback-zOQWokmk.cjs → signPsbtsWithFallback-CrkvpSJz.cjs} +2 -2
  26. package/dist/{signPsbtsWithFallback-zOQWokmk.cjs.map → signPsbtsWithFallback-CrkvpSJz.cjs.map} +1 -1
  27. package/dist/signing-BJ3X66b-.cjs +2 -0
  28. package/dist/signing-BJ3X66b-.cjs.map +1 -0
  29. package/dist/signing-Cm-McVR2.js +22 -0
  30. package/dist/signing-Cm-McVR2.js.map +1 -0
  31. package/dist/tbv/core/clients/eth/types.d.ts +0 -2
  32. package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
  33. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -1
  34. package/dist/tbv/core/clients/index.cjs +1 -1
  35. package/dist/tbv/core/clients/index.js +2 -2
  36. package/dist/tbv/core/clients/mempool/mempoolApi.d.ts +9 -1
  37. package/dist/tbv/core/clients/mempool/mempoolApi.d.ts.map +1 -1
  38. package/dist/tbv/core/index.cjs +1 -1
  39. package/dist/tbv/core/index.js +222 -221
  40. package/dist/tbv/core/managers/index.cjs +1 -1
  41. package/dist/tbv/core/managers/index.js +2 -2
  42. package/dist/tbv/core/primitives/index.cjs +1 -1
  43. package/dist/tbv/core/primitives/index.d.ts +2 -0
  44. package/dist/tbv/core/primitives/index.d.ts.map +1 -1
  45. package/dist/tbv/core/primitives/index.js +23 -22
  46. package/dist/tbv/core/primitives/psbt/__tests__/finalizeScriptPathWithSignatures.test.d.ts +11 -0
  47. package/dist/tbv/core/primitives/psbt/__tests__/finalizeScriptPathWithSignatures.test.d.ts.map +1 -0
  48. package/dist/tbv/core/primitives/psbt/finalizeScriptPathWithSignatures.d.ts +52 -0
  49. package/dist/tbv/core/primitives/psbt/finalizeScriptPathWithSignatures.d.ts.map +1 -0
  50. package/dist/tbv/core/primitives/psbt/reclaim.d.ts +23 -1
  51. package/dist/tbv/core/primitives/psbt/reclaim.d.ts.map +1 -1
  52. package/dist/tbv/core/services/index.cjs +1 -1
  53. package/dist/tbv/core/services/index.js +2 -2
  54. package/dist/tbv/core/services/reclaim/__tests__/buildAndBroadcastReclaim.walletPsbt.test.d.ts +14 -0
  55. package/dist/tbv/core/services/reclaim/__tests__/buildAndBroadcastReclaim.walletPsbt.test.d.ts.map +1 -0
  56. package/dist/tbv/core/services/reclaim/buildAndBroadcastReclaim.d.ts +14 -2
  57. package/dist/tbv/core/services/reclaim/buildAndBroadcastReclaim.d.ts.map +1 -1
  58. package/dist/tbv/core/services/refund/buildAndBroadcastRefund.d.ts.map +1 -1
  59. package/dist/tbv/core/utils/index.cjs +1 -1
  60. package/dist/tbv/core/utils/index.js +13 -13
  61. package/dist/tbv/index.cjs +1 -1
  62. package/dist/tbv/index.js +222 -221
  63. package/dist/toRefundInputs-CY9u84U9.cjs +2 -0
  64. package/dist/{toRefundInputs-Bdtz8p27.cjs.map → toRefundInputs-CY9u84U9.cjs.map} +1 -1
  65. package/dist/{toRefundInputs-CgXMcHrk.js → toRefundInputs-Df1vi23S.js} +5 -5
  66. package/dist/{toRefundInputs-CgXMcHrk.js.map → toRefundInputs-Df1vi23S.js.map} +1 -1
  67. package/dist/{verifyScriptPathSchnorrSignature-mzYCzaSy.cjs → verifyScriptPathSchnorrSignature-BfNUSgA7.cjs} +2 -2
  68. package/dist/{verifyScriptPathSchnorrSignature-mzYCzaSy.cjs.map → verifyScriptPathSchnorrSignature-BfNUSgA7.cjs.map} +1 -1
  69. package/dist/{verifyScriptPathSchnorrSignature-ZAZfFJ6S.js → verifyScriptPathSchnorrSignature-Ciq_xZhw.js} +5 -4
  70. package/dist/{verifyScriptPathSchnorrSignature-ZAZfFJ6S.js.map → verifyScriptPathSchnorrSignature-Ciq_xZhw.js.map} +1 -1
  71. package/dist/waitForTransactionReceiptSmartAware-DpQ69ySe.cjs +2 -0
  72. package/dist/waitForTransactionReceiptSmartAware-DpQ69ySe.cjs.map +1 -0
  73. package/dist/{waitForTransactionReceiptSmartAware-B6oYRdFO.js → waitForTransactionReceiptSmartAware-z3Xfmo44.js} +42 -47
  74. package/dist/waitForTransactionReceiptSmartAware-z3Xfmo44.js.map +1 -0
  75. package/package.json +1 -1
  76. package/dist/PeginManager-BIKAnZ-X.cjs +0 -2
  77. package/dist/buildAndBroadcastReclaim-kRx7-o2y.cjs +0 -2
  78. package/dist/mempoolApi-BQllf-ji.cjs +0 -2
  79. package/dist/mempoolApi-BQllf-ji.cjs.map +0 -1
  80. package/dist/mempoolApi-CRNMOsbC.js.map +0 -1
  81. package/dist/noPayout--lxo7qe4.js +0 -300
  82. package/dist/noPayout--lxo7qe4.js.map +0 -1
  83. package/dist/noPayout-CegnEwfp.cjs +0 -2
  84. package/dist/noPayout-CegnEwfp.cjs.map +0 -1
  85. package/dist/primeVpAuth-D1qbOkhb.js.map +0 -1
  86. package/dist/primeVpAuth-tEXx9TGx.cjs.map +0 -1
  87. package/dist/signing-Bnsro0hE.cjs +0 -2
  88. package/dist/signing-Bnsro0hE.cjs.map +0 -1
  89. package/dist/signing-DaLvGwQe.js +0 -16
  90. package/dist/signing-DaLvGwQe.js.map +0 -1
  91. package/dist/toRefundInputs-Bdtz8p27.cjs +0 -2
  92. package/dist/waitForTransactionReceiptSmartAware-B6oYRdFO.js.map +0 -1
  93. package/dist/waitForTransactionReceiptSmartAware-Ct7LPwPI.cjs +0 -2
  94. package/dist/waitForTransactionReceiptSmartAware-Ct7LPwPI.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"primeVpAuth-tLRjdHwZ.js","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","../src/tbv/core/clients/vault-provider/auth/cbor.ts","../src/tbv/core/clients/vault-provider/auth/serverIdentity.ts","../src/tbv/core/clients/vault-provider/auth/gatedMethods.ts","../src/tbv/core/clients/vault-provider/auth/innerTokenClient.ts","../src/tbv/core/clients/vault-provider/auth/cborDecode.ts","../src/tbv/core/clients/vault-provider/auth/verifyDepositorCwt.ts","../src/tbv/core/clients/vault-provider/auth/tokenProvider.ts","../src/tbv/core/clients/vault-provider/auth/tokenRegistry.ts","../src/tbv/core/clients/vault-provider/auth/createAuthenticatedVpClient.ts","../src/tbv/core/clients/vault-provider/auth/primeVpAuth.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 ) {\n const results = (await this.publicClient.multicall({\n contracts: calls,\n allowFailure: false,\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 ): 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 );\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 async getPegInConfiguration(): Promise<PegInConfiguration> {\n const results = await this.publicClient.multicall({\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 * 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 ): Promise<AddressBTCKeyPair[]> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ApplicationRegistryABI,\n functionName: \"getVaultKeepersByVersion\",\n args: [appEntryPoint, version],\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 ): Promise<number> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ApplicationRegistryABI,\n functionName: \"getCurrentVaultKeepersVersion\",\n args: [appEntryPoint],\n })) as number;\n\n return result;\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 ): Promise<AddressBTCKeyPair[]> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getUniversalChallengersByVersion\",\n args: [version],\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(): Promise<number> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"latestUniversalChallengersVersion\",\n })) as number;\n\n return result;\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 ): 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\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 getPegInConfiguration(): 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/** Interface for reading vault keepers from the ApplicationRegistry contract. */\nexport interface VaultKeeperReader {\n getVaultKeepersByVersion(\n appEntryPoint: Address,\n version: number,\n ): Promise<AddressBTCKeyPair[]>;\n getCurrentVaultKeepers(appEntryPoint: Address): Promise<AddressBTCKeyPair[]>;\n getCurrentVaultKeepersVersion(appEntryPoint: Address): Promise<number>;\n}\n\n/** Interface for reading universal challengers from the ProtocolParams contract. */\nexport interface UniversalChallengerReader {\n getUniversalChallengersByVersion(\n version: number,\n ): Promise<AddressBTCKeyPair[]>;\n getCurrentUniversalChallengers(): Promise<AddressBTCKeyPair[]>;\n getLatestUniversalChallengersVersion(): Promise<number>;\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(query: OperationKeyQuery): 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","/**\n * Minimal CBOR encoder for the server-identity payload shape.\n *\n * We only need to encode one specific CBOR structure — the 3-tuple\n * `(SERVER_IDENTITY_DOMAIN, ephemeral_pubkey_bytes, expires_at_u64)` —\n * byte-for-byte identical to what the Rust `ciborium` crate produces\n * for the corresponding tuple, because that's the exact message the\n * VP signs with BIP-322.\n *\n * IMPORTANT encoding quirk: the Rust side passes the domain and\n * pubkey as `&[u8]` / `Vec<u8>` without a `#[serde(with = \"serde_bytes\")]`\n * attribute, so serde/ciborium encodes them as **CBOR arrays of u8**\n * (major type 4, one item per byte) — NOT as CBOR byte strings (major\n * type 2). A naive byte-string encoding would produce the wrong bytes\n * and signature verification would fail.\n *\n * Rather than pull in a full CBOR dependency for this one shape, we\n * implement the exact subset inline (~40 LOC) and pin it with golden\n * vectors against the Rust reference output.\n *\n * @module tbv/core/clients/vault-provider/auth/cbor\n */\n\n/**\n * Encode a small CBOR unsigned-integer \"head\" byte for major type\n * `major` (0..7) with argument `arg` (0..2^64-1).\n *\n * Returns the header bytes; the caller concatenates any trailing data\n * (e.g. array elements). Encoding rules:\n * arg < 24 → single byte `(major << 5) | arg`\n * arg < 256 → `(major << 5) | 24` + 1-byte arg\n * arg < 65536 → `(major << 5) | 25` + 2-byte BE arg\n * arg < 2^32 → `(major << 5) | 26` + 4-byte BE arg\n * arg < 2^64 → `(major << 5) | 27` + 8-byte BE arg\n */\nfunction cborHead(major: number, arg: number | bigint): Uint8Array {\n const tag = (major & 0x07) << 5;\n const n = typeof arg === \"bigint\" ? arg : BigInt(arg);\n if (n < 0n) throw new Error(\"cborHead: negative argument\");\n\n if (n < 24n) return new Uint8Array([tag | Number(n)]);\n if (n < 0x100n) return new Uint8Array([tag | 24, Number(n)]);\n if (n < 0x10000n) {\n const v = Number(n);\n return new Uint8Array([tag | 25, (v >>> 8) & 0xff, v & 0xff]);\n }\n if (n < 0x1_0000_0000n) {\n const v = Number(n);\n return new Uint8Array([\n tag | 26,\n (v >>> 24) & 0xff,\n (v >>> 16) & 0xff,\n (v >>> 8) & 0xff,\n v & 0xff,\n ]);\n }\n // 8-byte BE for u64 range\n const out = new Uint8Array(9);\n out[0] = tag | 27;\n for (let i = 7; i >= 0; i--) {\n out[1 + i] = Number(n >> BigInt((7 - i) * 8)) & 0xff;\n }\n return out;\n}\n\nfunction concat(...parts: Uint8Array[]): Uint8Array {\n const total = parts.reduce((s, p) => s + p.length, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const p of parts) {\n out.set(p, offset);\n offset += p.length;\n }\n return out;\n}\n\n/**\n * Encode a `Vec<u8>` / `&[u8]` the way ciborium does by default — as a\n * CBOR array of u8 (major type 4), one element per byte.\n *\n * Each byte becomes a CBOR unsigned integer (major type 0): bytes\n * < 24 are encoded as single bytes, bytes 24..255 as `0x18 XX`.\n */\nfunction encodeBytesAsArrayOfU8(bytes: Uint8Array): Uint8Array {\n const header = cborHead(4, bytes.length);\n const items: Uint8Array[] = [header];\n for (const b of bytes) {\n items.push(cborHead(0, b));\n }\n return concat(...items);\n}\n\n/**\n * Encode the server-identity payload the Rust side signs:\n *\n * ciborium::into_writer(\n * &(SERVER_IDENTITY_DOMAIN, ephemeral_pubkey.serialize().to_vec(), expires_at),\n * buf\n * )\n *\n * Output bytes are byte-for-byte identical to the Rust reference,\n * pinned by the golden vector in the corresponding test file.\n *\n * @internal Exposed only for the golden-vector test that pins this\n * encoding against ciborium's output. Production callers reach this\n * via `verifyServerIdentity` from `./serverIdentity`.\n *\n * @param domain - Must be `\"btc-auth.server-identity.v1\"` (27 bytes)\n * — the constant from btc-vault's `server_identity.rs`.\n * @param ephemeralPubkeyCompressed - 33-byte SEC1-compressed pubkey.\n * @param expiresAt - Unix timestamp (seconds). Must be a safe integer.\n */\nexport function encodeServerIdentityPayload(\n domain: Uint8Array,\n ephemeralPubkeyCompressed: Uint8Array,\n expiresAt: number,\n): Uint8Array {\n if (!Number.isSafeInteger(expiresAt) || expiresAt < 0) {\n throw new Error(\n `encodeServerIdentityPayload: expires_at must be a non-negative safe integer, got ${expiresAt}`,\n );\n }\n const arrayHeader = cborHead(4, 3); // 3-tuple encoded as array of 3\n const domainBytes = encodeBytesAsArrayOfU8(domain);\n const pubkeyBytes = encodeBytesAsArrayOfU8(ephemeralPubkeyCompressed);\n const expiresAtBytes = cborHead(0, expiresAt);\n return concat(arrayHeader, domainBytes, pubkeyBytes, expiresAtBytes);\n}\n","/**\n * Server-identity verification for the vault provider's\n * `auth_createDepositorToken` response.\n *\n * The VP returns a `ServerIdentityResponse` bundled with every issued\n * token:\n *\n * - `server_pubkey`: VP's persistent x-only pubkey (HEX, 32B)\n * - `ephemeral_pubkey`: VP's ephemeral token-signing key (HEX, 33B compressed)\n * - `expires_at`: Unix timestamp when the ephemeral key expires\n * - `signature`: BIP-322 signature by the persistent key over\n * `(SERVER_IDENTITY_DOMAIN, ephemeral_pubkey, expires_at)`\n *\n * The FE pins `server_pubkey` against the on-chain `VaultProvider.btcPubKey`\n * it reads from the registry contract. A mismatch rejects the token.\n *\n * @module tbv/core/clients/vault-provider/auth/serverIdentity\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\n\nimport {\n SCHNORR_SIG_HEX_LEN,\n stripHexPrefix,\n} from \"../../../primitives/utils/bitcoin\";\nimport {\n COMPRESSED_PUBKEY_HEX_LEN,\n HEX_RE,\n X_ONLY_PUBKEY_HEX_LEN,\n} from \"../../../utils/validation\";\n\nimport { verifyBip322Simple } from \"./bip322Verify\";\nimport { encodeServerIdentityPayload } from \"./cbor\";\n\n/**\n * Byte-string domain the btc-vault Rust reference passes as the first\n * element of the CBOR tuple signed over for server-identity proofs.\n * Must match `SERVER_IDENTITY_DOMAIN` in\n * `btc-vault/crates/btc-auth/src/server_identity.rs`.\n */\nconst SERVER_IDENTITY_DOMAIN = new TextEncoder().encode(\n \"btc-auth.server-identity.v1\",\n);\n\n/**\n * Cap on `proof.expires_at - now`. Bounds how long a leaked VP\n * ephemeral key stays usable; the bearer token's own TTL does not\n * (different trust boundary). 2h = Rust ref VP's 1h rotation × 2 for\n * clock skew. Override per call via `maxLifetimeSecs`.\n */\nconst DEFAULT_MAX_PROOF_LIFETIME_SECS = 2 * 3600;\n\n/**\n * Wire representation from btc-vault's `ServerIdentityResponse`.\n */\nexport interface ServerIdentityResponse {\n /** Hex-encoded x-only (32-byte) persistent server pubkey. */\n server_pubkey: string;\n /** Hex-encoded compressed (33-byte) ephemeral token-signing pubkey. */\n ephemeral_pubkey: string;\n /** Unix timestamp at which the ephemeral key expires. */\n expires_at: number;\n /** Hex-encoded 64-byte BIP-322 Schnorr signature. */\n signature: string;\n}\n\nexport interface VerifyServerIdentityInput {\n /** The proof returned by `auth_createDepositorToken`. */\n proof: ServerIdentityResponse;\n /**\n * The x-only persistent server pubkey the FE expects (sourced from\n * the on-chain `VaultProvider.btcPubKey` via the vault registry\n * reader). 64-char lowercase hex, no `0x` prefix.\n */\n pinnedServerPubkey: string;\n /** Current Unix timestamp in seconds. Injected for testability. */\n now: number;\n /** Cap on `proof.expires_at - now` (seconds). Defaults to {@link DEFAULT_MAX_PROOF_LIFETIME_SECS}. */\n maxLifetimeSecs?: number;\n}\n\nexport class ServerIdentityError extends Error {\n constructor(\n message: string,\n public readonly reason:\n | \"pinned_pubkey_mismatch\"\n | \"expired\"\n | \"expires_too_far\"\n | \"invalid_expires_at\"\n | \"invalid_max_lifetime\"\n | \"invalid_pubkey_encoding\"\n | \"invalid_ephemeral_pubkey\"\n | \"invalid_signature_encoding\"\n | \"signature_verification_failed\",\n ) {\n super(message);\n this.name = \"ServerIdentityError\";\n }\n}\n\n/** Parse a lowercase-hex string to bytes. Expects even length, already validated. */\nfunction hexToBytes(hex: string): Uint8Array {\n const out = new Uint8Array(hex.length / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n }\n return out;\n}\n\n/**\n * Verify a server identity proof against a pinned server pubkey.\n *\n * Checks:\n * 1. `server_pubkey` matches the pin.\n * 2. `now < expires_at <= now + maxLifetimeSecs` (with integer guards).\n * 3. `ephemeral_pubkey` is a well-formed 33-byte compressed pubkey.\n * 4. `signature` is a well-formed 64-byte Schnorr hex string.\n * 5. The BIP-322 Schnorr signature cryptographically verifies\n * against `server_pubkey` over the CBOR-encoded tuple\n * `(SERVER_IDENTITY_DOMAIN, ephemeral_pubkey, expires_at)`.\n *\n * Step 5 is what actually binds the ephemeral key to the persistent\n * pubkey — without it, a TLS-MITM attacker who reads the pinned\n * pubkey from the on-chain registry could substitute an arbitrary\n * ephemeral pubkey paired with any lexically-valid signature.\n *\n * @throws ServerIdentityError on any validation failure.\n */\nexport function verifyServerIdentity(input: VerifyServerIdentityInput): void {\n const { proof, pinnedServerPubkey, now } = input;\n const maxLifetimeSecs =\n input.maxLifetimeSecs ?? DEFAULT_MAX_PROOF_LIFETIME_SECS;\n\n const pinned = stripHexPrefix(pinnedServerPubkey).toLowerCase();\n if (pinned.length !== X_ONLY_PUBKEY_HEX_LEN || !HEX_RE.test(pinned)) {\n throw new ServerIdentityError(\n `pinnedServerPubkey must be 32-byte hex; got ${pinned.length} chars`,\n \"invalid_pubkey_encoding\",\n );\n }\n\n const actual = stripHexPrefix(proof.server_pubkey).toLowerCase();\n if (actual.length !== X_ONLY_PUBKEY_HEX_LEN || !HEX_RE.test(actual)) {\n throw new ServerIdentityError(\n `server_pubkey must be 32-byte hex; got ${actual.length} chars`,\n \"invalid_pubkey_encoding\",\n );\n }\n\n if (actual !== pinned) {\n throw new ServerIdentityError(\n `server_pubkey does not match pinned value: expected ${pinned}, got ${actual}`,\n \"pinned_pubkey_mismatch\",\n );\n }\n\n // Validate both sides of the comparison are well-formed integers\n // BEFORE comparing — untrusted JSON-RPC input can supply\n // undefined/NaN/string values for `expires_at`, and relational\n // comparisons with those silently evaluate to `false` (accepting the\n // proof). Caller's `now` is injected but we still sanity-check it.\n // Garbage data and \"valid but past\" both render the proof unusable\n // but mean different things to a caller — keep the reasons distinct.\n if (!Number.isSafeInteger(proof.expires_at)) {\n throw new ServerIdentityError(\n `expires_at must be a finite integer; got ${JSON.stringify(proof.expires_at)}`,\n \"invalid_expires_at\",\n );\n }\n if (!Number.isSafeInteger(now)) {\n throw new ServerIdentityError(\n `now must be a finite integer; got ${JSON.stringify(now)}`,\n \"invalid_expires_at\",\n );\n }\n if (proof.expires_at <= now) {\n throw new ServerIdentityError(\n `server identity proof expired at ${proof.expires_at}, now ${now}`,\n \"expired\",\n );\n }\n if (!Number.isSafeInteger(maxLifetimeSecs) || maxLifetimeSecs <= 0) {\n throw new ServerIdentityError(\n `maxLifetimeSecs must be a positive safe integer; got ${JSON.stringify(maxLifetimeSecs)}`,\n \"invalid_max_lifetime\",\n );\n }\n if (proof.expires_at - now > maxLifetimeSecs) {\n throw new ServerIdentityError(\n `server identity proof expires too far in the future: ` +\n `expires_at=${proof.expires_at}, now=${now}, max lifetime=${maxLifetimeSecs}s`,\n \"expires_too_far\",\n );\n }\n\n const eph = stripHexPrefix(proof.ephemeral_pubkey).toLowerCase();\n if (eph.length !== COMPRESSED_PUBKEY_HEX_LEN || !HEX_RE.test(eph)) {\n throw new ServerIdentityError(\n `ephemeral_pubkey must be 33-byte compressed hex; got ${eph.length} chars`,\n \"invalid_ephemeral_pubkey\",\n );\n }\n const prefix = eph.slice(0, 2);\n if (prefix !== \"02\" && prefix !== \"03\") {\n throw new ServerIdentityError(\n `ephemeral_pubkey must be compressed (prefix 02/03); got ${prefix}`,\n \"invalid_ephemeral_pubkey\",\n );\n }\n // Curve validation. The BIP-322 signature attests to the byte string\n // of `ephemeral_pubkey` only, not to its curve validity. Without\n // this check, a server could sign a structurally-valid byte string\n // that doesn't decode to a secp256k1 point — passing verification\n // here and surfacing as an obscure crypto error later when the\n // depositor tries to use the key. Reject up front.\n const ephBytes = hexToBytes(eph);\n if (!ecc.isPoint(ephBytes)) {\n throw new ServerIdentityError(\n \"ephemeral_pubkey is not a valid secp256k1 point\",\n \"invalid_ephemeral_pubkey\",\n );\n }\n\n const sig = stripHexPrefix(proof.signature).toLowerCase();\n if (sig.length !== SCHNORR_SIG_HEX_LEN || !HEX_RE.test(sig)) {\n throw new ServerIdentityError(\n `signature must be 64-byte Schnorr hex; got ${sig.length} chars`,\n \"invalid_signature_encoding\",\n );\n }\n\n // Cryptographic verification of the BIP-322 signature over the\n // CBOR-encoded payload. Without this, the ephemeral-key binding is\n // unenforced and a TLS-MITM could substitute a fake ephemeral key\n // alongside the real (publicly-readable) pinned pubkey.\n const payload = encodeServerIdentityPayload(\n SERVER_IDENTITY_DOMAIN,\n hexToBytes(eph),\n proof.expires_at,\n );\n const verified = verifyBip322Simple(\n payload,\n hexToBytes(actual),\n hexToBytes(sig),\n );\n if (!verified) {\n throw new ServerIdentityError(\n \"BIP-322 signature verification failed — ephemeral key is not attested by pinned server pubkey\",\n \"signature_verification_failed\",\n );\n }\n}\n","/**\n * VP RPC methods that require `Authorization: Bearer <token>`.\n * Protocol invariant — must be kept in sync with the VP server.\n *\n * Split into two sets by the CWT subject the VP demands:\n *\n * - {@link AUTH_GATED_METHODS} — bearer minted by\n * `auth_createDepositorToken` (Subject::VaultdJsonRpc). These run\n * through the proxy's plain JSON-RPC forward path.\n * - {@link GRPC_AUTH_GATED_METHODS} — bearer minted by\n * `auth_createDepositorTokenGrpc` (Subject::VaultdGrpc). The proxy\n * translates these into gRPC calls to vaultd's daemon gRPC server,\n * so a JSON-RPC-subject token would be rejected by\n * `GrpcAuthInterceptor`.\n *\n * @stability frozen\n *\n * @module tbv/core/clients/vault-provider/auth/gatedMethods\n */\n\nexport const AUTH_GATED_METHODS: ReadonlySet<string> = new Set([\n \"vaultProvider_submitDepositorWotsKey\",\n \"vaultProvider_submitDepositorPresignatures\",\n \"vaultProvider_requestDepositorPresignTransactions\",\n]);\n\nexport const GRPC_AUTH_GATED_METHODS: ReadonlySet<string> = new Set([\n \"vaultProvider_requestDepositorClaimerArtifacts\",\n]);\n","/**\n * Shared internals for the unauthenticated token-issuing JSON-RPC\n * client. The \"inner\" client is dedicated to `auth_createDepositorToken`\n * — it MUST NOT carry a `tokenProvider`, else the JSON-RPC header\n * builder would recurse into token acquisition.\n *\n * @module tbv/core/clients/vault-provider/auth/innerTokenClient\n */\n\nimport { JsonRpcClient } from \"../json-rpc-client\";\n\nconst TOKEN_RPC_TIMEOUT_MS = 60_000;\n\nexport const TOKEN_ISSUE_METHOD = \"auth_createDepositorToken\";\n/**\n * gRPC-subject sibling of {@link TOKEN_ISSUE_METHOD}. The proxy bridges\n * this call to vaultd's `VaultProviderDepositorAuthService.CreateDepositorToken`\n * so the resulting CWT is bound to `Subject::VaultdGrpc` — required to\n * pass vaultd's `GrpcAuthInterceptor` on methods the proxy translates to\n * gRPC (currently just the artifact stream).\n */\nexport const GRPC_TOKEN_ISSUE_METHOD = \"auth_createDepositorTokenGrpc\";\n\nexport function buildInnerTokenClient(\n baseUrl: string,\n headers?: Record<string, string>,\n): JsonRpcClient {\n return new JsonRpcClient({\n baseUrl,\n timeout: TOKEN_RPC_TIMEOUT_MS,\n headers,\n retryableFor: (method) =>\n method === TOKEN_ISSUE_METHOD || method === GRPC_TOKEN_ISSUE_METHOD,\n });\n}\n","/**\n * Minimal CBOR decoder — the read-side counterpart to {@link ./cbor}.\n *\n * Decodes only the subset needed to verify a vault-provider CWT bearer\n * token (RFC 8392) wrapped in a COSE Sign1 envelope (RFC 8152): tagged\n * values, definite-length arrays and maps, byte/text strings, and\n * unsigned/negative integers. Indefinite-length items, floats, and\n * big-number tags are intentionally rejected — the issuer\n * (btc-vault's `coset`/`ciborium` stack) never emits them for this\n * shape, so accepting them would only widen the parser's attack\n * surface.\n *\n * The decoder is a cursor over a single buffer. {@link CborReader.pos}\n * is public so callers can slice the exact encoded byte range of an\n * item (head + content) — required to reconstruct the COSE\n * `Sig_structure` byte-for-byte from the token's own protected-header\n * and payload byte strings.\n *\n * @module tbv/core/clients/vault-provider/auth/cborDecode\n */\n\n/** CBOR major types (the high 3 bits of the initial byte). */\nconst MAJOR_UNSIGNED_INT = 0;\nconst MAJOR_NEGATIVE_INT = 1;\nconst MAJOR_BYTE_STRING = 2;\nconst MAJOR_TEXT_STRING = 3;\nconst MAJOR_ARRAY = 4;\nconst MAJOR_MAP = 5;\nconst MAJOR_TAG = 6;\nconst MAJOR_SIMPLE = 7;\n\n/**\n * Smallest additional-info value that introduces a multi-byte argument\n * (24 ⇒ 1 byte, 25 ⇒ 2, 26 ⇒ 4, 27 ⇒ 8 — i.e. `1 << (info - 24)`).\n */\nconst ARG_IN_NEXT_1_BYTE = 24;\n/** Additional-info ≥ this (28..31) is reserved/indefinite — unsupported. */\nconst ARG_RESERVED_MIN = 28;\n\n/** Major-7 simple values we accept. */\nconst SIMPLE_FALSE = 20;\nconst SIMPLE_TRUE = 21;\nconst SIMPLE_NULL = 22;\n\n/**\n * Maximum CBOR nesting depth. Mirrors the issuer's recursion cap (256 in\n * btc-vault's `ciborium` stack). The COSE protected header is decoded\n * *before* the signature is verified, so without this bound a\n * malicious/MITM'd VP could send a deeply-nested blob and crash token\n * acquisition with an uncatchable stack overflow. Far below the JS call\n * stack limit, so it converts that DoS into a catchable decode error.\n */\nconst MAX_NESTING_DEPTH = 256;\n\n/** A decoded CBOR data item. Maps preserve key insertion order. */\nexport type CborValue =\n | number\n | bigint\n | string\n | Uint8Array\n | boolean\n | null\n | CborValue[]\n | Map<CborValue, CborValue>\n | CborTagged;\n\n/** A CBOR tagged value (major type 6). */\nexport interface CborTagged {\n tag: number;\n value: CborValue;\n}\n\n/** Parsed initial-byte header: major type plus its decoded argument. */\nexport interface CborHead {\n major: number;\n /** The header argument (length, value, tag number, …) as a number. */\n arg: number;\n}\n\nexport class CborDecodeError extends Error {\n constructor(message: string) {\n super(`CBOR decode: ${message}`);\n this.name = \"CborDecodeError\";\n }\n}\n\n/**\n * Cursor-based reader over a CBOR buffer. Not reusable across buffers —\n * construct one per decode.\n */\nexport class CborReader {\n readonly buf: Uint8Array;\n /** Current read offset. Public so callers can slice encoded sub-ranges. */\n pos = 0;\n\n constructor(buf: Uint8Array) {\n this.buf = buf;\n }\n\n private nextByte(): number {\n if (this.pos >= this.buf.length) {\n throw new CborDecodeError(\"unexpected end of input\");\n }\n return this.buf[this.pos++];\n }\n\n /**\n * Read an initial byte and its argument. Rejects indefinite-length\n * and reserved additional-info encodings. Arguments wider than\n * {@link Number.MAX_SAFE_INTEGER} are rejected — none of the token's\n * lengths, tags, or timestamps approach that bound.\n */\n readHead(): CborHead {\n const initial = this.nextByte();\n const major = initial >> 5;\n const info = initial & 0x1f;\n\n if (info < ARG_IN_NEXT_1_BYTE) {\n return { major, arg: info };\n }\n if (info >= ARG_RESERVED_MIN) {\n throw new CborDecodeError(\n `unsupported additional info ${info} (indefinite-length or reserved)`,\n );\n }\n\n const byteCount = 1 << (info - ARG_IN_NEXT_1_BYTE);\n\n let value = 0n;\n for (let i = 0; i < byteCount; i++) {\n value = (value << 8n) | BigInt(this.nextByte());\n }\n if (value > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new CborDecodeError(`argument ${value} exceeds safe integer range`);\n }\n return { major, arg: Number(value) };\n }\n\n /** Read `length` raw bytes as a sub-array view into the backing buffer. */\n private readBytes(length: number): Uint8Array {\n if (this.pos + length > this.buf.length) {\n throw new CborDecodeError(\"length overruns end of input\");\n }\n const slice = this.buf.subarray(this.pos, this.pos + length);\n this.pos += length;\n return slice;\n }\n\n /**\n * Read a byte string (major type 2), returning its content bytes.\n * Throws if the next item is not a byte string.\n */\n readByteString(): Uint8Array {\n const head = this.readHead();\n if (head.major !== MAJOR_BYTE_STRING) {\n throw new CborDecodeError(\n `expected byte string (major ${MAJOR_BYTE_STRING}), got major ${head.major}`,\n );\n }\n return this.readBytes(head.arg);\n }\n\n /**\n * Read the next complete data item as a decoded {@link CborValue}.\n *\n * `depth` tracks the current nesting level so a deeply-nested blob is\n * rejected with a {@link CborDecodeError} rather than overflowing the\n * native call stack (see {@link MAX_NESTING_DEPTH}).\n */\n readValue(depth = 0): CborValue {\n if (depth > MAX_NESTING_DEPTH) {\n throw new CborDecodeError(\n `nesting exceeds maximum depth ${MAX_NESTING_DEPTH}`,\n );\n }\n const head = this.readHead();\n switch (head.major) {\n case MAJOR_UNSIGNED_INT:\n return head.arg;\n case MAJOR_NEGATIVE_INT:\n // RFC 8949 §3.1: the encoded argument n represents -1 - n.\n return -1 - head.arg;\n case MAJOR_BYTE_STRING:\n return this.readBytes(head.arg);\n case MAJOR_TEXT_STRING:\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(\n this.readBytes(head.arg),\n );\n case MAJOR_ARRAY: {\n const items: CborValue[] = [];\n for (let i = 0; i < head.arg; i++) {\n items.push(this.readValue(depth + 1));\n }\n return items;\n }\n case MAJOR_MAP: {\n const map = new Map<CborValue, CborValue>();\n for (let i = 0; i < head.arg; i++) {\n const key = this.readValue(depth + 1);\n const value = this.readValue(depth + 1);\n map.set(key, value);\n }\n return map;\n }\n case MAJOR_TAG:\n return { tag: head.arg, value: this.readValue(depth + 1) };\n case MAJOR_SIMPLE:\n if (head.arg === SIMPLE_FALSE) return false;\n if (head.arg === SIMPLE_TRUE) return true;\n if (head.arg === SIMPLE_NULL) return null;\n throw new CborDecodeError(\n `unsupported simple/float value ${head.arg}`,\n );\n default:\n throw new CborDecodeError(`unsupported major type ${head.major}`);\n }\n }\n}\n\n/**\n * Decode a single CBOR item from `bytes`, rejecting any trailing bytes.\n *\n * Used to parse the COSE protected header and CWT claims set — both are\n * exactly one top-level item, so a valid prefix followed by extra bytes\n * is a malformed structure, not a benign tail. Strict consumption keeps\n * the parser from silently accepting a token a stricter CWT/COSE\n * consumer would interpret differently.\n */\nexport function decodeCbor(bytes: Uint8Array): CborValue {\n const reader = new CborReader(bytes);\n const value = reader.readValue();\n if (reader.pos !== bytes.length) {\n throw new CborDecodeError(\"trailing bytes after top-level item\");\n }\n return value;\n}\n","/**\n * Verify a vault-provider CWT bearer (RFC 8392 / COSE Sign1, ES256K): checks the\n * signature against the VP's attested ephemeral key (see {@link ./serverIdentity})\n * and binds `iss`/`sub`/`aud` to the pinned VP, subject, and depositor. TS port\n * of btc-vault `client.rs::validate_token_with_public_key_at_time`.\n *\n * Divergence from that reference: the FE does NOT clock-gate `nbf`/`iat`. The VP\n * server is the temporal authority and re-checks `nbf`/`exp` on every gated call;\n * re-checking `nbf` against the browser clock only bricked freshly minted tokens\n * on benign skew. `exp` (wide window) and the structural `iat <= exp` are kept.\n *\n * @module tbv/core/clients/vault-provider/auth/verifyDepositorCwt\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\n\nimport {\n hexToUint8Array,\n stripHexPrefix,\n} from \"../../../primitives/utils/bitcoin\";\nimport {\n COMPRESSED_PUBKEY_HEX_LEN,\n HEX_RE,\n X_ONLY_PUBKEY_HEX_LEN,\n} from \"../../../utils/validation\";\n\nimport { CborReader, decodeCbor } from \"./cborDecode\";\n\n/** CWT `sub` value for JSON-RPC-subject tokens (`auth_createDepositorToken`). */\nexport const CWT_SUBJECT_JSONRPC = \"vaultd-jsonrpc\";\n/** CWT `sub` value for gRPC-subject tokens (`auth_createDepositorTokenGrpc`). */\nexport const CWT_SUBJECT_GRPC = \"vaultd-grpc\";\n\n/** CBOR tag wrapping a COSE_Sign1 structure (RFC 8152 §2). */\nconst COSE_SIGN1_TAG = 18;\n/** A COSE_Sign1 is a 4-element array: [protected, unprotected, payload, signature]. */\nconst COSE_SIGN1_ARRAY_LEN = 4;\n/** COSE algorithm id for ES256K (ECDSA w/ secp256k1 + SHA-256), RFC 8812. */\nconst COSE_ALG_ES256K = -47;\n/** COSE header label for the algorithm (RFC 8152 §3.1). */\nconst COSE_HEADER_LABEL_ALG = 1;\n/** ECDSA signature length in COSE compact (r‖s) form. */\nconst ECDSA_COMPACT_SIG_LEN = 64;\n\n/** CBOR major-type 4 (array) high bits, for the Sig_structure header. */\nconst CBOR_ARRAY_HEAD = 0x80;\n/** CBOR major-type 3 (text string) high bits, for the context string head. */\nconst CBOR_TEXT_STRING_HEAD = 0x60;\n/** CBOR encoding of an empty byte string (major type 2, length 0). */\nconst CBOR_EMPTY_BYTE_STRING = 0x40;\n\n/** CWT registered claim keys (RFC 8392 §4 / IANA CWT registry). */\nconst CWT_CLAIM_ISS = 1;\nconst CWT_CLAIM_SUB = 2;\nconst CWT_CLAIM_AUD = 3;\nconst CWT_CLAIM_EXP = 4;\nconst CWT_CLAIM_NBF = 5;\nconst CWT_CLAIM_IAT = 6;\nconst CWT_CLAIM_CTI = 7;\n\n/**\n * Context string for a COSE_Sign1 Sig_structure (RFC 8152 §4.4). 10\n * bytes, so it encodes with a single-byte CBOR text-string head.\n */\nconst SIG_STRUCTURE_CONTEXT = new TextEncoder().encode(\"Signature1\");\n\nexport type CwtVerificationReason =\n | \"invalid_input\"\n | \"invalid_token_structure\"\n | \"unexpected_algorithm\"\n | \"signature_verification_failed\"\n | \"invalid_claims\"\n | \"issuer_mismatch\"\n | \"subject_mismatch\"\n | \"audience_mismatch\"\n | \"token_expired\"\n | \"expiry_mismatch\"\n | \"server_identity_expires_before_token\";\n\nexport class CwtVerificationError extends Error {\n constructor(\n message: string,\n public readonly reason: CwtVerificationReason,\n ) {\n super(message);\n this.name = \"CwtVerificationError\";\n }\n}\n\nexport interface VerifyDepositorCwtInput {\n /** Base64url (no padding) COSE Sign1 token from `auth_createDepositorToken`. */\n token: string;\n /**\n * VP ephemeral token-signing pubkey (33-byte compressed hex) from the\n * bundled `server_identity` proof — MUST already be verified by\n * {@link verifyServerIdentity} before being passed here.\n */\n ephemeralPubkeyHex: string;\n /** Pinned VP persistent x-only pubkey (on-chain). Asserted against the token `iss`. */\n expectedIssuerXOnlyPubkey: string;\n /** Expected `sub` — {@link CWT_SUBJECT_JSONRPC} or {@link CWT_SUBJECT_GRPC}. */\n expectedSubject: string;\n /** Depositor x-only pubkey. Asserted against the token `aud`. */\n expectedAudienceXOnlyPubkey: string;\n /** Outer wire `expires_at`. Must equal the token's `exp` exactly. */\n responseExpiresAt: number;\n /** `server_identity.expires_at`. Must be ≥ the token's `exp`. */\n serverIdentityExpiresAt: number;\n /** Current Unix time (seconds). Injected for testability. */\n now: number;\n}\n\nexport interface VerifiedCwtClaims {\n issuer: string;\n subject: string;\n audience: string;\n expiresAt: number;\n notBefore: number;\n issuedAt: number;\n}\n\n/**\n * Verify a depositor CWT and return its claims, or throw\n * {@link CwtVerificationError}.\n *\n * Steps (mirroring the Rust reference; see the divergence note above):\n * 1. Decode the COSE Sign1 envelope and assert the protected header\n * pins ES256K.\n * 2. Verify the ECDSA signature over the reconstructed Sig_structure\n * against the (already server-identity-verified) ephemeral key.\n * 3. Decode the CWT claims and assert `iss`/`sub`/`aud` bindings, the\n * structural `iat <= exp`, `exp` validity, `cti` presence, and the\n * outer-vs-inner expiry cross-checks. `nbf`/`iat` are intentionally not\n * clock-gated here (see the module note above).\n */\nexport function verifyDepositorCwt(\n input: VerifyDepositorCwtInput,\n): VerifiedCwtClaims {\n const expectedIssuer = normalizeXOnly(\n input.expectedIssuerXOnlyPubkey,\n \"expectedIssuerXOnlyPubkey\",\n );\n const expectedAudience = normalizeXOnly(\n input.expectedAudienceXOnlyPubkey,\n \"expectedAudienceXOnlyPubkey\",\n );\n const ephemeral = decodeCompressedPubkey(input.ephemeralPubkeyHex);\n\n const tokenBytes = base64UrlToBytes(input.token);\n\n // --- 1. COSE Sign1 structural decode -------------------------------\n // Capture the exact encoded byte ranges of the protected header and\n // payload so the Sig_structure can be rebuilt byte-for-byte from the\n // token's own bytes (any re-encoding risks a non-canonical mismatch).\n const reader = new CborReader(tokenBytes);\n const tag = reader.readHead();\n if (tag.major !== 6 || tag.arg !== COSE_SIGN1_TAG) {\n throw new CwtVerificationError(\n `token is not a COSE Sign1 tagged value (tag ${COSE_SIGN1_TAG})`,\n \"invalid_token_structure\",\n );\n }\n const array = reader.readHead();\n if (array.major !== 4 || array.arg !== COSE_SIGN1_ARRAY_LEN) {\n throw new CwtVerificationError(\n `COSE Sign1 must be a ${COSE_SIGN1_ARRAY_LEN}-element array`,\n \"invalid_token_structure\",\n );\n }\n\n const protectedStart = reader.pos;\n const protectedContent = reader.readByteString();\n const protectedBstr = tokenBytes.subarray(protectedStart, reader.pos);\n\n // Unprotected header map: present in the envelope but unused here.\n reader.readValue();\n\n const payloadStart = reader.pos;\n const payloadContent = reader.readByteString();\n const payloadBstr = tokenBytes.subarray(payloadStart, reader.pos);\n\n const signature = reader.readByteString();\n if (signature.length !== ECDSA_COMPACT_SIG_LEN) {\n throw new CwtVerificationError(\n `COSE signature must be ${ECDSA_COMPACT_SIG_LEN} bytes, got ${signature.length}`,\n \"invalid_token_structure\",\n );\n }\n // Reject anything after the COSE_Sign1 structure. The bearer we verify\n // must be the exact bytes attached to authenticated calls; a stricter\n // CWT/COSE consumer could interpret trailing bytes differently.\n if (reader.pos !== tokenBytes.length) {\n throw new CwtVerificationError(\n \"COSE Sign1 token has trailing bytes after the signature\",\n \"invalid_token_structure\",\n );\n }\n\n // --- 2a. Algorithm pin --------------------------------------------\n const alg = readProtectedAlgorithm(protectedContent);\n if (alg !== COSE_ALG_ES256K) {\n throw new CwtVerificationError(\n `unexpected COSE algorithm ${alg} (expected ES256K ${COSE_ALG_ES256K})`,\n \"unexpected_algorithm\",\n );\n }\n\n // --- 2b. Signature verification -----------------------------------\n const sigStructure = buildSigStructure(protectedBstr, payloadBstr);\n const digest = sha256(sigStructure);\n // strict = true enforces low-S, matching libsecp256k1's `verify_ecdsa`.\n if (!ecc.verify(digest, ephemeral, signature, true)) {\n throw new CwtVerificationError(\n \"COSE signature does not verify against the server's ephemeral key\",\n \"signature_verification_failed\",\n );\n }\n\n // --- 3. Claims -----------------------------------------------------\n const claims = decodeClaims(payloadContent);\n\n const audience = claims.audience.toLowerCase();\n if (audience.length !== X_ONLY_PUBKEY_HEX_LEN || !HEX_RE.test(audience)) {\n throw new CwtVerificationError(\n \"token `aud` is not a 32-byte x-only pubkey hex\",\n \"invalid_claims\",\n );\n }\n if (claims.issuedAt > claims.expiresAt) {\n throw new CwtVerificationError(\n `token iat (${claims.issuedAt}) is after exp (${claims.expiresAt})`,\n \"invalid_claims\",\n );\n }\n\n if (claims.issuer.toLowerCase() !== expectedIssuer) {\n throw new CwtVerificationError(\n `token issuer does not match pinned server pubkey: expected ${expectedIssuer}, got ${claims.issuer.toLowerCase()}`,\n \"issuer_mismatch\",\n );\n }\n if (claims.subject !== input.expectedSubject) {\n throw new CwtVerificationError(\n `token subject mismatch: expected ${input.expectedSubject}, got ${claims.subject}`,\n \"subject_mismatch\",\n );\n }\n if (audience !== expectedAudience) {\n throw new CwtVerificationError(\n `token audience does not match depositor pubkey: expected ${expectedAudience}, got ${audience}`,\n \"audience_mismatch\",\n );\n }\n // No nbf/iat clock-gate on purpose — the VP server is the temporal authority\n // (re-checks nbf/exp per call). See the module-level divergence note.\n if (claims.expiresAt <= input.now) {\n throw new CwtVerificationError(\n `token expired: exp ${claims.expiresAt} <= now ${input.now}`,\n \"token_expired\",\n );\n }\n if (input.responseExpiresAt !== claims.expiresAt) {\n throw new CwtVerificationError(\n `response expires_at (${input.responseExpiresAt}) does not equal token exp (${claims.expiresAt})`,\n \"expiry_mismatch\",\n );\n }\n if (input.serverIdentityExpiresAt < claims.expiresAt) {\n throw new CwtVerificationError(\n `server identity expires (${input.serverIdentityExpiresAt}) before token exp (${claims.expiresAt})`,\n \"server_identity_expires_before_token\",\n );\n }\n\n return {\n issuer: claims.issuer,\n subject: claims.subject,\n audience,\n expiresAt: claims.expiresAt,\n notBefore: claims.notBefore,\n issuedAt: claims.issuedAt,\n };\n}\n\n/** Read the algorithm label from the COSE protected-header byte string. */\nfunction readProtectedAlgorithm(protectedContent: Uint8Array): number {\n if (protectedContent.length === 0) {\n throw new CwtVerificationError(\n \"empty COSE protected header (no algorithm)\",\n \"unexpected_algorithm\",\n );\n }\n const header = decodeCbor(protectedContent);\n if (!(header instanceof Map)) {\n throw new CwtVerificationError(\n \"COSE protected header is not a map\",\n \"invalid_token_structure\",\n );\n }\n const alg = header.get(COSE_HEADER_LABEL_ALG);\n if (typeof alg !== \"number\") {\n throw new CwtVerificationError(\n \"COSE protected header missing integer algorithm label\",\n \"unexpected_algorithm\",\n );\n }\n return alg;\n}\n\n/**\n * Rebuild the COSE_Sign1 Sig_structure (RFC 8152 §4.4):\n *\n * [ \"Signature1\", body_protected (bstr), external_aad = h'' , payload (bstr) ]\n *\n * `body_protected` and `payload` are spliced verbatim from the token's\n * own encoded byte strings, so the result is byte-identical to what the\n * issuer signed regardless of CBOR canonicalization choices.\n */\nfunction buildSigStructure(\n protectedBstr: Uint8Array,\n payloadBstr: Uint8Array,\n): Uint8Array {\n return concatBytes(\n Uint8Array.of(CBOR_ARRAY_HEAD | COSE_SIGN1_ARRAY_LEN),\n Uint8Array.of(CBOR_TEXT_STRING_HEAD | SIG_STRUCTURE_CONTEXT.length),\n SIG_STRUCTURE_CONTEXT,\n protectedBstr,\n Uint8Array.of(CBOR_EMPTY_BYTE_STRING),\n payloadBstr,\n );\n}\n\ninterface DecodedClaims {\n issuer: string;\n subject: string;\n audience: string;\n expiresAt: number;\n notBefore: number;\n issuedAt: number;\n}\n\n/** Decode and type-check the CWT registered claims from the payload. */\nfunction decodeClaims(payloadContent: Uint8Array): DecodedClaims {\n const root = decodeCbor(payloadContent);\n if (!(root instanceof Map)) {\n throw new CwtVerificationError(\n \"CWT claims root is not a map\",\n \"invalid_claims\",\n );\n }\n const cti = requireBytes(root, CWT_CLAIM_CTI, \"cti\");\n if (cti.length === 0) {\n throw new CwtVerificationError(\"token cti is empty\", \"invalid_claims\");\n }\n return {\n issuer: requireString(root, CWT_CLAIM_ISS, \"iss\"),\n subject: requireString(root, CWT_CLAIM_SUB, \"sub\"),\n audience: requireString(root, CWT_CLAIM_AUD, \"aud\"),\n expiresAt: requireTimestamp(root, CWT_CLAIM_EXP, \"exp\"),\n notBefore: requireTimestamp(root, CWT_CLAIM_NBF, \"nbf\"),\n issuedAt: requireTimestamp(root, CWT_CLAIM_IAT, \"iat\"),\n };\n}\n\nfunction requireString(\n claims: Map<unknown, unknown>,\n key: number,\n name: string,\n): string {\n const value = claims.get(key);\n if (typeof value !== \"string\") {\n throw new CwtVerificationError(\n `token claim ${name} is missing or not a text string`,\n \"invalid_claims\",\n );\n }\n return value;\n}\n\nfunction requireBytes(\n claims: Map<unknown, unknown>,\n key: number,\n name: string,\n): Uint8Array {\n const value = claims.get(key);\n if (!(value instanceof Uint8Array)) {\n throw new CwtVerificationError(\n `token claim ${name} is missing or not a byte string`,\n \"invalid_claims\",\n );\n }\n return value;\n}\n\nfunction requireTimestamp(\n claims: Map<unknown, unknown>,\n key: number,\n name: string,\n): number {\n const value = claims.get(key);\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 0) {\n throw new CwtVerificationError(\n `token claim ${name} is missing or not a non-negative integer timestamp`,\n \"invalid_claims\",\n );\n }\n return value;\n}\n\n/** Validate and normalize a 32-byte x-only pubkey to lowercase hex. */\nfunction normalizeXOnly(pubkey: string, label: string): string {\n const normalized = stripHexPrefix(pubkey).toLowerCase();\n if (normalized.length !== X_ONLY_PUBKEY_HEX_LEN || !HEX_RE.test(normalized)) {\n throw new CwtVerificationError(\n `${label} must be 32-byte x-only hex; got ${normalized.length} chars`,\n \"invalid_input\",\n );\n }\n return normalized;\n}\n\n/** Validate a 33-byte compressed pubkey hex and return its bytes. */\nfunction decodeCompressedPubkey(pubkeyHex: string): Uint8Array {\n const normalized = stripHexPrefix(pubkeyHex).toLowerCase();\n const prefix = normalized.slice(0, 2);\n if (\n normalized.length !== COMPRESSED_PUBKEY_HEX_LEN ||\n !HEX_RE.test(normalized) ||\n (prefix !== \"02\" && prefix !== \"03\")\n ) {\n throw new CwtVerificationError(\n \"ephemeralPubkeyHex must be 33-byte compressed pubkey hex (prefix 02/03)\",\n \"invalid_input\",\n );\n }\n return hexToUint8Array(normalized);\n}\n\nconst B64URL_LOOKUP = (() => {\n const table = new Int16Array(128).fill(-1);\n const alphabet =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n for (let i = 0; i < alphabet.length; i++) {\n table[alphabet.charCodeAt(i)] = i;\n }\n return table;\n})();\n\n/** Decode a base64url (no-padding) string to bytes. */\nfunction base64UrlToBytes(input: string): Uint8Array {\n const len = input.length;\n const fullGroups = Math.floor(len / 4);\n const remainder = len % 4;\n if (remainder === 1) {\n throw new CwtVerificationError(\n \"invalid base64url length\",\n \"invalid_token_structure\",\n );\n }\n const outLen = fullGroups * 3 + (remainder === 0 ? 0 : remainder - 1);\n const out = new Uint8Array(outLen);\n\n const sextet = (charCode: number): number => {\n const value = charCode < 128 ? B64URL_LOOKUP[charCode] : -1;\n if (value < 0) {\n throw new CwtVerificationError(\n \"invalid base64url character\",\n \"invalid_token_structure\",\n );\n }\n return value;\n };\n\n let inPos = 0;\n let outPos = 0;\n for (let g = 0; g < fullGroups; g++) {\n const a = sextet(input.charCodeAt(inPos++));\n const b = sextet(input.charCodeAt(inPos++));\n const c = sextet(input.charCodeAt(inPos++));\n const d = sextet(input.charCodeAt(inPos++));\n out[outPos++] = (a << 2) | (b >> 4);\n out[outPos++] = ((b & 0x0f) << 4) | (c >> 2);\n out[outPos++] = ((c & 0x03) << 6) | d;\n }\n if (remainder === 2) {\n const a = sextet(input.charCodeAt(inPos++));\n const b = sextet(input.charCodeAt(inPos++));\n out[outPos++] = (a << 2) | (b >> 4);\n } else if (remainder === 3) {\n const a = sextet(input.charCodeAt(inPos++));\n const b = sextet(input.charCodeAt(inPos++));\n const c = sextet(input.charCodeAt(inPos++));\n out[outPos++] = (a << 2) | (b >> 4);\n out[outPos++] = ((b & 0x0f) << 4) | (c >> 2);\n }\n return out;\n}\n\nfunction concatBytes(...parts: Uint8Array[]): Uint8Array {\n const total = parts.reduce((sum, part) => sum + part.length, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n","/**\n * `VpTokenProvider` — caches CWT bearer tokens issued by the vault\n * provider's `auth_createDepositorToken` RPC, with lazy expiry check\n * and single-flight concurrent acquire.\n *\n * Usage:\n *\n * ```ts\n * const provider = new VpTokenProvider({\n * client,\n * peginTxid,\n * authAnchorHex,\n * pinnedServerPubkey,\n * authGatedMethods,\n * });\n * const bearer = await provider.getToken(method); // null if not gated\n * ```\n *\n * The provider implements the `BearerTokenProvider` interface expected\n * by `JsonRpcClient`. Plug directly:\n *\n * ```ts\n * const client = new JsonRpcClient({ ..., tokenProvider: provider });\n * ```\n *\n * @module tbv/core/clients/vault-provider/auth/tokenProvider\n */\n\nimport type { OnChainBtcPubkey } from \"../../eth/types\";\nimport type { BearerTokenProvider, JsonRpcClient } from \"../json-rpc-client\";\nimport {\n GRPC_TOKEN_ISSUE_METHOD,\n TOKEN_ISSUE_METHOD,\n} from \"./innerTokenClient\";\nimport {\n type ServerIdentityResponse,\n verifyServerIdentity,\n} from \"./serverIdentity\";\nimport {\n CWT_SUBJECT_GRPC,\n CWT_SUBJECT_JSONRPC,\n verifyDepositorCwt,\n} from \"./verifyDepositorCwt\";\n\n/**\n * Maximum reasonable `expires_at` value (seconds since epoch). Guards\n * against a bogus far-future timestamp that would lock the cache on a\n * bad token forever. Jan 1, 2100 in Unix seconds.\n */\nconst MAX_EXPIRES_AT_SECS = 4_102_444_800;\n\n/**\n * Default safety margin before `expires_at` — we treat a token as\n * expired this many seconds before its stated expiry so that in-flight\n * requests don't race the expiry boundary.\n */\nconst DEFAULT_REFRESH_SKEW_SECS = 30;\n\n/**\n * Wire response shape of `auth_createDepositorToken`.\n */\nexport interface CreateDepositorTokenResponse {\n /** Base64url-encoded COSE Sign1 CWT bearer token. */\n token: string;\n /** Unix timestamp at which the token expires. */\n expires_at: number;\n /** Server identity proof bundled with every token response. */\n server_identity: ServerIdentityResponse;\n}\n\nexport interface VpTokenProviderConfig {\n client: JsonRpcClient;\n /** Per-vault depositor-signed PegIn tx id. NOT shared across sibling vaults in a batch. */\n peginTxid: string;\n /** 64-char hex of the 32-byte OP_RETURN auth-anchor preimage. */\n authAnchorHex: string;\n /** Pinned VP pubkey from the on-chain registry; branded so indexer mirrors can't substitute. */\n pinnedServerPubkey: OnChainBtcPubkey;\n /**\n * Depositor x-only pubkey (32-byte hex). Asserted against every\n * issued token's CWT `aud` claim so a token minted for a different\n * depositor — or mis-issued by a buggy/compromised VP — is rejected\n * before it can authenticate a mutation.\n */\n expectedAudienceXOnlyPubkey: string;\n /**\n * Methods that need a JSON-RPC-subject bearer (minted via\n * `auth_createDepositorToken`). Forwarded over plain HTTP JSON-RPC by\n * the proxy. `getToken` returns `null` for any method outside this and\n * {@link grpcGatedMethods}.\n */\n authGatedMethods: ReadonlySet<string>;\n /**\n * Methods that need a gRPC-subject bearer (minted via\n * `auth_createDepositorTokenGrpc`). The proxy translates these into\n * gRPC calls to vaultd; the JSON-RPC bearer is rejected with a\n * `Subject` mismatch.\n */\n grpcGatedMethods: ReadonlySet<string>;\n /** Default {@link DEFAULT_REFRESH_SKEW_SECS}. */\n refreshSkewSecs?: number;\n /** Clock source for testability. */\n now?: () => number;\n}\n\ninterface CachedToken {\n token: string;\n expiresAt: number;\n}\n\n/**\n * Acquire, cache, and refresh VP bearer tokens.\n *\n * Implements {@link BearerTokenProvider}. Safe to pass directly into\n * `JsonRpcClient` as `tokenProvider`.\n */\nexport class VpTokenProvider implements BearerTokenProvider {\n // `client` is the only mutable field — see `setClient`. The\n // identity-bearing fields (peginTxid/authAnchorHex/pinnedServerPubkey)\n // remain readonly and are checked against re-registration in the\n // registry's `getOrCreate`.\n private client: JsonRpcClient;\n private readonly peginTxid: string;\n private readonly authAnchorHex: string;\n private readonly pinnedServerPubkey: OnChainBtcPubkey;\n private readonly expectedAudienceXOnlyPubkey: string;\n private readonly authGatedMethods: ReadonlySet<string>;\n private readonly grpcGatedMethods: ReadonlySet<string>;\n private readonly refreshSkewSecs: number;\n private readonly now: () => number;\n\n /** Cached JSON-RPC-subject bearer (auth_createDepositorToken). */\n private cachedJsonRpc: CachedToken | null = null;\n private inFlightJsonRpc: Promise<CachedToken> | null = null;\n /** Cached gRPC-subject bearer (auth_createDepositorTokenGrpc). */\n private cachedGrpc: CachedToken | null = null;\n private inFlightGrpc: Promise<CachedToken> | null = null;\n\n constructor(config: VpTokenProviderConfig) {\n this.client = config.client;\n this.peginTxid = config.peginTxid;\n this.authAnchorHex = config.authAnchorHex;\n this.pinnedServerPubkey = config.pinnedServerPubkey;\n this.expectedAudienceXOnlyPubkey = config.expectedAudienceXOnlyPubkey;\n this.authGatedMethods = config.authGatedMethods;\n this.grpcGatedMethods = config.grpcGatedMethods;\n this.refreshSkewSecs = config.refreshSkewSecs ?? DEFAULT_REFRESH_SKEW_SECS;\n this.now = config.now ?? (() => Math.floor(Date.now() / 1000));\n }\n\n /**\n * Return a bearer token for `method`, or `null` if `method` is not\n * auth-gated.\n *\n * Routes by subject: `authGatedMethods` → JSON-RPC bearer (issued via\n * `auth_createDepositorToken`); `grpcGatedMethods` → gRPC bearer\n * (`auth_createDepositorTokenGrpc`). Either path acquires lazily and\n * single-flights concurrent callers; the two cache slots are\n * independent.\n *\n * Both token-issuing methods are hard-exempted from the gate — if\n * either were ever included in the gated sets (caller misconfiguration)\n * the provider would recurse into `acquireSingleFlight` from inside the\n * JSON-RPC header builder before `inFlight` is assigned, defeating the\n * single-flight guard. Returning `null` here breaks that recursion\n * deterministically.\n */\n async getToken(method: string): Promise<string | null> {\n if (method === TOKEN_ISSUE_METHOD || method === GRPC_TOKEN_ISSUE_METHOD) {\n return null;\n }\n\n if (this.grpcGatedMethods.has(method)) {\n return this.getTokenForSubject(\"grpc\");\n }\n if (this.authGatedMethods.has(method)) {\n return this.getTokenForSubject(\"jsonrpc\");\n }\n return null;\n }\n\n /**\n * Drop both cached tokens. Next `getToken` call re-acquires the slot\n * that's actually needed. Called by `JsonRpcClient` on wire\n * `auth_expired` responses; the client doesn't tell us which subject\n * expired, so we evict both to stay correct under either.\n *\n * Worst case is one extra round-trip on the slot that was still fresh,\n * which is cheaper than carrying a `Subject` argument through\n * `BearerTokenProvider`.\n */\n invalidate(): void {\n this.cachedJsonRpc = null;\n this.cachedGrpc = null;\n // Do NOT clear `inFlight*` — a concurrent acquire is still valid;\n // the invalidator is saying \"the cached token is bad\", not \"any\n // in-flight acquire is bad\". The in-flight acquire will populate\n // a fresh `cached*` on completion.\n }\n\n private async getTokenForSubject(\n subject: \"jsonrpc\" | \"grpc\",\n ): Promise<string> {\n const cached =\n subject === \"grpc\" ? this.cachedGrpc : this.cachedJsonRpc;\n if (cached && this.now() + this.refreshSkewSecs < cached.expiresAt) {\n return cached.token;\n }\n const fresh = await this.acquireSingleFlight(subject);\n return fresh.token;\n }\n\n /**\n * Swap in a different transport for subsequent token-issuing calls.\n * Used by the registry when a later caller registers the same\n * `peginTxid` against a different `baseUrl` — the cached token\n * (bound to identity, not transport) stays valid, but future\n * refreshes hit the new URL. An in-flight acquire keeps using the\n * old client (it captured the reference); next call uses the new.\n */\n setClient(client: JsonRpcClient): void {\n this.client = client;\n }\n\n private acquireSingleFlight(\n subject: \"jsonrpc\" | \"grpc\",\n ): Promise<CachedToken> {\n const existing =\n subject === \"grpc\" ? this.inFlightGrpc : this.inFlightJsonRpc;\n if (existing) return existing;\n\n const issueMethod =\n subject === \"grpc\" ? GRPC_TOKEN_ISSUE_METHOD : TOKEN_ISSUE_METHOD;\n\n const p = (async () => {\n try {\n const response = await this.client.call<\n { pegin_txid: string; auth_anchor: string },\n CreateDepositorTokenResponse\n >(issueMethod, {\n pegin_txid: this.peginTxid,\n auth_anchor: this.authAnchorHex,\n });\n\n verifyServerIdentity({\n proof: response.server_identity,\n pinnedServerPubkey: this.pinnedServerPubkey,\n now: this.now(),\n });\n\n // Validate wire payload before caching so a malformed response\n // from a compromised VP or proxy can't poison the cache with\n // unusable values (non-string token, non-integer expiry, etc.).\n if (typeof response.token !== \"string\" || response.token.length === 0) {\n throw new Error(\n `VpTokenProvider: invalid token in acquire response (expected non-empty string, got ${typeof response.token})`,\n );\n }\n const now = this.now();\n if (\n !Number.isSafeInteger(response.expires_at) ||\n response.expires_at <= now ||\n response.expires_at > MAX_EXPIRES_AT_SECS\n ) {\n throw new Error(\n `VpTokenProvider: invalid expires_at in acquire response (got ${JSON.stringify(response.expires_at)}; must be a safe integer in (${now}, ${MAX_EXPIRES_AT_SECS}])`,\n );\n }\n\n // Cryptographically verify the token itself — not just the wire\n // envelope. The COSE Sign1 signature is checked against the\n // (server-identity-verified) ephemeral key, and the inner CWT\n // claims are bound to this depositor (`aud`), this VP (`iss`),\n // and this subject. Without this the bearer is an opaque blob the\n // FE would attach to mutations on the VP's word alone.\n verifyDepositorCwt({\n token: response.token,\n ephemeralPubkeyHex: response.server_identity.ephemeral_pubkey,\n expectedIssuerXOnlyPubkey: this.pinnedServerPubkey,\n expectedSubject:\n subject === \"grpc\" ? CWT_SUBJECT_GRPC : CWT_SUBJECT_JSONRPC,\n expectedAudienceXOnlyPubkey: this.expectedAudienceXOnlyPubkey,\n responseExpiresAt: response.expires_at,\n serverIdentityExpiresAt: response.server_identity.expires_at,\n now,\n });\n\n const fresh: CachedToken = {\n token: response.token,\n expiresAt: response.expires_at,\n };\n if (subject === \"grpc\") {\n this.cachedGrpc = fresh;\n } else {\n this.cachedJsonRpc = fresh;\n }\n return fresh;\n } finally {\n if (subject === \"grpc\") {\n this.inFlightGrpc = null;\n } else {\n this.inFlightJsonRpc = null;\n }\n }\n })();\n\n if (subject === \"grpc\") {\n this.inFlightGrpc = p;\n } else {\n this.inFlightJsonRpc = p;\n }\n return p;\n }\n}\n","/**\n * In-memory registry of {@link VpTokenProvider} instances keyed by\n * the per-vault depositor-signed PegIn tx hash. Module-level\n * singleton, per-tab, never persisted.\n *\n * @module tbv/core/clients/vault-provider/auth/tokenRegistry\n */\n\nimport type { OnChainBtcPubkey } from \"../../eth/types\";\nimport type { JsonRpcClient } from \"../json-rpc-client\";\n\nimport { AUTH_GATED_METHODS, GRPC_AUTH_GATED_METHODS } from \"./gatedMethods\";\nimport { VpTokenProvider } from \"./tokenProvider\";\n\nexport interface VpTokenRegistryInput {\n client: JsonRpcClient;\n peginTxid: string;\n authAnchorHex: string;\n pinnedServerPubkey: OnChainBtcPubkey;\n /** Depositor x-only pubkey (32-byte hex), asserted against each token's CWT `aud`. */\n expectedAudienceXOnlyPubkey: string;\n}\n\ninterface RegistryEntry {\n provider: VpTokenProvider;\n authAnchorHex: string;\n pinnedServerPubkey: OnChainBtcPubkey;\n expectedAudienceXOnlyPubkey: string;\n}\n\nexport class VpTokenRegistry {\n private readonly entries = new Map<string, RegistryEntry>();\n\n /**\n * Return the cached `VpTokenProvider` for `peginTxid` if one exists\n * with matching `authAnchorHex` and `pinnedServerPubkey`, otherwise\n * construct and cache a fresh provider. A mismatch on either throws —\n * silent overwrite would mask derivation drift or VP pubkey rotation.\n */\n getOrCreate(input: VpTokenRegistryInput): VpTokenProvider {\n const existing = this.entries.get(input.peginTxid);\n if (existing) {\n if (existing.authAnchorHex !== input.authAnchorHex) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to authAnchorHex ${existing.authAnchorHex.slice(0, 8)}…; got ${input.authAnchorHex.slice(0, 8)}…`,\n );\n }\n if (existing.pinnedServerPubkey !== input.pinnedServerPubkey) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to pinnedServerPubkey ${existing.pinnedServerPubkey.slice(0, 8)}…; got ${input.pinnedServerPubkey.slice(0, 8)}…`,\n );\n }\n if (\n existing.expectedAudienceXOnlyPubkey !==\n input.expectedAudienceXOnlyPubkey\n ) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to expectedAudienceXOnlyPubkey ${existing.expectedAudienceXOnlyPubkey.slice(0, 8)}…; got ${input.expectedAudienceXOnlyPubkey.slice(0, 8)}…`,\n );\n }\n // Refresh the inner transport on every reuse so a VP URL\n // change between calls doesn't leave the cached provider\n // pinned to a dead URL for token refresh.\n existing.provider.setClient(input.client);\n return existing.provider;\n }\n\n const provider = new VpTokenProvider({\n client: input.client,\n peginTxid: input.peginTxid,\n authAnchorHex: input.authAnchorHex,\n pinnedServerPubkey: input.pinnedServerPubkey,\n expectedAudienceXOnlyPubkey: input.expectedAudienceXOnlyPubkey,\n authGatedMethods: AUTH_GATED_METHODS,\n grpcGatedMethods: GRPC_AUTH_GATED_METHODS,\n });\n this.entries.set(input.peginTxid, {\n provider,\n authAnchorHex: input.authAnchorHex,\n pinnedServerPubkey: input.pinnedServerPubkey,\n expectedAudienceXOnlyPubkey: input.expectedAudienceXOnlyPubkey,\n });\n return provider;\n }\n\n /** Return the cached provider, or `undefined` if none. */\n peek(peginTxid: string): VpTokenProvider | undefined {\n return this.entries.get(peginTxid)?.provider;\n }\n\n /**\n * Evict the entry for `peginTxid`. Idempotent. Called on terminal\n * paths — activation success, user-cancel, or component unmount —\n * so `authAnchorHex` doesn't outlive the deposit session.\n */\n release(peginTxid: string): void {\n this.entries.delete(peginTxid);\n }\n\n /**\n * Wipe every cached entry. Test-only escape hatch — not exposed on\n * the public {@link VpTokenRegistryPublic} singleton type.\n *\n * @internal\n */\n clear(): void {\n this.entries.clear();\n }\n\n get size(): number {\n return this.entries.size;\n }\n}\n\n/**\n * Public surface of the singleton — excludes the test-only `clear`\n * method.\n */\nexport interface VpTokenRegistryPublic {\n getOrCreate(input: VpTokenRegistryInput): VpTokenProvider;\n peek(peginTxid: string): VpTokenProvider | undefined;\n release(peginTxid: string): void;\n readonly size: number;\n}\n\nexport const vpTokenRegistry: VpTokenRegistryPublic = new VpTokenRegistry();\n","/**\n * Build a {@link VaultProviderRpcClient} that auto-attaches CWT\n * bearer tokens on auth-gated methods. Caller pre-derives both the\n * `authAnchorHex` (from the wallet) and the `pinnedServerPubkey`\n * (from the on-chain registry) and hands them in — the SDK has no\n * notion of wallets here.\n *\n * @module tbv/core/clients/vault-provider/auth/createAuthenticatedVpClient\n */\n\nimport { processPublicKeyToXOnly } from \"../../../primitives/utils/bitcoin\";\nimport type { OnChainBtcPubkey } from \"../../eth/types\";\nimport {\n VaultProviderRpcClient,\n type VaultProviderRpcClientOptions,\n} from \"../api\";\n\nimport { buildInnerTokenClient } from \"./innerTokenClient\";\nimport { vpTokenRegistry } from \"./tokenRegistry\";\n\nexport interface AuthenticatedVpClientConfig {\n /** Base URL of the VP RPC endpoint (already proxied if applicable). */\n baseUrl: string;\n /** Per-vault depositor-signed PegIn tx id (registry cache key). */\n peginTxid: string;\n /** Already-derived 32-byte auth-anchor preimage (64-char hex, no `0x`). */\n authAnchorHex: string;\n /** On-chain VP pubkey, branded so it can only come from the registry reader. */\n pinnedServerPubkey: OnChainBtcPubkey;\n /**\n * Depositor BTC pubkey (x-only or compressed hex). Normalized to\n * x-only and asserted against every issued token's CWT `aud` claim.\n */\n depositorBtcPubkey: string;\n /** Optional outer-client tunables (timeout, retries, headers, etc.). */\n options?: VaultProviderRpcClientOptions;\n}\n\nexport function createAuthenticatedVpClient(\n config: AuthenticatedVpClientConfig,\n): VaultProviderRpcClient {\n const innerTokenClient = buildInnerTokenClient(\n config.baseUrl,\n config.options?.headers,\n );\n\n const tokenProvider = vpTokenRegistry.getOrCreate({\n client: innerTokenClient,\n peginTxid: config.peginTxid,\n authAnchorHex: config.authAnchorHex,\n pinnedServerPubkey: config.pinnedServerPubkey,\n expectedAudienceXOnlyPubkey: processPublicKeyToXOnly(\n config.depositorBtcPubkey,\n ),\n });\n\n return new VaultProviderRpcClient(config.baseUrl, {\n ...config.options,\n tokenProvider,\n });\n}\n","/**\n * Pre-populate {@link vpTokenRegistry} when the caller already has\n * both the auth-anchor preimage and the on-chain VP pubkey. Seeds\n * the cache for a `peginTxid` so a later `createAuthenticatedVpClient`\n * call reuses the cached `VpTokenProvider` instead of rebuilding it.\n *\n * @module tbv/core/clients/vault-provider/auth/primeVpAuth\n */\n\nimport { processPublicKeyToXOnly } from \"../../../primitives/utils/bitcoin\";\nimport type { OnChainBtcPubkey } from \"../../eth/types\";\n\nimport { buildInnerTokenClient } from \"./innerTokenClient\";\nimport { vpTokenRegistry } from \"./tokenRegistry\";\n\nexport interface PrimeVpAuthInput {\n baseUrl: string;\n peginTxid: string;\n authAnchorHex: string;\n pinnedServerPubkey: OnChainBtcPubkey;\n /**\n * Depositor BTC pubkey (x-only or compressed hex). Normalized to\n * x-only and asserted against every issued token's CWT `aud` claim.\n */\n depositorBtcPubkey: string;\n /** Optional headers forwarded to the inner token client (e.g. gateway auth). */\n headers?: Record<string, string>;\n}\n\nexport function primeVpTokenRegistry(input: PrimeVpAuthInput): void {\n vpTokenRegistry.getOrCreate({\n client: buildInnerTokenClient(input.baseUrl, input.headers),\n peginTxid: input.peginTxid,\n authAnchorHex: input.authAnchorHex,\n pinnedServerPubkey: input.pinnedServerPubkey,\n expectedAudienceXOnlyPubkey: processPublicKeyToXOnly(\n input.depositorBtcPubkey,\n ),\n });\n}\n"],"names":["resolveProtocolAddresses","publicClient","btcVaultRegistryAddress","protocolParams","applicationRegistry","BTCVaultRegistryABI","assertMulticallLength","actual","expected","label","partition","results","keeperCount","ViemOperationKeyReader","contracts","calls","challengerCount","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","ViemVaultKeeperReader","appEntryPoint","ViemUniversalChallengerReader","OnChainBtcVaultStatus","cborHead","major","arg","tag","out","concat","parts","total","s","p","offset","encodeBytesAsArrayOfU8","bytes","items","b","encodeServerIdentityPayload","domain","ephemeralPubkeyCompressed","expiresAt","arrayHeader","domainBytes","pubkeyBytes","expiresAtBytes","SERVER_IDENTITY_DOMAIN","DEFAULT_MAX_PROOF_LIFETIME_SECS","ServerIdentityError","message","reason","hexToBytes","hex","verifyServerIdentity","input","proof","pinnedServerPubkey","now","maxLifetimeSecs","pinned","stripHexPrefix","X_ONLY_PUBKEY_HEX_LEN","HEX_RE","eph","COMPRESSED_PUBKEY_HEX_LEN","prefix","ephBytes","ecc","sig","SCHNORR_SIG_HEX_LEN","payload","verifyBip322Simple","AUTH_GATED_METHODS","GRPC_AUTH_GATED_METHODS","TOKEN_RPC_TIMEOUT_MS","TOKEN_ISSUE_METHOD","GRPC_TOKEN_ISSUE_METHOD","buildInnerTokenClient","baseUrl","headers","JsonRpcClient","method","MAJOR_UNSIGNED_INT","MAJOR_NEGATIVE_INT","MAJOR_BYTE_STRING","MAJOR_TEXT_STRING","MAJOR_ARRAY","MAJOR_MAP","MAJOR_TAG","MAJOR_SIMPLE","ARG_IN_NEXT_1_BYTE","ARG_RESERVED_MIN","SIMPLE_FALSE","SIMPLE_TRUE","SIMPLE_NULL","MAX_NESTING_DEPTH","CborDecodeError","CborReader","buf","__publicField","initial","info","byteCount","value","length","slice","head","depth","map","key","decodeCbor","reader","CWT_SUBJECT_JSONRPC","CWT_SUBJECT_GRPC","COSE_SIGN1_TAG","COSE_SIGN1_ARRAY_LEN","COSE_ALG_ES256K","COSE_HEADER_LABEL_ALG","ECDSA_COMPACT_SIG_LEN","CBOR_ARRAY_HEAD","CBOR_TEXT_STRING_HEAD","CBOR_EMPTY_BYTE_STRING","CWT_CLAIM_ISS","CWT_CLAIM_SUB","CWT_CLAIM_AUD","CWT_CLAIM_EXP","CWT_CLAIM_NBF","CWT_CLAIM_IAT","CWT_CLAIM_CTI","SIG_STRUCTURE_CONTEXT","CwtVerificationError","verifyDepositorCwt","expectedIssuer","normalizeXOnly","expectedAudience","ephemeral","decodeCompressedPubkey","tokenBytes","base64UrlToBytes","array","protectedStart","protectedContent","protectedBstr","payloadStart","payloadContent","payloadBstr","signature","alg","readProtectedAlgorithm","sigStructure","buildSigStructure","digest","sha256","claims","decodeClaims","audience","header","concatBytes","root","requireBytes","requireString","requireTimestamp","name","pubkey","normalized","pubkeyHex","hexToUint8Array","B64URL_LOOKUP","table","alphabet","len","fullGroups","remainder","outLen","sextet","charCode","inPos","outPos","g","a","c","d","sum","part","MAX_EXPIRES_AT_SECS","DEFAULT_REFRESH_SKEW_SECS","VpTokenProvider","subject","cached","client","existing","issueMethod","response","fresh","VpTokenRegistry","provider","peginTxid","_a","vpTokenRegistry","createAuthenticatedVpClient","innerTokenClient","tokenProvider","processPublicKeyToXOnly","VaultProviderRpcClient","primeVpTokenRegistry"],"mappings":";;;;;;;;;;;;AA8BA,eAAsBA,GACpBC,GACAC,GAC4B;AAC5B,QAAM,CAACC,GAAgBC,CAAmB,IAAI,MAAMH,EAAa,UAAU;AAAA,IACzE,WAAW;AAAA,MACT;AAAA,QACE,SAASC;AAAA,QACT,KAAKG;AAAA,QACL,cAAc;AAAA,MAAA;AAAA,MAEhB;AAAA,QACE,SAASH;AAAA,QACT,KAAKG;AAAA,QACL,cAAc;AAAA,MAAA;AAAA,IAChB;AAAA,IAEF,cAAc;AAAA,EAAA,CACf;AAED,SAAO;AAAA,IACL,gBAAAF;AAAA,IACA,qBAAAC;AAAA,EAAA;AAEJ;ACTA,SAASE,EACPC,GACAC,GACAC,GACM;AACN,MAAIF,MAAWC;AACb,UAAM,IAAI;AAAA,MACR,GAAGC,CAAK,wBAAwBF,CAAM,gBAAgBC,CAAQ;AAAA,IAAA;AAIpE;AAYA,SAASE,GACPC,GACAC,GACoE;AACpE,SAAO;AAAA,IACL,eAAeD,EAAQ,CAAC;AAAA,IACxB,cAAcA,EAAQ,MAAM,GAAG,IAAIC,CAAW;AAAA,IAC9C,sBAAsBD,EAAQ,MAAM,IAAIC,CAAW;AAAA,EAAA;AAEvD;AAWO,MAAMC,GAAqD;AAAA,EAChE,YACUZ,GACAa,GACR;AAFQ,SAAA,eAAAb,GACA,KAAA,YAAAa;AAAA,EACP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQH,MAAc,QACZC,GACAH,GACAI,GACAP,GACA;AACA,UAAME,IAAW,MAAM,KAAK,aAAa,UAAU;AAAA,MACjD,WAAWI;AAAA,MACX,cAAc;AAAA,IAAA,CACf;AAED,WAAAT;AAAA,MACEK,EAAQ;AAAA,MACR,IAAIC,IAAcI;AAAA,MAClBP;AAAA,IAAA,GAGKC,GAAUC,GAASC,CAAW;AAAA,EACvC;A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AAA;ACvFnD,SAASK,GACdhM,GACwB;;AACxB,QAAMiM,IAAmB3H;AAAA,IACvBtE,EAAO;AAAA,KACP8L,IAAA9L,EAAO,YAAP,gBAAA8L,EAAgB;AAAA,EAAA,GAGZI,IAAgBH,GAAgB,YAAY;AAAA,IAChD,QAAQE;AAAA,IACR,WAAWjM,EAAO;AAAA,IAClB,eAAeA,EAAO;AAAA,IACtB,oBAAoBA,EAAO;AAAA,IAC3B,6BAA6BmM;AAAA,MAC3BnM,EAAO;AAAA,IAAA;AAAA,EACT,CACD;AAED,SAAO,IAAIoM,GAAuBpM,EAAO,SAAS;AAAA,IAChD,GAAGA,EAAO;AAAA,IACV,eAAAkM;AAAA,EAAA,CACD;AACH;AC/BO,SAASG,GAAqBtJ,GAA+B;AAClE,EAAAgJ,GAAgB,YAAY;AAAA,IAC1B,QAAQzH,GAAsBvB,EAAM,SAASA,EAAM,OAAO;AAAA,IAC1D,WAAWA,EAAM;AAAA,IACjB,eAAeA,EAAM;AAAA,IACrB,oBAAoBA,EAAM;AAAA,IAC1B,6BAA6BoJ;AAAA,MAC3BpJ,EAAM;AAAA,IAAA;AAAA,EACR,CACD;AACH;"}
@@ -4,9 +4,9 @@ var p = (t, e, s) => R(t, typeof e != "symbol" ? e + "" : e, s);
4
4
  import * as T from "bitcoinjs-lib";
5
5
  import { s as w, v as h } from "./bitcoin-C-TuHb-v.js";
6
6
  import { s as C } from "./sha2-BYVxyZzX.js";
7
- import { f as b, i as y, g as d, j as f } from "./verifyScriptPathSchnorrSignature-ZAZfFJ6S.js";
7
+ import { f as b, i as y, g as d, j as f } from "./verifyScriptPathSchnorrSignature-Ciq_xZhw.js";
8
8
  import { D as x } from "./constants-CPzppOdq.js";
9
- import { c as m } from "./signing-DaLvGwQe.js";
9
+ import { a as m } from "./signing-Cm-McVR2.js";
10
10
  const S = 106, H = 32, l = 34;
11
11
  function W(t, e, s) {
12
12
  const o = w(t), r = T.Transaction.fromHex(o);
@@ -308,4 +308,4 @@ export {
308
308
  _ as s,
309
309
  M as v
310
310
  };
311
- //# sourceMappingURL=signPsbtsWithFallback-BjXdnI0X.js.map
311
+ //# sourceMappingURL=signPsbtsWithFallback-CCFTzE0o.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"signPsbtsWithFallback-BjXdnI0X.js","sources":["../src/tbv/core/managers/pegin/assertAuthAnchorOpReturn.ts","../src/tbv/core/services/htlc/index.ts","../src/tbv/core/deposit-terms/depositTerms.ts","../src/tbv/core/managers/PayoutManager.ts","../src/tbv/core/managers/pegin/signPsbtsWithFallback.ts"],"sourcesContent":["/**\n * Structural verifier for the auth-anchor OP_RETURN in a funded\n * Pre-PegIn transaction.\n *\n * @module managers/pegin/assertAuthAnchorOpReturn\n */\n\nimport * as bitcoin from \"bitcoinjs-lib\";\n\nimport { stripHexPrefix } from \"../../primitives/utils/bitcoin\";\n\n/** OP_RETURN opcode. */\nconst OP_RETURN = 0x6a;\n/** Push-32-bytes opcode (raw push, not OP_PUSHDATA1). */\nconst OP_PUSH32 = 0x20;\n/** Encoded length of a standard OP_RETURN script with a 32-byte payload. */\nconst OP_RETURN_PUSH32_SCRIPT_LEN = 1 + 1 + 32;\n\n/**\n * Verify the broadcast Pre-PegIn carries the expected OP_RETURN\n * commitment to the auth anchor.\n *\n * The OP_RETURN sits at `vout = vaultCount` (right after the per-vault\n * HTLC outputs and before the depositor-claim/change outputs) and\n * pushes the 32-byte `SHA256(authAnchor)`. The script encoding is\n * exactly `OP_RETURN || PUSH32 || <32 bytes>` (34 bytes). A\n * non-conformant WASM build that omitted the OP_RETURN, swapped its\n * position, or changed its push payload would let the depositor\n * obtain a valid bearer token for a Pre-PegIn whose on-chain\n * commitment doesn't actually bind the anchor — degrading the auth\n * from on-chain-bound to a shared secret. Fail closed.\n *\n * @throws If the OP_RETURN is missing, mis-located, mis-encoded, or\n * pushes a payload other than `expectedAuthAnchorHashHex`.\n */\nexport function assertAuthAnchorOpReturn(\n fundedPrePeginTxHex: string,\n vaultCount: number,\n expectedAuthAnchorHashHex: string,\n): void {\n const cleanHex = stripHexPrefix(fundedPrePeginTxHex);\n const tx = bitcoin.Transaction.fromHex(cleanHex);\n\n if (tx.outs.length <= vaultCount) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN missing: tx has ${tx.outs.length} ` +\n `outputs, expected at least ${vaultCount + 1} (vault outputs + OP_RETURN)`,\n );\n }\n\n const opReturnOutput = tx.outs[vaultCount];\n const script = opReturnOutput.script;\n if (\n script.length !== OP_RETURN_PUSH32_SCRIPT_LEN ||\n script[0] !== OP_RETURN ||\n script[1] !== OP_PUSH32\n ) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN at vout ${vaultCount} has unexpected ` +\n `script encoding (got ${script.length}-byte script with prefix ` +\n `0x${script.slice(0, Math.min(2, script.length)).toString(\"hex\")}; ` +\n `expected ${OP_RETURN_PUSH32_SCRIPT_LEN}-byte OP_RETURN + PUSH32 layout)`,\n );\n }\n\n const pushedHex = script.slice(2).toString(\"hex\").toLowerCase();\n if (pushedHex !== expectedAuthAnchorHashHex.toLowerCase()) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN payload mismatch at vout ${vaultCount}: ` +\n `tx pushes ${pushedHex}, expected ${expectedAuthAnchorHashHex}`,\n );\n }\n\n if (opReturnOutput.value !== 0) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN at vout ${vaultCount} has non-zero ` +\n `value ${opReturnOutput.value}; OP_RETURN outputs must be 0-value`,\n );\n }\n}\n\n/**\n * Scan a funded Pre-PegIn transaction for its auth-anchor commitment\n * (an `OP_RETURN || PUSH32 || <32 bytes>` output with value 0).\n *\n * Returns `{ vout, hash }` when exactly one such output is found.\n * Returns `undefined` when:\n * - the hex is unparseable,\n * - no matching output exists (legacy non-auth-anchored Pre-PegIn),\n * - more than one matching output exists (ambiguous / malformed).\n *\n * Used by the refund orchestrator to (a) locate the on-chain anchor\n * regardless of how many HTLCs preceded it and (b) detect multi-vault\n * funded transactions structurally: the single-vault refund path\n * reconstructs only one hashlock and expects the anchor at vout 1, so\n * any other vout signals a layout this call cannot safely refund.\n */\nexport function findAuthAnchorOpReturn(\n fundedPrePeginTxHex: string,\n): { vout: number; hash: string } | undefined {\n let tx: bitcoin.Transaction;\n try {\n tx = bitcoin.Transaction.fromHex(stripHexPrefix(fundedPrePeginTxHex));\n } catch {\n return undefined;\n }\n\n const hits: { vout: number; hash: string }[] = [];\n for (let i = 0; i < tx.outs.length; i++) {\n const output = tx.outs[i];\n const script = output.script;\n if (\n script.length === OP_RETURN_PUSH32_SCRIPT_LEN &&\n script[0] === OP_RETURN &&\n script[1] === OP_PUSH32 &&\n output.value === 0\n ) {\n hits.push({\n vout: i,\n hash: script.slice(2).toString(\"hex\").toLowerCase(),\n });\n }\n }\n\n return hits.length === 1 ? hits[0] : undefined;\n}\n","/**\n * HTLC Secret / Hashlock Utilities\n *\n * Pure functions for computing and validating SHA-256 hashlocks used in the\n * vault deposit protocol's HTLC (Hash Time Lock Contract).\n *\n * The SDK does NOT generate secrets — that is the caller's responsibility.\n * Today callers use `crypto.getRandomValues(32)`; when the `deriveContextHash`\n * wallet API ships, callers will use `wallet.deriveContextHash(\"babylon-btc-vault\", ctx)`.\n * These utilities work identically regardless of how the secret was produced.\n *\n * On-chain contract validation (BTCVaultRegistry.activateVaultWithSecret):\n * if (sha256(abi.encodePacked(s)) != hashlock) revert InvalidSecret();\n *\n * @module htlc\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport type { Hex } from \"viem\";\n\n/** Expected hex length for a 0x-prefixed bytes32 value. */\nconst HEX_BYTES32_LENGTH = 66; // \"0x\" + 64 hex chars\n\n/**\n * Decode a 0x-prefixed hex string to bytes, with strict validation.\n * @throws if the input is not a valid 0x-prefixed hex string\n */\nfunction hexToBytes(hex: Hex): Uint8Array {\n if (!hex.startsWith(\"0x\") && !hex.startsWith(\"0X\")) {\n throw new Error(\"Expected 0x-prefixed hex string\");\n }\n const clean = hex.slice(2);\n if (clean.length % 2 !== 0) {\n throw new Error(`Hex string has odd length: ${clean.length}`);\n }\n if (!/^[0-9a-fA-F]*$/.test(clean)) {\n throw new Error(\"Hex string contains non-hex characters\");\n }\n const bytes = new Uint8Array(clean.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Encode a Uint8Array as a 0x-prefixed lowercase hex string.\n */\nfunction bytesToHex(bytes: Uint8Array): Hex {\n return `0x${Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")}`;\n}\n\n/**\n * Validate that a value is a 0x-prefixed bytes32 (exactly 32 bytes).\n * @throws if the value is not exactly 32 bytes\n */\nfunction assertBytes32(value: Hex, label: string): void {\n if (value.length !== HEX_BYTES32_LENGTH) {\n throw new Error(\n `${label} must be exactly 32 bytes (${HEX_BYTES32_LENGTH} hex chars with 0x prefix), got ${value.length}`,\n );\n }\n}\n\n/**\n * Compute the SHA-256 hashlock from a secret preimage.\n *\n * Matches the on-chain validation: `sha256(abi.encodePacked(s))` where `s` is a `bytes32`.\n * `abi.encodePacked(bytes32)` is just the raw 32 bytes — no ABI padding.\n *\n * @param secret - 0x-prefixed bytes32 secret (66 hex chars)\n * @returns 0x-prefixed bytes32 SHA-256 hash\n * @throws if secret is not exactly 32 bytes\n */\nexport function computeHashlock(secret: Hex): Hex {\n assertBytes32(secret, \"Secret\");\n const secretBytes = hexToBytes(secret);\n const hash = sha256(secretBytes);\n return bytesToHex(hash);\n}\n\n/**\n * Validate that a secret's SHA-256 hash matches the expected hashlock.\n *\n * Use this for client-side pre-validation before sending the activation\n * transaction to avoid wasting gas on a contract revert.\n *\n * @param secret - 0x-prefixed bytes32 secret (66 hex chars)\n * @param hashlock - 0x-prefixed bytes32 expected hashlock from the vault\n * @returns true if SHA-256(secret) matches the hashlock\n * @throws if secret or hashlock is not exactly 32 bytes\n */\nexport function validateSecretAgainstHashlock(\n secret: Hex,\n hashlock: Hex,\n): boolean {\n assertBytes32(secret, \"Secret\");\n assertBytes32(hashlock, \"Hashlock\");\n // Validate hashlock is valid hex (secret is validated inside computeHashlock)\n hexToBytes(hashlock);\n\n const computed = computeHashlock(secret);\n return computed.toLowerCase() === hashlock.toLowerCase();\n}\n","import type { BitcoinWallet } from \"../../../shared/wallets/interfaces\";\n\n// Field docs use /** */ so they survive into the emitted .d.ts — the published\n// package is the only contract the external provider author (#2109) sees.\n\nexport interface DepositTermsVaultGroup {\n /** 0-based; equals the group's position (groups are ascending by vout). */\n readonly htlcVout: number;\n /** x-only hex (64 chars), as validated on-chain upstream. */\n readonly vaultProviderBtcPubkey: string;\n /** sats */\n readonly peginAmount: bigint;\n /**\n * sats; the MAXIMUM commission the depositor accepts —\n * floor(peginAmount * maxAcceptableCommissionBps / 10_000), the same\n * ceiling the registration calldata carries. An approving wallet MUST\n * enforce the VP payout commission output `<= commissionFee` (e.g. the\n * Ledger vault app does, firmware >= c8db53e), and every commission the\n * contract admits stays under this ceiling (floor is monotonic in bps),\n * so no contract-admitted deposit can be refused at payout. The actual\n * stamped commission may be lower. Display the quoted value in UI, not this.\n */\n readonly commissionFee: bigint;\n /** sats; the same value for every vault. */\n readonly depositorClaimValue: bigint;\n /**\n * sats; the cap an approving wallet enforces on the PegIn tx fee. Equals\n * the graph's exact (minimum) PegIn fee, which is deterministic — so the\n * cap is satisfied exact-by-construction.\n */\n readonly peginMaxFee: bigint;\n}\n\n/**\n * Field names follow btc-vault vocabulary (the protocol source of truth);\n * a device-wire encoder maps them to its intent fields (e.g. the Ledger TLV:\n * protocolFeeRate -> base_fee_rate, timelockPegin -> pegin_csv_timelock,\n * timelockAssert -> payout_timelock, peginAmount -> vault_amount).\n */\nexport interface DepositTerms {\n /**\n * btc-vault tx-graph version (`vaultCoreVersion`) these terms describe —\n * the vault's stamped on-chain version for resumes, the chain's\n * `activeVaultCoreVersion` for fresh deposits. It selects the PegIn shape\n * an approving wallet must expect: v1 = 2 outputs, no anchor; v2/v3 = TRUC\n * nVersion 3, 3 outputs with a 240-sat P2A anchor at vout 2, and an\n * Assert OP_RETURN marker that raises the claim value\n * (btc-vault `transactions/pegin.rs`, `assert_marker.rs`). A provider that\n * supports only one shape MUST reject the others here rather than\n * mis-validating the PSBTs later.\n */\n vaultCoreVersion: number;\n /**\n * sat/vB; the tx-graph fee rate (protocolFeeRate), NOT the mempool funding\n * rate. Approving wallets bound each payout's fee against this rate —\n * pass the exact graph rate, not an inflated ceiling.\n */\n protocolFeeRate: bigint;\n /** Vault-UTXO CSV timelock (blocks). */\n timelockPegin: number;\n /**\n * btc-vault `timelock_assert` (t2) — the CSV on Assert output 0. Its own\n * param, though production derives it and `timelockPegin` from one value.\n */\n timelockAssert: number;\n /** HTLC refund CSV timelock (blocks). */\n timelockRefund: number;\n /**\n * 64-char hex in display order. A device-wire encoder may need the\n * little-endian form — some hardware byte-compares it against\n * PSBT_IN_PREVIOUS_TXID rather than recomputing the txid.\n */\n prepeginTxid: string;\n /** sats; the funded Pre-PegIn fee (an approving wallet caps the signed fee at this). */\n prepeginMaxFee: bigint;\n /**\n * x-only hex. Sorted ascending by the upstream on-chain validation\n * (validateOnChainParticipantKeys); the builder passes them through\n * unasserted — approving devices may reject unsorted lists at load.\n */\n vaultKeeperBtcPubkeys: readonly string[];\n /**\n * x-only hex, sorted ascending upstream independently of vaultKeeperBtcPubkeys (same\n * pass-through contract). Universal challengers only — the full graph\n * challenger set is vaultKeeperBtcPubkeys ∪ universalChallengerBtcPubkeys (vault keepers are the local\n * challengers).\n */\n universalChallengerBtcPubkeys: readonly string[];\n /** Per-vault groups, ordered by ascending htlcVout. */\n vaults: readonly DepositTermsVaultGroup[];\n}\n\n/**\n * Implemented only by depositor-approval wallets (e.g. a Ledger vault\n * provider). Provider obligations:\n *\n * - Envelope: validate terms against the device's envelope BEFORE the\n * ceremony, rejecting with the shape `{ name: \"DepositTermsRejectedError\",\n * reason: \"device-envelope\", message }` (matched structurally, not by class).\n * - Idempotence: a byte-equal re-approval MUST be a no-op while the\n * device-side approval is live; anything that invalidates it (a later\n * `deriveContextHash`, a signing failure) MUST clear the memo.\n *\n * Seam invariant: any derive invalidates a prior approval, so the SDK\n * re-approves after every derive and before the next terms-bound signature.\n * The re-approval sites are `PeginManager.preparePegin`,\n * `runDepositorPresignFlow`, and `signAndBroadcast` (the Pre-PegIn broadcast,\n * which re-derives before approving unless `holdsApprovedDepositTerms`\n * reports the byte-equal intent still live — see `ensurePrePeginTermsApproval`).\n */\nexport interface DepositTermsApprover {\n approveDepositTerms(terms: DepositTerms): Promise<void>;\n /**\n * OPTIONAL fast-path probe: can the Pre-PegIn signature for exactly these\n * terms proceed under the connection's held approval without a new\n * ceremony? MUST report false once that Pre-PegIn was signed (one-shot),\n * MUST answer from host state without device I/O, MUST return false on any\n * doubt, and MUST never throw. A stale true fails closed at the next\n * signature — this is a UX optimization, never an authorization.\n */\n holdsApprovedDepositTerms?(terms: DepositTerms): Promise<boolean>;\n /**\n * OPTIONAL validate-only pre-check (#2110): reject terms the device\n * envelope would refuse, with the same `{ name:\n * \"DepositTermsRejectedError\", reason: \"device-envelope\", message }` shape\n * as `approveDepositTerms`, WITHOUT any device I/O and WITHOUT touching a\n * held approval — the SDK calls it before the first derive screen, so a\n * side effect here would cost or invalidate a physical ceremony. Success\n * is NOT an approval: `approveDepositTerms` still runs its own envelope\n * gate before the ceremony. Callers may pass provisional terms whose\n * `prepeginTxid` is a placeholder (the real txid exists only post-derive),\n * so implementations MUST NOT validate or bind `prepeginTxid` here.\n */\n validateDepositTerms?(terms: DepositTerms): Promise<void>;\n}\n\n/**\n * Where Pre-PegIn change must pay. Approval (policy) wallets sign key-path\n * under a wallet policy whose change branch the device alone can derive and\n * mark internal — the receive address is NOT acceptable change\n * (`process_in_outs.c:114-117` @ e400d8d8).\n *\n * Separate from {@link DepositTermsApprover} because only the Pre-PegIn build\n * needs it: the presign/payout ceremonies approve terms without ever creating\n * change, so they must not require a wallet to implement this.\n *\n * MUST be stable across a deposit flow: the app reads it to build the tx and\n * `preparePegin` re-reads it to verify, so mid-flow rotation fails that gate.\n */\nexport interface PrePeginChangeSource {\n getChangeAddress(): Promise<string>;\n}\n\n/** Probes {@link DepositTermsApprover.approveDepositTerms}. */\nexport function supportsDepositApproval(\n wallet: BitcoinWallet,\n): wallet is BitcoinWallet & DepositTermsApprover {\n return (\n typeof (wallet as Partial<DepositTermsApprover>).approveDepositTerms ===\n \"function\"\n );\n}\n\n/**\n * The wallet's change address, for the one caller that needs it.\n *\n * Narrowing on `approveDepositTerms` alone cannot promise this method, so\n * calling it off the narrowed value would die on `is not a function` in the\n * middle of `preparePegin`, after the pubkey read. Ask here instead and fail\n * with something a provider author can act on.\n *\n * @throws If the wallet cannot report a change address.\n */\nexport async function requireChangeAddress(\n wallet: BitcoinWallet,\n): Promise<string> {\n const changeSource = wallet as Partial<PrePeginChangeSource>;\n if (typeof changeSource.getChangeAddress !== \"function\") {\n throw new Error(\n \"Approval wallet does not implement getChangeAddress; it must expose its change branch, \" +\n \"because the signing device accepts Pre-PegIn change only there.\",\n );\n }\n return changeSource.getChangeAddress();\n}\n\n/**\n * Spreadable forward of the approval capability for wallet-wrapper objects.\n * Object spread drops prototype methods, so every `{...wallet}` wrapper site\n * must re-attach the capability explicitly: `...forwardDepositApproval(wallet)`.\n */\nexport function forwardDepositApproval(\n wallet: BitcoinWallet,\n): Partial<DepositTermsApprover & PrePeginChangeSource> {\n if (!supportsDepositApproval(wallet)) {\n return {};\n }\n const holdsApprovedDepositTerms = wallet.holdsApprovedDepositTerms;\n const validateDepositTerms = wallet.validateDepositTerms;\n const getChangeAddress = (wallet as Partial<PrePeginChangeSource>)\n .getChangeAddress;\n return {\n approveDepositTerms: (terms) => wallet.approveDepositTerms(terms),\n // All optional in the seam: forward only what the provider implements, so\n // wrapper consumers can keep probing by typeof.\n ...(typeof getChangeAddress === \"function\"\n ? { getChangeAddress: () => getChangeAddress.call(wallet) }\n : {}),\n ...(typeof holdsApprovedDepositTerms === \"function\"\n ? {\n holdsApprovedDepositTerms: (terms: DepositTerms) =>\n holdsApprovedDepositTerms.call(wallet, terms),\n }\n : {}),\n ...(typeof validateDepositTerms === \"function\"\n ? {\n validateDepositTerms: (terms: DepositTerms) =>\n validateDepositTerms.call(wallet, terms),\n }\n : {}),\n };\n}\n\nexport interface BuildDepositTermsInputs {\n /** btc-vault tx-graph version the graph is built under. */\n vaultCoreVersion: number;\n protocolFeeRate: bigint;\n timelockPegin: number;\n /** btc-vault `timelock_assert` (t2) — its own param; NOT derived from timelockPegin here. */\n timelockAssert: number;\n timelockRefund: number;\n prepeginTxid: string;\n prepeginMaxFee: bigint;\n vaultProviderBtcPubkey: string;\n vaultKeeperBtcPubkeys: readonly string[];\n universalChallengerBtcPubkeys: readonly string[];\n /** Ceiling bps, not the quote — see {@link DepositTermsVaultGroup.commissionFee}. */\n maxAcceptableCommissionBps: number;\n peginAmounts: readonly bigint[];\n depositorClaimValue: bigint;\n peginMaxFee: bigint;\n}\n","/**\n * Payout Manager\n *\n * High-level manager that orchestrates the payout signing flow by coordinating\n * SDK primitives ({@link buildPayoutPsbt}, {@link extractPayoutSignature})\n * with a user-provided Bitcoin wallet.\n *\n * The Payout transaction references the Assert transaction (input 1).\n *\n * @see {@link PeginManager} - For Steps 1–4 of the peg-in flow\n * @see {@link buildPayoutPsbt} - Lower-level primitive for custom implementations\n * @see {@link extractPayoutSignature} - Extract signatures from signed PSBTs\n *\n * @module managers/PayoutManager\n */\n\nimport type { BitcoinWallet, SignPsbtOptions } from \"../../../shared/wallets\";\nimport {\n assertPsbtUnsignedTxMatches,\n assertScriptPathSchnorrSignature,\n buildPayoutPsbt,\n extractPayoutSignature,\n validateWalletPubkey,\n type Network,\n} from \"../primitives\";\nimport { DEPOSITOR_SIGNED_INPUT_COUNT } from \"../primitives/psbt/constants\";\nimport { createTaprootScriptPathSignOptions } from \"../utils/signing\";\n\n/** Payout PSBTs are signed by the depositor on input 0 (Taproot script-path). */\nconst PAYOUT_SIGNED_INPUT_INDEX = 0;\n\n/**\n * Configuration for the PayoutManager.\n */\nexport interface PayoutManagerConfig {\n /**\n * Bitcoin network to use for transactions.\n */\n network: Network;\n\n /**\n * Bitcoin wallet for signing payout transactions.\n */\n btcWallet: BitcoinWallet;\n}\n\n/**\n * Base parameters shared by both payout transaction types.\n */\ninterface SignPayoutBaseParams {\n /**\n * Vault core (tx-graph) version the vault was registered under — the\n * vault's stamped on-chain `vaultCoreVersion`. Forwarded to\n * {@link buildPayoutPsbt} to derive the matching graph's payout scripts.\n */\n vaultCoreVersion: number;\n\n /**\n * Peg-in transaction hex.\n * The original transaction that created the vault output being spent.\n */\n peginTxHex: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex).\n */\n vaultProviderBtcPubkey: string;\n\n /**\n * Vault keeper BTC public keys (x-only, 64-char hex).\n */\n vaultKeeperBtcPubkeys: string[];\n\n /**\n * Universal challenger BTC public keys (x-only, 64-char hex).\n */\n universalChallengerBtcPubkeys: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n /** btc-vault `timelock_assert`; payout input 1's sequence. */\n timelockAssert: number;\n\n /**\n * Depositor's BTC public key (x-only, 64-char hex). This MUST be the\n * key registered on-chain for the vault — typically read from\n * `BTCVaultRegistry.getBtcVaultBasicInfo(...).depositorBtcPubKey`.\n *\n * Required: omitting it would degrade `validateWalletPubkey` to a\n * self-comparison, allowing the wrong wallet to produce a signature\n * over a script tree that doesn't match the on-chain UTXO.\n */\n depositorBtcPubkey: string;\n\n /**\n * The on-chain registered depositor payout scriptPubKey (hex, with or without 0x prefix).\n * Used to validate that the VP-provided payout transaction actually pays to the\n * correct depositor payout address before signing.\n */\n registeredPayoutScriptPubKey: string;\n\n /**\n * The claimer's x-only BTC public key for this payout (64-char hex, no prefix).\n * Forwarded to {@link buildPayoutPsbt} for per-role output validation.\n */\n claimerBtcPubkey: string;\n\n /**\n * VP commission in basis points (`1..=9999`). Forwarded to {@link buildPayoutPsbt}.\n */\n commissionBps: number;\n\n /**\n * Version-locked tx-graph fee rate (sat/vB) the graph was built with.\n * Forwarded to {@link buildPayoutPsbt} for the fee band.\n */\n protocolFeeRate: bigint;\n\n /**\n * Security council member x-only pubkeys (hex); forwarded to\n * {@link buildPayoutPsbt} to rebuild the Assert:0 payout leaf and to size the\n * fee floor (see PayoutParams).\n */\n councilMembers: string[];\n\n /** M-of-N council quorum; shapes the Assert:0 council leaf (see PayoutParams). */\n councilQuorum: number;\n\n /**\n * RFC-006 resolved payout destinations, keyed by lowercased x-only operation\n * pubkey. Forwarded verbatim to {@link buildPayoutPsbt}; every VK claimer\n * must be present.\n */\n vkClaimerPayoutScriptPubKeys: Readonly<Record<string, string>>;\n /** RFC-006 VP commission destination. Forwarded to {@link buildPayoutPsbt}. */\n vpCommissionScriptPubKey: string;\n}\n\n/**\n * Parameters for signing a Payout transaction.\n *\n * Payout is used in the challenge path after Assert, when the claimer proves validity.\n * Input 1 references the Assert transaction.\n */\nexport interface SignPayoutParams extends SignPayoutBaseParams {\n /**\n * Payout transaction hex (unsigned).\n * This is the transaction from the vault provider that needs depositor signature.\n */\n payoutTxHex: string;\n\n /**\n * Assert transaction hex.\n * Payout input 1 references Assert output 0.\n */\n assertTxHex: string;\n}\n\n/**\n * Result of signing a payout transaction.\n */\nexport interface PayoutSignatureResult {\n /**\n * 64-byte Schnorr signature (128 hex characters).\n */\n signature: string;\n\n /**\n * Depositor's BTC public key used for signing.\n */\n depositorBtcPubkey: string;\n}\n\n/**\n * High-level manager for payout transaction signing.\n *\n * @remarks\n * After registering your peg-in on Ethereum (Step 3), the vault provider prepares\n * claim/payout transaction pairs. You must sign each payout transaction using this\n * manager and submit the signatures to the vault provider's RPC API.\n *\n * **What happens internally:**\n * 1. Validates your wallet's public key matches the vault's depositor\n * 2. Builds an unsigned PSBT with taproot script path spend info\n * 3. Signs input 0 (the vault UTXO) with your wallet\n * 4. Extracts the 64-byte Schnorr signature\n *\n * **Note:** The payout transaction has 2 inputs. PayoutManager only signs input 0\n * (from the peg-in tx). Input 1 (from the assert tx) is signed by the vault provider.\n *\n * @see {@link PeginManager} - For the complete peg-in flow context\n * @see {@link buildPayoutPsbt} - Lower-level primitive used internally\n * @see {@link extractPayoutSignature} - Signature extraction primitive\n */\nexport class PayoutManager {\n private readonly config: PayoutManagerConfig;\n\n /**\n * Creates a new PayoutManager instance.\n *\n * @param config - Manager configuration including wallet\n */\n constructor(config: PayoutManagerConfig) {\n this.config = config;\n }\n\n /**\n * Signs a Payout transaction and extracts the Schnorr signature.\n *\n * Flow:\n * 1. Vault provider submits Claim transaction\n * 2. Claimer submits Assert transaction to prove validity\n * 3. Payout can be executed (references Assert tx)\n *\n * This method orchestrates the following steps:\n * 1. Get wallet's public key and convert to x-only format\n * 2. Validate wallet pubkey matches on-chain depositor pubkey (if provided)\n * 3. Build unsigned PSBT using primitives\n * 4. Sign PSBT via btcWallet.signPsbt()\n * 5. Extract 64-byte Schnorr signature using primitives\n *\n * The returned signature can be submitted to the vault provider API.\n *\n * @param params - Payout signing parameters\n * @returns Signature result with 64-byte Schnorr signature and depositor pubkey\n * @throws Error if wallet pubkey doesn't match depositor pubkey\n * @throws Error if wallet operations fail or signature extraction fails\n */\n async signPayoutTransaction(\n params: SignPayoutParams,\n ): Promise<PayoutSignatureResult> {\n // Validate wallet pubkey matches depositor and get both formats\n const walletPubkeyRaw = await this.config.btcWallet.getPublicKeyHex();\n const { depositorPubkey } = validateWalletPubkey(\n walletPubkeyRaw,\n params.depositorBtcPubkey,\n );\n\n // Build unsigned PSBT for Payout (uses Assert tx). Per-role output\n // validation happens inside buildPayoutPsbt against the resolved input\n // values.\n const payoutPsbt = await buildPayoutPsbt({\n vaultCoreVersion: params.vaultCoreVersion,\n payoutTxHex: params.payoutTxHex,\n peginTxHex: params.peginTxHex,\n assertTxHex: params.assertTxHex,\n depositorBtcPubkey: depositorPubkey,\n vaultProviderBtcPubkey: params.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: params.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: params.universalChallengerBtcPubkeys,\n timelockPegin: params.timelockPegin,\n timelockAssert: params.timelockAssert,\n network: this.config.network,\n claimerBtcPubkey: params.claimerBtcPubkey,\n registeredPayoutScriptPubKey: params.registeredPayoutScriptPubKey,\n commissionBps: params.commissionBps,\n protocolFeeRate: params.protocolFeeRate,\n councilMembers: params.councilMembers,\n councilQuorum: params.councilQuorum,\n vkClaimerPayoutScriptPubKeys: params.vkClaimerPayoutScriptPubKeys,\n vpCommissionScriptPubKey: params.vpCommissionScriptPubKey,\n });\n\n // Sign PSBT via wallet (Taproot script-path spend, input 0 only)\n const signedPsbtHex = await this.config.btcWallet.signPsbt(\n payoutPsbt.psbtHex,\n createTaprootScriptPathSignOptions(\n walletPubkeyRaw,\n DEPOSITOR_SIGNED_INPUT_COUNT,\n ),\n );\n\n assertPsbtUnsignedTxMatches({\n requestedPsbtHex: payoutPsbt.psbtHex,\n returnedPsbtHex: signedPsbtHex,\n });\n\n // Extract Schnorr signature\n const signature = extractPayoutSignature(signedPsbtHex, depositorPubkey);\n // Critical Path #7: verify the signature against a sighash recomputed from\n // the PSBT we built, not the wallet-returned one.\n assertScriptPathSchnorrSignature({\n requestedPsbtHex: payoutPsbt.psbtHex,\n signatureHex: signature,\n signerXOnlyPubkeyHex: depositorPubkey,\n inputIndex: PAYOUT_SIGNED_INPUT_INDEX,\n });\n\n return {\n signature,\n depositorBtcPubkey: depositorPubkey,\n };\n }\n\n /**\n * Gets the configured Bitcoin network.\n *\n * @returns The Bitcoin network (mainnet, testnet, signet, regtest)\n */\n getNetwork(): Network {\n return this.config.network;\n }\n\n /**\n * Checks if the wallet supports batch signing (signPsbts).\n *\n * @returns true if batch signing is supported\n */\n supportsBatchSigning(): boolean {\n return typeof this.config.btcWallet.signPsbts === \"function\";\n }\n\n /**\n * Batch signs multiple payout transactions (1 per claimer).\n * This allows signing all transactions with a single wallet interaction.\n *\n * @param transactions - Array of payout params to sign\n * @returns Array of signature results matching input order\n * @throws Error if wallet doesn't support batch signing\n * @throws Error if any signing operation fails\n */\n async signPayoutTransactionsBatch(transactions: SignPayoutParams[]): Promise<\n Array<{\n payoutSignature: string;\n depositorBtcPubkey: string;\n }>\n > {\n if (!this.supportsBatchSigning()) {\n throw new Error(\n \"Wallet does not support batch signing (signPsbts method not available)\",\n );\n }\n\n // Get wallet pubkey once\n const walletPubkeyRaw = await this.config.btcWallet.getPublicKeyHex();\n\n // Build all PSBTs (1 per claimer)\n const psbtsToSign: string[] = [];\n const signOptions: SignPsbtOptions[] = [];\n const depositorPubkeys: string[] = [];\n\n for (const tx of transactions) {\n // Validate wallet pubkey matches depositor\n const { depositorPubkey } = validateWalletPubkey(\n walletPubkeyRaw,\n tx.depositorBtcPubkey,\n );\n depositorPubkeys.push(depositorPubkey);\n\n // Build Payout PSBT (output validation runs inside buildPayoutPsbt\n // against resolved input values).\n const payoutPsbt = await buildPayoutPsbt({\n vaultCoreVersion: tx.vaultCoreVersion,\n payoutTxHex: tx.payoutTxHex,\n peginTxHex: tx.peginTxHex,\n assertTxHex: tx.assertTxHex,\n depositorBtcPubkey: depositorPubkey,\n vaultProviderBtcPubkey: tx.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: tx.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: tx.universalChallengerBtcPubkeys,\n timelockPegin: tx.timelockPegin,\n timelockAssert: tx.timelockAssert,\n network: this.config.network,\n claimerBtcPubkey: tx.claimerBtcPubkey,\n registeredPayoutScriptPubKey: tx.registeredPayoutScriptPubKey,\n commissionBps: tx.commissionBps,\n protocolFeeRate: tx.protocolFeeRate,\n councilMembers: tx.councilMembers,\n councilQuorum: tx.councilQuorum,\n vkClaimerPayoutScriptPubKeys: tx.vkClaimerPayoutScriptPubKeys,\n vpCommissionScriptPubKey: tx.vpCommissionScriptPubKey,\n });\n psbtsToSign.push(payoutPsbt.psbtHex);\n signOptions.push(\n createTaprootScriptPathSignOptions(\n walletPubkeyRaw,\n DEPOSITOR_SIGNED_INPUT_COUNT,\n ),\n );\n }\n\n // Batch sign all PSBTs with single wallet interaction\n const signedPsbts = await this.config.btcWallet.signPsbts!(\n psbtsToSign,\n signOptions,\n );\n\n // Validate that wallet returned the expected number of signed PSBTs\n if (signedPsbts.length !== transactions.length) {\n throw new Error(\n `Expected ${transactions.length} signed PSBTs but received ${signedPsbts.length}`,\n );\n }\n\n // Extract signatures from signed PSBTs\n const results: Array<{\n payoutSignature: string;\n depositorBtcPubkey: string;\n }> = [];\n\n for (let i = 0; i < transactions.length; i++) {\n const depositorPubkey = depositorPubkeys[i];\n assertPsbtUnsignedTxMatches({\n requestedPsbtHex: psbtsToSign[i],\n returnedPsbtHex: signedPsbts[i],\n });\n const payoutSignature = extractPayoutSignature(\n signedPsbts[i],\n depositorPubkey,\n );\n assertScriptPathSchnorrSignature({\n requestedPsbtHex: psbtsToSign[i],\n signatureHex: payoutSignature,\n signerXOnlyPubkeyHex: depositorPubkey,\n inputIndex: PAYOUT_SIGNED_INPUT_INDEX,\n });\n\n results.push({\n payoutSignature,\n depositorBtcPubkey: depositorPubkey,\n });\n }\n\n return results;\n }\n}\n","/**\n * Wallet-signing helper that routes a lone PSBT to `signPsbt`, prefers native\n * `signPsbts` for real batches, and falls back to sequential `signPsbt` for\n * wallets that don't implement batch signing.\n *\n * @module managers/pegin/signPsbtsWithFallback\n */\n\nimport type {\n BitcoinWallet,\n SignPsbtOptions,\n} from \"../../../../shared/wallets\";\n\n/**\n * Sign one or more PSBTs against a wallet.\n *\n * A single PSBT is always signed via `signPsbt`, never the batch endpoint: it's\n * one wallet interaction either way, and `signPsbt` is the universally-required\n * wallet method (batch `signPsbts` is optional), so single-sign is the portable\n * choice — some integrations (notably MPC / institutional wallets) prefer it.\n * For a real batch (>1), wallets exposing native `signPsbts` (e.g. UniSat) sign\n * in one interaction; others loop `signPsbt`.\n *\n * @throws If native `signPsbts` returns a different number of signed PSBTs\n * than were submitted.\n */\nexport async function signPsbtsWithFallback(\n wallet: BitcoinWallet,\n psbtsHexes: string[],\n options?: SignPsbtOptions[],\n): Promise<string[]> {\n if (psbtsHexes.length === 1) {\n return [await wallet.signPsbt(psbtsHexes[0], options?.[0])];\n }\n\n if (typeof wallet.signPsbts === \"function\") {\n const signedPsbts = await wallet.signPsbts(psbtsHexes, options);\n if (signedPsbts.length !== psbtsHexes.length) {\n throw new Error(\n `Expected ${psbtsHexes.length} signed PSBTs but received ${signedPsbts.length}`,\n );\n }\n return signedPsbts;\n }\n\n const signedPsbts: string[] = [];\n for (let i = 0; i < psbtsHexes.length; i++) {\n signedPsbts.push(await wallet.signPsbt(psbtsHexes[i], options?.[i]));\n }\n return signedPsbts;\n}\n"],"names":["OP_RETURN","OP_PUSH32","OP_RETURN_PUSH32_SCRIPT_LEN","assertAuthAnchorOpReturn","fundedPrePeginTxHex","vaultCount","expectedAuthAnchorHashHex","cleanHex","stripHexPrefix","tx","bitcoin","opReturnOutput","script","pushedHex","findAuthAnchorOpReturn","hits","i","output","HEX_BYTES32_LENGTH","hexToBytes","hex","clean","bytes","bytesToHex","b","assertBytes32","value","label","computeHashlock","secret","secretBytes","hash","sha256","validateSecretAgainstHashlock","hashlock","supportsDepositApproval","wallet","requireChangeAddress","changeSource","forwardDepositApproval","holdsApprovedDepositTerms","validateDepositTerms","getChangeAddress","terms","PAYOUT_SIGNED_INPUT_INDEX","PayoutManager","config","__publicField","params","walletPubkeyRaw","depositorPubkey","validateWalletPubkey","payoutPsbt","buildPayoutPsbt","signedPsbtHex","createTaprootScriptPathSignOptions","DEPOSITOR_SIGNED_INPUT_COUNT","assertPsbtUnsignedTxMatches","signature","extractPayoutSignature","assertScriptPathSchnorrSignature","transactions","psbtsToSign","signOptions","depositorPubkeys","signedPsbts","results","payoutSignature","signPsbtsWithFallback","psbtsHexes","options"],"mappings":";;;;;;;;;AAYA,MAAMA,IAAY,KAEZC,IAAY,IAEZC,IAA8B;AAmB7B,SAASC,EACdC,GACAC,GAC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9B,WAASjD,IAAI,GAAGA,IAAIqD,EAAW,QAAQrD;AACrC,IAAAiD,EAAY,KAAK,MAAM7B,EAAO,SAASiC,EAAWrD,CAAC,GAAGsD,KAAA,gBAAAA,EAAUtD,EAAE,CAAC;AAErE,SAAOiD;AACT;"}
1
+ {"version":3,"file":"signPsbtsWithFallback-CCFTzE0o.js","sources":["../src/tbv/core/managers/pegin/assertAuthAnchorOpReturn.ts","../src/tbv/core/services/htlc/index.ts","../src/tbv/core/deposit-terms/depositTerms.ts","../src/tbv/core/managers/PayoutManager.ts","../src/tbv/core/managers/pegin/signPsbtsWithFallback.ts"],"sourcesContent":["/**\n * Structural verifier for the auth-anchor OP_RETURN in a funded\n * Pre-PegIn transaction.\n *\n * @module managers/pegin/assertAuthAnchorOpReturn\n */\n\nimport * as bitcoin from \"bitcoinjs-lib\";\n\nimport { stripHexPrefix } from \"../../primitives/utils/bitcoin\";\n\n/** OP_RETURN opcode. */\nconst OP_RETURN = 0x6a;\n/** Push-32-bytes opcode (raw push, not OP_PUSHDATA1). */\nconst OP_PUSH32 = 0x20;\n/** Encoded length of a standard OP_RETURN script with a 32-byte payload. */\nconst OP_RETURN_PUSH32_SCRIPT_LEN = 1 + 1 + 32;\n\n/**\n * Verify the broadcast Pre-PegIn carries the expected OP_RETURN\n * commitment to the auth anchor.\n *\n * The OP_RETURN sits at `vout = vaultCount` (right after the per-vault\n * HTLC outputs and before the depositor-claim/change outputs) and\n * pushes the 32-byte `SHA256(authAnchor)`. The script encoding is\n * exactly `OP_RETURN || PUSH32 || <32 bytes>` (34 bytes). A\n * non-conformant WASM build that omitted the OP_RETURN, swapped its\n * position, or changed its push payload would let the depositor\n * obtain a valid bearer token for a Pre-PegIn whose on-chain\n * commitment doesn't actually bind the anchor — degrading the auth\n * from on-chain-bound to a shared secret. Fail closed.\n *\n * @throws If the OP_RETURN is missing, mis-located, mis-encoded, or\n * pushes a payload other than `expectedAuthAnchorHashHex`.\n */\nexport function assertAuthAnchorOpReturn(\n fundedPrePeginTxHex: string,\n vaultCount: number,\n expectedAuthAnchorHashHex: string,\n): void {\n const cleanHex = stripHexPrefix(fundedPrePeginTxHex);\n const tx = bitcoin.Transaction.fromHex(cleanHex);\n\n if (tx.outs.length <= vaultCount) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN missing: tx has ${tx.outs.length} ` +\n `outputs, expected at least ${vaultCount + 1} (vault outputs + OP_RETURN)`,\n );\n }\n\n const opReturnOutput = tx.outs[vaultCount];\n const script = opReturnOutput.script;\n if (\n script.length !== OP_RETURN_PUSH32_SCRIPT_LEN ||\n script[0] !== OP_RETURN ||\n script[1] !== OP_PUSH32\n ) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN at vout ${vaultCount} has unexpected ` +\n `script encoding (got ${script.length}-byte script with prefix ` +\n `0x${script.slice(0, Math.min(2, script.length)).toString(\"hex\")}; ` +\n `expected ${OP_RETURN_PUSH32_SCRIPT_LEN}-byte OP_RETURN + PUSH32 layout)`,\n );\n }\n\n const pushedHex = script.slice(2).toString(\"hex\").toLowerCase();\n if (pushedHex !== expectedAuthAnchorHashHex.toLowerCase()) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN payload mismatch at vout ${vaultCount}: ` +\n `tx pushes ${pushedHex}, expected ${expectedAuthAnchorHashHex}`,\n );\n }\n\n if (opReturnOutput.value !== 0) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN at vout ${vaultCount} has non-zero ` +\n `value ${opReturnOutput.value}; OP_RETURN outputs must be 0-value`,\n );\n }\n}\n\n/**\n * Scan a funded Pre-PegIn transaction for its auth-anchor commitment\n * (an `OP_RETURN || PUSH32 || <32 bytes>` output with value 0).\n *\n * Returns `{ vout, hash }` when exactly one such output is found.\n * Returns `undefined` when:\n * - the hex is unparseable,\n * - no matching output exists (legacy non-auth-anchored Pre-PegIn),\n * - more than one matching output exists (ambiguous / malformed).\n *\n * Used by the refund orchestrator to (a) locate the on-chain anchor\n * regardless of how many HTLCs preceded it and (b) detect multi-vault\n * funded transactions structurally: the single-vault refund path\n * reconstructs only one hashlock and expects the anchor at vout 1, so\n * any other vout signals a layout this call cannot safely refund.\n */\nexport function findAuthAnchorOpReturn(\n fundedPrePeginTxHex: string,\n): { vout: number; hash: string } | undefined {\n let tx: bitcoin.Transaction;\n try {\n tx = bitcoin.Transaction.fromHex(stripHexPrefix(fundedPrePeginTxHex));\n } catch {\n return undefined;\n }\n\n const hits: { vout: number; hash: string }[] = [];\n for (let i = 0; i < tx.outs.length; i++) {\n const output = tx.outs[i];\n const script = output.script;\n if (\n script.length === OP_RETURN_PUSH32_SCRIPT_LEN &&\n script[0] === OP_RETURN &&\n script[1] === OP_PUSH32 &&\n output.value === 0\n ) {\n hits.push({\n vout: i,\n hash: script.slice(2).toString(\"hex\").toLowerCase(),\n });\n }\n }\n\n return hits.length === 1 ? hits[0] : undefined;\n}\n","/**\n * HTLC Secret / Hashlock Utilities\n *\n * Pure functions for computing and validating SHA-256 hashlocks used in the\n * vault deposit protocol's HTLC (Hash Time Lock Contract).\n *\n * The SDK does NOT generate secrets — that is the caller's responsibility.\n * Today callers use `crypto.getRandomValues(32)`; when the `deriveContextHash`\n * wallet API ships, callers will use `wallet.deriveContextHash(\"babylon-btc-vault\", ctx)`.\n * These utilities work identically regardless of how the secret was produced.\n *\n * On-chain contract validation (BTCVaultRegistry.activateVaultWithSecret):\n * if (sha256(abi.encodePacked(s)) != hashlock) revert InvalidSecret();\n *\n * @module htlc\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport type { Hex } from \"viem\";\n\n/** Expected hex length for a 0x-prefixed bytes32 value. */\nconst HEX_BYTES32_LENGTH = 66; // \"0x\" + 64 hex chars\n\n/**\n * Decode a 0x-prefixed hex string to bytes, with strict validation.\n * @throws if the input is not a valid 0x-prefixed hex string\n */\nfunction hexToBytes(hex: Hex): Uint8Array {\n if (!hex.startsWith(\"0x\") && !hex.startsWith(\"0X\")) {\n throw new Error(\"Expected 0x-prefixed hex string\");\n }\n const clean = hex.slice(2);\n if (clean.length % 2 !== 0) {\n throw new Error(`Hex string has odd length: ${clean.length}`);\n }\n if (!/^[0-9a-fA-F]*$/.test(clean)) {\n throw new Error(\"Hex string contains non-hex characters\");\n }\n const bytes = new Uint8Array(clean.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Encode a Uint8Array as a 0x-prefixed lowercase hex string.\n */\nfunction bytesToHex(bytes: Uint8Array): Hex {\n return `0x${Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")}`;\n}\n\n/**\n * Validate that a value is a 0x-prefixed bytes32 (exactly 32 bytes).\n * @throws if the value is not exactly 32 bytes\n */\nfunction assertBytes32(value: Hex, label: string): void {\n if (value.length !== HEX_BYTES32_LENGTH) {\n throw new Error(\n `${label} must be exactly 32 bytes (${HEX_BYTES32_LENGTH} hex chars with 0x prefix), got ${value.length}`,\n );\n }\n}\n\n/**\n * Compute the SHA-256 hashlock from a secret preimage.\n *\n * Matches the on-chain validation: `sha256(abi.encodePacked(s))` where `s` is a `bytes32`.\n * `abi.encodePacked(bytes32)` is just the raw 32 bytes — no ABI padding.\n *\n * @param secret - 0x-prefixed bytes32 secret (66 hex chars)\n * @returns 0x-prefixed bytes32 SHA-256 hash\n * @throws if secret is not exactly 32 bytes\n */\nexport function computeHashlock(secret: Hex): Hex {\n assertBytes32(secret, \"Secret\");\n const secretBytes = hexToBytes(secret);\n const hash = sha256(secretBytes);\n return bytesToHex(hash);\n}\n\n/**\n * Validate that a secret's SHA-256 hash matches the expected hashlock.\n *\n * Use this for client-side pre-validation before sending the activation\n * transaction to avoid wasting gas on a contract revert.\n *\n * @param secret - 0x-prefixed bytes32 secret (66 hex chars)\n * @param hashlock - 0x-prefixed bytes32 expected hashlock from the vault\n * @returns true if SHA-256(secret) matches the hashlock\n * @throws if secret or hashlock is not exactly 32 bytes\n */\nexport function validateSecretAgainstHashlock(\n secret: Hex,\n hashlock: Hex,\n): boolean {\n assertBytes32(secret, \"Secret\");\n assertBytes32(hashlock, \"Hashlock\");\n // Validate hashlock is valid hex (secret is validated inside computeHashlock)\n hexToBytes(hashlock);\n\n const computed = computeHashlock(secret);\n return computed.toLowerCase() === hashlock.toLowerCase();\n}\n","import type { BitcoinWallet } from \"../../../shared/wallets/interfaces\";\n\n// Field docs use /** */ so they survive into the emitted .d.ts — the published\n// package is the only contract the external provider author (#2109) sees.\n\nexport interface DepositTermsVaultGroup {\n /** 0-based; equals the group's position (groups are ascending by vout). */\n readonly htlcVout: number;\n /** x-only hex (64 chars), as validated on-chain upstream. */\n readonly vaultProviderBtcPubkey: string;\n /** sats */\n readonly peginAmount: bigint;\n /**\n * sats; the MAXIMUM commission the depositor accepts —\n * floor(peginAmount * maxAcceptableCommissionBps / 10_000), the same\n * ceiling the registration calldata carries. An approving wallet MUST\n * enforce the VP payout commission output `<= commissionFee` (e.g. the\n * Ledger vault app does, firmware >= c8db53e), and every commission the\n * contract admits stays under this ceiling (floor is monotonic in bps),\n * so no contract-admitted deposit can be refused at payout. The actual\n * stamped commission may be lower. Display the quoted value in UI, not this.\n */\n readonly commissionFee: bigint;\n /** sats; the same value for every vault. */\n readonly depositorClaimValue: bigint;\n /**\n * sats; the cap an approving wallet enforces on the PegIn tx fee. Equals\n * the graph's exact (minimum) PegIn fee, which is deterministic — so the\n * cap is satisfied exact-by-construction.\n */\n readonly peginMaxFee: bigint;\n}\n\n/**\n * Field names follow btc-vault vocabulary (the protocol source of truth);\n * a device-wire encoder maps them to its intent fields (e.g. the Ledger TLV:\n * protocolFeeRate -> base_fee_rate, timelockPegin -> pegin_csv_timelock,\n * timelockAssert -> payout_timelock, peginAmount -> vault_amount).\n */\nexport interface DepositTerms {\n /**\n * btc-vault tx-graph version (`vaultCoreVersion`) these terms describe —\n * the vault's stamped on-chain version for resumes, the chain's\n * `activeVaultCoreVersion` for fresh deposits. It selects the PegIn shape\n * an approving wallet must expect: v1 = 2 outputs, no anchor; v2/v3 = TRUC\n * nVersion 3, 3 outputs with a 240-sat P2A anchor at vout 2, and an\n * Assert OP_RETURN marker that raises the claim value\n * (btc-vault `transactions/pegin.rs`, `assert_marker.rs`). A provider that\n * supports only one shape MUST reject the others here rather than\n * mis-validating the PSBTs later.\n */\n vaultCoreVersion: number;\n /**\n * sat/vB; the tx-graph fee rate (protocolFeeRate), NOT the mempool funding\n * rate. Approving wallets bound each payout's fee against this rate —\n * pass the exact graph rate, not an inflated ceiling.\n */\n protocolFeeRate: bigint;\n /** Vault-UTXO CSV timelock (blocks). */\n timelockPegin: number;\n /**\n * btc-vault `timelock_assert` (t2) — the CSV on Assert output 0. Its own\n * param, though production derives it and `timelockPegin` from one value.\n */\n timelockAssert: number;\n /** HTLC refund CSV timelock (blocks). */\n timelockRefund: number;\n /**\n * 64-char hex in display order. A device-wire encoder may need the\n * little-endian form — some hardware byte-compares it against\n * PSBT_IN_PREVIOUS_TXID rather than recomputing the txid.\n */\n prepeginTxid: string;\n /** sats; the funded Pre-PegIn fee (an approving wallet caps the signed fee at this). */\n prepeginMaxFee: bigint;\n /**\n * x-only hex. Sorted ascending by the upstream on-chain validation\n * (validateOnChainParticipantKeys); the builder passes them through\n * unasserted — approving devices may reject unsorted lists at load.\n */\n vaultKeeperBtcPubkeys: readonly string[];\n /**\n * x-only hex, sorted ascending upstream independently of vaultKeeperBtcPubkeys (same\n * pass-through contract). Universal challengers only — the full graph\n * challenger set is vaultKeeperBtcPubkeys ∪ universalChallengerBtcPubkeys (vault keepers are the local\n * challengers).\n */\n universalChallengerBtcPubkeys: readonly string[];\n /** Per-vault groups, ordered by ascending htlcVout. */\n vaults: readonly DepositTermsVaultGroup[];\n}\n\n/**\n * Implemented only by depositor-approval wallets (e.g. a Ledger vault\n * provider). Provider obligations:\n *\n * - Envelope: validate terms against the device's envelope BEFORE the\n * ceremony, rejecting with the shape `{ name: \"DepositTermsRejectedError\",\n * reason: \"device-envelope\", message }` (matched structurally, not by class).\n * - Idempotence: a byte-equal re-approval MUST be a no-op while the\n * device-side approval is live; anything that invalidates it (a later\n * `deriveContextHash`, a signing failure) MUST clear the memo.\n *\n * Seam invariant: any derive invalidates a prior approval, so the SDK\n * re-approves after every derive and before the next terms-bound signature.\n * The re-approval sites are `PeginManager.preparePegin`,\n * `runDepositorPresignFlow`, and `signAndBroadcast` (the Pre-PegIn broadcast,\n * which re-derives before approving unless `holdsApprovedDepositTerms`\n * reports the byte-equal intent still live — see `ensurePrePeginTermsApproval`).\n */\nexport interface DepositTermsApprover {\n approveDepositTerms(terms: DepositTerms): Promise<void>;\n /**\n * OPTIONAL fast-path probe: can the Pre-PegIn signature for exactly these\n * terms proceed under the connection's held approval without a new\n * ceremony? MUST report false once that Pre-PegIn was signed (one-shot),\n * MUST answer from host state without device I/O, MUST return false on any\n * doubt, and MUST never throw. A stale true fails closed at the next\n * signature — this is a UX optimization, never an authorization.\n */\n holdsApprovedDepositTerms?(terms: DepositTerms): Promise<boolean>;\n /**\n * OPTIONAL validate-only pre-check (#2110): reject terms the device\n * envelope would refuse, with the same `{ name:\n * \"DepositTermsRejectedError\", reason: \"device-envelope\", message }` shape\n * as `approveDepositTerms`, WITHOUT any device I/O and WITHOUT touching a\n * held approval — the SDK calls it before the first derive screen, so a\n * side effect here would cost or invalidate a physical ceremony. Success\n * is NOT an approval: `approveDepositTerms` still runs its own envelope\n * gate before the ceremony. Callers may pass provisional terms whose\n * `prepeginTxid` is a placeholder (the real txid exists only post-derive),\n * so implementations MUST NOT validate or bind `prepeginTxid` here.\n */\n validateDepositTerms?(terms: DepositTerms): Promise<void>;\n}\n\n/**\n * Where Pre-PegIn change must pay. Approval (policy) wallets sign key-path\n * under a wallet policy whose change branch the device alone can derive and\n * mark internal — the receive address is NOT acceptable change\n * (`process_in_outs.c:114-117` @ e400d8d8).\n *\n * Separate from {@link DepositTermsApprover} because only the Pre-PegIn build\n * needs it: the presign/payout ceremonies approve terms without ever creating\n * change, so they must not require a wallet to implement this.\n *\n * MUST be stable across a deposit flow: the app reads it to build the tx and\n * `preparePegin` re-reads it to verify, so mid-flow rotation fails that gate.\n */\nexport interface PrePeginChangeSource {\n getChangeAddress(): Promise<string>;\n}\n\n/** Probes {@link DepositTermsApprover.approveDepositTerms}. */\nexport function supportsDepositApproval(\n wallet: BitcoinWallet,\n): wallet is BitcoinWallet & DepositTermsApprover {\n return (\n typeof (wallet as Partial<DepositTermsApprover>).approveDepositTerms ===\n \"function\"\n );\n}\n\n/**\n * The wallet's change address, for the one caller that needs it.\n *\n * Narrowing on `approveDepositTerms` alone cannot promise this method, so\n * calling it off the narrowed value would die on `is not a function` in the\n * middle of `preparePegin`, after the pubkey read. Ask here instead and fail\n * with something a provider author can act on.\n *\n * @throws If the wallet cannot report a change address.\n */\nexport async function requireChangeAddress(\n wallet: BitcoinWallet,\n): Promise<string> {\n const changeSource = wallet as Partial<PrePeginChangeSource>;\n if (typeof changeSource.getChangeAddress !== \"function\") {\n throw new Error(\n \"Approval wallet does not implement getChangeAddress; it must expose its change branch, \" +\n \"because the signing device accepts Pre-PegIn change only there.\",\n );\n }\n return changeSource.getChangeAddress();\n}\n\n/**\n * Spreadable forward of the approval capability for wallet-wrapper objects.\n * Object spread drops prototype methods, so every `{...wallet}` wrapper site\n * must re-attach the capability explicitly: `...forwardDepositApproval(wallet)`.\n */\nexport function forwardDepositApproval(\n wallet: BitcoinWallet,\n): Partial<DepositTermsApprover & PrePeginChangeSource> {\n if (!supportsDepositApproval(wallet)) {\n return {};\n }\n const holdsApprovedDepositTerms = wallet.holdsApprovedDepositTerms;\n const validateDepositTerms = wallet.validateDepositTerms;\n const getChangeAddress = (wallet as Partial<PrePeginChangeSource>)\n .getChangeAddress;\n return {\n approveDepositTerms: (terms) => wallet.approveDepositTerms(terms),\n // All optional in the seam: forward only what the provider implements, so\n // wrapper consumers can keep probing by typeof.\n ...(typeof getChangeAddress === \"function\"\n ? { getChangeAddress: () => getChangeAddress.call(wallet) }\n : {}),\n ...(typeof holdsApprovedDepositTerms === \"function\"\n ? {\n holdsApprovedDepositTerms: (terms: DepositTerms) =>\n holdsApprovedDepositTerms.call(wallet, terms),\n }\n : {}),\n ...(typeof validateDepositTerms === \"function\"\n ? {\n validateDepositTerms: (terms: DepositTerms) =>\n validateDepositTerms.call(wallet, terms),\n }\n : {}),\n };\n}\n\nexport interface BuildDepositTermsInputs {\n /** btc-vault tx-graph version the graph is built under. */\n vaultCoreVersion: number;\n protocolFeeRate: bigint;\n timelockPegin: number;\n /** btc-vault `timelock_assert` (t2) — its own param; NOT derived from timelockPegin here. */\n timelockAssert: number;\n timelockRefund: number;\n prepeginTxid: string;\n prepeginMaxFee: bigint;\n vaultProviderBtcPubkey: string;\n vaultKeeperBtcPubkeys: readonly string[];\n universalChallengerBtcPubkeys: readonly string[];\n /** Ceiling bps, not the quote — see {@link DepositTermsVaultGroup.commissionFee}. */\n maxAcceptableCommissionBps: number;\n peginAmounts: readonly bigint[];\n depositorClaimValue: bigint;\n peginMaxFee: bigint;\n}\n","/**\n * Payout Manager\n *\n * High-level manager that orchestrates the payout signing flow by coordinating\n * SDK primitives ({@link buildPayoutPsbt}, {@link extractPayoutSignature})\n * with a user-provided Bitcoin wallet.\n *\n * The Payout transaction references the Assert transaction (input 1).\n *\n * @see {@link PeginManager} - For Steps 1–4 of the peg-in flow\n * @see {@link buildPayoutPsbt} - Lower-level primitive for custom implementations\n * @see {@link extractPayoutSignature} - Extract signatures from signed PSBTs\n *\n * @module managers/PayoutManager\n */\n\nimport type { BitcoinWallet, SignPsbtOptions } from \"../../../shared/wallets\";\nimport {\n assertPsbtUnsignedTxMatches,\n assertScriptPathSchnorrSignature,\n buildPayoutPsbt,\n extractPayoutSignature,\n validateWalletPubkey,\n type Network,\n} from \"../primitives\";\nimport { DEPOSITOR_SIGNED_INPUT_COUNT } from \"../primitives/psbt/constants\";\nimport { createTaprootScriptPathSignOptions } from \"../utils/signing\";\n\n/** Payout PSBTs are signed by the depositor on input 0 (Taproot script-path). */\nconst PAYOUT_SIGNED_INPUT_INDEX = 0;\n\n/**\n * Configuration for the PayoutManager.\n */\nexport interface PayoutManagerConfig {\n /**\n * Bitcoin network to use for transactions.\n */\n network: Network;\n\n /**\n * Bitcoin wallet for signing payout transactions.\n */\n btcWallet: BitcoinWallet;\n}\n\n/**\n * Base parameters shared by both payout transaction types.\n */\ninterface SignPayoutBaseParams {\n /**\n * Vault core (tx-graph) version the vault was registered under — the\n * vault's stamped on-chain `vaultCoreVersion`. Forwarded to\n * {@link buildPayoutPsbt} to derive the matching graph's payout scripts.\n */\n vaultCoreVersion: number;\n\n /**\n * Peg-in transaction hex.\n * The original transaction that created the vault output being spent.\n */\n peginTxHex: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex).\n */\n vaultProviderBtcPubkey: string;\n\n /**\n * Vault keeper BTC public keys (x-only, 64-char hex).\n */\n vaultKeeperBtcPubkeys: string[];\n\n /**\n * Universal challenger BTC public keys (x-only, 64-char hex).\n */\n universalChallengerBtcPubkeys: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n /** btc-vault `timelock_assert`; payout input 1's sequence. */\n timelockAssert: number;\n\n /**\n * Depositor's BTC public key (x-only, 64-char hex). This MUST be the\n * key registered on-chain for the vault — typically read from\n * `BTCVaultRegistry.getBtcVaultBasicInfo(...).depositorBtcPubKey`.\n *\n * Required: omitting it would degrade `validateWalletPubkey` to a\n * self-comparison, allowing the wrong wallet to produce a signature\n * over a script tree that doesn't match the on-chain UTXO.\n */\n depositorBtcPubkey: string;\n\n /**\n * The on-chain registered depositor payout scriptPubKey (hex, with or without 0x prefix).\n * Used to validate that the VP-provided payout transaction actually pays to the\n * correct depositor payout address before signing.\n */\n registeredPayoutScriptPubKey: string;\n\n /**\n * The claimer's x-only BTC public key for this payout (64-char hex, no prefix).\n * Forwarded to {@link buildPayoutPsbt} for per-role output validation.\n */\n claimerBtcPubkey: string;\n\n /**\n * VP commission in basis points (`1..=9999`). Forwarded to {@link buildPayoutPsbt}.\n */\n commissionBps: number;\n\n /**\n * Version-locked tx-graph fee rate (sat/vB) the graph was built with.\n * Forwarded to {@link buildPayoutPsbt} for the fee band.\n */\n protocolFeeRate: bigint;\n\n /**\n * Security council member x-only pubkeys (hex); forwarded to\n * {@link buildPayoutPsbt} to rebuild the Assert:0 payout leaf and to size the\n * fee floor (see PayoutParams).\n */\n councilMembers: string[];\n\n /** M-of-N council quorum; shapes the Assert:0 council leaf (see PayoutParams). */\n councilQuorum: number;\n\n /**\n * RFC-006 resolved payout destinations, keyed by lowercased x-only operation\n * pubkey. Forwarded verbatim to {@link buildPayoutPsbt}; every VK claimer\n * must be present.\n */\n vkClaimerPayoutScriptPubKeys: Readonly<Record<string, string>>;\n /** RFC-006 VP commission destination. Forwarded to {@link buildPayoutPsbt}. */\n vpCommissionScriptPubKey: string;\n}\n\n/**\n * Parameters for signing a Payout transaction.\n *\n * Payout is used in the challenge path after Assert, when the claimer proves validity.\n * Input 1 references the Assert transaction.\n */\nexport interface SignPayoutParams extends SignPayoutBaseParams {\n /**\n * Payout transaction hex (unsigned).\n * This is the transaction from the vault provider that needs depositor signature.\n */\n payoutTxHex: string;\n\n /**\n * Assert transaction hex.\n * Payout input 1 references Assert output 0.\n */\n assertTxHex: string;\n}\n\n/**\n * Result of signing a payout transaction.\n */\nexport interface PayoutSignatureResult {\n /**\n * 64-byte Schnorr signature (128 hex characters).\n */\n signature: string;\n\n /**\n * Depositor's BTC public key used for signing.\n */\n depositorBtcPubkey: string;\n}\n\n/**\n * High-level manager for payout transaction signing.\n *\n * @remarks\n * After registering your peg-in on Ethereum (Step 3), the vault provider prepares\n * claim/payout transaction pairs. You must sign each payout transaction using this\n * manager and submit the signatures to the vault provider's RPC API.\n *\n * **What happens internally:**\n * 1. Validates your wallet's public key matches the vault's depositor\n * 2. Builds an unsigned PSBT with taproot script path spend info\n * 3. Signs input 0 (the vault UTXO) with your wallet\n * 4. Extracts the 64-byte Schnorr signature\n *\n * **Note:** The payout transaction has 2 inputs. PayoutManager only signs input 0\n * (from the peg-in tx). Input 1 (from the assert tx) is signed by the vault provider.\n *\n * @see {@link PeginManager} - For the complete peg-in flow context\n * @see {@link buildPayoutPsbt} - Lower-level primitive used internally\n * @see {@link extractPayoutSignature} - Signature extraction primitive\n */\nexport class PayoutManager {\n private readonly config: PayoutManagerConfig;\n\n /**\n * Creates a new PayoutManager instance.\n *\n * @param config - Manager configuration including wallet\n */\n constructor(config: PayoutManagerConfig) {\n this.config = config;\n }\n\n /**\n * Signs a Payout transaction and extracts the Schnorr signature.\n *\n * Flow:\n * 1. Vault provider submits Claim transaction\n * 2. Claimer submits Assert transaction to prove validity\n * 3. Payout can be executed (references Assert tx)\n *\n * This method orchestrates the following steps:\n * 1. Get wallet's public key and convert to x-only format\n * 2. Validate wallet pubkey matches on-chain depositor pubkey (if provided)\n * 3. Build unsigned PSBT using primitives\n * 4. Sign PSBT via btcWallet.signPsbt()\n * 5. Extract 64-byte Schnorr signature using primitives\n *\n * The returned signature can be submitted to the vault provider API.\n *\n * @param params - Payout signing parameters\n * @returns Signature result with 64-byte Schnorr signature and depositor pubkey\n * @throws Error if wallet pubkey doesn't match depositor pubkey\n * @throws Error if wallet operations fail or signature extraction fails\n */\n async signPayoutTransaction(\n params: SignPayoutParams,\n ): Promise<PayoutSignatureResult> {\n // Validate wallet pubkey matches depositor and get both formats\n const walletPubkeyRaw = await this.config.btcWallet.getPublicKeyHex();\n const { depositorPubkey } = validateWalletPubkey(\n walletPubkeyRaw,\n params.depositorBtcPubkey,\n );\n\n // Build unsigned PSBT for Payout (uses Assert tx). Per-role output\n // validation happens inside buildPayoutPsbt against the resolved input\n // values.\n const payoutPsbt = await buildPayoutPsbt({\n vaultCoreVersion: params.vaultCoreVersion,\n payoutTxHex: params.payoutTxHex,\n peginTxHex: params.peginTxHex,\n assertTxHex: params.assertTxHex,\n depositorBtcPubkey: depositorPubkey,\n vaultProviderBtcPubkey: params.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: params.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: params.universalChallengerBtcPubkeys,\n timelockPegin: params.timelockPegin,\n timelockAssert: params.timelockAssert,\n network: this.config.network,\n claimerBtcPubkey: params.claimerBtcPubkey,\n registeredPayoutScriptPubKey: params.registeredPayoutScriptPubKey,\n commissionBps: params.commissionBps,\n protocolFeeRate: params.protocolFeeRate,\n councilMembers: params.councilMembers,\n councilQuorum: params.councilQuorum,\n vkClaimerPayoutScriptPubKeys: params.vkClaimerPayoutScriptPubKeys,\n vpCommissionScriptPubKey: params.vpCommissionScriptPubKey,\n });\n\n // Sign PSBT via wallet (Taproot script-path spend, input 0 only)\n const signedPsbtHex = await this.config.btcWallet.signPsbt(\n payoutPsbt.psbtHex,\n createTaprootScriptPathSignOptions(\n walletPubkeyRaw,\n DEPOSITOR_SIGNED_INPUT_COUNT,\n ),\n );\n\n assertPsbtUnsignedTxMatches({\n requestedPsbtHex: payoutPsbt.psbtHex,\n returnedPsbtHex: signedPsbtHex,\n });\n\n // Extract Schnorr signature\n const signature = extractPayoutSignature(signedPsbtHex, depositorPubkey);\n // Critical Path #7: verify the signature against a sighash recomputed from\n // the PSBT we built, not the wallet-returned one.\n assertScriptPathSchnorrSignature({\n requestedPsbtHex: payoutPsbt.psbtHex,\n signatureHex: signature,\n signerXOnlyPubkeyHex: depositorPubkey,\n inputIndex: PAYOUT_SIGNED_INPUT_INDEX,\n });\n\n return {\n signature,\n depositorBtcPubkey: depositorPubkey,\n };\n }\n\n /**\n * Gets the configured Bitcoin network.\n *\n * @returns The Bitcoin network (mainnet, testnet, signet, regtest)\n */\n getNetwork(): Network {\n return this.config.network;\n }\n\n /**\n * Checks if the wallet supports batch signing (signPsbts).\n *\n * @returns true if batch signing is supported\n */\n supportsBatchSigning(): boolean {\n return typeof this.config.btcWallet.signPsbts === \"function\";\n }\n\n /**\n * Batch signs multiple payout transactions (1 per claimer).\n * This allows signing all transactions with a single wallet interaction.\n *\n * @param transactions - Array of payout params to sign\n * @returns Array of signature results matching input order\n * @throws Error if wallet doesn't support batch signing\n * @throws Error if any signing operation fails\n */\n async signPayoutTransactionsBatch(transactions: SignPayoutParams[]): Promise<\n Array<{\n payoutSignature: string;\n depositorBtcPubkey: string;\n }>\n > {\n if (!this.supportsBatchSigning()) {\n throw new Error(\n \"Wallet does not support batch signing (signPsbts method not available)\",\n );\n }\n\n // Get wallet pubkey once\n const walletPubkeyRaw = await this.config.btcWallet.getPublicKeyHex();\n\n // Build all PSBTs (1 per claimer)\n const psbtsToSign: string[] = [];\n const signOptions: SignPsbtOptions[] = [];\n const depositorPubkeys: string[] = [];\n\n for (const tx of transactions) {\n // Validate wallet pubkey matches depositor\n const { depositorPubkey } = validateWalletPubkey(\n walletPubkeyRaw,\n tx.depositorBtcPubkey,\n );\n depositorPubkeys.push(depositorPubkey);\n\n // Build Payout PSBT (output validation runs inside buildPayoutPsbt\n // against resolved input values).\n const payoutPsbt = await buildPayoutPsbt({\n vaultCoreVersion: tx.vaultCoreVersion,\n payoutTxHex: tx.payoutTxHex,\n peginTxHex: tx.peginTxHex,\n assertTxHex: tx.assertTxHex,\n depositorBtcPubkey: depositorPubkey,\n vaultProviderBtcPubkey: tx.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: tx.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: tx.universalChallengerBtcPubkeys,\n timelockPegin: tx.timelockPegin,\n timelockAssert: tx.timelockAssert,\n network: this.config.network,\n claimerBtcPubkey: tx.claimerBtcPubkey,\n registeredPayoutScriptPubKey: tx.registeredPayoutScriptPubKey,\n commissionBps: tx.commissionBps,\n protocolFeeRate: tx.protocolFeeRate,\n councilMembers: tx.councilMembers,\n councilQuorum: tx.councilQuorum,\n vkClaimerPayoutScriptPubKeys: tx.vkClaimerPayoutScriptPubKeys,\n vpCommissionScriptPubKey: tx.vpCommissionScriptPubKey,\n });\n psbtsToSign.push(payoutPsbt.psbtHex);\n signOptions.push(\n createTaprootScriptPathSignOptions(\n walletPubkeyRaw,\n DEPOSITOR_SIGNED_INPUT_COUNT,\n ),\n );\n }\n\n // Batch sign all PSBTs with single wallet interaction\n const signedPsbts = await this.config.btcWallet.signPsbts!(\n psbtsToSign,\n signOptions,\n );\n\n // Validate that wallet returned the expected number of signed PSBTs\n if (signedPsbts.length !== transactions.length) {\n throw new Error(\n `Expected ${transactions.length} signed PSBTs but received ${signedPsbts.length}`,\n );\n }\n\n // Extract signatures from signed PSBTs\n const results: Array<{\n payoutSignature: string;\n depositorBtcPubkey: string;\n }> = [];\n\n for (let i = 0; i < transactions.length; i++) {\n const depositorPubkey = depositorPubkeys[i];\n assertPsbtUnsignedTxMatches({\n requestedPsbtHex: psbtsToSign[i],\n returnedPsbtHex: signedPsbts[i],\n });\n const payoutSignature = extractPayoutSignature(\n signedPsbts[i],\n depositorPubkey,\n );\n assertScriptPathSchnorrSignature({\n requestedPsbtHex: psbtsToSign[i],\n signatureHex: payoutSignature,\n signerXOnlyPubkeyHex: depositorPubkey,\n inputIndex: PAYOUT_SIGNED_INPUT_INDEX,\n });\n\n results.push({\n payoutSignature,\n depositorBtcPubkey: depositorPubkey,\n });\n }\n\n return results;\n }\n}\n","/**\n * Wallet-signing helper that routes a lone PSBT to `signPsbt`, prefers native\n * `signPsbts` for real batches, and falls back to sequential `signPsbt` for\n * wallets that don't implement batch signing.\n *\n * @module managers/pegin/signPsbtsWithFallback\n */\n\nimport type {\n BitcoinWallet,\n SignPsbtOptions,\n} from \"../../../../shared/wallets\";\n\n/**\n * Sign one or more PSBTs against a wallet.\n *\n * A single PSBT is always signed via `signPsbt`, never the batch endpoint: it's\n * one wallet interaction either way, and `signPsbt` is the universally-required\n * wallet method (batch `signPsbts` is optional), so single-sign is the portable\n * choice — some integrations (notably MPC / institutional wallets) prefer it.\n * For a real batch (>1), wallets exposing native `signPsbts` (e.g. UniSat) sign\n * in one interaction; others loop `signPsbt`.\n *\n * @throws If native `signPsbts` returns a different number of signed PSBTs\n * than were submitted.\n */\nexport async function signPsbtsWithFallback(\n wallet: BitcoinWallet,\n psbtsHexes: string[],\n options?: SignPsbtOptions[],\n): Promise<string[]> {\n if (psbtsHexes.length === 1) {\n return [await wallet.signPsbt(psbtsHexes[0], options?.[0])];\n }\n\n if (typeof wallet.signPsbts === \"function\") {\n const signedPsbts = await wallet.signPsbts(psbtsHexes, options);\n if (signedPsbts.length !== psbtsHexes.length) {\n throw new Error(\n `Expected ${psbtsHexes.length} signed PSBTs but received ${signedPsbts.length}`,\n );\n }\n return signedPsbts;\n }\n\n const signedPsbts: string[] = [];\n for (let i = 0; i < psbtsHexes.length; i++) {\n signedPsbts.push(await wallet.signPsbt(psbtsHexes[i], options?.[i]));\n }\n return signedPsbts;\n}\n"],"names":["OP_RETURN","OP_PUSH32","OP_RETURN_PUSH32_SCRIPT_LEN","assertAuthAnchorOpReturn","fundedPrePeginTxHex","vaultCount","expectedAuthAnchorHashHex","cleanHex","stripHexPrefix","tx","bitcoin","opReturnOutput","script","pushedHex","findAuthAnchorOpReturn","hits","i","output","HEX_BYTES32_LENGTH","hexToBytes","hex","clean","bytes","bytesToHex","b","assertBytes32","value","label","computeHashlock","secret","secretBytes","hash","sha256","validateSecretAgainstHashlock","hashlock","supportsDepositApproval","wallet","requireChangeAddress","changeSource","forwardDepositApproval","holdsApprovedDepositTerms","validateDepositTerms","getChangeAddress","terms","PAYOUT_SIGNED_INPUT_INDEX","PayoutManager","config","__publicField","params","walletPubkeyRaw","depositorPubkey","validateWalletPubkey","payoutPsbt","buildPayoutPsbt","signedPsbtHex","createTaprootScriptPathSignOptions","DEPOSITOR_SIGNED_INPUT_COUNT","assertPsbtUnsignedTxMatches","signature","extractPayoutSignature","assertScriptPathSchnorrSignature","transactions","psbtsToSign","signOptions","depositorPubkeys","signedPsbts","results","payoutSignature","signPsbtsWithFallback","psbtsHexes","options"],"mappings":";;;;;;;;;AAYA,MAAMA,IAAY,KAEZC,IAAY,IAEZC,IA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