@aztec/foundation 0.0.1-commit.54489865 → 0.0.1-commit.5914bae

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 (109) 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/slot.d.ts +4 -1
  5. package/dest/branded-types/slot.d.ts.map +1 -1
  6. package/dest/branded-types/slot.js +3 -0
  7. package/dest/buffer/index.d.ts +2 -1
  8. package/dest/buffer/index.d.ts.map +1 -1
  9. package/dest/buffer/index.js +1 -0
  10. package/dest/buffer/utils.d.ts +3 -0
  11. package/dest/buffer/utils.d.ts.map +1 -0
  12. package/dest/buffer/utils.js +7 -0
  13. package/dest/collection/array.d.ts +3 -1
  14. package/dest/collection/array.d.ts.map +1 -1
  15. package/dest/collection/array.js +15 -0
  16. package/dest/config/env_var.d.ts +2 -2
  17. package/dest/config/env_var.d.ts.map +1 -1
  18. package/dest/config/index.d.ts +1 -1
  19. package/dest/config/index.d.ts.map +1 -1
  20. package/dest/config/index.js +15 -0
  21. package/dest/config/network_config.d.ts +19 -1
  22. package/dest/config/network_config.d.ts.map +1 -1
  23. package/dest/config/network_config.js +4 -1
  24. package/dest/crypto/poseidon/index.d.ts +1 -1
  25. package/dest/crypto/poseidon/index.d.ts.map +1 -1
  26. package/dest/crypto/poseidon/index.js +40 -33
  27. package/dest/crypto/secp256k1-signer/utils.d.ts +12 -1
  28. package/dest/crypto/secp256k1-signer/utils.d.ts.map +1 -1
  29. package/dest/crypto/secp256k1-signer/utils.js +26 -0
  30. package/dest/curves/bn254/field.d.ts +2 -1
  31. package/dest/curves/bn254/field.d.ts.map +1 -1
  32. package/dest/curves/bn254/field.js +5 -2
  33. package/dest/curves/grumpkin/point.d.ts +4 -4
  34. package/dest/curves/grumpkin/point.d.ts.map +1 -1
  35. package/dest/curves/grumpkin/point.js +7 -4
  36. package/dest/eth-signature/eth_signature.d.ts +2 -1
  37. package/dest/eth-signature/eth_signature.d.ts.map +1 -1
  38. package/dest/eth-signature/eth_signature.js +7 -2
  39. package/dest/json-rpc/client/safe_json_rpc_client.d.ts +2 -1
  40. package/dest/json-rpc/client/safe_json_rpc_client.d.ts.map +1 -1
  41. package/dest/json-rpc/client/safe_json_rpc_client.js +1 -1
  42. package/dest/json-rpc/server/api_key_auth.d.ts +19 -0
  43. package/dest/json-rpc/server/api_key_auth.d.ts.map +1 -0
  44. package/dest/json-rpc/server/api_key_auth.js +57 -0
  45. package/dest/json-rpc/server/index.d.ts +2 -1
  46. package/dest/json-rpc/server/index.d.ts.map +1 -1
  47. package/dest/json-rpc/server/index.js +1 -0
  48. package/dest/log/bigint-utils.d.ts +5 -0
  49. package/dest/log/bigint-utils.d.ts.map +1 -0
  50. package/dest/log/bigint-utils.js +21 -0
  51. package/dest/log/gcloud-logger-config.d.ts +1 -1
  52. package/dest/log/gcloud-logger-config.d.ts.map +1 -1
  53. package/dest/log/gcloud-logger-config.js +3 -0
  54. package/dest/log/log-filters.d.ts +17 -4
  55. package/dest/log/log-filters.d.ts.map +1 -1
  56. package/dest/log/log-filters.js +26 -12
  57. package/dest/log/pino-logger.d.ts +1 -1
  58. package/dest/log/pino-logger.d.ts.map +1 -1
  59. package/dest/log/pino-logger.js +6 -2
  60. package/dest/queue/base_memory_queue.d.ts +2 -2
  61. package/dest/queue/base_memory_queue.d.ts.map +1 -1
  62. package/dest/schemas/api.d.ts +2 -2
  63. package/dest/schemas/api.d.ts.map +1 -1
  64. package/dest/serialize/buffer_reader.d.ts +27 -7
  65. package/dest/serialize/buffer_reader.d.ts.map +1 -1
  66. package/dest/serialize/buffer_reader.js +31 -5
  67. package/dest/serialize/field_reader.d.ts +13 -5
  68. package/dest/serialize/field_reader.d.ts.map +1 -1
  69. package/dest/serialize/field_reader.js +13 -0
  70. package/dest/serialize/serialize.d.ts +19 -1
  71. package/dest/serialize/serialize.d.ts.map +1 -1
  72. package/dest/serialize/serialize.js +31 -0
  73. package/dest/timer/date.d.ts +23 -1
  74. package/dest/timer/date.d.ts.map +1 -1
  75. package/dest/timer/date.js +29 -0
  76. package/dest/transport/transport_client.js +2 -2
  77. package/dest/types/index.d.ts +3 -1
  78. package/dest/types/index.d.ts.map +1 -1
  79. package/dest/types/index.js +3 -0
  80. package/package.json +22 -2
  81. package/src/array/sorted_array.ts +22 -17
  82. package/src/branded-types/slot.ts +5 -0
  83. package/src/buffer/index.ts +1 -0
  84. package/src/buffer/utils.ts +8 -0
  85. package/src/collection/array.ts +14 -0
  86. package/src/config/env_var.ts +45 -6
  87. package/src/config/index.ts +15 -0
  88. package/src/config/network_config.ts +3 -0
  89. package/src/crypto/poseidon/index.ts +42 -34
  90. package/src/crypto/secp256k1-signer/utils.ts +32 -0
  91. package/src/curves/bn254/field.ts +6 -2
  92. package/src/curves/grumpkin/point.ts +6 -3
  93. package/src/eth-signature/eth_signature.ts +7 -1
  94. package/src/json-rpc/client/safe_json_rpc_client.ts +2 -0
  95. package/src/json-rpc/server/api_key_auth.ts +63 -0
  96. package/src/json-rpc/server/index.ts +1 -0
  97. package/src/log/bigint-utils.ts +25 -0
  98. package/src/log/gcloud-logger-config.ts +5 -0
  99. package/src/log/log-filters.ts +29 -11
  100. package/src/log/pino-logger.ts +6 -2
  101. package/src/queue/base_memory_queue.ts +1 -1
  102. package/src/schemas/api.ts +4 -1
  103. package/src/serialize/buffer_reader.ts +44 -6
  104. package/src/serialize/field_reader.ts +22 -4
  105. package/src/serialize/serialize.ts +32 -0
  106. package/src/timer/date.ts +42 -0
  107. package/src/transport/transport_client.ts +2 -2
  108. package/src/trees/membership_witness.ts +2 -2
  109. package/src/types/index.ts +5 -0
