@aztec/foundation 0.0.1-commit.8c0b8ff → 0.0.1-commit.8cb2d04d8

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 (150) hide show
  1. package/dest/branded-types/buffer32_hash.d.ts +24 -0
  2. package/dest/branded-types/buffer32_hash.d.ts.map +1 -0
  3. package/dest/branded-types/buffer32_hash.js +19 -0
  4. package/dest/branded-types/checkpoint_number.d.ts +4 -1
  5. package/dest/branded-types/checkpoint_number.d.ts.map +1 -1
  6. package/dest/branded-types/checkpoint_number.js +3 -0
  7. package/dest/branded-types/index.d.ts +2 -1
  8. package/dest/branded-types/index.d.ts.map +1 -1
  9. package/dest/branded-types/index.js +1 -0
  10. package/dest/buffer/buffer16.d.ts +3 -1
  11. package/dest/buffer/buffer16.d.ts.map +1 -1
  12. package/dest/buffer/buffer32.d.ts +28 -61
  13. package/dest/buffer/buffer32.d.ts.map +1 -1
  14. package/dest/buffer/buffer32.js +26 -60
  15. package/dest/collection/index.d.ts +2 -1
  16. package/dest/collection/index.d.ts.map +1 -1
  17. package/dest/collection/index.js +1 -0
  18. package/dest/collection/lru_set.d.ts +35 -0
  19. package/dest/collection/lru_set.d.ts.map +1 -0
  20. package/dest/collection/lru_set.js +95 -0
  21. package/dest/config/env_var.d.ts +2 -2
  22. package/dest/config/env_var.d.ts.map +1 -1
  23. package/dest/config/index.d.ts +48 -30
  24. package/dest/config/index.d.ts.map +1 -1
  25. package/dest/config/index.js +21 -30
  26. package/dest/config/network_config.d.ts +6 -6
  27. package/dest/config/network_config.js +2 -2
  28. package/dest/config/network_name.d.ts +2 -2
  29. package/dest/config/network_name.d.ts.map +1 -1
  30. package/dest/config/network_name.js +2 -0
  31. package/dest/crypto/aes128/index.d.ts +2 -1
  32. package/dest/crypto/aes128/index.d.ts.map +1 -1
  33. package/dest/crypto/aes128/index.js +11 -2
  34. package/dest/crypto/bls/bn254_keystore.d.ts +1 -10
  35. package/dest/crypto/bls/bn254_keystore.d.ts.map +1 -1
  36. package/dest/crypto/bls/bn254_keystore.js +0 -17
  37. package/dest/curves/bls12/field.d.ts +1 -1
  38. package/dest/curves/bls12/field.d.ts.map +1 -1
  39. package/dest/curves/bls12/field.js +0 -5
  40. package/dest/curves/bn254/field.d.ts +17 -16
  41. package/dest/curves/bn254/field.d.ts.map +1 -1
  42. package/dest/curves/bn254/field.js +18 -13
  43. package/dest/eth-address/index.d.ts +1 -1
  44. package/dest/eth-address/index.d.ts.map +1 -1
  45. package/dest/eth-address/index.js +0 -3
  46. package/dest/fifo/fifo_frame_reader.d.ts +41 -0
  47. package/dest/fifo/fifo_frame_reader.d.ts.map +1 -0
  48. package/dest/fifo/fifo_frame_reader.js +74 -0
  49. package/dest/fifo/index.d.ts +2 -0
  50. package/dest/fifo/index.d.ts.map +1 -0
  51. package/dest/fifo/index.js +1 -0
  52. package/dest/jest/setup.js +24 -0
  53. package/dest/json-rpc/client/fetch.d.ts +1 -1
  54. package/dest/json-rpc/client/fetch.d.ts.map +1 -1
  55. package/dest/json-rpc/client/fetch.js +4 -3
  56. package/dest/json-rpc/client/undici.d.ts +1 -1
  57. package/dest/json-rpc/client/undici.d.ts.map +1 -1
  58. package/dest/json-rpc/client/undici.js +5 -3
  59. package/dest/log/pino-logger.d.ts +1 -1
  60. package/dest/log/pino-logger.d.ts.map +1 -1
  61. package/dest/log/pino-logger.js +17 -2
  62. package/dest/queue/batch_queue.d.ts +1 -1
  63. package/dest/queue/batch_queue.d.ts.map +1 -1
  64. package/dest/queue/batch_queue.js +1 -0
  65. package/dest/retry/index.d.ts +12 -1
  66. package/dest/retry/index.d.ts.map +1 -1
  67. package/dest/retry/index.js +21 -0
  68. package/dest/serialize/buffer_reader.d.ts +7 -20
  69. package/dest/serialize/buffer_reader.d.ts.map +1 -1
  70. package/dest/serialize/buffer_reader.js +5 -18
  71. package/dest/serialize/field_reader.d.ts +5 -13
  72. package/dest/serialize/field_reader.d.ts.map +1 -1
  73. package/dest/serialize/field_reader.js +0 -13
  74. package/dest/sleep/index.d.ts +2 -1
  75. package/dest/sleep/index.d.ts.map +1 -1
  76. package/dest/sleep/index.js +10 -1
  77. package/dest/string/index.js +1 -1
  78. package/dest/timer/date.d.ts +3 -1
  79. package/dest/timer/date.d.ts.map +1 -1
  80. package/dest/timer/date.js +4 -0
  81. package/dest/transport/dispatch/create_dispatch_proxy.d.ts +11 -2
  82. package/dest/transport/dispatch/create_dispatch_proxy.d.ts.map +1 -1
  83. package/dest/transport/index.d.ts +1 -2
  84. package/dest/transport/index.d.ts.map +1 -1
  85. package/dest/transport/index.js +0 -1
  86. package/dest/trees/balanced_merkle_tree_root.d.ts +2 -3
  87. package/dest/trees/balanced_merkle_tree_root.d.ts.map +1 -1
  88. package/dest/trees/balanced_merkle_tree_root.js +2 -3
  89. package/dest/trees/hasher.d.ts +3 -2
  90. package/dest/trees/hasher.d.ts.map +1 -1
  91. package/dest/trees/hasher.js +5 -5
  92. package/dest/trees/indexed_merkle_tree_calculator.d.ts +1 -1
  93. package/dest/trees/indexed_merkle_tree_calculator.d.ts.map +1 -1
  94. package/dest/trees/indexed_merkle_tree_calculator.js +5 -1
  95. package/dest/trees/merkle_tree_calculator.d.ts +4 -2
  96. package/dest/trees/merkle_tree_calculator.d.ts.map +1 -1
  97. package/dest/trees/merkle_tree_calculator.js +1 -5
  98. package/dest/trees/sibling_path.d.ts +2 -2
  99. package/dest/trees/sibling_path.d.ts.map +1 -1
  100. package/dest/trees/sibling_path.js +1 -5
  101. package/dest/trees/unbalanced_merkle_tree_root.d.ts +2 -3
  102. package/dest/trees/unbalanced_merkle_tree_root.d.ts.map +1 -1
  103. package/dest/trees/unbalanced_merkle_tree_root.js +2 -3
  104. package/package.json +3 -2
  105. package/src/branded-types/buffer32_hash.ts +42 -0
  106. package/src/branded-types/checkpoint_number.ts +5 -0
  107. package/src/branded-types/index.ts +1 -0
  108. package/src/buffer/buffer16.ts +3 -0
  109. package/src/buffer/buffer32.ts +36 -65
  110. package/src/collection/index.ts +1 -0
  111. package/src/collection/lru_set.ts +115 -0
  112. package/src/config/env_var.ts +12 -7
  113. package/src/config/index.ts +96 -84
  114. package/src/config/network_config.ts +1 -1
  115. package/src/config/network_name.ts +4 -1
  116. package/src/crypto/aes128/index.ts +11 -2
  117. package/src/crypto/bls/bn254_keystore.ts +0 -23
  118. package/src/curves/bls12/field.ts +0 -7
  119. package/src/curves/bn254/field.ts +25 -31
  120. package/src/eth-address/index.ts +0 -4
  121. package/src/fifo/fifo_frame_reader.ts +98 -0
  122. package/src/fifo/index.ts +1 -0
  123. package/src/jest/setup.mjs +27 -0
  124. package/src/json-rpc/client/fetch.ts +4 -3
  125. package/src/json-rpc/client/undici.ts +5 -3
  126. package/src/log/pino-logger.ts +19 -2
  127. package/src/queue/batch_queue.ts +1 -0
  128. package/src/retry/index.ts +30 -0
  129. package/src/serialize/buffer_reader.ts +6 -29
  130. package/src/serialize/field_reader.ts +4 -22
  131. package/src/sleep/index.ts +10 -1
  132. package/src/string/index.ts +1 -1
  133. package/src/timer/date.ts +6 -0
  134. package/src/transport/dispatch/create_dispatch_proxy.ts +11 -1
  135. package/src/transport/index.ts +0 -1
  136. package/src/trees/balanced_merkle_tree_root.ts +2 -5
  137. package/src/trees/hasher.ts +6 -3
  138. package/src/trees/indexed_merkle_tree_calculator.ts +5 -1
  139. package/src/trees/membership_witness.ts +2 -2
  140. package/src/trees/merkle_tree_calculator.ts +4 -10
  141. package/src/trees/sibling_path.ts +1 -2
  142. package/src/trees/unbalanced_merkle_tree_root.ts +2 -5
  143. package/dest/crypto/serialize.d.ts +0 -51
  144. package/dest/crypto/serialize.d.ts.map +0 -1
  145. package/dest/crypto/serialize.js +0 -68
  146. package/dest/transport/dispatch/create_dispatch_fn.d.ts +0 -25
  147. package/dest/transport/dispatch/create_dispatch_fn.d.ts.map +0 -1
  148. package/dest/transport/dispatch/create_dispatch_fn.js +0 -17
  149. package/src/crypto/serialize.ts +0 -85
  150. package/src/transport/dispatch/create_dispatch_fn.ts +0 -35
