@aztec/foundation 0.0.1-commit.3fd054f6 → 0.0.1-commit.42ee6df9b

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 (71) hide show
  1. package/dest/buffer/buffer16.d.ts +3 -1
  2. package/dest/buffer/buffer16.d.ts.map +1 -1
  3. package/dest/buffer/buffer32.d.ts +3 -1
  4. package/dest/buffer/buffer32.d.ts.map +1 -1
  5. package/dest/collection/array.d.ts +3 -1
  6. package/dest/collection/array.d.ts.map +1 -1
  7. package/dest/collection/array.js +15 -0
  8. package/dest/collection/index.d.ts +2 -1
  9. package/dest/collection/index.d.ts.map +1 -1
  10. package/dest/collection/index.js +1 -0
  11. package/dest/collection/lru_set.d.ts +35 -0
  12. package/dest/collection/lru_set.d.ts.map +1 -0
  13. package/dest/collection/lru_set.js +95 -0
  14. package/dest/config/env_var.d.ts +2 -2
  15. package/dest/config/env_var.d.ts.map +1 -1
  16. package/dest/crypto/aes128/index.d.ts +2 -1
  17. package/dest/crypto/aes128/index.d.ts.map +1 -1
  18. package/dest/crypto/aes128/index.js +11 -2
  19. package/dest/crypto/bls/bn254_keystore.d.ts +1 -10
  20. package/dest/crypto/bls/bn254_keystore.d.ts.map +1 -1
  21. package/dest/crypto/bls/bn254_keystore.js +0 -17
  22. package/dest/crypto/poseidon/index.d.ts +1 -1
  23. package/dest/crypto/poseidon/index.d.ts.map +1 -1
  24. package/dest/crypto/poseidon/index.js +40 -33
  25. package/dest/curves/grumpkin/point.d.ts +1 -1
  26. package/dest/curves/grumpkin/point.js +1 -1
  27. package/dest/json-rpc/client/fetch.d.ts +1 -1
  28. package/dest/json-rpc/client/fetch.d.ts.map +1 -1
  29. package/dest/json-rpc/client/fetch.js +3 -2
  30. package/dest/log/pino-logger.d.ts +1 -1
  31. package/dest/log/pino-logger.d.ts.map +1 -1
  32. package/dest/log/pino-logger.js +2 -1
  33. package/dest/retry/index.d.ts +12 -1
  34. package/dest/retry/index.d.ts.map +1 -1
  35. package/dest/retry/index.js +21 -0
  36. package/dest/schemas/api.d.ts +2 -2
  37. package/dest/schemas/api.d.ts.map +1 -1
  38. package/dest/transport/dispatch/create_dispatch_proxy.d.ts +11 -2
  39. package/dest/transport/dispatch/create_dispatch_proxy.d.ts.map +1 -1
  40. package/dest/transport/index.d.ts +1 -2
  41. package/dest/transport/index.d.ts.map +1 -1
  42. package/dest/transport/index.js +0 -1
  43. package/dest/trees/indexed_merkle_tree_calculator.d.ts +1 -1
  44. package/dest/trees/indexed_merkle_tree_calculator.d.ts.map +1 -1
  45. package/dest/trees/indexed_merkle_tree_calculator.js +5 -1
  46. package/package.json +2 -2
  47. package/src/buffer/buffer16.ts +3 -0
  48. package/src/buffer/buffer32.ts +3 -0
  49. package/src/collection/array.ts +14 -0
  50. package/src/collection/index.ts +1 -0
  51. package/src/collection/lru_set.ts +115 -0
  52. package/src/config/env_var.ts +2 -2
  53. package/src/crypto/aes128/index.ts +11 -2
  54. package/src/crypto/bls/bn254_keystore.ts +0 -23
  55. package/src/crypto/poseidon/index.ts +42 -34
  56. package/src/curves/grumpkin/point.ts +1 -1
  57. package/src/json-rpc/client/fetch.ts +3 -2
  58. package/src/log/pino-logger.ts +3 -1
  59. package/src/retry/index.ts +30 -0
  60. package/src/schemas/api.ts +4 -1
  61. package/src/transport/dispatch/create_dispatch_proxy.ts +11 -1
  62. package/src/transport/index.ts +0 -1
  63. package/src/trees/indexed_merkle_tree_calculator.ts +5 -1
  64. package/dest/crypto/serialize.d.ts +0 -51
  65. package/dest/crypto/serialize.d.ts.map +0 -1
  66. package/dest/crypto/serialize.js +0 -68
  67. package/dest/transport/dispatch/create_dispatch_fn.d.ts +0 -25
  68. package/dest/transport/dispatch/create_dispatch_fn.d.ts.map +0 -1
  69. package/dest/transport/dispatch/create_dispatch_fn.js +0 -17
  70. package/src/crypto/serialize.ts +0 -85
  71. package/src/transport/dispatch/create_dispatch_fn.ts +0 -35