@@ -0,0 +1,63 @@
1
+ import { timingSafeEqual } from 'crypto';
2
+ import type Koa from 'koa';
3
+
4
+ import { sha256 } from '../../crypto/sha256/index.js';
5
+ import { createLogger } from '../../log/index.js';
6
+
7
+ const log = createLogger('json-rpc:api-key-auth');
8
+
9
+ /**
10
+ * Computes the SHA-256 hash of a string and returns it as a Buffer.
11
+ * @param input - The input string to hash.
12
+ * @returns The SHA-256 hash as a Buffer.
13
+ */
14
+ export function sha256Hash(input: string): Buffer {
15
+ return sha256(Buffer.from(input));
16
+ }
17
+
18
+ /**
19
+ * Creates a Koa middleware that enforces API key authentication on all requests
20
+ * except the health check endpoint (GET /status).
21
+ *
22
+ * The API key can be provided via the `x-api-key` header or the `Authorization: Bearer <key>` header.
23
+ * Comparison is done by hashing the provided key with SHA-256 and comparing against the stored hash.
24
+ *
25
+ * @param apiKeyHash - The SHA-256 hash of the expected API key as a Buffer.
26
+ * @returns A Koa middleware that rejects requests without a valid API key.
27
+ */
28
+ export function getApiKeyAuthMiddleware(
29
+ apiKeyHash: Buffer,
30
+ ): (ctx: Koa.Context, next: () => Promise<void>) => Promise<void> {
31
+ return async (ctx: Koa.Context, next: () => Promise<void>) => {
32
+ // Allow health check through without auth
33
+ if (ctx.path === '/status' && ctx.method === 'GET') {
34
+ return next();
35
+ }
36
+
37
+ const providedKey = ctx.get('x-api-key') || ctx.get('authorization')?.replace(/^Bearer\s+/i, '');
38
+ if (!providedKey) {
39
+ log.warn(`Rejected admin RPC request from ${ctx.ip}: missing API key`);
40
+ ctx.status = 401;
41
+ ctx.body = {
42
+ jsonrpc: '2.0',
43
+ id: null,
44
+ error: { code: -32000, message: 'Unauthorized: invalid or missing API key' },
45
+ };
46
+ return;
47
+ }
48
+
49
+ const providedHashBuf = sha256Hash(providedKey);
50
+ if (!timingSafeEqual(apiKeyHash, providedHashBuf)) {
51
+ log.warn(`Rejected admin RPC request from ${ctx.ip}: invalid API key`);
52
+ ctx.status = 401;
53
+ ctx.body = {
54
+ jsonrpc: '2.0',
55
+ id: null,
56
+ error: { code: -32000, message: 'Unauthorized: invalid or missing API key' },
57
+ };
58
+ return;
59
+ }
60
+
61
+ await next();
62
+ };
63
+ }
@@ -1 +1,2 @@
1
+ export * from './api_key_auth.js';
1
2
  export * from './safe_json_rpc_server.js';
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Converts bigint values to strings recursively in a log object to avoid serialization issues.
3
+ */
4
+ export function convertBigintsToStrings(obj: unknown): unknown {
5
+ if (typeof obj === 'bigint') {
6
+ return String(obj);
7
+ }
8
+
9
+ if (Array.isArray(obj)) {
10
+ return obj.map(item => convertBigintsToStrings(item));
11
+ }
12
+
13
+ if (obj !== null && typeof obj === 'object') {
14
+ if (typeof (obj as any).toJSON === 'function') {
15
+ return convertBigintsToStrings((obj as any).toJSON());
16
+ }
17
+ const result: Record<string, unknown> = {};
18
+ for (const key in obj) {
19
+ result[key] = convertBigintsToStrings((obj as Record<string, unknown>)[key]);
20
+ }
21
+ return result;
22
+ }
23
+
24
+ return obj;
25
+ }
@@ -1,5 +1,7 @@
1
1
  import type { pino } from 'pino';
