@aztec/foundation 3.0.3 → 3.9.9-nightly.20260312

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 (226) hide show
  1. package/dest/array/index.d.ts +2 -1
  2. package/dest/array/index.d.ts.map +1 -1
  3. package/dest/array/index.js +1 -0
  4. package/dest/array/sorted_array.d.ts +15 -0
  5. package/dest/array/sorted_array.d.ts.map +1 -0
  6. package/dest/array/sorted_array.js +109 -0
  7. package/dest/branded-types/block_number.d.ts +4 -1
  8. package/dest/branded-types/block_number.d.ts.map +1 -1
  9. package/dest/branded-types/block_number.js +3 -0
  10. package/dest/branded-types/checkpoint_number.d.ts +10 -2
  11. package/dest/branded-types/checkpoint_number.d.ts.map +1 -1
  12. package/dest/branded-types/checkpoint_number.js +17 -8
  13. package/dest/branded-types/index.d.ts +3 -2
  14. package/dest/branded-types/index.d.ts.map +1 -1
  15. package/dest/branded-types/index.js +2 -1
  16. package/dest/branded-types/index_within_checkpoint.d.ts +42 -0
  17. package/dest/branded-types/index_within_checkpoint.d.ts.map +1 -0
  18. package/dest/branded-types/index_within_checkpoint.js +59 -0
  19. package/dest/buffer/buffer16.d.ts +4 -1
  20. package/dest/buffer/buffer16.d.ts.map +1 -1
  21. package/dest/buffer/buffer16.js +3 -1
  22. package/dest/buffer/buffer32.d.ts +4 -1
  23. package/dest/buffer/buffer32.d.ts.map +1 -1
  24. package/dest/buffer/buffer32.js +3 -1
  25. package/dest/collection/array.d.ts +12 -1
  26. package/dest/collection/array.d.ts.map +1 -1
  27. package/dest/collection/array.js +51 -0
  28. package/dest/config/env_var.d.ts +2 -2
  29. package/dest/config/env_var.d.ts.map +1 -1
  30. package/dest/config/index.d.ts +6 -3
  31. package/dest/config/index.d.ts.map +1 -1
  32. package/dest/config/index.js +31 -7
  33. package/dest/config/network_config.d.ts +31 -1
  34. package/dest/config/network_config.d.ts.map +1 -1
  35. package/dest/config/network_config.js +6 -1
  36. package/dest/config/parse-env.d.ts +3 -0
  37. package/dest/config/parse-env.d.ts.map +1 -0
  38. package/dest/config/parse-env.js +7 -0
  39. package/dest/config/secret_value.js +3 -1
  40. package/dest/crypto/ecdsa/signature.d.ts +10 -1
  41. package/dest/crypto/ecdsa/signature.d.ts.map +1 -1
  42. package/dest/crypto/poseidon/index.d.ts +1 -2
  43. package/dest/crypto/poseidon/index.d.ts.map +1 -1
  44. package/dest/crypto/poseidon/index.js +13 -22
  45. package/dest/crypto/random/randomness_singleton.d.ts +4 -3
  46. package/dest/crypto/random/randomness_singleton.d.ts.map +1 -1
  47. package/dest/crypto/random/randomness_singleton.js +5 -5
  48. package/dest/crypto/secp256k1-signer/utils.d.ts +12 -1
  49. package/dest/crypto/secp256k1-signer/utils.d.ts.map +1 -1
  50. package/dest/crypto/secp256k1-signer/utils.js +26 -0
  51. package/dest/crypto/sync/poseidon/index.d.ts +1 -2
  52. package/dest/crypto/sync/poseidon/index.d.ts.map +1 -1
  53. package/dest/crypto/sync/poseidon/index.js +0 -8
  54. package/dest/curves/bls12/field.js +6 -3
  55. package/dest/curves/bls12/point.d.ts +10 -1
  56. package/dest/curves/bls12/point.d.ts.map +1 -1
  57. package/dest/curves/bls12/point.js +3 -1
  58. package/dest/curves/bn254/field.d.ts +7 -7
  59. package/dest/curves/bn254/field.d.ts.map +1 -1
  60. package/dest/curves/bn254/field.js +33 -43
  61. package/dest/curves/grumpkin/point.d.ts +11 -2
  62. package/dest/curves/grumpkin/point.d.ts.map +1 -1
  63. package/dest/error/index.d.ts +4 -4
  64. package/dest/error/index.d.ts.map +1 -1
  65. package/dest/eth-address/index.js +4 -2
  66. package/dest/eth-signature/eth_signature.d.ts +5 -1
  67. package/dest/eth-signature/eth_signature.d.ts.map +1 -1
  68. package/dest/eth-signature/eth_signature.js +7 -2
  69. package/dest/iterator/filter.d.ts +3 -0
  70. package/dest/iterator/filter.d.ts.map +1 -0
  71. package/dest/iterator/filter.js +7 -0
  72. package/dest/iterator/index.d.ts +2 -0
  73. package/dest/iterator/index.d.ts.map +1 -0
  74. package/dest/iterator/index.js +1 -0
  75. package/dest/jest/setup.js +4 -1
  76. package/dest/json-rpc/client/safe_json_rpc_client.d.ts +2 -1
  77. package/dest/json-rpc/client/safe_json_rpc_client.d.ts.map +1 -1
  78. package/dest/json-rpc/client/safe_json_rpc_client.js +1 -1
  79. package/dest/json-rpc/client/undici.d.ts +1 -1
  80. package/dest/json-rpc/client/undici.d.ts.map +1 -1
  81. package/dest/json-rpc/client/undici.js +21 -4
  82. package/dest/json-rpc/fixtures/class_a.d.ts +3 -3
  83. package/dest/json-rpc/fixtures/class_a.d.ts.map +1 -1
  84. package/dest/json-rpc/fixtures/class_b.d.ts +3 -3
  85. package/dest/json-rpc/fixtures/class_b.d.ts.map +1 -1
  86. package/dest/json-rpc/server/api_key_auth.d.ts +19 -0
  87. package/dest/json-rpc/server/api_key_auth.d.ts.map +1 -0
  88. package/dest/json-rpc/server/api_key_auth.js +57 -0
  89. package/dest/json-rpc/server/index.d.ts +2 -1
  90. package/dest/json-rpc/server/index.d.ts.map +1 -1
  91. package/dest/json-rpc/server/index.js +1 -0
  92. package/dest/json-rpc/server/safe_json_rpc_server.js +1 -1
  93. package/dest/log/bigint-utils.d.ts +5 -0
  94. package/dest/log/bigint-utils.d.ts.map +1 -0
  95. package/dest/log/bigint-utils.js +21 -0
  96. package/dest/log/gcloud-logger-config.d.ts +1 -1
  97. package/dest/log/gcloud-logger-config.d.ts.map +1 -1
  98. package/dest/log/gcloud-logger-config.js +3 -0
  99. package/dest/log/libp2p_logger.d.ts +5 -2
  100. package/dest/log/libp2p_logger.d.ts.map +1 -1
  101. package/dest/log/libp2p_logger.js +14 -4
  102. package/dest/log/log-filters.d.ts +17 -4
  103. package/dest/log/log-filters.d.ts.map +1 -1
  104. package/dest/log/log-filters.js +26 -12
  105. package/dest/log/pino-logger-server.d.ts +9 -0
  106. package/dest/log/pino-logger-server.d.ts.map +1 -0
  107. package/dest/log/pino-logger-server.js +18 -0
  108. package/dest/log/pino-logger.d.ts +37 -8
  109. package/dest/log/pino-logger.d.ts.map +1 -1
  110. package/dest/log/pino-logger.js +122 -29
  111. package/dest/queue/base_memory_queue.d.ts +2 -2
  112. package/dest/queue/base_memory_queue.d.ts.map +1 -1
  113. package/dest/queue/semaphore.d.ts +5 -1
  114. package/dest/queue/semaphore.d.ts.map +1 -1
  115. package/dest/retry/index.d.ts +11 -1
  116. package/dest/retry/index.d.ts.map +1 -1
  117. package/dest/retry/index.js +11 -0
  118. package/dest/schemas/schemas.d.ts +3 -1
  119. package/dest/schemas/schemas.d.ts.map +1 -1
  120. package/dest/schemas/schemas.js +5 -0
  121. package/dest/schemas/types.d.ts +31 -1
  122. package/dest/schemas/types.d.ts.map +1 -1
  123. package/dest/schemas/types.js +25 -1
  124. package/dest/serialize/buffer_reader.d.ts +14 -4
  125. package/dest/serialize/buffer_reader.d.ts.map +1 -1
  126. package/dest/serialize/buffer_reader.js +26 -4
  127. package/dest/serialize/serialize.d.ts +19 -1
  128. package/dest/serialize/serialize.d.ts.map +1 -1
  129. package/dest/serialize/serialize.js +31 -0
  130. package/dest/sleep/index.d.ts +3 -1
  131. package/dest/sleep/index.d.ts.map +1 -1
  132. package/dest/sleep/index.js +4 -0
  133. package/dest/timer/date.d.ts +24 -1
  134. package/dest/timer/date.d.ts.map +1 -1
  135. package/dest/timer/date.js +32 -0
  136. package/dest/transport/transport_client.js +2 -2
  137. package/dest/trees/balanced_merkle_tree_root.d.ts +17 -0
  138. package/dest/trees/balanced_merkle_tree_root.d.ts.map +1 -0
  139. package/dest/trees/{balanced_merkle_tree.js → balanced_merkle_tree_root.js} +2 -17
  140. package/dest/trees/hasher.d.ts +3 -1
  141. package/dest/trees/hasher.d.ts.map +1 -1
  142. package/dest/trees/hasher.js +10 -5
  143. package/dest/trees/index.d.ts +4 -4
  144. package/dest/trees/index.d.ts.map +1 -1
  145. package/dest/trees/index.js +3 -3
  146. package/dest/trees/membership_witness.d.ts +11 -1
  147. package/dest/trees/membership_witness.d.ts.map +1 -1
  148. package/dest/trees/membership_witness.js +9 -0
  149. package/dest/trees/merkle_tree_calculator.d.ts +1 -1
  150. package/dest/trees/merkle_tree_calculator.d.ts.map +1 -1
  151. package/dest/trees/merkle_tree_calculator.js +2 -2
  152. package/dest/trees/sibling_path.d.ts +2 -1
  153. package/dest/trees/sibling_path.d.ts.map +1 -1
  154. package/dest/trees/sibling_path.js +2 -2
  155. package/dest/trees/unbalanced_merkle_tree_calculator.d.ts +2 -3
  156. package/dest/trees/unbalanced_merkle_tree_calculator.d.ts.map +1 -1
  157. package/dest/trees/unbalanced_merkle_tree_calculator.js +1 -5
  158. package/dest/trees/{unbalanced_merkle_tree.d.ts → unbalanced_merkle_tree_root.d.ts} +3 -5
  159. package/dest/trees/unbalanced_merkle_tree_root.d.ts.map +1 -0
  160. package/dest/trees/{unbalanced_merkle_tree.js → unbalanced_merkle_tree_root.js} +11 -49
  161. package/dest/trees/unbalanced_tree_store.d.ts +5 -1
  162. package/dest/trees/unbalanced_tree_store.d.ts.map +1 -1
  163. package/dest/trees/unbalanced_tree_store.js +49 -1
  164. package/dest/types/index.d.ts +6 -2
  165. package/dest/types/index.d.ts.map +1 -1
  166. package/dest/types/index.js +6 -0
  167. package/package.json +26 -4
  168. package/src/array/index.ts +1 -0
  169. package/src/array/sorted_array.ts +138 -0
  170. package/src/branded-types/block_number.ts +5 -0
  171. package/src/branded-types/checkpoint_number.ts +22 -7
  172. package/src/branded-types/index.ts +2 -1
  173. package/src/branded-types/index_within_checkpoint.ts +88 -0
  174. package/src/collection/array.ts +52 -0
  175. package/src/config/env_var.ts +75 -15
  176. package/src/config/index.ts +34 -4
  177. package/src/config/network_config.ts +5 -0
  178. package/src/config/parse-env.ts +4 -0
  179. package/src/crypto/poseidon/index.ts +13 -23
  180. package/src/crypto/random/randomness_singleton.ts +6 -4
  181. package/src/crypto/secp256k1-signer/utils.ts +32 -0
  182. package/src/crypto/sync/poseidon/index.ts +0 -9
  183. package/src/curves/bn254/field.ts +32 -43
  184. package/src/eth-address/index.ts +1 -1
  185. package/src/eth-signature/eth_signature.ts +7 -1
  186. package/src/iterator/filter.ts +11 -0
  187. package/src/iterator/index.ts +1 -0
  188. package/src/jest/setup.mjs +4 -1
  189. package/src/json-rpc/client/safe_json_rpc_client.ts +2 -0
  190. package/src/json-rpc/client/undici.ts +21 -3
  191. package/src/json-rpc/server/api_key_auth.ts +63 -0
  192. package/src/json-rpc/server/index.ts +1 -0
  193. package/src/json-rpc/server/safe_json_rpc_server.ts +1 -1
  194. package/src/log/bigint-utils.ts +25 -0
  195. package/src/log/gcloud-logger-config.ts +5 -0
  196. package/src/log/libp2p_logger.ts +12 -5
  197. package/src/log/log-filters.ts +29 -11
  198. package/src/log/pino-logger-server.ts +25 -0
  199. package/src/log/pino-logger.ts +144 -39
  200. package/src/queue/base_memory_queue.ts +1 -1
  201. package/src/queue/semaphore.ts +5 -0
  202. package/src/retry/index.ts +18 -0
  203. package/src/schemas/schemas.ts +8 -0
  204. package/src/schemas/types.ts +33 -0
  205. package/src/serialize/buffer_reader.ts +36 -9
  206. package/src/serialize/serialize.ts +32 -0
  207. package/src/sleep/index.ts +6 -0
  208. package/src/timer/date.ts +46 -0
  209. package/src/transport/transport_client.ts +2 -2
  210. package/src/trees/{balanced_merkle_tree.ts → balanced_merkle_tree_root.ts} +2 -18
  211. package/src/trees/hasher.ts +9 -0
  212. package/src/trees/index.ts +3 -3
  213. package/src/trees/membership_witness.ts +8 -0
  214. package/src/trees/merkle_tree_calculator.ts +2 -2
  215. package/src/trees/sibling_path.ts +2 -2
  216. package/src/trees/unbalanced_merkle_tree_calculator.ts +1 -12
  217. package/src/trees/{unbalanced_merkle_tree.ts → unbalanced_merkle_tree_root.ts} +17 -61
  218. package/src/trees/unbalanced_tree_store.ts +57 -2
  219. package/src/types/index.ts +11 -1
  220. package/dest/json-rpc/server/telemetry.d.ts +0 -2
  221. package/dest/json-rpc/server/telemetry.d.ts.map +0 -1
  222. package/dest/json-rpc/server/telemetry.js +0 -0
  223. package/dest/trees/balanced_merkle_tree.d.ts +0 -22
  224. package/dest/trees/balanced_merkle_tree.d.ts.map +0 -1
  225. package/dest/trees/unbalanced_merkle_tree.d.ts.map +0 -1
  226. package/src/json-rpc/server/telemetry.ts +0 -0
