@aztec/foundation 0.0.1-commit.29c6b1a3 → 0.0.1-commit.2c0ee1788

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 (234) hide show
  1. package/dest/array/sorted_array.d.ts +6 -1
  2. package/dest/array/sorted_array.d.ts.map +1 -1
  3. package/dest/array/sorted_array.js +18 -15
  4. package/dest/branded-types/buffer32_hash.d.ts +24 -0
  5. package/dest/branded-types/buffer32_hash.d.ts.map +1 -0
  6. package/dest/branded-types/buffer32_hash.js +19 -0
  7. package/dest/branded-types/checkpoint_number.d.ts +4 -1
  8. package/dest/branded-types/checkpoint_number.d.ts.map +1 -1
  9. package/dest/branded-types/checkpoint_number.js +3 -0
  10. package/dest/branded-types/index.d.ts +2 -1
  11. package/dest/branded-types/index.d.ts.map +1 -1
  12. package/dest/branded-types/index.js +1 -0
  13. package/dest/branded-types/slot.d.ts +4 -1
  14. package/dest/branded-types/slot.d.ts.map +1 -1
  15. package/dest/branded-types/slot.js +3 -0
  16. package/dest/buffer/buffer16.d.ts +3 -1
  17. package/dest/buffer/buffer16.d.ts.map +1 -1
  18. package/dest/buffer/buffer32.d.ts +28 -61
  19. package/dest/buffer/buffer32.d.ts.map +1 -1
  20. package/dest/buffer/buffer32.js +26 -60
  21. package/dest/buffer/index.d.ts +2 -1
  22. package/dest/buffer/index.d.ts.map +1 -1
  23. package/dest/buffer/index.js +1 -0
  24. package/dest/buffer/utils.d.ts +3 -0
  25. package/dest/buffer/utils.d.ts.map +1 -0
  26. package/dest/buffer/utils.js +7 -0
  27. package/dest/collection/array.d.ts +3 -1
  28. package/dest/collection/array.d.ts.map +1 -1
  29. package/dest/collection/array.js +15 -0
  30. package/dest/collection/index.d.ts +2 -1
  31. package/dest/collection/index.d.ts.map +1 -1
  32. package/dest/collection/index.js +1 -0
  33. package/dest/collection/lru_set.d.ts +35 -0
  34. package/dest/collection/lru_set.d.ts.map +1 -0
  35. package/dest/collection/lru_set.js +95 -0
  36. package/dest/config/env_var.d.ts +2 -2
  37. package/dest/config/env_var.d.ts.map +1 -1
  38. package/dest/config/index.d.ts +48 -30
  39. package/dest/config/index.d.ts.map +1 -1
  40. package/dest/config/index.js +35 -29
  41. package/dest/config/network_config.d.ts +19 -1
  42. package/dest/config/network_config.d.ts.map +1 -1
  43. package/dest/config/network_config.js +4 -1
  44. package/dest/config/network_name.d.ts +2 -2
  45. package/dest/config/network_name.d.ts.map +1 -1
  46. package/dest/config/network_name.js +2 -0
  47. package/dest/crypto/aes128/index.d.ts +2 -1
  48. package/dest/crypto/aes128/index.d.ts.map +1 -1
  49. package/dest/crypto/aes128/index.js +11 -2
  50. package/dest/crypto/bls/bn254_keystore.d.ts +1 -10
  51. package/dest/crypto/bls/bn254_keystore.d.ts.map +1 -1
  52. package/dest/crypto/bls/bn254_keystore.js +0 -17
  53. package/dest/crypto/poseidon/index.d.ts +1 -1
  54. package/dest/crypto/poseidon/index.d.ts.map +1 -1
  55. package/dest/crypto/poseidon/index.js +40 -33
  56. package/dest/crypto/random/randomness_singleton.d.ts +4 -3
  57. package/dest/crypto/random/randomness_singleton.d.ts.map +1 -1
  58. package/dest/crypto/random/randomness_singleton.js +4 -4
  59. package/dest/crypto/secp256k1-signer/utils.d.ts +12 -1
  60. package/dest/crypto/secp256k1-signer/utils.d.ts.map +1 -1
  61. package/dest/crypto/secp256k1-signer/utils.js +26 -0
  62. package/dest/curves/bls12/field.d.ts +1 -1
  63. package/dest/curves/bls12/field.d.ts.map +1 -1
  64. package/dest/curves/bls12/field.js +0 -5
  65. package/dest/curves/bn254/field.d.ts +18 -16
  66. package/dest/curves/bn254/field.d.ts.map +1 -1
  67. package/dest/curves/bn254/field.js +23 -15
  68. package/dest/curves/grumpkin/point.d.ts +4 -4
  69. package/dest/curves/grumpkin/point.d.ts.map +1 -1
  70. package/dest/curves/grumpkin/point.js +7 -4
  71. package/dest/eth-address/index.d.ts +1 -1
  72. package/dest/eth-address/index.d.ts.map +1 -1
  73. package/dest/eth-address/index.js +0 -3
  74. package/dest/eth-signature/eth_signature.d.ts +2 -1
  75. package/dest/eth-signature/eth_signature.d.ts.map +1 -1
  76. package/dest/eth-signature/eth_signature.js +7 -2
  77. package/dest/fifo/fifo_frame_reader.d.ts +41 -0
  78. package/dest/fifo/fifo_frame_reader.d.ts.map +1 -0
  79. package/dest/fifo/fifo_frame_reader.js +74 -0
  80. package/dest/fifo/index.d.ts +2 -0
  81. package/dest/fifo/index.d.ts.map +1 -0
  82. package/dest/fifo/index.js +1 -0
  83. package/dest/jest/setup.js +28 -1
  84. package/dest/json-rpc/client/fetch.d.ts +1 -1
  85. package/dest/json-rpc/client/fetch.d.ts.map +1 -1
  86. package/dest/json-rpc/client/fetch.js +4 -3
  87. package/dest/json-rpc/client/safe_json_rpc_client.d.ts +2 -1
  88. package/dest/json-rpc/client/safe_json_rpc_client.d.ts.map +1 -1
  89. package/dest/json-rpc/client/safe_json_rpc_client.js +1 -1
  90. package/dest/json-rpc/client/undici.d.ts +1 -1
  91. package/dest/json-rpc/client/undici.d.ts.map +1 -1
  92. package/dest/json-rpc/client/undici.js +5 -3
  93. package/dest/json-rpc/server/api_key_auth.d.ts +19 -0
  94. package/dest/json-rpc/server/api_key_auth.d.ts.map +1 -0
  95. package/dest/json-rpc/server/api_key_auth.js +57 -0
  96. package/dest/json-rpc/server/index.d.ts +2 -1
  97. package/dest/json-rpc/server/index.d.ts.map +1 -1
  98. package/dest/json-rpc/server/index.js +1 -0
  99. package/dest/log/bigint-utils.d.ts +5 -0
  100. package/dest/log/bigint-utils.d.ts.map +1 -0
  101. package/dest/log/bigint-utils.js +21 -0
  102. package/dest/log/gcloud-logger-config.d.ts +1 -1
  103. package/dest/log/gcloud-logger-config.d.ts.map +1 -1
  104. package/dest/log/gcloud-logger-config.js +3 -0
  105. package/dest/log/libp2p_logger.d.ts +5 -2
  106. package/dest/log/libp2p_logger.d.ts.map +1 -1
  107. package/dest/log/libp2p_logger.js +14 -4
  108. package/dest/log/log-filters.d.ts +17 -4
  109. package/dest/log/log-filters.d.ts.map +1 -1
  110. package/dest/log/log-filters.js +26 -12
  111. package/dest/log/pino-logger-server.d.ts +9 -0
  112. package/dest/log/pino-logger-server.d.ts.map +1 -0
  113. package/dest/log/pino-logger-server.js +18 -0
  114. package/dest/log/pino-logger.d.ts +37 -8
  115. package/dest/log/pino-logger.d.ts.map +1 -1
  116. package/dest/log/pino-logger.js +137 -29
  117. package/dest/queue/base_memory_queue.d.ts +2 -2
  118. package/dest/queue/base_memory_queue.d.ts.map +1 -1
  119. package/dest/queue/batch_queue.d.ts +1 -1
  120. package/dest/queue/batch_queue.d.ts.map +1 -1
  121. package/dest/queue/batch_queue.js +1 -0
  122. package/dest/retry/index.d.ts +12 -1
  123. package/dest/retry/index.d.ts.map +1 -1
  124. package/dest/retry/index.js +21 -0
  125. package/dest/schemas/api.d.ts +2 -2
  126. package/dest/schemas/api.d.ts.map +1 -1
  127. package/dest/serialize/buffer_reader.d.ts +8 -1
  128. package/dest/serialize/buffer_reader.d.ts.map +1 -1
  129. package/dest/serialize/buffer_reader.js +13 -0
  130. package/dest/serialize/serialize.d.ts +19 -1
  131. package/dest/serialize/serialize.d.ts.map +1 -1
  132. package/dest/serialize/serialize.js +31 -0
  133. package/dest/sleep/index.d.ts +2 -1
  134. package/dest/sleep/index.d.ts.map +1 -1
  135. package/dest/sleep/index.js +10 -1
  136. package/dest/string/index.js +1 -1
  137. package/dest/timer/date.d.ts +25 -1
  138. package/dest/timer/date.d.ts.map +1 -1
  139. package/dest/timer/date.js +33 -0
  140. package/dest/transport/dispatch/create_dispatch_proxy.d.ts +11 -2
  141. package/dest/transport/dispatch/create_dispatch_proxy.d.ts.map +1 -1
  142. package/dest/transport/index.d.ts +1 -2
  143. package/dest/transport/index.d.ts.map +1 -1
  144. package/dest/transport/index.js +0 -1
  145. package/dest/transport/transport_client.js +2 -2
  146. package/dest/trees/balanced_merkle_tree_root.d.ts +2 -3
  147. package/dest/trees/balanced_merkle_tree_root.d.ts.map +1 -1
  148. package/dest/trees/balanced_merkle_tree_root.js +2 -3
  149. package/dest/trees/hasher.d.ts +3 -2
  150. package/dest/trees/hasher.d.ts.map +1 -1
  151. package/dest/trees/hasher.js +5 -5
  152. package/dest/trees/indexed_merkle_tree_calculator.d.ts +1 -1
  153. package/dest/trees/indexed_merkle_tree_calculator.d.ts.map +1 -1
  154. package/dest/trees/indexed_merkle_tree_calculator.js +5 -1
  155. package/dest/trees/merkle_tree_calculator.d.ts +4 -2
  156. package/dest/trees/merkle_tree_calculator.d.ts.map +1 -1
  157. package/dest/trees/merkle_tree_calculator.js +1 -5
  158. package/dest/trees/sibling_path.d.ts +2 -2
  159. package/dest/trees/sibling_path.d.ts.map +1 -1
  160. package/dest/trees/sibling_path.js +1 -5
  161. package/dest/trees/unbalanced_merkle_tree_root.d.ts +2 -3
  162. package/dest/trees/unbalanced_merkle_tree_root.d.ts.map +1 -1
  163. package/dest/trees/unbalanced_merkle_tree_root.js +2 -3
  164. package/dest/types/index.d.ts +11 -1
  165. package/dest/types/index.d.ts.map +1 -1
  166. package/dest/types/index.js +3 -0
  167. package/package.json +24 -2
  168. package/src/array/sorted_array.ts +22 -17
  169. package/src/branded-types/buffer32_hash.ts +42 -0
  170. package/src/branded-types/checkpoint_number.ts +5 -0
  171. package/src/branded-types/index.ts +1 -0
  172. package/src/branded-types/slot.ts +5 -0
  173. package/src/buffer/buffer16.ts +3 -0
  174. package/src/buffer/buffer32.ts +36 -65
  175. package/src/buffer/index.ts +1 -0
  176. package/src/buffer/utils.ts +8 -0
  177. package/src/collection/array.ts +14 -0
  178. package/src/collection/index.ts +1 -0
  179. package/src/collection/lru_set.ts +115 -0
  180. package/src/config/env_var.ts +60 -13
  181. package/src/config/index.ts +110 -83
  182. package/src/config/network_config.ts +3 -0
  183. package/src/config/network_name.ts +4 -1
  184. package/src/crypto/aes128/index.ts +11 -2
  185. package/src/crypto/bls/bn254_keystore.ts +0 -23
  186. package/src/crypto/poseidon/index.ts +42 -34
  187. package/src/crypto/random/randomness_singleton.ts +9 -5
  188. package/src/crypto/secp256k1-signer/utils.ts +32 -0
  189. package/src/curves/bls12/field.ts +0 -7
  190. package/src/curves/bn254/field.ts +31 -33
  191. package/src/curves/grumpkin/point.ts +6 -3
  192. package/src/eth-address/index.ts +0 -4
  193. package/src/eth-signature/eth_signature.ts +7 -1
  194. package/src/fifo/fifo_frame_reader.ts +98 -0
  195. package/src/fifo/index.ts +1 -0
  196. package/src/jest/setup.mjs +31 -1
  197. package/src/json-rpc/client/fetch.ts +4 -3
  198. package/src/json-rpc/client/safe_json_rpc_client.ts +2 -0
  199. package/src/json-rpc/client/undici.ts +5 -3
  200. package/src/json-rpc/server/api_key_auth.ts +63 -0
  201. package/src/json-rpc/server/index.ts +1 -0
  202. package/src/log/bigint-utils.ts +25 -0
  203. package/src/log/gcloud-logger-config.ts +5 -0
  204. package/src/log/libp2p_logger.ts +12 -5
  205. package/src/log/log-filters.ts +29 -11
  206. package/src/log/pino-logger-server.ts +25 -0
  207. package/src/log/pino-logger.ts +160 -39
  208. package/src/queue/base_memory_queue.ts +1 -1
  209. package/src/queue/batch_queue.ts +1 -0
  210. package/src/retry/index.ts +30 -0
  211. package/src/schemas/api.ts +4 -1
  212. package/src/serialize/buffer_reader.ts +15 -0
  213. package/src/serialize/serialize.ts +32 -0
  214. package/src/sleep/index.ts +10 -1
  215. package/src/string/index.ts +1 -1
  216. package/src/timer/date.ts +48 -0
  217. package/src/transport/dispatch/create_dispatch_proxy.ts +11 -1
  218. package/src/transport/index.ts +0 -1
  219. package/src/transport/transport_client.ts +2 -2
  220. package/src/trees/balanced_merkle_tree_root.ts +2 -5
  221. package/src/trees/hasher.ts +6 -3
  222. package/src/trees/indexed_merkle_tree_calculator.ts +5 -1
  223. package/src/trees/merkle_tree_calculator.ts +4 -10
  224. package/src/trees/sibling_path.ts +1 -2
  225. package/src/trees/unbalanced_merkle_tree_root.ts +2 -5
  226. package/src/types/index.ts +19 -0
  227. package/dest/crypto/serialize.d.ts +0 -51
  228. package/dest/crypto/serialize.d.ts.map +0 -1
  229. package/dest/crypto/serialize.js +0 -68
  230. package/dest/transport/dispatch/create_dispatch_fn.d.ts +0 -25
  231. package/dest/transport/dispatch/create_dispatch_fn.d.ts.map +0 -1
  232. package/dest/transport/dispatch/create_dispatch_fn.js +0 -17
  233. package/src/crypto/serialize.ts +0 -85
  234. package/src/transport/dispatch/create_dispatch_fn.ts +0 -35
