@babylonlabs-io/ts-sdk 3.1.2 → 3.2.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 (168) hide show
  1. package/dist/BTCVaultRegistry.abi-BH2-LHxN.cjs +2 -0
  2. package/dist/BTCVaultRegistry.abi-BH2-LHxN.cjs.map +1 -0
  3. package/dist/{BTCVaultRegistry.abi-BmHpMUWD.js → BTCVaultRegistry.abi-BzNTa_EU.js} +19 -1
  4. package/dist/BTCVaultRegistry.abi-BzNTa_EU.js.map +1 -0
  5. package/dist/{PayoutManager-DOdsgcUR.cjs → PayoutManager-B1Ev0r7o.cjs} +2 -2
  6. package/dist/{PayoutManager-DOdsgcUR.cjs.map → PayoutManager-B1Ev0r7o.cjs.map} +1 -1
  7. package/dist/{PayoutManager-BZ212yml.js → PayoutManager-xEGvTbhL.js} +3 -3
  8. package/dist/{PayoutManager-BZ212yml.js.map → PayoutManager-xEGvTbhL.js.map} +1 -1
  9. package/dist/{PeginManager-PyKbfy5q.cjs → PeginManager-BCRtUqyX.cjs} +2 -2
  10. package/dist/{PeginManager-PyKbfy5q.cjs.map → PeginManager-BCRtUqyX.cjs.map} +1 -1
  11. package/dist/{PeginManager-Dfr5Qe1g.js → PeginManager-sizm3dlw.js} +7 -7
  12. package/dist/{PeginManager-Dfr5Qe1g.js.map → PeginManager-sizm3dlw.js.map} +1 -1
  13. package/dist/buildAndBroadcastReclaim-CE77jzTp.cjs +2 -0
  14. package/dist/buildAndBroadcastReclaim-CE77jzTp.cjs.map +1 -0
  15. package/dist/{buildAndBroadcastReclaim-R0HNpLMD.js → buildAndBroadcastReclaim-rQyAiAUS.js} +901 -867
  16. package/dist/buildAndBroadcastReclaim-rQyAiAUS.js.map +1 -0
  17. package/dist/challengeAssert-B2otuf7y.js +509 -0
  18. package/dist/challengeAssert-B2otuf7y.js.map +1 -0
  19. package/dist/challengeAssert-C3eMcM5Y.cjs +2 -0
  20. package/dist/challengeAssert-C3eMcM5Y.cjs.map +1 -0
  21. package/dist/constants-CAm10Qwp.cjs +2 -0
  22. package/dist/constants-CAm10Qwp.cjs.map +1 -0
  23. package/dist/constants-CvQZuxKv.js +48 -0
  24. package/dist/constants-CvQZuxKv.js.map +1 -0
  25. package/dist/{index-CVBtBjQ5.js → index-BRsWXDlv.js} +6 -6
  26. package/dist/{index-CVBtBjQ5.js.map → index-BRsWXDlv.js.map} +1 -1
  27. package/dist/{index-DpjYs5yr.cjs → index-C6avwx1s.cjs} +2 -2
  28. package/dist/{index-DpjYs5yr.cjs.map → index-C6avwx1s.cjs.map} +1 -1
  29. package/dist/index.cjs +1 -1
  30. package/dist/index.js +297 -298
  31. package/dist/index.js.map +1 -1
  32. package/dist/{pegin-registration-client-kdz4fT5_.js → pegin-registration-client-8tzSRDaq.js} +46 -45
  33. package/dist/pegin-registration-client-8tzSRDaq.js.map +1 -0
  34. package/dist/pegin-registration-client-Bmkh1OZ9.cjs +2 -0
  35. package/dist/pegin-registration-client-Bmkh1OZ9.cjs.map +1 -0
  36. package/dist/peginState-CIibG9S_.js +75 -0
  37. package/dist/peginState-CIibG9S_.js.map +1 -0
  38. package/dist/peginState-IyE22wWh.cjs +2 -0
  39. package/dist/peginState-IyE22wWh.cjs.map +1 -0
  40. package/dist/{primeVpAuth-BPj2TPdD.cjs → primeVpAuth-CXNXYKrh.cjs} +2 -2
  41. package/dist/{primeVpAuth-BPj2TPdD.cjs.map → primeVpAuth-CXNXYKrh.cjs.map} +1 -1
  42. package/dist/{primeVpAuth-CiCdRNGf.js → primeVpAuth-D4UWXQ76.js} +2 -2
  43. package/dist/{primeVpAuth-CiCdRNGf.js.map → primeVpAuth-D4UWXQ76.js.map} +1 -1
  44. package/dist/{registration-records-CKLAv3gw.js → registration-records-BBOz21Dm.js} +15 -15
  45. package/dist/{registration-records-CKLAv3gw.js.map → registration-records-BBOz21Dm.js.map} +1 -1
  46. package/dist/{registration-records-DFQgBaYi.cjs → registration-records-DaBufozs.cjs} +2 -2
  47. package/dist/{registration-records-DFQgBaYi.cjs.map → registration-records-DaBufozs.cjs.map} +1 -1
  48. package/dist/{reservation-DOAHVT3B.js → reservation-BZQABu4g.js} +2 -2
  49. package/dist/{reservation-DOAHVT3B.js.map → reservation-BZQABu4g.js.map} +1 -1
  50. package/dist/{reservation-ECxjZi5t.cjs → reservation-CA5knoQ0.cjs} +2 -2
  51. package/dist/{reservation-ECxjZi5t.cjs.map → reservation-CA5knoQ0.cjs.map} +1 -1
  52. package/dist/{signer-set-reader-DFAu6I-v.cjs → signer-set-reader-D-CyIYR5.cjs} +2 -2
  53. package/dist/{signer-set-reader-DFAu6I-v.cjs.map → signer-set-reader-D-CyIYR5.cjs.map} +1 -1
  54. package/dist/{signer-set-reader-BCtmSKUM.js → signer-set-reader-DFF9MgQN.js} +2 -2
  55. package/dist/{signer-set-reader-BCtmSKUM.js.map → signer-set-reader-DFF9MgQN.js.map} +1 -1
  56. package/dist/tbv/core/clients/eth/index.cjs +1 -1
  57. package/dist/tbv/core/clients/eth/index.js +4 -4
  58. package/dist/tbv/core/clients/eth/types.d.ts +8 -0
  59. package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
  60. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -1
  61. package/dist/tbv/core/clients/index.cjs +1 -1
  62. package/dist/tbv/core/clients/index.js +6 -6
  63. package/dist/tbv/core/clients/vault-provider/status/index.cjs +1 -1
  64. package/dist/tbv/core/clients/vault-provider/status/index.js +1 -1
  65. package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts +14 -0
  66. package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts.map +1 -1
  67. package/dist/tbv/core/contracts/index.cjs +1 -1
  68. package/dist/tbv/core/contracts/index.js +1 -1
  69. package/dist/tbv/core/index.cjs +1 -1
  70. package/dist/tbv/core/index.js +293 -294
  71. package/dist/tbv/core/index.js.map +1 -1
  72. package/dist/tbv/core/managers/index.cjs +1 -1
  73. package/dist/tbv/core/managers/index.js +2 -2
  74. package/dist/tbv/core/primitives/index.cjs +1 -1
  75. package/dist/tbv/core/primitives/index.js +29 -30
  76. package/dist/tbv/core/primitives/index.js.map +1 -1
  77. package/dist/tbv/core/primitives/psbt/__tests__/challengeAssert.test.d.ts +2 -0
  78. package/dist/tbv/core/primitives/psbt/__tests__/challengeAssert.test.d.ts.map +1 -0
  79. package/dist/tbv/core/primitives/psbt/__tests__/noPayout.test.d.ts +2 -0
  80. package/dist/tbv/core/primitives/psbt/__tests__/noPayout.test.d.ts.map +1 -0
  81. package/dist/tbv/core/primitives/psbt/challengeAssert.d.ts +43 -0
  82. package/dist/tbv/core/primitives/psbt/challengeAssert.d.ts.map +1 -1
  83. package/dist/tbv/core/primitives/psbt/constants.d.ts +50 -2
  84. package/dist/tbv/core/primitives/psbt/constants.d.ts.map +1 -1
  85. package/dist/tbv/core/primitives/psbt/noPayout.d.ts +42 -0
  86. package/dist/tbv/core/primitives/psbt/noPayout.d.ts.map +1 -1
  87. package/dist/tbv/core/services/activation/activateVault.d.ts +50 -0
  88. package/dist/tbv/core/services/activation/activateVault.d.ts.map +1 -1
  89. package/dist/tbv/core/services/activation/index.d.ts +1 -1
  90. package/dist/tbv/core/services/activation/index.d.ts.map +1 -1
  91. package/dist/tbv/core/services/delegated-claim/__tests__/realWasmWatchtowerArtifacts.test.d.ts +9 -0
  92. package/dist/tbv/core/services/delegated-claim/__tests__/realWasmWatchtowerArtifacts.test.d.ts.map +1 -0
  93. package/dist/tbv/core/services/delegated-claim/assembleWatchtowerArtifacts.d.ts +5 -7
  94. package/dist/tbv/core/services/delegated-claim/assembleWatchtowerArtifacts.d.ts.map +1 -1
  95. package/dist/tbv/core/services/delegated-claim/index.d.ts +3 -4
  96. package/dist/tbv/core/services/delegated-claim/index.d.ts.map +1 -1
  97. package/dist/tbv/core/services/delegated-claim/planDelegatedClaimSigning.d.ts.map +1 -1
  98. package/dist/tbv/core/services/delegated-claim/readWatchtowerArtifacts.d.ts +14 -8
  99. package/dist/tbv/core/services/delegated-claim/readWatchtowerArtifacts.d.ts.map +1 -1
  100. package/dist/tbv/core/services/delegated-claim/types.d.ts +32 -19
  101. package/dist/tbv/core/services/delegated-claim/types.d.ts.map +1 -1
  102. package/dist/tbv/core/services/deposit/__tests__/signDepositorGraph.realGraph.test.d.ts +12 -0
  103. package/dist/tbv/core/services/deposit/__tests__/signDepositorGraph.realGraph.test.d.ts.map +1 -0
  104. package/dist/tbv/core/services/deposit/peginState.d.ts +20 -1
  105. package/dist/tbv/core/services/deposit/peginState.d.ts.map +1 -1
  106. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts +7 -0
  107. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts.map +1 -1
  108. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts +46 -1
  109. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts.map +1 -1
  110. package/dist/tbv/core/services/index.cjs +1 -1
  111. package/dist/tbv/core/services/index.js +59 -59
  112. package/dist/tbv/core/utils/index.cjs +1 -1
  113. package/dist/tbv/core/utils/index.js +1 -1
  114. package/dist/tbv/core/wasm/__tests__/challengeAssertOutputConnector.test.d.ts +2 -0
  115. package/dist/tbv/core/wasm/__tests__/challengeAssertOutputConnector.test.d.ts.map +1 -0
  116. package/dist/tbv/core/wasm/index.cjs +1 -1
  117. package/dist/tbv/core/wasm/index.cjs.map +1 -1
  118. package/dist/tbv/core/wasm/index.d.ts +14 -2
  119. package/dist/tbv/core/wasm/index.d.ts.map +1 -1
  120. package/dist/tbv/core/wasm/index.js +81 -77
  121. package/dist/tbv/core/wasm/index.js.map +1 -1
  122. package/dist/tbv/index.cjs +1 -1
  123. package/dist/tbv/index.js +293 -294
  124. package/dist/tbv/index.js.map +1 -1
  125. package/dist/{toRefundInputs-BbAOOUg6.cjs → toRefundInputs-DOCLxqC1.cjs} +2 -2
  126. package/dist/{toRefundInputs-BbAOOUg6.cjs.map → toRefundInputs-DOCLxqC1.cjs.map} +1 -1
  127. package/dist/{toRefundInputs-DW14g6wH.js → toRefundInputs-Dso_QEr-.js} +5 -5
  128. package/dist/{toRefundInputs-DW14g6wH.js.map → toRefundInputs-Dso_QEr-.js.map} +1 -1
  129. package/dist/{types-Bda75Od0.cjs → types-DGr5HWwD.cjs} +2 -2
  130. package/dist/types-DGr5HWwD.cjs.map +1 -0
  131. package/dist/{types-C5jj3Cc-.js → types-Dbs--c2M.js} +2 -2
  132. package/dist/types-Dbs--c2M.js.map +1 -0
  133. package/dist/{verifyKeyPathSchnorrSignature-CQUut2-O.cjs → verifyKeyPathSchnorrSignature-BRTpEH9X.cjs} +2 -2
  134. package/dist/{verifyKeyPathSchnorrSignature-CQUut2-O.cjs.map → verifyKeyPathSchnorrSignature-BRTpEH9X.cjs.map} +1 -1
  135. package/dist/{verifyKeyPathSchnorrSignature-DxPbeSdQ.js → verifyKeyPathSchnorrSignature-IIj3Z2se.js} +2 -2
  136. package/dist/{verifyKeyPathSchnorrSignature-DxPbeSdQ.js.map → verifyKeyPathSchnorrSignature-IIj3Z2se.js.map} +1 -1
  137. package/dist/{verifyScriptPathSchnorrSignature-D2t1yACC.cjs → verifyScriptPathSchnorrSignature-CahYx5Td.cjs} +2 -2
  138. package/dist/{verifyScriptPathSchnorrSignature-D2t1yACC.cjs.map → verifyScriptPathSchnorrSignature-CahYx5Td.cjs.map} +1 -1
  139. package/dist/{verifyScriptPathSchnorrSignature-B3-VkvnK.js → verifyScriptPathSchnorrSignature-owu3BfyT.js} +2 -2
  140. package/dist/{verifyScriptPathSchnorrSignature-B3-VkvnK.js.map → verifyScriptPathSchnorrSignature-owu3BfyT.js.map} +1 -1
  141. package/package.json +3 -3
  142. package/dist/BTCVaultRegistry.abi-BmHpMUWD.js.map +0 -1
  143. package/dist/BTCVaultRegistry.abi-DffWFdpA.cjs +0 -2
  144. package/dist/BTCVaultRegistry.abi-DffWFdpA.cjs.map +0 -1
  145. package/dist/buildAndBroadcastReclaim-Da8rD5Z7.cjs +0 -2
  146. package/dist/buildAndBroadcastReclaim-Da8rD5Z7.cjs.map +0 -1
  147. package/dist/buildAndBroadcastReclaim-R0HNpLMD.js.map +0 -1
  148. package/dist/challengeAssert-Cp_GeRg8.js +0 -64
  149. package/dist/challengeAssert-Cp_GeRg8.js.map +0 -1
  150. package/dist/challengeAssert-Z7_YULBb.cjs +0 -2
  151. package/dist/challengeAssert-Z7_YULBb.cjs.map +0 -1
  152. package/dist/constants-BeYquVd-.js +0 -36
  153. package/dist/constants-BeYquVd-.js.map +0 -1
  154. package/dist/constants-BwCg5K6R.cjs +0 -2
  155. package/dist/constants-BwCg5K6R.cjs.map +0 -1
  156. package/dist/noPayout-B-vGXJ-V.js +0 -361
  157. package/dist/noPayout-B-vGXJ-V.js.map +0 -1
  158. package/dist/noPayout-DOHak0ui.cjs +0 -2
  159. package/dist/noPayout-DOHak0ui.cjs.map +0 -1
  160. package/dist/pegin-registration-client-C-abxMWq.cjs +0 -2
  161. package/dist/pegin-registration-client-C-abxMWq.cjs.map +0 -1
  162. package/dist/pegin-registration-client-kdz4fT5_.js.map +0 -1
  163. package/dist/peginState-BU2ONFXF.js +0 -68
  164. package/dist/peginState-BU2ONFXF.js.map +0 -1
  165. package/dist/peginState-DUv10EJR.cjs +0 -2
  166. package/dist/peginState-DUv10EJR.cjs.map +0 -1
  167. package/dist/types-Bda75Od0.cjs.map +0 -1
  168. package/dist/types-C5jj3Cc-.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"registration-records-CKLAv3gw.js","sources":["../../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/legacy.js","../src/tbv/core/clients/eth/onChainBtcPubkey.ts","../src/tbv/core/clients/eth/payout-script.ts","../src/tbv/core/clients/eth/pegin-transaction.ts","../src/tbv/core/clients/eth/claimable-event-error.ts","../src/tbv/core/clients/eth/protocol-params-validation.ts","../src/tbv/core/clients/eth/registration-logs-error.ts","../src/tbv/core/clients/eth/registration-records.ts"],"sourcesContent":["/**\n\nSHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions.\nDon't use them in a new protocol. What \"weak\" means:\n\n- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.\n- No practical pre-image attacks (only theoretical, 2^123.4)\n- HMAC seems kinda ok: https://www.rfc-editor.org/rfc/rfc6151\n * @module\n */\nimport { Chi, HashMD, Maj } from \"./_md.js\";\nimport { clean, createHasher, rotl } from \"./utils.js\";\n/** Initial SHA1 state */\nconst SHA1_IV = /* @__PURE__ */ Uint32Array.from([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n// Reusable temporary buffer\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA1 legacy hash class. */\nexport class _SHA1 extends HashMD {\n A = SHA1_IV[0] | 0;\n B = SHA1_IV[1] | 0;\n C = SHA1_IV[2] | 0;\n D = SHA1_IV[3] | 0;\n E = SHA1_IV[4] | 0;\n constructor() {\n super(64, 20, 8, false);\n }\n get() {\n const { A, B, C, D, E } = this;\n return [A, B, C, D, E];\n }\n set(A, B, C, D, E) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n SHA1_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 80; i++)\n SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n // Compression function main loop, 80 rounds\n let { A, B, C, D, E } = this;\n for (let i = 0; i < 80; i++) {\n let F, K;\n if (i < 20) {\n F = Chi(B, C, D);\n K = 0x5a827999;\n }\n else if (i < 40) {\n F = B ^ C ^ D;\n K = 0x6ed9eba1;\n }\n else if (i < 60) {\n F = Maj(B, C, D);\n K = 0x8f1bbcdc;\n }\n else {\n F = B ^ C ^ D;\n K = 0xca62c1d6;\n }\n const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n E = D;\n D = C;\n C = rotl(B, 30);\n B = A;\n A = T;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n this.set(A, B, C, D, E);\n }\n roundClean() {\n clean(SHA1_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. */\nexport const sha1 = /* @__PURE__ */ createHasher(() => new _SHA1());\n/** Per-round constants */\nconst p32 = /* @__PURE__ */ Math.pow(2, 32);\nconst K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) => Math.floor(p32 * Math.abs(Math.sin(i + 1))));\n/** md5 initial state: same as sha1, but 4 u32 instead of 5. */\nconst MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);\n// Reusable temporary buffer\nconst MD5_W = /* @__PURE__ */ new Uint32Array(16);\n/** Internal MD5 legacy hash class. */\nexport class _MD5 extends HashMD {\n A = MD5_IV[0] | 0;\n B = MD5_IV[1] | 0;\n C = MD5_IV[2] | 0;\n D = MD5_IV[3] | 0;\n constructor() {\n super(64, 16, 8, true);\n }\n get() {\n const { A, B, C, D } = this;\n return [A, B, C, D];\n }\n set(A, B, C, D) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n MD5_W[i] = view.getUint32(offset, true);\n // Compression function main loop, 64 rounds\n let { A, B, C, D } = this;\n for (let i = 0; i < 64; i++) {\n let F, g, s;\n if (i < 16) {\n F = Chi(B, C, D);\n g = i;\n s = [7, 12, 17, 22];\n }\n else if (i < 32) {\n F = Chi(D, B, C);\n g = (5 * i + 1) % 16;\n s = [5, 9, 14, 20];\n }\n else if (i < 48) {\n F = B ^ C ^ D;\n g = (3 * i + 5) % 16;\n s = [4, 11, 16, 23];\n }\n else {\n F = C ^ (B | ~D);\n g = (7 * i) % 16;\n s = [6, 10, 15, 21];\n }\n F = F + A + K[i] + MD5_W[g];\n A = D;\n D = C;\n C = B;\n B = B + rotl(F, s[i % 4]);\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n this.set(A, B, C, D);\n }\n roundClean() {\n clean(MD5_W);\n }\n destroy() {\n this.set(0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/**\n * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.\n * MD5 architecture is similar to SHA1, with some differences:\n * - Reduced output length: 16 bytes (128 bit) instead of 20\n * - 64 rounds, instead of 80\n * - Little-endian: could be faster, but will require more code\n * - Non-linear index selection: huge speed-up for unroll\n * - Per round constants: more memory accesses, additional speed-up for unroll\n */\nexport const md5 = /* @__PURE__ */ createHasher(() => new _MD5());\n// RIPEMD-160\nconst Rho160 = /* @__PURE__ */ Uint8Array.from([\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n]);\nconst Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();\nconst Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();\nconst idxLR = /* @__PURE__ */ (() => {\n const L = [Id160];\n const R = [Pi160];\n const res = [L, R];\n for (let i = 0; i < 4; i++)\n for (let j of res)\n j.push(j[i].map((k) => Rho160[k]));\n return res;\n})();\nconst idxL = /* @__PURE__ */ (() => idxLR[0])();\nconst idxR = /* @__PURE__ */ (() => idxLR[1])();\n// const [idxL, idxR] = idxLR;\nconst shifts160 = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => Uint8Array.from(i));\nconst shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst Kl160 = /* @__PURE__ */ Uint32Array.from([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\nconst Kr160 = /* @__PURE__ */ Uint32Array.from([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// It's called f() in spec.\nfunction ripemd_f(group, x, y, z) {\n if (group === 0)\n return x ^ y ^ z;\n if (group === 1)\n return (x & y) | (~x & z);\n if (group === 2)\n return (x | ~y) ^ z;\n if (group === 3)\n return (x & z) | (y & ~z);\n return x ^ (y | ~z);\n}\n// Reusable temporary buffer\nconst BUF_160 = /* @__PURE__ */ new Uint32Array(16);\nexport class _RIPEMD160 extends HashMD {\n h0 = 0x67452301 | 0;\n h1 = 0xefcdab89 | 0;\n h2 = 0x98badcfe | 0;\n h3 = 0x10325476 | 0;\n h4 = 0xc3d2e1f0 | 0;\n constructor() {\n super(64, 20, 8, true);\n }\n get() {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n set(h0, h1, h2, h3, h4) {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n BUF_160[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0);\n }\n roundClean() {\n clean(BUF_160);\n }\n destroy() {\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0);\n }\n}\n/**\n * RIPEMD-160 - a legacy hash function from 1990s.\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf\n */\nexport const ripemd160 = /* @__PURE__ */ createHasher(() => new _RIPEMD160());\n//# sourceMappingURL=legacy.js.map","/**\n * The single validator that mints {@link OnChainBtcPubkey}.\n *\n * Extracted from `ViemVaultRegistryReader.getVaultProviderGenesisBtcPubKey` so that\n * RFC-006 operation-key resolution can produce branded keys through exactly\n * the same checks, rather than casting past the brand. Every producer of an\n * `OnChainBtcPubkey` must go through here.\n */\n\nimport type { Hex } from \"viem\";\n\nimport type { OnChainBtcPubkey } from \"./types\";\n\n/** secp256k1's base-field prime, `2^256 - 2^32 - 977`. */\nconst SECP256K1_FIELD_PRIME =\n 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn;\n\n/** secp256k1's curve coefficient `b`, from `y^2 = x^3 + b`. */\nconst SECP256K1_CURVE_B = 7n;\n\n/** Modular exponentiation without a crypto-library dependency. */\nfunction modPow(base: bigint, exponent: bigint, modulus: bigint): bigint {\n let result = 1n;\n let factor = base % modulus;\n let remaining = exponent;\n\n while (remaining > 0n) {\n if ((remaining & 1n) === 1n) {\n result = (result * factor) % modulus;\n }\n factor = (factor * factor) % modulus;\n remaining >>= 1n;\n }\n\n return result;\n}\n\n/**\n * secp256k1's field prime is congruent to 3 mod 4, so an x-coordinate is on\n * the curve iff `(x^3 + 7)^((p + 1) / 4)` squares back to `x^3 + 7` modulo\n * p. This is the same curve-membership condition used by x-only key parsers;\n * it deliberately does not merely validate length/range.\n * `x^3 + 7` cannot be zero because `-7` is not a cubic residue in this field,\n * so the zero square-root edge case is unreachable.\n */\nfunction isSecp256k1XCoordinate(value: string): boolean {\n const x = BigInt(`0x${value}`);\n if (x >= SECP256K1_FIELD_PRIME) return false;\n\n const xCubed =\n (((x * x) % SECP256K1_FIELD_PRIME) * x) % SECP256K1_FIELD_PRIME;\n const curveValue = (xCubed + SECP256K1_CURVE_B) % SECP256K1_FIELD_PRIME;\n const y = modPow(\n curveValue,\n (SECP256K1_FIELD_PRIME + 1n) >> 2n,\n SECP256K1_FIELD_PRIME,\n );\n\n return (y * y) % SECP256K1_FIELD_PRIME === curveValue;\n}\n\n/**\n * Validate a registry-returned `bytes32` as an x-only BTC pubkey and mint the\n * brand. Checks length, hex form, and secp256k1 curve membership. Returns\n * 64-char lowercase hex without the `0x` prefix.\n *\n * `label` identifies the read site in error messages (e.g.\n * `getOperationBtcKeyAtEpoch (vp=0x…, epoch=0)`), so a failure names which\n * participant and which getter produced it.\n *\n * A zero hash fails the curve check, so an unregistered operator or an epoch\n * with no bonded key surfaces as an error rather than a silent all-zero key.\n */\nexport function assertOnChainBtcPubkey(\n value: Hex,\n label: string,\n): OnChainBtcPubkey {\n const lowered = value.toLowerCase();\n if (!/^0x[0-9a-f]{64}$/.test(lowered)) {\n throw new Error(\n `${label} returned an unexpected value (length ${lowered.length}, prefix \"${lowered.slice(0, 2)}\")`,\n );\n }\n const stripped = lowered.slice(2);\n if (!isSecp256k1XCoordinate(stripped)) {\n throw new Error(\n `${label} returned a value that is not on the secp256k1 curve`,\n );\n }\n return stripped as OnChainBtcPubkey;\n}\n","import { schnorr, secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { ripemd160 } from \"@noble/hashes/legacy.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, hexToBytes } from \"@noble/hashes/utils.js\";\nimport type { Hex } from \"viem\";\n\nimport { MAX_PAYOUT_SCRIPT_LEN } from \"../../primitives/psbt/constants\";\nimport { assertOnChainBtcPubkey } from \"./onChainBtcPubkey\";\n\nconst P2TR_SCRIPT_PREFIX = \"5120\";\nconst P2WPKH_SCRIPT_PREFIX = \"0014\";\nconst HASH160_BYTES = 20;\nconst COMPRESSED_PUBKEY_BYTES = 33;\nconst UNCOMPRESSED_PUBKEY_BYTES = 65;\nconst SEC1_EVEN_Y_PREFIX = 0x02;\nconst SEC1_ODD_Y_PREFIX = 0x03;\nconst SEC1_UNCOMPRESSED_PREFIX = 0x04;\n\nfunction normalizeHex(value: string, label: string): Hex {\n const body =\n value.startsWith(\"0x\") || value.startsWith(\"0X\") ? value.slice(2) : value;\n if (!/^(?:[0-9a-fA-F]{2})+$/.test(body)) {\n throw new Error(`${label} must be non-empty, even-length hex`);\n }\n return `0x${body.toLowerCase()}`;\n}\n\n/**\n * The BIP-86 key-path P2TR scriptPubKey of an x-only key (bare lowercase\n * hex): the internal key tweaked with no script tree, matching Rust\n * `Bip86KeyConnector` (btc-vault `connectors/mod.rs:237-268` @ ac4954e7).\n *\n * @internal\n */\nexport function deriveP2trScript(xOnlyPubkey: string): Hex {\n const pubkeyBytes = hexToBytes(xOnlyPubkey);\n const internalKey = schnorr.utils.lift_x(BigInt(`0x${xOnlyPubkey}`));\n const tweak = schnorr.utils.bytesToNumberBE(\n schnorr.utils.taggedHash(\"TapTweak\", pubkeyBytes),\n );\n if (tweak >= secp256k1.CURVE.n) {\n throw new Error(\"Proof of possession BTC pubkey has an invalid TapTweak\");\n }\n const outputKey =\n tweak === 0n\n ? internalKey\n : internalKey.add(schnorr.Point.BASE.multiply(tweak));\n return `0x${P2TR_SCRIPT_PREFIX}${bytesToHex(\n schnorr.utils.pointToBytes(outputKey),\n )}`;\n}\n\nfunction normalizePayoutPubkey(value: string): {\n xOnlyPubkey: string;\n compressedPubkey?: Uint8Array;\n} {\n const normalized = normalizeHex(value, \"depositorBtcPubkeyRaw\");\n const pubkey = hexToBytes(normalized.slice(2));\n if (pubkey.length === 32) {\n return {\n xOnlyPubkey: assertOnChainBtcPubkey(normalized, \"Payout BTC pubkey\"),\n };\n }\n const isCompressed =\n pubkey.length === COMPRESSED_PUBKEY_BYTES &&\n (pubkey[0] === SEC1_EVEN_Y_PREFIX || pubkey[0] === SEC1_ODD_Y_PREFIX);\n const isUncompressed =\n pubkey.length === UNCOMPRESSED_PUBKEY_BYTES &&\n pubkey[0] === SEC1_UNCOMPRESSED_PREFIX;\n if (!isCompressed && !isUncompressed) {\n throw new Error(\n \"depositorBtcPubkeyRaw must be x-only, compressed, or uncompressed\",\n );\n }\n try {\n secp256k1.Point.fromBytes(pubkey);\n } catch {\n throw new Error(\"depositorBtcPubkeyRaw is not a valid BTC pubkey\");\n }\n return {\n xOnlyPubkey: bytesToHex(pubkey.subarray(1, COMPRESSED_PUBKEY_BYTES)),\n compressedPubkey: isCompressed ? pubkey : undefined,\n };\n}\n\nfunction deriveP2wpkhScript(pubkey: Uint8Array): Hex {\n return `0x${P2WPKH_SCRIPT_PREFIX}${bytesToHex(ripemd160(sha256(pubkey)))}`;\n}\n\n/** Verify the irreversible payout script at the final submission boundary. */\nexport function assertPayoutScriptMatchesPopKey(\n scriptPubKey: string,\n depositorBtcPubkey: string,\n depositorBtcPubkeyRaw: string,\n): Hex {\n const payoutScript = normalizeHex(\n scriptPubKey,\n \"depositorPayoutScriptPubKey\",\n );\n if ((payoutScript.length - 2) / 2 > MAX_PAYOUT_SCRIPT_LEN) {\n throw new Error(\n `depositorPayoutScriptPubKey exceeds ${MAX_PAYOUT_SCRIPT_LEN} bytes`,\n );\n }\n const keyBody =\n depositorBtcPubkey.startsWith(\"0x\") || depositorBtcPubkey.startsWith(\"0X\")\n ? depositorBtcPubkey.slice(2)\n : depositorBtcPubkey;\n const xOnlyPubkey = assertOnChainBtcPubkey(\n `0x${keyBody}` as Hex,\n \"Proof of possession BTC pubkey\",\n );\n const payoutPubkey = normalizePayoutPubkey(depositorBtcPubkeyRaw);\n if (payoutPubkey.xOnlyPubkey !== xOnlyPubkey) {\n throw new Error(\n \"depositorBtcPubkeyRaw does not match the proof of possession BTC pubkey\",\n );\n }\n\n if (payoutScript === deriveP2trScript(xOnlyPubkey)) {\n return payoutScript;\n }\n if (\n payoutScript.startsWith(`0x${P2WPKH_SCRIPT_PREFIX}`) &&\n payoutScript.length ===\n 2 + P2WPKH_SCRIPT_PREFIX.length + HASH160_BYTES * 2\n ) {\n if (!payoutPubkey.compressedPubkey) {\n throw new Error(\"A P2WPKH payout requires a compressed BTC pubkey\");\n }\n if (payoutScript === deriveP2wpkhScript(payoutPubkey.compressedPubkey)) {\n return payoutScript;\n }\n }\n throw new Error(\n \"depositorPayoutScriptPubKey does not match the proof of possession BTC pubkey\",\n );\n}\n","/**\n * Dependency-free Bitcoin txid and vault-ID helpers for Ethereum-only clients.\n * Transaction hex and vault-ID inputs accept an optional `0x` prefix.\n * Depositor addresses use strict EIP-55 validation.\n * Txids use a `0x` prefix. Vault IDs use no prefix. Both use lowercase hex.\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport {\n encodeAbiParameters,\n isAddress,\n keccak256,\n type Address,\n type Hex,\n} from \"viem\";\n\n/** Decode an optional-prefixed, even-length hex string. */\nfunction decodeHex(value: string, label: string): Uint8Array {\n const clean = value.startsWith(\"0x\") ? value.slice(2) : value;\n if (clean.length === 0 || clean.length % 2 !== 0) {\n throw new Error(`${label} must be non-empty, even-length hex`);\n }\n if (!/^[0-9a-fA-F]+$/.test(clean)) {\n throw new Error(`${label} contains non-hex characters`);\n }\n\n const bytes = new Uint8Array(clean.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = Number.parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\n/** Encode bytes as lowercase hex without a prefix. */\nfunction encodeHex(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\n \"\",\n );\n}\n\n/** Concatenate byte chunks without a buffer dependency. */\nfunction concatBytes(chunks: readonly Uint8Array[]): Uint8Array {\n const result = new Uint8Array(\n chunks.reduce((length, chunk) => length + chunk.length, 0),\n );\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.length;\n }\n return result;\n}\n\n/**\n * Parse enough of Bitcoin's consensus transaction encoding to serialize the\n * no-witness form used for txid calculation. Every length is bounds-checked;\n * malformed/trailing data is rejected rather than hashed as an opaque blob.\n */\nfunction serializeWithoutWitness(transaction: Uint8Array): Uint8Array {\n let offset = 0;\n\n const take = (length: number, label: string): Uint8Array => {\n if (!Number.isSafeInteger(length) || length < 0) {\n throw new Error(`Invalid ${label} length ${length}`);\n }\n if (offset + length > transaction.length) {\n throw new Error(`Truncated Bitcoin transaction while reading ${label}`);\n }\n const value = transaction.slice(offset, offset + length);\n offset += length;\n return value;\n };\n\n const readLittleEndian = (length: number, label: string): bigint => {\n const bytes = take(length, label);\n let value = 0n;\n for (let i = bytes.length - 1; i >= 0; i--) {\n value = (value << 8n) | BigInt(bytes[i]);\n }\n return value;\n };\n\n const readCompactSize = (\n label: string,\n ): { encoded: Uint8Array; value: number } => {\n const start = offset;\n const prefix = take(1, label)[0];\n let value: bigint;\n if (prefix < 0xfd) {\n value = BigInt(prefix);\n } else if (prefix === 0xfd) {\n value = readLittleEndian(2, label);\n if (value < 0xfdn) throw new Error(`Non-canonical ${label}`);\n } else if (prefix === 0xfe) {\n value = readLittleEndian(4, label);\n if (value <= 0xffffn) throw new Error(`Non-canonical ${label}`);\n } else {\n value = readLittleEndian(8, label);\n if (value <= 0xffffffffn) throw new Error(`Non-canonical ${label}`);\n }\n if (value > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new Error(`${label} exceeds JavaScript's safe integer range`);\n }\n return {\n encoded: transaction.slice(start, offset),\n value: Number(value),\n };\n };\n\n const version = take(4, \"version\");\n const hasWitness =\n transaction[offset] === 0x00 && transaction[offset + 1] === 0x01;\n if (hasWitness) offset += 2;\n\n const inputCount = readCompactSize(\"input count\");\n const inputs: Uint8Array[] = [];\n for (let i = 0; i < inputCount.value; i++) {\n const start = offset;\n take(32, `input ${i} previous transaction hash`);\n take(4, `input ${i} previous output index`);\n const scriptLength = readCompactSize(`input ${i} script length`);\n take(scriptLength.value, `input ${i} script`);\n take(4, `input ${i} sequence`);\n inputs.push(transaction.slice(start, offset));\n }\n\n const outputCount = readCompactSize(\"output count\");\n const outputs: Uint8Array[] = [];\n for (let i = 0; i < outputCount.value; i++) {\n const start = offset;\n take(8, `output ${i} value`);\n const scriptLength = readCompactSize(`output ${i} script length`);\n take(scriptLength.value, `output ${i} script`);\n outputs.push(transaction.slice(start, offset));\n }\n\n if (hasWitness) {\n let hasWitnessData = false;\n for (let i = 0; i < inputCount.value; i++) {\n const itemCount = readCompactSize(`input ${i} witness item count`);\n hasWitnessData ||= itemCount.value > 0;\n for (let j = 0; j < itemCount.value; j++) {\n const itemLength = readCompactSize(\n `input ${i} witness item ${j} length`,\n );\n take(itemLength.value, `input ${i} witness item ${j}`);\n }\n }\n if (!hasWitnessData) {\n throw new Error(\"Bitcoin transaction has superfluous witness marker\");\n }\n }\n\n const locktime = take(4, \"locktime\");\n if (offset !== transaction.length) {\n throw new Error(\n `Bitcoin transaction has ${transaction.length - offset} trailing byte(s)`,\n );\n }\n\n return concatBytes([\n version,\n inputCount.encoded,\n ...inputs,\n outputCount.encoded,\n ...outputs,\n locktime,\n ]);\n}\n\n/** Calculate a Bitcoin txid without importing bitcoinjs-lib. */\nexport function calculateBtcTxHash(transactionHex: string): Hex {\n const serialized = serializeWithoutWitness(\n decodeHex(transactionHex, \"transactionHex\"),\n );\n const digest = sha256(sha256(serialized));\n digest.reverse();\n return `0x${encodeHex(digest)}`;\n}\n\n/**\n * Derive the Solidity vault ID without loading the Rust/WASM package.\n *\n * Inputs accept an optional `0x` prefix to match the current PeginManager\n * call sites. Address validation stays strict: lowercase and valid EIP-55\n * addresses pass, while uppercase and incorrectly checksummed mixed-case\n * addresses fail. The synchronous result is lowercase hex without a prefix,\n * matching the WASM helper that this function replaces.\n */\nexport function derivePeginVaultId(\n peginTxHash: string,\n depositor: string,\n): string {\n const normalizedPeginTxHash = peginTxHash.startsWith(\"0x\")\n ? peginTxHash\n : `0x${peginTxHash}`;\n if (!/^0x[0-9a-fA-F]{64}$/.test(normalizedPeginTxHash)) {\n throw new Error(\"peginTxHash must be a 32-byte hex value\");\n }\n const normalizedDepositor = depositor.startsWith(\"0x\")\n ? depositor\n : `0x${depositor}`;\n if (!isAddress(normalizedDepositor, { strict: true })) {\n throw new Error(`Invalid depositor Ethereum address: ${depositor}`);\n }\n return keccak256(\n encodeAbiParameters(\n [{ type: \"bytes32\" }, { type: \"address\" }],\n [normalizedPeginTxHash as Hex, normalizedDepositor as Address],\n ),\n ).slice(2);\n}\n","/**\n * Typed absence of a vault's `VaultClaimableBy` log for a claimer key.\n *\n * Distinct from a transport failure: the scan covered the whole range and\n * found nothing. That is what a not-yet-redeemed vault looks like, and it is\n * also what a load-balanced public node that lacks the block answers, so a\n * caller that knows the vault is redeemed may retry. Name-matchable across\n * module instances like `RegistrationLogsUnavailableError`.\n *\n * @module clients/eth/claimable-event-error\n */\n\nimport type { Hex } from \"viem\";\n\n/** The `name` this error carries, so a foreign module instance still matches. */\nexport const VAULT_CLAIMABLE_BY_NOT_FOUND_ERROR_NAME =\n \"VaultClaimableByNotFoundError\";\n\n/** @experimental */\nexport class VaultClaimableByNotFoundError extends Error {\n constructor(\n readonly vaultId: Hex,\n readonly claimerPk: Hex,\n readonly fromBlock: bigint,\n readonly toBlock: bigint,\n detail = \"the vault has not been redeemed for this key, or the node did not serve the block. Redeem first, or try again.\",\n options?: ErrorOptions,\n ) {\n super(\n `No VaultClaimableBy log for vault ${vaultId} and claimer ${claimerPk} in blocks ` +\n `${fromBlock}..${toBlock}: ${detail}`,\n options,\n );\n this.name = VAULT_CLAIMABLE_BY_NOT_FOUND_ERROR_NAME;\n }\n}\n\n/** Matches `instanceof` OR the documented `name` (dual module instances). @experimental */\nexport function isVaultClaimableByNotFoundError(\n err: unknown,\n): err is VaultClaimableByNotFoundError {\n if (err instanceof VaultClaimableByNotFoundError) return true;\n if (typeof err !== \"object\" || err === null) return false;\n return (\n (err as { name?: unknown }).name === VAULT_CLAIMABLE_BY_NOT_FOUND_ERROR_NAME\n );\n}\n","/**\n * Validation for protocol parameters fetched from the ProtocolParams contract.\n *\n * These values feed Bitcoin script construction and deposit validation.\n * Invalid params must be caught before they reach transaction-building code,\n * since errors after wallet signing prompts are unrecoverable.\n *\n * The {@link ViemProtocolParamsReader} runs these on every read; consumers\n * implementing their own reader against the same `ProtocolParamsReader`\n * interface should call them too.\n */\n\nimport { assertValidVaultCoreVersion } from \"../../primitives/vaultCoreVersion\";\n\nimport type {\n PegInConfiguration,\n TBVProtocolParams,\n VersionedOffchainParams,\n} from \"./types\";\n\n/**\n * Maximum value for a Solidity uint16. btc-vault carries the PegIn timelock as\n * a `NonZeroU16` (`transactions/pegin.rs:33` @ ac4954e7).\n */\nconst UINT16_MAX = 65535;\n\n/** Maximum valid value for basis points (100%) */\nconst MAX_BASIS_POINTS = 10000;\n\n/** Maximum value for a Solidity uint32. */\nconst UINT32_MAX = 4_294_967_295;\n\n/** Maximum valid value for a uint8 (e.g. maxHtlcOutputCount). */\nconst UINT8_MAX = 255;\n\n/**\n * Validate an `offchainParamsVersion` value sourced from a contract read.\n * `Number()` on a malformed payload yields `NaN` or a non-integer; both\n * silently break consumers that loop `1..version` or use the value as a\n * map key. Used by reader entry points that surface the version to JS.\n */\nexport function assertValidOffchainParamsVersion(version: number): void {\n if (\n !Number.isInteger(version) ||\n version < 0 ||\n version > UINT32_MAX\n ) {\n throw new Error(\n `Invalid offchainParamsVersion from contract: must be a uint32, got ${version}`,\n );\n }\n}\n\n/**\n * Validate offchain params consistency and bounds.\n * @throws Error on invalid values to prevent constructing invalid Bitcoin scripts.\n */\nexport function validateOffchainParams(params: VersionedOffchainParams): void {\n const errors: string[] = [];\n\n if (params.timelockAssert <= 0n) {\n errors.push(\n `timelockAssert must be positive, got ${params.timelockAssert}`,\n );\n }\n if (params.timelockAssert > BigInt(UINT16_MAX)) {\n errors.push(\n `timelockAssert ${params.timelockAssert} exceeds uint16 max (${UINT16_MAX})`,\n );\n }\n\n if (params.timelockChallengeAssert <= 0n) {\n errors.push(\n `timelockChallengeAssert must be positive, got ${params.timelockChallengeAssert}`,\n );\n }\n\n if (params.tRefund <= 0) {\n errors.push(`tRefund must be positive, got ${params.tRefund}`);\n }\n\n if (params.tStale <= 0) {\n errors.push(`tStale must be positive, got ${params.tStale}`);\n }\n\n if (params.securityCouncilKeys.length === 0) {\n errors.push(\"securityCouncilKeys must not be empty\");\n }\n\n if (params.councilQuorum <= 0) {\n errors.push(`councilQuorum must be positive, got ${params.councilQuorum}`);\n }\n if (params.councilQuorum > params.securityCouncilKeys.length) {\n errors.push(\n `councilQuorum (${params.councilQuorum}) exceeds securityCouncilKeys count (${params.securityCouncilKeys.length})`,\n );\n }\n\n if (params.feeRate <= 0n) {\n errors.push(`feeRate must be positive, got ${params.feeRate}`);\n }\n\n if (params.minPeginFeeRate <= 0n) {\n errors.push(\n `minPeginFeeRate must be positive, got ${params.minPeginFeeRate}`,\n );\n }\n\n if (\n !Number.isInteger(params.proverCircuitVersion) ||\n params.proverCircuitVersion < 0 ||\n params.proverCircuitVersion > UINT16_MAX\n ) {\n errors.push(\n `proverCircuitVersion must be a uint16, got ${params.proverCircuitVersion}`,\n );\n }\n\n if (\n !Number.isInteger(params.minPrepeginDepth) ||\n params.minPrepeginDepth <= 0 ||\n params.minPrepeginDepth > UINT32_MAX\n ) {\n errors.push(\n `minPrepeginDepth must be a uint32 in [1, ${UINT32_MAX}], got ${params.minPrepeginDepth}`,\n );\n }\n\n if (params.babeTotalInstances <= 0) {\n errors.push(\n `babeTotalInstances must be positive, got ${params.babeTotalInstances}`,\n );\n }\n if (params.babeInstancesToFinalize <= 0) {\n errors.push(\n `babeInstancesToFinalize must be positive, got ${params.babeInstancesToFinalize}`,\n );\n }\n if (params.babeInstancesToFinalize > params.babeTotalInstances) {\n errors.push(\n `babeInstancesToFinalize (${params.babeInstancesToFinalize}) exceeds babeTotalInstances (${params.babeTotalInstances})`,\n );\n }\n\n if (\n params.minVpCommissionBps < 0 ||\n params.minVpCommissionBps > MAX_BASIS_POINTS\n ) {\n errors.push(\n `minVpCommissionBps must be in [0, ${MAX_BASIS_POINTS}], got ${params.minVpCommissionBps}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(\n `Invalid offchain protocol parameters: ${errors.join(\"; \")}`,\n );\n }\n}\n\n/**\n * Validate TBV protocol params returned from the contract.\n * @throws Error on invalid amounts or out-of-range bounded fields.\n */\nexport function validateTBVProtocolParams(params: TBVProtocolParams): void {\n const errors: string[] = [];\n\n if (params.minimumPegInAmount <= 0n) {\n errors.push(\n `minimumPegInAmount must be positive, got ${params.minimumPegInAmount}`,\n );\n }\n\n if (params.maxPegInAmount < params.minimumPegInAmount) {\n errors.push(\n `maxPegInAmount (${params.maxPegInAmount}) must be >= minimumPegInAmount (${params.minimumPegInAmount})`,\n );\n }\n\n if (params.pegInAckTimeout <= 0n) {\n errors.push(\n `pegInAckTimeout must be positive, got ${params.pegInAckTimeout}`,\n );\n }\n\n if (params.pegInActivationTimeout <= 0n) {\n errors.push(\n `pegInActivationTimeout must be positive, got ${params.pegInActivationTimeout}`,\n );\n }\n\n if (\n !Number.isInteger(params.maxHtlcOutputCount) ||\n params.maxHtlcOutputCount <= 0 ||\n params.maxHtlcOutputCount > UINT8_MAX\n ) {\n errors.push(\n `maxHtlcOutputCount must be an integer in [1, ${UINT8_MAX}], got ${params.maxHtlcOutputCount}`,\n );\n }\n\n if (\n typeof params.expiredPegInGraceBlocks !== \"bigint\" ||\n params.expiredPegInGraceBlocks <= 0n\n ) {\n errors.push(\n `expiredPegInGraceBlocks must be a positive bigint, got ${params.expiredPegInGraceBlocks}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(`Invalid TBV protocol parameters: ${errors.join(\"; \")}`);\n }\n}\n\n/**\n * Validate the full peg-in configuration after assembly.\n * Checks both TBV params and offchain params consistency, and the\n * top-level `offchainParamsVersion` (which originates from a separate\n * multicall result and so must be range-checked alongside the params it\n * names).\n */\nexport function validatePegInConfiguration(config: PegInConfiguration): void {\n validateTBVProtocolParams(config);\n validateOffchainParams(config.offchainParams);\n\n if (\n !Number.isInteger(config.offchainParamsVersion) ||\n config.offchainParamsVersion < 0 ||\n config.offchainParamsVersion > UINT32_MAX\n ) {\n throw new Error(\n `Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${config.offchainParamsVersion}`,\n );\n }\n\n // The contract enforces ≥ 1 (setter rejects 0); a 0 here means a\n // mis-decoded read or a pre-vaultCoreVersion contract — fail closed.\n assertValidVaultCoreVersion(\n config.activeVaultCoreVersion,\n \"ProtocolParams.activeVaultCoreVersion()\",\n );\n}\n","/**\n * Transient failure of a registration-log read.\n *\n * Every registered vault has its `PegInSubmitted` log in its `createdAt`\n * block, so an Ethereum node answering that block's registration-log query\n * with no logs at all did not serve the block — load-balanced public RPCs\n * answer `[]` for a block a backend lacks instead of erroring, which viem's\n * transport retry cannot see (it retries errors only). Callers may retry.\n *\n * The same holds for an answer that is merely incomplete: the registry emits\n * `PegInSubmitted` and `PegInSubmittedV2` together on every submission\n * (vault-contracts-aave-v4 `PeginLogic.sol:144-147` @ c559f5c2), so a block\n * answer carrying only some of them is a partial answer as readily as it is\n * an old registry. Those shapes carry their own message.\n *\n * @module clients/eth/registration-logs-error\n */\n\n/** The `name` this error carries, so a foreign module instance still matches. */\nexport const REGISTRATION_LOGS_UNAVAILABLE_ERROR_NAME =\n \"RegistrationLogsUnavailableError\";\n\nexport class RegistrationLogsUnavailableError extends Error {\n readonly blockNumber: bigint;\n\n /**\n * `message` replaces the empty-answer wording for the partial-answer shapes\n * that are not \"no logs at all\"; the caller names which logs it did get.\n */\n constructor(blockNumber: bigint, message?: string) {\n super(\n message ??\n `The Ethereum node returned no registration logs for block ${blockNumber}, ` +\n `which holds a vault registration; the node may not have indexed that ` +\n `block yet. Try again.`,\n );\n this.name = REGISTRATION_LOGS_UNAVAILABLE_ERROR_NAME;\n this.blockNumber = blockNumber;\n }\n}\n\n/** Matches `instanceof` OR the documented `name` (dual module instances). */\nexport function isRegistrationLogsUnavailableError(\n err: unknown,\n): err is RegistrationLogsUnavailableError {\n if (err instanceof RegistrationLogsUnavailableError) return true;\n if (typeof err !== \"object\" || err === null) return false;\n return (\n (err as { name?: unknown }).name ===\n REGISTRATION_LOGS_UNAVAILABLE_ERROR_NAME\n );\n}\n","/**\n * Pure helpers over {@link PeginRegistrationRecord}.\n *\n * The reader decodes a whole block leniently; the strict per-record checks\n * live here and run only on the records a caller selects, so a stranger's\n * malformed registration in the same block cannot fail an unrelated read (the\n * vault app's deposit resume reads its commission ceiling through the same\n * block). That leniency stops at duplicates: a vault registers once, so two\n * logs for any vault id are an inconsistent node and the reader fails the\n * whole block's read closed by design.\n *\n * @module clients/eth/registration-records\n */\n\nimport type { Hex } from \"viem\";\n\nimport { MAX_PAYOUT_SCRIPT_LEN } from \"../../primitives/psbt/constants\";\nimport { calculateBtcTxHash } from \"./pegin-transaction\";\nimport { RegistrationLogsUnavailableError } from \"./registration-logs-error\";\nimport type { PeginRegistrationRecord } from \"./types\";\n\nconst HEX_PREFIX_LEN = 2;\n\n/**\n * The record of `vaultId` among a block's registrations.\n *\n * @throws {RegistrationLogsUnavailableError} (transient, retry) when the\n * block's registration logs do not include the vault: the registry emits a\n * `PegInSubmittedV2` on every submission, so an answer without the target's\n * is as readily a node's partial answer as a vault registered elsewhere.\n * @experimental\n */\nexport function findRegistrationRecord(\n records: readonly PeginRegistrationRecord[],\n vaultId: Hex,\n createdAt: bigint,\n): PeginRegistrationRecord {\n const wanted = vaultId.toLowerCase();\n const record = records.find((r) => r.vaultId === wanted);\n if (record === undefined) {\n // Both shapes are emitted together on every submission\n // (vault-contracts-aave-v4 `PeginLogic.sol:144-147` @ c559f5c2).\n throw new RegistrationLogsUnavailableError(\n createdAt,\n `Vault ${vaultId} has no PegInSubmittedV2 registration log at its on-chain registration ` +\n `block ${createdAt}: either the node served a partial answer for block ${createdAt} ` +\n `(retry, preferably another node) or the vault was not registered in this block`,\n );\n }\n return record;\n}\n\n/**\n * Txid of the record's `unsignedPrePeginTx`, `0x`-prefixed display order —\n * what the vault record stores as `prePeginTxHash`.\n *\n * @throws When the log's transaction does not parse.\n * @experimental\n */\nexport function registrationPrePeginTxHash(\n record: PeginRegistrationRecord,\n): Hex {\n return calculateBtcTxHash(record.unsignedPrePeginTx);\n}\n\n/**\n * The bound `assertPayoutScriptMatchesPopKey` enforces before a registration\n * is submitted (payout-script.ts); a log outside it is not a script the SDK\n * ever registered.\n *\n * @experimental\n */\nexport function assertRegisteredPayoutScriptBounds(\n record: PeginRegistrationRecord,\n): void {\n const bytes =\n (record.depositorPayoutScriptPubKey.length - HEX_PREFIX_LEN) / 2;\n if (bytes === 0 || bytes > MAX_PAYOUT_SCRIPT_LEN) {\n throw new Error(\n `PegInSubmittedV2 log for vault ${record.vaultId} carries a ${bytes}-byte ` +\n `depositorPayoutBtcAddress; expected 1..${MAX_PAYOUT_SCRIPT_LEN} bytes`,\n );\n }\n}\n"],"names":["Rho160","Id160","_","i","Pi160","idxLR","res","j","k","idxL","idxR","shifts160","shiftsL160","idx","shiftsR160","Kl160","Kr160","ripemd_f","group","x","y","z","BUF_160","_RIPEMD160","HashMD","__publicField","h0","h1","h2","h3","h4","view","offset","al","ar","bl","br","cl","cr","dl","dr","el","er","rGroup","hbl","hbr","rl","rr","sl","sr","tl","rotl","tr","clean","ripemd160","createHasher","SECP256K1_FIELD_PRIME","SECP256K1_CURVE_B","modPow","base","exponent","modulus","result","factor","remaining","isSecp256k1XCoordinate","value","curveValue","assertOnChainBtcPubkey","label","lowered","stripped","P2TR_SCRIPT_PREFIX","P2WPKH_SCRIPT_PREFIX","HASH160_BYTES","COMPRESSED_PUBKEY_BYTES","UNCOMPRESSED_PUBKEY_BYTES","SEC1_EVEN_Y_PREFIX","SEC1_ODD_Y_PREFIX","SEC1_UNCOMPRESSED_PREFIX","normalizeHex","body","deriveP2trScript","xOnlyPubkey","pubkeyBytes","hexToBytes","internalKey","schnorr","tweak","secp256k1","outputKey","bytesToHex","normalizePayoutPubkey","normalized","pubkey","isCompressed","isUncompressed","deriveP2wpkhScript","sha256","assertPayoutScriptMatchesPopKey","scriptPubKey","depositorBtcPubkey","depositorBtcPubkeyRaw","payoutScript","MAX_PAYOUT_SCRIPT_LEN","keyBody","payoutPubkey","decodeHex","bytes","encodeHex","byte","concatBytes","chunks","length","chunk","serializeWithoutWitness","transaction","take","readLittleEndian","readCompactSize","start","prefix","version","hasWitness","inputCount","inputs","scriptLength","outputCount","outputs","hasWitnessData","itemCount","itemLength","locktime","calculateBtcTxHash","transactionHex","serialized","digest","derivePeginVaultId","peginTxHash","depositor","normalizedPeginTxHash","normalizedDepositor","isAddress","keccak256","encodeAbiParameters","VAULT_CLAIMABLE_BY_NOT_FOUND_ERROR_NAME","VaultClaimableByNotFoundError","vaultId","claimerPk","fromBlock","toBlock","detail","options","isVaultClaimableByNotFoundError","err","UINT16_MAX","MAX_BASIS_POINTS","UINT32_MAX","UINT8_MAX","assertValidOffchainParamsVersion","validateOffchainParams","params","errors","validateTBVProtocolParams","validatePegInConfiguration","config","assertValidVaultCoreVersion","REGISTRATION_LOGS_UNAVAILABLE_ERROR_NAME","RegistrationLogsUnavailableError","blockNumber","message","isRegistrationLogsUnavailableError","HEX_PREFIX_LEN","findRegistrationRecord","records","createdAt","wanted","record","r","registrationPrePeginTxHash","assertRegisteredPayoutScriptBounds"],"mappings":";;;;;;;AA8KA,MAAMA,KAAyB,2BAAW,KAAK;AAAA,EAC3C;AAAA,EAAG;AAAA,EAAG;AAAA,EAAI;AAAA,EAAG;AAAA,EAAI;AAAA,EAAG;AAAA,EAAI;AAAA,EAAG;AAAA,EAAI;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAI;AAAA,EAAI;AACvD,CAAC,GACKC,IAA+B,WAAW,KAAK,IAAI,MAAM,EAAE,EAAE,KAAK,CAAC,EAAE,IAAI,CAACC,GAAGC,MAAMA,CAAC,CAAC,GACrFC,KAA+BH,EAAM,IAAI,CAACE,OAAO,IAAIA,IAAI,KAAK,EAAE,GAChEE,IAAyB,uBAAM;AAGjC,QAAMC,IAAM,CAFF,CAACL,CAAK,GACN,CAACG,EAAK,CACC;AACjB,WAASD,IAAI,GAAGA,IAAI,GAAGA;AACnB,aAASI,KAAKD;AACV,MAAAC,EAAE,KAAKA,EAAEJ,CAAC,EAAE,IAAI,CAACK,MAAMR,GAAOQ,CAAC,CAAC,CAAC;AACzC,SAAOF;AACX,GAAC,GACKG,IAA8BJ,EAAM,CAAC,GACrCK,IAA8BL,EAAM,CAAC,GAErCM,IAA4B;AAAA,EAC9B,CAAC,IAAI,IAAI,IAAI,IAAI,GAAG,GAAG,GAAG,GAAG,IAAI,IAAI,IAAI,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AAA;AAGvE;","x_google_ignoreList":[0]}
