@babylonlabs-io/ts-sdk 0.33.8 → 0.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/dist/{PayoutManager-DDnNB0mj.cjs → PayoutManager-BhJoQZsG.cjs} +2 -2
  2. package/dist/PayoutManager-BhJoQZsG.cjs.map +1 -0
  3. package/dist/{PayoutManager-C9XHKZ5j.js → PayoutManager-s_uH8Uuj.js} +2 -2
  4. package/dist/PayoutManager-s_uH8Uuj.js.map +1 -0
  5. package/dist/PeginManager-DF1oinIQ.js +1172 -0
  6. package/dist/PeginManager-DF1oinIQ.js.map +1 -0
  7. package/dist/PeginManager-cPQuJTB9.cjs +2 -0
  8. package/dist/PeginManager-cPQuJTB9.cjs.map +1 -0
  9. package/dist/{buildAndBroadcastRefund-C7hnNWbj.cjs → buildAndBroadcastRefund-BQ0CaL6Q.cjs} +2 -2
  10. package/dist/{buildAndBroadcastRefund-C7hnNWbj.cjs.map → buildAndBroadcastRefund-BQ0CaL6Q.cjs.map} +1 -1
  11. package/dist/{buildAndBroadcastRefund-B6fGRmvo.js → buildAndBroadcastRefund-DzX11N9S.js} +2 -2
  12. package/dist/{buildAndBroadcastRefund-B6fGRmvo.js.map → buildAndBroadcastRefund-DzX11N9S.js.map} +1 -1
  13. package/dist/index.cjs +1 -1
  14. package/dist/index.js +127 -123
  15. package/dist/sha2-BYVxyZzX.js +274 -0
  16. package/dist/{sha2-6wN58S6R.js.map → sha2-BYVxyZzX.js.map} +1 -1
  17. package/dist/sha2-DsrLC4NM.cjs +2 -0
  18. package/dist/{sha2-CsTynrfJ.cjs.map → sha2-DsrLC4NM.cjs.map} +1 -1
  19. package/dist/tbv/core/clients/eth/index.d.ts +2 -1
  20. package/dist/tbv/core/clients/eth/index.d.ts.map +1 -1
  21. package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts +21 -3
  22. package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts.map +1 -1
  23. package/dist/tbv/core/clients/eth/protocol-params-validation.d.ts +27 -0
  24. package/dist/tbv/core/clients/eth/protocol-params-validation.d.ts.map +1 -0
  25. package/dist/tbv/core/clients/eth/types.d.ts +30 -0
  26. package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
  27. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts +6 -0
  28. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -1
  29. package/dist/tbv/core/clients/index.cjs +1 -1
  30. package/dist/tbv/core/clients/index.js +30 -27
  31. package/dist/tbv/core/index.cjs +1 -1
  32. package/dist/tbv/core/index.js +126 -122
  33. package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
  34. package/dist/tbv/core/managers/index.cjs +1 -1
  35. package/dist/tbv/core/managers/index.js +2 -2
  36. package/dist/tbv/core/services/index.cjs +1 -1
  37. package/dist/tbv/core/services/index.js +2 -2
  38. package/dist/tbv/core/utils/eth/__tests__/waitForTransactionReceiptSmartAware.test.d.ts +2 -0
  39. package/dist/tbv/core/utils/eth/__tests__/waitForTransactionReceiptSmartAware.test.d.ts.map +1 -0
  40. package/dist/tbv/core/utils/eth/index.d.ts +2 -0
  41. package/dist/tbv/core/utils/eth/index.d.ts.map +1 -0
  42. package/dist/tbv/core/utils/eth/waitForTransactionReceiptSmartAware.d.ts +18 -0
  43. package/dist/tbv/core/utils/eth/waitForTransactionReceiptSmartAware.d.ts.map +1 -0
  44. package/dist/tbv/core/utils/index.cjs +1 -1
  45. package/dist/tbv/core/utils/index.d.ts +1 -0
  46. package/dist/tbv/core/utils/index.d.ts.map +1 -1
  47. package/dist/tbv/core/utils/index.js +14 -13
  48. package/dist/tbv/core/vault-secrets/__tests__/deriveVaultRoot.test.d.ts +1 -1
  49. package/dist/tbv/core/vault-secrets/__tests__/expand.test.d.ts +4 -6
  50. package/dist/tbv/core/vault-secrets/__tests__/expand.test.d.ts.map +1 -1
  51. package/dist/tbv/core/vault-secrets/deriveVaultRoot.d.ts +1 -1
  52. package/dist/tbv/core/vault-secrets/deriveVaultRoot.d.ts.map +1 -1
  53. package/dist/tbv/core/vault-secrets/index.d.ts +1 -1
  54. package/dist/tbv/core/vault-secrets/index.d.ts.map +1 -1
  55. package/dist/tbv/index.cjs +1 -1
  56. package/dist/tbv/index.js +126 -122
  57. package/dist/testing/index.cjs +1 -1
  58. package/dist/testing/index.js +1 -1
  59. package/dist/vault-registry-reader-BBk0p-u-.js +1292 -0
  60. package/dist/vault-registry-reader-BBk0p-u-.js.map +1 -0
  61. package/dist/vault-registry-reader-DQgnZilV.cjs +2 -0
  62. package/dist/vault-registry-reader-DQgnZilV.cjs.map +1 -0
  63. package/dist/waitForTransactionReceiptSmartAware-Cj_DKm0G.js +217 -0
  64. package/dist/waitForTransactionReceiptSmartAware-Cj_DKm0G.js.map +1 -0
  65. package/dist/waitForTransactionReceiptSmartAware-D9ykVriz.cjs +2 -0
  66. package/dist/waitForTransactionReceiptSmartAware-D9ykVriz.cjs.map +1 -0
  67. package/package.json +1 -2
  68. package/dist/PayoutManager-C9XHKZ5j.js.map +0 -1
  69. package/dist/PayoutManager-DDnNB0mj.cjs.map +0 -1
  70. package/dist/PeginManager-C8-I4gFH.js +0 -1280
  71. package/dist/PeginManager-C8-I4gFH.js.map +0 -1
  72. package/dist/PeginManager-D0TW9RET.cjs +0 -2
  73. package/dist/PeginManager-D0TW9RET.cjs.map +0 -1
  74. package/dist/psbtInputFields-2224j2ZY.js +0 -128
  75. package/dist/psbtInputFields-2224j2ZY.js.map +0 -1
  76. package/dist/psbtInputFields-B1lrwYzH.cjs +0 -2
  77. package/dist/psbtInputFields-B1lrwYzH.cjs.map +0 -1
  78. package/dist/sha2-6wN58S6R.js +0 -280
  79. package/dist/sha2-CsTynrfJ.cjs +0 -2
  80. package/dist/tbv/core/vault-secrets/__tests__/info.test.d.ts +0 -8
  81. package/dist/tbv/core/vault-secrets/__tests__/info.test.d.ts.map +0 -1
  82. package/dist/tbv/core/vault-secrets/expand.d.ts +0 -58
  83. package/dist/tbv/core/vault-secrets/expand.d.ts.map +0 -1
  84. package/dist/tbv/core/vault-secrets/info.d.ts +0 -55
  85. package/dist/tbv/core/vault-secrets/info.d.ts.map +0 -1
  86. package/dist/vault-registry-reader-DNiXOSYM.cjs +0 -2
  87. package/dist/vault-registry-reader-DNiXOSYM.cjs.map +0 -1
  88. package/dist/vault-registry-reader-PsSxB0JZ.js +0 -1162
  89. package/dist/vault-registry-reader-PsSxB0JZ.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"psbtInputFields-B1lrwYzH.cjs","sources":["../src/tbv/core/utils/utxo/selectUtxos.ts","../src/tbv/core/utils/transaction/btcTxHash.ts","../src/tbv/core/utils/btc/scriptType.ts","../src/tbv/core/utils/btc/psbtInputFields.ts"],"sourcesContent":["/**\n * UTXO selection utilities for peg-in transactions.\n * Follows btc-staking-ts methodology with iterative fee calculation.\n */\n\nimport { script as bitcoinScript } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport {\n BTC_DUST_SAT,\n DUST_THRESHOLD,\n MAX_NON_LEGACY_OUTPUT_SIZE,\n P2TR_INPUT_SIZE,\n rateBasedTxBufferFee,\n TX_BUFFER_SIZE_OVERHEAD,\n} from \"../fee/constants\";\n\n/**\n * Unspent Transaction Output (UTXO) for funding peg-in transactions.\n */\nexport interface UTXO {\n /**\n * Transaction ID of the UTXO (64-char hex without 0x prefix).\n */\n txid: string;\n\n /**\n * Output index within the transaction.\n */\n vout: number;\n\n /**\n * Value in satoshis.\n */\n value: number;\n\n /**\n * Script public key hex.\n */\n scriptPubKey: string;\n}\n\nexport interface UTXOSelectionResult {\n selectedUTXOs: UTXO[];\n totalValue: bigint;\n fee: bigint;\n changeAmount: bigint;\n}\n\n/**\n * Assert that no two UTXOs share the same txid:vout outpoint.\n * Duplicates from a buggy or compromised UTXO source would produce\n * an invalid Bitcoin transaction that double-spends the same outpoint.\n */\nfunction assertNoDuplicateUtxos(utxos: UTXO[]): void {\n const seen = new Set<string>();\n for (const utxo of utxos) {\n const key = `${utxo.txid.toLowerCase()}:${utxo.vout}`;\n if (seen.has(key)) {\n throw new Error(\n `Duplicate UTXO detected: ${utxo.txid}:${utxo.vout}. ` +\n `This indicates a data integrity issue with the UTXO source.`,\n );\n }\n seen.add(key);\n }\n}\n\n/**\n * Selects UTXOs to fund a peg-in transaction with iterative fee calculation.\n *\n * This function implements the btc-staking-ts approach:\n * 1. Filter UTXOs for script validity (no minimum value filter)\n * 2. Sort by value (largest first) to minimize number of inputs\n * 3. Iteratively add UTXOs and recalculate fee until we have enough\n *\n * The fee recalculation is critical because:\n * - Each UTXO added increases transaction size → increases fee\n * - More fee needed might require another UTXO\n * - Change output detection affects fee (adds output size if needed)\n *\n * @param availableUTXOs - All available UTXOs from wallet\n * @param peginAmount - Amount to peg in (satoshis)\n * @param feeRate - Fee rate (sat/vbyte)\n * @param numOutputs - Number of outputs in the unfunded transaction (HTLC + CPFP anchor, before change)\n * @returns Selected UTXOs, total value, calculated fee, and change amount\n * @throws Error if insufficient funds or no valid UTXOs\n */\nexport function selectUtxosForPegin(\n availableUTXOs: UTXO[],\n peginAmount: bigint,\n feeRate: number,\n numOutputs: number,\n): UTXOSelectionResult {\n if (!Number.isInteger(numOutputs) || numOutputs < 1) {\n throw new Error(\n `Invalid numOutputs: expected a positive integer, got ${numOutputs}`,\n );\n }\n\n if (availableUTXOs.length === 0) {\n throw new Error(\"Insufficient funds: no UTXOs available\");\n }\n\n assertNoDuplicateUtxos(availableUTXOs);\n\n // Filter for script validity ONLY (matching btc-staking-ts approach)\n // No minimum value filter - we accept any UTXO with valid script\n const validUTXOs = availableUTXOs.filter((utxo) => {\n const script = Buffer.from(utxo.scriptPubKey, \"hex\");\n const decompiledScript = bitcoinScript.decompile(script);\n return !!decompiledScript;\n });\n\n if (validUTXOs.length === 0) {\n throw new Error(\n \"Insufficient funds: no valid UTXOs available (all have invalid scripts)\",\n );\n }\n\n // Sort by value: HIGHEST to LOWEST (use big UTXOs first)\n // Use spread to avoid mutating the original array\n const sortedUTXOs = [...validUTXOs].sort((a, b) => b.value - a.value);\n\n const selectedUTXOs: UTXO[] = [];\n let accumulatedValue = 0n;\n let estimatedFee = 0n;\n\n // Iteratively select UTXOs and recalculate fee\n for (const utxo of sortedUTXOs) {\n selectedUTXOs.push(utxo);\n accumulatedValue += BigInt(utxo.value);\n\n // Recalculate fee based on CURRENT number of inputs\n const inputSize = selectedUTXOs.length * P2TR_INPUT_SIZE;\n const outputSize = numOutputs * MAX_NON_LEGACY_OUTPUT_SIZE;\n const baseTxSize = inputSize + outputSize + TX_BUFFER_SIZE_OVERHEAD;\n\n // Calculate base fee with buffer\n estimatedFee =\n BigInt(Math.ceil(baseTxSize * feeRate)) +\n BigInt(rateBasedTxBufferFee(feeRate));\n\n // Check if there will be change left after pegin amount and fee\n const changeAmount = accumulatedValue - peginAmount - estimatedFee;\n\n // If change is above dust, add fee for change output\n if (changeAmount > DUST_THRESHOLD) {\n const changeOutputFee = BigInt(\n Math.ceil(MAX_NON_LEGACY_OUTPUT_SIZE * feeRate),\n );\n estimatedFee += changeOutputFee;\n }\n\n // Check if we have enough to cover pegin amount + fees\n if (accumulatedValue >= peginAmount + estimatedFee) {\n // Success! We have enough funds\n const finalChangeAmount = accumulatedValue - peginAmount - estimatedFee;\n\n return {\n selectedUTXOs,\n totalValue: accumulatedValue,\n fee: estimatedFee,\n changeAmount: finalChangeAmount,\n };\n }\n }\n\n // If we get here, we don't have enough funds\n throw new Error(\n `Insufficient funds: need ${peginAmount + estimatedFee} sats (${peginAmount} pegin + ${estimatedFee} fee), have ${accumulatedValue} sats`,\n );\n}\n\n/**\n * Checks if change amount is above dust threshold.\n *\n * @param changeAmount - Change amount in satoshis\n * @returns true if change should be added as output, false if it should go to miners\n */\nexport function shouldAddChangeOutput(changeAmount: bigint): boolean {\n return changeAmount > DUST_THRESHOLD;\n}\n\n/**\n * Gets the dust threshold value.\n *\n * @returns Dust threshold in satoshis\n */\nexport function getDustThreshold(): number {\n return BTC_DUST_SAT;\n}\n","/**\n * Bitcoin Transaction Hash Utilities\n *\n * Provides utilities for calculating Bitcoin transaction hashes in a way that matches\n * the contract's BtcUtils.hashBtcTx() implementation.\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\nimport type { Hex } from \"viem\";\n\n/**\n * Calculate Bitcoin transaction hash\n *\n * This matches the contract's BtcUtils.hashBtcTx() implementation:\n * 1. Double SHA256 the transaction bytes\n * 2. Reverse the byte order (Bitcoin convention)\n *\n * The resulting hash is used as the unique vault identifier in the BTCVaultRegistry contract.\n *\n * @param txHex - Transaction hex (with or without 0x prefix)\n * @returns The transaction hash as Hex (with 0x prefix)\n */\nexport function calculateBtcTxHash(txHex: string): Hex {\n // Remove 0x prefix if present\n const cleanHex = txHex.startsWith(\"0x\") ? txHex.slice(2) : txHex;\n\n // Use bitcoinjs-lib to calculate transaction ID (already does double SHA256 + reverse)\n const tx = Transaction.fromHex(cleanHex);\n const txid = tx.getId();\n\n // Return with 0x prefix to match Ethereum hex format\n return `0x${txid}` as Hex;\n}\n","/**\n * Bitcoin Script Type Detection\n *\n * Utilities to detect Bitcoin script types for proper PSBT input construction.\n *\n * @module utils/btc/scriptType\n */\n\n/**\n * Bitcoin script types.\n */\nexport enum BitcoinScriptType {\n P2PKH = \"P2PKH\",\n P2SH = \"P2SH\",\n P2WPKH = \"P2WPKH\",\n P2WSH = \"P2WSH\",\n P2TR = \"P2TR\",\n UNKNOWN = \"UNKNOWN\",\n}\n\n/**\n * Detect the type of a Bitcoin script.\n *\n * @param scriptPubKey - The script public key buffer\n * @returns The detected script type\n *\n * @example\n * ```typescript\n * const scriptType = getScriptType(Buffer.from(scriptPubKeyHex, 'hex'));\n * if (scriptType === BitcoinScriptType.P2TR) {\n * // Handle Taproot input\n * }\n * ```\n */\nexport function getScriptType(scriptPubKey: Buffer): BitcoinScriptType {\n const length = scriptPubKey.length;\n\n // P2PKH: OP_DUP OP_HASH160 <20 bytes> OP_EQUALVERIFY OP_CHECKSIG (25 bytes)\n if (\n length === 25 &&\n scriptPubKey[0] === 0x76 && // OP_DUP\n scriptPubKey[1] === 0xa9 && // OP_HASH160\n scriptPubKey[2] === 0x14 && // Push 20 bytes\n scriptPubKey[23] === 0x88 && // OP_EQUALVERIFY\n scriptPubKey[24] === 0xac // OP_CHECKSIG\n ) {\n return BitcoinScriptType.P2PKH;\n }\n\n // P2SH: OP_HASH160 <20 bytes> OP_EQUAL (23 bytes)\n if (\n length === 23 &&\n scriptPubKey[0] === 0xa9 && // OP_HASH160\n scriptPubKey[1] === 0x14 && // Push 20 bytes\n scriptPubKey[22] === 0x87 // OP_EQUAL\n ) {\n return BitcoinScriptType.P2SH;\n }\n\n // P2WPKH: OP_0 <20 bytes> (22 bytes)\n if (\n length === 22 &&\n scriptPubKey[0] === 0x00 && // OP_0\n scriptPubKey[1] === 0x14 // Push 20 bytes\n ) {\n return BitcoinScriptType.P2WPKH;\n }\n\n // P2WSH: OP_0 <32 bytes> (34 bytes)\n if (\n length === 34 &&\n scriptPubKey[0] === 0x00 && // OP_0\n scriptPubKey[1] === 0x20 // Push 32 bytes\n ) {\n return BitcoinScriptType.P2WSH;\n }\n\n // P2TR (Taproot): OP_1 <32 bytes> (34 bytes)\n if (\n length === 34 &&\n scriptPubKey[0] === 0x51 && // OP_1\n scriptPubKey[1] === 0x20 // Push 32 bytes\n ) {\n return BitcoinScriptType.P2TR;\n }\n\n return BitcoinScriptType.UNKNOWN;\n}\n\n","/**\n * PSBT Input Field Construction\n *\n * Constructs the correct PSBT input fields for a given UTXO based on its script type.\n *\n * @module utils/btc/psbtInputFields\n */\n\nimport { Buffer } from \"buffer\";\n\nimport { BitcoinScriptType, getScriptType } from \"./scriptType\";\n\n/**\n * PSBT input fields for supported script types (P2TR, P2WPKH, P2WSH).\n */\nexport interface PsbtInputFields {\n witnessUtxo?: {\n script: Buffer;\n value: number;\n };\n witnessScript?: Buffer;\n tapInternalKey?: Buffer;\n}\n\n/**\n * UTXO information for PSBT construction.\n *\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n */\nexport interface UtxoForPsbt {\n /** Transaction ID of the UTXO */\n txid: string;\n /** Output index (vout) of the UTXO */\n vout: number;\n /** Value of the UTXO in satoshis */\n value: number;\n /** ScriptPubKey of the UTXO (hex string) */\n scriptPubKey: string;\n /** Witness script (required for P2WSH) */\n witnessScript?: string;\n}\n\n/**\n * Get PSBT input fields for a given UTXO based on its script type.\n *\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n *\n * @param utxo - The unspent transaction output to process\n * @param publicKeyNoCoord - The x-only public key (32 bytes) for Taproot signing\n * @returns PSBT input fields object containing the necessary data\n * @throws Error if required input data is missing or unsupported script type\n */\nexport function getPsbtInputFields(\n utxo: UtxoForPsbt,\n publicKeyNoCoord?: Buffer,\n): PsbtInputFields {\n const scriptPubKey = Buffer.from(utxo.scriptPubKey, \"hex\");\n const type = getScriptType(scriptPubKey);\n\n switch (type) {\n case BitcoinScriptType.P2WPKH: {\n return {\n witnessUtxo: {\n script: scriptPubKey,\n value: utxo.value,\n },\n };\n }\n\n case BitcoinScriptType.P2WSH: {\n if (!utxo.witnessScript) {\n throw new Error(\"Missing witnessScript for P2WSH input\");\n }\n return {\n witnessUtxo: {\n script: scriptPubKey,\n value: utxo.value,\n },\n witnessScript: Buffer.from(utxo.witnessScript, \"hex\"),\n };\n }\n\n case BitcoinScriptType.P2TR: {\n if (publicKeyNoCoord && publicKeyNoCoord.length !== 32) {\n throw new Error(\n `Invalid tapInternalKey length: expected 32 bytes, got ${publicKeyNoCoord.length}`,\n );\n }\n return {\n witnessUtxo: {\n script: scriptPubKey,\n value: utxo.value,\n },\n // tapInternalKey is needed for Taproot signing\n ...(publicKeyNoCoord && { tapInternalKey: publicKeyNoCoord }),\n };\n }\n\n default:\n throw new Error(`Unsupported script type: ${type}`);\n }\n}\n\n"],"names":["assertNoDuplicateUtxos","utxos","seen","utxo","key","selectUtxosForPegin","availableUTXOs","peginAmount","feeRate","numOutputs","validUTXOs","script","Buffer","bitcoinScript","sortedUTXOs","b","selectedUTXOs","accumulatedValue","estimatedFee","inputSize","P2TR_INPUT_SIZE","outputSize","MAX_NON_LEGACY_OUTPUT_SIZE","baseTxSize","TX_BUFFER_SIZE_OVERHEAD","rateBasedTxBufferFee","DUST_THRESHOLD","changeOutputFee","finalChangeAmount","shouldAddChangeOutput","changeAmount","getDustThreshold","BTC_DUST_SAT","calculateBtcTxHash","txHex","cleanHex","Transaction","BitcoinScriptType","getScriptType","scriptPubKey","length","getPsbtInputFields","publicKeyNoCoord","type"],"mappings":"mHAsDA,SAASA,EAAuBC,EAAqB,CACnD,MAAMC,MAAW,IACjB,UAAWC,KAAQF,EAAO,CACxB,MAAMG,EAAM,GAAGD,EAAK,KAAK,aAAa,IAAIA,EAAK,IAAI,GACnD,GAAID,EAAK,IAAIE,CAAG,EACd,MAAM,IAAI,MACR,4BAA4BD,EAAK,IAAI,IAAIA,EAAK,IAAI,+DAAA,EAItDD,EAAK,IAAIE,CAAG,CACd,CACF,CAsBO,SAASC,EACdC,EACAC,EACAC,EACAC,EACqB,CACrB,GAAI,CAAC,OAAO,UAAUA,CAAU,GAAKA,EAAa,EAChD,MAAM,IAAI,MACR,wDAAwDA,CAAU,EAAA,EAItE,GAAIH,EAAe,SAAW,EAC5B,MAAM,IAAI,MAAM,wCAAwC,EAG1DN,EAAuBM,CAAc,EAIrC,MAAMI,EAAaJ,EAAe,OAAQH,GAAS,CACjD,MAAMQ,EAASC,EAAAA,OAAO,KAAKT,EAAK,aAAc,KAAK,EAEnD,MAAO,CAAC,CADiBU,EAAAA,OAAc,UAAUF,CAAM,CAEzD,CAAC,EAED,GAAID,EAAW,SAAW,EACxB,MAAM,IAAI,MACR,yEAAA,EAMJ,MAAMI,EAAc,CAAC,GAAGJ,CAAU,EAAE,KAAK,CAAC,EAAGK,IAAMA,EAAE,MAAQ,EAAE,KAAK,EAE9DC,EAAwB,CAAA,EAC9B,IAAIC,EAAmB,GACnBC,EAAe,GAGnB,UAAWf,KAAQW,EAAa,CAC9BE,EAAc,KAAKb,CAAI,EACvBc,GAAoB,OAAOd,EAAK,KAAK,EAGrC,MAAMgB,EAAYH,EAAc,OAASI,EAAAA,gBACnCC,EAAaZ,EAAaa,EAAAA,2BAC1BC,EAAaJ,EAAYE,EAAaG,EAAAA,wBAW5C,GARAN,EACE,OAAO,KAAK,KAAKK,EAAaf,CAAO,CAAC,EACtC,OAAOiB,uBAAqBjB,CAAO,CAAC,EAGjBS,EAAmBV,EAAcW,EAGnCQ,EAAAA,eAAgB,CACjC,MAAMC,EAAkB,OACtB,KAAK,KAAKL,EAAAA,2BAA6Bd,CAAO,CAAA,EAEhDU,GAAgBS,CAClB,CAGA,GAAIV,GAAoBV,EAAcW,EAAc,CAElD,MAAMU,EAAoBX,EAAmBV,EAAcW,EAE3D,MAAO,CACL,cAAAF,EACA,WAAYC,EACZ,IAAKC,EACL,aAAcU,CAAA,CAElB,CACF,CAGA,MAAM,IAAI,MACR,4BAA4BrB,EAAcW,CAAY,UAAUX,CAAW,YAAYW,CAAY,eAAeD,CAAgB,OAAA,CAEtI,CAQO,SAASY,EAAsBC,EAA+B,CACnE,OAAOA,EAAeJ,EAAAA,cACxB,CAOO,SAASK,GAA2B,CACzC,OAAOC,EAAAA,YACT,CCzKO,SAASC,EAAmBC,EAAoB,CAErD,MAAMC,EAAWD,EAAM,WAAW,IAAI,EAAIA,EAAM,MAAM,CAAC,EAAIA,EAO3D,MAAO,KAJIE,EAAAA,YAAY,QAAQD,CAAQ,EACvB,MAAA,CAGA,EAClB,CCrBO,IAAKE,GAAAA,IACVA,EAAA,MAAQ,QACRA,EAAA,KAAO,OACPA,EAAA,OAAS,SACTA,EAAA,MAAQ,QACRA,EAAA,KAAO,OACPA,EAAA,QAAU,UANAA,IAAAA,GAAA,CAAA,CAAA,EAuBL,SAASC,EAAcC,EAAyC,CACrE,MAAMC,EAASD,EAAa,OAG5B,OACEC,IAAW,IACXD,EAAa,CAAC,IAAM,KACpBA,EAAa,CAAC,IAAM,KACpBA,EAAa,CAAC,IAAM,IACpBA,EAAa,EAAE,IAAM,KACrBA,EAAa,EAAE,IAAM,IAEd,QAKPC,IAAW,IACXD,EAAa,CAAC,IAAM,KACpBA,EAAa,CAAC,IAAM,IACpBA,EAAa,EAAE,IAAM,IAEd,OAKPC,IAAW,IACXD,EAAa,CAAC,IAAM,GACpBA,EAAa,CAAC,IAAM,GAEb,SAKPC,IAAW,IACXD,EAAa,CAAC,IAAM,GACpBA,EAAa,CAAC,IAAM,GAEb,QAKPC,IAAW,IACXD,EAAa,CAAC,IAAM,IACpBA,EAAa,CAAC,IAAM,GAEb,OAGF,SACT,CCnCO,SAASE,EACdtC,EACAuC,EACiB,CACjB,MAAMH,EAAe3B,EAAAA,OAAO,KAAKT,EAAK,aAAc,KAAK,EACnDwC,EAAOL,EAAcC,CAAY,EAEvC,OAAQI,EAAA,CACN,KAAKN,EAAkB,OACrB,MAAO,CACL,YAAa,CACX,OAAQE,EACR,MAAOpC,EAAK,KAAA,CACd,EAIJ,KAAKkC,EAAkB,MAAO,CAC5B,GAAI,CAAClC,EAAK,cACR,MAAM,IAAI,MAAM,uCAAuC,EAEzD,MAAO,CACL,YAAa,CACX,OAAQoC,EACR,MAAOpC,EAAK,KAAA,EAEd,cAAeS,EAAAA,OAAO,KAAKT,EAAK,cAAe,KAAK,CAAA,CAExD,CAEA,KAAKkC,EAAkB,KAAM,CAC3B,GAAIK,GAAoBA,EAAiB,SAAW,GAClD,MAAM,IAAI,MACR,yDAAyDA,EAAiB,MAAM,EAAA,EAGpF,MAAO,CACL,YAAa,CACX,OAAQH,EACR,MAAOpC,EAAK,KAAA,EAGd,GAAIuC,GAAoB,CAAE,eAAgBA,CAAA,CAAiB,CAE/D,CAEA,QACE,MAAM,IAAI,MAAM,4BAA4BC,CAAI,EAAE,CAAA,CAExD"}