@@ -1,4 +1,4 @@
1
- import { createColors, isColorSupported } from 'colorette';
1
+ import { type Color, createColors, isColorSupported } from 'colorette';
2
2
  import isNode from 'detect-node';
3
3
  import { pino, symbols } from 'pino';
4
4
  import type { Writable } from 'stream';
@@ -7,14 +7,59 @@ import { inspect } from 'util';
7
7
  import { compactArray } from '../collection/array.js';
8
8
  import type { EnvVar } from '../config/index.js';
9
9
  import { parseBooleanEnv } from '../config/parse-env.js';
10
+ import { convertBigintsToStrings } from './bigint-utils.js';
10
11
  import { GoogleCloudLoggerConfig } from './gcloud-logger-config.js';
11
- import { getLogLevelFromFilters, parseEnv } from './log-filters.js';
12
+ import { getLogLevelFromFilters, parseLogLevelEnvVar } from './log-filters.js';
12
13
  import type { LogLevel } from './log-levels.js';
13
14
  import type { LogData, LogFn } from './log_fn.js';
14
15
 
15
- export function createLogger(module: string): Logger {
16
- module = logNameHandlers.reduce((moduleName, handler) => handler(moduleName), module.replace(/^aztec:/, ''));
17
- const pinoLogger = logger.child({ module }, { level: getLogLevelFromFilters(logFilters, module) });
16
+ /** Optional bindings to pass to createLogger for additional context. */
17
+ export type LoggerBindings = {
18
+ /** Actor label shown in logs (e.g., 'MAIN', 'prover-node'). */
19
+ actor?: string;
20
+ /** Instance identifier for distinguishing multiple instances of the same component. */
21
+ instanceId?: string;
22
+ };
23
+
24
+ const MAX_MODULE_NAME_LENGTH = 256;
25
+
26
+ // Allow global hooks for providing default bindings.
27
+ // Used by withLoggerBindings in pino-logger-server to propagate bindings via AsyncLocalStorage.
28
+ type LogBindingsHandler = () => LoggerBindings | undefined;
29
+ const logBindingsHandlers: LogBindingsHandler[] = [];
30
+
31
+ export function addLogBindingsHandler(handler: LogBindingsHandler): void {
32
+ logBindingsHandlers.push(handler);
33
+ }
34
+
35
+ export function removeLogBindingsHandler(handler: LogBindingsHandler) {
36
+ const index = logBindingsHandlers.indexOf(handler);
37
+ if (index !== -1) {
38
+ logBindingsHandlers.splice(index, 1);
39
+ }
40
+ }
41
+
42
+ function getBindingsFromHandlers(): LoggerBindings | undefined {
43
+ for (const handler of logBindingsHandlers) {
44
+ const bindings = handler();
45
+ if (bindings) {
46
+ return bindings;
47
+ }
48
+ }
49
+ return undefined;
50
+ }
51
+
52
+ export function createLogger(module: string, bindings?: LoggerBindings): Logger {
53
+ module = module.slice(0, MAX_MODULE_NAME_LENGTH).replace(/^aztec:/, '');
54
+
55
+ const resolvedBindings = { ...getBindingsFromHandlers(), ...bindings };
56
+ const actor = resolvedBindings?.actor;
57
+ const instanceId = resolvedBindings?.instanceId;
58
+
59
+ const pinoLogger = logger.child(
60
+ { module, ...(actor && { actor }), ...(instanceId && { instanceId }) },
61
+ { level: getLogLevelFromFilters(logFilters, module) },
62
+ );
18
63
 
19
64
  // We check manually for isLevelEnabled to avoid calling processLogData unnecessarily.
20
65
  // Note that isLevelEnabled is missing from the browser version of pino.
@@ -44,11 +89,24 @@ export function createLogger(module: string): Logger {
44
89
  isLevelEnabled: (level: LogLevel) => isLevelEnabled(pinoLogger, level),
45
90
  /** Module name for the logger. */
46
91
  module,
47
- /** Creates another logger by extending this logger module name. */
48
- createChild: (childModule: string) => createLogger(`${module}:${childModule}`),
92
+ /** Creates another logger by extending this logger module name and preserving bindings. */
93
+ createChild: (childModule: string) => createLogger(`${module}:${childModule}`, { actor, instanceId }),
94
+ /** Returns the bindings (actor, instanceId) for this logger. */
95
+ getBindings: () => ({ actor, instanceId }),
49
96
  };
50
97
  }
51
98
 
99
+ /**
100
+ * Returns a logger for the given module. If loggerOrBindings is already a Logger, returns it directly.
101
+ * Otherwise, creates a new logger with the given module name and bindings.
102
+ */
103
+ export function resolveLogger(module: string, loggerOrBindings?: Logger | LoggerBindings): Logger {
104
+ if (loggerOrBindings && 'info' in loggerOrBindings) {
105
+ return loggerOrBindings as Logger;
106
+ }
107
+ return createLogger(module, loggerOrBindings);
108
+ }
109
+
52
110
  // Allow global hooks for processing log data.
53
111
  // Used for injecting OTEL trace_id in telemetry client.
54
112
  type LogDataHandler = (data: LogData) => LogData;
@@ -62,31 +120,6 @@ function processLogData(data: LogData): LogData {
62
120
  return logDataHandlers.reduce((accum, handler) => handler(accum), data);
63
121
  }
64
122
 
65
- // Allow global hooks for tweaking module names.
66
- // Used in tests to add a uid to modules, so we can differentiate multiple nodes in the same process.
67
- type LogNameHandler = (module: string) => string;
68
- const logNameHandlers: LogNameHandler[] = [];
69
-
70
- export function addLogNameHandler(handler: LogNameHandler): void {
71
- logNameHandlers.push(handler);
72
- }
73
-
74
- export function removeLogNameHandler(handler: LogNameHandler) {
75
- const index = logNameHandlers.indexOf(handler);
76
- if (index !== -1) {
77
- logNameHandlers.splice(index, 1);
78
- }
79
- }
80
-
81
- /** Creates all loggers within the given callback with the suffix appended to the module name. */
82
- export async function withLogNameSuffix<T>(suffix: string, callback: () => Promise<T>): Promise<T> {
83
- const logNameHandler = (module: string) => `${module}:${suffix}`;
84
- addLogNameHandler(logNameHandler);
85
- const result = await callback();
86
- removeLogNameHandler(logNameHandler);
87
- return result;
88
- }
89
-
90
123
  // Patch isLevelEnabled missing from pino/browser.
91
124
  function isLevelEnabled(logger: pino.Logger<'verbose', boolean>, level: LogLevel): boolean {
92
125
  return typeof logger.isLevelEnabled === 'function'
@@ -96,7 +129,7 @@ function isLevelEnabled(logger: pino.Logger<'verbose', boolean>, level: LogLevel
96
129
 
97
130
  // Load log levels from environment variables.
98
131
  const defaultLogLevel = process.env.NODE_ENV === 'test' ? 'silent' : 'info';
99
- export const [logLevel, logFilters] = parseEnv(process.env.LOG_LEVEL, defaultLogLevel);
132
+ export const [logLevel, logFilters] = parseLogLevelEnvVar(process.env.LOG_LEVEL, defaultLogLevel);
100
133
 
101
134
  // Define custom logging levels for pino.
102
135
  const customLevels = { verbose: 25 };
@@ -135,6 +168,9 @@ const pinoOpts: pino.LoggerOptions<keyof typeof customLevels> = {
135
168
  ...redactedPaths.map(p => `opts.${p}`),
136
169
  ],
137
170
  },
171
+ formatters: {
172
+ log: obj => convertBigintsToStrings(obj) as Record<string, unknown>,
173
+ },
138
174
  ...(useGcloudLogging ? GoogleCloudLoggerConfig : {}),
139
175
  };
140
176
 
@@ -146,22 +182,90 @@ export const levels = {
146
182
  // Transport options for pretty logging to stderr via pino-pretty.
147
183
  const colorEnv = process.env['FORCE_COLOR' satisfies EnvVar];
148
184
  const useColor = colorEnv === undefined ? isColorSupported : parseBooleanEnv(colorEnv);
149
- const { bold, reset } = createColors({ useColor });
150
- export const pinoPrettyOpts = {
185
+ const { bold, reset, cyan, magenta, yellow, blue, green, magentaBright, yellowBright, blueBright, greenBright } =
186
+ createColors({ useColor });
187
+
188
+ // Per-actor coloring: each unique actor gets a different color for easier visual distinction.
189
+ // Disabled when LOG_NO_COLOR_PER_ACTOR is set to a truthy value.
190
+ const useColorPerActor = useColor && !parseBooleanEnv(process.env['LOG_NO_COLOR_PER_ACTOR' satisfies EnvVar]);
191
+ const actorColors: Color[] = [yellow, magenta, blue, green, magentaBright, yellowBright, blueBright, greenBright];
192
+ const actorColorMap = new Map<string, Color>();
193
+ let nextColorIndex = 0;
194
+
195
+ /** Returns the color function assigned to a given actor, assigning a new one if needed. */
196
+ export function getActorColor(actor: string): Color {
197
+ let color = actorColorMap.get(actor);
198
+ if (!color) {
199
+ color = actorColors[nextColorIndex % actorColors.length];
200
+ actorColorMap.set(actor, color);
201
+ nextColorIndex++;
202
+ }
203
+ return color;
204
+ }
205
+
206
+ /** Resets the actor-to-color mapping. Useful for testing. */
207
+ export function resetActorColors(): void {
208
+ actorColorMap.clear();
209
+ nextColorIndex = 0;
210
+ }
211
+
212
+ // String template for messageFormat (used in worker threads and when per-actor coloring is disabled).
213
+ const messageFormatString = `${bold('{module}')}{if actor} ${cyan('{actor}')}{end}{if instanceId} ${reset(cyan('{instanceId}'))}{end} ${reset('{msg}')}`;
214
+
215
+ // Function for messageFormat when per-actor coloring is enabled (can only be used in-process, not worker threads).
216
+ type LogObject = { actor?: string; module?: string; instanceId?: string; msg?: string };
217
+
218
+ /** Formats a log message with per-actor coloring. Actor, module, and instanceId share the same color. */
219
+ export function formatLogMessage(log: LogObject, messageKey: string): string {
220
+ const actor = log.actor;
221
+ const module = log.module ?? '';
222
+ const instanceId = log.instanceId;
223
+ const msg = log[messageKey as keyof LogObject] ?? '';
224
+
225
+ // Use actor color for actor, module, and instanceId when actor is present
226
+ const color = actor ? getActorColor(actor) : cyan;
227
+
228
+ let result = bold(color(module));
229
+ if (actor) {
230
+ result += ' ' + color(actor);
231
+ }
232
+ if (instanceId) {
233
+ result += ' ' + reset(color(instanceId));
234
+ }
235
+ result += ' ' + reset(String(msg));
236
+ return result;
237
+ }
238
+
239
+ // Base options for pino-pretty (shared between transport and direct use).
240
+ const pinoPrettyBaseOpts = {
151
241
  destination: 2,
152
242
  sync: true,
153
243
  colorize: useColor,
154
- ignore: 'module,pid,hostname,trace_id,span_id,trace_flags,severity',
155
- messageFormat: `${bold('{module}')} ${reset('{msg}')}`,
244
+ ignore: 'module,actor,instanceId,pid,hostname,trace_id,span_id,trace_flags,severity',
156
245
  customLevels: 'fatal:60,error:50,warn:40,info:30,verbose:25,debug:20,trace:10',
157
246
  customColors: 'fatal:bgRed,error:red,warn:yellow,info:green,verbose:magenta,debug:blue,trace:gray',
158
247
  minimumLevel: 'trace' as const,
159
248
  singleLine: !parseBooleanEnv(process.env['LOG_MULTILINE' satisfies EnvVar]),
160
249
  };
161
250
 
251
+ /**
252
+ * Pino-pretty options for direct use (e.g., jest/setup.mjs).
253
+ * Includes function-based messageFormat for per-actor coloring when enabled.
254
+ */
255
+ export const pinoPrettyOpts = {
256
+ ...pinoPrettyBaseOpts,
257
+ messageFormat: useColorPerActor ? formatLogMessage : messageFormatString,
258
+ };
259
+
260
+ // Transport options use string template only (functions can't be serialized to worker threads).
261
+ const prettyTransportOpts = {
262
+ ...pinoPrettyBaseOpts,
263
+ messageFormat: messageFormatString,
264
+ };
265
+
162
266
  const prettyTransport: pino.TransportTargetOptions = {
163
267
  target: 'pino-pretty',
164
- options: pinoPrettyOpts,
268
+ options: prettyTransportOpts,
165
269
  level: 'trace',
166
270
  };
167
271
 
@@ -262,6 +366,8 @@ export type Logger = { [K in LogLevel]: LogFn } & { /** Error log function */ er
262
366
  isLevelEnabled: (level: LogLevel) => boolean;
263
367
  module: string;
264
368
  createChild: (childModule: string) => Logger;
369
+ /** Returns the bindings (actor, instanceId) for this logger. */
370
+ getBindings: () => LoggerBindings;
265
371
  };
266
372
 
267
373
  /**
@@ -271,5 +377,20 @@ export type Logger = { [K in LogLevel]: LogFn } & { /** Error log function */ er
271
377
  * @returns A string with both the log message and the error message.
272
378
  */
273
379
  function formatErr(msg: string, err?: unknown): string {
274
- return err ? `${msg}: ${inspect(err)}` : msg;
380
+ if (!err) {
381
+ return msg;
382
+ }
383
+
384
+ try {
385
+ return `${msg}: ${inspect(err)}`;
386
+ } catch {
387
+ // inspect can crash on error objects with broken property descriptors
388
+ try {
389
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string
390
+ return `${msg}: ${err instanceof Error ? `${err.name}: ${err.message}` : String(err)}`;
391
+ } catch {
392
+ // if even String(err) fails, return the original message with a note about the error
393
+ return `${msg}: [unserializable error]`;
394
+ }
395
+ }
275
396
  }
@@ -122,7 +122,7 @@ export abstract class BaseMemoryQueue<T> {
122
122
  * @param handler - A function that takes an item of type T and returns a Promise<void> after processing the item.
123
123
  * @returns A Promise<void> that resolves when the queue is finished processing.
124
124
  */
125
- public async process(handler: (item: T) => Promise<void>) {
125
+ public async process(handler: (item: T) => Promise<void> | void) {
126
126
  try {
127
127
  while (true) {
128
128
  const item = await this.get();
@@ -105,6 +105,7 @@ export class BatchQueue<T, K extends string | number> {
105
105
  return Promise.resolve();
106
106
  }
107
107
 
108
+ this.flushCurrentBatch();
108
109
  this.container.end();
109
110
  return runningPromise;
110
111
  }
@@ -104,6 +104,36 @@ export async function retryUntil<T>(
104
104
  }
105
105
  }
106
106
 
107
+ /**
108
+ * Retry an asynchronous function until it returns a truthy value or the maximum number of retries is exceeded.
109
+ * The function is retried periodically with a fixed interval between attempts.
110
+ *
111
+ * @param fn - The asynchronous function to be retried, which should return a truthy value upon success or undefined otherwise.
112
+ * @param name - The optional name of the operation, used for generating error messages.
113
+ * @param maxRetries - The maximum number of retry attempts before throwing an error.
114
+ * @param retryInterval - The optional interval, in seconds, between retry attempts. Defaults to 1 second.
115
+ * @returns A Promise that resolves with the successful (truthy) result of the provided function, or rejects if retries are exhausted.
116
+ */
117
+ export async function retryTimes<T>(
118
+ fn: () => (T | undefined) | Promise<T | undefined>,
119
+ name = '',
120
+ maxRetries: number,
121
+ retryInterval = 1,
122
+ ) {
123
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
124
+ const result = await fn();
125
+ if (result) {
126
+ return result;
127
+ }
128
+
129
+ if (attempt < maxRetries) {
130
+ await sleep(retryInterval * 1000);
131
+ }
132
+ }
133
+
134
+ throw new Error(name ? `Retries exhausted awaiting ${name}` : 'Retries exhausted');
135
+ }
136
+
107
137
  /**
108
138
  * Convenience wrapper around retryUntil with fast polling for tests.
109
139
  * Uses 10s timeout and 100ms polling interval by default.
@@ -37,7 +37,10 @@ export type ApiSchema = {
37
37
  };
38
38
 
39
39
  /** Return whether an API schema defines a valid function schema for a given method name. */
40
- export function schemaHasMethod(schema: ApiSchema, methodName: string) {
40
+ export function schemaHasMethod<T extends ApiSchema>(
41
+ schema: T,
42
+ methodName: string,
43
+ ): methodName is Extract<keyof T, string> {
41
44
  return (
42
45
  typeof methodName === 'string' &&
43
46
  Object.hasOwn(schema, methodName) &&
@@ -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();
@@ -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
 
@@ -58,7 +58,7 @@ export function urlJoin(...args: string[]): string {
58
58
  end--;
59
59
  }
60
60
 
61
- if (start < end) {
61
+ if (start <= end) {
62
62
  processed.push(arg.slice(start, end + 1));
63
63
  }
64
64
  }
package/src/timer/date.ts CHANGED
@@ -31,4 +31,52 @@ export class TestDateProvider extends DateProvider {
31
31
  this.offset = timeMs - Date.now();
32
32
  this.logger.warn(`Time set to ${new Date(timeMs).toISOString()}`, { offset: this.offset, timeMs });
33
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
+ }
34
82
  }
@@ -2,7 +2,17 @@ import { EventEmitter } from 'events';
2
2
 
3
3
  import { type TransferDescriptor, isTransferDescriptor } from '../interface/transferable.js';
4
4
  import type { TransportClient } from '../transport_client.js';
5
- import type { DispatchMsg } from './create_dispatch_fn.js';
5
+
6
+ /**
7
+ * Represents a message object for dispatching function calls.
8
+ * Contains the function name ('fn') and an array of arguments ('args') required to call the target method.
9
+ */
10
+ export interface DispatchMsg {
11
+ /** Name of the target method to be called. */
12
+ fn: string;
13
+ /** An array of arguments to be passed to the target method. */
14
+ args: any[];
15
+ }
6
16
 
7
17
  /**
8
18
  * FilterOutAttributes type filters out all non-method properties of an object, leaving only the attributes
@@ -1,4 +1,3 @@
1
- export * from './dispatch/create_dispatch_fn.js';
2
1
  export * from './dispatch/create_dispatch_proxy.js';
3
2
  export * from './dispatch/messages.js';
4
3
  export * from './interface/connector.js';
@@ -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,10 +1,7 @@
1
- import { poseidonMerkleHash, shaMerkleHash } from './hasher.js';
1
+ import { shaMerkleHash } from './hasher.js';
2
2
 
3
3
  export const computeBalancedShaRoot = (leaves: Buffer[]) => computeBalancedMerkleTreeRoot(leaves);
4
4
 
5
- export const computeBalancedPoseidonRoot = async (leaves: Buffer[]) =>
6
- await computeBalancedMerkleTreeRootAsync(leaves, poseidonMerkleHash);
7
-
8
5
  /**
9
6
  * Computes the Merkle root with the provided leaves **synchronously**.
10
7
  * This method uses a synchronous hash function (defaults to `sha256Trunc`).
@@ -36,7 +33,7 @@ export function computeBalancedMerkleTreeRoot(leaves: Buffer[], hasher = shaMerk
36
33
  */
37
34
  export async function computeBalancedMerkleTreeRootAsync(
38
35
  leaves: Buffer[],
39
- hasher = poseidonMerkleHash,
36
+ hasher: (left: Buffer, right: Buffer) => Promise<Buffer<ArrayBuffer>>,
40
37
  ): Promise<Buffer> {
41
38
  const height = getTreeHeight(leaves);
42
39
  let nodes = leaves.slice();
@@ -1,4 +1,4 @@
1
- import { poseidon2Hash } from '../crypto/poseidon/index.js';
1
+ import { poseidon2HashWithSeparator } from '../crypto/poseidon/index.js';
2
2
  import { sha256Trunc } from '../crypto/sha256/index.js';
3
3
 
4
4
  /**
@@ -44,5 +44,8 @@ export interface AsyncHasher {
44
44
  export const shaMerkleHash: Hasher['hash'] = (left: Buffer, right: Buffer) =>
45
45
  sha256Trunc(Buffer.concat([left, right])) as Buffer<ArrayBuffer>;
46
46
 
47
- export const poseidonMerkleHash: AsyncHasher['hash'] = async (left: Buffer, right: Buffer) =>
48
- (await poseidon2Hash([left, right])).toBuffer() as Buffer<ArrayBuffer>;
47
+ /** Creates a poseidon2 merkle hasher with the given domain separator. */
48
+ export const makePoseidonMerkleHash =
49
+ (separator: number): AsyncHasher['hash'] =>
50
+ async (left: Buffer, right: Buffer) =>
51
+ (await poseidon2HashWithSeparator([left, right], separator)).toBuffer() as Buffer<ArrayBuffer>;
@@ -40,7 +40,11 @@ export class IndexedMerkleTreeCalculator<T extends IndexedTreeLeafPreimage, N ex
40
40
  }
41
41
  const sorted = values
42
42
  .map((v, i) => ({ value: v, index: i }))
43
- .sort((a, b) => Number(toBigIntBE(b.value) - toBigIntBE(a.value)));
43
+ .sort((a, b): -1 | 0 | 1 => {
44
+ const aBigInt = toBigIntBE(a.value);
45
+ const bBigInt = toBigIntBE(b.value);
46
+ return aBigInt < bBigInt ? 1 : aBigInt > bBigInt ? -1 : 0;
47
+ });
44
48
  const indexedLeaves = sorted.map((item, i) => ({
45
49
  leaf: this.factory.fromBuffer(
46
50
  Buffer.concat([
@@ -1,8 +1,7 @@
1
- import { poseidon2Hash } from '@aztec/foundation/crypto/poseidon';
2
-
3
- import type { AsyncHasher } from './hasher.js';
4
1
  import { MerkleTree } from './merkle_tree.js';
5
2
 
3
+ type MerkleHashFn = (left: Buffer, right: Buffer) => Promise<Buffer<ArrayBuffer>>;
4
+
6
5
  /**
7
6
  * Merkle tree calculator.
8
7
  */
@@ -10,17 +9,12 @@ export class MerkleTreeCalculator {
10
9
  private constructor(
11
10
  private height: number,
12
11
  private zeroHashes: Buffer[],
13
- private hasher: AsyncHasher['hash'],
12
+ private hasher: MerkleHashFn,
14
13
  ) {
15
14
  this.hasher = hasher;
16
15
  }
17
16
 
18
- static async create(
19
- height: number,
20
- zeroLeaf: Buffer = Buffer.alloc(32),
21
- hasher = async (left: Buffer, right: Buffer) =>
22
- (await poseidon2Hash([left, right])).toBuffer() as Buffer<ArrayBuffer>,
23
- ) {
17
+ static async create(height: number, zeroLeaf: Buffer = Buffer.alloc(32), hasher: MerkleHashFn) {
24
18
  const zeroHashes = [zeroLeaf];
25
19
  for (let i = 0; i < height; i++) {
26
20
  zeroHashes.push((await hasher(zeroHashes[i], zeroHashes[i])) as Buffer<ArrayBuffer>);
@@ -1,5 +1,4 @@
1
1
  import { makeTuple } from '../array/array.js';
2
- import { poseidon2Hash } from '../crypto/poseidon/index.js';
3
2
  import { Fr } from '../curves/bn254/index.js';
4
3
  import { schemas } from '../schemas/index.js';
5
4
  import {
@@ -172,7 +171,7 @@ export async function computeRootFromSiblingPath(
172
171
  leaf: Buffer,
173
172
  siblingPath: Buffer[],
174
173
  index: number,
175
- hasher = async (left: Buffer, right: Buffer) => (await poseidon2Hash([left, right])).toBuffer(),
174
+ hasher: (left: Buffer, right: Buffer) => Promise<Buffer>,
176
175
  ) {
177
176
  let result = leaf;
178
177
  for (const sibling of siblingPath) {