@aztec/foundation 0.0.1-commit.9593d84 → 0.0.1-commit.967fc6998

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 (329) hide show
  1. package/dest/array/index.d.ts +2 -1
  2. package/dest/array/index.d.ts.map +1 -1
  3. package/dest/array/index.js +1 -0
  4. package/dest/array/sorted_array.d.ts +15 -0
  5. package/dest/array/sorted_array.d.ts.map +1 -0
  6. package/dest/array/sorted_array.js +109 -0
  7. package/dest/branded-types/block_number.d.ts +56 -0
  8. package/dest/branded-types/block_number.d.ts.map +1 -0
  9. package/dest/branded-types/block_number.js +78 -0
  10. package/dest/branded-types/checkpoint_number.d.ts +54 -0
  11. package/dest/branded-types/checkpoint_number.d.ts.map +1 -0
  12. package/dest/branded-types/checkpoint_number.js +77 -0
  13. package/dest/branded-types/index.d.ts +4 -1
  14. package/dest/branded-types/index.d.ts.map +1 -1
  15. package/dest/branded-types/index.js +3 -0
  16. package/dest/branded-types/index_within_checkpoint.d.ts +42 -0
  17. package/dest/branded-types/index_within_checkpoint.d.ts.map +1 -0
  18. package/dest/branded-types/index_within_checkpoint.js +59 -0
  19. package/dest/buffer/buffer16.d.ts +5 -2
  20. package/dest/buffer/buffer16.d.ts.map +1 -1
  21. package/dest/buffer/buffer16.js +4 -2
  22. package/dest/buffer/buffer32.d.ts +5 -2
  23. package/dest/buffer/buffer32.d.ts.map +1 -1
  24. package/dest/buffer/buffer32.js +4 -2
  25. package/dest/collection/array.d.ts +12 -1
  26. package/dest/collection/array.d.ts.map +1 -1
  27. package/dest/collection/array.js +51 -0
  28. package/dest/config/env_var.d.ts +2 -2
  29. package/dest/config/env_var.d.ts.map +1 -1
  30. package/dest/config/index.d.ts +15 -4
  31. package/dest/config/index.d.ts.map +1 -1
  32. package/dest/config/index.js +32 -9
  33. package/dest/config/network_config.d.ts +13 -1
  34. package/dest/config/network_config.d.ts.map +1 -1
  35. package/dest/config/network_config.js +3 -1
  36. package/dest/config/network_name.d.ts +2 -2
  37. package/dest/config/network_name.d.ts.map +1 -1
  38. package/dest/config/network_name.js +2 -0
  39. package/dest/config/parse-env.d.ts +3 -0
  40. package/dest/config/parse-env.d.ts.map +1 -0
  41. package/dest/config/parse-env.js +7 -0
  42. package/dest/config/secret_value.js +3 -1
  43. package/dest/crypto/bls/bn254_keystore.js +1 -1
  44. package/dest/crypto/bls/index.js +1 -1
  45. package/dest/crypto/bn254/index.d.ts +35 -51
  46. package/dest/crypto/bn254/index.d.ts.map +1 -1
  47. package/dest/crypto/bn254/index.js +51 -140
  48. package/dest/crypto/ecdsa/signature.d.ts +11 -2
  49. package/dest/crypto/ecdsa/signature.d.ts.map +1 -1
  50. package/dest/crypto/ecdsa/signature.js +2 -2
  51. package/dest/crypto/grumpkin/index.d.ts +4 -2
  52. package/dest/crypto/grumpkin/index.d.ts.map +1 -1
  53. package/dest/crypto/grumpkin/index.js +2 -1
  54. package/dest/crypto/keys/index.d.ts +2 -2
  55. package/dest/crypto/keys/index.d.ts.map +1 -1
  56. package/dest/crypto/keys/index.js +1 -1
  57. package/dest/crypto/pedersen/pedersen.wasm.d.ts +2 -2
  58. package/dest/crypto/pedersen/pedersen.wasm.d.ts.map +1 -1
  59. package/dest/crypto/pedersen/pedersen.wasm.js +1 -1
  60. package/dest/crypto/poseidon/index.d.ts +2 -3
  61. package/dest/crypto/poseidon/index.d.ts.map +1 -1
  62. package/dest/crypto/poseidon/index.js +14 -23
  63. package/dest/crypto/random/randomness_singleton.d.ts +4 -3
  64. package/dest/crypto/random/randomness_singleton.d.ts.map +1 -1
  65. package/dest/crypto/random/randomness_singleton.js +5 -5
  66. package/dest/crypto/schnorr/index.d.ts +3 -2
  67. package/dest/crypto/schnorr/index.d.ts.map +1 -1
  68. package/dest/crypto/schnorr/index.js +1 -1
  69. package/dest/crypto/schnorr/signature.d.ts +2 -2
  70. package/dest/crypto/schnorr/signature.d.ts.map +1 -1
  71. package/dest/crypto/schnorr/signature.js +2 -2
  72. package/dest/crypto/sha256/index.d.ts +2 -2
  73. package/dest/crypto/sha256/index.d.ts.map +1 -1
  74. package/dest/crypto/sha256/index.js +1 -1
  75. package/dest/crypto/sha512/index.d.ts +2 -2
  76. package/dest/crypto/sha512/index.d.ts.map +1 -1
  77. package/dest/crypto/sha512/index.js +1 -1
  78. package/dest/crypto/signature/index.d.ts +2 -2
  79. package/dest/crypto/signature/index.d.ts.map +1 -1
  80. package/dest/crypto/sync/pedersen/index.d.ts +2 -2
  81. package/dest/crypto/sync/pedersen/index.d.ts.map +1 -1
  82. package/dest/crypto/sync/pedersen/index.js +1 -1
  83. package/dest/crypto/sync/poseidon/index.d.ts +2 -3
  84. package/dest/crypto/sync/poseidon/index.d.ts.map +1 -1
  85. package/dest/crypto/sync/poseidon/index.js +1 -9
  86. package/dest/{fields/bls12_fields.d.ts → curves/bls12/field.d.ts} +3 -3
  87. package/dest/curves/bls12/field.d.ts.map +1 -0
  88. package/dest/{fields/bls12_fields.js → curves/bls12/field.js} +12 -9
  89. package/dest/curves/bls12/index.d.ts +3 -0
  90. package/dest/curves/bls12/index.d.ts.map +1 -0
  91. package/dest/curves/bls12/index.js +2 -0
  92. package/dest/{fields/bls12_point.d.ts → curves/bls12/point.d.ts} +13 -4
  93. package/dest/curves/bls12/point.d.ts.map +1 -0
  94. package/dest/{fields/bls12_point.js → curves/bls12/point.js} +10 -8
  95. package/dest/{fields/fields.d.ts → curves/bn254/field.d.ts} +8 -15
  96. package/dest/curves/bn254/field.d.ts.map +1 -0
  97. package/dest/{fields/fields.js → curves/bn254/field.js} +38 -49
  98. package/dest/curves/bn254/index.d.ts +3 -0
  99. package/dest/curves/bn254/index.d.ts.map +1 -0
  100. package/dest/curves/bn254/index.js +2 -0
  101. package/dest/curves/bn254/point.d.ts +54 -0
  102. package/dest/curves/bn254/point.d.ts.map +1 -0
  103. package/dest/curves/bn254/point.js +143 -0
  104. package/dest/curves/grumpkin/index.d.ts +10 -0
  105. package/dest/curves/grumpkin/index.d.ts.map +1 -0
  106. package/dest/curves/grumpkin/index.js +3 -0
  107. package/dest/{fields → curves/grumpkin}/point.d.ts +13 -4
  108. package/dest/curves/grumpkin/point.d.ts.map +1 -0
  109. package/dest/{fields → curves/grumpkin}/point.js +7 -7
  110. package/dest/error/index.d.ts +4 -4
  111. package/dest/error/index.d.ts.map +1 -1
  112. package/dest/eth-address/index.d.ts +3 -2
  113. package/dest/eth-address/index.d.ts.map +1 -1
  114. package/dest/eth-address/index.js +10 -3
  115. package/dest/eth-signature/eth_signature.d.ts +4 -1
  116. package/dest/eth-signature/eth_signature.d.ts.map +1 -1
  117. package/dest/iterator/filter.d.ts +3 -0
  118. package/dest/iterator/filter.d.ts.map +1 -0
  119. package/dest/iterator/filter.js +7 -0
  120. package/dest/iterator/index.d.ts +2 -0
  121. package/dest/iterator/index.d.ts.map +1 -0
  122. package/dest/iterator/index.js +1 -0
  123. package/dest/jest/setup.js +28 -1
  124. package/dest/json-rpc/client/safe_json_rpc_client.d.ts +2 -1
  125. package/dest/json-rpc/client/safe_json_rpc_client.d.ts.map +1 -1
  126. package/dest/json-rpc/client/safe_json_rpc_client.js +1 -1
  127. package/dest/json-rpc/client/undici.d.ts +1 -1
  128. package/dest/json-rpc/client/undici.d.ts.map +1 -1
  129. package/dest/json-rpc/client/undici.js +21 -4
  130. package/dest/json-rpc/fixtures/class_a.d.ts +3 -3
  131. package/dest/json-rpc/fixtures/class_a.d.ts.map +1 -1
  132. package/dest/json-rpc/fixtures/class_b.d.ts +3 -3
  133. package/dest/json-rpc/fixtures/class_b.d.ts.map +1 -1
  134. package/dest/json-rpc/server/api_key_auth.d.ts +19 -0
  135. package/dest/json-rpc/server/api_key_auth.d.ts.map +1 -0
  136. package/dest/json-rpc/server/api_key_auth.js +57 -0
  137. package/dest/json-rpc/server/index.d.ts +2 -1
  138. package/dest/json-rpc/server/index.d.ts.map +1 -1
  139. package/dest/json-rpc/server/index.js +1 -0
  140. package/dest/json-rpc/server/safe_json_rpc_server.js +1 -1
  141. package/dest/log/bigint-utils.d.ts +5 -0
  142. package/dest/log/bigint-utils.d.ts.map +1 -0
  143. package/dest/log/bigint-utils.js +18 -0
  144. package/dest/log/gcloud-logger-config.d.ts +1 -1
  145. package/dest/log/gcloud-logger-config.d.ts.map +1 -1
  146. package/dest/log/gcloud-logger-config.js +3 -0
  147. package/dest/log/libp2p_logger.d.ts +5 -2
  148. package/dest/log/libp2p_logger.d.ts.map +1 -1
  149. package/dest/log/libp2p_logger.js +14 -4
  150. package/dest/log/log-filters.d.ts +17 -4
  151. package/dest/log/log-filters.d.ts.map +1 -1
  152. package/dest/log/log-filters.js +26 -12
  153. package/dest/log/pino-logger-server.d.ts +9 -0
  154. package/dest/log/pino-logger-server.d.ts.map +1 -0
  155. package/dest/log/pino-logger-server.js +18 -0
  156. package/dest/log/pino-logger.d.ts +37 -8
  157. package/dest/log/pino-logger.d.ts.map +1 -1
  158. package/dest/log/pino-logger.js +122 -29
  159. package/dest/queue/base_memory_queue.d.ts +2 -2
  160. package/dest/queue/base_memory_queue.d.ts.map +1 -1
  161. package/dest/queue/semaphore.d.ts +5 -1
  162. package/dest/queue/semaphore.d.ts.map +1 -1
  163. package/dest/retry/index.d.ts +11 -1
  164. package/dest/retry/index.d.ts.map +1 -1
  165. package/dest/retry/index.js +11 -0
  166. package/dest/schemas/schemas.d.ts +7 -3
  167. package/dest/schemas/schemas.d.ts.map +1 -1
  168. package/dest/schemas/schemas.js +9 -3
  169. package/dest/schemas/types.d.ts +31 -1
  170. package/dest/schemas/types.d.ts.map +1 -1
  171. package/dest/schemas/types.js +25 -1
  172. package/dest/serialize/buffer_reader.d.ts +14 -4
  173. package/dest/serialize/buffer_reader.d.ts.map +1 -1
  174. package/dest/serialize/buffer_reader.js +26 -4
  175. package/dest/serialize/field_reader.d.ts +2 -2
  176. package/dest/serialize/field_reader.d.ts.map +1 -1
  177. package/dest/serialize/field_reader.js +1 -1
  178. package/dest/serialize/free_funcs.d.ts +2 -2
  179. package/dest/serialize/free_funcs.d.ts.map +1 -1
  180. package/dest/serialize/free_funcs.js +1 -1
  181. package/dest/serialize/serialize.d.ts +20 -2
  182. package/dest/serialize/serialize.d.ts.map +1 -1
  183. package/dest/serialize/serialize.js +32 -1
  184. package/dest/sleep/index.d.ts +4 -1
  185. package/dest/sleep/index.d.ts.map +1 -1
  186. package/dest/sleep/index.js +14 -1
  187. package/dest/timer/date.d.ts +26 -1
  188. package/dest/timer/date.d.ts.map +1 -1
  189. package/dest/timer/date.js +36 -0
  190. package/dest/transport/transport_client.js +2 -2
  191. package/dest/trees/balanced_merkle_tree_root.d.ts +17 -0
  192. package/dest/trees/balanced_merkle_tree_root.d.ts.map +1 -0
  193. package/dest/trees/{balanced_merkle_tree.js → balanced_merkle_tree_root.js} +2 -15
  194. package/dest/trees/hasher.d.ts +3 -1
  195. package/dest/trees/hasher.d.ts.map +1 -1
  196. package/dest/trees/hasher.js +10 -5
  197. package/dest/trees/index.d.ts +4 -4
  198. package/dest/trees/index.d.ts.map +1 -1
  199. package/dest/trees/index.js +3 -3
  200. package/dest/trees/indexed_merkle_tree.js +1 -1
  201. package/dest/trees/membership_witness.d.ts +12 -2
  202. package/dest/trees/membership_witness.d.ts.map +1 -1
  203. package/dest/trees/membership_witness.js +10 -1
  204. package/dest/trees/merkle_tree_calculator.d.ts +1 -1
  205. package/dest/trees/merkle_tree_calculator.d.ts.map +1 -1
  206. package/dest/trees/merkle_tree_calculator.js +2 -2
  207. package/dest/trees/sibling_path.d.ts +3 -2
  208. package/dest/trees/sibling_path.d.ts.map +1 -1
  209. package/dest/trees/sibling_path.js +3 -3
  210. package/dest/trees/unbalanced_merkle_tree_calculator.d.ts +2 -3
  211. package/dest/trees/unbalanced_merkle_tree_calculator.d.ts.map +1 -1
  212. package/dest/trees/unbalanced_merkle_tree_calculator.js +1 -5
  213. package/dest/trees/{unbalanced_merkle_tree.d.ts → unbalanced_merkle_tree_root.d.ts} +3 -5
  214. package/dest/trees/unbalanced_merkle_tree_root.d.ts.map +1 -0
  215. package/dest/trees/{unbalanced_merkle_tree.js → unbalanced_merkle_tree_root.js} +11 -49
  216. package/dest/trees/unbalanced_tree_store.d.ts +5 -1
  217. package/dest/trees/unbalanced_tree_store.d.ts.map +1 -1
  218. package/dest/trees/unbalanced_tree_store.js +49 -1
  219. package/dest/types/index.d.ts +6 -2
  220. package/dest/types/index.d.ts.map +1 -1
  221. package/dest/types/index.js +6 -0
  222. package/package.json +48 -9
  223. package/src/array/index.ts +1 -0
  224. package/src/array/sorted_array.ts +138 -0
  225. package/src/branded-types/block_number.ts +117 -0
  226. package/src/branded-types/checkpoint_number.ts +115 -0
  227. package/src/branded-types/index.ts +3 -0
  228. package/src/branded-types/index_within_checkpoint.ts +88 -0
  229. package/src/buffer/buffer16.ts +2 -2
  230. package/src/buffer/buffer32.ts +2 -2
  231. package/src/collection/array.ts +52 -0
  232. package/src/config/env_var.ts +71 -14
  233. package/src/config/index.ts +39 -6
  234. package/src/config/network_config.ts +2 -0
  235. package/src/config/network_name.ts +4 -1
  236. package/src/config/parse-env.ts +4 -0
  237. package/src/crypto/bls/bn254_keystore.ts +1 -1
  238. package/src/crypto/bls/index.ts +1 -1
  239. package/src/crypto/bn254/index.ts +50 -159
  240. package/src/crypto/ecdsa/signature.ts +2 -2
  241. package/src/crypto/grumpkin/index.ts +3 -1
  242. package/src/crypto/keys/index.ts +1 -1
  243. package/src/crypto/pedersen/pedersen.wasm.ts +1 -1
  244. package/src/crypto/poseidon/index.ts +14 -24
  245. package/src/crypto/random/randomness_singleton.ts +6 -4
  246. package/src/crypto/schnorr/index.ts +2 -1
  247. package/src/crypto/schnorr/signature.ts +2 -2
  248. package/src/crypto/sha256/index.ts +1 -1
  249. package/src/crypto/sha512/index.ts +1 -1
  250. package/src/crypto/signature/index.ts +1 -1
  251. package/src/crypto/sync/pedersen/index.ts +1 -1
  252. package/src/crypto/sync/poseidon/index.ts +1 -10
  253. package/src/{fields/bls12_fields.ts → curves/bls12/field.ts} +6 -6
  254. package/src/curves/bls12/index.ts +2 -0
  255. package/src/{fields/bls12_point.ts → curves/bls12/point.ts} +7 -7
  256. package/src/{fields/fields.ts → curves/bn254/field.ts} +37 -56
  257. package/src/curves/bn254/index.ts +2 -0
  258. package/src/curves/bn254/point.ts +170 -0
  259. package/src/curves/grumpkin/index.ts +11 -0
  260. package/src/{fields → curves/grumpkin}/point.ts +7 -7
  261. package/src/eth-address/index.ts +8 -2
  262. package/src/iterator/filter.ts +11 -0
  263. package/src/iterator/index.ts +1 -0
  264. package/src/jest/setup.mjs +31 -1
  265. package/src/json-rpc/client/safe_json_rpc_client.ts +2 -0
  266. package/src/json-rpc/client/undici.ts +21 -3
  267. package/src/json-rpc/server/api_key_auth.ts +63 -0
  268. package/src/json-rpc/server/index.ts +1 -0
  269. package/src/json-rpc/server/safe_json_rpc_server.ts +1 -1
  270. package/src/log/bigint-utils.ts +22 -0
  271. package/src/log/gcloud-logger-config.ts +5 -0
  272. package/src/log/libp2p_logger.ts +12 -5
  273. package/src/log/log-filters.ts +29 -11
  274. package/src/log/pino-logger-server.ts +25 -0
  275. package/src/log/pino-logger.ts +144 -39
  276. package/src/queue/base_memory_queue.ts +1 -1
  277. package/src/queue/semaphore.ts +5 -0
  278. package/src/retry/index.ts +18 -0
  279. package/src/schemas/schemas.ts +14 -3
  280. package/src/schemas/types.ts +33 -0
  281. package/src/serialize/buffer_reader.ts +36 -9
  282. package/src/serialize/field_reader.ts +1 -1
  283. package/src/serialize/free_funcs.ts +1 -1
  284. package/src/serialize/serialize.ts +33 -1
  285. package/src/sleep/index.ts +16 -1
  286. package/src/timer/date.ts +52 -0
  287. package/src/transport/transport_client.ts +2 -2
  288. package/src/trees/{balanced_merkle_tree.ts → balanced_merkle_tree_root.ts} +2 -16
  289. package/src/trees/hasher.ts +9 -0
  290. package/src/trees/index.ts +3 -3
  291. package/src/trees/indexed_merkle_tree.ts +1 -1
  292. package/src/trees/membership_witness.ts +9 -1
  293. package/src/trees/merkle_tree_calculator.ts +2 -2
  294. package/src/trees/sibling_path.ts +3 -3
  295. package/src/trees/unbalanced_merkle_tree_calculator.ts +1 -12
  296. package/src/trees/{unbalanced_merkle_tree.ts → unbalanced_merkle_tree_root.ts} +17 -61
  297. package/src/trees/unbalanced_tree_store.ts +57 -2
  298. package/src/types/index.ts +11 -1
  299. package/dest/crypto/bn254/bn254_utils.d.ts +0 -39
  300. package/dest/crypto/bn254/bn254_utils.d.ts.map +0 -1
  301. package/dest/crypto/bn254/bn254_utils.js +0 -56
  302. package/dest/crypto/index.d.ts +0 -17
  303. package/dest/crypto/index.d.ts.map +0 -1
  304. package/dest/crypto/index.js +0 -16
  305. package/dest/fields/bls12_fields.d.ts.map +0 -1
  306. package/dest/fields/bls12_point.d.ts.map +0 -1
  307. package/dest/fields/coordinate.d.ts +0 -63
  308. package/dest/fields/coordinate.d.ts.map +0 -1
  309. package/dest/fields/coordinate.js +0 -96
  310. package/dest/fields/fields.d.ts.map +0 -1
  311. package/dest/fields/index.d.ts +0 -6
  312. package/dest/fields/index.d.ts.map +0 -1
  313. package/dest/fields/index.js +0 -5
  314. package/dest/fields/point.d.ts.map +0 -1
  315. package/dest/index.d.ts +0 -31
  316. package/dest/index.d.ts.map +0 -1
  317. package/dest/index.js +0 -31
  318. package/dest/json-rpc/server/telemetry.d.ts +0 -2
  319. package/dest/json-rpc/server/telemetry.d.ts.map +0 -1
  320. package/dest/json-rpc/server/telemetry.js +0 -0
  321. package/dest/trees/balanced_merkle_tree.d.ts +0 -22
  322. package/dest/trees/balanced_merkle_tree.d.ts.map +0 -1
  323. package/dest/trees/unbalanced_merkle_tree.d.ts.map +0 -1
  324. package/src/crypto/bn254/bn254_utils.ts +0 -64
  325. package/src/crypto/index.ts +0 -16
  326. package/src/fields/coordinate.ts +0 -104
  327. package/src/fields/index.ts +0 -5
  328. package/src/index.ts +0 -31
  329. package/src/json-rpc/server/telemetry.ts +0 -0
