@aztec/foundation 0.0.1-commit.d117d021b → 0.0.1-commit.d1da697d6

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 (95) hide show
  1. package/dest/branded-types/slot.d.ts +4 -1
  2. package/dest/branded-types/slot.d.ts.map +1 -1
  3. package/dest/branded-types/slot.js +3 -0
  4. package/dest/buffer/buffer16.d.ts +3 -1
  5. package/dest/buffer/buffer16.d.ts.map +1 -1
  6. package/dest/buffer/buffer32.d.ts +3 -1
  7. package/dest/buffer/buffer32.d.ts.map +1 -1
  8. package/dest/buffer/index.d.ts +2 -1
  9. package/dest/buffer/index.d.ts.map +1 -1
  10. package/dest/buffer/index.js +1 -0
  11. package/dest/buffer/utils.d.ts +3 -0
  12. package/dest/buffer/utils.d.ts.map +1 -0
  13. package/dest/buffer/utils.js +7 -0
  14. package/dest/collection/array.d.ts +3 -1
  15. package/dest/collection/array.d.ts.map +1 -1
  16. package/dest/collection/array.js +15 -0
  17. package/dest/collection/index.d.ts +2 -1
  18. package/dest/collection/index.d.ts.map +1 -1
  19. package/dest/collection/index.js +1 -0
  20. package/dest/collection/lru_set.d.ts +35 -0
  21. package/dest/collection/lru_set.d.ts.map +1 -0
  22. package/dest/collection/lru_set.js +95 -0
  23. package/dest/config/env_var.d.ts +2 -2
  24. package/dest/config/env_var.d.ts.map +1 -1
  25. package/dest/config/network_config.d.ts +7 -1
  26. package/dest/config/network_config.d.ts.map +1 -1
  27. package/dest/config/network_config.js +1 -0
  28. package/dest/crypto/aes128/index.d.ts +2 -1
  29. package/dest/crypto/aes128/index.d.ts.map +1 -1
  30. package/dest/crypto/aes128/index.js +11 -2
  31. package/dest/crypto/bls/bn254_keystore.d.ts +1 -10
  32. package/dest/crypto/bls/bn254_keystore.d.ts.map +1 -1
  33. package/dest/crypto/bls/bn254_keystore.js +0 -17
  34. package/dest/crypto/poseidon/index.d.ts +1 -1
  35. package/dest/crypto/poseidon/index.d.ts.map +1 -1
  36. package/dest/crypto/poseidon/index.js +40 -33
  37. package/dest/curves/grumpkin/point.d.ts +1 -1
  38. package/dest/curves/grumpkin/point.js +1 -1
  39. package/dest/fifo/fifo_frame_reader.d.ts +41 -0
  40. package/dest/fifo/fifo_frame_reader.d.ts.map +1 -0
  41. package/dest/fifo/fifo_frame_reader.js +74 -0
  42. package/dest/fifo/index.d.ts +2 -0
  43. package/dest/fifo/index.d.ts.map +1 -0
  44. package/dest/fifo/index.js +1 -0
  45. package/dest/json-rpc/client/fetch.d.ts +1 -1
  46. package/dest/json-rpc/client/fetch.d.ts.map +1 -1
  47. package/dest/json-rpc/client/fetch.js +4 -3
  48. package/dest/log/pino-logger.d.ts +1 -1
  49. package/dest/log/pino-logger.d.ts.map +1 -1
  50. package/dest/log/pino-logger.js +2 -1
  51. package/dest/retry/index.d.ts +12 -1
  52. package/dest/retry/index.d.ts.map +1 -1
  53. package/dest/retry/index.js +21 -0
  54. package/dest/schemas/api.d.ts +2 -2
  55. package/dest/schemas/api.d.ts.map +1 -1
  56. package/dest/transport/dispatch/create_dispatch_proxy.d.ts +11 -2
  57. package/dest/transport/dispatch/create_dispatch_proxy.d.ts.map +1 -1
  58. package/dest/transport/index.d.ts +1 -2
  59. package/dest/transport/index.d.ts.map +1 -1
  60. package/dest/transport/index.js +0 -1
  61. package/dest/trees/indexed_merkle_tree_calculator.d.ts +1 -1
  62. package/dest/trees/indexed_merkle_tree_calculator.d.ts.map +1 -1
  63. package/dest/trees/indexed_merkle_tree_calculator.js +5 -1
  64. package/package.json +3 -2
  65. package/src/branded-types/slot.ts +5 -0
  66. package/src/buffer/buffer16.ts +3 -0
  67. package/src/buffer/buffer32.ts +3 -0
  68. package/src/buffer/index.ts +1 -0
  69. package/src/buffer/utils.ts +8 -0
  70. package/src/collection/array.ts +14 -0
  71. package/src/collection/index.ts +1 -0
  72. package/src/collection/lru_set.ts +115 -0
  73. package/src/config/env_var.ts +11 -2
  74. package/src/config/network_config.ts +1 -0
  75. package/src/crypto/aes128/index.ts +11 -2
  76. package/src/crypto/bls/bn254_keystore.ts +0 -23
  77. package/src/crypto/poseidon/index.ts +42 -34
  78. package/src/curves/grumpkin/point.ts +1 -1
  79. package/src/fifo/fifo_frame_reader.ts +98 -0
  80. package/src/fifo/index.ts +1 -0
  81. package/src/json-rpc/client/fetch.ts +4 -3
  82. package/src/log/pino-logger.ts +3 -1
  83. package/src/retry/index.ts +30 -0
  84. package/src/schemas/api.ts +4 -1
  85. package/src/transport/dispatch/create_dispatch_proxy.ts +11 -1
  86. package/src/transport/index.ts +0 -1
  87. package/src/trees/indexed_merkle_tree_calculator.ts +5 -1
  88. package/dest/crypto/serialize.d.ts +0 -51
  89. package/dest/crypto/serialize.d.ts.map +0 -1
  90. package/dest/crypto/serialize.js +0 -68
  91. package/dest/transport/dispatch/create_dispatch_fn.d.ts +0 -25
  92. package/dest/transport/dispatch/create_dispatch_fn.d.ts.map +0 -1
  93. package/dest/transport/dispatch/create_dispatch_fn.js +0 -17
  94. package/src/crypto/serialize.ts +0 -85
  95. package/src/transport/dispatch/create_dispatch_fn.ts +0 -35
