@aztec/foundation 0.0.1-commit.f295ac2 → 0.0.1-commit.f504929

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 (140) 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/collection/array.d.ts +12 -1
  5. package/dest/collection/array.d.ts.map +1 -1
  6. package/dest/collection/array.js +51 -0
  7. package/dest/config/env_var.d.ts +2 -2
  8. package/dest/config/env_var.d.ts.map +1 -1
  9. package/dest/config/index.d.ts +1 -1
  10. package/dest/config/index.d.ts.map +1 -1
  11. package/dest/config/index.js +15 -0
  12. package/dest/config/network_config.d.ts +7 -1
  13. package/dest/config/network_config.d.ts.map +1 -1
  14. package/dest/config/network_config.js +2 -1
  15. package/dest/config/network_name.d.ts +2 -2
  16. package/dest/config/network_name.d.ts.map +1 -1
  17. package/dest/config/network_name.js +2 -0
  18. package/dest/crypto/poseidon/index.d.ts +1 -2
  19. package/dest/crypto/poseidon/index.d.ts.map +1 -1
  20. package/dest/crypto/poseidon/index.js +13 -22
  21. package/dest/crypto/random/randomness_singleton.d.ts +4 -3
  22. package/dest/crypto/random/randomness_singleton.d.ts.map +1 -1
  23. package/dest/crypto/random/randomness_singleton.js +4 -4
  24. package/dest/crypto/secp256k1-signer/utils.d.ts +12 -1
  25. package/dest/crypto/secp256k1-signer/utils.d.ts.map +1 -1
  26. package/dest/crypto/secp256k1-signer/utils.js +26 -0
  27. package/dest/crypto/sync/poseidon/index.d.ts +1 -2
  28. package/dest/crypto/sync/poseidon/index.d.ts.map +1 -1
  29. package/dest/crypto/sync/poseidon/index.js +0 -8
  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/eth-signature/eth_signature.d.ts +2 -1
  34. package/dest/eth-signature/eth_signature.d.ts.map +1 -1
  35. package/dest/eth-signature/eth_signature.js +7 -2
  36. package/dest/jest/setup.js +28 -1
  37. package/dest/json-rpc/client/safe_json_rpc_client.d.ts +2 -1
  38. package/dest/json-rpc/client/safe_json_rpc_client.d.ts.map +1 -1
  39. package/dest/json-rpc/client/safe_json_rpc_client.js +1 -1
  40. package/dest/json-rpc/client/undici.d.ts +1 -1
  41. package/dest/json-rpc/client/undici.d.ts.map +1 -1
  42. package/dest/json-rpc/client/undici.js +21 -4
  43. package/dest/json-rpc/server/api_key_auth.d.ts +19 -0
  44. package/dest/json-rpc/server/api_key_auth.d.ts.map +1 -0
  45. package/dest/json-rpc/server/api_key_auth.js +57 -0
  46. package/dest/json-rpc/server/index.d.ts +2 -1
  47. package/dest/json-rpc/server/index.d.ts.map +1 -1
  48. package/dest/json-rpc/server/index.js +1 -0
  49. package/dest/json-rpc/server/safe_json_rpc_server.js +1 -1
  50. package/dest/log/bigint-utils.d.ts +5 -0
  51. package/dest/log/bigint-utils.d.ts.map +1 -0
  52. package/dest/log/bigint-utils.js +21 -0
  53. package/dest/log/gcloud-logger-config.d.ts +1 -1
  54. package/dest/log/gcloud-logger-config.d.ts.map +1 -1
  55. package/dest/log/gcloud-logger-config.js +3 -0
  56. package/dest/log/libp2p_logger.d.ts +5 -2
  57. package/dest/log/libp2p_logger.d.ts.map +1 -1
  58. package/dest/log/libp2p_logger.js +14 -4
  59. package/dest/log/log-filters.d.ts +17 -4
  60. package/dest/log/log-filters.d.ts.map +1 -1
  61. package/dest/log/log-filters.js +26 -12
  62. package/dest/log/pino-logger-server.d.ts +9 -0
  63. package/dest/log/pino-logger-server.d.ts.map +1 -0
  64. package/dest/log/pino-logger-server.js +18 -0
  65. package/dest/log/pino-logger.d.ts +37 -8
  66. package/dest/log/pino-logger.d.ts.map +1 -1
  67. package/dest/log/pino-logger.js +121 -28
  68. package/dest/queue/base_memory_queue.d.ts +2 -2
  69. package/dest/queue/base_memory_queue.d.ts.map +1 -1
  70. package/dest/queue/semaphore.d.ts +5 -1
  71. package/dest/queue/semaphore.d.ts.map +1 -1
  72. package/dest/serialize/buffer_reader.d.ts +8 -1
  73. package/dest/serialize/buffer_reader.d.ts.map +1 -1
  74. package/dest/serialize/buffer_reader.js +13 -0
  75. package/dest/serialize/serialize.d.ts +19 -1
  76. package/dest/serialize/serialize.d.ts.map +1 -1
  77. package/dest/serialize/serialize.js +31 -0
  78. package/dest/sleep/index.d.ts +2 -1
  79. package/dest/sleep/index.d.ts.map +1 -1
  80. package/dest/sleep/index.js +10 -1
  81. package/dest/timer/date.d.ts +25 -1
  82. package/dest/timer/date.d.ts.map +1 -1
  83. package/dest/timer/date.js +33 -0
  84. package/dest/transport/transport_client.js +2 -2
  85. package/dest/trees/balanced_merkle_tree_root.d.ts +2 -3
  86. package/dest/trees/balanced_merkle_tree_root.d.ts.map +1 -1
  87. package/dest/trees/balanced_merkle_tree_root.js +2 -3
  88. package/dest/trees/hasher.d.ts +1 -2
  89. package/dest/trees/hasher.d.ts.map +1 -1
  90. package/dest/trees/hasher.js +0 -5
  91. package/dest/trees/membership_witness.d.ts +5 -1
  92. package/dest/trees/membership_witness.d.ts.map +1 -1
  93. package/dest/trees/membership_witness.js +9 -0
  94. package/dest/trees/merkle_tree_calculator.d.ts +1 -1
  95. package/dest/trees/merkle_tree_calculator.d.ts.map +1 -1
  96. package/dest/trees/merkle_tree_calculator.js +2 -2
  97. package/dest/trees/sibling_path.d.ts +1 -1
  98. package/dest/trees/sibling_path.d.ts.map +1 -1
  99. package/dest/trees/sibling_path.js +2 -2
  100. package/dest/types/index.d.ts +3 -1
  101. package/dest/types/index.d.ts.map +1 -1
  102. package/dest/types/index.js +3 -0
  103. package/package.json +23 -2
  104. package/src/array/sorted_array.ts +22 -17
  105. package/src/collection/array.ts +52 -0
  106. package/src/config/env_var.ts +42 -3
  107. package/src/config/index.ts +15 -0
  108. package/src/config/network_config.ts +1 -0
  109. package/src/config/network_name.ts +4 -1
  110. package/src/crypto/poseidon/index.ts +13 -23
  111. package/src/crypto/random/randomness_singleton.ts +9 -5
  112. package/src/crypto/secp256k1-signer/utils.ts +32 -0
  113. package/src/crypto/sync/poseidon/index.ts +0 -9
  114. package/src/curves/bn254/field.ts +6 -2
  115. package/src/eth-signature/eth_signature.ts +7 -1
  116. package/src/jest/setup.mjs +31 -1
  117. package/src/json-rpc/client/safe_json_rpc_client.ts +2 -0
  118. package/src/json-rpc/client/undici.ts +21 -3
  119. package/src/json-rpc/server/api_key_auth.ts +63 -0
  120. package/src/json-rpc/server/index.ts +1 -0
  121. package/src/json-rpc/server/safe_json_rpc_server.ts +1 -1
  122. package/src/log/bigint-utils.ts +25 -0
  123. package/src/log/gcloud-logger-config.ts +5 -0
  124. package/src/log/libp2p_logger.ts +12 -5
  125. package/src/log/log-filters.ts +29 -11
  126. package/src/log/pino-logger-server.ts +25 -0
  127. package/src/log/pino-logger.ts +142 -38
  128. package/src/queue/base_memory_queue.ts +1 -1
  129. package/src/queue/semaphore.ts +5 -0
  130. package/src/serialize/buffer_reader.ts +15 -0
  131. package/src/serialize/serialize.ts +32 -0
  132. package/src/sleep/index.ts +10 -1
  133. package/src/timer/date.ts +48 -0
  134. package/src/transport/transport_client.ts +2 -2
  135. package/src/trees/balanced_merkle_tree_root.ts +2 -5
  136. package/src/trees/hasher.ts +0 -4
  137. package/src/trees/membership_witness.ts +8 -0
  138. package/src/trees/merkle_tree_calculator.ts +2 -2
  139. package/src/trees/sibling_path.ts +2 -2
  140. package/src/types/index.ts +5 -0