@@ -4,10 +4,10 @@ import { EpochNumber, EpochNumberSchema } from '../branded-types/epoch.js';
4
4
  import { SlotNumber, SlotNumberSchema } from '../branded-types/slot.js';
5
5
  import { Buffer32 } from '../buffer/buffer32.js';
6
6
  import { SecretValue } from '../config/secret_value.js';
7
+ import { Fq, Fr } from '../curves/bn254/field.js';
8
+ import { Point } from '../curves/grumpkin/point.js';
7
9
  import { EthAddress } from '../eth-address/index.js';
8
- import { Fq, Fr } from '../fields/fields.js';
9
- import { Point } from '../fields/point.js';
10
- import { isHex, withoutHexPrefix } from '../string/index.js';
10
+ import { isHex, withHexPrefix, withoutHexPrefix } from '../string/index.js';
11
11
  import { bufferSchema, hexSchema } from './utils.js';
12
12
 
13
13
  export const schemas = {
@@ -58,6 +58,14 @@ export const schemas = {
58
58
  .max(2 ** 32 - 1),
59
59
  ),
60
60
 
61
+ /** Coerces input to UInt64. */
62
+ UInt64: z.union([z.bigint(), z.number(), z.string()]).pipe(
63
+ z.coerce
64
+ .bigint()
65
+ .min(0n)
66
+ .max(2n ** 64n - 1n),
67
+ ),
68
+
61
69
  /** Accepts a hex string as a Buffer32 type. */
62
70
  Buffer32: z.string().refine(isHex, 'Not a valid hex string').transform(Buffer32.fromString),
63
71
 
@@ -74,6 +82,9 @@ export const schemas = {
74
82
  /** Hex string with an optional 0x prefix which gets removed as part of the parsing. */
75
83
  HexString: hexSchema,
76
84
 
85
+ /** Hex string with an optional 0x prefix which gets enforced as part of the parsing. */
86
+ HexStringWith0x: z.string().refine(isHex, 'Not a valid hex string').transform(withHexPrefix),
87
+
77
88
  /** A secret config value */
78
89
  SecretValue: SecretValue.schema,
79
90
  };
@@ -1,3 +1,36 @@
1
1
  import type { ZodType } from 'zod';
2
2
 
3
3
  export type ZodFor<T> = ZodType<T, any, any>;
4
+
5
+ /**
6
+ * Creates a schema validator that enforces all properties of type T are present in the schema.
7
+ * This provides compile-time safety to ensure schemas don't miss optional properties.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * interface MyConfig {
12
+ * foo: string;
13
+ * bar?: number;
14
+ * }
15
+ *
16
+ * // ✅ This will work - all keys present
17
+ * const schema1 = zodFor<MyConfig>()(z.object({
18
+ * foo: z.string(),
19
+ * bar: z.number().optional(),
20
+ * }));
21
+ *
22
+ * // ❌ This will error - 'bar' is missing
23
+ * const schema2 = zodFor<MyConfig>()(z.object({
24
+ * foo: z.string(),
25
+ * }));
26
+ * ```
27
+ */
28
+ export function zodFor<T>() {
29
+ return (schema => schema) as <S extends ZodType<any, any, any>>(
30
+ schema: keyof T extends keyof S['_output']
31
+ ? keyof S['_output'] extends keyof T
32
+ ? S
33
+ : S & { __error__: 'Schema has extra keys not in type'; __extra__: Exclude<keyof S['_output'], keyof T> }
34
+ : S & { __error__: 'Schema is missing keys from type'; __missing__: Exclude<keyof T, keyof S['_output']> },
35
+ ) => S;
36
+ }
@@ -1,3 +1,4 @@
1
+ import { toBigIntBE } from '../bigint-buffer/index.js';
1
2
  import type { Tuple } from './types.js';
2
3
 
3
4
  /**
@@ -130,6 +131,20 @@ export class BufferReader {
130
131
  return result;
131
132
  }
132
133
 
134
+ /**
135
+ * Reads a 256-bit signed integer (two's complement) from the buffer at the current index position.
136
+ * Updates the index position by 32 bytes after reading the number.
137
+ *
138
+ * @returns The read 256 bit signed value as a bigint.
139
+ */
140
+ public readInt256(): bigint {
141
+ this.#rangeCheck(32);
142
+ const unsigned = toBigIntBE(this.buffer.subarray(this.index, this.index + 32));
143
+ this.index += 32;
144
+ const signBit = 1n << 255n;
145
+ return unsigned >= signBit ? unsigned - (1n << 256n) : unsigned;
146
+ }
147
+
133
148
  /** Alias for readUInt256 */
134
149
  public readBigInt(): bigint {
135
150
  return this.readUInt256();
@@ -224,15 +239,22 @@ export class BufferReader {
224
239
  * deserializing each one using the 'fromBuffer' method of 'itemDeserializer'.
225
240
  *
226
241
  * @param itemDeserializer - Object with 'fromBuffer' method to deserialize vector elements.
242
+ * @param maxSize - Optional maximum allowed size for the vector. If the size exceeds this, an error is thrown.
227
243
  * @returns An array of deserialized elements of type T.
228
244
  */
229
- public readVector<T>(itemDeserializer: {
230
- /**
231
- * A method to deserialize data from a buffer.
232
- */
233
- fromBuffer: (reader: BufferReader) => T;
234
- }): T[] {
245
+ public readVector<T>(
246
+ itemDeserializer: {
247
+ /**
248
+ * A method to deserialize data from a buffer.
249
+ */
250
+ fromBuffer: (reader: BufferReader) => T;
251
+ },
252
+ maxSize?: number,
253
+ ): T[] {
235
254
  const size = this.readNumber();
255
+ if (maxSize !== undefined && size > maxSize) {
256
+ throw new Error(`Vector size ${size} exceeds maximum allowed ${maxSize}`);
257
+ }
236
258
  const result = new Array<T>(size);
237
259
  for (let i = 0; i < size; i++) {
238
260
  result[i] = itemDeserializer.fromBuffer(this);
@@ -344,10 +366,11 @@ export class BufferReader {
344
366
  * The method first reads the size of the string, then reads the corresponding
345
367
  * number of bytes from the buffer and converts them to a string.
346
368
  *
369
+ * @param maxSize - Optional maximum allowed size for the string buffer. If the size exceeds this, an error is thrown.
347
370
  * @returns The read string from the buffer.
348
371
  */
349
- public readString(): string {
350
- return this.readBuffer().toString();
372
+ public readString(maxSize?: number): string {
373
+ return this.readBuffer(maxSize).toString();
351
374
  }
352
375
 
353
376
  /**
@@ -356,10 +379,14 @@ export class BufferReader {
356
379
  * a Buffer with that size containing the bytes. Useful for reading variable-length
357
380
  * binary data encoded as (size, data) format.
358
381
  *
382
+ * @param maxSize - Optional maximum allowed size for the buffer. If the size exceeds this, an error is thrown.
359
383
  * @returns A Buffer containing the read bytes.
360
384
  */
361
- public readBuffer(): Buffer {
385
+ public readBuffer(maxSize?: number): Buffer {
362
386
  const size = this.readNumber();
387
+ if (maxSize !== undefined && size > maxSize) {
388
+ throw new Error(`Buffer size ${size} exceeds maximum allowed ${maxSize}`);
389
+ }
363
390
  this.#rangeCheck(size);
364
391
  return this.readBytes(size);
365
392
  }
@@ -1,4 +1,4 @@
1
- import { Fq, type Fr } from '../fields/fields.js';
1
+ import { Fq, type Fr } from '../curves/bn254/field.js';
2
2
  import type { Tuple } from './types.js';
3
3
 
4
4
  /**
@@ -1,5 +1,5 @@
1
1
  import { toBufferBE } from '../bigint-buffer/index.js';
2
- import { Fr } from '../fields/fields.js';
2
+ import { Fr } from '../curves/bn254/field.js';
3
3
  import type { Tuple } from './types.js';
4
4
 
5
5
  /**
@@ -1,5 +1,5 @@
1
1
  import { toBigIntBE, toBufferBE } from '../bigint-buffer/index.js';
2
- import { Fr } from '../fields/fields.js';
2
+ import { Fr } from '../curves/bn254/field.js';
3
3
  import { numToUInt32BE } from './free_funcs.js';
4
4
 
5
5
  /**
@@ -269,6 +269,22 @@ export function serializeBigInt(n: bigint, width = 32) {
269
269
  return toBufferBE(n, width);
270
270
  }
271
271
 
272
+ /**
273
+ * Serialize a signed BigInt value into a Buffer of specified width using two's complement.
274
+ * @param n - The signed BigInt value to be serialized.
275
+ * @param width - The width (in bytes) of the output Buffer, optional with default value 32.
276
+ * @returns A Buffer containing the serialized signed BigInt value in big-endian format.
277
+ */
278
+ export function serializeSignedBigInt(n: bigint, width = 32) {
279
+ const widthBits = BigInt(width * 8);
280
+ const max = 1n << (widthBits - 1n);
281
+ if (n < -max || n >= max) {
282
+ throw new Error(`Signed BigInt ${n.toString()} does not fit into ${width} bytes`);
283
+ }
284
+ const unsigned = n < 0n ? (1n << widthBits) + n : n;
285
+ return toBufferBE(unsigned, width);
286
+ }
287
+
272
288
  /**
273
289
  * Deserialize a big integer from a buffer, given an offset and width.
274
290
  * Reads the specified number of bytes from the buffer starting at the offset, converts it to a big integer, and returns the deserialized result along with the number of bytes read (advanced).
@@ -282,6 +298,22 @@ export function deserializeBigInt(buf: Buffer, offset = 0, width = 32) {
282
298
  return { elem: toBigIntBE(buf.subarray(offset, offset + width)), adv: width };
283
299
  }
284
300
 
301
+ /**
302
+ * Deserialize a signed BigInt from a buffer (two's complement).
303
+ * @param buf - The buffer containing the signed big integer to be deserialized.
304
+ * @param offset - The position in the buffer where the integer starts. Defaults to 0.
305
+ * @param width - The number of bytes to read from the buffer for the integer. Defaults to 32.
306
+ * @returns An object containing the deserialized signed bigint value ('elem') and bytes advanced ('adv').
307
+ */
308
+ export function deserializeSignedBigInt(buf: Buffer, offset = 0, width = 32) {
309
+ const { elem, adv } = deserializeBigInt(buf, offset, width);
310
+ const widthBits = BigInt(width * 8);
311
+ const signBit = 1n << (widthBits - 1n);
312
+ const fullRange = 1n << widthBits;
313
+ const signed = elem >= signBit ? elem - fullRange : elem;
314
+ return { elem: signed, adv };
315
+ }
316
+
285
317
  /**
286
318
  * Serializes a Date object into a Buffer containing its timestamp as a big integer value.
287
319
  * The resulting Buffer has a fixed width of 8 bytes, representing a 64-bit big-endian integer.
@@ -22,6 +22,7 @@ import { InterruptError } from '../error/index.js';
22
22
  */
23
23
  export class InterruptibleSleep {
24
24
  private interrupts: Array<(shouldThrow: boolean) => void> = [];
25
+ private timeoutIds: NodeJS.Timeout[] = [];
25
26
 
26
27
  /**
27
28
  * Sleep for a specified amount of time in milliseconds.
@@ -38,9 +39,15 @@ export class InterruptibleSleep {
38
39
  this.interrupts.push(resolve);
39
40
  });
40
41
 
41
- const timeoutPromise = new Promise<boolean>(resolve => setTimeout(() => resolve(false), ms));
42
+ let timeoutId: NodeJS.Timeout;
43
+ const timeoutPromise = new Promise<boolean>(resolve => {
44
+ timeoutId = setTimeout(() => resolve(false), ms);
45
+ this.timeoutIds.push(timeoutId);
46
+ });
42
47
  const shouldThrow = await Promise.race([interruptPromise, timeoutPromise]);
43
48
 
49
+ clearTimeout(timeoutId!);
50
+ this.timeoutIds = this.timeoutIds.filter(id => id !== timeoutId);
44
51
  this.interrupts = this.interrupts.filter(res => res !== interruptResolve);
45
52
 
46
53
  if (shouldThrow) {
@@ -58,6 +65,8 @@ export class InterruptibleSleep {
58
65
  public interrupt(sleepShouldThrow = false): void {
59
66
  this.interrupts.forEach(resolve => resolve(sleepShouldThrow));
60
67
  this.interrupts = [];
68
+ this.timeoutIds.forEach(id => clearTimeout(id));
69
+ this.timeoutIds = [];
61
70
  }
62
71
  }
63
72
 
@@ -73,3 +82,9 @@ export class InterruptibleSleep {
73
82
  export function sleep<T>(ms: number, returnValue?: T): Promise<T> {
74
83
  return new Promise(resolve => setTimeout(() => resolve(returnValue as T), ms));
75
84
  }
85
+
86
+ /** Sleeps until the target date */
87
+ export function sleepUntil<T>(target: Date, now: Date, returnValue?: T): Promise<T> {
88
+ const ms = target.getTime() - now.getTime();
89
+ return sleep(ms, returnValue);
90
+ }
package/src/timer/date.ts CHANGED
@@ -9,6 +9,10 @@ export class DateProvider {
9
9
  public nowInSeconds(): number {
10
10
  return Math.floor(this.now() / 1000);
11
11
  }
12
+
13
+ public nowAsDate(): Date {
14
+ return new Date(this.now());
15
+ }
12
16
  }
13
17
 
14
18
  /** Returns current datetime and allows to override it. */
@@ -27,4 +31,52 @@ export class TestDateProvider extends DateProvider {
27
31
  this.offset = timeMs - Date.now();
28
32
  this.logger.warn(`Time set to ${new Date(timeMs).toISOString()}`, { offset: this.offset, timeMs });
29
33
  }
34
+
35
+ /** Resets the time back to real time (offset = 0). */
36
+ public reset() {
37
+ this.offset = 0;
38
+ this.logger.warn('Time reset to real time');
39
+ }
40
+
41
+ /** Advances the time by the given number of seconds. */
42
+ public advanceTime(seconds: number) {
43
+ this.offset += seconds * 1000;
44
+ }
45
+ }
46
+
47
+ /**
48
+ * A date provider for tests that only advances time via explicit advanceTime() calls.
49
+ * Unlike TestDateProvider, this does NOT track real time progression - time is completely
50
+ * frozen until explicitly advanced. This eliminates flakiness from tests taking
51
+ * varying amounts of real time to execute.
52
+ */
53
+ export class ManualDateProvider extends DateProvider {
54
+ private currentTimeMs: number;
55
+
56
+ /**
57
+ * @param initialTimeMs - Initial time in milliseconds. Defaults to a round timestamp for easy visualization.
58
+ */
59
+ constructor(initialTimeMs: number = Date.UTC(2025, 0, 1, 0, 0, 0)) {
60
+ super();
61
+ this.currentTimeMs = initialTimeMs;
62
+ }
63
+
64
+ public override now(): number {
65
+ return this.currentTimeMs;
66
+ }
67
+
68
+ /** Sets the current time to the given timestamp in milliseconds. */
69
+ public setTime(timeMs: number) {
70
+ this.currentTimeMs = timeMs;
71
+ }
72
+
73
+ /** Advances the time by the given number of seconds. */
74
+ public advanceTime(seconds: number) {
75
+ this.currentTimeMs += seconds * 1000;
76
+ }
77
+
78
+ /** Advances the time by the given number of milliseconds. */
79
+ public advanceTimeMs(ms: number) {
80
+ this.currentTimeMs += ms;
81
+ }
30
82
  }
@@ -91,7 +91,7 @@ export class TransportClient<Payload> extends EventEmitter {
91
91
  }
92
92
  const msgId = this.msgId++;
93
93
  const msg = { msgId, payload };
94
- log.debug(format(`->`, msg));
94
+ log.trace(format(`->`, msg));
95
95
  return new Promise<any>((resolve, reject) => {
96
96
  this.pendingRequests.push({ resolve, reject, msgId });
97
97
  this.socket!.send(msg, transfer).catch(reject);
@@ -111,7 +111,7 @@ export class TransportClient<Payload> extends EventEmitter {
111
111
  this.close();
112
112
  return;
113
113
  }
114
- log.debug(format(`<-`, msg));
114
+ log.trace(format(`<-`, msg));
115
115
  if (isEventMessage(msg)) {
116
116
  this.emit('event_msg', msg.payload);
117
117
  return;
@@ -1,21 +1,7 @@
1
- import { pedersenHash as pedersenHashArray, poseidon2Hash, sha256Trunc } from '@aztec/foundation/crypto';
2
-
3
- import type { AsyncHasher, Hasher } from './hasher.js';
4
-
5
- export const shaMerkleHash: Hasher['hash'] = (left: Buffer, right: Buffer) =>
6
- sha256Trunc(Buffer.concat([left, right])) as Buffer<ArrayBuffer>;
7
-
8
- export const pedersenMerkleHash: AsyncHasher['hash'] = async (left: Buffer, right: Buffer) =>
9
- (await pedersenHashArray([left, right])).toBuffer() as Buffer<ArrayBuffer>;
10
-
11
- export const poseidonMerkleHash: AsyncHasher['hash'] = async (left: Buffer, right: Buffer) =>
12
- (await poseidon2Hash([left, right])).toBuffer() as Buffer<ArrayBuffer>;
1
+ import { poseidonMerkleHash, shaMerkleHash } from './hasher.js';
13
2
 
14
3
  export const computeBalancedShaRoot = (leaves: Buffer[]) => computeBalancedMerkleTreeRoot(leaves);
15
4
 
16
- export const computeBalancedPedersenRoot = async (leaves: Buffer[]) =>
17
- await computeBalancedMerkleTreeRootAsync(leaves, pedersenMerkleHash);
18
-
19
5
  export const computeBalancedPoseidonRoot = async (leaves: Buffer[]) =>
20
6
  await computeBalancedMerkleTreeRootAsync(leaves, poseidonMerkleHash);
21
7
 
@@ -44,7 +30,7 @@ export function computeBalancedMerkleTreeRoot(leaves: Buffer[], hasher = shaMerk
44
30
 
45
31
  /**
46
32
  * Computes the Merkle root with the provided leaves **asynchronously**.
47
- * This method uses an asynchronous hash function (defaults to `pedersenHash`).
33
+ * This method uses an asynchronous hash function (defaults to `poseidon2Hash`).
48
34
  *
49
35
  * @throws If the number of leaves is not a power of two.
50
36
  */
@@ -1,3 +1,6 @@
1
+ import { poseidon2Hash } from '../crypto/poseidon/index.js';
2
+ import { sha256Trunc } from '../crypto/sha256/index.js';
3
+
1
4
  /**
2
5
  * Defines hasher interface used by Merkle trees.
3
6
  */
@@ -37,3 +40,9 @@ export interface AsyncHasher {
37
40
  */
38
41
  hashInputs(inputs: Buffer[]): Promise<Buffer<ArrayBuffer>>;
39
42
  }
43
+
44
+ export const shaMerkleHash: Hasher['hash'] = (left: Buffer, right: Buffer) =>
45
+ sha256Trunc(Buffer.concat([left, right])) as Buffer<ArrayBuffer>;
46
+
47
+ export const poseidonMerkleHash: AsyncHasher['hash'] = async (left: Buffer, right: Buffer) =>
48
+ (await poseidon2Hash([left, right])).toBuffer() as Buffer<ArrayBuffer>;
@@ -1,6 +1,4 @@
1
- export * from './balanced_merkle_tree.js';
2
- export * from './unbalanced_merkle_tree.js';
3
- export * from './unbalanced_tree_store.js';
1
+ export * from './balanced_merkle_tree_root.js';
4
2
  export * from './merkle_tree_calculator.js';
5
3
  export * from './merkle_tree.js';
6
4
  export * from './indexed_merkle_tree_calculator.js';
@@ -10,3 +8,5 @@ export * from './membership_witness.js';
10
8
  export * from './hasher.js';
11
9
  export * from './indexed_tree_leaf.js';
12
10
  export * from './unbalanced_merkle_tree_calculator.js';
11
+ export * from './unbalanced_merkle_tree_root.js';
12
+ export * from './unbalanced_tree_store.js';
@@ -1,4 +1,4 @@
1
- import { Fr } from '../fields/index.js';
1
+ import { Fr } from '../curves/bn254/index.js';
2
2
  import { assertLength } from '../serialize/index.js';
3
3
  import type { IndexedTreeLeafPreimage } from './indexed_tree_leaf.js';
4
4
  import { MembershipWitness } from './membership_witness.js';
@@ -1,6 +1,6 @@
1
1
  import { assertMemberLength } from '../array/array.js';
2
2
  import { toBigIntBE, toBufferBE } from '../bigint-buffer/index.js';
3
- import { Fr } from '../fields/fields.js';
3
+ import { Fr } from '../curves/bn254/field.js';
4
4
  import { schemas } from '../schemas/schemas.js';
5
5
  import { BufferReader, type Tuple, serializeToBuffer } from '../serialize/index.js';
6
6
  import type { SiblingPath } from './sibling_path.js';
@@ -38,6 +38,14 @@ export class MembershipWitness<N extends number> {
38
38
  return [new Fr(this.leafIndex), ...this.siblingPath];
39
39
  }
40
40
 
41
+ /**
42
+ * Returns a representation of the membership witness as expected by intrinsic Noir deserialization.
43
+ */
44
+ public toNoirRepresentation(): (string | string[])[] {
45
+ // TODO(#12874): remove the stupid as string conversion by modifying ForeignCallOutput type in acvm.js
46
+ return [new Fr(this.leafIndex).toString() as string, this.siblingPath.map(fr => fr.toString()) as string[]];
47
+ }
48
+
41
49
  static schemaFor<N extends number>(size: N) {
42
50
  return schemas.Buffer.transform(b => MembershipWitness.fromBuffer(b, size));
43
51
  }
@@ -1,4 +1,4 @@
1
- import { pedersenHash } from '@aztec/foundation/crypto';
1
+ import { poseidon2Hash } from '@aztec/foundation/crypto/poseidon';
2
2
 
3
3
  import type { AsyncHasher } from './hasher.js';
4
4
  import { MerkleTree } from './merkle_tree.js';
@@ -19,7 +19,7 @@ export class MerkleTreeCalculator {
19
19
  height: number,
20
20
  zeroLeaf: Buffer = Buffer.alloc(32),
21
21
  hasher = async (left: Buffer, right: Buffer) =>
22
- (await pedersenHash([left, right])).toBuffer() as Buffer<ArrayBuffer>,
22
+ (await poseidon2Hash([left, right])).toBuffer() as Buffer<ArrayBuffer>,
23
23
  ) {
24
24
  const zeroHashes = [zeroLeaf];
25
25
  for (let i = 0; i < height; i++) {
@@ -1,6 +1,6 @@
1
1
  import { makeTuple } from '../array/array.js';
2
- import { pedersenHash } from '../crypto/index.js';
3
- import { Fr } from '../fields/index.js';
2
+ import { poseidon2Hash } from '../crypto/poseidon/index.js';
3
+ import { Fr } from '../curves/bn254/index.js';
4
4
  import { schemas } from '../schemas/index.js';
5
5
  import {
6
6
  type Tuple,
@@ -172,7 +172,7 @@ export async function computeRootFromSiblingPath(
172
172
  leaf: Buffer,
173
173
  siblingPath: Buffer[],
174
174
  index: number,
175
- hasher = async (left: Buffer, right: Buffer) => (await pedersenHash([left, right])).toBuffer(),
175
+ hasher = async (left: Buffer, right: Buffer) => (await poseidon2Hash([left, right])).toBuffer(),
176
176
  ) {
177
177
  let result = leaf;
178
178
  for (const sibling of siblingPath) {
@@ -1,18 +1,7 @@
1
- import { shaMerkleHash } from './balanced_merkle_tree.js';
2
- import type { Hasher } from './hasher.js';
1
+ import { type Hasher, shaMerkleHash } from './hasher.js';
3
2
  import { SiblingPath } from './sibling_path.js';
4
3
  import { type TreeNodeLocation, UnbalancedTreeStore } from './unbalanced_tree_store.js';
5
4
 
6
- export function computeCompressedUnbalancedMerkleTreeRoot(
7
- leaves: Buffer[],
8
- valueToCompress = Buffer.alloc(32),
9
- emptyRoot = Buffer.alloc(32),
10
- hasher?: Hasher['hash'],
11
- ): Buffer {
12
- const calculator = UnbalancedMerkleTreeCalculator.create(leaves, valueToCompress, emptyRoot, hasher);
13
- return calculator.getRoot();
14
- }
15
-
16
5
  interface TreeNode {
17
6
  value: Buffer;
18
7
  leafIndex?: number;
@@ -1,15 +1,14 @@
1
- import {
2
- computeBalancedMerkleTreeRoot,
3
- computeBalancedMerkleTreeRootAsync,
4
- poseidonMerkleHash,
5
- shaMerkleHash,
6
- } from './balanced_merkle_tree.js';
1
+ import { computeBalancedMerkleTreeRoot, computeBalancedMerkleTreeRootAsync } from './balanced_merkle_tree_root.js';
2
+ import { poseidonMerkleHash, shaMerkleHash } from './hasher.js';
3
+ import { UnbalancedMerkleTreeCalculator } from './unbalanced_merkle_tree_calculator.js';
7
4
 
8
5
  export const computeUnbalancedShaRoot = (leaves: Buffer[]) => computeUnbalancedMerkleTreeRoot(leaves, shaMerkleHash);
9
6
 
10
7
  export const computeUnbalancedPoseidonRoot = async (leaves: Buffer[]) =>
11
8
  await computeUnbalancedMerkleTreeRootAsync(leaves, poseidonMerkleHash);
12
9
 
10
+ export const computeWonkyShaRoot = (leaves: Buffer[]) => computeWonkyMerkleTreeRoot(leaves);
11
+
13
12
  /**
14
13
  * Computes the Merkle root of an unbalanced tree.
15
14
  *
@@ -101,59 +100,16 @@ export async function computeUnbalancedMerkleTreeRootAsync(
101
100
  return root!;
102
101
  }
103
102
 
104
- /// Get the depth of the maximum balanced tree that can be created with the given number of leaves. The subtree will be
105
- /// the left most subtree of the wonky tree with a total of `numLeaves` leaves.
106
- ///
107
- /// Note: All the leaves may not be used to form the tree. For example, if there are 5 leaves, the maximum depth is 2,
108
- /// only 4 leaves are used to form a balanced tree.
109
- function getMaxBalancedSubtreeDepth(numLeaves: number) {
110
- return Math.floor(Math.log2(numLeaves));
111
- }
112
-
113
- /// Get the maximum depth of an unbalanced tree that can be created with the given number of leaves.
114
- function getMaxUnbalancedTreeDepth(numLeaves: number) {
115
- return Math.ceil(Math.log2(numLeaves));
116
- }
117
-
118
- function findPosition(
119
- rootLevel: number,
120
- leafLevel: number,
121
- numLeaves: number,
122
- indexOffset: number,
123
- targetIndex: number,
124
- ): { level: number; indexAtLevel: number } {
125
- if (numLeaves <= 1) {
126
- // Single leaf.
127
- return { level: rootLevel, indexAtLevel: indexOffset };
128
- }
129
-
130
- // The largest balanced tree that can be created with the given number of leaves.
131
- const maxBalancedTreeDepth = getMaxBalancedSubtreeDepth(numLeaves);
132
- const numBalancedLeaves = 2 ** maxBalancedTreeDepth;
133
- const numRemainingLeaves = numLeaves - numBalancedLeaves;
134
-
135
- if (targetIndex < numBalancedLeaves) {
136
- // Target is in the balanced tree.
137
-
138
- // - If numRemainingLeaves is 0: this balanced tree is grown from the current root.
139
- // - If numRemainingLeaves is not 0: the remaining leaves will form another tree, which will become the right child of the root.
140
- // And the balanced tree will be the left child of the root.
141
- // There will be an extra level between the root of the balanced tree and the current root.
142
- const extraLevel = numRemainingLeaves ? 1 : 0;
143
-
144
- return { level: rootLevel + maxBalancedTreeDepth + extraLevel, indexAtLevel: indexOffset + targetIndex };
145
- } else {
146
- // Target is in the right branch.
147
- const rightBranchMaxLevel = getMaxUnbalancedTreeDepth(numRemainingLeaves);
148
- const shiftedUp = leafLevel - rootLevel - rightBranchMaxLevel - 1;
149
- const nextLeafLevel = leafLevel - shiftedUp;
150
- const newIndexOffset = (indexOffset + numBalancedLeaves) >> shiftedUp;
151
- const shiftedTargetIndex = targetIndex - numBalancedLeaves;
152
- return findPosition(rootLevel + 1, nextLeafLevel, numRemainingLeaves, newIndexOffset, shiftedTargetIndex);
153
- }
154
- }
155
-
156
- export function findLeafLevelAndIndex(numLeaves: number, leafIndex: number) {
157
- const maxLevel = getMaxUnbalancedTreeDepth(numLeaves);
158
- return findPosition(0, maxLevel, numLeaves, 0, leafIndex);
103
+ // A **wonky** tree is a "compressed" unbalanced Merkle tree.
104
+ // It is constructed in the same way as an unbalanced tree: by first creating the largest possible left subtree, with
105
+ // the remaining leaves forming a right subtree that follows the same process recursively.
106
+ // During construction, leaves equal to `valueToCompress` are skipped (compressed) and do not contribute to the tree.
107
+ export function computeWonkyMerkleTreeRoot(
108
+ leaves: Buffer[],
109
+ valueToCompress = Buffer.alloc(32),
110
+ emptyRoot = Buffer.alloc(32),
111
+ hasher = shaMerkleHash,
112
+ ): Buffer {
113
+ const calculator = UnbalancedMerkleTreeCalculator.create(leaves, valueToCompress, emptyRoot, hasher);
114
+ return calculator.getRoot();
159
115
  }
@@ -1,5 +1,3 @@
1
- import { findLeafLevelAndIndex } from './unbalanced_merkle_tree.js';
2
-
3
1
  export interface TreeNodeLocation {
4
2
  level: number;
5
3
  index: number;
@@ -104,3 +102,60 @@ export class UnbalancedTreeStore<T> {
104
102
  return `${location.level}-${location.index}`;
105
103
  }
106
104
  }
105
+
106
+ /// Get the depth of the maximum balanced tree that can be created with the given number of leaves. The subtree will be
107
+ /// the left most subtree of the unbalanced tree with a total of `numLeaves` leaves.
108
+ ///
109
+ /// Note: All the leaves may not be used to form the tree. For example, if there are 5 leaves, the maximum depth is 2,
110
+ /// only 4 leaves are used to form a balanced tree.
111
+ function getMaxBalancedSubtreeDepth(numLeaves: number) {
112
+ return Math.floor(Math.log2(numLeaves));
113
+ }
114
+
115
+ /// Get the maximum depth of an unbalanced tree that can be created with the given number of leaves.
116
+ function getMaxUnbalancedTreeDepth(numLeaves: number) {
117
+ return Math.ceil(Math.log2(numLeaves));
118
+ }
119
+
120
+ function findPosition(
121
+ rootLevel: number,
122
+ leafLevel: number,
123
+ numLeaves: number,
124
+ indexOffset: number,
125
+ targetIndex: number,
126
+ ): { level: number; indexAtLevel: number } {
127
+ if (numLeaves <= 1) {
128
+ // Single leaf.
129
+ return { level: rootLevel, indexAtLevel: indexOffset };
130
+ }
131
+
132
+ // The largest balanced tree that can be created with the given number of leaves.
133
+ const maxBalancedTreeDepth = getMaxBalancedSubtreeDepth(numLeaves);
134
+ const numBalancedLeaves = 2 ** maxBalancedTreeDepth;
135
+ const numRemainingLeaves = numLeaves - numBalancedLeaves;
136
+
137
+ if (targetIndex < numBalancedLeaves) {
138
+ // Target is in the balanced tree.
139
+
140
+ // - If numRemainingLeaves is 0: this balanced tree is grown from the current root.
141
+ // - If numRemainingLeaves is not 0: the remaining leaves will form another tree, which will become the right child of the root.
142
+ // And the balanced tree will be the left child of the root.
143
+ // There will be an extra level between the root of the balanced tree and the current root.
144
+ const extraLevel = numRemainingLeaves ? 1 : 0;
145
+
146
+ return { level: rootLevel + maxBalancedTreeDepth + extraLevel, indexAtLevel: indexOffset + targetIndex };
147
+ } else {
148
+ // Target is in the right branch.
149
+ const rightBranchMaxLevel = getMaxUnbalancedTreeDepth(numRemainingLeaves);
150
+ const shiftedUp = leafLevel - rootLevel - rightBranchMaxLevel - 1;
151
+ const nextLeafLevel = leafLevel - shiftedUp;
152
+ const newIndexOffset = (indexOffset + numBalancedLeaves) >> shiftedUp;
153
+ const shiftedTargetIndex = targetIndex - numBalancedLeaves;
154
+ return findPosition(rootLevel + 1, nextLeafLevel, numRemainingLeaves, newIndexOffset, shiftedTargetIndex);
155
+ }
156
+ }
157
+
158
+ export function findLeafLevelAndIndex(numLeaves: number, leafIndex: number) {
159
+ const maxLevel = getMaxUnbalancedTreeDepth(numLeaves);
160
+ return findPosition(0, maxLevel, numLeaves, 0, leafIndex);
161
+ }