2
2
 
3
+ import { convertBigintsToStrings } from './bigint-utils.js';
4
+
3
5
  /* eslint-disable camelcase */
4
6
 
5
7
  const GOOGLE_CLOUD_TRACE_ID = 'logging.googleapis.com/trace';
@@ -15,6 +17,9 @@ export const GoogleCloudLoggerConfig = {
15
17
  messageKey: 'message',
16
18
  formatters: {
17
19
  log(object: Record<string, unknown>): Record<string, unknown> {
20
+ // Convert bigints to strings recursively to avoid serialization issues
21
+ object = convertBigintsToStrings(object) as Record<string, unknown>;
22
+
18
23
  // Add trace context attributes following Cloud Logging structured log format described
19
24
  // in https://cloud.google.com/logging/docs/structured-logging#special-payload-fields
20
25
  const { trace_id, span_id, trace_flags, ...rest } = object;
@@ -19,22 +19,40 @@ export function getLogLevelFromFilters(filters: LogFilters, module: string): Log
19
19
  return undefined;
20
20
  }
21
21
 
22
- export function assertLogLevel(level: string): asserts level is LogLevel {
23
- if (!LogLevels.includes(level as LogLevel)) {
24
- throw new Error(`Invalid log level: ${level}`);
22
+ /**
23
+ * Parses the LOG_LEVEL env string into a default level and per-module filter overrides.
24
+ *
25
+ * Format: `<default_level>;<level>:<module1>,<module2>;<level>:<module3>;...`
26
+ * - First segment (before the first `;`) is the default log level for all modules.
27
+ * - Remaining segments are `level:module` pairs: apply the given level to the listed modules (comma-separated).
28
+ * - Later filters override earlier ones for overlapping module matches.
29
+ * - The `aztec:` prefix is stripped from module names; spaces are trimmed.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * parseLogLevel('debug;warn:module1,module2;error:module3', 'info')
34
+ * // => ['debug', [['module3', 'error'], ['module2', 'warn'], ['module1', 'warn']]]
35
+ * ```
36
+ */
37
+ export function parseLogLevelEnvVar(
38
+ logLevelEnvVar: string | undefined,
39
+ defaultLevel: LogLevel,
40
+ ): [LogLevel, LogFilters] {
41
+ if (!logLevelEnvVar) {
42
+ return [defaultLevel, []];
25
43
  }
44
+ const [level] = logLevelEnvVar.split(';', 1);
45
+ assertValidLogLevel(level);
46
+ return [level, parseFilters(logLevelEnvVar.slice(level.length + 1))];
26
47
  }
27
48
 
28
- export function parseEnv(env: string | undefined, defaultLevel: LogLevel): [LogLevel, LogFilters] {
29
- if (!env) {
30
- return [defaultLevel, []];
49
+ function assertValidLogLevel(level: string): asserts level is LogLevel {
50
+ if (!LogLevels.includes(level as LogLevel)) {
51
+ throw new Error(`Invalid log level: ${level}`);
31
52
  }
32
- const [level] = env.split(';', 1);
33
- assertLogLevel(level);
34
- return [level, parseFilters(env.slice(level.length + 1))];
35
53
  }
36
54
 
37
- export function parseFilters(definition: string | undefined): LogFilters {
55
+ function parseFilters(definition: string | undefined): LogFilters {
38
56
  if (!definition) {
39
57
  return [];
40
58
  }
@@ -48,7 +66,7 @@ export function parseFilters(definition: string | undefined): LogFilters {
48
66
  throw new Error(`Invalid log filter statement: ${statement}`);
49
67
  }
50
68
  const sanitizedLevel = level.trim().toLowerCase();
51
- assertLogLevel(sanitizedLevel);
69
+ assertValidLogLevel(sanitizedLevel);
52
70
  for (const module of modules.split(',')) {
53
71
  filters.push([
54
72
  module
@@ -7,8 +7,9 @@ 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
 
@@ -126,7 +127,7 @@ function isLevelEnabled(logger: pino.Logger<'verbose', boolean>, level: LogLevel
126
127
 
127
128
  // Load log levels from environment variables.
128
129
  const defaultLogLevel = process.env.NODE_ENV === 'test' ? 'silent' : 'info';
129
- export const [logLevel, logFilters] = parseEnv(process.env.LOG_LEVEL, defaultLogLevel);
130
+ export const [logLevel, logFilters] = parseLogLevelEnvVar(process.env.LOG_LEVEL, defaultLogLevel);
130
131
 
131
132
  // Define custom logging levels for pino.
132
133
  const customLevels = { verbose: 25 };
@@ -165,6 +166,9 @@ const pinoOpts: pino.LoggerOptions<keyof typeof customLevels> = {
165
166
  ...redactedPaths.map(p => `opts.${p}`),
166
167
  ],
167
168
  },
169
+ formatters: {
170
+ log: obj => convertBigintsToStrings(obj) as Record<string, unknown>,
171
+ },
168
172
  ...(useGcloudLogging ? GoogleCloudLoggerConfig : {}),
169
173
  };
170
174
 
@@ -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();
@@ -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();
@@ -271,16 +286,39 @@ export class BufferReader {
271
286
  }
272
287
 
273
288
  /**
274
- * Read an array of a fixed size with elements of type T from the buffer.
275
- * The 'itemDeserializer' object should have a 'fromBuffer' method that takes a BufferReader instance as input,
276
- * and returns an instance of the desired deserialized data type T.
277
- * This method will call the 'fromBuffer' method for each element in the array and return the resulting array.
289
+ * Read an array from the buffer using lazy allocation (new Array + loop).
290
+ * Safe for use with untrusted sizes does not pre-allocate memory proportional to size.
278
291
  *
279
- * @param size - The fixed number of elements in the array.
292
+ * @param size - The number of elements to read.
280
293
  * @param itemDeserializer - An object with a 'fromBuffer' method to deserialize individual elements of type T.
281
294
  * @returns An array of instances of type T.
282
295
  */
283
- public readArray<T, N extends number>(
296
+ public readArray<T>(
297
+ size: number,
298
+ itemDeserializer: {
299
+ /**
300
+ * A function for deserializing data from a BufferReader instance.
301
+ */
302
+ fromBuffer: (reader: BufferReader) => T;
303
+ },
304
+ ): T[] {
305
+ const result = new Array<T>(size);
306
+ for (let i = 0; i < size; i++) {
307
+ result[i] = itemDeserializer.fromBuffer(this);
308
+ }
309
+ return result;
310
+ }
311
+
312
+ /**
313
+ * Read a fixed-size tuple from the buffer using dense allocation (Array.from).
314
+ * Only use with compile-time constant sizes — the size parameter MUST NOT come from untrusted input
315
+ * as Array.from pre-allocates memory proportional to size.
316
+ *
317
+ * @param size - The fixed number of elements (must be a compile-time constant).
318
+ * @param itemDeserializer - An object with a 'fromBuffer' method to deserialize individual elements of type T.
319
+ * @returns A densely-allocated tuple of instances of type T.
320
+ */
321
+ public readTuple<T, N extends number>(
284
322
  size: N,
285
323
  itemDeserializer: {
286
324
  /**
@@ -169,12 +169,30 @@ export class FieldReader {
169
169
  * @param itemDeserializer - An object with a 'fromFields' method to deserialize individual elements of type T.
170
170
  * @returns An array of instances of type T.
171
171
  */
172
- public readArray<T, N extends number>(
172
+ /**
173
+ * Read an array from the field array using lazy allocation (new Array + loop).
174
+ * Safe for use with untrusted sizes.
175
+ */
176
+ public readArray<T>(
177
+ size: number,
178
+ itemDeserializer: {
179
+ fromFields: (reader: FieldReader) => T;
180
+ },
181
+ ): T[] {
182
+ const result = new Array<T>(size);
183
+ for (let i = 0; i < size; i++) {
184
+ result[i] = itemDeserializer.fromFields(this);
185
+ }
186
+ return result;
187
+ }
188
+
189
+ /**
190
+ * Read a fixed-size tuple from the field array using dense allocation (Array.from).
191
+ * Only use with compile-time constant sizes — the size parameter MUST NOT come from untrusted input.
192
+ */
193
+ public readTuple<T, N extends number>(
173
194
  size: N,
174
195
  itemDeserializer: {
175
- /**
176
- * A function for deserializing data from a FieldReader instance.
177
- */
178
196
  fromFields: (reader: FieldReader) => T;
179
197
  },
180
198
  ): Tuple<T, N> {
@@ -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.
package/src/timer/date.ts CHANGED
@@ -31,4 +31,46 @@ 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
+ /** Advances the time by the given number of seconds. */
36
+ public advanceTime(seconds: number) {
37
+ this.offset += seconds * 1000;
38
+ }
39
+ }
40
+
41
+ /**
42
+ * A date provider for tests that only advances time via explicit advanceTime() calls.
43
+ * Unlike TestDateProvider, this does NOT track real time progression - time is completely
44
+ * frozen until explicitly advanced. This eliminates flakiness from tests taking
45
+ * varying amounts of real time to execute.
46
+ */
47
+ export class ManualDateProvider extends DateProvider {
48
+ private currentTimeMs: number;
49
+
50
+ /**
51
+ * @param initialTimeMs - Initial time in milliseconds. Defaults to a round timestamp for easy visualization.
52
+ */
53
+ constructor(initialTimeMs: number = Date.UTC(2025, 0, 1, 0, 0, 0)) {
54
+ super();
55
+ this.currentTimeMs = initialTimeMs;
56
+ }
57
+
58
+ public override now(): number {
59
+ return this.currentTimeMs;
60
+ }
61
+
62
+ /** Sets the current time to the given timestamp in milliseconds. */
63
+ public setTime(timeMs: number) {
64
+ this.currentTimeMs = timeMs;
65
+ }
66
+
67
+ /** Advances the time by the given number of seconds. */
68
+ public advanceTime(seconds: number) {
69
+ this.currentTimeMs += seconds * 1000;
70
+ }
71
+
72
+ /** Advances the time by the given number of milliseconds. */
73
+ public advanceTimeMs(ms: number) {
74
+ this.currentTimeMs += ms;
75
+ }
34
76
  }
@@ -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;
@@ -94,7 +94,7 @@ export class MembershipWitness<N extends number> {
94
94
  static fromBuffer<N extends number>(buffer: Buffer | BufferReader, size: N): MembershipWitness<N> {
95
95
  const reader = BufferReader.asReader(buffer);
96
96
  const leafIndex = toBigIntBE(reader.readBytes(32));
97
- const siblingPath = reader.readArray(size, Fr);
97
+ const siblingPath = reader.readArray(size, Fr) as Tuple<Fr, N>;
98
98
  return new MembershipWitness(size, leafIndex, siblingPath);
99
99
  }
100
100
 
@@ -108,7 +108,7 @@ export class MembershipWitness<N extends number> {
108
108
  fromBuffer: (buffer: Buffer | BufferReader) => {
109
109
  const reader = BufferReader.asReader(buffer);
110
110
  const leafIndex = toBigIntBE(reader.readBytes(32));
111
- const siblingPath = reader.readArray(size, Fr);
111
+ const siblingPath = reader.readArray(size, Fr) as Tuple<Fr, N>;
112
112
  return new MembershipWitness(size, leafIndex, siblingPath);
113
113
  },
114
114
  };
@@ -24,6 +24,11 @@ export function isDefined<T>(value: T | undefined): value is T {
24
24
  return value !== undefined;
25
25
  }
26
26
 
27
+ /** Type guard for error classes */
28
+ export function isErrorClass<T extends Error>(value: unknown, errorClass: new (...args: any[]) => T): value is T {
29
+ return value instanceof errorClass || (value instanceof Error && value.name === errorClass.name);
30
+ }
31
+
27
32
  /** Resolves a record-like type. Lifted from viem. */
28
33
  export type Prettify<T> = {
29
34
  [K in keyof T]: T[K];