@aztec/foundation 0.16.4 → 0.16.6

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 (121) hide show
  1. package/dest/abi/function_selector.js +2 -2
  2. package/dest/aztec-address/index.js +2 -2
  3. package/dest/json-rpc/server/index.d.ts +1 -1
  4. package/dest/json-rpc/server/index.d.ts.map +1 -1
  5. package/dest/json-rpc/server/index.js +2 -2
  6. package/dest/json-rpc/server/json_rpc_server.d.ts +7 -0
  7. package/dest/json-rpc/server/json_rpc_server.d.ts.map +1 -1
  8. package/dest/json-rpc/server/json_rpc_server.js +13 -1
  9. package/package.json +2 -2
  10. package/src/abi/abi.ts +0 -310
  11. package/src/abi/abi_coder.ts +0 -25
  12. package/src/abi/decoder.ts +0 -161
  13. package/src/abi/encoder.ts +0 -120
  14. package/src/abi/function_selector.ts +0 -135
  15. package/src/abi/index.ts +0 -6
  16. package/src/abi/utils.ts +0 -28
  17. package/src/async-map/index.ts +0 -18
  18. package/src/aztec-address/index.ts +0 -30
  19. package/src/bigint-buffer/index.ts +0 -74
  20. package/src/collection/array.ts +0 -54
  21. package/src/collection/index.ts +0 -1
  22. package/src/committable/committable.ts +0 -46
  23. package/src/committable/index.ts +0 -1
  24. package/src/crypto/index.ts +0 -16
  25. package/src/crypto/keccak/index.ts +0 -33
  26. package/src/crypto/pedersen/index.ts +0 -1
  27. package/src/crypto/pedersen/pedersen.elliptic.ts +0 -584
  28. package/src/crypto/pedersen/pedersen.noble.ts +0 -573
  29. package/src/crypto/pedersen/pedersen.wasm.ts +0 -42
  30. package/src/crypto/random/index.ts +0 -42
  31. package/src/crypto/sha256/index.ts +0 -3
  32. package/src/errors/index.ts +0 -6
  33. package/src/eth-address/index.ts +0 -244
  34. package/src/fields/coordinate.ts +0 -104
  35. package/src/fields/fields.ts +0 -261
  36. package/src/fields/index.ts +0 -3
  37. package/src/fields/point.ts +0 -140
  38. package/src/fifo/bounded_serial_queue.ts +0 -100
  39. package/src/fifo/index.ts +0 -4
  40. package/src/fifo/memory_fifo.ts +0 -114
  41. package/src/fifo/semaphore.ts +0 -33
  42. package/src/fifo/serial_queue.ts +0 -78
  43. package/src/index.ts +0 -29
  44. package/src/json-rpc/README.md +0 -55
  45. package/src/json-rpc/class_converter.ts +0 -209
  46. package/src/json-rpc/client/index.ts +0 -1
  47. package/src/json-rpc/client/json_rpc_client.ts +0 -136
  48. package/src/json-rpc/convert.ts +0 -163
  49. package/src/json-rpc/fixtures/class_a.ts +0 -15
  50. package/src/json-rpc/fixtures/class_b.ts +0 -15
  51. package/src/json-rpc/fixtures/test_state.ts +0 -59
  52. package/src/json-rpc/index.ts +0 -8
  53. package/src/json-rpc/js_utils.ts +0 -20
  54. package/src/json-rpc/server/index.ts +0 -2
  55. package/src/json-rpc/server/json_proxy.ts +0 -43
  56. package/src/json-rpc/server/json_rpc_server.ts +0 -190
  57. package/src/log/console.ts +0 -39
  58. package/src/log/debug.ts +0 -83
  59. package/src/log/index.ts +0 -5
  60. package/src/log/log_fn.ts +0 -5
  61. package/src/log/log_history.ts +0 -44
  62. package/src/log/logger.ts +0 -137
  63. package/src/mutex/index.ts +0 -83
  64. package/src/mutex/mutex_database.ts +0 -12
  65. package/src/noir/index.ts +0 -1
  66. package/src/noir/noir_package_config.ts +0 -54
  67. package/src/retry/index.ts +0 -99
  68. package/src/running-promise/index.ts +0 -60
  69. package/src/serialize/buffer_reader.ts +0 -250
  70. package/src/serialize/free_funcs.ts +0 -279
  71. package/src/serialize/index.ts +0 -3
  72. package/src/serialize/types.ts +0 -40
  73. package/src/sleep/index.ts +0 -71
  74. package/src/testing/index.ts +0 -1
  75. package/src/testing/test_data.ts +0 -36
  76. package/src/timer/elapsed.ts +0 -23
  77. package/src/timer/index.ts +0 -3
  78. package/src/timer/timeout.ts +0 -64
  79. package/src/timer/timer.ts +0 -48
  80. package/src/transport/browser/index.ts +0 -4
  81. package/src/transport/browser/message_port_socket.ts +0 -48
  82. package/src/transport/browser/shared_worker_connector.ts +0 -21
  83. package/src/transport/browser/shared_worker_listener.ts +0 -53
  84. package/src/transport/browser/worker_connector.ts +0 -30
  85. package/src/transport/browser/worker_listener.ts +0 -54
  86. package/src/transport/dispatch/create_dispatch_fn.ts +0 -35
  87. package/src/transport/dispatch/create_dispatch_proxy.ts +0 -141
  88. package/src/transport/dispatch/messages.ts +0 -58
  89. package/src/transport/index.ts +0 -11
  90. package/src/transport/interface/connector.ts +0 -9
  91. package/src/transport/interface/listener.ts +0 -16
  92. package/src/transport/interface/socket.ts +0 -15
  93. package/src/transport/interface/transferable.ts +0 -125
  94. package/src/transport/node/index.ts +0 -2
  95. package/src/transport/node/node_connector.ts +0 -30
  96. package/src/transport/node/node_connector_socket.ts +0 -52
  97. package/src/transport/node/node_listener.ts +0 -34
  98. package/src/transport/node/node_listener_socket.ts +0 -48
  99. package/src/transport/transport_client.ts +0 -131
  100. package/src/transport/transport_server.ts +0 -108
  101. package/src/trees/index.ts +0 -48
  102. package/src/types/index.ts +0 -7
  103. package/src/url/index.ts +0 -73
  104. package/src/wasm/README.md +0 -6
  105. package/src/wasm/empty_wasi_sdk.ts +0 -166
  106. package/src/wasm/fixtures/gcd.wasm +0 -0
  107. package/src/wasm/fixtures/gcd.wat +0 -27
  108. package/src/wasm/index.ts +0 -1
  109. package/src/wasm/wasm_module.ts +0 -260
  110. package/src/worker/browser/index.ts +0 -2
  111. package/src/worker/browser/start_web_module.ts +0 -23
  112. package/src/worker/browser/web_data_store.ts +0 -38
  113. package/src/worker/browser/web_worker.ts +0 -24
  114. package/src/worker/data_store.ts +0 -19
  115. package/src/worker/index.ts +0 -2
  116. package/src/worker/node/index.ts +0 -2
  117. package/src/worker/node/node_data_store.ts +0 -27
  118. package/src/worker/node/node_worker.ts +0 -22
  119. package/src/worker/node/start_node_module.ts +0 -29
  120. package/src/worker/wasm_worker.ts +0 -7
  121. package/src/worker/worker_pool.ts +0 -73