@@ -250,6 +250,58 @@ export function chunk<T>(items: T[], chunkSize: number): T[][] {
250
250
  return chunks;
251
251
  }
252
252
 
253
+ /**
254
+ * Splits the given array into chunks of the given size, wrapping around to the beginning
255
+ * if the last chunk would be smaller than the requested size.
256
+ * Returns empty array for empty input. Returns single chunk with all items if chunkSize <= 0.
257
+ */
258
+ export function chunkWrapAround<T>(items: T[], chunkSize: number): T[][] {
259
+ if (items.length === 0) {
260
+ return [];
261
+ }
262
+ if (chunkSize <= 0 || items.length <= chunkSize) {
263
+ return [items];
264
+ }
265
+ const remainder = items.length % chunkSize;
266
+ if (remainder === 0) {
267
+ return chunk(items, chunkSize);
268
+ }
269
+ const wrapAroundCount = chunkSize - remainder;
270
+ const wrappedItems = [...items, ...items.slice(0, wrapAroundCount)];
271
+ return chunk(wrappedItems, chunkSize);
272
+ }
273
+
274
+ const UNINITIALIZED = Symbol('uninitialized');
275
+
276
+ /**
277
+ * Splits the given iterable into chunks based on the key returned by the given function.
278
+ * Items must be contiguous to be included in the same chunk.
279
+ */
280
+ export function chunkBy<T, U>(items: T[], fn: (item: T) => U): T[][] {
281
+ const chunks: T[][] = [];
282
+ let currentChunk: T[] = [];
283
+ let currentKey: U | typeof UNINITIALIZED = UNINITIALIZED;
284
+
285
+ for (const item of items) {
286
+ const key = fn(item);
287
+ if (currentKey === UNINITIALIZED || key !== currentKey) {
288
+ if (currentChunk.length > 0) {
289
+ chunks.push(currentChunk);
290
+ }
291
+ currentChunk = [item];
292
+ currentKey = key;
293
+ } else {
294
+ currentChunk.push(item);
295
+ }
296
+ }
297
+
298
+ if (currentChunk.length > 0) {
299
+ chunks.push(currentChunk);
300
+ }
301
+
302
+ return chunks;
303
+ }
304
+
253
305
  /** Partitions the given iterable into two arrays based on the predicate. */