@@ -8,8 +8,6 @@ import { hexSchemaFor } from '../../schemas/utils.js';
8
8
  import { BufferReader } from '../../serialize/buffer_reader.js';
9
9
  import { TypeRegistry } from '../../serialize/type_registry.js';
10
10
 
11
- const ZERO_BUFFER = Buffer.alloc(32);
12
-
13
11
  /* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */
14
12
 
15
13
  /**
@@ -25,14 +23,12 @@ type DerivedField<T extends BaseField> = {
25
23
 
26
24
  /**
27
25
  * Base field class.
28
- * Conversions from Buffer to BigInt and vice-versa are not cheap.
29
- * We allow construction with either form and lazily convert to other as needed.
30
- * We only check we are within the field modulus when initializing with bigint.
26
+ * Uses bigint as the internal representation.
27
+ * Buffers are generated on demand from the bigint value.
31
28
  */
32
29
  abstract class BaseField {
33
30
  static SIZE_IN_BYTES = 32;
34
- private asBuffer?: Buffer;
35
- private asBigInt?: bigint;
31
+ private readonly asBigInt: bigint;
36
32
 
37
33
  /**
38
34
  * Return bigint representation.
@@ -52,53 +48,41 @@ abstract class BaseField {
52
48
  if (value.length > BaseField.SIZE_IN_BYTES) {
53
49
  throw new Error(`Value length ${value.length} exceeds ${BaseField.SIZE_IN_BYTES}`);
54
50
  }
55
- this.asBuffer =
56
- value.length === BaseField.SIZE_IN_BYTES
57
- ? value
58
- : Buffer.concat([Buffer.alloc(BaseField.SIZE_IN_BYTES - value.length), value]);
51
+ this.asBigInt = toBigIntBE(value);
59
52
  } else if (typeof value === 'bigint' || typeof value === 'number' || typeof value === 'boolean') {
60
53
  this.asBigInt = BigInt(value);
61
- if (this.asBigInt >= this.modulus()) {
62
- throw new Error(`Value 0x${this.asBigInt.toString(16)} is greater or equal to field modulus.`);
63
- } else if (this.asBigInt < 0n) {
64
- throw new Error(`Value 0x${this.asBigInt.toString(16)} is negative.`);
65
- }
66
54
  } else if (value instanceof BaseField) {
67
- this.asBuffer = value.asBuffer;
68
55
  this.asBigInt = value.asBigInt;
69
56
  } else {
70
57
  throw new Error(`Type '${typeof value}' with value '${value}' passed to BaseField ctor.`);
71
58
  }
59
+
60
+ if (this.asBigInt < 0n) {
61
+ throw new Error(`Value 0x${this.asBigInt.toString(16)} is negative.`);
62
+ } else if (this.asBigInt >= this.modulus()) {
63
+ throw new Error(`Value 0x${this.asBigInt.toString(16)} is greater or equal to field modulus.`);
64
+ }
72
65
  }
73
66
 
74
67
  protected abstract modulus(): bigint;
75
68
 
76
69
  /**
77
- * We return a copy of the Buffer to ensure this remains immutable.
70
+ * Converts the bigint to a Buffer.
78
71
  */
79
72
  toBuffer(): Buffer {
80
- if (!this.asBuffer) {
81
- this.asBuffer = toBufferBE(this.asBigInt!, 32);
82
- }
83
- return Buffer.from(this.asBuffer);
73
+ return toBufferBE(this.asBigInt, 32);
84
74
  }
85
75
 
86
76
  toString(): `0x${string}` {
87
- return `0x${this.toBuffer().toString('hex')}`;
77
+ return `0x${this.asBigInt.toString(16).padStart(64, '0')}`;
88
78
  }
89
79
 
90
80
  toBigInt(): bigint {
91
- if (this.asBigInt === undefined) {
92
- this.asBigInt = toBigIntBE(this.asBuffer!);
93
- if (this.asBigInt >= this.modulus()) {
94
- throw new Error(`Value 0x${this.asBigInt.toString(16)} is greater or equal to field modulus.`);
95
- }
96
- }
97
81
  return this.asBigInt;
98
82
  }
99
83
 
100
84
  toBool(): boolean {
101
- return Boolean(this.toBigInt());
85
+ return this.asBigInt !== 0n;
102
86
  }
103
87
 
104
88
  /**
@@ -106,11 +90,10 @@ abstract class BaseField {
106
90
  * Throws if the underlying value is greater than MAX_SAFE_INTEGER.
107
91
  */
108
92
  toNumber(): number {
109
- const value = this.toBigInt();
110
- if (value > Number.MAX_SAFE_INTEGER) {
111
- throw new Error(`Value ${value.toString(16)} greater than than max safe integer`);
93
+ if (this.asBigInt > Number.MAX_SAFE_INTEGER) {
94
+ throw new Error(`Value ${this.asBigInt.toString(16)} greater than than max safe integer`);
112
95
  }
113
- return Number(value);
96
+ return Number(this.asBigInt);
114
97
  }
115
98
 
116
99
  /**
@@ -118,8 +101,7 @@ abstract class BaseField {
118
101
  * May cause loss of precision if the underlying value is greater than MAX_SAFE_INTEGER.
119
102
  */
120
103
  toNumberUnsafe(): number {
121
- const value = this.toBigInt();
122
- return Number(value);
104
+ return Number(this.asBigInt);
123
105
  }
124
106
 
125
107
  toShortString(): string {
@@ -128,21 +110,28 @@ abstract class BaseField {
128
110
  }
129
111
 
130
112
  equals(rhs: BaseField): boolean {
131
- return this.toBuffer().equals(rhs.toBuffer());
113
+ return this.asBigInt === rhs.asBigInt;
132
114
  }
133
115
 
134
116
  lt(rhs: BaseField): boolean {
135
- return this.toBigInt() < rhs.toBigInt();
117
+ return this.asBigInt < rhs.asBigInt;
136
118
  }
137
119
 
138
120
  cmp(rhs: BaseField): -1 | 0 | 1 {
139
- const lhsBigInt = this.toBigInt();
140
- const rhsBigInt = rhs.toBigInt();
141
- return lhsBigInt === rhsBigInt ? 0 : lhsBigInt < rhsBigInt ? -1 : 1;
121
+ return BaseField.cmpAsBigInt(this.asBigInt, rhs.asBigInt);
122
+ }
123
+
124
+ static cmp(lhs: BaseField, rhs: BaseField): -1 | 0 | 1 {
125
+ return lhs.cmp(rhs);
126
+ }
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;
142
131
  }
143
132
 
144
133
  isZero(): boolean {
145
- return this.toBuffer().equals(ZERO_BUFFER);
134
+ return this.asBigInt === 0n;
146
135
  }
147
136
 
148
137
  isEmpty(): boolean {
@@ -195,7 +184,7 @@ function fromHexString<T extends BaseField>(buf: string, f: DerivedField<T>) {
195
184
 
196
185
  const buffer = Buffer.from(checked.length % 2 === 1 ? '0' + checked : checked, 'hex');
197
186
 
198
- return new f(buffer);
187
+ return new f(toBigIntBE(buffer));
199
188
  }
200
189
 
201
190
  /** Branding to ensure fields are not interchangeable types. */
@@ -249,7 +249,7 @@ export class EthAddress {
249
249
  /** Converts a number into an address. Useful for testing. */
250
250
  static fromNumber(num: bigint | number): EthAddress {
251
251
  const buffer = Buffer.alloc(EthAddress.SIZE_IN_BYTES);
252
- buffer.writeBigUInt64BE(BigInt(num), 0);
252
+ buffer.writeBigUInt64BE(BigInt(num), EthAddress.SIZE_IN_BYTES - 8);
253
253
  return new EthAddress(buffer);
254
254
  }
255
255
 
@@ -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 {
@@ -0,0 +1,11 @@
1
+ /** Wraps an async iterable iterator such that it filters values based on a predicate. */
2
+ export async function* filter<T>(
3
+ iterator: AsyncIterableIterator<T>,
4
+ predicate: (item: T) => boolean | Promise<boolean>,
5
+ ): AsyncIterableIterator<T> {
6
+ for await (const item of iterator) {
7
+ if (await predicate(item)) {
8
+ yield item;
9
+ }
10
+ }
11
+ }
@@ -0,0 +1 @@
1
+ export { filter } from './filter.js';
@@ -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,6 @@ 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
+ }
@@ -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 {
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Converts bigint values to strings recursively in a log object to avoid serialization issues.
3
+ */
4
+ export function convertBigintsToStrings(obj: unknown): unknown {
5
+ if (typeof obj === 'bigint') {
6
+ return String(obj);
7
+ }
8
+
9
+ if (Array.isArray(obj)) {
10
+ return obj.map(item => convertBigintsToStrings(item));
11
+ }
12
+
13
+ if (obj !== null && typeof obj === 'object') {
14
+ if (typeof (obj as any).toJSON === 'function') {
15
+ return convertBigintsToStrings((obj as any).toJSON());
16
+ }
17
+ const result: Record<string, unknown> = {};
18
+ for (const key in obj) {
19
+ result[key] = convertBigintsToStrings((obj as Record<string, unknown>)[key]);
20
+ }
21
+ return result;
22
+ }
23
+
24
+ return obj;
25
+ }
@@ -1,5 +1,7 @@
1
1
  import type { pino } from 'pino';
2
2
 
3
+ import { convertBigintsToStrings } from './bigint-utils.js';
4
+
3
5
  /* eslint-disable camelcase */
4
6
 
5
7
  const GOOGLE_CLOUD_TRACE_ID = 'logging.googleapis.com/trace';
@@ -15,6 +17,9 @@ export const GoogleCloudLoggerConfig = {
15
17
  messageKey: 'message',
16
18
  formatters: {
17
19
  log(object: Record<string, unknown>): Record<string, unknown> {
20
+ // Convert bigints to strings recursively to avoid serialization issues
21
+ object = convertBigintsToStrings(object) as Record<string, unknown>;
22
+
18
23
  // Add trace context attributes following Cloud Logging structured log format described
19
24
  // in https://cloud.google.com/logging/docs/structured-logging#special-payload-fields
20
25
  const { trace_id, span_id, trace_flags, ...rest } = object;
@@ -2,15 +2,17 @@ import type { ComponentLogger, Logger } from '@libp2p/interface';
2
2
 
3
3
  import { getLogLevelFromFilters } from './log-filters.js';
4
4
  import type { LogLevel } from './log-levels.js';
5
- import { logFilters, logger } from './pino-logger.js';
5
+ import { type LoggerBindings, logFilters, logger } from './pino-logger.js';
6
6
 
7
7
  /**
8
8
  * Creates a libp2p compatible logger that wraps our pino logger.
9
9
  * This adapter implements the ComponentLogger interface required by libp2p.
10
+ * @param namespace - Base namespace for the logger
11
+ * @param bindings - Optional bindings to pass to the logger (actor, instanceId)
10
12
  */
11
- export function createLibp2pComponentLogger(namespace: string): ComponentLogger {
13
+ export function createLibp2pComponentLogger(namespace: string, bindings?: LoggerBindings): ComponentLogger {
12
14
  return {
13
- forComponent: (component: string) => createLibp2pLogger(`${namespace}:${component}`),
15
+ forComponent: (component: string) => createLibp2pLogger(`${namespace}:${component}`, bindings),
14
16
  };
15
17
  }
16
18
 
@@ -24,9 +26,14 @@ function replaceFormatting(message: string) {
24
26
  return message.replace(/(%p|%a)/g, '%s');
25
27
  }
26
28
 
27
- function createLibp2pLogger(component: string): Logger {
29
+ function createLibp2pLogger(component: string, bindings?: LoggerBindings): Logger {
28
30
  // Create a direct pino logger instance for libp2p that supports string interpolation
29
- const log = logger.child({ module: component }, { level: getLogLevelFromFilters(logFilters, component) });
31
+ const actor = bindings?.actor;
32
+ const instanceId = bindings?.instanceId;
33
+ const log = logger.child(
34
+ { module: component, ...(actor && { actor }), ...(instanceId && { instanceId }) },
35
+ { level: getLogLevelFromFilters(logFilters, component) },
36
+ );
30
37
 
31
38
  const logIfEnabled = (level: LogLevel, message: string, ...args: unknown[]) => {
32
39
  if (!log.isLevelEnabled(level)) {
@@ -19,22 +19,40 @@ export function getLogLevelFromFilters(filters: LogFilters, module: string): Log
19
19
  return undefined;
20
20
  }
21
21
 
22
- export function assertLogLevel(level: string): asserts level is LogLevel {
23
- if (!LogLevels.includes(level as LogLevel)) {
24
- throw new Error(`Invalid log level: ${level}`);
22
+ /**
23
+ * Parses the LOG_LEVEL env string into a default level and per-module filter overrides.
24
+ *
25
+ * Format: `<default_level>;<level>:<module1>,<module2>;<level>:<module3>;...`
26
+ * - First segment (before the first `;`) is the default log level for all modules.
27
+ * - Remaining segments are `level:module` pairs: apply the given level to the listed modules (comma-separated).
28
+ * - Later filters override earlier ones for overlapping module matches.
29
+ * - The `aztec:` prefix is stripped from module names; spaces are trimmed.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * parseLogLevel('debug;warn:module1,module2;error:module3', 'info')
34
+ * // => ['debug', [['module3', 'error'], ['module2', 'warn'], ['module1', 'warn']]]
35
+ * ```
36
+ */
37
+ export function parseLogLevelEnvVar(
38
+ logLevelEnvVar: string | undefined,
39
+ defaultLevel: LogLevel,
40
+ ): [LogLevel, LogFilters] {
41
+ if (!logLevelEnvVar) {
42
+ return [defaultLevel, []];
25
43
  }
44
+ const [level] = logLevelEnvVar.split(';', 1);
45
+ assertValidLogLevel(level);
46
+ return [level, parseFilters(logLevelEnvVar.slice(level.length + 1))];
26
47
  }
27
48
 
28
- export function parseEnv(env: string | undefined, defaultLevel: LogLevel): [LogLevel, LogFilters] {
29
- if (!env) {
30
- return [defaultLevel, []];
49
+ function assertValidLogLevel(level: string): asserts level is LogLevel {
50
+ if (!LogLevels.includes(level as LogLevel)) {
51
+ throw new Error(`Invalid log level: ${level}`);
31
52
  }
32
- const [level] = env.split(';', 1);
33
- assertLogLevel(level);
34
- return [level, parseFilters(env.slice(level.length + 1))];
35
53
  }
36
54
 
37
- export function parseFilters(definition: string | undefined): LogFilters {
55
+ function parseFilters(definition: string | undefined): LogFilters {
38
56
  if (!definition) {
39
57
  return [];
40
58
  }
@@ -48,7 +66,7 @@ export function parseFilters(definition: string | undefined): LogFilters {
48
66
  throw new Error(`Invalid log filter statement: ${statement}`);
49
67
  }
50
68
  const sanitizedLevel = level.trim().toLowerCase();
51
- assertLogLevel(sanitizedLevel);
69
+ assertValidLogLevel(sanitizedLevel);
52
70
  for (const module of modules.split(',')) {
53
71
  filters.push([
54
72
  module
@@ -0,0 +1,25 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+
3
+ import { type LoggerBindings, addLogBindingsHandler, removeLogBindingsHandler } from './pino-logger.js';
4
+
5
+ /** AsyncLocalStorage for logger bindings context propagation (Node.js only). */
6
+ const bindingsStorage = new AsyncLocalStorage<LoggerBindings>();
7
+
8
+ /** Returns the current bindings from AsyncLocalStorage, if any. */
9
+ export function getBindings(): LoggerBindings | undefined {
10
+ return bindingsStorage.getStore();
11
+ }
12
+
13
+ /**
14
+ * Runs a callback within a bindings context. All loggers created within the callback
15
+ * will automatically inherit the bindings (actor, instanceId) via the log bindings handler.
16
+ */
17
+ export async function withLoggerBindings<T>(bindings: LoggerBindings, callback: () => Promise<T>): Promise<T> {
18
+ const handler = () => bindingsStorage.getStore();
19
+ addLogBindingsHandler(handler);
20
+ try {
21
+ return await bindingsStorage.run(bindings, callback);
22
+ } finally {
23
+ removeLogBindingsHandler(handler);
24
+ }
25
+ }