@@ -1,280 +0,0 @@
1
- var U = Object.defineProperty;
2
- var B = (t, e, s) => e in t ? U(t, e, { enumerable: !0, configurable: !0, writable: !0, value: s }) : t[e] = s;
3
- var a = (t, e, s) => B(t, typeof e != "symbol" ? e + "" : e, s);
4
- function I(t) {
5
- return t instanceof Uint8Array || ArrayBuffer.isView(t) && t.constructor.name === "Uint8Array";
6
- }
7
- function E(t, e = "") {
8
- if (!Number.isSafeInteger(t) || t < 0) {
9
- const s = e && `"${e}" `;
10
- throw new Error(`${s}expected integer >= 0, got ${t}`);
11
- }
12
- }
13
- function m(t, e, s = "") {
14
- const i = I(t), n = t == null ? void 0 : t.length, c = e !== void 0;
15
- if (!i || c && n !== e) {
16
- const o = s && `"${s}" `, f = c ? ` of length ${e}` : "", h = i ? `length=${n}` : `type=${typeof t}`;
17
- throw new Error(o + "expected Uint8Array" + f + ", got " + h);
18
- }
19
- return t;
20
- }
21
- function N(t) {
22
- if (typeof t != "function" || typeof t.create != "function")
23
- throw new Error("Hash must wrapped by utils.createHasher");
24
- E(t.outputLen), E(t.blockLen);
25
- }
26
- function H(t, e = !0) {
27
- if (t.destroyed)
28
- throw new Error("Hash instance has been destroyed");
29
- if (e && t.finished)
30
- throw new Error("Hash#digest() has already been called");
31
- }
32
- function _(t, e) {
33
- m(t, void 0, "digestInto() output");
34
- const s = e.outputLen;
35
- if (t.length < s)
36
- throw new Error('"digestInto() output" expected to be of length >=' + s);
37
- }
38
- function T(t) {
39
- return new Uint32Array(t.buffer, t.byteOffset, Math.floor(t.byteLength / 4));
40
- }
41
- function L(...t) {
42
- for (let e = 0; e < t.length; e++)
43
- t[e].fill(0);
44
- }
45
- function w(t) {
46
- return new DataView(t.buffer, t.byteOffset, t.byteLength);
47
- }
48
- function x(t, e) {
49
- return t << 32 - e | t >>> e;
50
- }
51
- function z(t, e) {
52
- return t << e | t >>> 32 - e >>> 0;
53
- }
54
- const k = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
55
- function S(t) {
56
- return t << 24 & 4278190080 | t << 8 & 16711680 | t >>> 8 & 65280 | t >>> 24 & 255;
57
- }
58
- function C(t) {
59
- for (let e = 0; e < t.length; e++)
60
- t[e] = S(t[e]);
61
- return t;
62
- }
63
- const K = k ? (t) => t : C;
64
- function D(t, e = {}) {
65
- const s = (n, c) => t(c).update(n).digest(), i = t(void 0);
66
- return s.outputLen = i.outputLen, s.blockLen = i.blockLen, s.create = (n) => t(n), Object.assign(s, e), Object.freeze(s);
67
- }
68
- const O = (t) => ({
69
- oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, t])
70
- });
71
- function $(t, e, s) {
72
- return t & e ^ ~t & s;
73
- }
74
- function F(t, e, s) {
75
- return t & e ^ t & s ^ e & s;
76
- }
77
- class G {
78
- constructor(e, s, i, n) {
79
- a(this, "blockLen");
80
- a(this, "outputLen");
81
- a(this, "padOffset");
82
- a(this, "isLE");
83
- // For partial updates less than block size
84
- a(this, "buffer");
85
- a(this, "view");
86
- a(this, "finished", !1);
87
- a(this, "length", 0);
88
- a(this, "pos", 0);
89
- a(this, "destroyed", !1);
90
- this.blockLen = e, this.outputLen = s, this.padOffset = i, this.isLE = n, this.buffer = new Uint8Array(e), this.view = w(this.buffer);
91
- }
92
- update(e) {
93
- H(this), m(e);
94
- const { view: s, buffer: i, blockLen: n } = this, c = e.length;
95
- for (let o = 0; o < c; ) {
96
- const f = Math.min(n - this.pos, c - o);
97
- if (f === n) {
98
- const h = w(e);
99
- for (; n <= c - o; o += n)
100
- this.process(h, o);
101
- continue;
102
- }
103
- i.set(e.subarray(o, o + f), this.pos), this.pos += f, o += f, this.pos === n && (this.process(s, 0), this.pos = 0);
104
- }
105
- return this.length += e.length, this.roundClean(), this;
106
- }
107
- digestInto(e) {
108
- H(this), _(e, this), this.finished = !0;
109
- const { buffer: s, view: i, blockLen: n, isLE: c } = this;
110
- let { pos: o } = this;
111
- s[o++] = 128, L(this.buffer.subarray(o)), this.padOffset > n - o && (this.process(i, 0), o = 0);
112
- for (let r = o; r < n; r++)
113
- s[r] = 0;
114
- i.setBigUint64(n - 8, BigInt(this.length * 8), c), this.process(i, 0);
115
- const f = w(e), h = this.outputLen;
116
- if (h % 4)
117
- throw new Error("_sha2: outputLen must be aligned to 32bit");
118
- const u = h / 4, b = this.get();
119
- if (u > b.length)
120
- throw new Error("_sha2: outputLen bigger than state");
121
- for (let r = 0; r < u; r++)
122
- f.setUint32(4 * r, b[r], c);
123
- }
124
- digest() {
125
- const { buffer: e, outputLen: s } = this;
126
- this.digestInto(e);
127
- const i = e.slice(0, s);
128
- return this.destroy(), i;
129
- }
130
- _cloneInto(e) {
131
- e || (e = new this.constructor()), e.set(...this.get());
132
- const { blockLen: s, buffer: i, length: n, finished: c, destroyed: o, pos: f } = this;
133
- return e.destroyed = o, e.finished = c, e.length = n, e.pos = f, n % s && e.buffer.set(i), e;
134
- }
135
- clone() {
136
- return this._cloneInto();
137
- }
138
- }
139
- const d = /* @__PURE__ */ Uint32Array.from([
140
- 1779033703,
141
- 3144134277,
142
- 1013904242,
143
- 2773480762,
144
- 1359893119,
145
- 2600822924,
146
- 528734635,
147
- 1541459225
148
- ]), V = /* @__PURE__ */ Uint32Array.from([
149
- 1116352408,
150
- 1899447441,
151
- 3049323471,
152
- 3921009573,
153
- 961987163,
154
- 1508970993,
155
- 2453635748,
156
- 2870763221,
157
- 3624381080,
158
- 310598401,
159
- 607225278,
160
- 1426881987,
161
- 1925078388,
162
- 2162078206,
163
- 2614888103,
164
- 3248222580,
165
- 3835390401,
166
- 4022224774,
167
- 264347078,
168
- 604807628,
169
- 770255983,
170
- 1249150122,
171
- 1555081692,
172
- 1996064986,
173
- 2554220882,
174
- 2821834349,
175
- 2952996808,
176
- 3210313671,
177
- 3336571891,
178
- 3584528711,
179
- 113926993,
180
- 338241895,
181
- 666307205,
182
- 773529912,
183
- 1294757372,
184
- 1396182291,
185
- 1695183700,
186
- 1986661051,
187
- 2177026350,
188
- 2456956037,
189
- 2730485921,
190
- 2820302411,
191
- 3259730800,
192
- 3345764771,
193
- 3516065817,
194
- 3600352804,
195
- 4094571909,
196
- 275423344,
197
- 430227734,
198
- 506948616,
199
- 659060556,
200
- 883997877,
201
- 958139571,
202
- 1322822218,
203
- 1537002063,
204
- 1747873779,
205
- 1955562222,
206
- 2024104815,
207
- 2227730452,
208
- 2361852424,
209
- 2428436474,
210
- 2756734187,
211
- 3204031479,
212
- 3329325298
213
- ]), p = /* @__PURE__ */ new Uint32Array(64);
214
- class M extends G {
215
- constructor(e) {
216
- super(64, e, 8, !1);
217
- }
218
- get() {
219
- const { A: e, B: s, C: i, D: n, E: c, F: o, G: f, H: h } = this;
220
- return [e, s, i, n, c, o, f, h];
221
- }
222
- // prettier-ignore
223
- set(e, s, i, n, c, o, f, h) {
224
- this.A = e | 0, this.B = s | 0, this.C = i | 0, this.D = n | 0, this.E = c | 0, this.F = o | 0, this.G = f | 0, this.H = h | 0;
225
- }
226
- process(e, s) {
227
- for (let r = 0; r < 16; r++, s += 4)
228
- p[r] = e.getUint32(s, !1);
229
- for (let r = 16; r < 64; r++) {
230
- const g = p[r - 15], l = p[r - 2], A = x(g, 7) ^ x(g, 18) ^ g >>> 3, y = x(l, 17) ^ x(l, 19) ^ l >>> 10;
231
- p[r] = y + p[r - 7] + A + p[r - 16] | 0;
232
- }
233
- let { A: i, B: n, C: c, D: o, E: f, F: h, G: u, H: b } = this;
234
- for (let r = 0; r < 64; r++) {
235
- const g = x(f, 6) ^ x(f, 11) ^ x(f, 25), l = b + g + $(f, h, u) + V[r] + p[r] | 0, y = (x(i, 2) ^ x(i, 13) ^ x(i, 22)) + F(i, n, c) | 0;
236
- b = u, u = h, h = f, f = o + l | 0, o = c, c = n, n = i, i = l + y | 0;
237
- }
238
- i = i + this.A | 0, n = n + this.B | 0, c = c + this.C | 0, o = o + this.D | 0, f = f + this.E | 0, h = h + this.F | 0, u = u + this.G | 0, b = b + this.H | 0, this.set(i, n, c, o, f, h, u, b);
239
- }
240
- roundClean() {
241
- L(p);
242
- }
243
- destroy() {
244
- this.set(0, 0, 0, 0, 0, 0, 0, 0), L(this.buffer);
245
- }
246
- }
247
- class j extends M {
248
- constructor() {
249
- super(32);
250
- // We cannot use array here since array allows indexing by variable
251
- // which means optimizer/compiler cannot use registers.
252
- a(this, "A", d[0] | 0);
253
- a(this, "B", d[1] | 0);
254
- a(this, "C", d[2] | 0);
255
- a(this, "D", d[3] | 0);
256
- a(this, "E", d[4] | 0);
257
- a(this, "F", d[5] | 0);
258
- a(this, "G", d[6] | 0);
259
- a(this, "H", d[7] | 0);
260
- }
261
- }
262
- const q = /* @__PURE__ */ D(
263
- () => new j(),
264
- /* @__PURE__ */ O(1)
265
- );
266
- export {
267
- G as H,
268
- N as a,
269
- m as b,
270
- L as c,
271
- H as d,
272
- E as e,
273
- D as f,
274
- K as g,
275
- _ as h,
276
- z as r,
277
- q as s,
278
- T as u
279
- };
280
- //# sourceMappingURL=sha2-6wN58S6R.js.map
@@ -1,2 +0,0 @@
1
- "use strict";var _=Object.defineProperty;var k=(t,e,s)=>e in t?_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var a=(t,e,s)=>k(t,typeof e!="symbol"?e+"":e,s);function D(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function A(t,e=""){if(!Number.isSafeInteger(t)||t<0){const s=e&&`"${e}" `;throw new Error(`${s}expected integer >= 0, got ${t}`)}}function H(t,e,s=""){const i=D(t),n=t==null?void 0:t.length,c=e!==void 0;if(!i||c&&n!==e){const o=s&&`"${s}" `,f=c?` of length ${e}`:"",h=i?`length=${n}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+f+", got "+h)}return t}function S(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash must wrapped by utils.createHasher");A(t.outputLen),A(t.blockLen)}function E(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function U(t,e){H(t,void 0,"digestInto() output");const s=e.outputLen;if(t.length<s)throw new Error('"digestInto() output" expected to be of length >='+s)}function C(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function y(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function L(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function x(t,e){return t<<32-e|t>>>e}function O(t,e){return t<<e|t>>>32-e>>>0}const $=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function F(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function G(t){for(let e=0;e<t.length;e++)t[e]=F(t[e]);return t}const M=$?t=>t:G;function B(t,e={}){const s=(n,c)=>t(c).update(n).digest(),i=t(void 0);return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=n=>t(n),Object.assign(s,e),Object.freeze(s)}const V=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function j(t,e,s){return t&e^~t&s}function W(t,e,s){return t&e^t&s^e&s}class I{constructor(e,s,i,n){a(this,"blockLen");a(this,"outputLen");a(this,"padOffset");a(this,"isLE");a(this,"buffer");a(this,"view");a(this,"finished",!1);a(this,"length",0);a(this,"pos",0);a(this,"destroyed",!1);this.blockLen=e,this.outputLen=s,this.padOffset=i,this.isLE=n,this.buffer=new Uint8Array(e),this.view=L(this.buffer)}update(e){E(this),H(e);const{view:s,buffer:i,blockLen:n}=this,c=e.length;for(let o=0;o<c;){const f=Math.min(n-this.pos,c-o);if(f===n){const h=L(e);for(;n<=c-o;o+=n)this.process(h,o);continue}i.set(e.subarray(o,o+f),this.pos),this.pos+=f,o+=f,this.pos===n&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){E(this),U(e,this),this.finished=!0;const{buffer:s,view:i,blockLen:n,isLE:c}=this;let{pos:o}=this;s[o++]=128,y(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(i,0),o=0);for(let r=o;r<n;r++)s[r]=0;i.setBigUint64(n-8,BigInt(this.length*8),c),this.process(i,0);const f=L(e),h=this.outputLen;if(h%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const u=h/4,b=this.get();if(u>b.length)throw new Error("_sha2: outputLen bigger than state");for(let r=0;r<u;r++)f.setUint32(4*r,b[r],c)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const i=e.slice(0,s);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,buffer:i,length:n,finished:c,destroyed:o,pos:f}=this;return e.destroyed=o,e.finished=c,e.length=n,e.pos=f,n%s&&e.buffer.set(i),e}clone(){return this._cloneInto()}}const d=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),N=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),p=new Uint32Array(64);class T extends I{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:s,C:i,D:n,E:c,F:o,G:f,H:h}=this;return[e,s,i,n,c,o,f,h]}set(e,s,i,n,c,o,f,h){this.A=e|0,this.B=s|0,this.C=i|0,this.D=n|0,this.E=c|0,this.F=o|0,this.G=f|0,this.H=h|0}process(e,s){for(let r=0;r<16;r++,s+=4)p[r]=e.getUint32(s,!1);for(let r=16;r<64;r++){const g=p[r-15],l=p[r-2],m=x(g,7)^x(g,18)^g>>>3,w=x(l,17)^x(l,19)^l>>>10;p[r]=w+p[r-7]+m+p[r-16]|0}let{A:i,B:n,C:c,D:o,E:f,F:h,G:u,H:b}=this;for(let r=0;r<64;r++){const g=x(f,6)^x(f,11)^x(f,25),l=b+g+j(f,h,u)+N[r]+p[r]|0,w=(x(i,2)^x(i,13)^x(i,22))+W(i,n,c)|0;b=u,u=h,h=f,f=o+l|0,o=c,c=n,n=i,i=l+w|0}i=i+this.A|0,n=n+this.B|0,c=c+this.C|0,o=o+this.D|0,f=f+this.E|0,h=h+this.F|0,u=u+this.G|0,b=b+this.H|0,this.set(i,n,c,o,f,h,u,b)}roundClean(){y(p)}destroy(){this.set(0,0,0,0,0,0,0,0),y(this.buffer)}}class z extends T{constructor(){super(32);a(this,"A",d[0]|0);a(this,"B",d[1]|0);a(this,"C",d[2]|0);a(this,"D",d[3]|0);a(this,"E",d[4]|0);a(this,"F",d[5]|0);a(this,"G",d[6]|0);a(this,"H",d[7]|0)}}const K=B(()=>new z,V(1));exports.HashMD=I;exports.abytes=H;exports.aexists=E;exports.ahash=S;exports.anumber=A;exports.aoutput=U;exports.clean=y;exports.createHasher=B;exports.rotl=O;exports.sha256=K;exports.swap32IfBE=M;exports.u32=C;
2
- //# sourceMappingURL=sha2-CsTynrfJ.cjs.map
@@ -1,8 +0,0 @@
1
- /**
2
- * Tests for the `info(label, ctx)` encoder per
3
- * `derive-vault-secrets.md` Appendix A.
4
- *
5
- * The golden hex strings below come from §4 "Label info encodings".
6
- */
7
- export {};
8
- //# sourceMappingURL=info.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"info.test.d.ts","sourceRoot":"","sources":["../../../../../src/tbv/core/vault-secrets/__tests__/info.test.ts"],"names":[],"mappings":"AAAA;;;;;GAKG"}
@@ -1,58 +0,0 @@
1
- /**
2
- * HKDF-Expand-based vault-secret derivation per
3
- * `derive-vault-secrets.md` §2.2.
4
- *
5
- * Pure, synchronous expanders that derive three domain-separated
6
- * secrets from a 32-byte `root`. The root is spec-opaque — typically
7
- * obtained via `deriveVaultRoot(wallet, vaultContextInput)` (which
8
- * forwards to the wallet's `deriveContextHash`), but any 32-byte
9
- * pseudorandom source satisfies the contract.
10
- *
11
- * All expand calls use HKDF-Expand-SHA-256 with `root` directly as the
12
- * PRK (RFC 5869 §3.3: the Extract step is omitted when the input is
13
- * already a uniformly-distributed pseudorandom key of HashLen bytes).
14
- *
15
- * @module vault-secrets/expand
16
- */
17
- /**
18
- * Derive the 32-byte `authAnchor` shared across a single Pre-PegIn
19
- * transaction.
20
- *
21
- * `SHA256(authAnchor)` is committed as the OP_RETURN preimage hash in
22
- * the Pre-PegIn; the raw preimage is revealed to the vault provider's
23
- * `auth_createDepositorToken` RPC in exchange for a CWT bearer token.
24
- *
25
- * @stability frozen — on-chain-binding. Changing the HKDF info encoding
26
- * (label or argument order) rotates the anchor and invalidates the VP
27
- * bearer-token flow for existing deposits.
28
- */
29
- export declare function expandAuthAnchor(root: Uint8Array): Uint8Array;
30
- /**
31
- * Derive the 32-byte `hashlockSecret` for the HTLC at output index
32
- * `htlcVout`.
33
- *
34
- * `SHA256(hashlockSecret)` is committed as the HTLC taproot hashlock
35
- * at vout = `htlcVout` in the Pre-PegIn. The raw preimage is revealed
36
- * on Ethereum via `activateVaultWithSecret`.
37
- *
38
- * @stability frozen — on-chain-binding. Changing the HKDF info
39
- * encoding produces a different secret whose SHA-256 will not match
40
- * the on-chain hashlock; affected vaults can never be activated.
41
- */
42
- export declare function expandHashlockSecret(root: Uint8Array, htlcVout: number): Uint8Array;
43
- /**
44
- * Derive the 64-byte `wotsSeed` for the vault at output index
45
- * `htlcVout`.
46
- *
47
- * Fed into the per-vault WOTS block-keypair derivation. Only the
48
- * `keccak256` hash of the derived public keys appears on-chain
49
- * (committed as `depositorWotsPkHash`).
50
- *
51
- * @stability frozen — on-chain-binding. Changing the HKDF info
52
- * encoding (label or htlcVout serialization) rotates the seed and
53
- * therefore the WOTS keys; existing `depositorWotsPkHash` commitments
54
- * would no longer match. Per-vault domain separation depends on the
55
- * `i2osp4(htlcVout)` argument: do not change its encoding.
56
- */
57
- export declare function expandWotsSeed(root: Uint8Array, htlcVout: number): Uint8Array;
58
- //# sourceMappingURL=expand.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"expand.d.ts","sourceRoot":"","sources":["../../../../src/tbv/core/vault-secrets/expand.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AA0BH;;;;;;;;;;;GAWG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,UAAU,GAAG,UAAU,CAQ7D;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,oBAAoB,CAClC,IAAI,EAAE,UAAU,EAChB,QAAQ,EAAE,MAAM,GACf,UAAU,CAQZ;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,GAAG,UAAU,CAQ7E"}
@@ -1,55 +0,0 @@
1
- /**
2
- * Info encoding for HKDF-Expand per `derive-vault-secrets.md` Appendix A.
3
- *
4
- * ```
5
- * info(label, ctx) :=
6
- * "babylonbtcvault" // fixed 15-byte ASCII domain tag
7
- * || I2OSP(len(label), 1) // 1-byte label length
8
- * || label // ASCII bytes of the label
9
- * || I2OSP(len(ctx), 2) // 2-byte big-endian ctx length
10
- * || ctx // opaque per-label context bytes
11
- * ```
12
- *
13
- * The fixed-width length prefixes make the encoding injective over the
14
- * set of legal `(label, ctx)` pairs, which is what lets distinct labels
15
- * produce computationally-independent HKDF-Expand outputs under the
16
- * HMAC-SHA-256 PRF assumption.
17
- *
18
- * @module vault-secrets/info
19
- */
20
- /**
21
- * @internal Label for the per-HTLC hashlock preimage (Appendix A §A.2).
22
- * Exported only so the spec-conformance tests can pin the literal value.
23
- */
24
- export declare const LABEL_HASHLOCK = "hashlock";
25
- /**
26
- * @internal Label for the per-Pre-PegIn shared auth-anchor (Appendix A §A.2).
27
- * Exported only so the spec-conformance tests can pin the literal value.
28
- */
29
- export declare const LABEL_AUTH_ANCHOR = "auth-anchor";
30
- /**
31
- * @internal Label for the per-HTLC WOTS block-derivation seed (Appendix A §A.2).
32
- * Exported only so the spec-conformance tests can pin the literal value.
33
- */
34
- export declare const LABEL_WOTS_SEED = "wots-seed";
35
- /**
36
- * Encode a 32-bit unsigned integer as 4 big-endian bytes (RFC 8017 §4.1,
37
- * `I2OSP(n, 4)`).
38
- *
39
- * @internal Helper used by `buildInfo` and the per-HTLC `expand*`
40
- * functions; consumed directly only by tests.
41
- *
42
- * @throws If `value` is not a non-negative integer ≤ `0xffffffff`.
43
- */
44
- export declare function i2osp4(value: number): Uint8Array;
45
- /**
46
- * Build the `info` byte-string for an HKDF-Expand invocation.
47
- *
48
- * @internal Used by the per-HTLC `expand*` functions; exposed for the
49
- * spec-conformance tests that pin the encoded byte layout.
50
- *
51
- * @param label - ASCII label tag. Length MUST be in `[1, 255]`.
52
- * @param ctx - Optional opaque context bytes. Length MUST be in `[0, 65535]`.
53
- */
54
- export declare function buildInfo(label: string, ctx?: Uint8Array): Uint8Array;
55
- //# sourceMappingURL=info.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"info.d.ts","sourceRoot":"","sources":["../../../../src/tbv/core/vault-secrets/info.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAaH;;;GAGG;AACH,eAAO,MAAM,cAAc,aAAa,CAAC;AAEzC;;;GAGG;AACH,eAAO,MAAM,iBAAiB,gBAAgB,CAAC;AAE/C;;;GAGG;AACH,eAAO,MAAM,eAAe,cAAc,CAAC;AAE3C;;;;;;;;GAQG;AACH,wBAAgB,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,CAUhD;AAED;;;;;;;;GAQG;AACH,wBAAgB,SAAS,CACvB,KAAK,EAAE,MAAM,EACb,GAAG,GAAE,UAA8B,GAClC,UAAU,CAyCZ"}
@@ -1,2 +0,0 @@
1
- "use strict";var le=Object.defineProperty;var ue=(r,e,t)=>e in r?le(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var g=(r,e,t)=>ue(r,typeof e!="symbol"?e+"":e,t);const N=require("./types-DnyyBNcC.cjs"),f=require("./bitcoin-B3aqjuMP.cjs"),k=require("./validation-u8W7Lp2x.cjs"),de=require("@bitcoin-js/tiny-secp256k1-asmjs"),E=require("bitcoinjs-lib"),A=require("buffer"),M=require("./sha2-CsTynrfJ.cjs"),$=require("./BTCVaultRegistry.abi-ZdPpION2.cjs"),m=require("./ProtocolParams.abi-BmvHwQJV.cjs");function pe(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const O=pe(de),X=new Set(Object.values(N.DaemonStatus)),he=200;function c(r){var e;return((e=JSON.stringify(r))==null?void 0:e.slice(0,he))??"undefined"}const ge="The vault provider returned an unexpected response. Please try again or contact support.";class s extends Error{constructor(t){super(ge);g(this,"detail");this.name="VpResponseValidationError",this.detail=t}}const S=64;function v(r){return typeof r=="string"&&r.length>0&&k.HEX_RE.test(r)}function W(r){return typeof r=="string"&&r.length>0}function J(r,e){if(!v(r))throw new s(`VP response validation failed: "${e}" must be a non-empty hex string, got ${c(r)}`)}function b(r,e){if(!W(r))throw new s(`VP response validation failed: "${e}" must be a non-empty string, got ${c(r)}`)}function Z(r,e){if(!v(r)||r.length!==f.X_ONLY_PUBKEY_HEX_LEN&&r.length!==f.COMPRESSED_PUBKEY_HEX_LEN)throw new s(`VP response validation failed: "${e}" must be a ${f.X_ONLY_PUBKEY_HEX_LEN} or ${f.COMPRESSED_PUBKEY_HEX_LEN}-char hex string (BTC pubkey), got ${c(r)}`)}function fe(r){const e=r.presigning;if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw new s('VP response validation failed: "progress.presigning" must be an object if present');const t=e;if(t.depositor_graph_created!==void 0&&typeof t.depositor_graph_created!="boolean")throw new s(`VP response validation failed: "progress.presigning.depositor_graph_created" must be a boolean if present, got ${c(t.depositor_graph_created)}`);if(t.vk_challenger_presigning_completed!==void 0&&typeof t.vk_challenger_presigning_completed!="number")throw new s(`VP response validation failed: "progress.presigning.vk_challenger_presigning_completed" must be a number if present, got ${c(t.vk_challenger_presigning_completed)}`);if(t.vk_challenger_presigning_total!==void 0&&typeof t.vk_challenger_presigning_total!="number")throw new s(`VP response validation failed: "progress.presigning.vk_challenger_presigning_total" must be a number if present, got ${c(t.vk_challenger_presigning_total)}`)}function Q(r){if(r===null||typeof r!="object")throw new s("VP response validation failed: getPeginStatus response is not an object");const e=r;if(!v(e.pegin_txid)||e.pegin_txid.length!==S)throw new s(`VP response validation failed: "pegin_txid" must be a ${S}-char hex string (txid), got ${c(e.pegin_txid)}`);if(typeof e.status!="string")throw new s('VP response validation failed: "status" must be a string');if(!X.has(e.status))throw new s(`VP response validation failed: unrecognized status "${e.status}". Expected one of: ${[...X].join(", ")}`);if(e.progress===null||typeof e.progress!="object"||Array.isArray(e.progress))throw new s('VP response validation failed: "progress" must be an object');if(fe(e.progress),typeof e.health_info!="string")throw new s('VP response validation failed: "health_info" must be a string');if(e.last_error!==void 0&&typeof e.last_error!="string")throw new s(`VP response validation failed: "last_error" must be a string if present, got ${c(e.last_error)}`)}function _e(r){if(r===null||typeof r!="object")throw new s("VP response validation failed: requestDepositorPresignTransactions response is not an object");const e=r;if(!Array.isArray(e.txs))throw new s('VP response validation failed: "txs" must be an array');for(let t=0;t<e.txs.length;t++)me(e.txs[t],`txs[${t}]`);if(e.depositor_graph===null||typeof e.depositor_graph!="object")throw new s('VP response validation failed: "depositor_graph" must be an object');Ae(e.depositor_graph)}function P(r,e){if(r===null||typeof r!="object")throw new s(`VP response validation failed: "${e}" must be an object`);J(r.tx_hex,`${e}.tx_hex`)}function me(r,e){if(r===null||typeof r!="object")throw new s(`VP response validation failed: "${e}" must be an object`);const t=r;Z(t.claimer_pubkey,`${e}.claimer_pubkey`),P(t.claim_tx,`${e}.claim_tx`),P(t.assert_tx,`${e}.assert_tx`),P(t.payout_tx,`${e}.payout_tx`),b(t.payout_psbt,`${e}.payout_psbt`)}function be(r,e){if(r===null||typeof r!="object")throw new s(`VP response validation failed: "${e}" must be an object`);const t=r;b(t.wots_pks_json,`${e}.wots_pks_json`),b(t.gc_wots_keys_json,`${e}.gc_wots_keys_json`)}function ye(r,e){if(r===null||typeof r!="object")throw new s(`VP response validation failed: "${e}" must be an object`);const t=r;if(Z(t.challenger_pubkey,`${e}.challenger_pubkey`),P(t.challenge_assert_x_tx,`${e}.challenge_assert_x_tx`),P(t.challenge_assert_y_tx,`${e}.challenge_assert_y_tx`),P(t.nopayout_tx,`${e}.nopayout_tx`),b(t.nopayout_psbt,`${e}.nopayout_psbt`),!Array.isArray(t.challenge_assert_connectors))throw new s(`VP response validation failed: "${e}.challenge_assert_connectors" must be an array`);for(let n=0;n<t.challenge_assert_connectors.length;n++)be(t.challenge_assert_connectors[n],`${e}.challenge_assert_connectors[${n}]`);if(!Array.isArray(t.output_label_hashes))throw new s(`VP response validation failed: "${e}.output_label_hashes" must be an array`);for(let n=0;n<t.output_label_hashes.length;n++)J(t.output_label_hashes[n],`${e}.output_label_hashes[${n}]`)}function ee(r){if(r===null||typeof r!="object")throw new s("VP response validation failed: requestDepositorClaimerArtifacts response is not an object");const e=r;if(!W(e.tx_graph_json))throw new s(`VP response validation failed: "tx_graph_json" must be a non-empty string, got ${c(e.tx_graph_json)}`);if(!v(e.verifying_key_hex))throw new s(`VP response validation failed: "verifying_key_hex" must be a non-empty hex string, got ${c(e.verifying_key_hex)}`);if(e.babe_sessions===null||typeof e.babe_sessions!="object")throw new s('VP response validation failed: "babe_sessions" must be an object');for(const[t,n]of Object.entries(e.babe_sessions)){if(n===null||typeof n!="object")throw new s(`VP response validation failed: "babe_sessions.${t}" must be an object`);const i=n;if(!v(i.decryptor_artifacts_hex))throw new s(`VP response validation failed: "babe_sessions.${t}.decryptor_artifacts_hex" must be a non-empty hex string, got ${c(i.decryptor_artifacts_hex)}`)}}function Pe(r){if(r===null||typeof r!="object")throw new s("VP response validation failed: pegout status payload is not an object");const e=r;if(!v(e.pegin_txid)||e.pegin_txid.length!==S)throw new s(`VP response validation failed: "pegin_txid" must be a ${S}-char hex string (txid), got ${c(e.pegin_txid)}`);if(typeof e.found!="boolean")throw new s(`VP response validation failed: "found" must be a boolean, got ${c(e.found)}`);if(e.claimer!==null){if(typeof e.claimer!="object")throw new s(`VP response validation failed: "claimer" must be an object or null, got ${c(e.claimer)}`);we(e.claimer)}if(!Array.isArray(e.challengers))throw new s(`VP response validation failed: "challengers" must be an array, got ${c(e.challengers)}`);for(let t=0;t<e.challengers.length;t++)ve(e.challengers[t],t)}function we(r){if(b(r.status,"claimer.status"),typeof r.failed!="boolean")throw new s(`VP response validation failed: "claimer.failed" must be a boolean, got ${c(r.failed)}`);if(b(r.claim_txid,"claimer.claim_txid"),b(r.claimer_pubkey,"claimer.claimer_pubkey"),b(r.assert_txid,"claimer.assert_txid"),r.challenger_pubkey!==null&&typeof r.challenger_pubkey!="string")throw new s(`VP response validation failed: "claimer.challenger_pubkey" must be a string or null, got ${c(r.challenger_pubkey)}`);if(typeof r.created_at!="number")throw new s(`VP response validation failed: "claimer.created_at" must be a number, got ${c(r.created_at)}`);if(typeof r.updated_at!="number")throw new s(`VP response validation failed: "claimer.updated_at" must be a number, got ${c(r.updated_at)}`)}function ve(r,e){if(r===null||typeof r!="object")throw new s(`VP response validation failed: "challengers[${e}]" must be an object, got ${c(r)}`);const t=r;if(b(t.status,`challengers[${e}].status`),b(t.claim_txid,`challengers[${e}].claim_txid`),b(t.claimer_pubkey,`challengers[${e}].claimer_pubkey`),B(t.assert_txid,`challengers[${e}].assert_txid`),B(t.challenge_assert_x_txid,`challengers[${e}].challenge_assert_x_txid`),B(t.challenge_assert_y_txid,`challengers[${e}].challenge_assert_y_txid`),B(t.nopayout_txid,`challengers[${e}].nopayout_txid`),typeof t.created_at!="number")throw new s(`VP response validation failed: "challengers[${e}].created_at" must be a number, got ${c(t.created_at)}`);if(typeof t.updated_at!="number")throw new s(`VP response validation failed: "challengers[${e}].updated_at" must be a number, got ${c(t.updated_at)}`)}function B(r,e){if(r!==null&&typeof r!="string")throw new s(`VP response validation failed: "${e}" must be a string or null, got ${c(r)}`)}function xe(r){te(r,"batchGetPeginStatus",e=>{e.result!==null&&Q(e.result)})}function Ve(r){te(r,"batchGetPegoutStatus",e=>{e.result!==null&&Pe(e.result)})}function te(r,e,t){if(r===null||typeof r!="object")throw new s(`VP response validation failed: ${e} response is not an object`);const n=r;if(!Array.isArray(n.results))throw new s(`VP response validation failed: "${e}.results" must be an array, got ${c(n.results)}`);for(let i=0;i<n.results.length;i++){const a=n.results[i];if(a===null||typeof a!="object")throw new s(`VP response validation failed: "${e}.results[${i}]" must be an object, got ${c(a)}`);const o=a;if(!v(o.pegin_txid)||o.pegin_txid.length!==S)throw new s(`VP response validation failed: "${e}.results[${i}].pegin_txid" must be a ${S}-char hex string, got ${c(o.pegin_txid)}`);if(o.error!==null&&typeof o.error!="string")throw new s(`VP response validation failed: "${e}.results[${i}].error" must be a string or null, got ${c(o.error)}`);if(o.result===null&&o.error===null)throw new s(`VP response validation failed: "${e}.results[${i}]" has neither "result" nor "error" populated`);if(o.result!==null&&o.error!==null)throw new s(`VP response validation failed: "${e}.results[${i}]" has both "result" and "error" populated`);t(o,i)}}function Ae(r){if(P(r.claim_tx,"depositor_graph.claim_tx"),P(r.assert_tx,"depositor_graph.assert_tx"),P(r.payout_tx,"depositor_graph.payout_tx"),b(r.payout_psbt,"depositor_graph.payout_psbt"),!Array.isArray(r.challenger_presign_data))throw new s('VP response validation failed: "depositor_graph.challenger_presign_data" must be an array');for(let e=0;e<r.challenger_presign_data.length;e++)ye(r.challenger_presign_data[e],`depositor_graph.challenger_presign_data[${e}]`);if(typeof r.offchain_params_version!="number")throw new s('VP response validation failed: "depositor_graph.offchain_params_version" must be a number')}const Se=6e4;class re{constructor(e,t){g(this,"client");const n={baseUrl:e,timeout:(t==null?void 0:t.timeout)??Se,retries:t==null?void 0:t.retries,retryDelay:t==null?void 0:t.retryDelay,retryableFor:t==null?void 0:t.retryableFor,headers:t==null?void 0:t.headers,tokenProvider:t==null?void 0:t.tokenProvider,maxResponseBytes:t==null?void 0:t.maxResponseBytes};this.client=new N.JsonRpcClient(n)}async requestDepositorPresignTransactions(e,t){const n=await this.client.call("vaultProvider_requestDepositorPresignTransactions",e,t);return _e(n),n}async submitDepositorPresignatures(e,t){return this.client.call("vaultProvider_submitDepositorPresignatures",e,t)}async submitDepositorWotsKey(e,t){return this.client.call("vaultProvider_submitDepositorWotsKey",e,t)}async requestDepositorClaimerArtifacts(e,t){const n=await this.client.call("vaultProvider_requestDepositorClaimerArtifacts",e,t);return ee(n),n}async getPeginStatus(e,t){const n=await this.client.call("vaultProvider_getPeginStatus",e,t);return Q(n),n}async batchGetPeginStatus(e,t){const n=await this.client.call("vaultProvider_batchGetPeginStatus",e,t);return xe(n),n}async batchGetPegoutStatus(e,t){const n=await this.client.call("vaultProvider_batchGetPegoutStatus",e,t);return Ve(n),n}}function ke(r,e){const t=new Set;for(const d of r)t.add(d.toLowerCase());const n=new Map,i=new Set,a=[],o=[];for(const d of e){const u=d.pegin_txid.toLowerCase();if(!t.has(u)){o.push(u);continue}if(i.has(u)){a.push(u);continue}i.add(u),n.set(u,{result:d.result,error:d.error})}const l=[];for(const d of t)i.has(d)||l.push(d);return{byTxid:n,missing:l,unexpected:o,duplicate:a}}async function $e(r){const{items:e,getTxid:t,batchCall:n,onItem:i,onMissing:a,onDuplicate:o,onDuplicateBatch:l,onWholeBatchError:d,onUnexpected:u,batchSize:_=N.VP_BATCH_MAX_SIZE}=r;if(!Number.isInteger(_)||_<=0)throw new Error(`batchPollByProvider: batchSize must be a positive integer, got ${_}`);for(let w=0;w<e.length;w+=_){const x=e.slice(w,w+_),T=new Map,j=[];for(const p of x){const y=t(p).toLowerCase();T.set(y,p),j.push(y)}let V;try{const p=await n(j);V=ke(j,p.results)}catch(p){d(x,p);continue}u&&V.unexpected.length>0&&u(V.unexpected);const C=new Set(V.duplicate);for(const p of C){const y=T.get(p);y&&o(y)}l&&C.size>0&&l(C.size);for(const p of V.missing){const y=T.get(p);y&&a(y)}for(const[p,y]of V.byTxid){if(C.has(p))continue;const L=T.get(p);L&&i(L,{pegin_txid:p,result:y.result,error:y.error})}}}const Te="BIP0322-signed-message",Ce="TapTweak",ne=32,Ee=64;function se(r,e){const t=new TextEncoder().encode(r),n=M.sha256(t),i=new Uint8Array(n.length*2+e.length);return i.set(n,0),i.set(n,n.length),i.set(e,n.length*2),M.sha256(i)}function Be(r){if(r.length!==ne)return null;const e=se(Ce,r),t=O.xOnlyPointAddTweak(r,e);return t?t.xOnlyPubkey:null}function Ie(r,e,t){if(e.length!==ne||t.length!==Ee)return!1;try{const n=se(Te,r),i=E.payments.p2tr({internalPubkey:A.Buffer.from(e)});if(!i.output)return!1;const a=i.output,o=0,l=new E.Transaction;l.version=0,l.locktime=0;const d=A.Buffer.concat([A.Buffer.from([0,32]),A.Buffer.from(n)]);l.addInput(A.Buffer.alloc(32,0),4294967295,0,d),l.addOutput(a,o);const u=new E.Transaction;u.version=0,u.locktime=0;const _=l.getHash();u.addInput(_,0,0),u.addOutput(A.Buffer.from([106]),o);const w=u.hashForWitnessV1(0,[a],[o],E.Transaction.SIGHASH_DEFAULT),x=Be(e);return x?O.verifySchnorr(w,x,t):!1}catch{return!1}}function R(r,e){const t=(r&7)<<5,n=typeof e=="bigint"?e:BigInt(e);if(n<0n)throw new Error("cborHead: negative argument");if(n<24n)return new Uint8Array([t|Number(n)]);if(n<0x100n)return new Uint8Array([t|24,Number(n)]);if(n<0x10000n){const a=Number(n);return new Uint8Array([t|25,a>>>8&255,a&255])}if(n<0x100000000n){const a=Number(n);return new Uint8Array([t|26,a>>>24&255,a>>>16&255,a>>>8&255,a&255])}const i=new Uint8Array(9);i[0]=t|27;for(let a=7;a>=0;a--)i[1+a]=Number(n>>BigInt((7-a)*8))&255;return i}function ie(...r){const e=r.reduce((i,a)=>i+a.length,0),t=new Uint8Array(e);let n=0;for(const i of r)t.set(i,n),n+=i.length;return t}function q(r){const t=[R(4,r.length)];for(const n of r)t.push(R(0,n));return ie(...t)}function Re(r,e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`encodeServerIdentityPayload: expires_at must be a non-negative safe integer, got ${t}`);const n=R(4,3),i=q(r),a=q(e),o=R(0,t);return ie(n,i,a,o)}const He=new TextEncoder().encode("btc-auth.server-identity.v1"),Ne=2*3600;class h extends Error{constructor(e,t){super(e),this.reason=t,this.name="ServerIdentityError"}}function I(r){const e=new Uint8Array(r.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(r.slice(t*2,t*2+2),16);return e}function ae(r){const{proof:e,pinnedServerPubkey:t,now:n}=r,i=r.maxLifetimeSecs??Ne,a=f.stripHexPrefix(t).toLowerCase();if(a.length!==f.X_ONLY_PUBKEY_HEX_LEN||!k.HEX_RE.test(a))throw new h(`pinnedServerPubkey must be 32-byte hex; got ${a.length} chars`,"invalid_pubkey_encoding");const o=f.stripHexPrefix(e.server_pubkey).toLowerCase();if(o.length!==f.X_ONLY_PUBKEY_HEX_LEN||!k.HEX_RE.test(o))throw new h(`server_pubkey must be 32-byte hex; got ${o.length} chars`,"invalid_pubkey_encoding");if(o!==a)throw new h(`server_pubkey does not match pinned value: expected ${a}, got ${o}`,"pinned_pubkey_mismatch");if(!Number.isSafeInteger(e.expires_at))throw new h(`expires_at must be a finite integer; got ${JSON.stringify(e.expires_at)}`,"invalid_expires_at");if(!Number.isSafeInteger(n))throw new h(`now must be a finite integer; got ${JSON.stringify(n)}`,"invalid_expires_at");if(e.expires_at<=n)throw new h(`server identity proof expired at ${e.expires_at}, now ${n}`,"expired");if(!Number.isSafeInteger(i)||i<=0)throw new h(`maxLifetimeSecs must be a positive safe integer; got ${JSON.stringify(i)}`,"invalid_max_lifetime");if(e.expires_at-n>i)throw new h(`server identity proof expires too far in the future: expires_at=${e.expires_at}, now=${n}, max lifetime=${i}s`,"expires_too_far");const l=f.stripHexPrefix(e.ephemeral_pubkey).toLowerCase();if(l.length!==f.COMPRESSED_PUBKEY_HEX_LEN||!k.HEX_RE.test(l))throw new h(`ephemeral_pubkey must be 33-byte compressed hex; got ${l.length} chars`,"invalid_ephemeral_pubkey");const d=l.slice(0,2);if(d!=="02"&&d!=="03")throw new h(`ephemeral_pubkey must be compressed (prefix 02/03); got ${d}`,"invalid_ephemeral_pubkey");const u=I(l);if(!O.isPoint(u))throw new h("ephemeral_pubkey is not a valid secp256k1 point","invalid_ephemeral_pubkey");const _=f.stripHexPrefix(e.signature).toLowerCase();if(_.length!==f.SCHNORR_SIG_HEX_LEN||!k.HEX_RE.test(_))throw new h(`signature must be 64-byte Schnorr hex; got ${_.length} chars`,"invalid_signature_encoding");const w=Re(He,I(l),e.expires_at);if(!Ie(w,I(o),I(_)))throw new h("BIP-322 signature verification failed — ephemeral key is not attested by pinned server pubkey","signature_verification_failed")}const Oe=new Set(["vaultProvider_submitDepositorWotsKey","vaultProvider_submitDepositorPresignatures","vaultProvider_requestDepositorPresignTransactions"]),je=6e4,U="auth_createDepositorToken";function oe(r,e){return new N.JsonRpcClient({baseUrl:r,timeout:je,headers:e,retryableFor:t=>t===U})}const F=4102444800,De=30;class Ue{constructor(e){g(this,"client");g(this,"peginTxid");g(this,"authAnchorHex");g(this,"pinnedServerPubkey");g(this,"authGatedMethods");g(this,"refreshSkewSecs");g(this,"now");g(this,"cached",null);g(this,"inFlight",null);this.client=e.client,this.peginTxid=e.peginTxid,this.authAnchorHex=e.authAnchorHex,this.pinnedServerPubkey=e.pinnedServerPubkey,this.authGatedMethods=e.authGatedMethods,this.refreshSkewSecs=e.refreshSkewSecs??De,this.now=e.now??(()=>Math.floor(Date.now()/1e3))}async getToken(e){if(e===U||!this.authGatedMethods.has(e))return null;const t=this.cached;return t&&this.now()+this.refreshSkewSecs<t.expiresAt?t.token:(await this.acquireSingleFlight()).token}invalidate(){this.cached=null}setClient(e){this.client=e}acquireSingleFlight(){const e=this.inFlight;if(e)return e;const t=(async()=>{try{const n=await this.client.call(U,{pegin_txid:this.peginTxid,auth_anchor:this.authAnchorHex});if(ae({proof:n.server_identity,pinnedServerPubkey:this.pinnedServerPubkey,now:this.now()}),typeof n.token!="string"||n.token.length===0)throw new Error(`VpTokenProvider: invalid token in acquire response (expected non-empty string, got ${typeof n.token})`);const i=this.now();if(!Number.isSafeInteger(n.expires_at)||n.expires_at<=i||n.expires_at>F)throw new Error(`VpTokenProvider: invalid expires_at in acquire response (got ${JSON.stringify(n.expires_at)}; must be a safe integer in (${i}, ${F}])`);const a={token:n.token,expiresAt:n.expires_at};return this.cached=a,a}finally{this.inFlight=null}})();return this.inFlight=t,t}}class ce{constructor(){g(this,"entries",new Map)}getOrCreate(e){const t=this.entries.get(e.peginTxid);if(t){if(t.authAnchorHex!==e.authAnchorHex)throw new Error(`VpTokenRegistry: peginTxid ${e.peginTxid} already bound to authAnchorHex ${t.authAnchorHex.slice(0,8)}…; got ${e.authAnchorHex.slice(0,8)}…`);if(t.pinnedServerPubkey!==e.pinnedServerPubkey)throw new Error(`VpTokenRegistry: peginTxid ${e.peginTxid} already bound to pinnedServerPubkey ${t.pinnedServerPubkey.slice(0,8)}…; got ${e.pinnedServerPubkey.slice(0,8)}…`);return t.provider.setClient(e.client),t.provider}const n=new Ue({client:e.client,peginTxid:e.peginTxid,authAnchorHex:e.authAnchorHex,pinnedServerPubkey:e.pinnedServerPubkey,authGatedMethods:Oe});return this.entries.set(e.peginTxid,{provider:n,authAnchorHex:e.authAnchorHex,pinnedServerPubkey:e.pinnedServerPubkey}),n}peek(e){var t;return(t=this.entries.get(e))==null?void 0:t.provider}release(e){this.entries.delete(e)}clear(){this.entries.clear()}get size(){return this.entries.size}}const K=new ce;function Ke(r){var n;const e=oe(r.baseUrl,(n=r.options)==null?void 0:n.headers),t=K.getOrCreate({client:e,peginTxid:r.peginTxid,authAnchorHex:r.authAnchorHex,pinnedServerPubkey:r.pinnedServerPubkey});return new re(r.baseUrl,{...r.options,tokenProvider:t})}function Le(r){K.getOrCreate({client:oe(r.baseUrl,r.headers),peginTxid:r.peginTxid,authAnchorHex:r.authAnchorHex,pinnedServerPubkey:r.pinnedServerPubkey})}async function Me(r,e){const[t,n]=await r.multicall({contracts:[{address:e,abi:$.BTCVaultRegistryABI,functionName:"protocolParams"},{address:e,abi:$.BTCVaultRegistryABI,functionName:"applicationRegistry"}],allowFailure:!1});return{protocolParams:t,applicationRegistry:n}}const G=65535;function D(r){return{timelockAssert:r.timelockAssert,timelockChallengeAssert:r.timelockChallengeAssert,securityCouncilKeys:[...r.securityCouncilKeys],councilQuorum:r.councilQuorum,feeRate:r.feeRate,babeTotalInstances:r.babeTotalInstances,babeInstancesToFinalize:r.babeInstancesToFinalize,minVpCommissionBps:r.minVpCommissionBps,tRefund:r.tRefund,tStale:r.tStale,minPeginFeeRate:r.minPeginFeeRate,proverProgramVersion:r.proverProgramVersion,minPrepeginDepth:r.minPrepeginDepth}}function Y(r){return{minimumPegInAmount:r.minimumPegInAmount,maxPegInAmount:r.maxPegInAmount,pegInAckTimeout:r.pegInAckTimeout,pegInActivationTimeout:r.pegInActivationTimeout,maxHtlcOutputCount:r.maxHtlcOutputCount}}function z(r){if(r>BigInt(G))throw new Error(`timelockAssert value ${r} exceeds uint16 max (${G})`);return Number(r)}class Xe{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getTBVProtocolParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:m.ProtocolParamsABI,functionName:"getTBVProtocolParams"});return Y(e)}async getLatestOffchainParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:m.ProtocolParamsABI,functionName:"getLatestOffchainParams"});return D(e)}async getOffchainParamsByVersion(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:m.ProtocolParamsABI,functionName:"getOffchainParamsByVersion",args:[e]});return D(t)}async getLatestOffchainParamsVersion(){return await this.publicClient.readContract({address:this.contractAddress,abi:m.ProtocolParamsABI,functionName:"latestOffchainParamsVersion"})}async getTimelockPeginByVersion(e){const t=await this.getOffchainParamsByVersion(e);return z(t.timelockAssert)}async getPegInConfiguration(){const e=await this.publicClient.multicall({contracts:[{address:this.contractAddress,abi:m.ProtocolParamsABI,functionName:"getTBVProtocolParams"},{address:this.contractAddress,abi:m.ProtocolParamsABI,functionName:"getLatestOffchainParams"}],allowFailure:!1}),t=Y(e[0]),n=D(e[1]);return{minimumPegInAmount:t.minimumPegInAmount,maxPegInAmount:t.maxPegInAmount,pegInAckTimeout:t.pegInAckTimeout,pegInActivationTimeout:t.pegInActivationTimeout,maxHtlcOutputCount:t.maxHtlcOutputCount,timelockPegin:z(n.timelockAssert),timelockRefund:n.tRefund,minVpCommissionBps:n.minVpCommissionBps,offchainParams:n}}}function H(r){return r.map(e=>({ethAddress:e.ethAddress,btcPubKey:e.btcPubKey}))}class qe{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getVaultKeepersByVersion(e,t){const n=await this.publicClient.readContract({address:this.contractAddress,abi:m.ApplicationRegistryABI,functionName:"getVaultKeepersByVersion",args:[e,t]});return H(n)}async getCurrentVaultKeepers(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:m.ApplicationRegistryABI,functionName:"getCurrentVaultKeepers",args:[e]});return H(t)}async getCurrentVaultKeepersVersion(e){return await this.publicClient.readContract({address:this.contractAddress,abi:m.ApplicationRegistryABI,functionName:"getCurrentVaultKeepersVersion",args:[e]})}}class Fe{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getUniversalChallengersByVersion(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:m.ProtocolParamsABI,functionName:"getUniversalChallengersByVersion",args:[e]});return H(t)}async getCurrentUniversalChallengers(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:m.ProtocolParamsABI,functionName:"getCurrentUniversalChallengers"});return H(e)}async getLatestUniversalChallengersVersion(){return await this.publicClient.readContract({address:this.contractAddress,abi:m.ProtocolParamsABI,functionName:"latestUniversalChallengersVersion"})}}class Ge{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getVaultProviderBtcPubKey(e){const n=(await this.publicClient.readContract({address:this.contractAddress,abi:$.BTCVaultRegistryABI,functionName:"getVaultProviderBTCKey",args:[e]})).toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(n))throw new Error(`getVaultProviderBTCKey returned an unexpected value (vp=${e}, length ${n.length}, prefix "${n.slice(0,2)}")`);const i=n.slice(2);if(!O.isXOnlyPoint(f.hexToUint8Array(i)))throw new Error(`getVaultProviderBTCKey returned a value that is not on the secp256k1 curve (vp=${e})`);return i}async getVaultBasicInfo(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:$.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[e]});return{depositor:t.depositor,depositorBtcPubKey:t.depositorBtcPubKey,amount:t.amount,vaultProvider:t.vaultProvider,status:t.status,applicationEntryPoint:t.applicationEntryPoint,createdAt:t.createdAt}}async getVaultProtocolInfo(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:$.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[e]});return{depositorSignedPeginTx:t.depositorSignedPeginTx,universalChallengersVersion:t.universalChallengersVersion,appVaultKeepersVersion:t.appVaultKeepersVersion,offchainParamsVersion:t.offchainParamsVersion,verifiedAt:t.verifiedAt,depositorWotsPkHash:t.depositorWotsPkHash,hashlock:t.hashlock,htlcVout:t.htlcVout,depositorPopSignature:t.depositorPopSignature,prePeginTxHash:t.prePeginTxHash,vaultProviderCommissionBps:t.vaultProviderCommissionBps}}async getVaultData(e){const[t,n]=await Promise.all([this.getVaultBasicInfo(e),this.getVaultProtocolInfo(e)]);if(!n.depositorSignedPeginTx||n.depositorSignedPeginTx==="0x")throw new Error(`Vault ${e} not found on-chain or has no pegin transaction`);return{basic:t,protocol:n}}}exports.ServerIdentityError=h;exports.VaultProviderRpcClient=re;exports.ViemProtocolParamsReader=Xe;exports.ViemUniversalChallengerReader=Fe;exports.ViemVaultKeeperReader=qe;exports.ViemVaultRegistryReader=Ge;exports.VpResponseValidationError=s;exports.VpTokenRegistry=ce;exports.batchPollByProvider=$e;exports.createAuthenticatedVpClient=Ke;exports.primeVpTokenRegistry=Le;exports.resolveProtocolAddresses=Me;exports.validateRequestDepositorClaimerArtifactsResponse=ee;exports.verifyServerIdentity=ae;exports.vpTokenRegistry=K;
2
- //# sourceMappingURL=vault-registry-reader-DNiXOSYM.cjs.map