254
306
  export function partition<T>(items: T[], predicate: (item: T) => boolean): [T[], T[]] {
255
307
  const pass: T[] = [];
@@ -12,6 +12,9 @@ export type EnvVar =
12
12
  | 'ARCHIVER_VIEM_POLLING_INTERVAL_MS'
13
13
  | 'ARCHIVER_BATCH_SIZE'
14
14
  | 'AZTEC_ADMIN_PORT'
15
+ | 'AZTEC_ADMIN_API_KEY_HASH'
16
+ | 'AZTEC_DISABLE_ADMIN_API_KEY'
17
+ | 'AZTEC_RESET_ADMIN_API_KEY'
15
18
  | 'AZTEC_NODE_ADMIN_URL'
16
19
  | 'AZTEC_NODE_URL'
17
20
  | 'AZTEC_PORT'
@@ -47,7 +50,10 @@ export type EnvVar =
47
50
  | 'BOT_TX_MINED_WAIT_SECONDS'
48
51
  | 'BOT_MAX_CONSECUTIVE_ERRORS'
49
52
  | 'BOT_STOP_WHEN_UNHEALTHY'
50
- | 'BOT_AMM_TXS'
53
+ | 'BOT_MODE'
54
+ | 'BOT_L2_TO_L1_MESSAGES_PER_TX'
55
+ | 'BOT_L1_TO_L2_SEED_COUNT'
56
+ | 'BOT_L1_TO_L2_SEED_INTERVAL'
51
57
  | 'COINBASE'
52
58
  | 'CRS_PATH'
53
59
  | 'DATA_DIRECTORY'
@@ -64,6 +70,7 @@ export type EnvVar =
64
70
  | 'PUBLIC_DATA_TREE_MAP_SIZE_KB'
65
71
  | 'DEBUG'
66
72
  | 'DEBUG_P2P_DISABLE_COLOCATION_PENALTY'
73
+ | 'ENABLE_PROVER_NODE'
67
74
  | 'ETHEREUM_HOSTS'
68
75
  | 'ETHEREUM_DEBUG_HOSTS'
69
76
  | 'ETHEREUM_ALLOW_NO_DEBUG_HOSTS'
@@ -75,8 +82,10 @@ export type EnvVar =
75
82
  | 'L1_CONSENSUS_HOST_URLS'
76
83
  | 'L1_CONSENSUS_HOST_API_KEYS'
77
84
  | 'L1_CONSENSUS_HOST_API_KEY_HEADERS'
85
+ | 'L1_TX_FAILED_STORE'
78
86
  | 'LOG_JSON'
79
87
  | 'LOG_MULTILINE'
88
+ | 'LOG_NO_COLOR_PER_ACTOR'
80
89
  | 'LOG_LEVEL'
81
90
  | 'MNEMONIC'
82
91
  | 'NETWORK'
@@ -94,7 +103,12 @@ export type EnvVar =
94
103
  | 'PUBLIC_OTEL_INCLUDE_METRICS'
95
104
  | 'PUBLIC_OTEL_COLLECT_FROM'
96
105
  | 'PUBLIC_OTEL_OPT_OUT'
106
+ | 'P2P_BATCH_TX_REQUESTER_SMART_PARALLEL_WORKER_COUNT'
107
+ | 'P2P_BATCH_TX_REQUESTER_DUMB_PARALLEL_WORKER_COUNT'
108
+ | 'P2P_BATCH_TX_REQUESTER_TX_BATCH_SIZE'
109
+ | 'P2P_BATCH_TX_REQUESTER_BAD_PEER_THRESHOLD'
97
110
  | 'P2P_BLOCK_CHECK_INTERVAL_MS'
111
+ | 'P2P_SLOT_CHECK_INTERVAL_MS'
98
112
  | 'P2P_BLOCK_REQUEST_BATCH_SIZE'
99
113
  | 'P2P_BOOTSTRAP_NODE_ENR_VERSION_CHECK'
100
114
  | 'P2P_BOOTSTRAP_NODES_AS_FULL_PEERS'
@@ -135,9 +149,9 @@ export type EnvVar =
135
149
  | 'P2P_PREFERRED_PEERS'
136
150
  | 'P2P_MAX_PENDING_TX_COUNT'
137
151
  | 'P2P_SEEN_MSG_CACHE_SIZE'
138
- | 'P2P_DROP_TX'
139
152
  | 'P2P_DROP_TX_CHANCE'
140
153
  | 'P2P_TX_POOL_DELETE_TXS_AFTER_REORG'
154
+ | 'P2P_MIN_TX_POOL_AGE_MS'
141
155
  | 'DEBUG_P2P_INSTRUMENT_MESSAGES'
142
156
  | 'PEER_ID_PRIVATE_KEY'
143
157
  | 'PEER_ID_PRIVATE_KEY_PATH'
@@ -151,7 +165,10 @@ export type EnvVar =
151
165
  | 'PROVER_BROKER_BATCH_INTERVAL_MS'
152
166
  | 'PROVER_BROKER_BATCH_SIZE'
153
167
  | 'PROVER_BROKER_MAX_EPOCHS_TO_KEEP_RESULTS_FOR'
168
+ | 'PROVER_BROKER_DEBUG_REPLAY_ENABLED'
169
+ | 'PROVER_CANCEL_JOBS_ON_STOP'
154
170
  | 'PROVER_COORDINATION_NODE_URLS'
171
+ | 'PROVER_PROOF_STORE'
155
172
  | 'PROVER_FAILED_PROOF_STORE'
156
173
  | 'PROVER_NODE_FAILED_EPOCH_STORE'
157
174
  | 'PROVER_NODE_DISABLE_PROOF_PUBLISH'
@@ -175,6 +192,7 @@ export type EnvVar =
175
192
  | 'PROVER_TEST_VERIFICATION_DELAY_MS'
176
193
  | 'PXE_L2_BLOCK_BATCH_SIZE'
177
194
  | 'PXE_PROVER_ENABLED'
195
+ | 'PXE_SYNC_CHAIN_TIP'
178
196
  | 'RPC_MAX_BATCH_SIZE'
179
197
  | 'RPC_MAX_BODY_SIZE'
180
198
  | 'RPC_SIMULATE_PUBLIC_MAX_GAS_LIMIT'
@@ -198,9 +216,11 @@ export type EnvVar =
198
216
  | 'SEQ_L1_PUBLISHING_TIME_ALLOWANCE_IN_SLOT'
199
217
  | 'SEQ_ATTESTATION_PROPAGATION_TIME'
200
218
  | 'SEQ_BLOCK_DURATION_MS'
219
+ | 'SEQ_EXPECTED_BLOCK_PROPOSALS_PER_SLOT'
201
220
  | 'SEQ_BUILD_CHECKPOINT_IF_EMPTY'
202
221
  | 'SEQ_SECONDS_BEFORE_INVALIDATING_BLOCK_AS_COMMITTEE_MEMBER'
203
222
  | 'SEQ_SECONDS_BEFORE_INVALIDATING_BLOCK_AS_NON_COMMITTEE_MEMBER'
223
+ | 'SEQ_SKIP_CHECKPOINT_PUBLISH_PERCENT'
204
224
  | 'SLASH_MIN_PENALTY_PERCENTAGE'
205
225
  | 'SLASH_MAX_PENALTY_PERCENTAGE'
206
226
  | 'SLASH_VALIDATORS_ALWAYS'
@@ -211,6 +231,8 @@ export type EnvVar =
211
231
  | 'SLASH_INACTIVITY_TARGET_PERCENTAGE'
212
232
  | 'SLASH_INACTIVITY_CONSECUTIVE_EPOCH_THRESHOLD'
213
233
  | 'SLASH_INVALID_BLOCK_PENALTY'
234
+ | 'SLASH_DUPLICATE_PROPOSAL_PENALTY'
235
+ | 'SLASH_DUPLICATE_ATTESTATION_PENALTY'
214
236
  | 'SLASH_OVERRIDE_PAYLOAD'
215
237
  | 'SLASH_PROPOSE_INVALID_ATTESTATIONS_PENALTY'
216
238
  | 'SLASH_ATTEST_DESCENDANT_OF_INVALID_PENALTY'
@@ -225,6 +247,7 @@ export type EnvVar =
225
247
  | 'TELEMETRY'
226
248
  | 'TEST_ACCOUNTS'
227
249
  | 'SPONSORED_FPC'
250
+ | 'PREFUND_ADDRESSES'
228
251
  | 'TX_COLLECTION_FAST_NODES_TIMEOUT_BEFORE_REQ_RESP_MS'
229
252
  | 'TX_COLLECTION_SLOW_NODES_INTERVAL_MS'
230
253
  | 'TX_COLLECTION_SLOW_REQ_RESP_INTERVAL_MS'
@@ -235,6 +258,20 @@ export type EnvVar =
235
258
  | 'TX_COLLECTION_FAST_MAX_PARALLEL_REQUESTS_PER_NODE'
236
259
  | 'TX_COLLECTION_NODE_RPC_MAX_BATCH_SIZE'
237
260
  | 'TX_COLLECTION_NODE_RPC_URLS'
261
+ | 'TX_COLLECTION_MISSING_TXS_COLLECTOR_TYPE'
262
+ | 'TX_COLLECTION_FILE_STORE_URLS'
263
+ | 'TX_COLLECTION_FILE_STORE_SLOW_DELAY_MS'
264
+ | 'TX_COLLECTION_FILE_STORE_FAST_DELAY_MS'
265
+ | 'TX_COLLECTION_FILE_STORE_FAST_WORKER_COUNT'
266
+ | 'TX_COLLECTION_FILE_STORE_SLOW_WORKER_COUNT'
267
+ | 'TX_COLLECTION_FILE_STORE_FAST_BACKOFF_BASE_MS'
268
+ | 'TX_COLLECTION_FILE_STORE_SLOW_BACKOFF_BASE_MS'
269
+ | 'TX_COLLECTION_FILE_STORE_FAST_BACKOFF_MAX_MS'
270
+ | 'TX_COLLECTION_FILE_STORE_SLOW_BACKOFF_MAX_MS'
271
+ | 'TX_FILE_STORE_URL'
272
+ | 'TX_FILE_STORE_UPLOAD_CONCURRENCY'
273
+ | 'TX_FILE_STORE_MAX_QUEUE_SIZE'
274
+ | 'TX_FILE_STORE_ENABLED'
238
275
  | 'TX_PUBLIC_SETUP_ALLOWLIST'
239
276
  | 'TXE_PORT'
240
277
  | 'TRANSACTIONS_DISABLED'
@@ -246,10 +283,10 @@ export type EnvVar =
246
283
  | 'VALIDATOR_ADDRESSES'
247
284
  | 'ROLLUP_VERSION'
248
285
  | 'WS_BLOCK_CHECK_INTERVAL_MS'
249
- | 'WS_PROVEN_BLOCKS_ONLY'
250
286
  | 'WS_BLOCK_REQUEST_BATCH_SIZE'
251
287
  | 'L1_READER_VIEM_POLLING_INTERVAL_MS'
252
288
  | 'WS_DATA_DIRECTORY'
289
+ | 'WS_NUM_HISTORIC_CHECKPOINTS'
253
290
  | 'WS_NUM_HISTORIC_BLOCKS'
254
291
  | 'ETHEREUM_SLOT_DURATION'
255
292
  | 'AZTEC_SLOT_DURATION'
@@ -264,6 +301,7 @@ export type EnvVar =
264
301
  | 'AZTEC_LOCAL_EJECTION_THRESHOLD'
265
302
  | 'AZTEC_MANA_TARGET'
266
303
  | 'AZTEC_PROVING_COST_PER_MANA'
304
+ | 'AZTEC_INITIAL_ETH_PER_FEE_ASSET'
267
305
  | 'AZTEC_SLASHING_QUORUM'
268
306
  | 'AZTEC_SLASHING_ROUND_SIZE_IN_EPOCHS'
269
307
  | 'AZTEC_SLASHING_LIFETIME_IN_ROUNDS'
@@ -318,6 +356,7 @@ export type EnvVar =
318
356
  | 'VALIDATOR_HA_POLLING_INTERVAL_MS'
319
357
  | 'VALIDATOR_HA_SIGNING_TIMEOUT_MS'
320
358
  | 'VALIDATOR_HA_MAX_STUCK_DUTIES_AGE_MS'
359
+ | 'VALIDATOR_HA_OLD_DUTIES_MAX_AGE_H'
321
360
  | 'VALIDATOR_HA_DATABASE_URL'
322
361
  | 'VALIDATOR_HA_RUN_MIGRATIONS'
323
362
  | 'VALIDATOR_HA_POOL_MAX'
@@ -177,6 +177,21 @@ export function bigintConfigHelper(defaultVal?: bigint): Pick<ConfigMapping, 'pa
177
177
  if (val === '') {
178
178
  return defaultVal;
179
179
  }
180
+ // Handle scientific notation (e.g. "1e+23", "2E23") which BigInt() doesn't accept directly.
181
+ // We parse it losslessly using bigint arithmetic instead of going through float64.
182
+ if (/[eE]/.test(val)) {
183
+ const match = val.match(/^(-?\d+(?:\.(\d+))?)[eE]([+-]?\d+)$/);
184
+ if (!match) {
185
+ throw new Error(`Cannot convert '${val}' to a BigInt`);
186
+ }
187
+ const digits = match[1].replace('.', '');
188
+ const decimalPlaces = match[2]?.length ?? 0;
189
+ const exponent = parseInt(match[3], 10) - decimalPlaces;
190
+ if (exponent < 0) {
191
+ throw new Error(`Cannot convert '${val}' to a BigInt: result is not an integer`);
192
+ }
193
+ return BigInt(digits) * 10n ** BigInt(exponent);
194
+ }
180
195
  return BigInt(val);
181
196
  },
