@aztec/foundation 0.55.1 → 0.56.0

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 (73) hide show
  1. package/dest/abi/decoder.d.ts +6 -6
  2. package/dest/abi/decoder.d.ts.map +1 -1
  3. package/dest/abi/decoder.js +23 -24
  4. package/dest/buffer/buffer32.d.ts +9 -0
  5. package/dest/buffer/buffer32.d.ts.map +1 -1
  6. package/dest/buffer/buffer32.js +18 -1
  7. package/dest/config/env_var.d.ts +1 -1
  8. package/dest/config/env_var.d.ts.map +1 -1
  9. package/dest/crypto/index.d.ts +1 -0
  10. package/dest/crypto/index.d.ts.map +1 -1
  11. package/dest/crypto/index.js +2 -1
  12. package/dest/crypto/secp256k1-signer/index.d.ts +3 -0
  13. package/dest/crypto/secp256k1-signer/index.d.ts.map +1 -0
  14. package/dest/crypto/secp256k1-signer/index.js +3 -0
  15. package/dest/crypto/secp256k1-signer/secp256k1_signer.d.ts +24 -0
  16. package/dest/crypto/secp256k1-signer/secp256k1_signer.d.ts.map +1 -0
  17. package/dest/crypto/secp256k1-signer/secp256k1_signer.js +31 -0
  18. package/dest/crypto/secp256k1-signer/utils.d.ts +39 -0
  19. package/dest/crypto/secp256k1-signer/utils.d.ts.map +1 -0
  20. package/dest/crypto/secp256k1-signer/utils.js +89 -0
  21. package/dest/crypto/sha256/index.d.ts +15 -3
  22. package/dest/crypto/sha256/index.d.ts.map +1 -1
  23. package/dest/crypto/sha256/index.js +110 -5
  24. package/dest/eth-signature/eth_signature.d.ts +54 -0
  25. package/dest/eth-signature/eth_signature.d.ts.map +1 -0
  26. package/dest/eth-signature/eth_signature.js +69 -0
  27. package/dest/eth-signature/index.d.ts +2 -0
  28. package/dest/eth-signature/index.d.ts.map +1 -0
  29. package/dest/eth-signature/index.js +2 -0
  30. package/dest/fields/point.d.ts.map +1 -1
  31. package/dest/fields/point.js +3 -2
  32. package/dest/index.d.ts +1 -0
  33. package/dest/index.d.ts.map +1 -1
  34. package/dest/index.js +2 -1
  35. package/dest/serialize/buffer_reader.d.ts +9 -0
  36. package/dest/serialize/buffer_reader.d.ts.map +1 -1
  37. package/dest/serialize/buffer_reader.js +18 -1
  38. package/dest/serialize/serialize.js +2 -2
  39. package/dest/serialize/types.d.ts +1 -1
  40. package/dest/serialize/types.d.ts.map +1 -1
  41. package/dest/serialize/types.js +1 -1
  42. package/dest/testing/index.d.ts +1 -0
  43. package/dest/testing/index.d.ts.map +1 -1
  44. package/dest/testing/index.js +2 -1
  45. package/dest/testing/port_allocator.d.ts +10 -0
  46. package/dest/testing/port_allocator.d.ts.map +1 -0
  47. package/dest/testing/port_allocator.js +32 -0
  48. package/dest/trees/index.d.ts +1 -0
  49. package/dest/trees/index.d.ts.map +1 -1
  50. package/dest/trees/index.js +2 -2
  51. package/dest/trees/unbalanced_merkle_root.d.ts +12 -0
  52. package/dest/trees/unbalanced_merkle_root.d.ts.map +1 -0
  53. package/dest/trees/unbalanced_merkle_root.js +52 -0
  54. package/package.json +5 -3
  55. package/src/abi/decoder.ts +24 -25
  56. package/src/buffer/buffer32.ts +18 -0
  57. package/src/config/env_var.ts +1 -1
  58. package/src/crypto/index.ts +1 -0
  59. package/src/crypto/secp256k1-signer/index.ts +2 -0
  60. package/src/crypto/secp256k1-signer/secp256k1_signer.ts +38 -0
  61. package/src/crypto/secp256k1-signer/utils.ts +99 -0
  62. package/src/crypto/sha256/index.ts +137 -4
  63. package/src/eth-signature/eth_signature.ts +90 -0
  64. package/src/eth-signature/index.ts +1 -0
  65. package/src/fields/point.ts +2 -1
  66. package/src/index.ts +1 -0
  67. package/src/serialize/buffer_reader.ts +20 -0
  68. package/src/serialize/serialize.ts +1 -1
  69. package/src/serialize/types.ts +1 -1
  70. package/src/testing/index.ts +1 -0
  71. package/src/testing/port_allocator.ts +31 -0
  72. package/src/trees/index.ts +2 -0
  73. package/src/trees/unbalanced_merkle_root.ts +52 -0
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/trees/index.ts"],"names":[],"mappings":";AAAA;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B;;OAEG;IACH,MAAM,IAAI,MAAM,CAAC;IACjB;;OAEG;IACH,QAAQ,IAAI,MAAM,CAAC;IACnB;;OAEG;IACH,OAAO,IAAI,OAAO,CAAC;IACnB;;;;OAIG;IACH,QAAQ,CAAC,OAAO,EAAE,eAAe,GAAG,eAAe,CAAC;CACrD;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;OAEG;IACH,MAAM,IAAI,MAAM,CAAC;IACjB;;OAEG;IACH,MAAM,IAAI,eAAe,CAAC;IAC1B;;OAEG;IACH,QAAQ,IAAI,MAAM,CAAC;IACnB;;OAEG;IACH,YAAY,IAAI,MAAM,EAAE,CAAC;CAC1B;AAED;;GAEG;AACH,MAAM,WAAW,uBAAwB,SAAQ,gBAAgB;IAC/D,UAAU,IAAI,MAAM,CAAC;IACrB;;OAEG;IACH,YAAY,IAAI,MAAM,CAAC;CACxB"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/trees/index.ts"],"names":[],"mappings":";AAAA,cAAc,6BAA6B,CAAC;AAE5C;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B;;OAEG;IACH,MAAM,IAAI,MAAM,CAAC;IACjB;;OAEG;IACH,QAAQ,IAAI,MAAM,CAAC;IACnB;;OAEG;IACH,OAAO,IAAI,OAAO,CAAC;IACnB;;;;OAIG;IACH,QAAQ,CAAC,OAAO,EAAE,eAAe,GAAG,eAAe,CAAC;CACrD;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;OAEG;IACH,MAAM,IAAI,MAAM,CAAC;IACjB;;OAEG;IACH,MAAM,IAAI,eAAe,CAAC;IAC1B;;OAEG;IACH,QAAQ,IAAI,MAAM,CAAC;IACnB;;OAEG;IACH,YAAY,IAAI,MAAM,EAAE,CAAC;CAC1B;AAED;;GAEG;AACH,MAAM,WAAW,uBAAwB,SAAQ,gBAAgB;IAC/D,UAAU,IAAI,MAAM,CAAC;IACrB;;OAEG;IACH,YAAY,IAAI,MAAM,CAAC;CACxB"}
@@ -1,2 +1,2 @@
1
- export {};
2
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvdHJlZXMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9
1
+ export * from './unbalanced_merkle_root.js';
2
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvdHJlZXMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsY0FBYyw2QkFBNkIsQ0FBQyJ9
@@ -0,0 +1,12 @@
1
+ /// <reference types="node" resolution-mode="require"/>
2
+ import { sha256Trunc } from '@aztec/foundation/crypto';
3
+ /**
4
+ * Computes the merkle root for an unbalanced tree.
5
+ *
6
+ * @dev Adapted from proving-state.ts -> findMergeLevel and unbalanced_tree.ts.
7
+ * Calculates the tree upwards layer by layer until we reach the root.
8
+ * The L1 calculation instead computes the tree from right to left (slightly cheaper gas).
9
+ * TODO: A more thorough investigation of which method is cheaper, then use that method everywhere.
10
+ */
11
+ export declare function computeUnbalancedMerkleRoot(leaves: Buffer[], emptyLeaf?: Buffer, hasher?: typeof sha256Trunc): Buffer;
12
+ //# sourceMappingURL=unbalanced_merkle_root.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unbalanced_merkle_root.d.ts","sourceRoot":"","sources":["../../src/trees/unbalanced_merkle_root.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAEvD;;;;;;;GAOG;AACH,wBAAgB,2BAA2B,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,SAAS,CAAC,EAAE,MAAM,EAAE,MAAM,qBAAc,GAAG,MAAM,CAwC9G"}
@@ -0,0 +1,52 @@
1
+ import { padArrayEnd } from '@aztec/foundation/collection';
2
+ import { sha256Trunc } from '@aztec/foundation/crypto';
3
+ /**
4
+ * Computes the merkle root for an unbalanced tree.
5
+ *
6
+ * @dev Adapted from proving-state.ts -> findMergeLevel and unbalanced_tree.ts.
7
+ * Calculates the tree upwards layer by layer until we reach the root.
8
+ * The L1 calculation instead computes the tree from right to left (slightly cheaper gas).
9
+ * TODO: A more thorough investigation of which method is cheaper, then use that method everywhere.
10
+ */
11
+ export function computeUnbalancedMerkleRoot(leaves, emptyLeaf, hasher = sha256Trunc) {
12
+ // Pad leaves to 2
13
+ if (leaves.length < 2) {
14
+ if (emptyLeaf === undefined) {
15
+ throw new Error('Cannot compute a Merkle root with less than 2 leaves');
16
+ }
17
+ else {
18
+ leaves = padArrayEnd(leaves, emptyLeaf, 2);
19
+ }
20
+ }
21
+ const depth = Math.ceil(Math.log2(leaves.length));
22
+ let [layerWidth, nodeToShift] = leaves.length & 1 ? [leaves.length - 1, leaves[leaves.length - 1]] : [leaves.length, Buffer.alloc(0)];
23
+ // Allocate this layer's leaves and init the next layer up
24
+ let thisLayer = leaves.slice(0, layerWidth);
25
+ let nextLayer = [];
26
+ for (let i = 0; i < depth; i++) {
27
+ for (let j = 0; j < layerWidth; j += 2) {
28
+ // Store the hash of each pair one layer up
29
+ nextLayer[j / 2] = hasher(Buffer.concat([thisLayer[j], thisLayer[j + 1]]));
30
+ }
31
+ layerWidth /= 2;
32
+ if (layerWidth & 1) {
33
+ if (nodeToShift.length) {
34
+ // If the next layer has odd length, and we have a node that needs to be shifted up, add it here
35
+ nextLayer.push(nodeToShift);
36
+ layerWidth += 1;
37
+ nodeToShift = Buffer.alloc(0);
38
+ }
39
+ else {
40
+ // If we don't have a node waiting to be shifted, store the next layer's final node to be shifted
41
+ layerWidth -= 1;
42
+ nodeToShift = nextLayer[layerWidth];
43
+ }
44
+ }
45
+ // reset the layers
46
+ thisLayer = nextLayer;
47
+ nextLayer = [];
48
+ }
49
+ // return the root
50
+ return thisLayer[0];
51
+ }
52
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidW5iYWxhbmNlZF9tZXJrbGVfcm9vdC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy90cmVlcy91bmJhbGFuY2VkX21lcmtsZV9yb290LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLE9BQU8sRUFBRSxXQUFXLEVBQUUsTUFBTSw4QkFBOEIsQ0FBQztBQUMzRCxPQUFPLEVBQUUsV0FBVyxFQUFFLE1BQU0sMEJBQTBCLENBQUM7QUFFdkQ7Ozs7Ozs7R0FPRztBQUNILE1BQU0sVUFBVSwyQkFBMkIsQ0FBQyxNQUFnQixFQUFFLFNBQWtCLEVBQUUsTUFBTSxHQUFHLFdBQVc7SUFDcEcsa0JBQWtCO0lBQ2xCLElBQUksTUFBTSxDQUFDLE1BQU0sR0FBRyxDQUFDLEVBQUUsQ0FBQztRQUN0QixJQUFJLFNBQVMsS0FBSyxTQUFTLEVBQUUsQ0FBQztZQUM1QixNQUFNLElBQUksS0FBSyxDQUFDLHNEQUFzRCxDQUFDLENBQUM7UUFDMUUsQ0FBQzthQUFNLENBQUM7WUFDTixNQUFNLEdBQUcsV0FBVyxDQUFDLE1BQU0sRUFBRSxTQUFTLEVBQUUsQ0FBQyxDQUFDLENBQUM7UUFDN0MsQ0FBQztJQUNILENBQUM7SUFFRCxNQUFNLEtBQUssR0FBRyxJQUFJLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxJQUFJLENBQUMsTUFBTSxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUM7SUFDbEQsSUFBSSxDQUFDLFVBQVUsRUFBRSxXQUFXLENBQUMsR0FDM0IsTUFBTSxDQUFDLE1BQU0sR0FBRyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsTUFBTSxDQUFDLE1BQU0sR0FBRyxDQUFDLEVBQUUsTUFBTSxDQUFDLE1BQU0sQ0FBQyxNQUFNLEdBQUcsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxNQUFNLENBQUMsTUFBTSxFQUFFLE1BQU0sQ0FBQyxLQUFLLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQztJQUN4RywwREFBMEQ7SUFDMUQsSUFBSSxTQUFTLEdBQUcsTUFBTSxDQUFDLEtBQUssQ0FBQyxDQUFDLEVBQUUsVUFBVSxDQUFDLENBQUM7SUFDNUMsSUFBSSxTQUFTLEdBQUcsRUFBRSxDQUFDO0lBQ25CLEtBQUssSUFBSSxDQUFDLEdBQUcsQ0FBQyxFQUFFLENBQUMsR0FBRyxLQUFLLEVBQUUsQ0FBQyxFQUFFLEVBQUUsQ0FBQztRQUMvQixLQUFLLElBQUksQ0FBQyxHQUFHLENBQUMsRUFBRSxDQUFDLEdBQUcsVUFBVSxFQUFFLENBQUMsSUFBSSxDQUFDLEVBQUUsQ0FBQztZQUN2QywyQ0FBMkM7WUFDM0MsU0FBUyxDQUFDLENBQUMsR0FBRyxDQUFDLENBQUMsR0FBRyxNQUFNLENBQUMsTUFBTSxDQUFDLE1BQU0sQ0FBQyxDQUFDLFNBQVMsQ0FBQyxDQUFDLENBQUMsRUFBRSxTQUFTLENBQUMsQ0FBQyxHQUFHLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDO1FBQzdFLENBQUM7UUFDRCxVQUFVLElBQUksQ0FBQyxDQUFDO1FBQ2hCLElBQUksVUFBVSxHQUFHLENBQUMsRUFBRSxDQUFDO1lBQ25CLElBQUksV0FBVyxDQUFDLE1BQU0sRUFBRSxDQUFDO2dCQUN2QixnR0FBZ0c7Z0JBQ2hHLFNBQVMsQ0FBQyxJQUFJLENBQUMsV0FBVyxDQUFDLENBQUM7Z0JBQzVCLFVBQVUsSUFBSSxDQUFDLENBQUM7Z0JBQ2hCLFdBQVcsR0FBRyxNQUFNLENBQUMsS0FBSyxDQUFDLENBQUMsQ0FBQyxDQUFDO1lBQ2hDLENBQUM7aUJBQU0sQ0FBQztnQkFDTixpR0FBaUc7Z0JBQ2pHLFVBQVUsSUFBSSxDQUFDLENBQUM7Z0JBQ2hCLFdBQVcsR0FBRyxTQUFTLENBQUMsVUFBVSxDQUFDLENBQUM7WUFDdEMsQ0FBQztRQUNILENBQUM7UUFDRCxtQkFBbUI7UUFDbkIsU0FBUyxHQUFHLFNBQVMsQ0FBQztRQUN0QixTQUFTLEdBQUcsRUFBRSxDQUFDO0lBQ2pCLENBQUM7SUFDRCxrQkFBa0I7SUFDbEIsT0FBTyxTQUFTLENBQUMsQ0FBQyxDQUFDLENBQUM7QUFDdEIsQ0FBQyJ9
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aztec/foundation",
3
- "version": "0.55.1",
3
+ "version": "0.56.0",
4
4
  "packageManager": "yarn@3.4.1",