@@ -1 +1 @@
1
- {"version":3,"file":"indexed_merkle_tree_calculator.d.ts","sourceRoot":"","sources":["../../src/trees/indexed_merkle_tree_calculator.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAEvE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAE7D,UAAU,mBAAmB,CAAC,CAAC,SAAS,uBAAuB;IAC7D,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,CAAC,CAAC;CAC/B;AAED;;GAEG;AACH,qBAAa,2BAA2B,CAAC,CAAC,SAAS,uBAAuB,EAAE,CAAC,SAAS,MAAM;IAExF,OAAO,CAAC,MAAM;IACd,OAAO,CAAC,UAAU;IAClB,OAAO,CAAC,MAAM;IACd,OAAO,CAAC,OAAO;IAJjB,OAAO,eAKH;IAEJ,OAAa,MAAM,CAAC,CAAC,SAAS,uBAAuB,EAAE,CAAC,SAAS,MAAM,EACrE,MAAM,EAAE,CAAC,EACT,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,mBAAmB,CAAC,CAAC,CAAC,EAC/B,QAAQ,sBAAmB,8CAO5B;IAEK,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAqCpE;IAEK,eAAe,CAAC,MAAM,GAAE,MAAM,EAAO,GAAG,OAAO,CAAC,MAAM,CAAC,CAkB5D;CACF"}
1
+ {"version":3,"file":"indexed_merkle_tree_calculator.d.ts","sourceRoot":"","sources":["../../src/trees/indexed_merkle_tree_calculator.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAEvE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAE7D,UAAU,mBAAmB,CAAC,CAAC,SAAS,uBAAuB;IAC7D,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,CAAC,CAAC;CAC/B;AAED;;GAEG;AACH,qBAAa,2BAA2B,CAAC,CAAC,SAAS,uBAAuB,EAAE,CAAC,SAAS,MAAM;IAExF,OAAO,CAAC,MAAM;IACd,OAAO,CAAC,UAAU;IAClB,OAAO,CAAC,MAAM;IACd,OAAO,CAAC,OAAO;IAJjB,OAAO,eAKH;IAEJ,OAAa,MAAM,CAAC,CAAC,SAAS,uBAAuB,EAAE,CAAC,SAAS,MAAM,EACrE,MAAM,EAAE,CAAC,EACT,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,mBAAmB,CAAC,CAAC,CAAC,EAC/B,QAAQ,sBAAmB,8CAO5B;IAEK,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAyCpE;IAEK,eAAe,CAAC,MAAM,GAAE,MAAM,EAAO,GAAG,OAAO,CAAC,MAAM,CAAC,CAkB5D;CACF"}
@@ -34,7 +34,11 @@ import { IndexedMerkleTree } from './indexed_merkle_tree.js';
34
34
  const sorted = values.map((v, i)=>({
35
35
  value: v,
36
36
  index: i
37
- })).sort((a, b)=>Number(toBigIntBE(b.value) - toBigIntBE(a.value)));
37
+ })).sort((a, b)=>{
38
+ const aBigInt = toBigIntBE(a.value);
39
+ const bBigInt = toBigIntBE(b.value);
40
+ return aBigInt < bBigInt ? 1 : aBigInt > bBigInt ? -1 : 0;
41
+ });
38
42
  const indexedLeaves = sorted.map((item, i)=>({
39
43
  leaf: this.factory.fromBuffer(Buffer.concat([
40
44
  item.value,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aztec/foundation",
3
- "version": "0.0.1-commit.d117d021b",
3
+ "version": "0.0.1-commit.d1da697d6",
4
4
  "type": "module",
5
5
  "main": "./dest/index.js",
6
6
  "types": "./dest/index.d.ts",
@@ -61,6 +61,7 @@
61
61
  "./eth-address": "./dest/eth-address/index.js",
62
62
  "./eth-signature": "./dest/eth-signature/index.js",
63
63
  "./queue": "./dest/queue/index.js",
64
+ "./fifo": "./dest/fifo/index.js",
64
65
  "./fs": "./dest/fs/index.js",
65
66
  "./buffer": "./dest/buffer/index.js",
66
67
  "./json-rpc": "./dest/json-rpc/index.js",
@@ -144,7 +145,7 @@
144
145
  "testEnvironment": "../../foundation/src/jest/env.mjs"
145
146
  },
146
147
  "dependencies": {
147
- "@aztec/bb.js": "0.0.1-commit.d117d021b",
148
+ "@aztec/bb.js": "0.0.1-commit.d1da697d6",
148
149
  "@koa/cors": "^5.0.0",
149
150
  "@noble/curves": "=1.7.0",
150
151
  "@noble/hashes": "^1.6.1",
@@ -73,6 +73,11 @@ SlotNumber.isValid = function (value: unknown): value is SlotNumber {
73
73
  return typeof value === 'number' && Number.isInteger(value) && value >= 0;
74
74
  };
75
75
 
76
+ /** Increments a SlotNumber by a given value. */
77
+ SlotNumber.add = function (sn: SlotNumber, increment: number): SlotNumber {
78
+ return SlotNumber(sn + increment);
79
+ };
80
+
76
81
  /**
77
82
  * The zero slot value.
78
83
  */
@@ -10,6 +10,9 @@ import { bufferToHex } from '../string/index.js';
10
10
  * A class representing a 16 byte Buffer.
11
11
  */
12
12
  export class Buffer16 {
13
+ /** Branding to prevent structural compatibility with Buffer32. */
14
+ declare readonly __brand: 'Buffer16';
15
+
13
16
  /**
14
17
  * The size of the hash in bytes.
15
18
  */
@@ -10,6 +10,9 @@ import { bufferToHex } from '../string/index.js';
10
10
  * A class representing a 32 byte Buffer.
11
11
  */
12
12
  export class Buffer32 {
13
+ /** Branding to prevent structural compatibility with Buffer16. */
14
+ declare readonly __brand: 'Buffer32';
15
+
13
16
  /**
14
17
  * The size of the hash in bytes.
15
18
  */
@@ -1,2 +1,3 @@
1
1
  export * from './buffer32.js';
2
2
  export * from './buffer16.js';
3
+ export * from './utils.js';
@@ -0,0 +1,8 @@
1
+ /** Returns the number of bytes in the buffer, excluding any trailing zero bytes. */
2
+ export function trimmedBytesLength(buf: Uint8Array): number {
3
+ let end = buf.length;
4
+ while (end > 0 && buf[end - 1] === 0) {
5
+ end--;
6
+ }
7
+ return end;
8
+ }
@@ -315,3 +315,17 @@ export function partition<T>(items: T[], predicate: (item: T) => boolean): [T[],
315
315
  }
316
316
  return [pass, fail];
317
317
  }
318
+
319
+ /** Partitions the given iterable into two arrays based on the predicate. */
320
+ export async function partitionAsync<T>(items: T[], predicate: (item: T) => Promise<boolean>): Promise<[T[], T[]]> {
321
+ const pass: T[] = [];
322
+ const fail: T[] = [];
323
+ for (const item of items) {
324
+ if (await predicate(item)) {
325
+ pass.push(item);
326
+ } else {
327
+ fail.push(item);
328
+ }
329
+ }
330
+ return [pass, fail];
331
+ }
@@ -1,2 +1,3 @@
1
1
  export * from './array.js';
2
+ export * from './lru_set.js';
2
3
  export * from './object.js';
@@ -0,0 +1,115 @@
1
+ /** Node in a doubly-linked list used by {@link LruSet}. */
2
+ type LruNode<T> = {
3
+ value: T;
4
+ prev: LruNode<T> | undefined;
5
+ next: LruNode<T> | undefined;
6
+ };
7
+
8
+ /**
9
+ * A bounded set with Least Recently Used (LRU) eviction.
10
+ * Both {@link has} and {@link add} count as an access and refresh the entry's
11
+ * recency, so items that are actively checked stay in the set longest.
12
+ *
13
+ * Uses a doubly-linked list for O(1) ordering and a Map for O(1) lookup.
14
+ * Head = least recent, tail = most recent.
15
+ */
16
+ export class LruSet<T> {
17
+ /** Map from value to its linked-list node for O(1) lookup. */
18
+ private readonly map = new Map<T, LruNode<T>>();
19
+ private head: LruNode<T> | undefined;
20
+ private tail: LruNode<T> | undefined;
21
+
22
+ constructor(private readonly maxSize: number) {
23
+ if (maxSize < 1) {
24
+ throw new Error('LruSet maxSize must be at least 1');
25
+ }
26
+ }
27
+
28
+ /** Number of entries in the set. */
29
+ get size(): number {
30
+ return this.map.size;
31
+ }
32
+
33
+ /**
34
+ * Returns true if the item is in the set.
35
+ * Refreshes the item's recency so it becomes the most recently used.
36
+ */
37
+ has(item: T): boolean {
38
+ const node = this.map.get(item);
39
+ if (!node) {
40
+ return false;
41
+ }
42
+ this.moveToTail(node);
43
+ return true;
44
+ }
45
+
46
+ /**
47
+ * Adds an item to the set. If the item already exists, refreshes its recency.
48
+ * If the set is at capacity, evicts the least recently used item.
49
+ */
50
+ add(item: T): void {
51
+ const existing = this.map.get(item);
52
+ if (existing) {
53
+ this.moveToTail(existing);
54
+ return;
55
+ }
56
+
57
+ if (this.map.size >= this.maxSize) {
58
+ this.evictHead();
59
+ }
60
+
61
+ const node: LruNode<T> = { value: item, prev: this.tail, next: undefined };
62
+ if (this.tail) {
63
+ this.tail.next = node;
64
+ } else {
65
+ this.head = node;
66
+ }
67
+ this.tail = node;
68
+ this.map.set(item, node);
69
+ }
70
+
71
+ /** Removes all entries from the set. */
72
+ clear(): void {
73
+ this.map.clear();
74
+ this.head = undefined;
75
+ this.tail = undefined;
76
+ }
77
+
78
+ /** Unlinks a node from its current position and relinks it at the tail. */
79
+ private moveToTail(node: LruNode<T>): void {
80
+ if (node === this.tail) {
81
+ return;
82
+ }
83
+
84
+ // Unlink
85
+ if (node.prev) {
86
+ node.prev.next = node.next;
87
+ } else {
88
+ this.head = node.next;
89
+ }
90
+ if (node.next) {
91
+ node.next.prev = node.prev;
92
+ }
93
+
94
+ // Relink at tail
95
+ node.prev = this.tail;
96
+ node.next = undefined;
97
+ if (this.tail) {
98
+ this.tail.next = node;
99
+ }
100
+ this.tail = node;
101
+ }
102
+
103
+ /** Evicts the head (least recently used) node. */
104
+ private evictHead(): void {
105
+ const oldHead = this.head!;
106
+ this.map.delete(oldHead.value);
107
+
108
+ this.head = oldHead.next;
109
+ if (this.head) {
110
+ this.head.prev = undefined;
111
+ } else {
112
+ this.tail = undefined;
113
+ }
114
+ }
115
+ }
@@ -23,6 +23,8 @@ export type EnvVar =
23
23
  | 'BB_WORKING_DIRECTORY'
24
24
  | 'BB_NUM_IVC_VERIFIERS'
25
25
  | 'BB_IVC_CONCURRENCY'
26
+ | 'BB_CHONK_VERIFY_MAX_BATCH'
27
+ | 'BB_CHONK_VERIFY_BATCH_CONCURRENCY'
26
28
  | 'BOOTSTRAP_NODES'
27
29
  | 'BLOB_ARCHIVE_API_URL'
28
30
  | 'BLOB_FILE_STORE_URLS'
@@ -81,6 +83,7 @@ export type EnvVar =
81
83
  | 'KEY_STORE_DIRECTORY'
82
84
  | 'L1_CHAIN_ID'
83
85
  | 'L1_CONSENSUS_HOST_URLS'
86
+ | 'ETHEREUM_HTTP_TIMEOUT_MS'
84
87
  | 'L1_CONSENSUS_HOST_API_KEYS'
85
88
  | 'L1_CONSENSUS_HOST_API_KEY_HEADERS'
86
89
  | 'L1_TX_FAILED_STORE'
@@ -130,6 +133,7 @@ export type EnvVar =
130
133
  | 'P2P_L2_QUEUE_SIZE'
131
134
  | 'P2P_MAX_PEERS'
132
135
  | 'P2P_PEER_CHECK_INTERVAL_MS'
136
+ | 'P2P_PEER_FAILED_BAN_TIME_MS'
133
137
  | 'P2P_PEER_PENALTY_VALUES'
134
138
  | 'P2P_QUERY_FOR_IP'
135
139
  | 'P2P_REQRESP_INDIVIDUAL_REQUEST_TIMEOUT_MS'
@@ -169,6 +173,7 @@ export type EnvVar =
169
173
  | 'PROVER_BROKER_MAX_EPOCHS_TO_KEEP_RESULTS_FOR'
170
174
  | 'PROVER_BROKER_DEBUG_REPLAY_ENABLED'
171
175
  | 'PROVER_CANCEL_JOBS_ON_STOP'
176
+ | 'PROVER_ENQUEUE_CONCURRENCY'
172
177
  | 'PROVER_COORDINATION_NODE_URLS'
173
178
  | 'PROVER_PROOF_STORE'
174
179
  | 'PROVER_FAILED_PROOF_STORE'
@@ -202,6 +207,7 @@ export type EnvVar =
202
207
  | 'SENTINEL_ENABLED'
203
208
  | 'SENTINEL_HISTORY_LENGTH_IN_EPOCHS'
204
209
  | 'SENTINEL_HISTORIC_PROVEN_PERFORMANCE_LENGTH_IN_EPOCHS'
210
+ | 'SEQ_ENABLE_PROPOSER_PIPELINING'
205
211
  | 'SEQ_MAX_TX_PER_BLOCK'
206
212
  | 'SEQ_MAX_TX_PER_CHECKPOINT'
207
213
  | 'SEQ_MIN_TX_PER_BLOCK'
@@ -209,11 +215,14 @@ export type EnvVar =
209
215
  | 'SEQ_MAX_DA_BLOCK_GAS'
210
216
  | 'SEQ_MAX_L2_BLOCK_GAS'
211
217
  | 'SEQ_PER_BLOCK_ALLOCATION_MULTIPLIER'
218
+ | 'SEQ_REDISTRIBUTE_CHECKPOINT_BUDGET'
212
219
  | 'SEQ_PUBLISHER_PRIVATE_KEY'
213
220
  | 'SEQ_PUBLISHER_PRIVATE_KEYS'
214
221
  | 'SEQ_PUBLISHER_ADDRESSES'
215
222
  | 'SEQ_PUBLISHER_ALLOW_INVALID_STATES'
216
223
  | 'SEQ_PUBLISHER_FORWARDER_ADDRESS'
224
+ | 'PUBLISHER_FUNDING_THRESHOLD'
225
+ | 'PUBLISHER_FUNDING_AMOUNT'
217
226
  | 'SEQ_POLLING_INTERVAL_MS'
218
227
  | 'SEQ_ENFORCE_TIME_TABLE'
219
228
  | 'SEQ_L1_PUBLISHING_TIME_ALLOWANCE_IN_SLOT'
@@ -286,7 +295,6 @@ export type EnvVar =
286
295
  | 'VALIDATOR_MAX_TX_PER_CHECKPOINT'
287
296
  | 'VALIDATOR_PRIVATE_KEYS'
288
297
  | 'VALIDATOR_PRIVATE_KEY'
289
- | 'VALIDATOR_REEXECUTE'
290
298
  | 'VALIDATOR_ADDRESSES'
291
299
  | 'ROLLUP_VERSION'
292
300
  | 'WS_BLOCK_CHECK_INTERVAL_MS'
@@ -349,10 +357,11 @@ export type EnvVar =
349
357
  | 'K8S_POD_UID'
350
358
  | 'K8S_NAMESPACE_NAME'
351
359
  | 'ENABLE_VERSION_CHECK'
352
- | 'VALIDATOR_REEXECUTE_DEADLINE_MS'
353
360
  | 'WEB3_SIGNER_URL'
354
361
  | 'SKIP_ARCHIVER_INITIAL_SYNC'
355
362
  | 'BLOB_ALLOW_EMPTY_SOURCES'
363
+ | 'BLOB_PREFER_FILESTORES'
364
+ | 'BLOB_FILE_STORE_TIMEOUT_MS'
356
365
  | 'FISHERMAN_MODE'
357
366
  | 'MAX_ALLOWED_ETH_CLIENT_DRIFT_SECONDS'
358
367
  | 'LEGACY_BLS_CLI'
@@ -5,6 +5,7 @@ export const NetworkConfigSchema = z
5
5
  bootnodes: z.array(z.string()),
6
6
  snapshots: z.array(z.string()),
7
7
  blobFileStoreUrls: z.array(z.string()).optional(),
8
+ txCollectionFileStoreUrls: z.array(z.string()).optional(),
8
9
  registryAddress: z.string(),
9
10
  feeAssetHandlerAddress: z.string().optional(),
10
11
  l1ChainId: z.number(),
@@ -59,10 +59,19 @@ export class Aes128 {
59
59
  * @param iv - AES initialization vector.
60
60
  * @param key - Key to decrypt with.
61
61
  * @returns Decrypted data.
62
+ * @throws If the decrypted buffer has invalid PKCS#7 padding.
62
63
  */
63
64
  public async decryptBufferCBC(data: Uint8Array, iv: Uint8Array, key: Uint8Array) {
64
65
  const paddedBuffer = await this.decryptBufferCBCKeepPadding(data, iv, key);
65
- const paddingToRemove = paddedBuffer[paddedBuffer.length - 1];
66
- return paddedBuffer.subarray(0, paddedBuffer.length - paddingToRemove);
66
+ const paddingLen = paddedBuffer[paddedBuffer.length - 1];
67
+ if (paddingLen === 0 || paddingLen > 16) {
68
+ throw new Error(`Invalid PKCS#7 padding length: ${paddingLen}`);
69
+ }
70
+ for (let i = paddedBuffer.length - paddingLen; i < paddedBuffer.length; i++) {
71
+ if (paddedBuffer[i] !== paddingLen) {
72
+ throw new Error('Invalid PKCS#7 padding');
73
+ }
74
+ }
75
+ return paddedBuffer.subarray(0, paddedBuffer.length - paddingLen);
67
76
  }
68
77
  }
@@ -262,26 +262,3 @@ export function decryptBn254KeystoreFromObject(keystore: Bn254Keystore, password
262
262
  throw new Bn254KeystoreError(`Failed to decrypt keystore: ${String(error)}`, error as Error);
263
263
  }
264
264
  }
265
-
266
- /**
267
- * Validates that a decrypted private key matches the public key in the keystore.
268
- *
269
- * @param privateKeyHex - Decrypted private key (0x-prefixed)
270
- * @param expectedPubkey - Expected public key from keystore
271
- * @param computePublicKey - Function to compute public key from private key
272
- * @returns true if keys match, false otherwise
273
- */
274
- export function verifyBn254Keypair(
275
- privateKeyHex: string,
276
- expectedPubkey: string,
277
- computePublicKey: (privateKey: string) => string,
278
- ): boolean {
279
- try {
280
- const computedPubkey = computePublicKey(privateKeyHex);
281
- const normalizedExpected = expectedPubkey.toLowerCase().replace(/^0x/i, '');
282
- const normalizedComputed = computedPubkey.toLowerCase().replace(/^0x/i, '');
283
- return normalizedExpected === normalizedComputed;
284
- } catch {
285
- return false;
286
- }
287
- }
@@ -1,21 +1,35 @@
1
- import { Barretenberg } from '@aztec/bb.js';
1
+ import { Barretenberg, BarretenbergSync } from '@aztec/bb.js';
2
2
 
3
3
  import { Fr } from '../../curves/bn254/field.js';
4
4
  import { type Fieldable, serializeToFields } from '../../serialize/serialize.js';
5
5
 
6
+ const IS_BROWSER = typeof self !== 'undefined';
7
+
8
+ async function poseidon2HashFields(inputFields: Fr[]): Promise<Fr> {
9
+ if (IS_BROWSER) {
10
+ await BarretenbergSync.initSingleton();
11
+ const api = BarretenbergSync.getSingleton();
12
+ const response = api.poseidon2Hash({
13
+ inputs: inputFields.map(i => i.toBuffer()),
14
+ });
15
+ return Fr.fromBuffer(Buffer.from(response.hash));
16
+ } else {
17
+ await Barretenberg.initSingleton();
18
+ const api = Barretenberg.getSingleton();
19
+ const response = await api.poseidon2Hash({
20
+ inputs: inputFields.map(i => i.toBuffer()),
21
+ });
22
+ return Fr.fromBuffer(Buffer.from(response.hash));
23
+ }
24
+ }
25
+
6
26
  /**
7
27
  * Create a poseidon hash (field) from an array of input fields.
8
28
  * @param input - The input fields to hash.
9
29
  * @returns The poseidon hash.
10
30
  */
11
- export async function poseidon2Hash(input: Fieldable[]): Promise<Fr> {
12
- const inputFields = serializeToFields(input);
13
- await Barretenberg.initSingleton();
14
- const api = Barretenberg.getSingleton();
15
- const response = await api.poseidon2Hash({
16
- inputs: inputFields.map(i => i.toBuffer()),
17
- });
18
- return Fr.fromBuffer(Buffer.from(response.hash));
31
+ export function poseidon2Hash(input: Fieldable[]): Promise<Fr> {
32
+ return poseidon2HashFields(serializeToFields(input));
19
33
  }
20
34
 
21
35
  /**
@@ -24,15 +38,10 @@ export async function poseidon2Hash(input: Fieldable[]): Promise<Fr> {
24
38
  * @param separator - The domain separator.
25
39
  * @returns The poseidon hash.
26
40
  */
27
- export async function poseidon2HashWithSeparator(input: Fieldable[], separator: number): Promise<Fr> {
41
+ export function poseidon2HashWithSeparator(input: Fieldable[], separator: number): Promise<Fr> {
28
42
  const inputFields = serializeToFields(input);
29
43
  inputFields.unshift(new Fr(separator));
30
- await Barretenberg.initSingleton();
31
- const api = Barretenberg.getSingleton();
32
- const response = await api.poseidon2Hash({
33
- inputs: inputFields.map(i => i.toBuffer()),
34
- });
35
- return Fr.fromBuffer(Buffer.from(response.hash));
44
+ return poseidon2HashFields(inputFields);
36
45
  }
37
46
 
38
47
  /**
@@ -42,19 +51,24 @@ export async function poseidon2HashWithSeparator(input: Fieldable[], separator:
42
51
  */
43
52
  export async function poseidon2Permutation(input: Fieldable[]): Promise<Fr[]> {
44
53
  const inputFields = serializeToFields(input);
45
- // We'd like this assertion but it's not possible to use it in the browser.
46
- // assert(input.length === 4, 'Input state must be of size 4');
47
- await Barretenberg.initSingleton();
48
- const api = Barretenberg.getSingleton();
49
- const response = await api.poseidon2Permutation({
50
- inputs: inputFields.map(i => i.toBuffer()),
51
- });
52
- // We'd like this assertion but it's not possible to use it in the browser.
53
- // assert(response.outputs.length === 4, 'Output state must be of size 4');
54
- return response.outputs.map(o => Fr.fromBuffer(Buffer.from(o)));
54
+ if (IS_BROWSER) {
55
+ await BarretenbergSync.initSingleton();
56
+ const api = BarretenbergSync.getSingleton();
57
+ const response = api.poseidon2Permutation({
58
+ inputs: inputFields.map(i => i.toBuffer()),
59
+ });
60
+ return response.outputs.map(o => Fr.fromBuffer(Buffer.from(o)));
61
+ } else {
62
+ await Barretenberg.initSingleton();
63
+ const api = Barretenberg.getSingleton();
64
+ const response = await api.poseidon2Permutation({
65
+ inputs: inputFields.map(i => i.toBuffer()),
66
+ });
67
+ return response.outputs.map(o => Fr.fromBuffer(Buffer.from(o)));
68
+ }
55
69
  }
56
70
 
57
- export async function poseidon2HashBytes(input: Buffer): Promise<Fr> {
71
+ export function poseidon2HashBytes(input: Buffer): Promise<Fr> {
58
72
  const inputFields = [];
59
73
  for (let i = 0; i < input.length; i += 31) {
60
74
  const fieldBytes = Buffer.alloc(32, 0);
@@ -65,11 +79,5 @@ export async function poseidon2HashBytes(input: Buffer): Promise<Fr> {
65
79
  inputFields.push(Fr.fromBuffer(fieldBytes));
66
80
  }
67
81
 
68
- await Barretenberg.initSingleton();
69
- const api = Barretenberg.getSingleton();
70
- const response = await api.poseidon2Hash({
71
- inputs: inputFields.map(i => i.toBuffer()),
72
- });
73
-
74
- return Fr.fromBuffer(Buffer.from(response.hash));
82
+ return poseidon2HashFields(inputFields);
75
83
  }
@@ -65,7 +65,7 @@ export class Point {
65
65
  }
66
66
 
67
67
  /**
68
- * Generate a random Point instance.
68
+ * Generate a random Point instance that is on the curve.
69
69
  *
70
70
  * @returns A randomly generated Point instance.
71
71
  */
@@ -0,0 +1,98 @@
1
+ import EventEmitter from 'node:events';
2
+ import * as fs from 'node:fs';
3
+ import type { Readable } from 'node:stream';
4
+
5
+ /**
6
+ * Events emitted by FifoFrameReader.
7
+ *
8
+ * - `frame`: A complete frame payload (without the 4-byte length header).
9
+ * - `error`: An unrecoverable error (invalid frame length, stream error).
10
+ * - `end`: The underlying stream has ended.
11
+ */
12
+ export interface FifoFrameReaderEvents {
13
+ frame: [payload: Buffer];
14
+ error: [error: Error];
15
+ end: [];
16
+ }
17
+
18
+ /**
19
+ * Reads length-delimited frames from a readable stream (typically a named FIFO pipe).
20
+ *
21
+ * Wire format: `[4-byte big-endian payload length][payload bytes]`
22
+ *
23
+ * Emits a `frame` event for each complete frame with the raw payload buffer.
24
+ * Callers are responsible for deserializing the payload (e.g., via msgpack).
25
+ *
26
+ * On encountering an invalid payload length (0 or >maxPayloadSize), emits `error`
27
+ * and destroys the stream.
28
+ */
29
+ export class FifoFrameReader extends EventEmitter<FifoFrameReaderEvents> {
30
+ private stream: Readable | null = null;
31
+ private pendingBuf: Buffer = Buffer.alloc(0);
32
+ private running = false;
33
+
34
+ constructor(private readonly maxPayloadSize = 10 * 1024 * 1024) {
35
+ super();
36
+ }
37
+
38
+ /** Open a FIFO at the given path and start reading frames. */
39
+ start(fifoPath: string, highWaterMark = 64 * 1024): void {
40
+ this.startFromStream(fs.createReadStream(fifoPath, { highWaterMark }));
41
+ }
42
+
43
+ /** Start reading frames from an existing readable stream. */
44
+ startFromStream(stream: Readable): void {
45
+ if (this.running) {
46
+ throw new Error('FifoFrameReader is already running');
47
+ }
48
+ this.running = true;
49
+ this.pendingBuf = Buffer.alloc(0);
50
+ this.stream = stream;
51
+
52
+ stream.on('data', (chunk: Buffer | string) => {
53
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
54
+ this.pendingBuf = this.pendingBuf.length > 0 ? Buffer.concat([this.pendingBuf, buf]) : buf;
55
+ this.drainFrames();
56
+ });
57
+
58
+ stream.on('error', (err: Error) => {
59
+ if (this.running) {
60
+ this.emit('error', err);
61
+ }
62
+ });
63
+
64
+ stream.on('end', () => {
65
+ this.emit('end');
66
+ });
67
+ }
68
+
69
+ /** Stop reading and destroy the underlying stream. */
70
+ stop(): void {
71
+ this.running = false;
72
+ if (this.stream) {
73
+ this.stream.destroy();
74
+ this.stream = null;
75
+ }
76
+ }
77
+
78
+ /** Parse complete frames out of the pending buffer. */
79
+ private drainFrames(): void {
80
+ while (this.pendingBuf.length >= 4) {
81
+ const payloadLen = this.pendingBuf.readUInt32BE(0);
82
+ if (payloadLen === 0 || payloadLen > this.maxPayloadSize) {
83
+ this.emit('error', new Error(`Invalid payload length: ${payloadLen}`));
84
+ this.stop();
85
+ return;
86
+ }
87
+
88
+ const frameLen = 4 + payloadLen;
89
+ if (this.pendingBuf.length < frameLen) {
90
+ break; // Wait for more data
91
+ }
92
+
93
+ const payload = this.pendingBuf.subarray(4, frameLen);
94
+ this.pendingBuf = this.pendingBuf.subarray(frameLen);
95
+ this.emit('frame', Buffer.from(payload));
96
+ }
97
+ }
98
+ }
@@ -0,0 +1 @@
1
+ export { FifoFrameReader } from './fifo_frame_reader.js';
@@ -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 {
@@ -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;
@@ -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.