182
197
  defaultValue: defaultVal,
@@ -9,6 +9,7 @@ export const NetworkConfigSchema = z
9
9
  feeAssetHandlerAddress: z.string().optional(),
10
10
  l1ChainId: z.number(),
11
11
  blockDurationMs: z.number().positive().optional(),
12
+ txPublicSetupAllowListExtend: z.string().optional(),
12
13
  })
13
14
  .passthrough(); // Allow additional unknown fields to pass through
14
15
 
@@ -5,7 +5,8 @@ export type NetworkNames =
5
5
  | 'testnet'
6
6
  | 'mainnet'
7
7
  | 'next-net'
8
- | 'devnet';
8
+ | 'devnet'
9
+ | `v${number}-devnet-${number}`;
9
10
 
10
11
  export function getActiveNetworkName(name?: string): NetworkNames {
11
12
  const network = name || process.env.NETWORK;
@@ -23,6 +24,8 @@ export function getActiveNetworkName(name?: string): NetworkNames {
23
24
  return 'next-net';
24
25
  } else if (network === 'devnet') {
25
26
  return 'devnet';
27
+ } else if (/^v\d+-devnet-\d+$/.test(network)) {
28
+ return network as `v${number}-devnet-${number}`;
26
29
  }
27
30
  throw new Error(`Unknown network: ${network}`);
28
31
  }