@@ -1,99 +0,0 @@
1
- import { createDebugLogger } from '../log/index.js';
2
- import { sleep } from '../sleep/index.js';
3
- import { Timer } from '../timer/index.js';
4
-
5
- /** An error that indicates that the operation should not be retried. */
6
- export class NoRetryError extends Error {}
7
-
8
- /**
9
- * Generates a backoff sequence for retrying operations with an increasing delay.
10
- * The backoff sequence follows this pattern: 1, 1, 1, 2, 4, 8, 16, 32, 64, ...
11
- * This generator can be used in combination with the `retry` function to perform
12
- * retries with exponential backoff and capped at 64 seconds between attempts.
13
- *
14
- * @returns A generator that yields the next backoff value in seconds as an integer.
15
- */
16
- export function* backoffGenerator() {
17
- const v = [1, 1, 1, 2, 4, 8, 16, 32, 64];
18
- let i = 0;
19
- while (true) {
20
- yield v[Math.min(i++, v.length - 1)];
21
- }
22
- }
23
-
24
- /**
25
- * Generates a backoff sequence based on the array of retry intervals to use with the `retry` function.
26
- * @param retries - Intervals to retry (in seconds).
27
- * @returns A generator sequence.
28
- */
29
- export function* makeBackoff(retries: number[]) {
30
- for (const retry of retries) {
31
- yield retry;
32
- }
33
- }
34
-
35
- /**
36
- * Retry a given asynchronous function with a specific backoff strategy, until it succeeds or backoff generator ends.
37
- * It logs the error and retry interval in case an error is caught. The function can be named for better log output.
38
- *
39
- * @param fn - The asynchronous function to be retried.
40
- * @param name - The optional name of the operation, used for logging purposes.
41
- * @param backoff - The optional backoff generator providing the intervals in seconds between retries. Defaults to a predefined series.
42
- * @param log - Logger to use for logging.
43
- * @param failSilently - Do not log errors while retrying.
44
- * @returns A Promise that resolves with the successful result of the provided function, or rejects if backoff generator ends.
45
- * @throws If `NoRetryError` is thrown by the `fn`, it is rethrown.
46
- */
47
- export async function retry<Result>(
48
- fn: () => Promise<Result>,
49
- name = 'Operation',
50
- backoff = backoffGenerator(),
51
- log = createDebugLogger('aztec:foundation:retry'),
52
- failSilently = false,
53
- ) {
54
- while (true) {
55
- try {
56
- return await fn();
57
- } catch (err: any) {
58
- if (err instanceof NoRetryError) {
59
- // A special error that indicates that the operation should not be retried. Rethrow it.
60
- throw err;
61
- }
62
- const s = backoff.next().value;
63
- if (s === undefined) {
64
- throw err;
65
- }
66
- log(`${name} failed. Will retry in ${s}s...`);
67
- !failSilently && log.error(err);
68
- await sleep(s * 1000);
69
- continue;
70
- }
71
- }
72
- }
73
-
74
- /**
75
- * Retry an asynchronous function until it returns a truthy value or the specified timeout is exceeded.
76
- * The function is retried periodically with a fixed interval between attempts. The operation can be named for better error messages.
77
- * Will never timeout if the value is 0.
78
- *
79
- * @param fn - The asynchronous function to be retried, which should return a truthy value upon success or undefined otherwise.
80
- * @param name - The optional name of the operation, used for generating timeout error message.
81
- * @param timeout - The optional maximum time, in seconds, to keep retrying before throwing a timeout error. Defaults to 0 (never timeout).
82
- * @param interval - The optional interval, in seconds, between retry attempts. Defaults to 1 second.
83
- * @returns A Promise that resolves with the successful (truthy) result of the provided function, or rejects if timeout is exceeded.
84
- */
85
- export async function retryUntil<T>(fn: () => Promise<T | undefined>, name = '', timeout = 0, interval = 1) {
86
- const timer = new Timer();
87
- while (true) {
88
- const result = await fn();
89
- if (result) {
90
- return result;
91
- }
92
-
93
- await sleep(interval * 1000);
94
-
95
- if (timeout && timer.s() > timeout) {
96
- throw new Error(name ? `Timeout awaiting ${name}` : 'Timeout');
97
- }
98
- }
99
- }
@@ -1,60 +0,0 @@
1
- /**
2
- * RunningPromise is a utility class that helps manage the execution of an asynchronous function
3
- * at a specified polling interval. It allows starting, stopping, and checking the status of the
4
- * internally managed promise. The class also supports interrupting the polling process when stopped.
5
- */
6
- export class RunningPromise {
7
- private running = false;
8
- private runningPromise = Promise.resolve();
9
- private interruptPromise = Promise.resolve();
10
- private interruptResolve = () => {};
11
- constructor(private fn: () => Promise<void>, private pollingInterval = 10000) {}
12
-
13
- /**
14
- * Starts the running promise.
15
- */
16
- public start() {
17
- this.running = true;
18
- this.interruptPromise = new Promise(resolve => (this.interruptResolve = resolve));
19
-
20
- const poll = async () => {
21
- while (this.running) {
22
- await this.fn();
23
- await this.interruptibleSleep(this.pollingInterval);
24
- }
25
- };
26
- this.runningPromise = poll();
27
- }
28
-
29
- /**
30
- * Stops the running promise, resolves any pending interruptible sleep,
31
- * and waits for the currently executing function to complete.
32
- */
33
- async stop(): Promise<void> {
34
- this.running = false;
35
- this.interruptResolve();
36
- await this.runningPromise;
37
- }
38
-
39
- /**
40
- * A sleep function that can be interrupted before the specified time.
41
- * The sleep duration is determined by 'timeInMs', and it can be terminated early if the 'interruptPromise' is resolved.
42
- * @param timeInMs - The time in milliseconds.
43
- */
44
- private async interruptibleSleep(timeInMs: number) {
45
- let timeout!: NodeJS.Timeout;
46
- const sleepPromise = new Promise(resolve => {
47
- timeout = setTimeout(resolve, timeInMs);
48
- });
49
- await Promise.race([sleepPromise, this.interruptPromise]);
50
- clearTimeout(timeout);
51
- }
52
-
53
- /**
54
- * Checks if the running promise is currently active.
55
- * @returns True if the promise is running.
56
- */
57
- public isRunning() {
58
- return this.running;
59
- }
60
- }
@@ -1,250 +0,0 @@
1
- import { Tuple } from './types.js';
2
-
3
- /**
4
- * The BufferReader class provides a utility for reading various data types from a buffer.
5
- * It supports reading numbers, booleans, byte arrays, Fr and Fq field elements,
6
- * vectors, arrays, objects, strings, and maps. It maintains an internal index to
7
- * keep track of the current reading position in the buffer.
8
- *
9
- * Usage:
10
- * Create a new instance of BufferReader with a buffer and an optional offset.
11
- * Use the provided methods to read desired data types from the buffer.
12
- * The reading methods automatically advance the internal index.
13
- *
14
- * @example
15
- * const reader = new BufferReader(someBuffer);
16
- * const num = reader.readNumber();
17
- * const bool = reader.readBoolean();
18
- * const byteArray = reader.readBytes(4);
19
- */
20
- export class BufferReader {
21
- private index: number;
22
- constructor(private buffer: Buffer, offset = 0) {
23
- this.index = offset;
24
- }
25
-
26
- /**
27
- * Creates a BufferReader instance from either a Buffer or an existing BufferReader.
28
- * If the input is a Buffer, it creates a new BufferReader with the given buffer.
29
- * If the input is already a BufferReader, it returns the input unchanged.
30
- *
31
- * @param bufferOrReader - A Buffer or BufferReader to initialize the BufferReader.
32
- * @returns An instance of BufferReader.
33
- */
34
- public static asReader(bufferOrReader: Buffer | BufferReader) {
35
- return Buffer.isBuffer(bufferOrReader) ? new BufferReader(bufferOrReader) : bufferOrReader;
36
- }
37
-
38
- /**
39
- * Reads a 32-bit unsigned integer from the buffer at the current index position.
40
- * Updates the index position by 4 bytes after reading the number.
41
- *
42
- * @returns The read 32-bit unsigned integer value.
43
- */
44
- public readNumber(): number {
45
- this.index += 4;
46
- return this.buffer.readUint32BE(this.index - 4);
47
- }
48
-
49
- /**
50
- * Reads a 16-bit unsigned integer from the buffer at the current index position.
51
- * Updates the index position by 2 bytes after reading the number.
52
- *
53
- * @returns The read 16 bit value.
54
- */
55
- public readUInt16(): number {
56
- this.index += 2;
57
- return this.buffer.readUInt16BE(this.index - 2);
58
- }
59
-
60
- /**
61
- * Reads and returns the next boolean value from the buffer.
62
- * Advances the internal index by 1, treating the byte at the current index as a boolean value.
63
- * Returns true if the byte is non-zero, false otherwise.
64
- *
65
- * @returns A boolean value representing the byte at the current index.
66
- */
67
- public readBoolean(): boolean {
68
- this.index += 1;
69
- return Boolean(this.buffer.at(this.index - 1));
70
- }
71
-
72
- /**
73
- * Reads a specified number of bytes from the buffer and returns a new Buffer containing those bytes.
74
- * Advances the reader's index by the number of bytes read. Throws an error if there are not enough
75
- * bytes left in the buffer to satisfy the requested number of bytes.
76
- *
77
- * @param n - The number of bytes to read from the buffer.
78
- * @returns A new Buffer containing the read bytes.
79
- */
80
- public readBytes(n: number): Buffer {
81
- this.index += n;
82
- return Buffer.from(this.buffer.subarray(this.index - n, this.index));
83
- }
84
-
85
- /**
86
- * Reads a vector of numbers from the buffer and returns it as an array of numbers.
87
- * The method utilizes the 'readVector' method, passing a deserializer that reads numbers.
88
- *
89
- * @returns An array of numbers representing the vector read from the buffer.
90
- */
91
- public readNumberVector(): number[] {
92
- return this.readVector({
93
- fromBuffer: (reader: BufferReader) => reader.readNumber(),
94
- });
95
- }
96
-
97
- /**
98
- * Reads a vector of fixed size from the buffer and deserializes its elements using the provided itemDeserializer object.
99
- * The 'itemDeserializer' object should have a 'fromBuffer' method that takes a BufferReader instance and returns the deserialized element.
100
- * The method first reads the size of the vector (a number) from the buffer, then iterates through its elements,
101
- * deserializing each one using the 'fromBuffer' method of 'itemDeserializer'.
102
- *
103
- * @param itemDeserializer - Object with 'fromBuffer' method to deserialize vector elements.
104
- * @returns An array of deserialized elements of type T.
105
- */
106
- public readVector<T>(itemDeserializer: {
107
- /**
108
- * A method to deserialize data from a buffer.
109
- */
110
- fromBuffer: (reader: BufferReader) => T;
111
- }): T[] {
112
- const size = this.readNumber();
113
- const result = new Array<T>(size);
114
- for (let i = 0; i < size; i++) {
115
- result[i] = itemDeserializer.fromBuffer(this);
116
- }
117
- return result;
118
- }
119
-
120
- /**
121
- * Read an array of a fixed size with elements of type T from the buffer.
122
- * The 'itemDeserializer' object should have a 'fromBuffer' method that takes a BufferReader instance as input,
123
- * and returns an instance of the desired deserialized data type T.
124
- * This method will call the 'fromBuffer' method for each element in the array and return the resulting array.
125
- *
126
- * @param size - The fixed number of elements in the array.
127
- * @param itemDeserializer - An object with a 'fromBuffer' method to deserialize individual elements of type T.
128
- * @returns An array of instances of type T.
129
- */
130
- public readArray<T, N extends number>(
131
- size: N,
132
- itemDeserializer: {
133
- /**
134
- * A function for deserializing data from a BufferReader instance.
135
- */
136
- fromBuffer: (reader: BufferReader) => T;
137
- },
138
- ): Tuple<T, N> {
139
- const result = Array.from({ length: size }, () => itemDeserializer.fromBuffer(this));
140
- return result as Tuple<T, N>;
141
- }
142
-
143
- /**
144
- * Read a variable sized Buffer array where elements are represented by length + data.
145
- * The method consecutively looks for a number which is the size of the proceeding buffer,
146
- * then reads the bytes until it reaches the end of the reader's internal buffer.
147
- * NOTE: if `size` is not provided, this will run to the end of the reader's buffer.
148
- * @param size - Size of the buffer array in bytes (full remaining buffer length if left empty).
149
- * @returns An array of variable sized buffers.
150
- */
151
- public readBufferArray(size = -1): Buffer[] {
152
- const result: Buffer[] = [];
153
- const end = size >= 0 ? this.index + size : this.buffer.length;
154
- while (this.index < end) {
155
- const item = this.readBuffer();
156
- result.push(item);
157
- }
158
- // Ensure that all bytes have been read.
159
- if (this.index !== end) {
160
- throw new Error(
161
- `Reader buffer was not fully consumed. Consumed up to ${this.index} bytes. End of data: ${end} bytes.`,
162
- );
163
- }
164
- return result;
165
- }
166
-
167
- /**
168
- * Reads a serialized object from a buffer and returns the deserialized object using the given deserializer.
169
- *
170
- * @typeparam T - The type of the deserialized object.
171
- * @param deserializer - An object with a 'fromBuffer' method that takes a BufferReader instance and returns an instance of the deserialized object.
172
- * @returns The deserialized object of type T.
173
- */
174
- public readObject<T>(deserializer: {
175
- /**
176
- * A method that takes a BufferReader instance and returns an instance of the deserialized data type.
177
- */
178
- fromBuffer: (reader: BufferReader) => T;
179
- }): T {
180
- return deserializer.fromBuffer(this);
181
- }
182
-
183
- /**
184
- * Returns a Buffer containing the next n bytes from the current buffer without modifying the reader's index position.
185
- * If n is not provided or exceeds the remaining length of the buffer, it returns all bytes from the current position till the end of the buffer.
186
- *
187
- * @param n - The number of bytes to peek from the current buffer. (Optional).
188
- * @returns A Buffer with the next n bytes or the remaining bytes if n is not provided or exceeds the buffer length.
189
- */
190
- public peekBytes(n?: number): Buffer {
191
- return this.buffer.subarray(this.index, n ? this.index + n : undefined);
192
- }
193
-
194
- /**
195
- * Reads a string from the buffer and returns it.
196
- * The method first reads the size of the string, then reads the corresponding
197
- * number of bytes from the buffer and converts them to a string.
198
- *
199
- * @returns The read string from the buffer.
200
- */
201
- public readString(): string {
202
- return this.readBuffer().toString();
203
- }
204
-
205
- /**
206
- * Reads a buffer from the current position of the reader and advances the index.
207
- * The method first reads the size (number) of bytes to be read, and then returns
208
- * a Buffer with that size containing the bytes. Useful for reading variable-length
209
- * binary data encoded as (size, data) format.
210
- *
211
- * @returns A Buffer containing the read bytes.
212
- */
213
- public readBuffer(): Buffer {
214
- const size = this.readNumber();
215
- return this.readBytes(size);
216
- }
217
-
218
- /**
219
- * Reads and constructs a map object from the current buffer using the provided deserializer.
220
- * The method reads the number of entries in the map, followed by iterating through each key-value pair.
221
- * The key is read as a string, while the value is obtained using the passed deserializer's `fromBuffer` method.
222
- * The resulting map object is returned, containing all the key-value pairs read from the buffer.
223
- *
224
- * @param deserializer - An object with a `fromBuffer` method to deserialize the values in the map.
225
- * @returns A map object with string keys and deserialized values based on the provided deserializer.
226
- */
227
- public readMap<T>(deserializer: {
228
- /**
229
- * Deserializes an element of type T from a BufferReader instance.
230
- */
231
- fromBuffer: (reader: BufferReader) => T;
232
- }): { [key: string]: T } {
233
- const numEntries = this.readNumber();
234
- const map: { [key: string]: T } = {};
235
- for (let i = 0; i < numEntries; i++) {
236
- const key = this.readString();
237
- const value = this.readObject<T>(deserializer);
238
- map[key] = value;
239
- }
240
- return map;
241
- }
242
-
243
- /**
244
- * Get the length of the reader's buffer.
245
- * @returns The length of the underlying reader's buffer.
246
- */
247
- public getLength(): number {
248
- return this.buffer.length;
249
- }
250
- }
@@ -1,279 +0,0 @@
1
- import { toBigIntBE, toBufferBE } from '@aztec/foundation/bigint-buffer';
2
- import { Fr } from '@aztec/foundation/fields';
3
-
4
- /**
5
- * Convert a boolean value to its corresponding byte representation in a Buffer of size 1.
6
- * The function takes a boolean value and writes it into a new buffer as either 1 (true) or 0 (false).
7
- * This method is useful for converting a boolean value into a binary format that can be stored or transmitted easily.
8
- *
9
- * @param b - The boolean value to be converted.
10
- * @returns A Buffer containing the byte representation of the input boolean value.
11
- */
12
- export function boolToByte(b: boolean) {
13
- const buf = Buffer.alloc(1);
14
- buf.writeUInt8(b ? 1 : 0);
15
- return buf;
16
- }
17
-
18
- /**
19
- * @param n - The input number to be converted to a big-endian unsigned 16-bit integer Buffer.
20
- * @param bufferSize - Optional, the size of the output Buffer (default is 2).
21
- * @returns A Buffer containing the big-endian unsigned 16-bit integer representation of the input number.
22
- */
23
- export function numToUInt16BE(n: number, bufferSize = 2) {
24
- const buf = Buffer.alloc(bufferSize);
25
- buf.writeUInt16BE(n, bufferSize - 2);
26
- return buf;
27
- }
28
-
29
- /**
30
- * Convert a number into a 4-byte little-endian unsigned integer buffer.
31
- * The input number is serialized as an unsigned 32-bit integer in little-endian byte order,
32
- * and returned as a Buffer of specified size (defaults to 4).
33
- * If the provided bufferSize is greater than 4, the additional bytes will be padded with zeros.
34
- *
35
- * @param n - The number to be converted into a little-endian unsigned integer buffer.
36
- * @param bufferSize - Optional, the size of the output buffer (default value is 4).
37
- * @returns A Buffer containing the serialized little-endian unsigned integer representation of the input number.
38
- */
39
- export function numToUInt32LE(n: number, bufferSize = 4) {
40
- const buf = Buffer.alloc(bufferSize);
41
- buf.writeUInt32LE(n, bufferSize - 4);
42
- return buf;
43
- }
44
-
45
- /**
46
- * Convert a number to a big-endian unsigned 32-bit integer Buffer.
47
- * This function takes a number and an optional buffer size as input and creates a Buffer with the specified size (defaults to 4) containing the big-endian representation of the input number as an unsigned 32-bit integer. Note that the bufferSize should be greater than or equal to 4, otherwise the output Buffer might truncate the serialized value.
48
- *
49
- * @param n - The input number to be converted to a big-endian unsigned 32-bit integer Buffer.
50
- * @param bufferSize - Optional, the size of the output Buffer (default is 4).
51
- * @returns A Buffer containing the big-endian unsigned 32-bit integer representation of the input number.
52
- */
53
- export function numToUInt32BE(n: number, bufferSize = 4) {
54
- const buf = Buffer.alloc(bufferSize);
55
- buf.writeUInt32BE(n, bufferSize - 4);
56
- return buf;
57
- }
58
-
59
- /**
60
- * Serialize a number into a big-endian signed 32-bit integer Buffer with the specified buffer size.
61
- * This function converts the input number into its binary representation and stores it in a Buffer
62
- * with the provided buffer size. By default, the buffer size is set to 4 bytes which represents a 32-bit integer.
63
- * The function will use the last 4 bytes of the buffer to store the serialized number. If the input number
64
- * is outside the range of a 32-bit signed integer, the resulting serialization may be incorrect due to truncation.
65
- *
66
- * @param n - The number to be serialized as a signed 32-bit integer.
67
- * @param bufferSize - Optional, the size of the output Buffer (default is 4 bytes).
68
- * @returns A Buffer containing the serialized big-endian signed 32-bit integer.
69
- */
70
- export function numToInt32BE(n: number, bufferSize = 4) {
71
- const buf = Buffer.alloc(bufferSize);
72
- buf.writeInt32BE(n, bufferSize - 4);
73
- return buf;
74
- }
75
-
76
- /**
77
- * Convert a number to an 8-bit unsigned integer and return it as a Buffer of length 1.
78
- * The input number is written as an 8-bit unsigned integer into the buffer. This function
79
- * is useful for converting small numeric values to a standardized binary format that can be
80
- * easily stored or transmitted.
81
- *
82
- * @param n - The number to be converted to an 8-bit unsigned integer.
83
- * @returns A Buffer containing the 8-bit unsigned integer representation of the input number.
84
- */
85
- export function numToUInt8(n: number) {
86
- const bufferSize = 1;
87
- const buf = Buffer.alloc(bufferSize);
88
- buf.writeUInt8(n, 0);
89
- return buf;
90
- }
91
-
92
- /**
93
- * Adds a 4-byte byte-length prefix to a buffer.
94
- * @param buf - The input Buffer to be prefixed
95
- * @returns A Buffer with 4-byte byte-length prefix.
96
- */
97
- export function prefixBufferWithLength(buf: Buffer) {
98
- const lengthBuf = Buffer.alloc(4);
99
- lengthBuf.writeUInt32BE(buf.length, 0);
100
- return Buffer.concat([lengthBuf, buf]);
101
- }
102
-
103
- /**
104
- * Serialize a BigInt value into a Buffer of specified width.
105
- * The function converts the input BigInt into its big-endian representation and stores it in a Buffer of the given width.
106
- * If the width is not provided, a default value of 32 bytes will be used. It is important to provide an appropriate width
107
- * to avoid truncation or incorrect serialization of large BigInt values.
108
- *
109
- * @param n - The BigInt value to be serialized.
110
- * @param width - The width (in bytes) of the output Buffer, optional with default value 32.
111
- * @returns A Buffer containing the serialized BigInt value in big-endian format.
112
- */
113
- export function serializeBigInt(n: bigint, width = 32) {
114
- return toBufferBE(n, width);
115
- }
116
-
117
- /**
118
- * Deserialize a big integer from a buffer, given an offset and width.
119
- * Reads the specified number of bytes from the buffer starting at the offset, converts it to a big integer, and returns the deserialized result along with the number of bytes read (advanced).
120
- *
121
- * @param buf - The buffer containing the big integer to be deserialized.
122
- * @param offset - The position in the buffer where the big integer starts. Defaults to 0.
123
- * @param width - The number of bytes to read from the buffer for the big integer. Defaults to 32.
124
- * @returns An object containing the deserialized big integer value ('elem') and the number of bytes advanced ('adv').
125
- */
126
- export function deserializeBigInt(buf: Buffer, offset = 0, width = 32) {
127
- return { elem: toBigIntBE(buf.subarray(offset, offset + width)), adv: width };
128
- }
129
-
130
- /**
131
- * Serializes a Date object into a Buffer containing its timestamp as a big integer value.
132
- * The resulting Buffer has a fixed width of 8 bytes, representing a 64-bit big-endian integer.
133
- * This function is useful for converting date values into a binary format that can be stored or transmitted easily.
134
- *
135
- * @param date - The Date object to be serialized.
136
- * @returns A Buffer containing the serialized timestamp of the input Date object.
137
- */
138
- export function serializeDate(date: Date) {
139
- return serializeBigInt(BigInt(date.getTime()), 8);
140
- }
141
-
142
- /**
143
- * Deserialize a boolean value from a given buffer at the specified offset.
144
- * Reads a single byte at the provided offset in the buffer and returns
145
- * the deserialized boolean value along with the number of bytes read (adv).
146
- *
147
- * @param buf - The buffer containing the serialized boolean value.
148
- * @param offset - The position in the buffer to start reading the boolean value.
149
- * @returns An object containing the deserialized boolean value (elem) and the number of bytes read (adv).
150
- */
151
- export function deserializeBool(buf: Buffer, offset = 0) {
152
- const adv = 1;
153
- return { elem: buf.readUInt8(offset), adv };
154
- }
155
-
156
- /**
157
- * Deserialize a 4-byte unsigned integer from a buffer, starting at the specified offset.
158
- * The deserialization reads 4 bytes from the given buffer and converts it into a number.
159
- * Returns an object containing the deserialized unsigned integer and the number of bytes advanced (4).
160
- *
161
- * @param buf - The buffer containing the serialized unsigned integer.
162
- * @param offset - The starting position in the buffer to deserialize from (default is 0).
163
- * @returns An object with the deserialized unsigned integer as 'elem' and the number of bytes advanced ('adv') as 4.
164
- */
165
- export function deserializeUInt32(buf: Buffer, offset = 0) {
166
- const adv = 4;
167
- return { elem: buf.readUInt32BE(offset), adv };
168
- }
169
-
170
- /**
171
- * Deserialize a signed 32-bit integer from a buffer at the given offset.
172
- * The input 'buf' should be a Buffer containing binary data, and 'offset' should be the position in the buffer
173
- * where the signed 32-bit integer starts. Returns an object with both the deserialized integer (elem) and the
174
- * number of bytes advanced in the buffer (adv, always equal to 4).
175
- *
176
- * @param buf - The buffer containing the binary data.
177
- * @param offset - Optional, the position in the buffer where the signed 32-bit integer starts (default is 0).
178
- * @returns An object with the deserialized integer as 'elem' and the number of bytes advanced as 'adv'.
179
- */
180
- export function deserializeInt32(buf: Buffer, offset = 0) {
181
- const adv = 4;
182
- return { elem: buf.readInt32BE(offset), adv };
183
- }
184
-
185
- /**
186
- * Deserialize a field element from a buffer, starting at the given offset.
187
- * The function reads 32 bytes from the buffer and converts it into a field element using Fr.fromBuffer.
188
- * It returns an object containing the deserialized field element and the number of bytes read (adv).
189
- *
190
- * @param buf - The buffer containing the serialized field element.
191
- * @param offset - The position in the buffer where the field element starts. Default is 0.
192
- * @returns An object with 'elem' as the deserialized field element and 'adv' as the number of bytes read.
193
- */
194
- export function deserializeField(buf: Buffer, offset = 0) {
195
- const adv = 32;
196
- return { elem: Fr.fromBuffer(buf.subarray(offset, offset + adv)), adv };
197
- }
198
-
199
- /**
200
- * Serialize an array of Buffer instances into a single Buffer by concatenating the array length as a 4-byte unsigned integer
201
- * and then the individual Buffer elements. The function is useful for storing or transmitting an array of binary data chunks
202
- * (e.g., file parts) in a compact format.
203
- *
204
- * @param arr - An array of Buffer instances to be serialized into a single vector-like Buffer.
205
- * @returns A Buffer containing the serialized array length followed by the concatenated elements of the input Buffer array.
206
- */
207
- export function serializeBufferArrayToVector(arr: Buffer[]) {
208
- const lengthBuf = Buffer.alloc(4);
209
- lengthBuf.writeUInt32BE(arr.length, 0);
210
- return Buffer.concat([lengthBuf, ...arr]);
211
- }
212
-
213
- /**
214
- * Deserialize an array of fixed length elements from a given buffer using a custom deserializer function.
215
- * The deserializer function should take the buffer and an offset as arguments, and return an object containing
216
- * the deserialized element and the number of bytes used to deserialize it (adv).
217
- *
218
- * @param deserialize - A custom deserializer function to extract individual elements from the buffer.
219
- * @param vector - The input buffer containing the serialized array.
220
- * @param offset - An optional starting position in the buffer for deserializing the array.
221
- * @returns An object containing the deserialized array and the total number of bytes used during deserialization (adv).
222
- * @deprecated User BufferReader instead.
223
- */
224
- export function deserializeArrayFromVector<T>(
225
- deserialize: (
226
- buf: Buffer,
227
- offset: number,
228
- ) => {
229
- /**
230
- * The element.
231
- */
232
- elem: T;
233
- /**
234
- * The advancement offset.
235
- */
236
- adv: number;
237
- },
238
- vector: Buffer,
239
- offset = 0,
240
- ) {
241
- let pos = offset;
242
- const size = vector.readUInt32BE(pos);
243
- pos += 4;
244
- const arr = new Array<T>(size);
245
- for (let i = 0; i < size; ++i) {
246
- const { elem, adv } = deserialize(vector, pos);
247
- pos += adv;
248
- arr[i] = elem;
249
- }
250
- return { elem: arr, adv: pos - offset };
251
- }
252
-
253
- /**
254
- * Parse a buffer as a big integer.
255
- */
256
- export function toBigInt(buf: Buffer): bigint {
257
- const hex = buf.toString('hex');
258
- if (hex.length === 0) {
259
- return BigInt(0);
260
- }
261
- return BigInt(`0x${hex}`);
262
- }
263
-
264
- /**
265
- * Stores full 256 bits of information in 2 fields.
266
- * @param buf - 32 bytes of data
267
- * @returns 2 field elements
268
- */
269
- export function to2Fields(buf: Buffer): [Fr, Fr] {
270
- if (buf.length !== 32) {
271
- throw new Error('Buffer must be 32 bytes');
272
- }
273
-
274
- // Split the hash into two fields, a high and a low
275
- const buf1 = Buffer.concat([Buffer.alloc(16), buf.subarray(0, 16)]);
276
- const buf2 = Buffer.concat([Buffer.alloc(16), buf.subarray(16, 32)]);
277
-
278
- return [Fr.fromBuffer(buf1), Fr.fromBuffer(buf2)];
279
- }
@@ -1,3 +0,0 @@
1
- export * from './free_funcs.js';
2
- export * from './buffer_reader.js';
3
- export * from './types.js';