1
+ {"version":3,"file":"registration-records-BBOz21Dm.js","sources":["../../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/legacy.js","../src/tbv/core/clients/eth/onChainBtcPubkey.ts","../src/tbv/core/clients/eth/payout-script.ts","../src/tbv/core/clients/eth/pegin-transaction.ts","../src/tbv/core/clients/eth/claimable-event-error.ts","../src/tbv/core/clients/eth/protocol-params-validation.ts","../src/tbv/core/clients/eth/registration-logs-error.ts","../src/tbv/core/clients/eth/registration-records.ts"],"sourcesContent":["/**\n\nSHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions.\nDon't use them in a new protocol. What \"weak\" means:\n\n- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.\n- No practical pre-image attacks (only theoretical, 2^123.4)\n- HMAC seems kinda ok: https://www.rfc-editor.org/rfc/rfc6151\n * @module\n */\nimport { Chi, HashMD, Maj } from \"./_md.js\";\nimport { clean, createHasher, rotl } from \"./utils.js\";\n/** Initial SHA1 state */\nconst SHA1_IV = /* @__PURE__ */ Uint32Array.from([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n// Reusable temporary buffer\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA1 legacy hash class. */\nexport class _SHA1 extends HashMD {\n A = SHA1_IV[0] | 0;\n B = SHA1_IV[1] | 0;\n C = SHA1_IV[2] | 0;\n D = SHA1_IV[3] | 0;\n E = SHA1_IV[4] | 0;\n constructor() {\n super(64, 20, 8, false);\n }\n get() {\n const { A, B, C, D, E } = this;\n return [A, B, C, D, E];\n }\n set(A, B, C, D, E) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n SHA1_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 80; i++)\n SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n // Compression function main loop, 80 rounds\n let { A, B, C, D, E } = this;\n for (let i = 0; i < 80; i++) {\n let F, K;\n if (i < 20) {\n F = Chi(B, C, D);\n K = 0x5a827999;\n }\n else if (i < 40) {\n F = B ^ C ^ D;\n K = 0x6ed9eba1;\n }\n else if (i < 60) {\n F = Maj(B, C, D);\n K = 0x8f1bbcdc;\n }\n else {\n F = B ^ C ^ D;\n K = 0xca62c1d6;\n }\n const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n E = D;\n D = C;\n C = rotl(B, 30);\n B = A;\n A = T;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n this.set(A, B, C, D, E);\n }\n roundClean() {\n clean(SHA1_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. */\nexport const sha1 = /* @__PURE__ */ createHasher(() => new _SHA1());\n/** Per-round constants */\nconst p32 = /* @__PURE__ */ Math.pow(2, 32);\nconst K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) => Math.floor(p32 * Math.abs(Math.sin(i + 1))));\n/** md5 initial state: same as sha1, but 4 u32 instead of 5. */\nconst MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);\n// Reusable temporary buffer\nconst MD5_W = /* @__PURE__ */ new Uint32Array(16);\n/** Internal MD5 legacy hash class. */\nexport class _MD5 extends HashMD {\n A = MD5_IV[0] | 0;\n B = MD5_IV[1] | 0;\n C = MD5_IV[2] | 0;\n D = MD5_IV[3] | 0;\n constructor() {\n super(64, 16, 8, true);\n }\n get() {\n const { A, B, C, D } = this;\n return [A, B, C, D];\n }\n set(A, B, C, D) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n MD5_W[i] = view.getUint32(offset, true);\n // Compression function main loop, 64 rounds\n let { A, B, C, D } = this;\n for (let i = 0; i < 64; i++) {\n let F, g, s;\n if (i < 16) {\n F = Chi(B, C, D);\n g = i;\n s = [7, 12, 17, 22];\n }\n else if (i < 32) {\n F = Chi(D, B, C);\n g = (5 * i + 1) % 16;\n s = [5, 9, 14, 20];\n }\n else if (i < 48) {\n F = B ^ C ^ D;\n g = (3 * i + 5) % 16;\n s = [4, 11, 16, 23];\n }\n else {\n F = C ^ (B | ~D);\n g = (7 * i) % 16;\n s = [6, 10, 15, 21];\n }\n F = F + A + K[i] + MD5_W[g];\n A = D;\n D = C;\n C = B;\n B = B + rotl(F, s[i % 4]);\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n this.set(A, B, C, D);\n }\n roundClean() {\n clean(MD5_W);\n }\n destroy() {\n this.set(0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/**\n * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.\n * MD5 architecture is similar to SHA1, with some differences:\n * - Reduced output length: 16 bytes (128 bit) instead of 20\n * - 64 rounds, instead of 80\n * - Little-endian: could be faster, but will require more code\n * - Non-linear index selection: huge speed-up for unroll\n * - Per round constants: more memory accesses, additional speed-up for unroll\n */\nexport const md5 = /* @__PURE__ */ createHasher(() => new _MD5());\n// RIPEMD-160\nconst Rho160 = /* @__PURE__ */ Uint8Array.from([\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n]);\nconst Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();\nconst Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();\nconst idxLR = /* @__PURE__ */ (() => {\n const L = [Id160];\n const R = [Pi160];\n const res = [L, R];\n for (let i = 0; i < 4; i++)\n for (let j of res)\n j.push(j[i].map((k) => Rho160[k]));\n return res;\n})();\nconst idxL = /* @__PURE__ */ (() => idxLR[0])();\nconst idxR = /* @__PURE__ */ (() => idxLR[1])();\n// const [idxL, idxR] = idxLR;\nconst shifts160 = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => Uint8Array.from(i));\nconst shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst Kl160 = /* @__PURE__ */ Uint32Array.from([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\nconst Kr160 = /* @__PURE__ */ Uint32Array.from([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// It's called f() in spec.\nfunction ripemd_f(group, x, y, z) {\n if (group === 0)\n return x ^ y ^ z;\n if (group === 1)\n return (x & y) | (~x & z);\n if (group === 2)\n return (x | ~y) ^ z;\n if (group === 3)\n return (x & z) | (y & ~z);\n return x ^ (y | ~z);\n}\n// Reusable temporary buffer\nconst BUF_160 = /* @__PURE__ */ new Uint32Array(16);\nexport class _RIPEMD160 extends HashMD {\n h0 = 0x67452301 | 0;\n h1 = 0xefcdab89 | 0;\n h2 = 0x98badcfe | 0;\n h3 = 0x10325476 | 0;\n h4 = 0xc3d2e1f0 | 0;\n constructor() {\n super(64, 20, 8, true);\n }\n get() {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n set(h0, h1, h2, h3, h4) {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n BUF_160[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0);\n }\n roundClean() {\n clean(BUF_160);\n }\n destroy() {\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0);\n }\n}\n/**\n * RIPEMD-160 - a legacy hash function from 1990s.\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf\n */\nexport const ripemd160 = /* @__PURE__ */ createHasher(() => new _RIPEMD160());\n//# sourceMappingURL=legacy.js.map","/**\n * The single validator that mints {@link OnChainBtcPubkey}.\n *\n * Extracted from `ViemVaultRegistryReader.getVaultProviderGenesisBtcPubKey` so that\n * RFC-006 operation-key resolution can produce branded keys through exactly\n * the same checks, rather than casting past the brand. Every producer of an\n * `OnChainBtcPubkey` must go through here.\n */\n\nimport type { Hex } from \"viem\";\n\nimport type { OnChainBtcPubkey } from \"./types\";\n\n/** secp256k1's base-field prime, `2^256 - 2^32 - 977`. */\nconst SECP256K1_FIELD_PRIME =\n 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn;\n\n/** secp256k1's curve coefficient `b`, from `y^2 = x^3 + b`. */\nconst SECP256K1_CURVE_B = 7n;\n\n/** Modular exponentiation without a crypto-library dependency. */\nfunction modPow(base: bigint, exponent: bigint, modulus: bigint): bigint {\n let result = 1n;\n let factor = base % modulus;\n let remaining = exponent;\n\n while (remaining > 0n) {\n if ((remaining & 1n) === 1n) {\n result = (result * factor) % modulus;\n }\n factor = (factor * factor) % modulus;\n remaining >>= 1n;\n }\n\n return result;\n}\n\n/**\n * secp256k1's field prime is congruent to 3 mod 4, so an x-coordinate is on\n * the curve iff `(x^3 + 7)^((p + 1) / 4)` squares back to `x^3 + 7` modulo\n * p. This is the same curve-membership condition used by x-only key parsers;\n * it deliberately does not merely validate length/range.\n * `x^3 + 7` cannot be zero because `-7` is not a cubic residue in this field,\n * so the zero square-root edge case is unreachable.\n */\nfunction isSecp256k1XCoordinate(value: string): boolean {\n const x = BigInt(`0x${value}`);\n if (x >= SECP256K1_FIELD_PRIME) return false;\n\n const xCubed =\n (((x * x) % SECP256K1_FIELD_PRIME) * x) % SECP256K1_FIELD_PRIME;\n const curveValue = (xCubed + SECP256K1_CURVE_B) % SECP256K1_FIELD_PRIME;\n const y = modPow(\n curveValue,\n (SECP256K1_FIELD_PRIME + 1n) >> 2n,\n SECP256K1_FIELD_PRIME,\n );\n\n return (y * y) % SECP256K1_FIELD_PRIME === curveValue;\n}\n\n/**\n * Validate a registry-returned `bytes32` as an x-only BTC pubkey and mint the\n * brand. Checks length, hex form, and secp256k1 curve membership. Returns\n * 64-char lowercase hex without the `0x` prefix.\n *\n * `label` identifies the read site in error messages (e.g.\n * `getOperationBtcKeyAtEpoch (vp=0x…, epoch=0)`), so a failure names which\n * participant and which getter produced it.\n *\n * A zero hash fails the curve check, so an unregistered operator or an epoch\n * with no bonded key surfaces as an error rather than a silent all-zero key.\n */\nexport function assertOnChainBtcPubkey(\n value: Hex,\n label: string,\n): OnChainBtcPubkey {\n const lowered = value.toLowerCase();\n if (!/^0x[0-9a-f]{64}$/.test(lowered)) {\n throw new Error(\n `${label} returned an unexpected value (length ${lowered.length}, prefix \"${lowered.slice(0, 2)}\")`,\n );\n }\n const stripped = lowered.slice(2);\n if (!isSecp256k1XCoordinate(stripped)) {\n throw new Error(\n `${label} returned a value that is not on the secp256k1 curve`,\n );\n }\n return stripped as OnChainBtcPubkey;\n}\n","import { schnorr, secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { ripemd160 } from \"@noble/hashes/legacy.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, hexToBytes } from \"@noble/hashes/utils.js\";\nimport type { Hex } from \"viem\";\n\nimport { MAX_PAYOUT_SCRIPT_LEN } from \"../../primitives/psbt/constants\";\nimport { assertOnChainBtcPubkey } from \"./onChainBtcPubkey\";\n\nconst P2TR_SCRIPT_PREFIX = \"5120\";\nconst P2WPKH_SCRIPT_PREFIX = \"0014\";\nconst HASH160_BYTES = 20;\nconst COMPRESSED_PUBKEY_BYTES = 33;\nconst UNCOMPRESSED_PUBKEY_BYTES = 65;\nconst SEC1_EVEN_Y_PREFIX = 0x02;\nconst SEC1_ODD_Y_PREFIX = 0x03;\nconst SEC1_UNCOMPRESSED_PREFIX = 0x04;\n\nfunction normalizeHex(value: string, label: string): Hex {\n const body =\n value.startsWith(\"0x\") || value.startsWith(\"0X\") ? value.slice(2) : value;\n if (!/^(?:[0-9a-fA-F]{2})+$/.test(body)) {\n throw new Error(`${label} must be non-empty, even-length hex`);\n }\n return `0x${body.toLowerCase()}`;\n}\n\n/**\n * The BIP-86 key-path P2TR scriptPubKey of an x-only key (bare lowercase\n * hex): the internal key tweaked with no script tree, matching Rust\n * `Bip86KeyConnector` (btc-vault `connectors/mod.rs:237-268` @ ac4954e7).\n *\n * @internal\n */\nexport function deriveP2trScript(xOnlyPubkey: string): Hex {\n const pubkeyBytes = hexToBytes(xOnlyPubkey);\n const internalKey = schnorr.utils.lift_x(BigInt(`0x${xOnlyPubkey}`));\n const tweak = schnorr.utils.bytesToNumberBE(\n schnorr.utils.taggedHash(\"TapTweak\", pubkeyBytes),\n );\n if (tweak >= secp256k1.CURVE.n) {\n throw new Error(\"Proof of possession BTC pubkey has an invalid TapTweak\");\n }\n const outputKey =\n tweak === 0n\n ? internalKey\n : internalKey.add(schnorr.Point.BASE.multiply(tweak));\n return `0x${P2TR_SCRIPT_PREFIX}${bytesToHex(\n schnorr.utils.pointToBytes(outputKey),\n )}`;\n}\n\nfunction normalizePayoutPubkey(value: string): {\n xOnlyPubkey: string;\n compressedPubkey?: Uint8Array;\n} {\n const normalized = normalizeHex(value, \"depositorBtcPubkeyRaw\");\n const pubkey = hexToBytes(normalized.slice(2));\n if (pubkey.length === 32) {\n return {\n xOnlyPubkey: assertOnChainBtcPubkey(normalized, \"Payout BTC pubkey\"),\n };\n }\n const isCompressed =\n pubkey.length === COMPRESSED_PUBKEY_BYTES &&\n (pubkey[0] === SEC1_EVEN_Y_PREFIX || pubkey[0] === SEC1_ODD_Y_PREFIX);\n const isUncompressed =\n pubkey.length === UNCOMPRESSED_PUBKEY_BYTES &&\n pubkey[0] === SEC1_UNCOMPRESSED_PREFIX;\n if (!isCompressed && !isUncompressed) {\n throw new Error(\n \"depositorBtcPubkeyRaw must be x-only, compressed, or uncompressed\",\n );\n }\n try {\n secp256k1.Point.fromBytes(pubkey);\n } catch {\n throw new Error(\"depositorBtcPubkeyRaw is not a valid BTC pubkey\");\n }\n return {\n xOnlyPubkey: bytesToHex(pubkey.subarray(1, COMPRESSED_PUBKEY_BYTES)),\n compressedPubkey: isCompressed ? pubkey : undefined,\n };\n}\n\nfunction deriveP2wpkhScript(pubkey: Uint8Array): Hex {\n return `0x${P2WPKH_SCRIPT_PREFIX}${bytesToHex(ripemd160(sha256(pubkey)))}`;\n}\n\n/** Verify the irreversible payout script at the final submission boundary. */\nexport function assertPayoutScriptMatchesPopKey(\n scriptPubKey: string,\n depositorBtcPubkey: string,\n depositorBtcPubkeyRaw: string,\n): Hex {\n const payoutScript = normalizeHex(\n scriptPubKey,\n \"depositorPayoutScriptPubKey\",\n );\n if ((payoutScript.length - 2) / 2 > MAX_PAYOUT_SCRIPT_LEN) {\n throw new Error(\n `depositorPayoutScriptPubKey exceeds ${MAX_PAYOUT_SCRIPT_LEN} bytes`,\n );\n }\n const keyBody =\n depositorBtcPubkey.startsWith(\"0x\") || depositorBtcPubkey.startsWith(\"0X\")\n ? depositorBtcPubkey.slice(2)\n : depositorBtcPubkey;\n const xOnlyPubkey = assertOnChainBtcPubkey(\n `0x${keyBody}` as Hex,\n \"Proof of possession BTC pubkey\",\n );\n const payoutPubkey = normalizePayoutPubkey(depositorBtcPubkeyRaw);\n if (payoutPubkey.xOnlyPubkey !== xOnlyPubkey) {\n throw new Error(\n \"depositorBtcPubkeyRaw does not match the proof of possession BTC pubkey\",\n );\n }\n\n if (payoutScript === deriveP2trScript(xOnlyPubkey)) {\n return payoutScript;\n }\n if (\n payoutScript.startsWith(`0x${P2WPKH_SCRIPT_PREFIX}`) &&\n payoutScript.length ===\n 2 + P2WPKH_SCRIPT_PREFIX.length + HASH160_BYTES * 2\n ) {\n if (!payoutPubkey.compressedPubkey) {\n throw new Error(\"A P2WPKH payout requires a compressed BTC pubkey\");\n }\n if (payoutScript === deriveP2wpkhScript(payoutPubkey.compressedPubkey)) {\n return payoutScript;\n }\n }\n throw new Error(\n \"depositorPayoutScriptPubKey does not match the proof of possession BTC pubkey\",\n );\n}\n","/**\n * Dependency-free Bitcoin txid and vault-ID helpers for Ethereum-only clients.\n * Transaction hex and vault-ID inputs accept an optional `0x` prefix.\n * Depositor addresses use strict EIP-55 validation.\n * Txids use a `0x` prefix. Vault IDs use no prefix. Both use lowercase hex.\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport {\n encodeAbiParameters,\n isAddress,\n keccak256,\n type Address,\n type Hex,\n} from \"viem\";\n\n/** Decode an optional-prefixed, even-length hex string. */\nfunction decodeHex(value: string, label: string): Uint8Array {\n const clean = value.startsWith(\"0x\") ? value.slice(2) : value;\n if (clean.length === 0 || clean.length % 2 !== 0) {\n throw new Error(`${label} must be non-empty, even-length hex`);\n }\n if (!/^[0-9a-fA-F]+$/.test(clean)) {\n throw new Error(`${label} contains non-hex characters`);\n }\n\n const bytes = new Uint8Array(clean.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = Number.parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\n/** Encode bytes as lowercase hex without a prefix. */\nfunction encodeHex(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\n \"\",\n );\n}\n\n/** Concatenate byte chunks without a buffer dependency. */\nfunction concatBytes(chunks: readonly Uint8Array[]): Uint8Array {\n const result = new Uint8Array(\n chunks.reduce((length, chunk) => length + chunk.length, 0),\n );\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.length;\n }\n return result;\n}\n\n/**\n * Parse enough of Bitcoin's consensus transaction encoding to serialize the\n * no-witness form used for txid calculation. Every length is bounds-checked;\n * malformed/trailing data is rejected rather than hashed as an opaque blob.\n */\nfunction serializeWithoutWitness(transaction: Uint8Array): Uint8Array {\n let offset = 0;\n\n const take = (length: number, label: string): Uint8Array => {\n if (!Number.isSafeInteger(length) || length < 0) {\n throw new Error(`Invalid ${label} length ${length}`);\n }\n if (offset + length > transaction.length) {\n throw new Error(`Truncated Bitcoin transaction while reading ${label}`);\n }\n const value = transaction.slice(offset, offset + length);\n offset += length;\n return value;\n };\n\n const readLittleEndian = (length: number, label: string): bigint => {\n const bytes = take(length, label);\n let value = 0n;\n for (let i = bytes.length - 1; i >= 0; i--) {\n value = (value << 8n) | BigInt(bytes[i]);\n }\n return value;\n };\n\n const readCompactSize = (\n label: string,\n ): { encoded: Uint8Array; value: number } => {\n const start = offset;\n const prefix = take(1, label)[0];\n let value: bigint;\n if (prefix < 0xfd) {\n value = BigInt(prefix);\n } else if (prefix === 0xfd) {\n value = readLittleEndian(2, label);\n if (value < 0xfdn) throw new Error(`Non-canonical ${label}`);\n } else if (prefix === 0xfe) {\n value = readLittleEndian(4, label);\n if (value <= 0xffffn) throw new Error(`Non-canonical ${label}`);\n } else {\n value = readLittleEndian(8, label);\n if (value <= 0xffffffffn) throw new Error(`Non-canonical ${label}`);\n }\n if (value > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new Error(`${label} exceeds JavaScript's safe integer range`);\n }\n return {\n encoded: transaction.slice(start, offset),\n value: Number(value),\n };\n };\n\n const version = take(4, \"version\");\n const hasWitness =\n transaction[offset] === 0x00 && transaction[offset + 1] === 0x01;\n if (hasWitness) offset += 2;\n\n const inputCount = readCompactSize(\"input count\");\n const inputs: Uint8Array[] = [];\n for (let i = 0; i < inputCount.value; i++) {\n const start = offset;\n take(32, `input ${i} previous transaction hash`);\n take(4, `input ${i} previous output index`);\n const scriptLength = readCompactSize(`input ${i} script length`);\n take(scriptLength.value, `input ${i} script`);\n take(4, `input ${i} sequence`);\n inputs.push(transaction.slice(start, offset));\n }\n\n const outputCount = readCompactSize(\"output count\");\n const outputs: Uint8Array[] = [];\n for (let i = 0; i < outputCount.value; i++) {\n const start = offset;\n take(8, `output ${i} value`);\n const scriptLength = readCompactSize(`output ${i} script length`);\n take(scriptLength.value, `output ${i} script`);\n outputs.push(transaction.slice(start, offset));\n }\n\n if (hasWitness) {\n let hasWitnessData = false;\n for (let i = 0; i < inputCount.value; i++) {\n const itemCount = readCompactSize(`input ${i} witness item count`);\n hasWitnessData ||= itemCount.value > 0;\n for (let j = 0; j < itemCount.value; j++) {\n const itemLength = readCompactSize(\n `input ${i} witness item ${j} length`,\n );\n take(itemLength.value, `input ${i} witness item ${j}`);\n }\n }\n if (!hasWitnessData) {\n throw new Error(\"Bitcoin transaction has superfluous witness marker\");\n }\n }\n\n const locktime = take(4, \"locktime\");\n if (offset !== transaction.length) {\n throw new Error(\n `Bitcoin transaction has ${transaction.length - offset} trailing byte(s)`,\n );\n }\n\n return concatBytes([\n version,\n inputCount.encoded,\n ...inputs,\n outputCount.encoded,\n ...outputs,\n locktime,\n ]);\n}\n\n/** Calculate a Bitcoin txid without importing bitcoinjs-lib. */\nexport function calculateBtcTxHash(transactionHex: string): Hex {\n const serialized = serializeWithoutWitness(\n decodeHex(transactionHex, \"transactionHex\"),\n );\n const digest = sha256(sha256(serialized));\n digest.reverse();\n return `0x${encodeHex(digest)}`;\n}\n\n/**\n * Derive the Solidity vault ID without loading the Rust/WASM package.\n *\n * Inputs accept an optional `0x` prefix to match the current PeginManager\n * call sites. Address validation stays strict: lowercase and valid EIP-55\n * addresses pass, while uppercase and incorrectly checksummed mixed-case\n * addresses fail. The synchronous result is lowercase hex without a prefix,\n * matching the WASM helper that this function replaces.\n */\nexport function derivePeginVaultId(\n peginTxHash: string,\n depositor: string,\n): string {\n const normalizedPeginTxHash = peginTxHash.startsWith(\"0x\")\n ? peginTxHash\n : `0x${peginTxHash}`;\n if (!/^0x[0-9a-fA-F]{64}$/.test(normalizedPeginTxHash)) {\n throw new Error(\"peginTxHash must be a 32-byte hex value\");\n }\n const normalizedDepositor = depositor.startsWith(\"0x\")\n ? depositor\n : `0x${depositor}`;\n if (!isAddress(normalizedDepositor, { strict: true })) {\n throw new Error(`Invalid depositor Ethereum address: ${depositor}`);\n }\n return keccak256(\n encodeAbiParameters(\n [{ type: \"bytes32\" }, { type: \"address\" }],\n [normalizedPeginTxHash as Hex, normalizedDepositor as Address],\n ),\n ).slice(2);\n}\n","/**\n * Typed absence of a vault's `VaultClaimableBy` log for a claimer key.\n *\n * Distinct from a transport failure: the scan covered the whole range and\n * found nothing. That is what a not-yet-redeemed vault looks like, and it is\n * also what a load-balanced public node that lacks the block answers, so a\n * caller that knows the vault is redeemed may retry. Name-matchable across\n * module instances like `RegistrationLogsUnavailableError`.\n *\n * @module clients/eth/claimable-event-error\n */\n\nimport type { Hex } from \"viem\";\n\n/** The `name` this error carries, so a foreign module instance still matches. */\nexport const VAULT_CLAIMABLE_BY_NOT_FOUND_ERROR_NAME =\n \"VaultClaimableByNotFoundError\";\n\n/** @experimental */\nexport class VaultClaimableByNotFoundError extends Error {\n constructor(\n readonly vaultId: Hex,\n readonly claimerPk: Hex,\n readonly fromBlock: bigint,\n readonly toBlock: bigint,\n detail = \"the vault has not been redeemed for this key, or the node did not serve the block. Redeem first, or try again.\",\n options?: ErrorOptions,\n ) {\n super(\n `No VaultClaimableBy log for vault ${vaultId} and claimer ${claimerPk} in blocks ` +\n `${fromBlock}..${toBlock}: ${detail}`,\n options,\n );\n this.name = VAULT_CLAIMABLE_BY_NOT_FOUND_ERROR_NAME;\n }\n}\n\n/** Matches `instanceof` OR the documented `name` (dual module instances). @experimental */\nexport function isVaultClaimableByNotFoundError(\n err: unknown,\n): err is VaultClaimableByNotFoundError {\n if (err instanceof VaultClaimableByNotFoundError) return true;\n if (typeof err !== \"object\" || err === null) return false;\n return (\n (err as { name?: unknown }).name === VAULT_CLAIMABLE_BY_NOT_FOUND_ERROR_NAME\n );\n}\n","/**\n * Validation for protocol parameters fetched from the ProtocolParams contract.\n *\n * These values feed Bitcoin script construction and deposit validation.\n * Invalid params must be caught before they reach transaction-building code,\n * since errors after wallet signing prompts are unrecoverable.\n *\n * The {@link ViemProtocolParamsReader} runs these on every read; consumers\n * implementing their own reader against the same `ProtocolParamsReader`\n * interface should call them too.\n */\n\nimport { assertValidVaultCoreVersion } from \"../../primitives/vaultCoreVersion\";\n\nimport type {\n PegInConfiguration,\n TBVProtocolParams,\n VersionedOffchainParams,\n} from \"./types\";\n\n/**\n * Maximum value for a Solidity uint16. btc-vault carries the PegIn timelock as\n * a `NonZeroU16` (`transactions/pegin.rs:33` @ ac4954e7).\n */\nconst UINT16_MAX = 65535;\n\n/** Maximum valid value for basis points (100%) */\nconst MAX_BASIS_POINTS = 10000;\n\n/** Maximum value for a Solidity uint32. */\nconst UINT32_MAX = 4_294_967_295;\n\n/** Maximum valid value for a uint8 (e.g. maxHtlcOutputCount). */\nconst UINT8_MAX = 255;\n\n/**\n * Validate an `offchainParamsVersion` value sourced from a contract read.\n * `Number()` on a malformed payload yields `NaN` or a non-integer; both\n * silently break consumers that loop `1..version` or use the value as a\n * map key. Used by reader entry points that surface the version to JS.\n */\nexport function assertValidOffchainParamsVersion(version: number): void {\n if (\n !Number.isInteger(version) ||\n version < 0 ||\n version > UINT32_MAX\n ) {\n throw new Error(\n `Invalid offchainParamsVersion from contract: must be a uint32, got ${version}`,\n );\n }\n}\n\n/**\n * Validate offchain params consistency and bounds.\n * @throws Error on invalid values to prevent constructing invalid Bitcoin scripts.\n */\nexport function validateOffchainParams(params: VersionedOffchainParams): void {\n const errors: string[] = [];\n\n if (params.timelockAssert <= 0n) {\n errors.push(\n `timelockAssert must be positive, got ${params.timelockAssert}`,\n );\n }\n if (params.timelockAssert > BigInt(UINT16_MAX)) {\n errors.push(\n `timelockAssert ${params.timelockAssert} exceeds uint16 max (${UINT16_MAX})`,\n );\n }\n\n if (params.timelockChallengeAssert <= 0n) {\n errors.push(\n `timelockChallengeAssert must be positive, got ${params.timelockChallengeAssert}`,\n );\n }\n\n if (params.tRefund <= 0) {\n errors.push(`tRefund must be positive, got ${params.tRefund}`);\n }\n\n if (params.tStale <= 0) {\n errors.push(`tStale must be positive, got ${params.tStale}`);\n }\n\n if (params.securityCouncilKeys.length === 0) {\n errors.push(\"securityCouncilKeys must not be empty\");\n }\n\n if (params.councilQuorum <= 0) {\n errors.push(`councilQuorum must be positive, got ${params.councilQuorum}`);\n }\n if (params.councilQuorum > params.securityCouncilKeys.length) {\n errors.push(\n `councilQuorum (${params.councilQuorum}) exceeds securityCouncilKeys count (${params.securityCouncilKeys.length})`,\n );\n }\n\n if (params.feeRate <= 0n) {\n errors.push(`feeRate must be positive, got ${params.feeRate}`);\n }\n\n if (params.minPeginFeeRate <= 0n) {\n errors.push(\n `minPeginFeeRate must be positive, got ${params.minPeginFeeRate}`,\n );\n }\n\n if (\n !Number.isInteger(params.proverCircuitVersion) ||\n params.proverCircuitVersion < 0 ||\n params.proverCircuitVersion > UINT16_MAX\n ) {\n errors.push(\n `proverCircuitVersion must be a uint16, got ${params.proverCircuitVersion}`,\n );\n }\n\n if (\n !Number.isInteger(params.minPrepeginDepth) ||\n params.minPrepeginDepth <= 0 ||\n params.minPrepeginDepth > UINT32_MAX\n ) {\n errors.push(\n `minPrepeginDepth must be a uint32 in [1, ${UINT32_MAX}], got ${params.minPrepeginDepth}`,\n );\n }\n\n if (params.babeTotalInstances <= 0) {\n errors.push(\n `babeTotalInstances must be positive, got ${params.babeTotalInstances}`,\n );\n }\n if (params.babeInstancesToFinalize <= 0) {\n errors.push(\n `babeInstancesToFinalize must be positive, got ${params.babeInstancesToFinalize}`,\n );\n }\n if (params.babeInstancesToFinalize > params.babeTotalInstances) {\n errors.push(\n `babeInstancesToFinalize (${params.babeInstancesToFinalize}) exceeds babeTotalInstances (${params.babeTotalInstances})`,\n );\n }\n\n if (\n params.minVpCommissionBps < 0 ||\n params.minVpCommissionBps > MAX_BASIS_POINTS\n ) {\n errors.push(\n `minVpCommissionBps must be in [0, ${MAX_BASIS_POINTS}], got ${params.minVpCommissionBps}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(\n `Invalid offchain protocol parameters: ${errors.join(\"; \")}`,\n );\n }\n}\n\n/**\n * Validate TBV protocol params returned from the contract.\n * @throws Error on invalid amounts or out-of-range bounded fields.\n */\nexport function validateTBVProtocolParams(params: TBVProtocolParams): void {\n const errors: string[] = [];\n\n if (params.minimumPegInAmount <= 0n) {\n errors.push(\n `minimumPegInAmount must be positive, got ${params.minimumPegInAmount}`,\n );\n }\n\n if (params.maxPegInAmount < params.minimumPegInAmount) {\n errors.push(\n `maxPegInAmount (${params.maxPegInAmount}) must be >= minimumPegInAmount (${params.minimumPegInAmount})`,\n );\n }\n\n if (params.pegInAckTimeout <= 0n) {\n errors.push(\n `pegInAckTimeout must be positive, got ${params.pegInAckTimeout}`,\n );\n }\n\n if (params.pegInActivationTimeout <= 0n) {\n errors.push(\n `pegInActivationTimeout must be positive, got ${params.pegInActivationTimeout}`,\n );\n }\n\n if (\n !Number.isInteger(params.maxHtlcOutputCount) ||\n params.maxHtlcOutputCount <= 0 ||\n params.maxHtlcOutputCount > UINT8_MAX\n ) {\n errors.push(\n `maxHtlcOutputCount must be an integer in [1, ${UINT8_MAX}], got ${params.maxHtlcOutputCount}`,\n );\n }\n\n if (\n typeof params.expiredPegInGraceBlocks !== \"bigint\" ||\n params.expiredPegInGraceBlocks <= 0n\n ) {\n errors.push(\n `expiredPegInGraceBlocks must be a positive bigint, got ${params.expiredPegInGraceBlocks}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(`Invalid TBV protocol parameters: ${errors.join(\"; \")}`);\n }\n}\n\n/**\n * Validate the full peg-in configuration after assembly.\n * Checks both TBV params and offchain params consistency, and the\n * top-level `offchainParamsVersion` (which originates from a separate\n * multicall result and so must be range-checked alongside the params it\n * names).\n */\nexport function validatePegInConfiguration(config: PegInConfiguration): void {\n validateTBVProtocolParams(config);\n validateOffchainParams(config.offchainParams);\n\n if (\n !Number.isInteger(config.offchainParamsVersion) ||\n config.offchainParamsVersion < 0 ||\n config.offchainParamsVersion > UINT32_MAX\n ) {\n throw new Error(\n `Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${config.offchainParamsVersion}`,\n );\n }\n\n // The contract enforces ≥ 1 (setter rejects 0); a 0 here means a\n // mis-decoded read or a pre-vaultCoreVersion contract — fail closed.\n assertValidVaultCoreVersion(\n config.activeVaultCoreVersion,\n \"ProtocolParams.activeVaultCoreVersion()\",\n );\n}\n","/**\n * Transient failure of a registration-log read.\n *\n * Every registered vault has its `PegInSubmitted` log in its `createdAt`\n * block, so an Ethereum node answering that block's registration-log query\n * with no logs at all did not serve the block — load-balanced public RPCs\n * answer `[]` for a block a backend lacks instead of erroring, which viem's\n * transport retry cannot see (it retries errors only). Callers may retry.\n *\n * The same holds for an answer that is merely incomplete: the registry emits\n * `PegInSubmitted` and `PegInSubmittedV2` together on every submission\n * (vault-contracts-aave-v4 `PeginLogic.sol:144-147` @ c559f5c2), so a block\n * answer carrying only some of them is a partial answer as readily as it is\n * an old registry. Those shapes carry their own message.\n *\n * @module clients/eth/registration-logs-error\n */\n\n/** The `name` this error carries, so a foreign module instance still matches. */\nexport const REGISTRATION_LOGS_UNAVAILABLE_ERROR_NAME =\n \"RegistrationLogsUnavailableError\";\n\nexport class RegistrationLogsUnavailableError extends Error {\n readonly blockNumber: bigint;\n\n /**\n * `message` replaces the empty-answer wording for the partial-answer shapes\n * that are not \"no logs at all\"; the caller names which logs it did get.\n */\n constructor(blockNumber: bigint, message?: string) {\n super(\n message ??\n `The Ethereum node returned no registration logs for block ${blockNumber}, ` +\n `which holds a vault registration; the node may not have indexed that ` +\n `block yet. Try again.`,\n );\n this.name = REGISTRATION_LOGS_UNAVAILABLE_ERROR_NAME;\n this.blockNumber = blockNumber;\n }\n}\n\n/** Matches `instanceof` OR the documented `name` (dual module instances). */\nexport function isRegistrationLogsUnavailableError(\n err: unknown,\n): err is RegistrationLogsUnavailableError {\n if (err instanceof RegistrationLogsUnavailableError) return true;\n if (typeof err !== \"object\" || err === null) return false;\n return (\n (err as { name?: unknown }).name ===\n REGISTRATION_LOGS_UNAVAILABLE_ERROR_NAME\n );\n}\n","/**\n * Pure helpers over {@link PeginRegistrationRecord}.\n *\n * The reader decodes a whole block leniently; the strict per-record checks\n * live here and run only on the records a caller selects, so a stranger's\n * malformed registration in the same block cannot fail an unrelated read (the\n * vault app's deposit resume reads its commission ceiling through the same\n * block). That leniency stops at duplicates: a vault registers once, so two\n * logs for any vault id are an inconsistent node and the reader fails the\n * whole block's read closed by design.\n *\n * @module clients/eth/registration-records\n */\n\nimport type { Hex } from \"viem\";\n\nimport { MAX_PAYOUT_SCRIPT_LEN } from \"../../primitives/psbt/constants\";\nimport { calculateBtcTxHash } from \"./pegin-transaction\";\nimport { RegistrationLogsUnavailableError } from \"./registration-logs-error\";\nimport type { PeginRegistrationRecord } from \"./types\";\n\nconst HEX_PREFIX_LEN = 2;\n\n/**\n * The record of `vaultId` among a block's registrations.\n *\n * @throws {RegistrationLogsUnavailableError} (transient, retry) when the\n * block's registration logs do not include the vault: the registry emits a\n * `PegInSubmittedV2` on every submission, so an answer without the target's\n * is as readily a node's partial answer as a vault registered elsewhere.\n * @experimental\n */\nexport function findRegistrationRecord(\n records: readonly PeginRegistrationRecord[],\n vaultId: Hex,\n createdAt: bigint,\n): PeginRegistrationRecord {\n const wanted = vaultId.toLowerCase();\n const record = records.find((r) => r.vaultId === wanted);\n if (record === undefined) {\n // Both shapes are emitted together on every submission\n // (vault-contracts-aave-v4 `PeginLogic.sol:144-147` @ c559f5c2).\n throw new RegistrationLogsUnavailableError(\n createdAt,\n `Vault ${vaultId} has no PegInSubmittedV2 registration log at its on-chain registration ` +\n `block ${createdAt}: either the node served a partial answer for block ${createdAt} ` +\n `(retry, preferably another node) or the vault was not registered in this block`,\n );\n }\n return record;\n}\n\n/**\n * Txid of the record's `unsignedPrePeginTx`, `0x`-prefixed display order —\n * what the vault record stores as `prePeginTxHash`.\n *\n * @throws When the log's transaction does not parse.\n * @experimental\n */\nexport function registrationPrePeginTxHash(\n record: PeginRegistrationRecord,\n): Hex {\n return calculateBtcTxHash(record.unsignedPrePeginTx);\n}\n\n/**\n * The bound `assertPayoutScriptMatchesPopKey` enforces before a registration\n * is submitted (payout-script.ts); a log outside it is not a script the SDK\n * ever registered.\n *\n * @experimental\n */\nexport function assertRegisteredPayoutScriptBounds(\n record: PeginRegistrationRecord,\n): void {\n const bytes =\n (record.depositorPayoutScriptPubKey.length - HEX_PREFIX_LEN) / 2;\n if (bytes === 0 || bytes > MAX_PAYOUT_SCRIPT_LEN) {\n throw new Error(\n `PegInSubmittedV2 log for vault ${record.vaultId} carries a ${bytes}-byte ` +\n `depositorPayoutBtcAddress; expected 1..${MAX_PAYOUT_SCRIPT_LEN} bytes`,\n );\n }\n}\n"],"names":["Rho160","Id160","_","i","Pi160","idxLR","res","j","k","idxL","idxR","shifts160","shiftsL160","idx","shiftsR160","Kl160","Kr160","ripemd_f","group","x","y","z","BUF_160","_RIPEMD160","HashMD","__publicField","h0","h1","h2","h3","h4","view","offset","al","ar","bl","br","cl","cr","dl","dr","el","er","rGroup","hbl","hbr","rl","rr","sl","sr","tl","rotl","tr","clean","ripemd160","createHasher","SECP256K1_FIELD_PRIME","SECP256K1_CURVE_B","modPow","base","exponent","modulus","result","factor","remaining","isSecp256k1XCoordinate","value","curveValue","assertOnChainBtcPubkey","label","lowered","stripped","P2TR_SCRIPT_PREFIX","P2WPKH_SCRIPT_PREFIX","HASH160_BYTES","COMPRESSED_PUBKEY_BYTES","UNCOMPRESSED_PUBKEY_BYTES","SEC1_EVEN_Y_PREFIX","SEC1_ODD_Y_PREFIX","SEC1_UNCOMPRESSED_PREFIX","normalizeHex","body","deriveP2trScript","xOnlyPubkey","pubkeyBytes","hexToBytes","internalKey","schnorr","tweak","secp256k1","outputKey","bytesToHex","normalizePayoutPubkey","normalized","pubkey","isCompressed","isUncompressed","deriveP2wpkhScript","sha256","assertPayoutScriptMatchesPopKey","scriptPubKey","depositorBtcPubkey","depositorBtcPubkeyRaw","payoutScript","MAX_PAYOUT_SCRIPT_LEN","keyBody","payoutPubkey","decodeHex","bytes","encodeHex","byte","concatBytes","chunks","length","chunk","serializeWithoutWitness","transaction","take","readLittleEndian","readCompactSize","start","prefix","version","hasWitness","inputCount","inputs","scriptLength","outputCount","outputs","hasWitnessData","itemCount","itemLength","locktime","calculateBtcTxHash","transactionHex","serialized","digest","derivePeginVaultId","peginTxHash","depositor","normalizedPeginTxHash","normalizedDepositor","isAddress","keccak256","encodeAbiParameters","VAULT_CLAIMABLE_BY_NOT_FOUND_ERROR_NAME","VaultClaimableByNotFoundError","vaultId","claimerPk","fromBlock","toBlock","detail","options","isVaultClaimableByNotFoundError","err","UINT16_MAX","MAX_BASIS_POINTS","UINT32_MAX","UINT8_MAX","assertValidOffchainParamsVersion","validateOffchainParams","params","errors","validateTBVProtocolParams","validatePegInConfiguration","config","assertValidVaultCoreVersion","REGISTRATION_LOGS_UNAVAILABLE_ERROR_NAME","RegistrationLogsUnavailableError","blockNumber","message","isRegistrationLogsUnavailableError","HEX_PREFIX_LEN","findRegistrationRecord","records","createdAt","wanted","record","r","registrationPrePeginTxHash","assertRegisteredPayoutScriptBounds"],"mappings":";;;;;;;AA8KA,MAAMA,KAAyB,2BAAW,KAAK;AAAA,EAC3C;AAAA,EAAG;AAAA,EAAG;AAAA,EAAI;AAAA,EAAG;AAAA,EAAI;AAAA,EAAG;AAAA,EAAI;AAAA,EAAG;AAAA,EAAI;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAG;AAAA,EAAI;AAAA,EAAI;AACvD,CAAC,GACKC,IAA+B,WAAW,KAAK,IAAI,MAAM,EAAE,EAAE,KAAK,CAAC,EAAE,IAAI,CAACC,GAAGC,MAAMA,CAAC,CAAC,GACrFC,KAA+BH,EAAM,IAAI,CAACE,OAAO,IAAIA,IAAI,KAAK,EAAE,GAChEE,IAAyB,uBAAM;AAGjC,QAAMC,IAAM,CAFF,CAACL,CA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MACRO;AAAA,MACA,SAAS5B,CAAO,gFACL4B,CAAS,uDAAuDA,CAAS;AAAA,IAAA;AAIxF,SAAOE;AACT;AASO,SAASE,GACdF,GACK;AACL,SAAO5C,GAAmB4C,EAAO,kBAAkB;AACrD;AASO,SAASG,GACdH,GACM;AACN,QAAMrE,KACHqE,EAAO,4BAA4B,SAASL,MAAkB;AACjE,MAAIhE,MAAU,KAAKA,IAAQJ;AACzB,UAAM,IAAI;AAAA,MACR,kCAAkCyE,EAAO,OAAO,cAAcrE,CAAK,gDACvBJ,CAAqB;AAAA,IAAA;AAGvE;","x_google_ignoreList":[0]}
@@ -1,2 +1,2 @@
1
- "use strict";var tt=Object.defineProperty;var et=(t,e,n)=>e in t?tt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var y=(t,e,n)=>et(t,typeof e!="symbol"?e+"":e,n);const g=require("./secp256k1-DDHQ1_za.cjs"),l=require("./sha2-Ce6KewYx.cjs"),w=require("./constants-BwCg5K6R.cjs"),C=require("viem"),nt=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),N=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),ot=N.map(t=>(9*t+5)%16),U=(()=>{const n=[[N],[ot]];for(let o=0;o<4;o++)for(let i of n)i.push(i[o].map(u=>nt[u]));return n})(),L=U[0],O=U[1],F=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(t=>Uint8Array.from(t)),it=L.map((t,e)=>t.map(n=>F[e][n])),rt=O.map((t,e)=>t.map(n=>F[e][n])),st=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),ut=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function R(t,e,n,o){return t===0?e^n^o:t===1?e&n|~e&o:t===2?(e|~n)^o:t===3?e&o|n&~o:e^(n|~o)}const x=new Uint32Array(16);class ct extends l.HashMD{constructor(){super(64,20,8,!0);y(this,"h0",1732584193);y(this,"h1",-271733879);y(this,"h2",-1732584194);y(this,"h3",271733878);y(this,"h4",-1009589776)}get(){const{h0:n,h1:o,h2:i,h3:u,h4:f}=this;return[n,o,i,u,f]}set(n,o,i,u,f){this.h0=n|0,this.h1=o|0,this.h2=i|0,this.h3=u|0,this.h4=f|0}process(n,o){for(let s=0;s<16;s++,o+=4)x[s]=n.getUint32(o,!0);let i=this.h0|0,u=i,f=this.h1|0,d=f,p=this.h2|0,b=p,m=this.h3|0,E=m,r=this.h4|0,c=r;for(let s=0;s<5;s++){const a=4-s,P=st[s],j=ut[s],q=L[s],Q=O[s],J=it[s],Z=rt[s];for(let h=0;h<16;h++){const v=l.rotl(i+R(s,f,p,m)+x[q[h]]+P,J[h])+r|0;i=r,r=m,m=l.rotl(p,10)|0,p=f,f=v}for(let h=0;h<16;h++){const v=l.rotl(u+R(a,d,b,E)+x[Q[h]]+j,Z[h])+c|0;u=c,c=E,E=l.rotl(b,10)|0,b=d,d=v}}this.set(this.h1+p+E|0,this.h2+m+c|0,this.h3+r+u|0,this.h4+i+d|0,this.h0+f+b|0)}roundClean(){l.clean(x)}destroy(){this.destroyed=!0,l.clean(this.buffer),this.set(0,0,0,0,0)}}const H=l.createHasher(()=>new ct),$=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,at=7n;function ft(t,e,n){let o=1n,i=t%n,u=e;for(;u>0n;)(u&1n)===1n&&(o=o*i%n),i=i*i%n,u>>=1n;return o}function lt(t){const e=BigInt(`0x${t}`);if(e>=$)return!1;const o=(e*e%$*e%$+at)%$,i=ft(o,$+1n>>2n,$);return i*i%$===o}function k(t,e){const n=t.toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(n))throw new Error(`${e} returned an unexpected value (length ${n.length}, prefix "${n.slice(0,2)}")`);const o=n.slice(2);if(!lt(o))throw new Error(`${e} returned a value that is not on the secp256k1 curve`);return o}const ht="5120",A="0014",dt=20,_=33,pt=65,mt=2,gt=3,bt=4;function K(t,e){const n=t.startsWith("0x")||t.startsWith("0X")?t.slice(2):t;if(!/^(?:[0-9a-fA-F]{2})+$/.test(n))throw new Error(`${e} must be non-empty, even-length hex`);return`0x${n.toLowerCase()}`}function M(t){const e=l.hexToBytes(t),n=g.schnorr.utils.lift_x(BigInt(`0x${t}`)),o=g.schnorr.utils.bytesToNumberBE(g.schnorr.utils.taggedHash("TapTweak",e));if(o>=g.secp256k1.CURVE.n)throw new Error("Proof of possession BTC pubkey has an invalid TapTweak");const i=o===0n?n:n.add(g.schnorr.Point.BASE.multiply(o));return`0x${ht}${l.bytesToHex(g.schnorr.utils.pointToBytes(i))}`}function Pt(t){const e=K(t,"depositorBtcPubkeyRaw"),n=l.hexToBytes(e.slice(2));if(n.length===32)return{xOnlyPubkey:k(e,"Payout BTC pubkey")};const o=n.length===_&&(n[0]===mt||n[0]===gt),i=n.length===pt&&n[0]===bt;if(!o&&!i)throw new Error("depositorBtcPubkeyRaw must be x-only, compressed, or uncompressed");try{g.secp256k1.Point.fromBytes(n)}catch{throw new Error("depositorBtcPubkeyRaw is not a valid BTC pubkey")}return{xOnlyPubkey:l.bytesToHex(n.subarray(1,_)),compressedPubkey:o?n:void 0}}function yt(t){return`0x${A}${l.bytesToHex(H(l.sha256(t)))}`}function $t(t,e,n){const o=K(t,"depositorPayoutScriptPubKey");if((o.length-2)/2>w.MAX_PAYOUT_SCRIPT_LEN)throw new Error(`depositorPayoutScriptPubKey exceeds ${w.MAX_PAYOUT_SCRIPT_LEN} bytes`);const i=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e,u=k(`0x${i}`,"Proof of possession BTC pubkey"),f=Pt(n);if(f.xOnlyPubkey!==u)throw new Error("depositorBtcPubkeyRaw does not match the proof of possession BTC pubkey");if(o===M(u))return o;if(o.startsWith(`0x${A}`)&&o.length===2+A.length+dt*2){if(!f.compressedPubkey)throw new Error("A P2WPKH payout requires a compressed BTC pubkey");if(o===yt(f.compressedPubkey))return o}throw new Error("depositorPayoutScriptPubKey does not match the proof of possession BTC pubkey")}function Et(t,e){const n=t.startsWith("0x")?t.slice(2):t;if(n.length===0||n.length%2!==0)throw new Error(`${e} must be non-empty, even-length hex`);if(!/^[0-9a-fA-F]+$/.test(n))throw new Error(`${e} contains non-hex characters`);const o=new Uint8Array(n.length/2);for(let i=0;i<o.length;i++)o[i]=Number.parseInt(n.slice(i*2,i*2+2),16);return o}function xt(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function wt(t){const e=new Uint8Array(t.reduce((o,i)=>o+i.length,0));let n=0;for(const o of t)e.set(o,n),n+=o.length;return e}function It(t){let e=0;const n=(r,c)=>{if(!Number.isSafeInteger(r)||r<0)throw new Error(`Invalid ${c} length ${r}`);if(e+r>t.length)throw new Error(`Truncated Bitcoin transaction while reading ${c}`);const s=t.slice(e,e+r);return e+=r,s},o=(r,c)=>{const s=n(r,c);let a=0n;for(let P=s.length-1;P>=0;P--)a=a<<8n|BigInt(s[P]);return a},i=r=>{const c=e,s=n(1,r)[0];let a;if(s<253)a=BigInt(s);else if(s===253){if(a=o(2,r),a<0xfdn)throw new Error(`Non-canonical ${r}`)}else if(s===254){if(a=o(4,r),a<=0xffffn)throw new Error(`Non-canonical ${r}`)}else if(a=o(8,r),a<=0xffffffffn)throw new Error(`Non-canonical ${r}`);if(a>BigInt(Number.MAX_SAFE_INTEGER))throw new Error(`${r} exceeds JavaScript's safe integer range`);return{encoded:t.slice(c,e),value:Number(a)}},u=n(4,"version"),f=t[e]===0&&t[e+1]===1;f&&(e+=2);const d=i("input count"),p=[];for(let r=0;r<d.value;r++){const c=e;n(32,`input ${r} previous transaction hash`),n(4,`input ${r} previous output index`);const s=i(`input ${r} script length`);n(s.value,`input ${r} script`),n(4,`input ${r} sequence`),p.push(t.slice(c,e))}const b=i("output count"),m=[];for(let r=0;r<b.value;r++){const c=e;n(8,`output ${r} value`);const s=i(`output ${r} script length`);n(s.value,`output ${r} script`),m.push(t.slice(c,e))}if(f){let r=!1;for(let c=0;c<d.value;c++){const s=i(`input ${c} witness item count`);r||(r=s.value>0);for(let a=0;a<s.value;a++){const P=i(`input ${c} witness item ${a} length`);n(P.value,`input ${c} witness item ${a}`)}}if(!r)throw new Error("Bitcoin transaction has superfluous witness marker")}const E=n(4,"locktime");if(e!==t.length)throw new Error(`Bitcoin transaction has ${t.length-e} trailing byte(s)`);return wt([u,d.encoded,...p,b.encoded,...m,E])}function X(t){const e=It(Et(t,"transactionHex")),n=l.sha256(l.sha256(e));return n.reverse(),`0x${xt(n)}`}function vt(t,e){const n=t.startsWith("0x")?t:`0x${t}`;if(!/^0x[0-9a-fA-F]{64}$/.test(n))throw new Error("peginTxHash must be a 32-byte hex value");const o=e.startsWith("0x")?e:`0x${e}`;if(!C.isAddress(o,{strict:!0}))throw new Error(`Invalid depositor Ethereum address: ${e}`);return C.keccak256(C.encodeAbiParameters([{type:"bytes32"},{type:"address"}],[n,o])).slice(2)}const D="VaultClaimableByNotFoundError";class W extends Error{constructor(e,n,o,i,u="the vault has not been redeemed for this key, or the node did not serve the block. Redeem first, or try again.",f){super(`No VaultClaimableBy log for vault ${e} and claimer ${n} in blocks ${o}..${i}: ${u}`,f),this.vaultId=e,this.claimerPk=n,this.fromBlock=o,this.toBlock=i,this.name=D}}function Ct(t){return t instanceof W?!0:typeof t!="object"||t===null?!1:t.name===D}const T=65535,S=1e4,I=4294967295,V=255;function Tt(t){if(!Number.isInteger(t)||t<0||t>I)throw new Error(`Invalid offchainParamsVersion from contract: must be a uint32, got ${t}`)}function Y(t){const e=[];if(t.timelockAssert<=0n&&e.push(`timelockAssert must be positive, got ${t.timelockAssert}`),t.timelockAssert>BigInt(T)&&e.push(`timelockAssert ${t.timelockAssert} exceeds uint16 max (${T})`),t.timelockChallengeAssert<=0n&&e.push(`timelockChallengeAssert must be positive, got ${t.timelockChallengeAssert}`),t.tRefund<=0&&e.push(`tRefund must be positive, got ${t.tRefund}`),t.tStale<=0&&e.push(`tStale must be positive, got ${t.tStale}`),t.securityCouncilKeys.length===0&&e.push("securityCouncilKeys must not be empty"),t.councilQuorum<=0&&e.push(`councilQuorum must be positive, got ${t.councilQuorum}`),t.councilQuorum>t.securityCouncilKeys.length&&e.push(`councilQuorum (${t.councilQuorum}) exceeds securityCouncilKeys count (${t.securityCouncilKeys.length})`),t.feeRate<=0n&&e.push(`feeRate must be positive, got ${t.feeRate}`),t.minPeginFeeRate<=0n&&e.push(`minPeginFeeRate must be positive, got ${t.minPeginFeeRate}`),(!Number.isInteger(t.proverCircuitVersion)||t.proverCircuitVersion<0||t.proverCircuitVersion>T)&&e.push(`proverCircuitVersion must be a uint16, got ${t.proverCircuitVersion}`),(!Number.isInteger(t.minPrepeginDepth)||t.minPrepeginDepth<=0||t.minPrepeginDepth>I)&&e.push(`minPrepeginDepth must be a uint32 in [1, ${I}], got ${t.minPrepeginDepth}`),t.babeTotalInstances<=0&&e.push(`babeTotalInstances must be positive, got ${t.babeTotalInstances}`),t.babeInstancesToFinalize<=0&&e.push(`babeInstancesToFinalize must be positive, got ${t.babeInstancesToFinalize}`),t.babeInstancesToFinalize>t.babeTotalInstances&&e.push(`babeInstancesToFinalize (${t.babeInstancesToFinalize}) exceeds babeTotalInstances (${t.babeTotalInstances})`),(t.minVpCommissionBps<0||t.minVpCommissionBps>S)&&e.push(`minVpCommissionBps must be in [0, ${S}], got ${t.minVpCommissionBps}`),e.length>0)throw new Error(`Invalid offchain protocol parameters: ${e.join("; ")}`)}function z(t){const e=[];if(t.minimumPegInAmount<=0n&&e.push(`minimumPegInAmount must be positive, got ${t.minimumPegInAmount}`),t.maxPegInAmount<t.minimumPegInAmount&&e.push(`maxPegInAmount (${t.maxPegInAmount}) must be >= minimumPegInAmount (${t.minimumPegInAmount})`),t.pegInAckTimeout<=0n&&e.push(`pegInAckTimeout must be positive, got ${t.pegInAckTimeout}`),t.pegInActivationTimeout<=0n&&e.push(`pegInActivationTimeout must be positive, got ${t.pegInActivationTimeout}`),(!Number.isInteger(t.maxHtlcOutputCount)||t.maxHtlcOutputCount<=0||t.maxHtlcOutputCount>V)&&e.push(`maxHtlcOutputCount must be an integer in [1, ${V}], got ${t.maxHtlcOutputCount}`),(typeof t.expiredPegInGraceBlocks!="bigint"||t.expiredPegInGraceBlocks<=0n)&&e.push(`expiredPegInGraceBlocks must be a positive bigint, got ${t.expiredPegInGraceBlocks}`),e.length>0)throw new Error(`Invalid TBV protocol parameters: ${e.join("; ")}`)}function At(t){if(z(t),Y(t.offchainParams),!Number.isInteger(t.offchainParamsVersion)||t.offchainParamsVersion<0||t.offchainParamsVersion>I)throw new Error(`Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${t.offchainParamsVersion}`);g.assertValidVaultCoreVersion(t.activeVaultCoreVersion,"ProtocolParams.activeVaultCoreVersion()")}const G="RegistrationLogsUnavailableError";class B extends Error{constructor(n,o){super(o??`The Ethereum node returned no registration logs for block ${n}, which holds a vault registration; the node may not have indexed that block yet. Try again.`);y(this,"blockNumber");this.name=G,this.blockNumber=n}}function kt(t){return t instanceof B?!0:typeof t!="object"||t===null?!1:t.name===G}const Bt=2;function Rt(t,e,n){const o=e.toLowerCase(),i=t.find(u=>u.vaultId===o);if(i===void 0)throw new B(n,`Vault ${e} has no PegInSubmittedV2 registration log at its on-chain registration block ${n}: either the node served a partial answer for block ${n} (retry, preferably another node) or the vault was not registered in this block`);return i}function _t(t){return X(t.unsignedPrePeginTx)}function St(t){const e=(t.depositorPayoutScriptPubKey.length-Bt)/2;if(e===0||e>w.MAX_PAYOUT_SCRIPT_LEN)throw new Error(`PegInSubmittedV2 log for vault ${t.vaultId} carries a ${e}-byte depositorPayoutBtcAddress; expected 1..${w.MAX_PAYOUT_SCRIPT_LEN} bytes`)}exports.RegistrationLogsUnavailableError=B;exports.VaultClaimableByNotFoundError=W;exports.assertOnChainBtcPubkey=k;exports.assertPayoutScriptMatchesPopKey=$t;exports.assertRegisteredPayoutScriptBounds=St;exports.assertValidOffchainParamsVersion=Tt;exports.calculateBtcTxHash=X;exports.deriveP2trScript=M;exports.derivePeginVaultId=vt;exports.findRegistrationRecord=Rt;exports.isRegistrationLogsUnavailableError=kt;exports.isVaultClaimableByNotFoundError=Ct;exports.registrationPrePeginTxHash=_t;exports.ripemd160=H;exports.validateOffchainParams=Y;exports.validatePegInConfiguration=At;exports.validateTBVProtocolParams=z;
2
- //# sourceMappingURL=registration-records-DFQgBaYi.cjs.map
1
+ "use strict";var tt=Object.defineProperty;var et=(t,e,n)=>e in t?tt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var y=(t,e,n)=>et(t,typeof e!="symbol"?e+"":e,n);const g=require("./secp256k1-DDHQ1_za.cjs"),l=require("./sha2-Ce6KewYx.cjs"),w=require("./constants-CAm10Qwp.cjs"),C=require("viem"),nt=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),N=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),ot=N.map(t=>(9*t+5)%16),U=(()=>{const n=[[N],[ot]];for(let o=0;o<4;o++)for(let i of n)i.push(i[o].map(u=>nt[u]));return n})(),L=U[0],O=U[1],F=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(t=>Uint8Array.from(t)),it=L.map((t,e)=>t.map(n=>F[e][n])),rt=O.map((t,e)=>t.map(n=>F[e][n])),st=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),ut=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function R(t,e,n,o){return t===0?e^n^o:t===1?e&n|~e&o:t===2?(e|~n)^o:t===3?e&o|n&~o:e^(n|~o)}const x=new Uint32Array(16);class ct extends l.HashMD{constructor(){super(64,20,8,!0);y(this,"h0",1732584193);y(this,"h1",-271733879);y(this,"h2",-1732584194);y(this,"h3",271733878);y(this,"h4",-1009589776)}get(){const{h0:n,h1:o,h2:i,h3:u,h4:f}=this;return[n,o,i,u,f]}set(n,o,i,u,f){this.h0=n|0,this.h1=o|0,this.h2=i|0,this.h3=u|0,this.h4=f|0}process(n,o){for(let s=0;s<16;s++,o+=4)x[s]=n.getUint32(o,!0);let i=this.h0|0,u=i,f=this.h1|0,d=f,p=this.h2|0,b=p,m=this.h3|0,E=m,r=this.h4|0,c=r;for(let s=0;s<5;s++){const a=4-s,P=st[s],j=ut[s],q=L[s],Q=O[s],J=it[s],Z=rt[s];for(let h=0;h<16;h++){const v=l.rotl(i+R(s,f,p,m)+x[q[h]]+P,J[h])+r|0;i=r,r=m,m=l.rotl(p,10)|0,p=f,f=v}for(let h=0;h<16;h++){const v=l.rotl(u+R(a,d,b,E)+x[Q[h]]+j,Z[h])+c|0;u=c,c=E,E=l.rotl(b,10)|0,b=d,d=v}}this.set(this.h1+p+E|0,this.h2+m+c|0,this.h3+r+u|0,this.h4+i+d|0,this.h0+f+b|0)}roundClean(){l.clean(x)}destroy(){this.destroyed=!0,l.clean(this.buffer),this.set(0,0,0,0,0)}}const H=l.createHasher(()=>new ct),$=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,at=7n;function ft(t,e,n){let o=1n,i=t%n,u=e;for(;u>0n;)(u&1n)===1n&&(o=o*i%n),i=i*i%n,u>>=1n;return o}function lt(t){const e=BigInt(`0x${t}`);if(e>=$)return!1;const o=(e*e%$*e%$+at)%$,i=ft(o,$+1n>>2n,$);return i*i%$===o}function k(t,e){const n=t.toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(n))throw new Error(`${e} returned an unexpected value (length ${n.length}, prefix "${n.slice(0,2)}")`);const o=n.slice(2);if(!lt(o))throw new Error(`${e} returned a value that is not on the secp256k1 curve`);return o}const ht="5120",A="0014",dt=20,_=33,pt=65,mt=2,gt=3,bt=4;function K(t,e){const n=t.startsWith("0x")||t.startsWith("0X")?t.slice(2):t;if(!/^(?:[0-9a-fA-F]{2})+$/.test(n))throw new Error(`${e} must be non-empty, even-length hex`);return`0x${n.toLowerCase()}`}function M(t){const e=l.hexToBytes(t),n=g.schnorr.utils.lift_x(BigInt(`0x${t}`)),o=g.schnorr.utils.bytesToNumberBE(g.schnorr.utils.taggedHash("TapTweak",e));if(o>=g.secp256k1.CURVE.n)throw new Error("Proof of possession BTC pubkey has an invalid TapTweak");const i=o===0n?n:n.add(g.schnorr.Point.BASE.multiply(o));return`0x${ht}${l.bytesToHex(g.schnorr.utils.pointToBytes(i))}`}function Pt(t){const e=K(t,"depositorBtcPubkeyRaw"),n=l.hexToBytes(e.slice(2));if(n.length===32)return{xOnlyPubkey:k(e,"Payout BTC pubkey")};const o=n.length===_&&(n[0]===mt||n[0]===gt),i=n.length===pt&&n[0]===bt;if(!o&&!i)throw new Error("depositorBtcPubkeyRaw must be x-only, compressed, or uncompressed");try{g.secp256k1.Point.fromBytes(n)}catch{throw new Error("depositorBtcPubkeyRaw is not a valid BTC pubkey")}return{xOnlyPubkey:l.bytesToHex(n.subarray(1,_)),compressedPubkey:o?n:void 0}}function yt(t){return`0x${A}${l.bytesToHex(H(l.sha256(t)))}`}function $t(t,e,n){const o=K(t,"depositorPayoutScriptPubKey");if((o.length-2)/2>w.MAX_PAYOUT_SCRIPT_LEN)throw new Error(`depositorPayoutScriptPubKey exceeds ${w.MAX_PAYOUT_SCRIPT_LEN} bytes`);const i=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e,u=k(`0x${i}`,"Proof of possession BTC pubkey"),f=Pt(n);if(f.xOnlyPubkey!==u)throw new Error("depositorBtcPubkeyRaw does not match the proof of possession BTC pubkey");if(o===M(u))return o;if(o.startsWith(`0x${A}`)&&o.length===2+A.length+dt*2){if(!f.compressedPubkey)throw new Error("A P2WPKH payout requires a compressed BTC pubkey");if(o===yt(f.compressedPubkey))return o}throw new Error("depositorPayoutScriptPubKey does not match the proof of possession BTC pubkey")}function Et(t,e){const n=t.startsWith("0x")?t.slice(2):t;if(n.length===0||n.length%2!==0)throw new Error(`${e} must be non-empty, even-length hex`);if(!/^[0-9a-fA-F]+$/.test(n))throw new Error(`${e} contains non-hex characters`);const o=new Uint8Array(n.length/2);for(let i=0;i<o.length;i++)o[i]=Number.parseInt(n.slice(i*2,i*2+2),16);return o}function xt(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function wt(t){const e=new Uint8Array(t.reduce((o,i)=>o+i.length,0));let n=0;for(const o of t)e.set(o,n),n+=o.length;return e}function It(t){let e=0;const n=(r,c)=>{if(!Number.isSafeInteger(r)||r<0)throw new Error(`Invalid ${c} length ${r}`);if(e+r>t.length)throw new Error(`Truncated Bitcoin transaction while reading ${c}`);const s=t.slice(e,e+r);return e+=r,s},o=(r,c)=>{const s=n(r,c);let a=0n;for(let P=s.length-1;P>=0;P--)a=a<<8n|BigInt(s[P]);return a},i=r=>{const c=e,s=n(1,r)[0];let a;if(s<253)a=BigInt(s);else if(s===253){if(a=o(2,r),a<0xfdn)throw new Error(`Non-canonical ${r}`)}else if(s===254){if(a=o(4,r),a<=0xffffn)throw new Error(`Non-canonical ${r}`)}else if(a=o(8,r),a<=0xffffffffn)throw new Error(`Non-canonical ${r}`);if(a>BigInt(Number.MAX_SAFE_INTEGER))throw new Error(`${r} exceeds JavaScript's safe integer range`);return{encoded:t.slice(c,e),value:Number(a)}},u=n(4,"version"),f=t[e]===0&&t[e+1]===1;f&&(e+=2);const d=i("input count"),p=[];for(let r=0;r<d.value;r++){const c=e;n(32,`input ${r} previous transaction hash`),n(4,`input ${r} previous output index`);const s=i(`input ${r} script length`);n(s.value,`input ${r} script`),n(4,`input ${r} sequence`),p.push(t.slice(c,e))}const b=i("output count"),m=[];for(let r=0;r<b.value;r++){const c=e;n(8,`output ${r} value`);const s=i(`output ${r} script length`);n(s.value,`output ${r} script`),m.push(t.slice(c,e))}if(f){let r=!1;for(let c=0;c<d.value;c++){const s=i(`input ${c} witness item count`);r||(r=s.value>0);for(let a=0;a<s.value;a++){const P=i(`input ${c} witness item ${a} length`);n(P.value,`input ${c} witness item ${a}`)}}if(!r)throw new Error("Bitcoin transaction has superfluous witness marker")}const E=n(4,"locktime");if(e!==t.length)throw new Error(`Bitcoin transaction has ${t.length-e} trailing byte(s)`);return wt([u,d.encoded,...p,b.encoded,...m,E])}function X(t){const e=It(Et(t,"transactionHex")),n=l.sha256(l.sha256(e));return n.reverse(),`0x${xt(n)}`}function vt(t,e){const n=t.startsWith("0x")?t:`0x${t}`;if(!/^0x[0-9a-fA-F]{64}$/.test(n))throw new Error("peginTxHash must be a 32-byte hex value");const o=e.startsWith("0x")?e:`0x${e}`;if(!C.isAddress(o,{strict:!0}))throw new Error(`Invalid depositor Ethereum address: ${e}`);return C.keccak256(C.encodeAbiParameters([{type:"bytes32"},{type:"address"}],[n,o])).slice(2)}const D="VaultClaimableByNotFoundError";class W extends Error{constructor(e,n,o,i,u="the vault has not been redeemed for this key, or the node did not serve the block. Redeem first, or try again.",f){super(`No VaultClaimableBy log for vault ${e} and claimer ${n} in blocks ${o}..${i}: ${u}`,f),this.vaultId=e,this.claimerPk=n,this.fromBlock=o,this.toBlock=i,this.name=D}}function Ct(t){return t instanceof W?!0:typeof t!="object"||t===null?!1:t.name===D}const T=65535,S=1e4,I=4294967295,V=255;function Tt(t){if(!Number.isInteger(t)||t<0||t>I)throw new Error(`Invalid offchainParamsVersion from contract: must be a uint32, got ${t}`)}function Y(t){const e=[];if(t.timelockAssert<=0n&&e.push(`timelockAssert must be positive, got ${t.timelockAssert}`),t.timelockAssert>BigInt(T)&&e.push(`timelockAssert ${t.timelockAssert} exceeds uint16 max (${T})`),t.timelockChallengeAssert<=0n&&e.push(`timelockChallengeAssert must be positive, got ${t.timelockChallengeAssert}`),t.tRefund<=0&&e.push(`tRefund must be positive, got ${t.tRefund}`),t.tStale<=0&&e.push(`tStale must be positive, got ${t.tStale}`),t.securityCouncilKeys.length===0&&e.push("securityCouncilKeys must not be empty"),t.councilQuorum<=0&&e.push(`councilQuorum must be positive, got ${t.councilQuorum}`),t.councilQuorum>t.securityCouncilKeys.length&&e.push(`councilQuorum (${t.councilQuorum}) exceeds securityCouncilKeys count (${t.securityCouncilKeys.length})`),t.feeRate<=0n&&e.push(`feeRate must be positive, got ${t.feeRate}`),t.minPeginFeeRate<=0n&&e.push(`minPeginFeeRate must be positive, got ${t.minPeginFeeRate}`),(!Number.isInteger(t.proverCircuitVersion)||t.proverCircuitVersion<0||t.proverCircuitVersion>T)&&e.push(`proverCircuitVersion must be a uint16, got ${t.proverCircuitVersion}`),(!Number.isInteger(t.minPrepeginDepth)||t.minPrepeginDepth<=0||t.minPrepeginDepth>I)&&e.push(`minPrepeginDepth must be a uint32 in [1, ${I}], got ${t.minPrepeginDepth}`),t.babeTotalInstances<=0&&e.push(`babeTotalInstances must be positive, got ${t.babeTotalInstances}`),t.babeInstancesToFinalize<=0&&e.push(`babeInstancesToFinalize must be positive, got ${t.babeInstancesToFinalize}`),t.babeInstancesToFinalize>t.babeTotalInstances&&e.push(`babeInstancesToFinalize (${t.babeInstancesToFinalize}) exceeds babeTotalInstances (${t.babeTotalInstances})`),(t.minVpCommissionBps<0||t.minVpCommissionBps>S)&&e.push(`minVpCommissionBps must be in [0, ${S}], got ${t.minVpCommissionBps}`),e.length>0)throw new Error(`Invalid offchain protocol parameters: ${e.join("; ")}`)}function z(t){const e=[];if(t.minimumPegInAmount<=0n&&e.push(`minimumPegInAmount must be positive, got ${t.minimumPegInAmount}`),t.maxPegInAmount<t.minimumPegInAmount&&e.push(`maxPegInAmount (${t.maxPegInAmount}) must be >= minimumPegInAmount (${t.minimumPegInAmount})`),t.pegInAckTimeout<=0n&&e.push(`pegInAckTimeout must be positive, got ${t.pegInAckTimeout}`),t.pegInActivationTimeout<=0n&&e.push(`pegInActivationTimeout must be positive, got ${t.pegInActivationTimeout}`),(!Number.isInteger(t.maxHtlcOutputCount)||t.maxHtlcOutputCount<=0||t.maxHtlcOutputCount>V)&&e.push(`maxHtlcOutputCount must be an integer in [1, ${V}], got ${t.maxHtlcOutputCount}`),(typeof t.expiredPegInGraceBlocks!="bigint"||t.expiredPegInGraceBlocks<=0n)&&e.push(`expiredPegInGraceBlocks must be a positive bigint, got ${t.expiredPegInGraceBlocks}`),e.length>0)throw new Error(`Invalid TBV protocol parameters: ${e.join("; ")}`)}function At(t){if(z(t),Y(t.offchainParams),!Number.isInteger(t.offchainParamsVersion)||t.offchainParamsVersion<0||t.offchainParamsVersion>I)throw new Error(`Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${t.offchainParamsVersion}`);g.assertValidVaultCoreVersion(t.activeVaultCoreVersion,"ProtocolParams.activeVaultCoreVersion()")}const G="RegistrationLogsUnavailableError";class B extends Error{constructor(n,o){super(o??`The Ethereum node returned no registration logs for block ${n}, which holds a vault registration; the node may not have indexed that block yet. Try again.`);y(this,"blockNumber");this.name=G,this.blockNumber=n}}function kt(t){return t instanceof B?!0:typeof t!="object"||t===null?!1:t.name===G}const Bt=2;function Rt(t,e,n){const o=e.toLowerCase(),i=t.find(u=>u.vaultId===o);if(i===void 0)throw new B(n,`Vault ${e} has no PegInSubmittedV2 registration log at its on-chain registration block ${n}: either the node served a partial answer for block ${n} (retry, preferably another node) or the vault was not registered in this block`);return i}function _t(t){return X(t.unsignedPrePeginTx)}function St(t){const e=(t.depositorPayoutScriptPubKey.length-Bt)/2;if(e===0||e>w.MAX_PAYOUT_SCRIPT_LEN)throw new Error(`PegInSubmittedV2 log for vault ${t.vaultId} carries a ${e}-byte depositorPayoutBtcAddress; expected 1..${w.MAX_PAYOUT_SCRIPT_LEN} bytes`)}exports.RegistrationLogsUnavailableError=B;exports.VaultClaimableByNotFoundError=W;exports.assertOnChainBtcPubkey=k;exports.assertPayoutScriptMatchesPopKey=$t;exports.assertRegisteredPayoutScriptBounds=St;exports.assertValidOffchainParamsVersion=Tt;exports.calculateBtcTxHash=X;exports.deriveP2trScript=M;exports.derivePeginVaultId=vt;exports.findRegistrationRecord=Rt;exports.isRegistrationLogsUnavailableError=kt;exports.isVaultClaimableByNotFoundError=Ct;exports.registrationPrePeginTxHash=_t;exports.ripemd160=H;exports.validateOffchainParams=Y;exports.validatePegInConfiguration=At;exports.validateTBVProtocolParams=z;
2
+ //# sourceMappingURL=registration-records-DaBufozs.cjs.map