@@ -1,4 +1,4 @@
1
- import { BarretenbergSync } from '@aztec/bb.js';
1
+ import { Barretenberg } 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';
@@ -10,9 +10,9 @@ import { type Fieldable, serializeToFields } from '../../serialize/serialize.js'
10
10
  */
11
11
  export async function poseidon2Hash(input: Fieldable[]): Promise<Fr> {
12
12
  const inputFields = serializeToFields(input);
13
- await BarretenbergSync.initSingleton();
14
- const api = BarretenbergSync.getSingleton();
15
- const response = api.poseidon2Hash({
13
+ await Barretenberg.initSingleton();
14
+ const api = Barretenberg.getSingleton();
15
+ const response = await api.poseidon2Hash({
16
16
  inputs: inputFields.map(i => i.toBuffer()),
17
17
  });
18
18
  return Fr.fromBuffer(Buffer.from(response.hash));
@@ -27,19 +27,9 @@ export async function poseidon2Hash(input: Fieldable[]): Promise<Fr> {
27
27
  export async function poseidon2HashWithSeparator(input: Fieldable[], separator: number): Promise<Fr> {
28
28
  const inputFields = serializeToFields(input);
29
29
  inputFields.unshift(new Fr(separator));
30
- await BarretenbergSync.initSingleton();
31
- const api = BarretenbergSync.getSingleton();
32
- const response = api.poseidon2Hash({
33
- inputs: inputFields.map(i => i.toBuffer()),
34
- });
35
- return Fr.fromBuffer(Buffer.from(response.hash));
36
- }
37
-
38
- export async function poseidon2HashAccumulate(input: Fieldable[]): Promise<Fr> {
39
- const inputFields = serializeToFields(input);
40
- await BarretenbergSync.initSingleton();
41
- const api = BarretenbergSync.getSingleton();
42
- const response = api.poseidon2HashAccumulate({
30
+ await Barretenberg.initSingleton();
31
+ const api = Barretenberg.getSingleton();
32
+ const response = await api.poseidon2Hash({
43
33
  inputs: inputFields.map(i => i.toBuffer()),
44
34
  });
45
35
  return Fr.fromBuffer(Buffer.from(response.hash));
@@ -54,9 +44,9 @@ export async function poseidon2Permutation(input: Fieldable[]): Promise<Fr[]> {
54
44
  const inputFields = serializeToFields(input);
55
45
  // We'd like this assertion but it's not possible to use it in the browser.
56
46
  // assert(input.length === 4, 'Input state must be of size 4');
57
- await BarretenbergSync.initSingleton();
58
- const api = BarretenbergSync.getSingleton();
59
- const response = api.poseidon2Permutation({
47
+ await Barretenberg.initSingleton();
48
+ const api = Barretenberg.getSingleton();
49
+ const response = await api.poseidon2Permutation({
60
50
  inputs: inputFields.map(i => i.toBuffer()),
61
51
  });
62
52
  // We'd like this assertion but it's not possible to use it in the browser.
@@ -75,9 +65,9 @@ export async function poseidon2HashBytes(input: Buffer): Promise<Fr> {
75
65
  inputFields.push(Fr.fromBuffer(fieldBytes));
76
66
  }
77
67
 
78
- await BarretenbergSync.initSingleton();
79
- const api = BarretenbergSync.getSingleton();
80
- const response = api.poseidon2Hash({
68
+ await Barretenberg.initSingleton();
69
+ const api = Barretenberg.getSingleton();
70
+ const response = await api.poseidon2Hash({
81
71
  inputs: inputFields.map(i => i.toBuffer()),
82
72
  });
83
73
 
@@ -1,4 +1,4 @@
1
- import { createLogger } from '../../log/pino-logger.js';
1
+ import { type Logger, type LoggerBindings, createLogger } from '../../log/pino-logger.js';
2
2
 
3
3
  /**
4
4
  * A number generator which is used as a source of randomness in the system. If the SEED env variable is set, the
@@ -12,9 +12,13 @@ export class RandomnessSingleton {
12
12
  private static instance: RandomnessSingleton;
13
13
 
14
14
  private counter = 0;
15
- private readonly log = createLogger('foundation:randomness_singleton');
15
+ private log: Logger;
16
16
 
17
- private constructor(private readonly seed?: number) {
17
+ private constructor(
18
+ private readonly seed?: number,
19
+ bindings?: LoggerBindings,
20
+ ) {
21
+ this.log = createLogger('foundation:randomness_singleton', bindings);
18
22
  if (seed !== undefined) {
19
23
  this.log.debug(`Using pseudo-randomness with seed: ${seed}`);
20
24
  this.counter = seed;
@@ -23,10 +27,10 @@ export class RandomnessSingleton {
23
27
  }
24
28
  }
25
29
 
26
- public static getInstance(): RandomnessSingleton {
30
+ public static getInstance(bindings?: LoggerBindings): RandomnessSingleton {
27
31
  if (!RandomnessSingleton.instance) {
28
32
  const seed = process.env.SEED ? Number(process.env.SEED) : undefined;
29
- RandomnessSingleton.instance = new RandomnessSingleton(seed);
33
+ RandomnessSingleton.instance = new RandomnessSingleton(seed, bindings);
30
34
  }
31
35
 
32
36
  return RandomnessSingleton.instance;
@@ -210,3 +210,35 @@ export function recoverPublicKey(hash: Buffer32, signature: Signature, opts: Rec
210
210
  const publicKey = sig.recoverPublicKey(hash.buffer).toHex(false);
211
211
  return Buffer.from(publicKey, 'hex');
212
212
  }
213
+
214
+ /** Arbitrary hash used for testing signature recoverability. */
215
+ const PROBE_HASH = Buffer32.fromBuffer(keccak256(Buffer.from('signature-recoverability-probe')));
216
+
217
+ /**
218
+ * Generates a random valid ECDSA signature that is recoverable to some address.
219
+ * Since Signature.random() produces real signatures via secp256k1 signing, the result is always
220
+ * recoverable, but we verify defensively by checking tryRecoverAddress.
221
+ */
222
+ export function generateRecoverableSignature(): Signature {
223
+ for (let i = 0; i < 100; i++) {
224
+ const sig = Signature.random();
225
+ if (tryRecoverAddress(PROBE_HASH, sig) !== undefined) {
226
+ return sig;
227
+ }
228
+ }
229
+ throw new Secp256k1Error('Failed to generate a recoverable signature after 100 attempts');
230
+ }
231
+
232
+ /**
233
+ * Generates a random signature where ECDSA address recovery fails.
234
+ * Uses random r/s values (not from real signing) so that r is unlikely to be a valid secp256k1 x-coordinate.
235
+ */
236
+ export function generateUnrecoverableSignature(): Signature {
237
+ for (let i = 0; i < 100; i++) {
238
+ const sig = new Signature(Buffer32.random(), Buffer32.random(), 27);
239
+ if (tryRecoverAddress(PROBE_HASH, sig) === undefined) {
240
+ return sig;
241
+ }
242
+ }
243
+ throw new Secp256k1Error('Failed to generate an unrecoverable signature after 100 attempts');
244
+ }
@@ -34,15 +34,6 @@ export function poseidon2HashWithSeparator(input: Fieldable[], separator: number
34
34
  return Fr.fromBuffer(Buffer.from(response.hash));
35
35
  }
36
36
 
37
- export function poseidon2HashAccumulate(input: Fieldable[]): Fr {
38
- const inputFields = serializeToFields(input);
39
- const api = BarretenbergSync.getSingleton();
40
- const response = api.poseidon2HashAccumulate({
41
- inputs: inputFields.map(i => i.toBuffer()),
42
- });
43
- return Fr.fromBuffer(Buffer.from(response.hash));
44
- }
45
-
46
37
  /**
47
38
  * Runs a Poseidon2 permutation.
48
39
  * @param input the input state. Expected to be of size 4.
@@ -118,14 +118,18 @@ abstract class BaseField {
118
118
  }
119
119
 
120
120
  cmp(rhs: BaseField): -1 | 0 | 1 {
121
- const rhsBigInt = rhs.asBigInt;
122
- return this.asBigInt === rhsBigInt ? 0 : this.asBigInt < rhsBigInt ? -1 : 1;
121
+ return BaseField.cmpAsBigInt(this.asBigInt, rhs.asBigInt);
123
122
  }
124
123
 
125
124
  static cmp(lhs: BaseField, rhs: BaseField): -1 | 0 | 1 {
126
125
  return lhs.cmp(rhs);
127
126
  }
128
127
 
128
+ // Actual bigint comparison. Arguments must have been validated previously.
129
+ static cmpAsBigInt(lhs: bigint, rhs: bigint): -1 | 0 | 1 {
130
+ return lhs === rhs ? 0 : lhs < rhs ? -1 : 1;
131
+ }
132
+
129
133
  isZero(): boolean {
130
134
  return this.asBigInt === 0n;
131
135
  }
@@ -1,8 +1,10 @@
1
1
  import { Buffer32 } from '@aztec/foundation/buffer';
2
2
  import { BufferReader, serializeToBuffer } from '@aztec/foundation/serialize';
3
3
 
4
+ import { secp256k1 } from '@noble/curves/secp256k1';
4
5
  import { z } from 'zod';
5
6
 
7
+ import { randomBytes } from '../crypto/random/index.js';
6
8
  import { hasHexPrefix, hexToBuffer } from '../string/index.js';
7
9
 
8
10
  /**
@@ -77,8 +79,12 @@ export class Signature {
77
79
  return new Signature(Buffer32.fromBuffer(hexToBuffer(sig.r)), Buffer32.fromBuffer(hexToBuffer(sig.s)), sig.yParity);
78
80
  }
79
81
 
82
+ /** Generates a random valid ECDSA signature with a low s-value by signing a random message with a random key. */
80
83
  static random(): Signature {
81
- return new Signature(Buffer32.random(), Buffer32.random(), 1);
84
+ const privateKey = randomBytes(32);
85
+ const message = randomBytes(32);
86
+ const { r, s, recovery } = secp256k1.sign(message, privateKey);
87
+ return new Signature(Buffer32.fromBigInt(r), Buffer32.fromBigInt(s), recovery ? 28 : 27);
82
88
  }
83
89
 
84
90
  static empty(): Signature {
@@ -1,3 +1,4 @@
1
+ import { parseBooleanEnv } from '@aztec/foundation/config';
1
2
  import { overwriteLoggingStream, pinoPrettyOpts } from '@aztec/foundation/log';
2
3
 
3
4
  import pretty from 'pino-pretty';
@@ -6,4 +7,33 @@ import pretty from 'pino-pretty';
6
7
  // file so we don't mess up with dependencies in non-testing environments,
7
8
  // since pino-pretty messes up with browser bundles.
8
9
  // See also https://www.npmjs.com/package/pino-pretty?activeTab=readme#user-content-usage-with-jest
9
- overwriteLoggingStream(pretty(pinoPrettyOpts));
10
+ if (!parseBooleanEnv(process.env.LOG_JSON)) {
11
+ overwriteLoggingStream(pretty(pinoPrettyOpts));
12
+ }
13
+
14
+ // Prevent timers from keeping the process alive after tests complete.
15
+ // Libraries like viem create internal polling loops (via setTimeout) that
16
+ // reschedule themselves indefinitely. In test environments we never want a
17
+ // timer to be the reason the process can't exit. We also unref stdout/stderr
18
+ // which, when they are pipes (as in Jest workers), remain ref'd by default.
19
+ {
20
+ const origSetTimeout = globalThis.setTimeout;
21
+ const origSetInterval = globalThis.setInterval;
22
+ globalThis.setTimeout = function unrefSetTimeout(...args) {
23
+ const id = origSetTimeout.apply(this, args);
24
+ id?.unref?.();
25
+ return id;
26
+ };
27
+ // Preserve .unref, .__promisify__ etc. that may exist on the original
28
+ Object.setPrototypeOf(globalThis.setTimeout, origSetTimeout);
29
+
30
+ globalThis.setInterval = function unrefSetInterval(...args) {
31
+ const id = origSetInterval.apply(this, args);
32
+ id?.unref?.();
33
+ return id;
34
+ };
35
+ Object.setPrototypeOf(globalThis.setInterval, origSetInterval);
36
+
37
+ if (process.stdout?._handle?.unref) process.stdout._handle.unref();
38
+ if (process.stderr?._handle?.unref) process.stderr._handle.unref();
39
+ }
@@ -24,6 +24,7 @@ export type SafeJsonRpcClientOptions = {
24
24
  batchWindowMS?: number;
25
25
  maxBatchSize?: number;
26
26
  maxRequestBodySize?: number;
27
+ extraHeaders?: Record<string, string>;
27
28
  onResponse?: (res: {
28
29
  response: any;
29
30
  headers: { get: (header: string) => string | null | undefined };
@@ -129,6 +130,7 @@ export function createSafeJsonRpcClient<T extends object>(
129
130
  const { response, headers } = await fetch(
130
131
  host,
131
132
  rpcCalls.map(({ request }) => request),
133
+ config.extraHeaders,
132
134
  );
133
135
 
134
136
  if (config.onResponse) {
@@ -1,3 +1,5 @@
1
+ import { promisify } from 'node:util';
2
+ import { gunzip as gunzipCb, gzip as gzipCb } from 'node:zlib';
1
3
  import { Agent, type Dispatcher } from 'undici';
2
4
 
3
5
  import { createLogger } from '../../log/pino-logger.js';
@@ -5,8 +7,14 @@ import { NoRetryError } from '../../retry/index.js';
5
7
  import { jsonStringify } from '../convert.js';
6
8
  import type { JsonRpcFetch } from './fetch.js';
7
9
 
10
+ const gzip = promisify(gzipCb);
11
+ const gunzip = promisify(gunzipCb);
12
+
8
13
  const log = createLogger('json-rpc:json_rpc_client:undici');
9
14
 
15
+ /** Minimum request size in bytes to trigger compression. */
16
+ const COMPRESSION_THRESHOLD = 1024;
17
+
10
18
  export { Agent };
11
19
 
12
20
  export function makeUndiciFetch(client = new Agent()): JsonRpcFetch {
@@ -14,14 +22,18 @@ export function makeUndiciFetch(client = new Agent()): JsonRpcFetch {
14
22
  log.trace(`JsonRpcClient.fetch: ${host}`, { host, body });
15
23
  let resp: Dispatcher.ResponseData;
16
24
  try {
25
+ const jsonBody = Buffer.from(jsonStringify(body));
26
+ const shouldCompress = jsonBody.length >= COMPRESSION_THRESHOLD;
17
27
  resp = await client.request({
18
28
  method: 'POST',
19
29
  origin: new URL(host),
20
30
  path: '/',
21
- body: jsonStringify(body),
31
+ body: shouldCompress ? await gzip(jsonBody) : jsonBody,
22
32
  headers: {
23
33
  ...extraHeaders,
24
34
  'content-type': 'application/json',
35
+ ...(shouldCompress && { 'content-encoding': 'gzip' }),
36
+ 'accept-encoding': 'gzip',
25
37
  },
26
38
  });
27
39
  } catch (err) {
@@ -31,13 +43,19 @@ export function makeUndiciFetch(client = new Agent()): JsonRpcFetch {
31
43
 
32
44
  let responseJson: any;
33
45
  const responseOk = resp.statusCode >= 200 && resp.statusCode <= 299;
46
+ const contentEncoding = resp.headers['content-encoding'];
34
47
  try {
35
- responseJson = await resp.body.json();
48
+ if (contentEncoding === 'gzip') {
49
+ const jsonBuffer = await gunzip(await resp.body.arrayBuffer());
50
+ responseJson = JSON.parse(jsonBuffer.toString('utf-8'));
51
+ } else {
52
+ responseJson = await resp.body.json();
53
+ }
36
54
  } catch {
37
55
  if (!responseOk) {
38
56
  throw new Error('HTTP ' + resp.statusCode);
39
57
  }
40
- throw new Error(`Failed to parse body as JSON: ${await resp.body.text()}`);
58
+ throw new Error(`Failed to parse body as JSON. encoding: ${contentEncoding}, body: ${await resp.body.text()}`);
41
59
  }
42
60
 
43
61
  if (!responseOk) {
@@ -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';
@@ -35,7 +35,7 @@ export type SafeJsonRpcServerConfig = {
35
35
  const defaultServerConfig: SafeJsonRpcServerConfig = {
36
36
  http200OnError: false,
37
37
  maxBatchSize: 100,
38
- maxBodySizeBytes: '50mb',
38
+ maxBodySizeBytes: '1mb',
39
39
  };
40
40
 
41
41
  export class SafeJsonRpcServer {