@@ -59,10 +59,19 @@ export class Aes128 {
59
59
  * @param iv - AES initialization vector.
60
60
  * @param key - Key to decrypt with.
61
61
  * @returns Decrypted data.
62
+ * @throws If the decrypted buffer has invalid PKCS#7 padding.
62
63
  */
63
64
  public async decryptBufferCBC(data: Uint8Array, iv: Uint8Array, key: Uint8Array) {
64
65
  const paddedBuffer = await this.decryptBufferCBCKeepPadding(data, iv, key);
65
- const paddingToRemove = paddedBuffer[paddedBuffer.length - 1];
66
- return paddedBuffer.subarray(0, paddedBuffer.length - paddingToRemove);
66
+ const paddingLen = paddedBuffer[paddedBuffer.length - 1];
67
+ if (paddingLen === 0 || paddingLen > 16) {
68
+ throw new Error(`Invalid PKCS#7 padding length: ${paddingLen}`);
69
+ }
70
+ for (let i = paddedBuffer.length - paddingLen; i < paddedBuffer.length; i++) {
71
+ if (paddedBuffer[i] !== paddingLen) {
72
+ throw new Error('Invalid PKCS#7 padding');
73
+ }
74
+ }
75
+ return paddedBuffer.subarray(0, paddedBuffer.length - paddingLen);
67
76
  }
68
77
  }
@@ -262,26 +262,3 @@ export function decryptBn254KeystoreFromObject(keystore: Bn254Keystore, password
262
262
  throw new Bn254KeystoreError(`Failed to decrypt keystore: ${String(error)}`, error as Error);
263
263
  }
264
264
  }
265
-
266
- /**
267
- * Validates that a decrypted private key matches the public key in the keystore.
268
- *
269
- * @param privateKeyHex - Decrypted private key (0x-prefixed)
270
- * @param expectedPubkey - Expected public key from keystore
271
- * @param computePublicKey - Function to compute public key from private key
272
- * @returns true if keys match, false otherwise
273
- */
274
- export function verifyBn254Keypair(
275
- privateKeyHex: string,
276
- expectedPubkey: string,
277
- computePublicKey: (privateKey: string) => string,
278
- ): boolean {
279
- try {
280
- const computedPubkey = computePublicKey(privateKeyHex);
281
- const normalizedExpected = expectedPubkey.toLowerCase().replace(/^0x/i, '');
282
- const normalizedComputed = computedPubkey.toLowerCase().replace(/^0x/i, '');
283
- return normalizedExpected === normalizedComputed;
284
- } catch {
285
- return false;
286
- }
287
- }
@@ -1,21 +1,35 @@
1
- import { Barretenberg } from '@aztec/bb.js';
1
+ import { Barretenberg, BarretenbergSync } from '@aztec/bb.js';
2
2
 
3
3
  import { Fr } from '../../curves/bn254/field.js';
4
4
  import { type Fieldable, serializeToFields } from '../../serialize/serialize.js';
5
5
 
6
+ const IS_BROWSER = typeof self !== 'undefined';
7
+
8
+ async function poseidon2HashFields(inputFields: Fr[]): Promise<Fr> {
9
+ if (IS_BROWSER) {
10
+ await BarretenbergSync.initSingleton();
11
+ const api = BarretenbergSync.getSingleton();
12
+ const response = api.poseidon2Hash({
13
+ inputs: inputFields.map(i => i.toBuffer()),
14
+ });
15
+ return Fr.fromBuffer(Buffer.from(response.hash));
16
+ } else {
17
+ await Barretenberg.initSingleton();
18
+ const api = Barretenberg.getSingleton();
19
+ const response = await api.poseidon2Hash({
20
+ inputs: inputFields.map(i => i.toBuffer()),
21
+ });
22
+ return Fr.fromBuffer(Buffer.from(response.hash));
23
+ }
24
+ }
25
+
6
26
  /**
7
27
  * Create a poseidon hash (field) from an array of input fields.
8
28
  * @param input - The input fields to hash.
9
29
  * @returns The poseidon hash.
10
30
  */