@@ -43,17 +43,18 @@ export async function defaultFetch(
43
43
  }
44
44
 
45
45
  let responseJson;
46
+ const responseText = await resp.text();
46
47
  try {
47
- responseJson = await resp.json();
48
+ responseJson = JSON.parse(responseText);
48
49
  } catch {
49
50
  if (!resp.ok) {
50
51
  throw new Error(resp.statusText);
51
52
  }
52
- throw new Error(`Failed to parse body as JSON: ${await resp.text()}`);
53
+ throw new Error(`Failed to parse body as JSON: ${responseText}`);
53
54
  }
54
55
 
55
56
  if (!resp.ok) {
56
- const errorMessage = `Error ${resp.status} from server ${host}: ${responseJson.error.message}`;
57
+ const errorMessage = `Error ${resp.status} from server ${host}: ${responseJson?.error?.message ?? JSON.stringify(responseJson)}`;
57
58
  if (noRetry || (resp.status >= 400 && resp.status < 500)) {
58
59
  throw new NoRetryError(errorMessage);
59
60
  } else {
@@ -44,18 +44,20 @@ export function makeUndiciFetch(client = new Agent()): JsonRpcFetch {
44
44
  let responseJson: any;
45
45
  const responseOk = resp.statusCode >= 200 && resp.statusCode <= 299;
46
46
  const contentEncoding = resp.headers['content-encoding'];
47
+ let responseText: string;
47
48
  try {
48
49
  if (contentEncoding === 'gzip') {
49
50
  const jsonBuffer = await gunzip(await resp.body.arrayBuffer());
50
- responseJson = JSON.parse(jsonBuffer.toString('utf-8'));
51
+ responseText = jsonBuffer.toString('utf-8');
51
52
  } else {
52
- responseJson = await resp.body.json();
53
+ responseText = await resp.body.text();
53
54
  }
55
+ responseJson = JSON.parse(responseText);
54
56
  } catch {
55
57
  if (!responseOk) {
56
58
  throw new Error('HTTP ' + resp.statusCode);
57
59
  }
58
- throw new Error(`Failed to parse body as JSON. encoding: ${contentEncoding}, body: ${await resp.body.text()}`);
60
+ throw new Error(`Failed to parse body as JSON. encoding: ${contentEncoding}, body: ${responseText!}`);
59
61
  }
60
62
 
61
63
  if (!responseOk) {
@@ -21,6 +21,8 @@ export type LoggerBindings = {
21
21
  instanceId?: string;
22
22
  };
23
23
 
24
+ const MAX_MODULE_NAME_LENGTH = 256;
25
+
24
26
  // Allow global hooks for providing default bindings.
25
27
  // Used by withLoggerBindings in pino-logger-server to propagate bindings via AsyncLocalStorage.
26
28
  type LogBindingsHandler = () => LoggerBindings | undefined;
@@ -48,7 +50,7 @@ function getBindingsFromHandlers(): LoggerBindings | undefined {
48
50
  }
49
51
 
50
52
  export function createLogger(module: string, bindings?: LoggerBindings): Logger {
51
- module = module.replace(/^aztec:/, '');
53
+ module = module.slice(0, MAX_MODULE_NAME_LENGTH).replace(/^aztec:/, '');
52
54
 
53
55
  const resolvedBindings = { ...getBindingsFromHandlers(), ...bindings };
54
56
  const actor = resolvedBindings?.actor;
@@ -375,5 +377,20 @@ export type Logger = { [K in LogLevel]: LogFn } & { /** Error log function */ er
375
377
  * @returns A string with both the log message and the error message.
376
378
  */
377
379
  function formatErr(msg: string, err?: unknown): string {
378
- 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
+ }
379
396
  }
@@ -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.
@@ -286,39 +286,16 @@ export class BufferReader {
286
286
  }
287
287
 
288
288
  /**
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.
289
+ * Read an array of a fixed size with elements of type T from the buffer.
290
+ * The 'itemDeserializer' object should have a 'fromBuffer' method that takes a BufferReader instance as input,
291
+ * and returns an instance of the desired deserialized data type T.
292
+ * This method will call the 'fromBuffer' method for each element in the array and return the resulting array.
291
293
  *
292
- * @param size - The number of elements to read.
294
+ * @param size - The fixed number of elements in the array.
293
295
  * @param itemDeserializer - An object with a 'fromBuffer' method to deserialize individual elements of type T.
294
296
  * @returns An array of instances of type T.
295
297
  */
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>(
298
+ public readArray<T, N extends number>(
322
299
  size: N,
323
300
  itemDeserializer: {
324
301
  /**
@@ -169,30 +169,12 @@ 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
- /**
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>(
172
+ public readArray<T, N extends number>(
194
173
  size: N,
195
174
  itemDeserializer: {
175
+ /**
176
+ * A function for deserializing data from a FieldReader instance.
177
+ */
196
178
  fromFields: (reader: FieldReader) => T;
197
179
  },
198
180
  ): Tuple<T, N> {
@@ -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
@@ -32,6 +32,12 @@ export class TestDateProvider extends DateProvider {
32
32
  this.logger.warn(`Time set to ${new Date(timeMs).toISOString()}`, { offset: this.offset, timeMs });
33
33
  }
34
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
+
35
41
  /** Advances the time by the given number of seconds. */
36
42
  public advanceTime(seconds: number) {
37
43
  this.offset += seconds * 1000;
@@ -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';
@@ -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([
@@ -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) as Tuple<Fr, N>;
97
+ const siblingPath = reader.readArray(size, Fr);
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) as Tuple<Fr, N>;
111
+ const siblingPath = reader.readArray(size, Fr);
112
112
  return new MembershipWitness(size, leafIndex, siblingPath);
113
113
  },
114
114
  };
@@ -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) {
@@ -1,12 +1,9 @@
1
1
  import { computeBalancedMerkleTreeRoot, computeBalancedMerkleTreeRootAsync } from './balanced_merkle_tree_root.js';
2
- import { poseidonMerkleHash, shaMerkleHash } from './hasher.js';
2
+ import { shaMerkleHash } from './hasher.js';
3
3
  import { UnbalancedMerkleTreeCalculator } from './unbalanced_merkle_tree_calculator.js';
4
4
 
5
5
  export const computeUnbalancedShaRoot = (leaves: Buffer[]) => computeUnbalancedMerkleTreeRoot(leaves, shaMerkleHash);
6
6
 
7
- export const computeUnbalancedPoseidonRoot = async (leaves: Buffer[]) =>
8
- await computeUnbalancedMerkleTreeRootAsync(leaves, poseidonMerkleHash);
9
-
10
7
  export const computeWonkyShaRoot = (leaves: Buffer[]) => computeWonkyMerkleTreeRoot(leaves);
11
8
 
12
9
  /**
@@ -67,7 +64,7 @@ export function computeUnbalancedMerkleTreeRoot(
67
64
 
68
65
  export async function computeUnbalancedMerkleTreeRootAsync(
69
66
  leaves: Buffer[],
70
- hasher = poseidonMerkleHash,
67
+ hasher: (left: Uint8Array, right: Uint8Array) => Promise<Buffer<ArrayBuffer>>,
71
68
  emptyRoot = Buffer.alloc(32),
72
69
  ): Promise<Buffer> {
73
70
  if (!leaves.length) {
@@ -1,51 +0,0 @@
1
- import { Buffer } from 'buffer';
2
- /**
3
- * For serializing an array of fixed length buffers.
4
- * TODO move to foundation pkg.
5
- * @param arr - Array of bufffers.
6
- * @returns The serialized buffers.
7
- */
8
- export declare function serializeBufferArrayToVector(arr: Buffer[]): Buffer<ArrayBuffer>;
9
- /**
10
- * Helper function for deserializeArrayFromVector.
11
- */
12
- type DeserializeFn<T> = (buf: Buffer, offset: number) => {
13
- /**
14
- * The deserialized type.
15
- */
16
- elem: T;
17
- /**
18
- * How many bytes to advance by.
19
- */
20
- adv: number;
21
- };
22
- /**
23
- * For deserializing numbers to 32-bit little-endian form.
24
- * TODO move to foundation pkg.
25
- * @param n - The number.
26
- * @returns The endian-corrected number.
27
- */
28
- export declare function deserializeArrayFromVector<T>(deserialize: DeserializeFn<T>, vector: Buffer, offset?: number): {
29
- elem: T[];
30
- adv: number;
31
- };
32
- /**
33
- * For serializing numbers to 32 bit little-endian form.
34
- * TODO move to foundation pkg.
35
- * @param n - The number.
36
- * @returns The endian-corrected number.
37
- */
38
- export declare function numToUInt32LE(n: number, bufferSize?: number): Buffer<ArrayBuffer>;
39
- /**
40
- * Deserialize the 256-bit number at address `offset`.
41
- * @param buf - The buffer.
42
- * @param offset - The address.
43
- * @returns The derserialized 256-bit field.
44
- */
45
- export declare function deserializeField(buf: Buffer, offset?: number): {
46
- elem: Buffer<ArrayBuffer>;
47
- adv: number;
48
- };
49
- export declare function concatenateUint8Arrays(arrayOfUint8Arrays: Uint8Array[]): Uint8Array<ArrayBuffer>;
50
- export {};
51
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2VyaWFsaXplLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvY3J5cHRvL3NlcmlhbGl6ZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFFQSxPQUFPLEVBQUUsTUFBTSxFQUFFLE1BQU0sUUFBUSxDQUFDO0FBRWhDOzs7OztHQUtHO0FBQ0gsd0JBQWdCLDRCQUE0QixDQUFDLEdBQUcsRUFBRSxNQUFNLEVBQUUsdUJBSXpEO0FBRUQ7O0dBRUc7QUFDSCxLQUFLLGFBQWEsQ0FBQyxDQUFDLElBQUksQ0FDdEIsR0FBRyxFQUFFLE1BQU0sRUFDWCxNQUFNLEVBQUUsTUFBTSxLQUNYO0lBQ0g7O09BRUc7SUFDSCxJQUFJLEVBQUUsQ0FBQyxDQUFDO0lBQ1I7O09BRUc7SUFDSCxHQUFHLEVBQUUsTUFBTSxDQUFDO0NBQ2IsQ0FBQztBQUVGOzs7OztHQUtHO0FBQ0gsd0JBQWdCLDBCQUEwQixDQUFDLENBQUMsRUFBRSxXQUFXLEVBQUUsYUFBYSxDQUFDLENBQUMsQ0FBQyxFQUFFLE1BQU0sRUFBRSxNQUFNLEVBQUUsTUFBTSxTQUFJOzs7RUFXdEc7QUFFRDs7Ozs7R0FLRztBQUNILHdCQUFnQixhQUFhLENBQUMsQ0FBQyxFQUFFLE1BQU0sRUFBRSxVQUFVLFNBQUksdUJBSXREO0FBRUQ7Ozs7O0dBS0c7QUFDSCx3QkFBZ0IsZ0JBQWdCLENBQUMsR0FBRyxFQUFFLE1BQU0sRUFBRSxNQUFNLFNBQUk7OztFQUd2RDtBQUVELHdCQUFnQixzQkFBc0IsQ0FBQyxrQkFBa0IsRUFBRSxVQUFVLEVBQUUsMkJBU3RFIn0=
@@ -1 +0,0 @@
1
- {"version":3,"file":"serialize.d.ts","sourceRoot":"","sources":["../../src/crypto/serialize.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC;;;;;GAKG;AACH,wBAAgB,4BAA4B,CAAC,GAAG,EAAE,MAAM,EAAE,uBAIzD;AAED;;GAEG;AACH,KAAK,aAAa,CAAC,CAAC,IAAI,CACtB,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,MAAM,KACX;IACH;;OAEG;IACH,IAAI,EAAE,CAAC,CAAC;IACR;;OAEG;IACH,GAAG,EAAE,MAAM,CAAC;CACb,CAAC;AAEF;;;;;GAKG;AACH,wBAAgB,0BAA0B,CAAC,CAAC,EAAE,WAAW,EAAE,aAAa,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,SAAI;;;EAWtG;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,CAAC,EAAE,MAAM,EAAE,UAAU,SAAI,uBAItD;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,SAAI;;;EAGvD;AAED,wBAAgB,sBAAsB,CAAC,kBAAkB,EAAE,UAAU,EAAE,2BAStE"}
@@ -1,68 +0,0 @@
1
- // TODO find a new home for this as we move to external bb.js
2
- // See https://github.com/AztecProtocol/aztec-packages/issues/782
3
- import { Buffer } from 'buffer';
4
- /**
5
- * For serializing an array of fixed length buffers.
6
- * TODO move to foundation pkg.
7
- * @param arr - Array of bufffers.
8
- * @returns The serialized buffers.
9
- */ export function serializeBufferArrayToVector(arr) {
10
- const lengthBuf = Buffer.alloc(4);
11
- lengthBuf.writeUInt32BE(arr.length, 0);
12
- return Buffer.concat([
13
- lengthBuf,
14
- ...arr
15
- ]);
16
- }
17
- /**
18
- * For deserializing numbers to 32-bit little-endian form.
19
- * TODO move to foundation pkg.
20
- * @param n - The number.
21
- * @returns The endian-corrected number.
22
- */ export function deserializeArrayFromVector(deserialize, vector, offset = 0) {
23
- let pos = offset;
24
- const size = vector.readUInt32BE(pos);
25
- pos += 4;
26
- const arr = new Array(size);
27
- for(let i = 0; i < size; ++i){
28
- const { elem, adv } = deserialize(vector, pos);
29
- pos += adv;
30
- arr[i] = elem;
31
- }
32
- return {
33
- elem: arr,
34
- adv: pos - offset
35
- };
36
- }
37
- /**
38
- * For serializing numbers to 32 bit little-endian form.
39
- * TODO move to foundation pkg.
40
- * @param n - The number.
41
- * @returns The endian-corrected number.
42
- */ export function numToUInt32LE(n, bufferSize = 4) {
43
- const buf = Buffer.alloc(bufferSize);
44
- buf.writeUInt32LE(n, bufferSize - 4);
45
- return buf;
46
- }
47
- /**
48
- * Deserialize the 256-bit number at address `offset`.
49
- * @param buf - The buffer.
50
- * @param offset - The address.
51
- * @returns The derserialized 256-bit field.
52
- */ export function deserializeField(buf, offset = 0) {
53
- const adv = 32;
54
- return {
55
- elem: buf.slice(offset, offset + adv),
56
- adv
57
- };
58
- }
59
- export function concatenateUint8Arrays(arrayOfUint8Arrays) {
60
- const totalLength = arrayOfUint8Arrays.reduce((prev, curr)=>prev + curr.length, 0);
61
- const result = new Uint8Array(totalLength);
62
- let length = 0;
63
- for (const array of arrayOfUint8Arrays){
64
- result.set(array, length);
65
- length += array.length;
66
- }
67
- return result;
68
- }
@@ -1,25 +0,0 @@
1
- /**
2
- * Represents a message object for dispatching function calls.
3
- * Contains the function name ('fn') and an array of arguments ('args') required to call the target method.
4
- */
5
- export interface DispatchMsg {
6
- /**
7
- * Name of the target method to be called.
8
- */
9
- fn: string;
10
- /**
11
- * An array of arguments to be passed to the target method.
12
- */
13
- args: any[];
14
- }
15
- /**
16
- * Creates a dispatch function that calls the target's specified method with provided arguments.
17
- * The created dispatch function takes a DispatchMsg object as input, which contains the name of
18
- * the method to be called ('fn') and an array of arguments to be passed to the method ('args').
19
- *
20
- * @param targetFn - A function that returns the target object containing the methods to be dispatched.
21
- * @param log - Optional logging function for debugging purposes.
22
- * @returns A dispatch function that accepts a DispatchMsg object and calls the target's method with provided arguments.
23
- */
24
- export declare function createDispatchFn(targetFn: () => any, log?: import("../../log/pino-logger.js").Logger): ({ fn, args }: DispatchMsg) => Promise<any>;
25
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY3JlYXRlX2Rpc3BhdGNoX2ZuLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvdHJhbnNwb3J0L2Rpc3BhdGNoL2NyZWF0ZV9kaXNwYXRjaF9mbi50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFJQTs7O0dBR0c7QUFDSCxNQUFNLFdBQVcsV0FBVztJQUMxQjs7T0FFRztJQUNILEVBQUUsRUFBRSxNQUFNLENBQUM7SUFDWDs7T0FFRztJQUNILElBQUksRUFBRSxHQUFHLEVBQUUsQ0FBQztDQUNiO0FBRUQ7Ozs7Ozs7O0dBUUc7QUFDSCx3QkFBZ0IsZ0JBQWdCLENBQUMsUUFBUSxFQUFFLE1BQU0sR0FBRyxFQUFFLEdBQUcsNENBQXNDLCtDQU05RiJ9
@@ -1 +0,0 @@
1
- {"version":3,"file":"create_dispatch_fn.d.ts","sourceRoot":"","sources":["../../../src/transport/dispatch/create_dispatch_fn.ts"],"names":[],"mappings":"AAIA;;;GAGG;AACH,MAAM,WAAW,WAAW;IAC1B;;OAEG;IACH,EAAE,EAAE,MAAM,CAAC;IACX;;OAEG;IACH,IAAI,EAAE,GAAG,EAAE,CAAC;CACb;AAED;;;;;;;;GAQG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,EAAE,GAAG,4CAAsC,+CAM9F"}
@@ -1,17 +0,0 @@
1
- import { format } from 'util';
2
- import { createLogger } from '../../log/index.js';
3
- /**
4
- * Creates a dispatch function that calls the target's specified method with provided arguments.
5
- * The created dispatch function takes a DispatchMsg object as input, which contains the name of
6
- * the method to be called ('fn') and an array of arguments to be passed to the method ('args').
7
- *
8
- * @param targetFn - A function that returns the target object containing the methods to be dispatched.
9
- * @param log - Optional logging function for debugging purposes.
10
- * @returns A dispatch function that accepts a DispatchMsg object and calls the target's method with provided arguments.
11
- */ export function createDispatchFn(targetFn, log = createLogger('foundation:dispatch')) {
12
- return async ({ fn, args })=>{
13
- const target = targetFn();
14
- log.debug(format(`dispatching to ${target}: ${fn}`, args));
15
- return await target[fn](...args);
16
- };
17
- }