5
5
  "type": "module",
6
6
  "main": "./dest/index.js",
@@ -17,6 +17,7 @@
17
17
  "./crypto": "./dest/crypto/index.js",
18
18
  "./error": "./dest/error/index.js",
19
19
  "./eth-address": "./dest/eth-address/index.js",
20
+ "./eth-signature": "./dest/eth-signature/index.js",
20
21
  "./queue": "./dest/queue/index.js",
21
22
  "./fs": "./dest/fs/index.js",
22
23
  "./buffer": "./dest/buffer/index.js",
@@ -90,7 +91,7 @@
90
91
  ]
91
92
  },
92
93
  "dependencies": {
93
- "@aztec/bb.js": "0.55.1",
94
+ "@aztec/bb.js": "0.56.0",
94
95
  "@koa/cors": "^5.0.0",
95
96
  "@noble/curves": "^1.2.0",
96
97
  "bn.js": "^5.2.1",
@@ -144,7 +145,8 @@
144
145
  "prettier": "^2.7.1",
145
146
  "supertest": "^6.3.3",
146
147
  "ts-node": "^10.9.1",
147
- "typescript": "^5.0.4"
148
+ "typescript": "^5.0.4",
149
+ "viem": "^2.7.15"
148
150
  },
149
151
  "files": [
150
152
  "dest",
@@ -6,21 +6,21 @@ import { isAztecAddressStruct } from './utils.js';
6
6
  /**
7
7
  * The type of our decoded ABI.
8
8
  */
9
- export type DecodedReturn = bigint | boolean | AztecAddress | DecodedReturn[] | { [key: string]: DecodedReturn };
9
+ export type AbiDecoded = bigint | boolean | AztecAddress | AbiDecoded[] | { [key: string]: AbiDecoded };
10
10
 
11
11
  /**
12
- * Decodes return values from a function call.
13
- * Missing support for integer and string.
12
+ * Decodes values using a provided ABI.
13
+ * Missing support for signed integer.
14
14
  */
15
- class ReturnValuesDecoder {
16
- constructor(private returnTypes: AbiType[], private flattened: Fr[]) {}
15
+ class AbiDecoder {
16
+ constructor(private types: AbiType[], private flattened: Fr[]) {}
17
17
 
18
18
  /**
19
19
  * Decodes a single return value from field to the given type.
20
20
  * @param abiType - The type of the return value.
21
21
  * @returns The decoded return value.
22
22
  */
23
- private decodeReturn(abiType: AbiType): DecodedReturn {
23
+ private decodeNext(abiType: AbiType): AbiDecoded {
24
24
  switch (abiType.kind) {
25
25
  case 'field':
26
26
  return this.getNextField().toBigInt();
@@ -34,18 +34,18 @@ class ReturnValuesDecoder {
34
34
  case 'array': {
35
35
  const array = [];
36
36
  for (let i = 0; i < abiType.length; i += 1) {
37
- array.push(this.decodeReturn(abiType.type));
37
+ array.push(this.decodeNext(abiType.type));
38
38
  }
39
39
  return array;
40
40
  }
41
41
  case 'struct': {
42
- const struct: { [key: string]: DecodedReturn } = {};
42
+ const struct: { [key: string]: AbiDecoded } = {};
43
43
  if (isAztecAddressStruct(abiType)) {
44
44
  return new AztecAddress(this.getNextField().toBuffer());
45
45
  }
46
46
 
47
47
  for (const field of abiType.fields) {
48
- struct[field.name] = this.decodeReturn(field.type);
48
+ struct[field.name] = this.decodeNext(field.type);
49
49
  }
50
50
  return struct;
51
51
  }
@@ -59,7 +59,7 @@ class ReturnValuesDecoder {
59
59
  case 'tuple': {
60
60
  const array = [];
61
61
  for (const tupleAbiType of abiType.fields) {
62
- array.push(this.decodeReturn(tupleAbiType));
62
+ array.push(this.decodeNext(tupleAbiType));
63
63
  }
64
64
  return array;
65
65
  }
@@ -69,8 +69,8 @@ class ReturnValuesDecoder {
69
69
  }
70
70
 
71
71
  /**
72
- * Gets the next field in the flattened return values.
73
- * @returns The next field in the flattened return values.
72
+ * Gets the next field in the flattened buffer.
73
+ * @returns The next field in the flattened buffer.
74
74
  */
75
75
  private getNextField(): Fr {
76
76
  const field = this.flattened.shift();
@@ -81,30 +81,29 @@ class ReturnValuesDecoder {
81
81
  }
82
82
 
83
83
  /**
84
- * Decodes all the return values for the given function ABI.
85
- * Aztec.nr support only single return value
86
- * The return value can however be simple types, structs or arrays
84
+ * Decodes all the values for the given ABI.
85
+ * The decided value can be simple types, structs or arrays
87
86
  * @returns The decoded return values.
88
87
  */
89
- public decode(): DecodedReturn {
90
- if (this.returnTypes.length > 1) {
91
- throw new Error('Multiple return values not supported');
88
+ public decode(): AbiDecoded {
89
+ if (this.types.length > 1) {
90
+ throw new Error('Multiple types not supported');
92
91
  }
93
- if (this.returnTypes.length === 0) {
92
+ if (this.types.length === 0) {
94
93
  return [];
95
94
  }
96
- return this.decodeReturn(this.returnTypes[0]);
95
+ return this.decodeNext(this.types[0]);
97
96
  }
98
97
  }
99
98
 
100
99
  /**
101
- * Decodes return values from a function call.
102
- * @param abi - The ABI entry of the function.
103
- * @param returnValues - The decoded return values.
100
+ * Decodes values in a flattened Field array using a provided ABI.
101
+ * @param abi - The ABI to use as reference.
102
+ * @param buffer - The flattened Field array to decode.
104
103
  * @returns
105
104
  */
106
- export function decodeReturnValues(returnTypes: AbiType[], returnValues: Fr[]) {
107
- return new ReturnValuesDecoder(returnTypes, returnValues.slice()).decode();
105
+ export function decodeFromAbi(typ: AbiType[], buffer: Fr[]) {
106
+ return new AbiDecoder(typ, buffer.slice()).decode();
108
107
  }
109
108
 
110
109
  /**
@@ -112,7 +112,25 @@ export class Buffer32 {
112
112
  * @param str - The TX hash in string format.
113
113
  * @returns A new Buffer32 object.
114
114
  */
115
+ public static fromStringUnchecked(str: string): Buffer32 {
116
+ return new Buffer32(Buffer.from(str, 'hex'));
117
+ }
118
+
119
+ /**
120
+ * Converts a string into a Buffer32 object.
121
+ * NOTE: this method includes checks for the 0x prefix and the length of the string.
122
+ * if you dont need this checks, use fromStringUnchecked instead.
123
+ *
124
+ * @param str - The TX hash in string format.
125
+ * @returns A new Buffer32 object.
126
+ */
115
127
  public static fromString(str: string): Buffer32 {
128
+ if (str.startsWith('0x')) {
129
+ str = str.slice(2);
130
+ }
131
+ if (str.length !== 64) {
132
+ throw new Error(`Expected string to be 64 characters long, but was ${str.length}`);
133
+ }
116
134
  return new Buffer32(Buffer.from(str, 'hex'));
117
135
  }
118
136
 
@@ -1,6 +1,6 @@
1
1
  export type EnvVar =
2
2
  | 'AZTEC_PORT'
3
- | 'ASSUME_PROVEN_UNTIL_BLOCK_NUMBER'
3
+ | 'ASSUME_PROVEN_THROUGH_BLOCK_NUMBER'
4
4
  | 'TEST_ACCOUNTS'
5
5
  | 'ENABLE_GAS'
6
6
  | 'API_PREFIX'
@@ -6,6 +6,7 @@ export * from './sha256/index.js';
6
6
  export * from './sha512/index.js';
7
7
  export * from './pedersen/index.js';
8
8
  export * from './poseidon/index.js';
9
+ export * from './secp256k1-signer/index.js';
9
10
 
10
11
  /**
11
12
  * Init the bb singleton. This constructs (if not already) the barretenberg sync api within bb.js itself.
@@ -0,0 +1,2 @@
1
+ export * from './secp256k1_signer.js';
2
+ export * from './utils.js';
@@ -0,0 +1,38 @@
1
+ import { Buffer32 } from '@aztec/foundation/buffer';
2
+ import { type EthAddress } from '@aztec/foundation/eth-address';
3
+ import { type Signature } from '@aztec/foundation/eth-signature';
4
+
5
+ import { addressFromPrivateKey, makeEthSignDigest, signMessage } from './utils.js';
6
+
7
+ /**
8
+ * Secp256k1Signer
9
+ *
10
+ * A class for signing messages using a secp256k1 private key.
11
+ * - This is a slim drop in replacement for an Ethereum signer, so it can be used in the same way.
12
+ * - See `utils.ts` for functions that enable recovering addresses and public keys from signatures.
13
+ */
14
+ export class Secp256k1Signer {
15
+ public readonly address: EthAddress;
16
+
17
+ constructor(private privateKey: Buffer32) {
18
+ this.address = addressFromPrivateKey(privateKey.buffer);
19
+ }
20
+
21
+ sign(message: Buffer32): Signature {
22
+ return signMessage(message, this.privateKey.buffer);
23
+ }
24
+
25
+ /**
26
+ * Sign a message using the same method as eth_sign
27
+ * @param message - The message to sign.
28
+ * @returns The signature.
29
+ */
30
+ signMessage(message: Buffer32): Signature {
31
+ const digest = makeEthSignDigest(message);
32
+ return this.sign(digest);
33
+ }
34
+
35
+ static random(): Secp256k1Signer {
36
+ return new Secp256k1Signer(Buffer32.random());
37
+ }
38
+ }
@@ -0,0 +1,99 @@
1
+ import { secp256k1 } from '@noble/curves/secp256k1';
2
+
3
+ import { Buffer32 } from '../../buffer/buffer32.js';
4
+ import { EthAddress } from '../../eth-address/index.js';
5
+ import { Signature } from '../../eth-signature/eth_signature.js';
6
+ import { keccak256 } from '../keccak/index.js';
7
+
8
+ const ETH_SIGN_PREFIX = '\x19Ethereum Signed Message:\n32';
9
+
10
+ // We just hash the message to make it easier to work with in the smart contract.
11
+ export function makeEthSignDigest(message: Buffer32): Buffer32 {
12
+ const prefix = Buffer.from(ETH_SIGN_PREFIX);
13
+ return Buffer32.fromBuffer(keccak256(Buffer.concat([prefix, message.buffer])));
14
+ }
15
+
16
+ /**
17
+ * Converts a public key to an address.
18
+ * @param publicKey - The public key to convert.
19
+ * @returns The address.
20
+ */
21
+ function publicKeyToAddress(publicKey: Buffer): EthAddress {
22
+ const hash = keccak256(publicKey.subarray(1));
23
+ return new EthAddress(hash.subarray(12));
24
+ }
25
+
26
+ /**
27
+ * Converts a private key to a public key.
28
+ * @param privateKey - The private key to convert.
29
+ * @returns The public key.
30
+ */
31
+ export function publicKeyFromPrivateKey(privateKey: Buffer): Buffer {
32
+ return Buffer.from(secp256k1.getPublicKey(privateKey, false));
33
+ }
34
+
35
+ /**
36
+ * Converts a private key to an address.
37
+ * @param privateKey - The private key to convert.
38
+ * @returns The address.
39
+ */
40
+ export function addressFromPrivateKey(privateKey: Buffer): EthAddress {
41
+ const publicKey = publicKeyFromPrivateKey(privateKey);
42
+ return publicKeyToAddress(publicKey);
43
+ }
44
+
45
+ /**
46
+ * Recovers an address from a hash and a signature.
47
+ * @param hash - The hash to recover the address from.
48
+ * @param signature - The signature to recover the address from.
49
+ * @returns The address.
50
+ */
51
+ export function recoverAddress(hash: Buffer32, signature: Signature): EthAddress {
52
+ const publicKey = recoverPublicKey(hash, signature);
53
+ return publicKeyToAddress(publicKey);
54
+ }
55
+
56
+ /**
57
+ * @attribution - viem
58
+ * Converts a yParityOrV value to a recovery bit.
59
+ * @param yParityOrV - The yParityOrV value to convert.
60
+ * @returns The recovery bit.
61
+ */
62
+ function toRecoveryBit(yParityOrV: number) {
63
+ if (yParityOrV === 0 || yParityOrV === 1) {
64
+ return yParityOrV;
65
+ }
66
+ if (yParityOrV === 27) {
67
+ return 0;
68
+ }
69
+ if (yParityOrV === 28) {
70
+ return 1;
71
+ }
72
+ throw new Error('Invalid yParityOrV value');
73
+ }
74
+
75
+ /**
76
+ * Signs a message using ecdsa over the secp256k1 curve.
77
+ * @param message - The message to sign.
78
+ * @param privateKey - The private key to sign the message with.
79
+ * @returns The signature.
80
+ */
81
+ export function signMessage(message: Buffer32, privateKey: Buffer) {
82
+ const { r, s, recovery } = secp256k1.sign(message.buffer, privateKey);
83
+ return new Signature(Buffer32.fromBigInt(r), Buffer32.fromBigInt(s), recovery ? 28 : 27);
84
+ }
85
+
86
+ /**
87
+ * Recovers a public key from a hash and a signature.
88
+ * @param hash - The hash to recover the public key from.
89
+ * @param signature - The signature to recover the public key from.
90
+ * @returns The public key.
91
+ */
92
+ export function recoverPublicKey(hash: Buffer32, signature: Signature): Buffer {
93
+ const { r, s, v } = signature;
94
+ const recoveryBit = toRecoveryBit(v);
95
+ const sig = new secp256k1.Signature(r.toBigInt(), s.toBigInt()).addRecoveryBit(recoveryBit);
96
+
97
+ const publicKey = sig.recoverPublicKey(hash.buffer).toHex(false);
98
+ return Buffer.from(publicKey, 'hex');
99
+ }
@@ -1,14 +1,147 @@
1
+ /* eslint-disable camelcase */
1
2
  import { default as hash } from 'hash.js';
2
3
 
3
4
  import { Fr } from '../../fields/fields.js';
4
5
  import { truncateAndPad } from '../../serialize/free_funcs.js';
5
6
  import { type Bufferable, serializeToBuffer } from '../../serialize/serialize.js';
6
7
 
7
- export const sha256 = (data: Buffer) => Buffer.from(hash.sha256().update(data).digest());
8
+ export function sha256(data: Buffer) {
9
+ return Buffer.from(hash.sha256().update(data).digest());
10
+ }
8
11
 
9
- export const sha256Trunc = (data: Buffer) => truncateAndPad(sha256(data));
12
+ export function sha256Trunc(data: Buffer) {
13
+ return truncateAndPad(sha256(data));
14
+ }
10
15
 
11
- export const sha256ToField = (data: Bufferable[]) => {
16
+ export function sha256ToField(data: Bufferable[]) {
12
17
  const buffer = serializeToBuffer(data);
13
18
  return Fr.fromBuffer(sha256Trunc(buffer));
14
- };
19
+ }
20
+
21
+ /**
22
+ * The "SHA256 Compression" operation (component operation of SHA256 "Hash").
23
+ * WARNING: modifies `state` in place (and also returns it)
24
+ *
25
+ * This algorithm is extracted from the hash.js package
26
+ * and modified to take in an initial state to operate on.
27
+ *
28
+ * @param state - The initial state to operate on (modified in-place). 8 u32s.
29
+ * @param inputs - The inputs to compress into the state. 16 u32s.
30
+ * @returns The modified state. 8 u32s.
31
+ */
32
+ export function sha256Compression(state: Uint32Array, inputs: Uint32Array): Uint32Array {
33
+ if (state.length !== 8) {
34
+ throw new Error('`state` argument to SHA256 compression must be of length 8');
35
+ }
36
+ if (inputs.length !== 16) {
37
+ throw new Error('`inputs` argument to SHA256 compression must be of length 16');
38
+ }
39
+
40
+ const W = new Array(64);
41
+ const k = [
42
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98,
43
+ 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
44
+ 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8,
45
+ 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
46
+ 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,
47
+ 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
48
+ 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
49
+ 0xc67178f2,
50
+ ];
51
+ let i = 0;
52
+ for (i = 0; i < 16; i++) {
53
+ W[i] = inputs[i];
54
+ }
55
+ for (i = 16; i < W.length; i++) {
56
+ W[i] = sum32_4(
57
+ W[i - 16],
58
+ W[i - 7],
59
+ g0_256(W[i - 15]), // Rot17, Rot18, Sh3
60
+ g1_256(W[i - 2]), //ROt17, Rot19, Sh10
61
+ );
62
+ }
63
+
64
+ let a = state[0];
65
+ let b = state[1];
66
+ let c = state[2];
67
+ let d = state[3];
68
+ let e = state[4];
69
+ let f = state[5];
70
+ let g = state[6];
71
+ let h = state[7];
72
+
73
+ for (let i = 0; i < 64; i++) {
74
+ const T1 = sum32_5(
75
+ h,
76
+ s1_256(e), // Rot6, Rot11, Rot25
77
+ ch32(e, f, g),
78
+ k[i],
79
+ W[i],
80
+ );
81
+
82
+ const T2 = sum32(
83
+ s0_256(a), // Rot2, Rot13, Rot22
84
+ maj32(a, b, c),
85
+ );
86
+ h = g;
87
+ g = f;
88
+ f = e;
89
+ e = sum32(d, T1);
90
+ d = c;
91
+ c = b;
92
+ b = a;
93
+ a = sum32(T1, T2);
94
+ }
95
+
96
+ state[0] = sum32(state[0], a);
97
+ state[1] = sum32(state[1], b);
98
+ state[2] = sum32(state[2], c);
99
+ state[3] = sum32(state[3], d);
100
+ state[4] = sum32(state[4], e);
101
+ state[5] = sum32(state[5], f);
102
+ state[6] = sum32(state[6], g);
103
+ state[7] = sum32(state[7], h);
104
+ return state;
105
+ }
106
+
107
+ // SHA256 HELPER FUNCTIONS (from hash.js package)
108
+
109
+ function rotr32(w: number, b: number) {
110
+ return (w >>> b) | (w << (32 - b));
111
+ }
112
+
113
+ function sum32(a: number, b: number) {
114
+ return (a + b) >>> 0;
115
+ }
116
+
117
+ function sum32_4(a: number, b: number, c: number, d: number) {
118
+ return (a + b + c + d) >>> 0;
119
+ }
120
+
121
+ function sum32_5(a: number, b: number, c: number, d: number, e: number) {
122
+ return (a + b + c + d + e) >>> 0;
123
+ }
124
+
125
+ function ch32(x: number, y: number, z: number) {
126
+ return (x & y) ^ (~x & z);
127
+ }
128
+
129
+ function maj32(x: number, y: number, z: number) {
130
+ return (x & y) ^ (x & z) ^ (y & z);
131
+ }
132
+
133
+ function s0_256(x: number) {
134
+ return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);
135
+ }
136
+
137
+ function s1_256(x: number) {
138
+ return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);
139
+ }
140
+
141
+ function g0_256(x: number) {
142
+ return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);
143
+ }
144
+
145
+ function g1_256(x: number) {
146
+ return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);
147
+ }
@@ -0,0 +1,90 @@
1
+ import { Buffer32 } from '@aztec/foundation/buffer';
2
+ import { BufferReader, serializeToBuffer } from '@aztec/foundation/serialize';
3
+
4
+ /**Viem Signature
5
+ *
6
+ * A version of the Signature class that uses `0x${string}` values for r and s rather than
7
+ * Buffer32s
8
+ */
9
+ export type ViemSignature = {
10
+ r: `0x${string}`;
11
+ s: `0x${string}`;
12
+ v: number;
13
+ isEmpty: boolean;
14
+ };
15
+
16
+ /**
17
+ * Signature
18
+ *
19
+ * Contains a signature split into it's primary components (r,s,v)
20
+ */
21
+ export class Signature {
22
+ constructor(
23
+ /** The r value of the signature */
24
+ public readonly r: Buffer32,
25
+ /** The s value of the signature */
26
+ public readonly s: Buffer32,
27
+ /** The v value of the signature */
28
+ public readonly v: number,
29
+ /** Does this struct store an empty signature */
30
+ public readonly isEmpty: boolean = false,
31
+ ) {}
32
+
33
+ static fromBuffer(buf: Buffer | BufferReader): Signature {
34
+ const reader = BufferReader.asReader(buf);
35
+
36
+ const r = reader.readObject(Buffer32);
37
+ const s = reader.readObject(Buffer32);
38
+ const v = reader.readNumber();
39
+
40
+ const isEmpty = r.isZero() && s.isZero();
41
+
42
+ return new Signature(r, s, v, isEmpty);
43
+ }
44
+
45
+ /**
46
+ * A seperate method exists for this as when signing locally with viem, as when
47
+ * parsing from viem, we can expect the v value to be a u8, rather than our
48
+ * default serialization of u32
49
+ */
50
+ static from0xString(sig: `0x${string}`): Signature {
51
+ const buf = Buffer.from(sig.slice(2), 'hex');
52
+ const reader = BufferReader.asReader(buf);
53
+
54
+ const r = reader.readObject(Buffer32);
55
+ const s = reader.readObject(Buffer32);
56
+ const v = reader.readUInt8();
57
+
58
+ const isEmpty = r.isZero() && s.isZero();
59
+
60
+ return new Signature(r, s, v, isEmpty);
61
+ }
62
+
63
+ static empty(): Signature {
64
+ return new Signature(Buffer32.ZERO, Buffer32.ZERO, 0, true);
65
+ }
66
+
67
+ equals(other: Signature): boolean {
68
+ return this.r.equals(other.r) && this.s.equals(other.s) && this.v === other.v && this.isEmpty === other.isEmpty;
69
+ }
70
+
71
+ toBuffer(): Buffer {
72
+ return serializeToBuffer([this.r, this.s, this.v]);
73
+ }
74
+
75
+ to0xString(): `0x${string}` {
76
+ return `0x${this.r.toString()}${this.s.toString()}${this.v.toString(16)}`;
77
+ }
78
+
79
+ /**
80
+ * Return the signature with `0x${string}` encodings for r and s
81
+ */
82
+ toViemSignature(): ViemSignature {
83
+ return {
84
+ r: this.r.to0xString(),
85
+ s: this.s.to0xString(),
86
+ v: this.v,
87
+ isEmpty: this.isEmpty,
88
+ };
89
+ }
90
+ }
@@ -0,0 +1 @@
1
+ export * from './eth_signature.js';
@@ -1,5 +1,6 @@
1
1
  import { toBigIntBE } from '../bigint-buffer/index.js';
2
- import { poseidon2Hash, randomBoolean } from '../crypto/index.js';
2
+ import { poseidon2Hash } from '../crypto/poseidon/index.js';
3
+ import { randomBoolean } from '../crypto/random/index.js';
3
4
  import { BufferReader, FieldReader, serializeToBuffer } from '../serialize/index.js';
4
5
  import { Fr } from './fields.js';
5
6