11
- export async function poseidon2Hash(input: Fieldable[]): Promise<Fr> {
12
- const inputFields = serializeToFields(input);
13
- await Barretenberg.initSingleton();
14
- const api = Barretenberg.getSingleton();
15
- const response = await api.poseidon2Hash({
16
- inputs: inputFields.map(i => i.toBuffer()),
17
- });
18
- return Fr.fromBuffer(Buffer.from(response.hash));
31
+ export function poseidon2Hash(input: Fieldable[]): Promise<Fr> {
32
+ return poseidon2HashFields(serializeToFields(input));
19
33
  }
20
34
 
21
35
  /**
@@ -24,15 +38,10 @@ export async function poseidon2Hash(input: Fieldable[]): Promise<Fr> {
24
38
  * @param separator - The domain separator.
25
39
  * @returns The poseidon hash.
26
40
  */
27
- export async function poseidon2HashWithSeparator(input: Fieldable[], separator: number): Promise<Fr> {
41
+ export function poseidon2HashWithSeparator(input: Fieldable[], separator: number): Promise<Fr> {
28
42
  const inputFields = serializeToFields(input);
29
43
  inputFields.unshift(new Fr(separator));
30
- await Barretenberg.initSingleton();
31
- const api = Barretenberg.getSingleton();
32
- const response = await api.poseidon2Hash({
33
- inputs: inputFields.map(i => i.toBuffer()),
34
- });
35
- return Fr.fromBuffer(Buffer.from(response.hash));
44
+ return poseidon2HashFields(inputFields);
36
45
  }
37
46
 
38
47
  /**
@@ -42,19 +51,24 @@ export async function poseidon2HashWithSeparator(input: Fieldable[], separator:
42
51
  */
43
52
  export async function poseidon2Permutation(input: Fieldable[]): Promise<Fr[]> {
44
53
  const inputFields = serializeToFields(input);
45
- // We'd like this assertion but it's not possible to use it in the browser.
46
- // assert(input.length === 4, 'Input state must be of size 4');
47
- await Barretenberg.initSingleton();
48
- const api = Barretenberg.getSingleton();
49
- const response = await api.poseidon2Permutation({
50
- inputs: inputFields.map(i => i.toBuffer()),
51
- });
52
- // We'd like this assertion but it's not possible to use it in the browser.
53
- // assert(response.outputs.length === 4, 'Output state must be of size 4');
54
- return response.outputs.map(o => Fr.fromBuffer(Buffer.from(o)));
54
+ if (IS_BROWSER) {
55
+ await BarretenbergSync.initSingleton();
56
+ const api = BarretenbergSync.getSingleton();
57
+ const response = api.poseidon2Permutation({
58
+ inputs: inputFields.map(i => i.toBuffer()),
59
+ });
60
+ return response.outputs.map(o => Fr.fromBuffer(Buffer.from(o)));
61
+ } else {
62
+ await Barretenberg.initSingleton();
63
+ const api = Barretenberg.getSingleton();
64
+ const response = await api.poseidon2Permutation({
65
+ inputs: inputFields.map(i => i.toBuffer()),
66
+ });
67
+ return response.outputs.map(o => Fr.fromBuffer(Buffer.from(o)));
68
+ }
55
69
  }
56
70
 
57
- export async function poseidon2HashBytes(input: Buffer): Promise<Fr> {
71
+ export function poseidon2HashBytes(input: Buffer): Promise<Fr> {
58
72
  const inputFields = [];
59
73
  for (let i = 0; i < input.length; i += 31) {
60
74
  const fieldBytes = Buffer.alloc(32, 0);
@@ -65,11 +79,5 @@ export async function poseidon2HashBytes(input: Buffer): Promise<Fr> {
65
79
  inputFields.push(Fr.fromBuffer(fieldBytes));
66
80
  }
67
81
 
68
- await Barretenberg.initSingleton();
69
- const api = Barretenberg.getSingleton();
70
- const response = await api.poseidon2Hash({
71
- inputs: inputFields.map(i => i.toBuffer()),
72
- });
73
-
74
- return Fr.fromBuffer(Buffer.from(response.hash));
82
+ return poseidon2HashFields(inputFields);
75
83
  }
@@ -65,7 +65,7 @@ export class Point {
65
65
  }
66
66
 
67
67
  /**
68
- * Generate a random Point instance.
68
+ * Generate a random Point instance that is on the curve.
69
69
  *
70
70
  * @returns A randomly generated Point instance.
71
71
  */
@@ -43,13 +43,14 @@ export async function defaultFetch(
43
43
  }
44
44
 
45
45
  let responseJson;
46
+ const responseText = await resp.text();
46
47
  try {
47
- responseJson = await resp.json();
48
+ responseJson = JSON.parse(responseText);
48
49
  } catch {
49
50
  if (!resp.ok) {
50
51
  throw new Error(resp.statusText);
51
52
  }
52
- throw new Error(`Failed to parse body as JSON: ${await resp.text()}`);
53
+ throw new Error(`Failed to parse body as JSON: ${responseText}`);
53
54
  }
54
55
 
55
56
  if (!resp.ok) {
@@ -21,6 +21,8 @@ export type LoggerBindings = {
21
21
  instanceId?: string;
22
22
  };
23
23
 
24
+ const MAX_MODULE_NAME_LENGTH = 256;
25
+
24
26
  // Allow global hooks for providing default bindings.
25
27
  // Used by withLoggerBindings in pino-logger-server to propagate bindings via AsyncLocalStorage.
26
28
  type LogBindingsHandler = () => LoggerBindings | undefined;
@@ -48,7 +50,7 @@ function getBindingsFromHandlers(): LoggerBindings | undefined {
48
50
  }
49
51
 
50
52
  export function createLogger(module: string, bindings?: LoggerBindings): Logger {
51
- module = module.replace(/^aztec:/, '');
53
+ module = module.slice(0, MAX_MODULE_NAME_LENGTH).replace(/^aztec:/, '');
52
54
 
53
55
  const resolvedBindings = { ...getBindingsFromHandlers(), ...bindings };
54
56
  const actor = resolvedBindings?.actor;
@@ -104,6 +104,36 @@ export async function retryUntil<T>(
104
104
  }
105
105
  }
106
106
 
107
+ /**
108
+ * Retry an asynchronous function until it returns a truthy value or the maximum number of retries is exceeded.
109
+ * The function is retried periodically with a fixed interval between attempts.
110
+ *
111
+ * @param fn - The asynchronous function to be retried, which should return a truthy value upon success or undefined otherwise.
112
+ * @param name - The optional name of the operation, used for generating error messages.
113
+ * @param maxRetries - The maximum number of retry attempts before throwing an error.
114
+ * @param retryInterval - The optional interval, in seconds, between retry attempts. Defaults to 1 second.
115
+ * @returns A Promise that resolves with the successful (truthy) result of the provided function, or rejects if retries are exhausted.
116
+ */
117
+ export async function retryTimes<T>(
118
+ fn: () => (T | undefined) | Promise<T | undefined>,
119
+ name = '',
120
+ maxRetries: number,
121
+ retryInterval = 1,
122
+ ) {
123
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
124
+ const result = await fn();
125
+ if (result) {
126
+ return result;
127
+ }
128
+
129
+ if (attempt < maxRetries) {
130
+ await sleep(retryInterval * 1000);
131
+ }
132
+ }
133
+
134
+ throw new Error(name ? `Retries exhausted awaiting ${name}` : 'Retries exhausted');
135
+ }
136
+
107
137
  /**
108
138
  * Convenience wrapper around retryUntil with fast polling for tests.
109
139
  * Uses 10s timeout and 100ms polling interval by default.
@@ -37,7 +37,10 @@ export type ApiSchema = {
37
37
  };
38
38
 
39
39
  /** Return whether an API schema defines a valid function schema for a given method name. */
40
- export function schemaHasMethod(schema: ApiSchema, methodName: string) {
40
+ export function schemaHasMethod<T extends ApiSchema>(
41
+ schema: T,
42
+ methodName: string,
43
+ ): methodName is Extract<keyof T, string> {
41
44
  return (
42
45
  typeof methodName === 'string' &&
43
46
  Object.hasOwn(schema, methodName) &&
@@ -2,7 +2,17 @@ import { EventEmitter } from 'events';
2
2
 
3
3
  import { type TransferDescriptor, isTransferDescriptor } from '../interface/transferable.js';
4
4
  import type { TransportClient } from '../transport_client.js';
5
- import type { DispatchMsg } from './create_dispatch_fn.js';
5
+
6
+ /**
7
+ * Represents a message object for dispatching function calls.
8
+ * Contains the function name ('fn') and an array of arguments ('args') required to call the target method.
9
+ */
10
+ export interface DispatchMsg {
11
+ /** Name of the target method to be called. */
12
+ fn: string;
13
+ /** An array of arguments to be passed to the target method. */
14
+ args: any[];
15
+ }
6
16
 
7
17
  /**
8
18
  * FilterOutAttributes type filters out all non-method properties of an object, leaving only the attributes
@@ -1,4 +1,3 @@
1
- export * from './dispatch/create_dispatch_fn.js';
2
1
  export * from './dispatch/create_dispatch_proxy.js';
3
2
  export * from './dispatch/messages.js';
4
3
  export * from './interface/connector.js';
@@ -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([
@@ -1,51 +0,0 @@
1
- import { Buffer } from 'buffer';
2
- /**
3
- * For serializing an array of fixed length buffers.
4
- * TODO move to foundation pkg.
5
- * @param arr - Array of bufffers.
6
- * @returns The serialized buffers.
7
- */
8
- export declare function serializeBufferArrayToVector(arr: Buffer[]): Buffer<ArrayBuffer>;
9
- /**
10
- * Helper function for deserializeArrayFromVector.
11
- */
12
- type DeserializeFn<T> = (buf: Buffer, offset: number) => {
13
- /**
14
- * The deserialized type.
15
- */
16
- elem: T;
17
- /**
18
- * How many bytes to advance by.
19
- */
20
- adv: number;
21
- };
22
- /**
23
- * For deserializing numbers to 32-bit little-endian form.
24
- * TODO move to foundation pkg.
25
- * @param n - The number.
26
- * @returns The endian-corrected number.
27
- */
28
- export declare function deserializeArrayFromVector<T>(deserialize: DeserializeFn<T>, vector: Buffer, offset?: number): {
29
- elem: T[];
30
- adv: number;
31
- };
32
- /**
33
- * For serializing numbers to 32 bit little-endian form.
34
- * TODO move to foundation pkg.
35
- * @param n - The number.
36
- * @returns The endian-corrected number.
37
- */
38
- export declare function numToUInt32LE(n: number, bufferSize?: number): Buffer<ArrayBuffer>;
39
- /**
40
- * Deserialize the 256-bit number at address `offset`.
41
- * @param buf - The buffer.
42
- * @param offset - The address.
43
- * @returns The derserialized 256-bit field.
44
- */
45
- export declare function deserializeField(buf: Buffer, offset?: number): {
46
- elem: Buffer<ArrayBuffer>;
47
- adv: number;
48
- };
49
- export declare function concatenateUint8Arrays(arrayOfUint8Arrays: Uint8Array[]): Uint8Array<ArrayBuffer>;
50
- export {};
51
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2VyaWFsaXplLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvY3J5cHRvL3NlcmlhbGl6ZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFFQSxPQUFPLEVBQUUsTUFBTSxFQUFFLE1BQU0sUUFBUSxDQUFDO0FBRWhDOzs7OztHQUtHO0FBQ0gsd0JBQWdCLDRCQUE0QixDQUFDLEdBQUcsRUFBRSxNQUFNLEVBQUUsdUJBSXpEO0FBRUQ7O0dBRUc7QUFDSCxLQUFLLGFBQWEsQ0FBQyxDQUFDLElBQUksQ0FDdEIsR0FBRyxFQUFFLE1BQU0sRUFDWCxNQUFNLEVBQUUsTUFBTSxLQUNYO0lBQ0g7O09BRUc7SUFDSCxJQUFJLEVBQUUsQ0FBQyxDQUFDO0lBQ1I7O09BRUc7SUFDSCxHQUFHLEVBQUUsTUFBTSxDQUFDO0NBQ2IsQ0FBQztBQUVGOzs7OztHQUtHO0FBQ0gsd0JBQWdCLDBCQUEwQixDQUFDLENBQUMsRUFBRSxXQUFXLEVBQUUsYUFBYSxDQUFDLENBQUMsQ0FBQyxFQUFFLE1BQU0sRUFBRSxNQUFNLEVBQUUsTUFBTSxTQUFJOzs7RUFXdEc7QUFFRDs7Ozs7R0FLRztBQUNILHdCQUFnQixhQUFhLENBQUMsQ0FBQyxFQUFFLE1BQU0sRUFBRSxVQUFVLFNBQUksdUJBSXREO0FBRUQ7Ozs7O0dBS0c7QUFDSCx3QkFBZ0IsZ0JBQWdCLENBQUMsR0FBRyxFQUFFLE1BQU0sRUFBRSxNQUFNLFNBQUk7OztFQUd2RDtBQUVELHdCQUFnQixzQkFBc0IsQ0FBQyxrQkFBa0IsRUFBRSxVQUFVLEVBQUUsMkJBU3RFIn0=
@@ -1 +0,0 @@
1
- {"version":3,"file":"serialize.d.ts","sourceRoot":"","sources":["../../src/crypto/serialize.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC;;;;;GAKG;AACH,wBAAgB,4BAA4B,CAAC,GAAG,EAAE,MAAM,EAAE,uBAIzD;AAED;;GAEG;AACH,KAAK,aAAa,CAAC,CAAC,IAAI,CACtB,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,MAAM,KACX;IACH;;OAEG;IACH,IAAI,EAAE,CAAC,CAAC;IACR;;OAEG;IACH,GAAG,EAAE,MAAM,CAAC;CACb,CAAC;AAEF;;;;;GAKG;AACH,wBAAgB,0BAA0B,CAAC,CAAC,EAAE,WAAW,EAAE,aAAa,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,SAAI;;;EAWtG;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,CAAC,EAAE,MAAM,EAAE,UAAU,SAAI,uBAItD;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,SAAI;;;EAGvD;AAED,wBAAgB,sBAAsB,CAAC,kBAAkB,EAAE,UAAU,EAAE,2BAStE"}
@@ -1,68 +0,0 @@
1
- // TODO find a new home for this as we move to external bb.js
2
- // See https://github.com/AztecProtocol/aztec-packages/issues/782
3
- import { Buffer } from 'buffer';
4
- /**
5
- * For serializing an array of fixed length buffers.
6
- * TODO move to foundation pkg.
7
- * @param arr - Array of bufffers.
8
- * @returns The serialized buffers.
9
- */ export function serializeBufferArrayToVector(arr) {
10
- const lengthBuf = Buffer.alloc(4);
11
- lengthBuf.writeUInt32BE(arr.length, 0);
12
- return Buffer.concat([
13
- lengthBuf,
14
- ...arr
15
- ]);
16
- }
17
- /**
18
- * For deserializing numbers to 32-bit little-endian form.
19
- * TODO move to foundation pkg.
20
- * @param n - The number.
21
- * @returns The endian-corrected number.
22
- */ export function deserializeArrayFromVector(deserialize, vector, offset = 0) {
23
- let pos = offset;
24
- const size = vector.readUInt32BE(pos);
25
- pos += 4;
26
- const arr = new Array(size);
27
- for(let i = 0; i < size; ++i){
28
- const { elem, adv } = deserialize(vector, pos);
29
- pos += adv;
30
- arr[i] = elem;
31
- }
32
- return {
33
- elem: arr,
34
- adv: pos - offset
35
- };
36
- }
37
- /**
38
- * For serializing numbers to 32 bit little-endian form.
39
- * TODO move to foundation pkg.
40
- * @param n - The number.
41
- * @returns The endian-corrected number.
42
- */ export function numToUInt32LE(n, bufferSize = 4) {
43
- const buf = Buffer.alloc(bufferSize);
44
- buf.writeUInt32LE(n, bufferSize - 4);
45
- return buf;
46
- }
47
- /**
48
- * Deserialize the 256-bit number at address `offset`.
49
- * @param buf - The buffer.
50
- * @param offset - The address.
51
- * @returns The derserialized 256-bit field.
52
- */ export function deserializeField(buf, offset = 0) {
53
- const adv = 32;
54
- return {
55
- elem: buf.slice(offset, offset + adv),
56
- adv
57
- };
58
- }
59
- export function concatenateUint8Arrays(arrayOfUint8Arrays) {
60
- const totalLength = arrayOfUint8Arrays.reduce((prev, curr)=>prev + curr.length, 0);
61
- const result = new Uint8Array(totalLength);
62
- let length = 0;
63
- for (const array of arrayOfUint8Arrays){
64
- result.set(array, length);
65
- length += array.length;
66
- }
67
- return result;
68
- }
@@ -1,25 +0,0 @@
1
- /**
2
- * Represents a message object for dispatching function calls.
3
- * Contains the function name ('fn') and an array of arguments ('args') required to call the target method.
4
- */
5
- export interface DispatchMsg {
6
- /**
7
- * Name of the target method to be called.
8
- */
9
- fn: string;
10
- /**
11
- * An array of arguments to be passed to the target method.
12
- */
13
- args: any[];
14
- }
15
- /**
16
- * Creates a dispatch function that calls the target's specified method with provided arguments.
17
- * The created dispatch function takes a DispatchMsg object as input, which contains the name of
18
- * the method to be called ('fn') and an array of arguments to be passed to the method ('args').
19
- *
20
- * @param targetFn - A function that returns the target object containing the methods to be dispatched.
21
- * @param log - Optional logging function for debugging purposes.
22
- * @returns A dispatch function that accepts a DispatchMsg object and calls the target's method with provided arguments.
23
- */
24
- export declare function createDispatchFn(targetFn: () => any, log?: import("../../log/pino-logger.js").Logger): ({ fn, args }: DispatchMsg) => Promise<any>;
25
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY3JlYXRlX2Rpc3BhdGNoX2ZuLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvdHJhbnNwb3J0L2Rpc3BhdGNoL2NyZWF0ZV9kaXNwYXRjaF9mbi50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFJQTs7O0dBR0c7QUFDSCxNQUFNLFdBQVcsV0FBVztJQUMxQjs7T0FFRztJQUNILEVBQUUsRUFBRSxNQUFNLENBQUM7SUFDWDs7T0FFRztJQUNILElBQUksRUFBRSxHQUFHLEVBQUUsQ0FBQztDQUNiO0FBRUQ7Ozs7Ozs7O0dBUUc7QUFDSCx3QkFBZ0IsZ0JBQWdCLENBQUMsUUFBUSxFQUFFLE1BQU0sR0FBRyxFQUFFLEdBQUcsNENBQXNDLCtDQU05RiJ9
@@ -1 +0,0 @@
1
- {"version":3,"file":"create_dispatch_fn.d.ts","sourceRoot":"","sources":["../../../src/transport/dispatch/create_dispatch_fn.ts"],"names":[],"mappings":"AAIA;;;GAGG;AACH,MAAM,WAAW,WAAW;IAC1B;;OAEG;IACH,EAAE,EAAE,MAAM,CAAC;IACX;;OAEG;IACH,IAAI,EAAE,GAAG,EAAE,CAAC;CACb;AAED;;;;;;;;GAQG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,EAAE,GAAG,4CAAsC,+CAM9F"}
@@ -1,17 +0,0 @@
1
- import { format } from 'util';
2
- import { createLogger } from '../../log/index.js';
3
- /**
4
- * Creates a dispatch function that calls the target's specified method with provided arguments.
5
- * The created dispatch function takes a DispatchMsg object as input, which contains the name of
6
- * the method to be called ('fn') and an array of arguments to be passed to the method ('args').
7
- *
8
- * @param targetFn - A function that returns the target object containing the methods to be dispatched.
9
- * @param log - Optional logging function for debugging purposes.
10
- * @returns A dispatch function that accepts a DispatchMsg object and calls the target's method with provided arguments.
11
- */ export function createDispatchFn(targetFn, log = createLogger('foundation:dispatch')) {
12
- return async ({ fn, args })=>{
13
- const target = targetFn();
14
- log.debug(format(`dispatching to ${target}: ${fn}`, args));
15
- return await target[fn](...args);
16
- };
17
- }
@@ -1,85 +0,0 @@
1
- // TODO find a new home for this as we move to external bb.js
2
- // See https://github.com/AztecProtocol/aztec-packages/issues/782
3
- import { Buffer } from 'buffer';
4
-
5
- /**
6
- * For serializing an array of fixed length buffers.
7
- * TODO move to foundation pkg.
8
- * @param arr - Array of bufffers.
9
- * @returns The serialized buffers.
10
- */
11
- export function serializeBufferArrayToVector(arr: Buffer[]) {
12
- const lengthBuf = Buffer.alloc(4);
13
- lengthBuf.writeUInt32BE(arr.length, 0);
14
- return Buffer.concat([lengthBuf, ...arr]);
15
- }
16
-
17
- /**
18
- * Helper function for deserializeArrayFromVector.
19
- */
20
- type DeserializeFn<T> = (
21
- buf: Buffer,
22
- offset: number,
23
- ) => {
24
- /**
25
- * The deserialized type.
26
- */
27
- elem: T;
28
- /**
29
- * How many bytes to advance by.
30
- */
31
- adv: number;
32
- };
33
-
34
- /**
35
- * For deserializing numbers to 32-bit little-endian form.
36
- * TODO move to foundation pkg.
37
- * @param n - The number.
38
- * @returns The endian-corrected number.
39
- */
40
- export function deserializeArrayFromVector<T>(deserialize: DeserializeFn<T>, vector: Buffer, offset = 0) {
41
- let pos = offset;
42
- const size = vector.readUInt32BE(pos);
43
- pos += 4;
44
- const arr = new Array<T>(size);
45
- for (let i = 0; i < size; ++i) {
46
- const { elem, adv } = deserialize(vector, pos);
47
- pos += adv;
48
- arr[i] = elem;
49
- }
50
- return { elem: arr, adv: pos - offset };
51
- }
52
-
53
- /**
54
- * For serializing numbers to 32 bit little-endian form.
55
- * TODO move to foundation pkg.
56
- * @param n - The number.
57
- * @returns The endian-corrected number.
58
- */
59
- export function numToUInt32LE(n: number, bufferSize = 4) {
60
- const buf = Buffer.alloc(bufferSize);
61
- buf.writeUInt32LE(n, bufferSize - 4);
62
- return buf;
63
- }
64
-
65
- /**
66
- * Deserialize the 256-bit number at address `offset`.
67
- * @param buf - The buffer.
68
- * @param offset - The address.
69
- * @returns The derserialized 256-bit field.
70
- */
71
- export function deserializeField(buf: Buffer, offset = 0) {
72
- const adv = 32;
73
- return { elem: buf.slice(offset, offset + adv), adv };
74
- }
75
-
76
- export function concatenateUint8Arrays(arrayOfUint8Arrays: Uint8Array[]) {
77
- const totalLength = arrayOfUint8Arrays.reduce((prev, curr) => prev + curr.length, 0);
78
- const result = new Uint8Array(totalLength);
79
- let length = 0;
80
- for (const array of arrayOfUint8Arrays) {
81
- result.set(array, length);
82
- length += array.length;
83
- }
84
- return result;
85
- }
@@ -1,35 +0,0 @@
1
- import { format } from 'util';
2
-
3
- import { createLogger } from '../../log/index.js';
4
-
5
- /**
6
- * Represents a message object for dispatching function calls.
7
- * Contains the function name ('fn') and an array of arguments ('args') required to call the target method.
8
- */
9
- export interface DispatchMsg {
10
- /**
11
- * Name of the target method to be called.
12
- */
13
- fn: string;
14
- /**
15
- * An array of arguments to be passed to the target method.
16
- */
17
- args: any[];
18
- }
19
-
20
- /**
21
- * Creates a dispatch function that calls the target's specified method with provided arguments.
22
- * The created dispatch function takes a DispatchMsg object as input, which contains the name of
23
- * the method to be called ('fn') and an array of arguments to be passed to the method ('args').
24
- *
25
- * @param targetFn - A function that returns the target object containing the methods to be dispatched.
26
- * @param log - Optional logging function for debugging purposes.
27
- * @returns A dispatch function that accepts a DispatchMsg object and calls the target's method with provided arguments.
28
- */
29
- export function createDispatchFn(targetFn: () => any, log = createLogger('foundation:dispatch')) {
30
- return async ({ fn, args }: DispatchMsg) => {
31
- const target = targetFn();
32
- log.debug(format(`dispatching to ${target}: ${fn}`, args));
33
- return await target[fn](...args);
34
- };
35
- }