@aztec/foundation 0.0.1-commit.dbf9cec → 0.0.1-commit.e0f15ab9b

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 (58) 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/index.d.ts +2 -1
  5. package/dest/buffer/index.d.ts.map +1 -1
  6. package/dest/buffer/index.js +1 -0
  7. package/dest/buffer/utils.d.ts +3 -0
  8. package/dest/buffer/utils.d.ts.map +1 -0
  9. package/dest/buffer/utils.js +7 -0
  10. package/dest/config/env_var.d.ts +2 -2
  11. package/dest/config/env_var.d.ts.map +1 -1
  12. package/dest/config/index.d.ts +1 -1
  13. package/dest/config/index.d.ts.map +1 -1
  14. package/dest/config/index.js +15 -0
  15. package/dest/config/network_config.d.ts +19 -1
  16. package/dest/config/network_config.d.ts.map +1 -1
  17. package/dest/config/network_config.js +4 -1
  18. package/dest/crypto/poseidon/index.d.ts +1 -1
  19. package/dest/crypto/poseidon/index.d.ts.map +1 -1
  20. package/dest/crypto/poseidon/index.js +40 -33
  21. package/dest/crypto/secp256k1-signer/utils.d.ts +12 -1
  22. package/dest/crypto/secp256k1-signer/utils.d.ts.map +1 -1
  23. package/dest/crypto/secp256k1-signer/utils.js +26 -0
  24. package/dest/eth-signature/eth_signature.d.ts +2 -1
  25. package/dest/eth-signature/eth_signature.d.ts.map +1 -1
  26. package/dest/eth-signature/eth_signature.js +7 -2
  27. package/dest/fifo/fifo_frame_reader.d.ts +41 -0
  28. package/dest/fifo/fifo_frame_reader.d.ts.map +1 -0
  29. package/dest/fifo/fifo_frame_reader.js +74 -0
  30. package/dest/fifo/index.d.ts +2 -0
  31. package/dest/fifo/index.d.ts.map +1 -0
  32. package/dest/fifo/index.js +1 -0
  33. package/dest/jest/setup.js +24 -0
  34. package/dest/log/bigint-utils.d.ts +1 -1
  35. package/dest/log/bigint-utils.d.ts.map +1 -1
  36. package/dest/log/bigint-utils.js +3 -0
  37. package/dest/sleep/index.d.ts +2 -1
  38. package/dest/sleep/index.d.ts.map +1 -1
  39. package/dest/sleep/index.js +10 -1
  40. package/dest/trees/indexed_merkle_tree_calculator.d.ts +1 -1
  41. package/dest/trees/indexed_merkle_tree_calculator.d.ts.map +1 -1
  42. package/dest/trees/indexed_merkle_tree_calculator.js +5 -1
  43. package/package.json +3 -2
  44. package/src/branded-types/slot.ts +5 -0
  45. package/src/buffer/index.ts +1 -0
  46. package/src/buffer/utils.ts +8 -0
  47. package/src/config/env_var.ts +19 -3
  48. package/src/config/index.ts +15 -0
  49. package/src/config/network_config.ts +3 -0
  50. package/src/crypto/poseidon/index.ts +42 -34
  51. package/src/crypto/secp256k1-signer/utils.ts +32 -0
  52. package/src/eth-signature/eth_signature.ts +7 -1
  53. package/src/fifo/fifo_frame_reader.ts +98 -0
  54. package/src/fifo/index.ts +1 -0
  55. package/src/jest/setup.mjs +27 -0
  56. package/src/log/bigint-utils.ts +3 -0
  57. package/src/sleep/index.ts +10 -1
  58. package/src/trees/indexed_merkle_tree_calculator.ts +5 -1
@@ -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,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';
@@ -10,3 +10,30 @@ import pretty from 'pino-pretty';
10
10
  if (!parseBooleanEnv(process.env.LOG_JSON)) {
11
11
  overwriteLoggingStream(pretty(pinoPrettyOpts));
12
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
+ }
@@ -11,6 +11,9 @@ export function convertBigintsToStrings(obj: unknown): unknown {
11
11
  }
12
12
 
13
13
  if (obj !== null && typeof obj === 'object') {
14
+ if (typeof (obj as any).toJSON === 'function') {
15
+ return convertBigintsToStrings((obj as any).toJSON());
16
+ }
14
17
  const result: Record<string, unknown> = {};
15
18
  for (const key in obj) {
16
19
  result[key] = convertBigintsToStrings((obj as Record<string, unknown>)[key]);
@@ -22,6 +22,7 @@ import { InterruptError } from '../error/index.js';
22
22
  */
23
23
  export class InterruptibleSleep {
24
24
  private interrupts: Array<(shouldThrow: boolean) => void> = [];
25
+ private timeoutIds: NodeJS.Timeout[] = [];
25
26
 
26
27
  /**
27
28
  * Sleep for a specified amount of time in milliseconds.
@@ -38,9 +39,15 @@ export class InterruptibleSleep {
38
39
  this.interrupts.push(resolve);
39
40
  });
40
41
 
41
- const timeoutPromise = new Promise<boolean>(resolve => setTimeout(() => resolve(false), ms));
42
+ let timeoutId: NodeJS.Timeout;
43
+ const timeoutPromise = new Promise<boolean>(resolve => {
44
+ timeoutId = setTimeout(() => resolve(false), ms);
45
+ this.timeoutIds.push(timeoutId);
46
+ });
42
47
  const shouldThrow = await Promise.race([interruptPromise, timeoutPromise]);
43
48
 
49
+ clearTimeout(timeoutId!);
50
+ this.timeoutIds = this.timeoutIds.filter(id => id !== timeoutId);
44
51
  this.interrupts = this.interrupts.filter(res => res !== interruptResolve);
45
52
 
46
53
  if (shouldThrow) {
@@ -58,6 +65,8 @@ export class InterruptibleSleep {
58
65
  public interrupt(sleepShouldThrow = false): void {
59
66
  this.interrupts.forEach(resolve => resolve(sleepShouldThrow));
60
67
  this.interrupts = [];
68
+ this.timeoutIds.forEach(id => clearTimeout(id));
69
+ this.timeoutIds = [];
61
70
  }
62
71
  }
63
72
 
@@ -40,7 +40,11 @@ export class IndexedMerkleTreeCalculator<T extends IndexedTreeLeafPreimage, N ex
40
40
  }
41
41
  const sorted = values
42
42
  .map((v, i) => ({ value: v, index: i }))
43
- .sort((a, b) => Number(toBigIntBE(b.value) - toBigIntBE(a.value)));
43
+ .sort((a, b): -1 | 0 | 1 => {
44
+ const aBigInt = toBigIntBE(a.value);
45
+ const bBigInt = toBigIntBE(b.value);
46
+ return aBigInt < bBigInt ? 1 : aBigInt > bBigInt ? -1 : 0;
47
+ });
44
48
  const indexedLeaves = sorted.map((item, i) => ({
45
49
  leaf: this.factory.fromBuffer(
46
50
  Buffer.concat([