From 23f9873fb70c0a841fe0c96a9e3321e24d903a11 Mon Sep 17 00:00:00 2001 From: ludamad Date: Thu, 30 Nov 2023 01:19:01 +0000 Subject: [PATCH] Format --- .../src/barretenberg/common/ref_vector.hpp | 2 +- yarn-project/circuits.js/src/abis/index.ts | 1 - .../src/abis/merkle_tree_calculator.test.ts | 40 - .../src/abis/merkle_tree_calculator.ts | 57 -- .../abis/merkle_tree_root_calculator.test.ts | 31 - .../src/abis/merkle_tree_root_calculator.ts | 33 - .../circuits.js/src/barretenberg/README.txt | 1 - .../barretenberg/crypto/aes128/index.test.ts | 43 - .../src/barretenberg/crypto/aes128/index.ts | 48 - .../barretenberg/crypto/ecdsa/index.test.ts | 45 - .../src/barretenberg/crypto/ecdsa/index.ts | 77 -- .../crypto/ecdsa/signature.test.ts | 21 - .../barretenberg/crypto/ecdsa/signature.ts | 101 -- .../crypto/grumpkin/index.test.ts | 41 - .../src/barretenberg/crypto/grumpkin/index.ts | 89 -- .../src/barretenberg/crypto/index.ts | 6 - .../barretenberg/crypto/schnorr/index.test.ts | 40 - .../src/barretenberg/crypto/schnorr/index.ts | 59 -- .../barretenberg/crypto/schnorr/signature.ts | 116 --- .../crypto/secp256k1/index.test.ts | 21 - .../barretenberg/crypto/secp256k1/index.ts | 58 -- .../barretenberg/crypto/signature/index.ts | 17 - .../circuits.js/src/barretenberg/index.ts | 1 - .../circuits.js/src/barretenberg/serialize.ts | 74 -- .../src/contract/contract_deployment_info.ts | 54 - .../contract_tree/function_tree_data.test.ts | 50 - .../contract_tree/function_tree_data.ts | 28 - .../src/contract/contract_tree/index.ts | 2 - .../circuits.js/src/contract/index.ts | 2 - .../src/structs/aggregation_object.ts | 79 -- .../circuits.js/src/structs/call_context.ts | 133 --- .../circuits.js/src/structs/call_request.ts | 121 --- .../src/structs/call_stack_item.ts | 152 --- .../src/structs/complete_address.test.ts | 30 - .../src/structs/complete_address.ts | 127 --- .../circuits.js/src/structs/function_data.ts | 97 -- .../src/structs/function_leaf_preimage.ts | 58 -- .../src/structs/global_variables.ts | 73 -- .../kernel/combined_accumulated_data.test.ts | 18 - .../structs/kernel/combined_constant_data.ts | 39 - .../kernel/historic_block_data.test.ts | 17 - .../structs/kernel/previous_kernel_data.ts | 75 -- .../src/structs/public_call_request.ts | 124 --- .../read_request_membership_witness.test.ts | 11 - .../rollup/append_only_tree_snapshot.ts | 50 - .../src/structs/rollup/merge_rollup.ts | 18 - .../circuits.js/src/structs/shared.ts | 50 - .../circuits.js/src/structs/tx_request.ts | 65 -- .../src/structs/verification_key.test.ts | 10 - .../src/structs/verification_key.ts | 155 --- .../circuits.js/src/tests/factories.ts | 968 ------------------ .../src/types/contract_function_dao.ts | 15 - .../circuits.js/src/types/deployment_info.ts | 19 - .../src/types/grumpkin_private_key.ts | 4 - yarn-project/circuits.js/src/types/index.ts | 5 - .../circuits.js/src/types/partial_address.ts | 7 - .../circuits.js/src/types/public_key.ts | 4 - yarn-project/circuits.js/src/utils/index.ts | 2 - yarn-project/circuits.js/src/utils/jsUtils.ts | 86 -- 59 files changed, 1 insertion(+), 3769 deletions(-) delete mode 100644 yarn-project/circuits.js/src/abis/index.ts delete mode 100644 yarn-project/circuits.js/src/abis/merkle_tree_calculator.test.ts delete mode 100644 yarn-project/circuits.js/src/abis/merkle_tree_calculator.ts delete mode 100644 yarn-project/circuits.js/src/abis/merkle_tree_root_calculator.test.ts delete mode 100644 yarn-project/circuits.js/src/abis/merkle_tree_root_calculator.ts delete mode 100644 yarn-project/circuits.js/src/barretenberg/README.txt delete mode 100644 yarn-project/circuits.js/src/barretenberg/crypto/aes128/index.test.ts delete mode 100644 yarn-project/circuits.js/src/barretenberg/crypto/aes128/index.ts delete mode 100644 yarn-project/circuits.js/src/barretenberg/crypto/ecdsa/index.test.ts delete mode 100644 yarn-project/circuits.js/src/barretenberg/crypto/ecdsa/index.ts delete mode 100644 yarn-project/circuits.js/src/barretenberg/crypto/ecdsa/signature.test.ts delete mode 100644 yarn-project/circuits.js/src/barretenberg/crypto/ecdsa/signature.ts delete mode 100644 yarn-project/circuits.js/src/barretenberg/crypto/grumpkin/index.test.ts delete mode 100644 yarn-project/circuits.js/src/barretenberg/crypto/grumpkin/index.ts delete mode 100644 yarn-project/circuits.js/src/barretenberg/crypto/index.ts delete mode 100644 yarn-project/circuits.js/src/barretenberg/crypto/schnorr/index.test.ts delete mode 100644 yarn-project/circuits.js/src/barretenberg/crypto/schnorr/index.ts delete mode 100644 yarn-project/circuits.js/src/barretenberg/crypto/schnorr/signature.ts delete mode 100644 yarn-project/circuits.js/src/barretenberg/crypto/secp256k1/index.test.ts delete mode 100644 yarn-project/circuits.js/src/barretenberg/crypto/secp256k1/index.ts delete mode 100644 yarn-project/circuits.js/src/barretenberg/crypto/signature/index.ts delete mode 100644 yarn-project/circuits.js/src/barretenberg/index.ts delete mode 100644 yarn-project/circuits.js/src/barretenberg/serialize.ts delete mode 100644 yarn-project/circuits.js/src/contract/contract_deployment_info.ts delete mode 100644 yarn-project/circuits.js/src/contract/contract_tree/function_tree_data.test.ts delete mode 100644 yarn-project/circuits.js/src/contract/contract_tree/function_tree_data.ts delete mode 100644 yarn-project/circuits.js/src/contract/contract_tree/index.ts delete mode 100644 yarn-project/circuits.js/src/contract/index.ts delete mode 100644 yarn-project/circuits.js/src/structs/aggregation_object.ts delete mode 100644 yarn-project/circuits.js/src/structs/call_context.ts delete mode 100644 yarn-project/circuits.js/src/structs/call_request.ts delete mode 100644 yarn-project/circuits.js/src/structs/call_stack_item.ts delete mode 100644 yarn-project/circuits.js/src/structs/complete_address.test.ts delete mode 100644 yarn-project/circuits.js/src/structs/complete_address.ts delete mode 100644 yarn-project/circuits.js/src/structs/function_data.ts delete mode 100644 yarn-project/circuits.js/src/structs/function_leaf_preimage.ts delete mode 100644 yarn-project/circuits.js/src/structs/global_variables.ts delete mode 100644 yarn-project/circuits.js/src/structs/kernel/combined_accumulated_data.test.ts delete mode 100644 yarn-project/circuits.js/src/structs/kernel/combined_constant_data.ts delete mode 100644 yarn-project/circuits.js/src/structs/kernel/historic_block_data.test.ts delete mode 100644 yarn-project/circuits.js/src/structs/kernel/previous_kernel_data.ts delete mode 100644 yarn-project/circuits.js/src/structs/public_call_request.ts delete mode 100644 yarn-project/circuits.js/src/structs/read_request_membership_witness.test.ts delete mode 100644 yarn-project/circuits.js/src/structs/rollup/append_only_tree_snapshot.ts delete mode 100644 yarn-project/circuits.js/src/structs/rollup/merge_rollup.ts delete mode 100644 yarn-project/circuits.js/src/structs/shared.ts delete mode 100644 yarn-project/circuits.js/src/structs/tx_request.ts delete mode 100644 yarn-project/circuits.js/src/structs/verification_key.test.ts delete mode 100644 yarn-project/circuits.js/src/structs/verification_key.ts delete mode 100644 yarn-project/circuits.js/src/tests/factories.ts delete mode 100644 yarn-project/circuits.js/src/types/contract_function_dao.ts delete mode 100644 yarn-project/circuits.js/src/types/deployment_info.ts delete mode 100644 yarn-project/circuits.js/src/types/grumpkin_private_key.ts delete mode 100644 yarn-project/circuits.js/src/types/index.ts delete mode 100644 yarn-project/circuits.js/src/types/partial_address.ts delete mode 100644 yarn-project/circuits.js/src/types/public_key.ts delete mode 100644 yarn-project/circuits.js/src/utils/index.ts delete mode 100644 yarn-project/circuits.js/src/utils/jsUtils.ts diff --git a/barretenberg/cpp/src/barretenberg/common/ref_vector.hpp b/barretenberg/cpp/src/barretenberg/common/ref_vector.hpp index f5d09b4b3c15..fa47379ba833 100644 --- a/barretenberg/cpp/src/barretenberg/common/ref_vector.hpp +++ b/barretenberg/cpp/src/barretenberg/common/ref_vector.hpp @@ -14,7 +14,7 @@ * It offers random access to its elements and provides an iterator class for traversal. * * @tparam T The type of elements stored in the vector. - * @warning This should NOT be used for long-term storage, only for efficient passing. Any long-term sharing of values + * @warning This should NOT be used for long-term storage, only for efficient passing. Any long-term sharing of values * should use shared pointers. */ template class RefVector { diff --git a/yarn-project/circuits.js/src/abis/index.ts b/yarn-project/circuits.js/src/abis/index.ts deleted file mode 100644 index 9c432c09e534..000000000000 --- a/yarn-project/circuits.js/src/abis/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './abis.js'; diff --git a/yarn-project/circuits.js/src/abis/merkle_tree_calculator.test.ts b/yarn-project/circuits.js/src/abis/merkle_tree_calculator.test.ts deleted file mode 100644 index 1be2f815b506..000000000000 --- a/yarn-project/circuits.js/src/abis/merkle_tree_calculator.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { Fr } from '@aztec/foundation/fields'; - -import { MerkleTreeCalculator } from './merkle_tree_calculator.js'; - -describe('merkle tree root calculator', () => { - it('should correctly handle no leaves', () => { - // Height of 3 is 8 leaves. - const calculator = new MerkleTreeCalculator(4); - const expected = calculator.computeTreeRoot(new Array(8).fill(new Fr(0)).map(fr => fr.toBuffer())); - expect(calculator.computeTreeRoot()).toEqual(expected); - }); - - it('should correctly leverage zero hashes', () => { - const calculator = new MerkleTreeCalculator(4); - const leaves = Array.from({ length: 5 }).map((_, i) => new Fr(i).toBuffer()); - const padded = [...leaves, ...new Array(3).fill(Buffer.alloc(32))]; - const expected = calculator.computeTreeRoot(padded); - const result = calculator.computeTreeRoot(leaves); - expect(result).not.toBeUndefined(); - expect(result).toEqual(expected); - }); - - it('should correctly handle non default zero leaf', () => { - const zeroLeaf = new Fr(666).toBuffer(); - const calculator = new MerkleTreeCalculator(4, zeroLeaf); - const leaves = Array.from({ length: 5 }).map((_, i) => new Fr(i).toBuffer()); - const padded = [...leaves, ...new Array(3).fill(zeroLeaf)]; - const expected = calculator.computeTreeRoot(padded); - expect(calculator.computeTreeRoot(leaves)).toEqual(expected); - }); - - it('should compute entire tree', () => { - const calculator = new MerkleTreeCalculator(4); - const leaves = Array.from({ length: 5 }).map((_, i) => new Fr(i).toBuffer()); - const expectedRoot = calculator.computeTreeRoot(leaves); - const result = calculator.computeTree(leaves); - expect(result.length).toEqual(31); - expect(result[result.length - 1]).toEqual(expectedRoot); - }); -}); diff --git a/yarn-project/circuits.js/src/abis/merkle_tree_calculator.ts b/yarn-project/circuits.js/src/abis/merkle_tree_calculator.ts deleted file mode 100644 index a4de23b39116..000000000000 --- a/yarn-project/circuits.js/src/abis/merkle_tree_calculator.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { pedersenHash } from '@aztec/foundation/crypto'; - -/** - * Merkle tree calculator. - */ -export class MerkleTreeCalculator { - private zeroHashes: Buffer[]; - - constructor(private height: number, zeroLeaf = Buffer.alloc(32)) { - this.zeroHashes = Array.from({ length: height }).reduce( - (acc: Buffer[], _, i) => [...acc, pedersenHash([acc[i], acc[i]])], - [zeroLeaf], - ); - } - - computeTree(leaves: Buffer[] = []) { - if (leaves.length === 0) { - return [this.zeroHashes[this.zeroHashes.length - 1]]; - } - - let result = leaves.slice(); - - for (let i = 0; i < this.height; ++i) { - const numLeaves = 2 ** (this.height - i); - const newLeaves: Buffer[] = []; - for (let j = 0; j < leaves.length / 2; ++j) { - const l = leaves[j * 2]; - const r = leaves[j * 2 + 1] || this.zeroHashes[i]; - newLeaves[j] = pedersenHash([l, r]); - } - result = result.concat(new Array(numLeaves - leaves.length).fill(this.zeroHashes[i]), newLeaves); - leaves = newLeaves; - } - - return result; - } - - computeTreeRoot(leaves: Buffer[] = []) { - if (leaves.length === 0) { - return this.zeroHashes[this.zeroHashes.length - 1]; - } - - leaves = leaves.slice(); - - for (let i = 0; i < this.height; ++i) { - let j = 0; - for (; j < leaves.length / 2; ++j) { - const l = leaves[j * 2]; - const r = leaves[j * 2 + 1] || this.zeroHashes[i]; - leaves[j] = pedersenHash([l, r]); - } - leaves = leaves.slice(0, j); - } - - return leaves[0]; - } -} diff --git a/yarn-project/circuits.js/src/abis/merkle_tree_root_calculator.test.ts b/yarn-project/circuits.js/src/abis/merkle_tree_root_calculator.test.ts deleted file mode 100644 index 589667289494..000000000000 --- a/yarn-project/circuits.js/src/abis/merkle_tree_root_calculator.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { Fr } from '@aztec/foundation/fields'; - -import { MerkleTreeRootCalculator } from './merkle_tree_root_calculator.js'; - -describe('merkle tree root calculator', () => { - it('should correctly handle no leaves', () => { - // Height of 3 is 8 leaves. - const calculator = new MerkleTreeRootCalculator(4); - const expected = calculator.computeTreeRoot(new Array(8).fill(new Fr(0)).map(fr => fr.toBuffer())); - expect(calculator.computeTreeRoot()).toEqual(expected); - }); - - it('should correctly leverage zero hashes', () => { - const calculator = new MerkleTreeRootCalculator(4); - const leaves = Array.from({ length: 5 }).map((_, i) => new Fr(i).toBuffer()); - const padded = [...leaves, ...new Array(3).fill(Buffer.alloc(32))]; - const expected = calculator.computeTreeRoot(padded); - const result = calculator.computeTreeRoot(leaves); - expect(result).not.toBeUndefined(); - expect(result).toEqual(expected); - }); - - it('should correctly handle non default zero leaf', () => { - const zeroLeaf = new Fr(666).toBuffer(); - const calculator = new MerkleTreeRootCalculator(4, zeroLeaf); - const leaves = Array.from({ length: 5 }).map((_, i) => new Fr(i).toBuffer()); - const padded = [...leaves, ...new Array(3).fill(zeroLeaf)]; - const expected = calculator.computeTreeRoot(padded); - expect(calculator.computeTreeRoot(leaves)).toEqual(expected); - }); -}); diff --git a/yarn-project/circuits.js/src/abis/merkle_tree_root_calculator.ts b/yarn-project/circuits.js/src/abis/merkle_tree_root_calculator.ts deleted file mode 100644 index 904eec357763..000000000000 --- a/yarn-project/circuits.js/src/abis/merkle_tree_root_calculator.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { pedersenHash } from '@aztec/foundation/crypto'; - -/** - * Calculates the root of a merkle tree. - */ -export class MerkleTreeRootCalculator { - private zeroHashes: Buffer[]; - - constructor(private height: number, zeroLeaf = Buffer.alloc(32)) { - this.zeroHashes = Array.from({ length: height }).reduce( - (acc: Buffer[], _, i) => [...acc, pedersenHash([acc[i], acc[i]])], - [zeroLeaf], - ); - } - - computeTreeRoot(leaves: Buffer[] = []) { - if (leaves.length === 0) { - return this.zeroHashes[this.zeroHashes.length - 1]; - } - - for (let i = 0; i < this.height; ++i) { - let j = 0; - for (; j < leaves.length / 2; ++j) { - const l = leaves[j * 2]; - const r = leaves[j * 2 + 1] || this.zeroHashes[i]; - leaves[j] = pedersenHash([l, r]); - } - leaves = leaves.slice(0, j); - } - - return leaves[0]; - } -} diff --git a/yarn-project/circuits.js/src/barretenberg/README.txt b/yarn-project/circuits.js/src/barretenberg/README.txt deleted file mode 100644 index e85c0ca52c03..000000000000 --- a/yarn-project/circuits.js/src/barretenberg/README.txt +++ /dev/null @@ -1 +0,0 @@ -Temporary folder - see https://github.com/AztecProtocol/aztec-packages/issues/782 diff --git a/yarn-project/circuits.js/src/barretenberg/crypto/aes128/index.test.ts b/yarn-project/circuits.js/src/barretenberg/crypto/aes128/index.test.ts deleted file mode 100644 index 9b8afc328e2c..000000000000 --- a/yarn-project/circuits.js/src/barretenberg/crypto/aes128/index.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { createCipheriv, createDecipheriv, randomBytes } from 'crypto'; - -import { Aes128 } from './index.js'; - -describe('aes128', () => { - let aes128!: Aes128; - - beforeAll(() => { - aes128 = new Aes128(); - }); - - it('should correctly encrypt input', () => { - const data = randomBytes(32); - const key = randomBytes(16); - const iv = randomBytes(16); - - const cipher = createCipheriv('aes-128-cbc', key, iv); - cipher.setAutoPadding(false); - const expected = Buffer.concat([cipher.update(data), cipher.final()]); - - const result: Buffer = aes128.encryptBufferCBC(data, iv, key); - - expect(result).toEqual(expected); - }); - - it('should correctly decrypt input', () => { - const data = randomBytes(32); - const key = randomBytes(16); - const iv = randomBytes(16); - - const cipher = createCipheriv('aes-128-cbc', key, iv); - cipher.setAutoPadding(false); - const ciphertext = Buffer.concat([cipher.update(data), cipher.final()]); - - const decipher = createDecipheriv('aes-128-cbc', key, iv); - decipher.setAutoPadding(false); - const expected = Buffer.concat([decipher.update(ciphertext), decipher.final()]); - - const result: Buffer = aes128.decryptBufferCBC(ciphertext, iv, key); - - expect(result).toEqual(expected); - }); -}); diff --git a/yarn-project/circuits.js/src/barretenberg/crypto/aes128/index.ts b/yarn-project/circuits.js/src/barretenberg/crypto/aes128/index.ts deleted file mode 100644 index 20e0e133b9c7..000000000000 --- a/yarn-project/circuits.js/src/barretenberg/crypto/aes128/index.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { BarretenbergSync, RawBuffer } from '@aztec/bb.js'; - -import { Buffer } from 'buffer'; - -// Get the singleton. This constructs (if not already) the barretenberg sync api within bb.js itself. -// This can be called from multiple other modules as needed, and it ensures it's only constructed once. -const api = await BarretenbergSync.getSingleton(); - -/** - * AES-128-CBC encryption/decryption. - */ -export class Aes128 { - /** - * Encrypt a buffer using AES-128-CBC. - * @param data - Data to encrypt. - * @param iv - AES initialization vector. - * @param key - Key to encrypt with. - * @returns Encrypted data. - */ - public encryptBufferCBC(data: Uint8Array, iv: Uint8Array, key: Uint8Array) { - const rawLength = data.length; - const numPaddingBytes = rawLength % 16 != 0 ? 16 - (rawLength % 16) : 0; - const paddingBuffer = Buffer.alloc(numPaddingBytes); - // input num bytes needs to be a multiple of 16 - // node uses PKCS#7-Padding scheme, where padding byte value = the number of padding bytes - if (numPaddingBytes != 0) { - paddingBuffer.fill(numPaddingBytes); - } - const input = Buffer.concat([data, paddingBuffer]); - - return Buffer.from( - api.aesEncryptBufferCbc(new RawBuffer(input), new RawBuffer(iv), new RawBuffer(key), input.length), - ); - } - - /** - * Decrypt a buffer using AES-128-CBC. - * @param data - Data to decrypt. - * @param iv - AES initialization vector. - * @param key - Key to decrypt with. - * @returns Decrypted data. - */ - public decryptBufferCBC(data: Uint8Array, iv: Uint8Array, key: Uint8Array) { - return Buffer.from( - api.aesDecryptBufferCbc(new RawBuffer(data), new RawBuffer(iv), new RawBuffer(key), data.length), - ); - } -} diff --git a/yarn-project/circuits.js/src/barretenberg/crypto/ecdsa/index.test.ts b/yarn-project/circuits.js/src/barretenberg/crypto/ecdsa/index.test.ts deleted file mode 100644 index 57a61da31248..000000000000 --- a/yarn-project/circuits.js/src/barretenberg/crypto/ecdsa/index.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { TextEncoder } from 'util'; - -import { Ecdsa } from './index.js'; - -describe('ecdsa', () => { - let ecdsa!: Ecdsa; - - beforeAll(() => { - ecdsa = new Ecdsa(); - }); - - it('should verify signature', () => { - // prettier-ignore - const privateKey = Buffer.from([ - 0x0b, 0x9b, 0x3a, 0xde, 0xe6, 0xb3, 0xd8, 0x1b, 0x28, 0xa0, 0x88, 0x6b, 0x2a, 0x84, 0x15, 0xc7, - 0xda, 0x31, 0x29, 0x1a, 0x5e, 0x96, 0xbb, 0x7a, 0x56, 0x63, 0x9e, 0x17, 0x7d, 0x30, 0x1b, 0xeb, - ]); - const pubKey = ecdsa.computePublicKey(privateKey); - const msg = new TextEncoder().encode('The quick brown dog jumped over the lazy fox.'); - const signature = ecdsa.constructSignature(msg, privateKey); - const verified = ecdsa.verifySignature(msg, pubKey, signature); - - expect(verified).toBe(true); - }); - - it('should recover public key from signature', () => { - // prettier-ignore - const privateKey = Buffer.from([ - 0x0b, 0x9b, 0x3a, 0xde, 0xe6, 0xb3, 0xd8, 0x1b, 0x28, 0xa0, 0x88, 0x6b, 0x2a, 0x84, 0x15, 0xc7, - 0xda, 0x31, 0x29, 0x1a, 0x5e, 0x96, 0xbb, 0x7a, 0x56, 0x63, 0x9e, 0x17, 0x7d, 0x30, 0x1b, 0xeb, - ]); - const pubKey = ecdsa.computePublicKey(privateKey); - const msg = new TextEncoder().encode('The quick brown dog jumped over the lazy fox...'); - const signature = ecdsa.constructSignature(msg, privateKey); - - // First, recover the public key - const recoveredPubKey = ecdsa.recoverPublicKey(msg, signature); - - // Then, verify the signature using the recovered public key - const verified = ecdsa.verifySignature(msg, recoveredPubKey, signature); - - expect(recoveredPubKey).toEqual(pubKey); - expect(verified).toBe(true); - }); -}); diff --git a/yarn-project/circuits.js/src/barretenberg/crypto/ecdsa/index.ts b/yarn-project/circuits.js/src/barretenberg/crypto/ecdsa/index.ts deleted file mode 100644 index e52933eccf40..000000000000 --- a/yarn-project/circuits.js/src/barretenberg/crypto/ecdsa/index.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { BarretenbergSync } from '@aztec/bb.js'; - -import { EcdsaSignature } from './signature.js'; - -export * from './signature.js'; - -const api = await BarretenbergSync.getSingleton(); -const wasm = api.getWasm(); - -/** - * ECDSA signature construction and helper operations. - */ -export class Ecdsa { - /** - * Computes a secp256k1 public key from a private key. - * @param privateKey - Secp256k1 private key. - * @returns A secp256k1 public key. - */ - public computePublicKey(privateKey: Buffer): Buffer { - wasm.writeMemory(0, privateKey); - wasm.call('ecdsa__compute_public_key', 0, 32); - return Buffer.from(wasm.getMemorySlice(32, 96)); - } - - /** - * Constructs an ECDSA signature given a msg and a private key. - * @param msg - Message over which the signature is constructed. - * @param privateKey - The secp256k1 private key of the signer. - * @returns An ECDSA signature of the form (r, s, v). - */ - public constructSignature(msg: Uint8Array, privateKey: Buffer) { - const mem = wasm.call('bbmalloc', msg.length); - wasm.writeMemory(0, privateKey); - wasm.writeMemory(mem, msg); - wasm.call('ecdsa__construct_signature', mem, msg.length, 0, 32, 64, 96); - - return new EcdsaSignature( - Buffer.from(wasm.getMemorySlice(32, 64)), - Buffer.from(wasm.getMemorySlice(64, 96)), - Buffer.from(wasm.getMemorySlice(96, 97)), - ); - } - - /** - * Recovers a secp256k1 public key from an ECDSA signature (similar to ecrecover). - * @param msg - Message over which the signature was constructed. - * @param sig - The ECDSA signature. - * @returns The secp256k1 public key of the signer. - */ - public recoverPublicKey(msg: Uint8Array, sig: EcdsaSignature): Buffer { - const mem = wasm.call('bbmalloc', msg.length); - wasm.writeMemory(0, sig.r); - wasm.writeMemory(32, sig.s); - wasm.writeMemory(64, sig.v); - wasm.writeMemory(mem, msg); - wasm.call('ecdsa__recover_public_key_from_signature', mem, msg.length, 0, 32, 64, 65); - - return Buffer.from(wasm.getMemorySlice(65, 129)); - } - - /** - * Verifies and ECDSA signature given a secp256k1 public key. - * @param msg - Message over which the signature was constructed. - * @param pubKey - The secp256k1 public key of the signer. - * @param sig - The ECDSA signature. - * @returns True or false. - */ - public verifySignature(msg: Uint8Array, pubKey: Buffer, sig: EcdsaSignature) { - const mem = wasm.call('bbmalloc', msg.length); - wasm.writeMemory(0, pubKey); - wasm.writeMemory(64, sig.r); - wasm.writeMemory(96, sig.s); - wasm.writeMemory(128, sig.v); - wasm.writeMemory(mem, msg); - return wasm.call('ecdsa__verify_signature', mem, msg.length, 0, 64, 96, 128) ? true : false; - } -} diff --git a/yarn-project/circuits.js/src/barretenberg/crypto/ecdsa/signature.test.ts b/yarn-project/circuits.js/src/barretenberg/crypto/ecdsa/signature.test.ts deleted file mode 100644 index 1bbc4f573166..000000000000 --- a/yarn-project/circuits.js/src/barretenberg/crypto/ecdsa/signature.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { EcdsaSignature } from './signature.js'; - -describe('ecdsa_signature', () => { - it('serializes signature with v to fields', () => { - const signature = EcdsaSignature.random(); - const asFields = signature.toFields(true); - const parts = asFields.map(fr => fr.toBuffer().subarray(1)); - const reassembled = EcdsaSignature.fromBuffer(Buffer.concat(parts)); - expect(reassembled).toEqual(signature); - }); - - it('serializes signature without v to fields', () => { - const signature = EcdsaSignature.random(); - const asFields = signature.toFields(false); - const parts = asFields.map(fr => fr.toBuffer().subarray(1)); - const reassembled = EcdsaSignature.fromBuffer(Buffer.concat(parts)); - expect(reassembled.r).toEqual(signature.r); - expect(reassembled.s).toEqual(signature.s); - expect(reassembled.v).toEqual(Buffer.alloc(1)); - }); -}); diff --git a/yarn-project/circuits.js/src/barretenberg/crypto/ecdsa/signature.ts b/yarn-project/circuits.js/src/barretenberg/crypto/ecdsa/signature.ts deleted file mode 100644 index 5a18f988c400..000000000000 --- a/yarn-project/circuits.js/src/barretenberg/crypto/ecdsa/signature.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { toBufferBE } from '@aztec/foundation/bigint-buffer'; -import { Fr } from '@aztec/foundation/fields'; -import { mapTuple } from '@aztec/foundation/serialize'; - -import { randomBytes } from 'crypto'; - -import { Signature } from '../index.js'; - -/** - * ECDSA signature used for transactions. - * @see cpp/barretenberg/cpp/src/barretenberg/crypto/ecdsa/ecdsa.hpp - */ -export class EcdsaSignature implements Signature { - constructor( - /** - * The r byte-array (32 bytes) in an ECDSA signature. - */ - public r: Buffer, - /** - * The s byte-array (32 bytes) in an ECDSA signature. - */ - public s: Buffer, - /** - * The recovery id (1 byte) in an ECDSA signature. - */ - public v: Buffer, - ) { - if (r.length != 32) { - throw new Error(`Invalid length of 'r' in ECDSA signature`); - } - if (s.length != 32) { - throw new Error(`Invalid length of 's' in ECDSA signature`); - } - if (v.length != 1) { - throw new Error(`Invalid length of '1' in ECDSA signature`); - } - } - - /** - * Converts an ECDSA signature to a buffer. - * @returns A buffer. - */ - toBuffer() { - return Buffer.concat([this.r, this.s, this.v]); - } - - /** - * Deserializes the signature from a buffer. - * @param buffer - The buffer from which to deserialize the signature. - * @returns The ECDSA signature - */ - public static fromBuffer(buffer: Buffer) { - return new EcdsaSignature(buffer.subarray(0, 32), buffer.subarray(32, 64), buffer.subarray(64, 65)); - } - - /** - * Creates a new instance from bigint r and s values. - * @param r - r. - * @param s - s. - * @param v - v. - * @returns The resulting signature. - */ - public static fromBigInts(r: bigint, s: bigint, v: number) { - return new EcdsaSignature(toBufferBE(r, 32), toBufferBE(s, 32), Buffer.from([v])); - } - - /** - * Generate a random ECDSA signature for testing. - * @returns A randomly generated ECDSA signature (not a valid one). - */ - public static random() { - return new EcdsaSignature(randomBytes(32), randomBytes(32), Buffer.from([27])); - } - - /** - * Convert an ECDSA signature to a buffer. - * @returns A 65-character string of the form 0x. - */ - toString() { - return `0x${this.toBuffer().toString('hex')}`; - } - - /** - * Converts the signature to an array of fields. - * @param includeV - Determines whether the 'v' term is included - * @returns The signature components as an array of fields - */ - toFields(includeV = false): Fr[] { - const sig = this.toBuffer(); - - const buf1 = Buffer.alloc(32); - const buf2 = Buffer.alloc(32); - const buf3 = Buffer.alloc(32); - - sig.copy(buf1, 1, 0, 31); - sig.copy(buf2, 1, 31, 62); - sig.copy(buf3, 1, 62, includeV ? 65 : 64); - - return mapTuple([buf1, buf2, buf3], Fr.fromBuffer); - } -} diff --git a/yarn-project/circuits.js/src/barretenberg/crypto/grumpkin/index.test.ts b/yarn-project/circuits.js/src/barretenberg/crypto/grumpkin/index.test.ts deleted file mode 100644 index 154ab39075fb..000000000000 --- a/yarn-project/circuits.js/src/barretenberg/crypto/grumpkin/index.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { createDebugLogger } from '@aztec/foundation/log'; - -import { GrumpkinScalar, Point } from '../../../index.js'; -import { Grumpkin } from './index.js'; - -const debug = createDebugLogger('bb:grumpkin_test'); - -describe('grumpkin', () => { - let grumpkin!: Grumpkin; - - beforeAll(() => { - grumpkin = new Grumpkin(); - }); - - it('should correctly perform scalar muls', () => { - const exponent = GrumpkinScalar.random(); - - const numPoints = 2048; - - const inputPoints: Point[] = []; - for (let i = 0; i < numPoints; ++i) { - inputPoints.push(grumpkin.mul(Grumpkin.generator, GrumpkinScalar.random())); - } - - const start = new Date().getTime(); - const outputPoints = grumpkin.batchMul(inputPoints, exponent); - debug(`batch mul in: ${new Date().getTime() - start}ms`); - - const start2 = new Date().getTime(); - for (let i = 0; i < numPoints; ++i) { - grumpkin.mul(inputPoints[i], exponent); - } - debug(`regular mul in: ${new Date().getTime() - start2}ms`); - - for (let i = 0; i < numPoints; ++i) { - const lhs = outputPoints[i]; - const rhs = grumpkin.mul(inputPoints[i], exponent); - expect(lhs).toEqual(rhs); - } - }); -}); diff --git a/yarn-project/circuits.js/src/barretenberg/crypto/grumpkin/index.ts b/yarn-project/circuits.js/src/barretenberg/crypto/grumpkin/index.ts deleted file mode 100644 index a41c0af1fa06..000000000000 --- a/yarn-project/circuits.js/src/barretenberg/crypto/grumpkin/index.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { BarretenbergSync } from '@aztec/bb.js'; -import { Fr, Point } from '@aztec/foundation/fields'; - -import { GrumpkinScalar } from '../../../index.js'; - -const api = await BarretenbergSync.getSingleton(); -const wasm = api.getWasm(); - -/** - * Grumpkin elliptic curve operations. - */ -export class Grumpkin { - // prettier-ignore - static generator = Point.fromBuffer(Buffer.from([ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xcf, 0x13, 0x5e, 0x75, 0x06, 0xa4, 0x5d, 0x63, - 0x2d, 0x27, 0x0d, 0x45, 0xf1, 0x18, 0x12, 0x94, 0x83, 0x3f, 0xc4, 0x8d, 0x82, 0x3f, 0x27, 0x2c, - ])); - - /** - * Point generator - * @returns The generator for the curve. - */ - public generator(): Point { - return Grumpkin.generator; - } - - /** - * Multiplies a point by a scalar (adds the point `scalar` amount of times). - * @param point - Point to multiply. - * @param scalar - Scalar to multiply by. - * @returns Result of the multiplication. - */ - public mul(point: Point, scalar: GrumpkinScalar): Point { - wasm.writeMemory(0, point.toBuffer()); - wasm.writeMemory(64, scalar.toBuffer()); - wasm.call('ecc_grumpkin__mul', 0, 64, 96); - return Point.fromBuffer(Buffer.from(wasm.getMemorySlice(96, 160))); - } - - /** - * Multiplies a set of points by a scalar. - * @param points - Points to multiply. - * @param scalar - Scalar to multiply by. - * @returns Points multiplied by the scalar. - */ - public batchMul(points: Point[], scalar: GrumpkinScalar) { - const concatenatedPoints: Buffer = Buffer.concat(points.map(point => point.toBuffer())); - const pointsByteLength = points.length * Point.SIZE_IN_BYTES; - - const mem = wasm.call('bbmalloc', pointsByteLength * 2); - - wasm.writeMemory(mem, concatenatedPoints); - wasm.writeMemory(0, scalar.toBuffer()); - wasm.call('ecc_grumpkin__batch_mul', mem, 0, points.length, mem + pointsByteLength); - - const result: Buffer = Buffer.from( - wasm.getMemorySlice(mem + pointsByteLength, mem + pointsByteLength + pointsByteLength), - ); - wasm.call('bbfree', mem); - - const parsedResult: Point[] = []; - for (let i = 0; i < pointsByteLength; i += 64) { - parsedResult.push(Point.fromBuffer(result.slice(i, i + 64))); - } - return parsedResult; - } - - /** - * Gets a random field element. - * @returns Random field element. - */ - public getRandomFr(): Fr { - wasm.call('ecc_grumpkin__get_random_scalar_mod_circuit_modulus', 0); - return Fr.fromBuffer(Buffer.from(wasm.getMemorySlice(0, 32))); - } - - /** - * Converts a 512 bits long buffer to a field. - * @param uint512Buf - The buffer to convert. - * @returns Buffer representation of the field element. - */ - public reduce512BufferToFr(uint512Buf: Buffer): Fr { - wasm.writeMemory(0, uint512Buf); - wasm.call('ecc_grumpkin__reduce512_buffer_mod_circuit_modulus', 0, 64); - return Fr.fromBuffer(Buffer.from(wasm.getMemorySlice(64, 96))); - } -} diff --git a/yarn-project/circuits.js/src/barretenberg/crypto/index.ts b/yarn-project/circuits.js/src/barretenberg/crypto/index.ts deleted file mode 100644 index e9c594c032d0..000000000000 --- a/yarn-project/circuits.js/src/barretenberg/crypto/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -export * from './aes128/index.js'; -export * from './grumpkin/index.js'; -export * from './ecdsa/index.js'; -export * from './secp256k1/index.js'; -export * from './schnorr/index.js'; -export * from './signature/index.js'; diff --git a/yarn-project/circuits.js/src/barretenberg/crypto/schnorr/index.test.ts b/yarn-project/circuits.js/src/barretenberg/crypto/schnorr/index.test.ts deleted file mode 100644 index db2e2101e6e6..000000000000 --- a/yarn-project/circuits.js/src/barretenberg/crypto/schnorr/index.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { TextEncoder } from 'util'; - -import { GrumpkinScalar } from '../../../index.js'; -import { Schnorr } from './index.js'; - -describe('schnorr', () => { - let schnorr!: Schnorr; - - beforeAll(() => { - schnorr = new Schnorr(); - }); - - it('should verify signature', () => { - // prettier-ignore - const privateKey = GrumpkinScalar.fromBuffer(Buffer.from([ - 0x0b, 0x9b, 0x3a, 0xde, 0xe6, 0xb3, 0xd8, 0x1b, 0x28, 0xa0, 0x88, 0x6b, 0x2a, 0x84, 0x15, 0xc7, - 0xda, 0x31, 0x29, 0x1a, 0x5e, 0x96, 0xbb, 0x7a, 0x56, 0x63, 0x9e, 0x17, 0x7d, 0x30, 0x1b, 0xeb, - ])); - const pubKey = schnorr.computePublicKey(privateKey); - const msg = new TextEncoder().encode('The quick brown dog jumped over the lazy fox.'); - const signature = schnorr.constructSignature(msg, privateKey); - const verified = schnorr.verifySignature(msg, pubKey, signature); - - expect(verified).toBe(true); - }); - - it('should fail invalid signature', () => { - // prettier-ignore - const privateKey = GrumpkinScalar.fromBuffer(Buffer.from([ - 0x0b, 0x9b, 0x3a, 0xde, 0xe6, 0xb3, 0xd8, 0x1b, 0x28, 0xa0, 0x88, 0x6b, 0x2a, 0x84, 0x15, 0xc7, - 0xda, 0x31, 0x29, 0x1a, 0x5e, 0x96, 0xbb, 0x7a, 0x56, 0x63, 0x9e, 0x17, 0x7d, 0x30, 0x1b, 0xeb, - ])); - const pubKey = schnorr.computePublicKey(privateKey); - const msg = new TextEncoder().encode('The quick brown dog jumped over the lazy fox.'); - const signature = schnorr.constructSignature(msg, GrumpkinScalar.random()); - const verified = schnorr.verifySignature(msg, pubKey, signature); - - expect(verified).toBe(false); - }); -}); diff --git a/yarn-project/circuits.js/src/barretenberg/crypto/schnorr/index.ts b/yarn-project/circuits.js/src/barretenberg/crypto/schnorr/index.ts deleted file mode 100644 index 4ab41700e7d2..000000000000 --- a/yarn-project/circuits.js/src/barretenberg/crypto/schnorr/index.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { BarretenbergSync } from '@aztec/bb.js'; -import { numToUInt32BE } from '@aztec/foundation/serialize'; - -import { GrumpkinPrivateKey, Point, PublicKey } from '../../../index.js'; -import { SchnorrSignature } from './signature.js'; - -export * from './signature.js'; - -const api = await BarretenbergSync.getSingleton(); -const wasm = api.getWasm(); - -/** - * Schnorr signature construction and helper operations. - */ -export class Schnorr { - /** - * Computes a grumpkin public key from a private key. - * @param privateKey - The private key. - * @returns A grumpkin public key. - */ - public computePublicKey(privateKey: GrumpkinPrivateKey): PublicKey { - wasm.writeMemory(0, privateKey.toBuffer()); - wasm.call('schnorr_compute_public_key', 0, 32); - return Point.fromBuffer(Buffer.from(wasm.getMemorySlice(32, 96))); - } - - /** - * Constructs a Schnorr signature given a msg and a private key. - * @param msg - Message over which the signature is constructed. - * @param privateKey - The private key of the signer. - * @returns A Schnorr signature of the form (s, e). - */ - public constructSignature(msg: Uint8Array, privateKey: GrumpkinPrivateKey) { - const mem = wasm.call('bbmalloc', msg.length + 4); - wasm.writeMemory(0, privateKey.toBuffer()); - wasm.writeMemory(mem, Buffer.concat([numToUInt32BE(msg.length), msg])); - wasm.call('schnorr_construct_signature', mem, 0, 32, 64); - - return new SchnorrSignature(Buffer.from(wasm.getMemorySlice(32, 96))); - } - - /** - * Verifies a Schnorr signature given a Grumpkin public key. - * @param msg - Message over which the signature was constructed. - * @param pubKey - The Grumpkin public key of the signer. - * @param sig - The Schnorr signature. - * @returns True or false. - */ - public verifySignature(msg: Uint8Array, pubKey: PublicKey, sig: SchnorrSignature) { - const mem = wasm.call('bbmalloc', msg.length + 4); - wasm.writeMemory(0, pubKey.toBuffer()); - wasm.writeMemory(64, sig.s); - wasm.writeMemory(96, sig.e); - wasm.writeMemory(mem, Buffer.concat([numToUInt32BE(msg.length), msg])); - wasm.call('schnorr_verify_signature', mem, 0, 64, 96, 128); - const result = wasm.getMemorySlice(128, 129); - return !Buffer.alloc(1, 0).equals(result); - } -} diff --git a/yarn-project/circuits.js/src/barretenberg/crypto/schnorr/signature.ts b/yarn-project/circuits.js/src/barretenberg/crypto/schnorr/signature.ts deleted file mode 100644 index c753a8470516..000000000000 --- a/yarn-project/circuits.js/src/barretenberg/crypto/schnorr/signature.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { randomBytes } from '@aztec/foundation/crypto'; -import { Fr } from '@aztec/foundation/fields'; -import { BufferReader, mapTuple } from '@aztec/foundation/serialize'; - -import { Signature } from '../index.js'; - -/** - * Schnorr signature used for transactions. - * @see cpp/barretenberg/cpp/src/barretenberg/crypto/schnorr/schnorr.hpp - */ -export class SchnorrSignature implements Signature { - /** - * The size of the signature in bytes. - */ - public static SIZE = 64; - - /** - * An empty signature. - */ - public static EMPTY = new SchnorrSignature(Buffer.alloc(64)); - - constructor(private buffer: Buffer) { - if (buffer.length !== SchnorrSignature.SIZE) { - throw new Error(`Invalid signature buffer of length ${buffer.length}.`); - } - } - - /** - * Determines if the provided signature is valid or not. - * @param signature - The data to be checked. - * @returns Boolean indicating if the provided data is a valid schnorr signature. - */ - public static isSignature(signature: string) { - return /^(0x)?[0-9a-f]{128}$/i.test(signature); - } - - /** - * Constructs a SchnorrSignature from the provided string. - * @param signature - The string to be converted to a schnorr signature. - * @returns The constructed schnorr signature. - */ - public static fromString(signature: string) { - if (!SchnorrSignature.isSignature(signature)) { - throw new Error(`Invalid signature string: ${signature}`); - } - return new SchnorrSignature(Buffer.from(signature.replace(/^0x/i, ''), 'hex')); - } - - /** - * Generates a random schnorr signature. - * @returns The randomly constructed signature. - */ - public static random() { - return new SchnorrSignature(randomBytes(64)); - } - - /** - * Returns the 's' component of the signature. - * @returns A buffer containing the signature's 's' component. - */ - get s() { - return this.buffer.subarray(0, 32); - } - - /** - * Returns the 'e' component of the signature. - * @returns A buffer containing the signature's 'e' component. - */ - get e() { - return this.buffer.subarray(32); - } - - /** - * Returns the full signature as a buffer. - * @returns A buffer containing the signature. - */ - toBuffer() { - return this.buffer; - } - - /** - * Deserializes from a buffer. - * @param buffer - The buffer representation of the object. - * @returns The new object. - */ - static fromBuffer(buffer: Buffer | BufferReader): SchnorrSignature { - const reader = BufferReader.asReader(buffer); - return new SchnorrSignature(reader.readBytes(SchnorrSignature.SIZE)); - } - - /** - * Returns the full signature as a hex string. - * @returns A string containing the signature in hex format. - */ - toString() { - return `0x${this.buffer.toString('hex')}`; - } - - /** - * Converts the signature to an array of three fields. - * @returns The signature components as an array of three fields - */ - toFields(): Fr[] { - const sig = this.toBuffer(); - - const buf1 = Buffer.alloc(32); - const buf2 = Buffer.alloc(32); - const buf3 = Buffer.alloc(32); - - sig.copy(buf1, 1, 0, 31); - sig.copy(buf2, 1, 31, 62); - sig.copy(buf3, 1, 62, 64); - - return mapTuple([buf1, buf2, buf3], Fr.fromBuffer); - } -} diff --git a/yarn-project/circuits.js/src/barretenberg/crypto/secp256k1/index.test.ts b/yarn-project/circuits.js/src/barretenberg/crypto/secp256k1/index.test.ts deleted file mode 100644 index 9da5a3623230..000000000000 --- a/yarn-project/circuits.js/src/barretenberg/crypto/secp256k1/index.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { randomBytes } from '@aztec/foundation/crypto'; - -import { Ecdsa } from '../ecdsa/index.js'; -import { Secp256k1 } from './index.js'; - -describe('secp256k1', () => { - let secp256k1!: Secp256k1; - let ecdsa!: Ecdsa; - - beforeAll(() => { - secp256k1 = new Secp256k1(); - ecdsa = new Ecdsa(); - }); - - it('should correctly compute public key', () => { - const privateKey = randomBytes(32); - const lhs = secp256k1.mul(Secp256k1.generator, privateKey); - const rhs = ecdsa.computePublicKey(privateKey); - expect(lhs).toEqual(rhs); - }); -}); diff --git a/yarn-project/circuits.js/src/barretenberg/crypto/secp256k1/index.ts b/yarn-project/circuits.js/src/barretenberg/crypto/secp256k1/index.ts deleted file mode 100644 index a388ce602fb7..000000000000 --- a/yarn-project/circuits.js/src/barretenberg/crypto/secp256k1/index.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { BarretenbergSync } from '@aztec/bb.js'; - -const api = await BarretenbergSync.getSingleton(); -const wasm = api.getWasm(); - -/** - * Secp256k1 elliptic curve operations. - */ -export class Secp256k1 { - // prettier-ignore - static generator = Buffer.from([ - 0x79, 0xbe, 0x66, 0x7e, 0xf9, 0xdc, 0xbb, 0xac, 0x55, 0xa0, 0x62, 0x95, 0xce, 0x87, 0x0b, 0x07, - 0x02, 0x9b, 0xfc, 0xdb, 0x2d, 0xce, 0x28, 0xd9, 0x59, 0xf2, 0x81, 0x5b, 0x16, 0xf8, 0x17, 0x98, - 0x48, 0x3a, 0xda, 0x77, 0x26, 0xa3, 0xc4, 0x65, 0x5d, 0xa4, 0xfb, 0xfc, 0x0e, 0x11, 0x08, 0xa8, - 0xfd, 0x17, 0xb4, 0x48, 0xa6, 0x85, 0x54, 0x19, 0x9c, 0x47, 0xd0, 0x8f, 0xfb, 0x10, 0xd4, 0xb8, - ]); - - /** - * Point generator - * @returns The generator for the curve. - */ - public generator(): Buffer { - return Secp256k1.generator; - } - - /** - * Multiplies a point by a scalar (adds the point `scalar` amount of time). - * @param point - Point to multiply. - * @param scalar - Scalar to multiply by. - * @returns Result of the multiplication. - */ - public mul(point: Uint8Array, scalar: Uint8Array) { - wasm.writeMemory(0, point); - wasm.writeMemory(64, scalar); - wasm.call('ecc_secp256k1__mul', 0, 64, 96); - return Buffer.from(wasm.getMemorySlice(96, 160)); - } - - /** - * Gets a random field element. - * @returns Random field element. - */ - public getRandomFr() { - wasm.call('ecc_secp256k1__get_random_scalar_mod_circuit_modulus', 0); - return Buffer.from(wasm.getMemorySlice(0, 32)); - } - - /** - * Converts a 512 bits long buffer to a field. - * @param uint512Buf - The buffer to convert. - * @returns Buffer representation of the field element. - */ - public reduce512BufferToFr(uint512Buf: Buffer) { - wasm.writeMemory(0, uint512Buf); - wasm.call('ecc_secp256k1__reduce512_buffer_mod_circuit_modulus', 0, 64); - return Buffer.from(wasm.getMemorySlice(64, 96)); - } -} diff --git a/yarn-project/circuits.js/src/barretenberg/crypto/signature/index.ts b/yarn-project/circuits.js/src/barretenberg/crypto/signature/index.ts deleted file mode 100644 index 1d76139464ea..000000000000 --- a/yarn-project/circuits.js/src/barretenberg/crypto/signature/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Fr } from '@aztec/foundation/fields'; - -/** - * Interface to represent a signature. - */ -export interface Signature { - /** - * Serializes to a buffer. - * @returns A buffer. - */ - toBuffer(): Buffer; - /** - * Serializes to an array of fields. - * @returns Fields. - */ - toFields(): Fr[]; -} diff --git a/yarn-project/circuits.js/src/barretenberg/index.ts b/yarn-project/circuits.js/src/barretenberg/index.ts deleted file mode 100644 index d86f006724fd..000000000000 --- a/yarn-project/circuits.js/src/barretenberg/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './crypto/index.js'; diff --git a/yarn-project/circuits.js/src/barretenberg/serialize.ts b/yarn-project/circuits.js/src/barretenberg/serialize.ts deleted file mode 100644 index 04cc095a0921..000000000000 --- a/yarn-project/circuits.js/src/barretenberg/serialize.ts +++ /dev/null @@ -1,74 +0,0 @@ -// TODO find a new home for this as we move to external bb.js -// See https://github.com/AztecProtocol/aztec-packages/issues/782 -import { Buffer } from 'buffer'; - -/** - * For serializing an array of fixed length buffers. - * TODO move to foundation pkg. - * @param arr - Array of bufffers. - * @returns The serialized buffers. - */ -export function serializeBufferArrayToVector(arr: Buffer[]) { - const lengthBuf = Buffer.alloc(4); - lengthBuf.writeUInt32BE(arr.length, 0); - return Buffer.concat([lengthBuf, ...arr]); -} - -/** - * Helper function for deserializeArrayFromVector. - */ -type DeserializeFn = ( - buf: Buffer, - offset: number, -) => { - /** - * The deserialized type. - */ - elem: T; - /** - * How many bytes to advance by. - */ - adv: number; -}; - -/** - * For deserializing numbers to 32-bit little-endian form. - * TODO move to foundation pkg. - * @param n - The number. - * @returns The endian-corrected number. - */ -export function deserializeArrayFromVector(deserialize: DeserializeFn, vector: Buffer, offset = 0) { - let pos = offset; - const size = vector.readUInt32BE(pos); - pos += 4; - const arr = new Array(size); - for (let i = 0; i < size; ++i) { - const { elem, adv } = deserialize(vector, pos); - pos += adv; - arr[i] = elem; - } - return { elem: arr, adv: pos - offset }; -} - -/** - * For serializing numbers to 32 bit little-endian form. - * TODO move to foundation pkg. - * @param n - The number. - * @returns The endian-corrected number. - */ -export function numToUInt32LE(n: number, bufferSize = 4) { - const buf = Buffer.alloc(bufferSize); - buf.writeUInt32LE(n, bufferSize - 4); - return buf; -} - -/** - * Deserialize the 256-bit number at address `offset`. - * @param buf - The buffer. - * @param offset - The address. - * @returns The derserialized 256-bit field. - */ -export function deserializeField(buf: Buffer, offset = 0) { - const adv = 32; - return { elem: buf.slice(offset, offset + adv), adv }; -} diff --git a/yarn-project/circuits.js/src/contract/contract_deployment_info.ts b/yarn-project/circuits.js/src/contract/contract_deployment_info.ts deleted file mode 100644 index 38a15d1cfcc2..000000000000 --- a/yarn-project/circuits.js/src/contract/contract_deployment_info.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { - computeCompleteAddress, - computeFunctionTreeRoot, - computeVarArgsHash, - hashConstructor, -} from '@aztec/circuits.js/abis'; -import { ContractArtifact, FunctionSelector, encodeArguments } from '@aztec/foundation/abi'; - -import { DeploymentInfo, Fr, FunctionData, PublicKey } from '../index.js'; -import { generateFunctionLeaves, hashVKStr, isConstructor } from './contract_tree/contract_tree.js'; - -/** - * Generates the deployment info for a contract - * @param artifact - The account contract build artifact. - * @param args - The args to the account contract constructor - * @param contractAddressSalt - The salt to be used in the contract address derivation - * @param publicKey - The account public key - * @returns - The contract deployment info - */ -export function getContractDeploymentInfo( - artifact: ContractArtifact, - args: any[], - contractAddressSalt: Fr, - publicKey: PublicKey, -): DeploymentInfo { - const constructorArtifact = artifact.functions.find(isConstructor); - if (!constructorArtifact) { - throw new Error('Cannot find constructor in the artifact.'); - } - if (!constructorArtifact.verificationKey) { - throw new Error('Missing verification key for the constructor.'); - } - - const vkHash = hashVKStr(constructorArtifact.verificationKey); - const constructorVkHash = Fr.fromBuffer(vkHash); - const functions = artifact.functions.map(f => ({ - ...f, - selector: FunctionSelector.fromNameAndParameters(f.name, f.parameters), - })); - const leaves = generateFunctionLeaves(functions); - const functionTreeRoot = computeFunctionTreeRoot(leaves); - const functionData = FunctionData.fromAbi(constructorArtifact); - const flatArgs = encodeArguments(constructorArtifact, args); - const argsHash = computeVarArgsHash(flatArgs); - const constructorHash = hashConstructor(functionData, argsHash, constructorVkHash.toBuffer()); - - const completeAddress = computeCompleteAddress(publicKey, contractAddressSalt, functionTreeRoot, constructorHash); - - return { - completeAddress, - constructorHash: constructorVkHash, - functionTreeRoot, - }; -} diff --git a/yarn-project/circuits.js/src/contract/contract_tree/function_tree_data.test.ts b/yarn-project/circuits.js/src/contract/contract_tree/function_tree_data.test.ts deleted file mode 100644 index aac4187726f8..000000000000 --- a/yarn-project/circuits.js/src/contract/contract_tree/function_tree_data.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { Fr } from '@aztec/foundation/fields'; - -import { computeFunctionTreeData } from './function_tree_data.js'; - -const getFr = (index: number) => Fr.fromBuffer(Buffer.alloc(32, index)); -const Tree = [ - // leaves - getFr(8), - getFr(9), - getFr(10), - getFr(11), - getFr(12), - getFr(13), - getFr(14), - getFr(15), - // 1st hash level - getFr(4), - getFr(5), - getFr(6), - getFr(7), - // 2nd hash level - getFr(2), - getFr(3), - // root - getFr(1), -]; - -const tests = [ - { index: 0, path: [getFr(9), getFr(5), getFr(3)] }, - { index: 1, path: [getFr(8), getFr(5), getFr(3)] }, - { index: 2, path: [getFr(11), getFr(4), getFr(3)] }, - { index: 3, path: [getFr(10), getFr(4), getFr(3)] }, - { index: 4, path: [getFr(13), getFr(7), getFr(2)] }, - { index: 5, path: [getFr(12), getFr(7), getFr(2)] }, - { index: 6, path: [getFr(15), getFr(6), getFr(2)] }, - { index: 7, path: [getFr(14), getFr(6), getFr(2)] }, -]; - -describe('Compute Function Tree Sibling Path', () => { - for (let i = 0; i < tests.length; i++) { - it('should generate the correct sibling path', () => { - const actual = computeFunctionTreeData(Tree, tests[i].index); - const expected = { - root: getFr(1), - siblingPath: tests[i].path, - }; - expect(actual).toEqual(expected); - }); - } -}); diff --git a/yarn-project/circuits.js/src/contract/contract_tree/function_tree_data.ts b/yarn-project/circuits.js/src/contract/contract_tree/function_tree_data.ts deleted file mode 100644 index c377adc95bd7..000000000000 --- a/yarn-project/circuits.js/src/contract/contract_tree/function_tree_data.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { Fr } from '@aztec/foundation/fields'; - -/** - * Computes the root and sibling path of a given function tree and index. - * The function takes in an array of Fr elements representing the function tree and an integer function index. - * It returns an object containing the root element of the tree and an array of sibling path elements. - * - * @param functionTree - The array of Fr elements representing the function tree. - * @param functionIndex - The integer index of the desired function in the tree. - * @returns An object containing the root element (Fr) of the tree and an array of sibling path elements (Fr[]). - */ -export function computeFunctionTreeData(functionTree: Fr[], functionIndex: number) { - let rowSize = Math.ceil(functionTree.length / 2); - let rowOffset = 0; - let index = functionIndex; - const siblingPath: Fr[] = []; - while (rowSize > 1) { - const isRight = index & 1; - siblingPath.push(functionTree[rowOffset + index + (isRight ? -1 : 1)]); - rowOffset += rowSize; - rowSize >>= 1; - index >>= 1; - } - return { - root: functionTree[functionTree.length - 1], - siblingPath, - }; -} diff --git a/yarn-project/circuits.js/src/contract/contract_tree/index.ts b/yarn-project/circuits.js/src/contract/contract_tree/index.ts deleted file mode 100644 index 33534f5568c7..000000000000 --- a/yarn-project/circuits.js/src/contract/contract_tree/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './contract_tree.js'; -export * from './function_tree_data.js'; diff --git a/yarn-project/circuits.js/src/contract/index.ts b/yarn-project/circuits.js/src/contract/index.ts deleted file mode 100644 index 38bc67a9e52a..000000000000 --- a/yarn-project/circuits.js/src/contract/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './contract_deployment_info.js'; -export * from './contract_tree/index.js'; diff --git a/yarn-project/circuits.js/src/structs/aggregation_object.ts b/yarn-project/circuits.js/src/structs/aggregation_object.ts deleted file mode 100644 index c00dd2795e0a..000000000000 --- a/yarn-project/circuits.js/src/structs/aggregation_object.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { Fq, Fr } from '@aztec/foundation/fields'; -import { BufferReader } from '@aztec/foundation/serialize'; - -import times from 'lodash.times'; - -import { serializeToBuffer } from '../utils/serialize.js'; -import { UInt32, Vector } from './shared.js'; -import { G1AffineElement } from './verification_key.js'; - -/** - * Contains the aggregated proof of all the previous kernel iterations. - * - * See barretenberg/cpp/src/barretenberg/stdlib/recursion/aggregation_state/native_aggregation_state.hpp - * for more context. - */ -export class AggregationObject { - constructor( - /** - * One of the 2 aggregated elements storing the verification results of proofs in the past. - */ - public p0: G1AffineElement, - /** - * One of the 2 aggregated elements storing the verification results of proofs in the past. - */ - public p1: G1AffineElement, - /** - * The public inputs of the inner proof (these become the private inputs to the recursive circuit). - */ - public publicInputs: Fr[], - /** - * Witness indices that point to (P0, P1). - */ - public proofWitnessIndices: UInt32[], - /** - * Indicates if this aggregation state contain past (P0, P1). - */ - public hasData = false, - ) {} - - toBuffer() { - return serializeToBuffer( - this.p0, - this.p1, - new Vector(this.publicInputs), - new Vector(this.proofWitnessIndices), - this.hasData, - ); - } - - /** - * Deserializes this object from a buffer. - * @param buffer - The buffer representation of this object. - * @returns The deserialized object. - */ - public static fromBuffer(buffer: Buffer | BufferReader): AggregationObject { - const reader = BufferReader.asReader(buffer); - return new AggregationObject( - reader.readObject(G1AffineElement), - reader.readObject(G1AffineElement), - reader.readVector(Fr), - reader.readNumberVector(), - reader.readBoolean(), - ); - } - - /** - * Creates a fake object for testing. - * @returns The fake object. - */ - public static makeFake(): AggregationObject { - return new AggregationObject( - new G1AffineElement(new Fq(1n), new Fq(2n)), - new G1AffineElement(new Fq(1n), new Fq(2n)), - [], - times(16, i => 3027 + i), - false, - ); - } -} diff --git a/yarn-project/circuits.js/src/structs/call_context.ts b/yarn-project/circuits.js/src/structs/call_context.ts deleted file mode 100644 index 860b2fc05ea8..000000000000 --- a/yarn-project/circuits.js/src/structs/call_context.ts +++ /dev/null @@ -1,133 +0,0 @@ -import { AztecAddress } from '@aztec/foundation/aztec-address'; -import { EthAddress } from '@aztec/foundation/eth-address'; -import { BufferReader } from '@aztec/foundation/serialize'; - -import { FieldsOf } from '../utils/jsUtils.js'; -import { serializeToBuffer } from '../utils/serialize.js'; -import { Fr, FunctionSelector } from './index.js'; - -/** - * Call context. - * @see abis/call_context.hpp - */ -export class CallContext { - /** - * Address of the portal contract to the storage contract. - */ - public portalContractAddress: EthAddress; - constructor( - /** - * Address of the account which represents the entity who invoked the call. - */ - public msgSender: AztecAddress, - /** - * The contract address against which all state changes will be stored. Not called `contractAddress` because during - * delegate call the contract whose code is being executed may be different from the contract whose state is being - * modified. - */ - public storageContractAddress: AztecAddress, - /** - * Address of the portal contract to the storage contract. - * Union type is a kludge until C++ has an eth address type. - */ - portalContractAddress: EthAddress | Fr, - /** - * Function selector of the function being called. - */ - public functionSelector: FunctionSelector, - /** - * Determines whether the call is a delegate call (see Ethereum's delegate call opcode for more information). - */ - public isDelegateCall: boolean, - /** - * Determines whether the call is modifying state. - */ - public isStaticCall: boolean, - /** - * Determines whether the call is a contract deployment. - */ - public isContractDeployment: boolean, - ) { - this.portalContractAddress = - portalContractAddress instanceof EthAddress ? portalContractAddress : EthAddress.fromField(portalContractAddress); - } - - /** - * Returns a new instance of CallContext with zero msg sender, storage contract address and portal contract address. - * @returns A new instance of CallContext with zero msg sender, storage contract address and portal contract address. - */ - public static empty(): CallContext { - return new CallContext( - AztecAddress.ZERO, - AztecAddress.ZERO, - Fr.ZERO, - FunctionSelector.empty(), - false, - false, - false, - ); - } - - isEmpty() { - return ( - this.msgSender.isZero() && - this.storageContractAddress.isZero() && - this.portalContractAddress.isZero() && - this.functionSelector.isEmpty() - ); - } - - static from(fields: FieldsOf): CallContext { - return new CallContext(...CallContext.getFields(fields)); - } - - static getFields(fields: FieldsOf) { - return [ - fields.msgSender, - fields.storageContractAddress, - fields.portalContractAddress, - fields.functionSelector, - fields.isDelegateCall, - fields.isStaticCall, - fields.isContractDeployment, - ] as const; - } - - /** - * Serialize this as a buffer. - * @returns The buffer. - */ - toBuffer() { - return serializeToBuffer(...CallContext.getFields(this)); - } - - /** - * Deserialize this from a buffer. - * @param buffer - The bufferable type from which to deserialize. - * @returns The deserialized instance of PublicCallRequest. - */ - static fromBuffer(buffer: Buffer | BufferReader) { - const reader = BufferReader.asReader(buffer); - return new CallContext( - new AztecAddress(reader.readBytes(32)), - new AztecAddress(reader.readBytes(32)), - new EthAddress(reader.readBytes(32)), - FunctionSelector.fromBuffer(reader.readBytes(4)), - reader.readBoolean(), - reader.readBoolean(), - reader.readBoolean(), - ); - } - - equals(callContext: CallContext) { - return ( - callContext.msgSender.equals(this.msgSender) && - callContext.storageContractAddress.equals(this.storageContractAddress) && - callContext.portalContractAddress.equals(this.portalContractAddress) && - callContext.functionSelector.equals(this.functionSelector) && - callContext.isDelegateCall === this.isDelegateCall && - callContext.isStaticCall === this.isStaticCall && - callContext.isContractDeployment === this.isContractDeployment - ); - } -} diff --git a/yarn-project/circuits.js/src/structs/call_request.ts b/yarn-project/circuits.js/src/structs/call_request.ts deleted file mode 100644 index da7e33042061..000000000000 --- a/yarn-project/circuits.js/src/structs/call_request.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { AztecAddress } from '@aztec/foundation/aztec-address'; -import { Fr } from '@aztec/foundation/fields'; -import { BufferReader } from '@aztec/foundation/serialize'; -import { FieldsOf } from '@aztec/foundation/types'; - -import { serializeToBuffer } from '../utils/serialize.js'; - -/** - * Caller context. - */ -export class CallerContext { - constructor( - /** - * Address of the caller contract. - */ - public msgSender: AztecAddress, - /** - * Storage contract address of the caller contract. - */ - public storageContractAddress: AztecAddress, - ) {} - - /** - * Returns a new instance of CallerContext with zero values. - * @returns A new instance of CallerContext with zero values. - */ - public static empty(): CallerContext { - return new CallerContext(AztecAddress.ZERO, AztecAddress.ZERO); - } - - isEmpty() { - return this.msgSender.isZero() && this.storageContractAddress.isZero(); - } - - static from(fields: FieldsOf): CallerContext { - return new CallerContext(...CallerContext.getFields(fields)); - } - - static getFields(fields: FieldsOf) { - return [fields.msgSender, fields.storageContractAddress] as const; - } - - /** - * Serialize this as a buffer. - * @returns The buffer. - */ - toBuffer() { - return serializeToBuffer(...CallerContext.getFields(this)); - } - - /** - * Deserialize this from a buffer. - * @param buffer - The bufferable type from which to deserialize. - * @returns The deserialized instance of PublicCallRequest. - */ - static fromBuffer(buffer: Buffer | BufferReader) { - const reader = BufferReader.asReader(buffer); - return new CallerContext(new AztecAddress(reader.readBytes(32)), new AztecAddress(reader.readBytes(32))); - } - - equals(callerContext: CallerContext) { - return ( - callerContext.msgSender.equals(this.msgSender) && - callerContext.storageContractAddress.equals(this.storageContractAddress) - ); - } -} - -/** - * Call request. - */ -export class CallRequest { - constructor( - /** - * The hash of the call stack item. - */ - public hash: Fr, - /** - * The address of the contract calling the function. - */ - public callerContractAddress: AztecAddress, - /** - * The call context of the contract calling the function. - */ - public callerContext: CallerContext, - ) {} - - toBuffer() { - return serializeToBuffer(this.hash, this.callerContractAddress, this.callerContext); - } - - /** - * Deserializes from a buffer or reader. - * @param buffer - Buffer or reader to read from. - * @returns The deserialized instance of CallRequest. - */ - public static fromBuffer(buffer: Buffer | BufferReader) { - const reader = BufferReader.asReader(buffer); - return new CallRequest(Fr.fromBuffer(reader), reader.readObject(AztecAddress), reader.readObject(CallerContext)); - } - - isEmpty() { - return this.hash.isZero() && this.callerContractAddress.isZero() && this.callerContext.isEmpty(); - } - - /** - * Returns a new instance of CallRequest with zero hash, caller contract address and caller context. - * @returns A new instance of CallRequest with zero hash, caller contract address and caller context. - */ - public static empty() { - return new CallRequest(Fr.ZERO, AztecAddress.ZERO, CallerContext.empty()); - } - - equals(callRequest: CallRequest) { - return ( - callRequest.hash.equals(this.hash) && - callRequest.callerContractAddress.equals(this.callerContractAddress) && - callRequest.callerContext.equals(this.callerContext) - ); - } -} diff --git a/yarn-project/circuits.js/src/structs/call_stack_item.ts b/yarn-project/circuits.js/src/structs/call_stack_item.ts deleted file mode 100644 index 9e1a67857a2d..000000000000 --- a/yarn-project/circuits.js/src/structs/call_stack_item.ts +++ /dev/null @@ -1,152 +0,0 @@ -import { AztecAddress } from '@aztec/foundation/aztec-address'; - -import { computePrivateCallStackItemHash, computePublicCallStackItemHash } from '../abis/abis.js'; -import { serializeToBuffer } from '../utils/serialize.js'; -import { CallRequest, CallerContext } from './call_request.js'; -import { FunctionData } from './function_data.js'; -import { PrivateCircuitPublicInputs } from './private_circuit_public_inputs.js'; -import { PublicCircuitPublicInputs } from './public_circuit_public_inputs.js'; - -/** - * Call stack item on a private call. - * @see cpp/src/aztec3/circuits/abis/call_stack_item.hpp. - */ -export class PrivateCallStackItem { - constructor( - /** - * Address of the contract on which the function is invoked. - */ - public contractAddress: AztecAddress, - /** - * Data identifying the function being called. - */ - public functionData: FunctionData, - /** - * Public inputs to the private kernel circuit. - */ - public publicInputs: PrivateCircuitPublicInputs, - /** - * Whether the current callstack item should be considered a public fn execution request. - */ - public readonly isExecutionRequest: boolean, - ) { - if (isExecutionRequest) { - throw new Error('boolean isExecutionRequest must be set to true for a PrivateCallStackItem object'); - } - } - - toBuffer() { - return serializeToBuffer(this.contractAddress, this.functionData, this.publicInputs, this.isExecutionRequest); - } - - /** - * Returns a new instance of PrivateCallStackItem with zero contract address, function data and public inputs. - * @returns A new instance of PrivateCallStackItem with zero contract address, function data and public inputs. - */ - public static empty(): PrivateCallStackItem { - return new PrivateCallStackItem( - AztecAddress.ZERO, - FunctionData.empty({ isPrivate: true }), - PrivateCircuitPublicInputs.empty(), - false, - ); - } - - isEmpty() { - return this.contractAddress.isZero() && this.functionData.isEmpty() && this.publicInputs.isEmpty(); - } - - /** - * Computes this call stack item hash. - * @returns Hash. - */ - public hash() { - return computePrivateCallStackItemHash(this); - } - - /** - * Creates a new CallRequest with values of the calling contract. - * @returns A CallRequest instance with the contract address, caller context, and the hash of the call stack item. - */ - public toCallRequest() { - if (this.isEmpty()) { - return CallRequest.empty(); - } - - const callContext = this.publicInputs.callContext; - const callerContext = callContext.isDelegateCall - ? new CallerContext(callContext.msgSender, callContext.storageContractAddress) - : CallerContext.empty(); - return new CallRequest(this.hash(), callContext.msgSender, callerContext); - } -} - -/** - * Call stack item on a public call. - * @see cpp/src/aztec3/circuits/abis/call_stack_item.hpp. - */ -export class PublicCallStackItem { - constructor( - /** - * Address of the contract on which the function is invoked. - */ - public contractAddress: AztecAddress, - /** - * Data identifying the function being called. - */ - public functionData: FunctionData, - /** - * Public inputs to the public kernel circuit. - */ - public publicInputs: PublicCircuitPublicInputs, - /** - * Whether the current callstack item should be considered a public fn execution request. - */ - public isExecutionRequest: boolean, - ) {} - - toBuffer() { - return serializeToBuffer(this.contractAddress, this.functionData, this.publicInputs, this.isExecutionRequest); - } - - /** - * Returns a new instance of PublicCallStackItem with zero contract address, function data and public inputs. - * @returns A new instance of PublicCallStackItem with zero contract address, function data and public inputs. - */ - public static empty(): PublicCallStackItem { - return new PublicCallStackItem( - AztecAddress.ZERO, - FunctionData.empty({ isPrivate: false }), - PublicCircuitPublicInputs.empty(), - false, - ); - } - - isEmpty() { - return this.contractAddress.isZero() && this.functionData.isEmpty() && this.publicInputs.isEmpty(); - } - - /** - * Computes this call stack item hash. - * @returns Hash. - */ - public hash() { - return computePublicCallStackItemHash(this); - } - - /** - * Creates a new CallRequest with values of the calling contract. - * @returns A CallRequest instance with the contract address, caller context, and the hash of the call stack item. - */ - public toCallRequest() { - if (this.isEmpty()) { - return CallRequest.empty(); - } - - const callContext = this.publicInputs.callContext; - const callerContext = callContext.isDelegateCall - ? new CallerContext(callContext.msgSender, callContext.storageContractAddress) - : CallerContext.empty(); - return new CallRequest(this.hash(), callContext.msgSender, callerContext); - } -} diff --git a/yarn-project/circuits.js/src/structs/complete_address.test.ts b/yarn-project/circuits.js/src/structs/complete_address.test.ts deleted file mode 100644 index c3047a267cb7..000000000000 --- a/yarn-project/circuits.js/src/structs/complete_address.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { AztecAddress } from '@aztec/foundation/aztec-address'; -import { Fr, Point } from '@aztec/foundation/fields'; - -import { CompleteAddress } from './complete_address.js'; - -describe('CompleteAddress', () => { - it('refuses to add an account with incorrect address for given partial address and pubkey', () => { - expect(() => CompleteAddress.create(AztecAddress.random(), Point.random(), Fr.random())).toThrowError( - /cannot be derived/, - ); - }); - - it('equals returns true when 2 instances are equal', () => { - const address1 = CompleteAddress.random(); - const address2 = CompleteAddress.create(address1.address, address1.publicKey, address1.partialAddress); - expect(address1.equals(address2)).toBe(true); - }); - - it('equals returns true when 2 instances are not equal', () => { - const address1 = CompleteAddress.random(); - const address2 = CompleteAddress.random(); - expect(address1.equals(address2)).toBe(false); - }); - - it('serializes / deserializes correctly', () => { - const expectedAddress = CompleteAddress.random(); - const address = CompleteAddress.fromBuffer(expectedAddress.toBuffer()); - expect(address.equals(expectedAddress)).toBe(true); - }); -}); diff --git a/yarn-project/circuits.js/src/structs/complete_address.ts b/yarn-project/circuits.js/src/structs/complete_address.ts deleted file mode 100644 index b2fd575e4d5a..000000000000 --- a/yarn-project/circuits.js/src/structs/complete_address.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { AztecAddress } from '@aztec/foundation/aztec-address'; -import { Fr, Point } from '@aztec/foundation/fields'; -import { BufferReader } from '@aztec/foundation/serialize'; - -import { computeContractAddressFromPartial } from '../abis/abis.js'; -import { Grumpkin } from '../barretenberg/index.js'; -import { GrumpkinPrivateKey, PartialAddress, PublicKey } from '../index.js'; - -/** - * A complete address is a combination of an Aztec address, a public key and a partial address. - * - * @remarks We have introduced this type because it is common that these 3 values are used together. They are commonly - * used together because it is the information needed to send user a note. - * @remarks See the link bellow for details about how address is computed: - * https://github.com/AztecProtocol/aztec-packages/blob/master/docs/docs/concepts/foundation/accounts/keys.md#addresses-partial-addresses-and-public-keys - */ -export class CompleteAddress { - // TODO: This constructor should be private so that the check in create method is always enforced. However, this is - // not possible now because we need the class to be compatible with `StringIOClass` to be able to pass it - // through `JsonRpcServer`. - public constructor( - /** Contract address (typically of an account contract) */ - public address: AztecAddress, - /** Public key corresponding to the address (used during note encryption). */ - public publicKey: PublicKey, - /** Partial key corresponding to the public key to the address. */ - public partialAddress: PartialAddress, - ) {} - - /** Size in bytes of an instance */ - static readonly SIZE_IN_BYTES = 32 * 4; - - static create(address: AztecAddress, publicKey: PublicKey, partialAddress: PartialAddress) { - const expectedAddress = computeContractAddressFromPartial(publicKey, partialAddress); - if (!expectedAddress.equals(address)) { - throw new Error( - `Address cannot be derived from pubkey and partial address (received ${address.toString()}, derived ${expectedAddress.toString()})`, - ); - } - return new CompleteAddress(address, publicKey, partialAddress); - } - - static random() { - const partialAddress = Fr.random(); - const pubKey = Point.random(); - const address = computeContractAddressFromPartial(pubKey, partialAddress); - return new CompleteAddress(address, pubKey, partialAddress); - } - - static fromPrivateKeyAndPartialAddress(privateKey: GrumpkinPrivateKey, partialAddress: Fr): CompleteAddress { - const grumpkin = new Grumpkin(); - const pubKey = grumpkin.mul(Grumpkin.generator, privateKey); - const address = computeContractAddressFromPartial(pubKey, partialAddress); - return new CompleteAddress(address, pubKey, partialAddress); - } - - /** - * Gets a readable string representation of a the complete address. - * @returns A readable string representation of the complete address. - */ - public toReadableString(): string { - return ` Address: ${this.address.toString()}\n Public Key: ${this.publicKey.toString()}\n Partial Address: ${this.partialAddress.toString()}\n`; - } - - /** - * Determines if this CompleteAddress instance is equal to the given CompleteAddress instance. - * Equality is based on the content of their respective buffers. - * - * @param other - The CompleteAddress instance to compare against. - * @returns True if the buffers of both instances are equal, false otherwise. - */ - equals(other: CompleteAddress) { - return ( - this.address.equals(other.address) && - this.publicKey.equals(other.publicKey) && - this.partialAddress.equals(other.partialAddress) - ); - } - - /** - * Converts the CompleteAddress instance into a Buffer. - * This method should be used when encoding the address for storage, transmission or serialization purposes. - * - * @returns A Buffer representation of the CompleteAddress instance. - */ - toBuffer() { - return Buffer.concat([this.address.toBuffer(), this.publicKey.toBuffer(), this.partialAddress.toBuffer()]); - } - - /** - * Creates an CompleteAddress instance from a given buffer or BufferReader. - * If the input is a Buffer, it wraps it in a BufferReader before processing. - * Throws an error if the input length is not equal to the expected size. - * - * @param buffer - The input buffer or BufferReader containing the address data. - * @returns - A new CompleteAddress instance with the extracted address data. - */ - static fromBuffer(buffer: Buffer | BufferReader) { - const reader = BufferReader.asReader(buffer); - const address = reader.readObject(AztecAddress); - const publicKey = reader.readObject(Point); - const partialAddress = reader.readObject(Fr); - return new this(address, publicKey, partialAddress); - } - - /** - * Create a CompleteAddress instance from a hex-encoded string. - * The input 'address' should be prefixed with '0x' or not, and have exactly 128 hex characters representing the x and y coordinates. - * Throws an error if the input length is invalid or coordinate values are out of range. - * - * @param address - The hex-encoded string representing the complete address. - * @returns A Point instance. - */ - static fromString(address: string): CompleteAddress { - return this.fromBuffer(Buffer.from(address.replace(/^0x/i, ''), 'hex')); - } - - /** - * Convert the CompleteAddress to a hexadecimal string representation, with a "0x" prefix. - * The resulting string will have a length of 66 characters (including the prefix). - * - * @returns A hexadecimal string representation of the CompleteAddress. - */ - toString(): string { - return `0x${this.toBuffer().toString('hex')}`; - } -} diff --git a/yarn-project/circuits.js/src/structs/function_data.ts b/yarn-project/circuits.js/src/structs/function_data.ts deleted file mode 100644 index 9838417a13b6..000000000000 --- a/yarn-project/circuits.js/src/structs/function_data.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { FunctionAbi, FunctionSelector, FunctionType } from '@aztec/foundation/abi'; -import { BufferReader } from '@aztec/foundation/serialize'; - -import { ContractFunctionDao } from '../index.js'; -import { serializeToBuffer } from '../utils/serialize.js'; - -/** - * Function description for circuit. - * @see abis/function_data.hpp - */ -export class FunctionData { - constructor( - /** - * Function selector of the function being called. - */ - public selector: FunctionSelector, - /** - * Indicates whether the function is only callable by self or not. - */ - public isInternal: boolean, - /** - * Indicates whether the function is private or public. - */ - public isPrivate: boolean, - /** - * Indicates whether the function is a constructor. - */ - public isConstructor: boolean, - ) {} - - static fromAbi(abi: FunctionAbi | ContractFunctionDao): FunctionData { - return new FunctionData( - FunctionSelector.fromNameAndParameters(abi.name, abi.parameters), - abi.isInternal, - abi.functionType === FunctionType.SECRET, - abi.name === 'constructor', - ); - } - - /** - * Serialize this as a buffer. - * @returns The buffer. - */ - toBuffer(): Buffer { - return serializeToBuffer(this.selector, this.isInternal, this.isPrivate, this.isConstructor); - } - - /** - * Returns whether this instance is empty. - * @returns True if the function selector is zero. - */ - isEmpty() { - return this.selector.isEmpty(); - } - - /** - * Returns a new instance of FunctionData with zero function selector. - * @param args - Arguments to pass to the constructor. - * @returns A new instance of FunctionData with zero function selector. - */ - public static empty(args?: { - /** - * Indicates whether the function is only callable by self or not. - */ - isInternal?: boolean; - /** - * Indicates whether the function is private or public. - */ - isPrivate?: boolean; - /** - * Indicates whether the function is a constructor. - */ - isConstructor?: boolean; - }): FunctionData { - return new FunctionData( - FunctionSelector.empty(), - args?.isInternal ?? false, - args?.isPrivate ?? false, - args?.isConstructor ?? false, - ); - } - - /** - * Deserializes from a buffer or reader, corresponding to a write in cpp. - * @param buffer - Buffer or reader to read from. - * @returns A new instance of FunctionData. - */ - static fromBuffer(buffer: Buffer | BufferReader): FunctionData { - const reader = BufferReader.asReader(buffer); - return new FunctionData( - reader.readObject(FunctionSelector), - reader.readBoolean(), - reader.readBoolean(), - reader.readBoolean(), - ); - } -} diff --git a/yarn-project/circuits.js/src/structs/function_leaf_preimage.ts b/yarn-project/circuits.js/src/structs/function_leaf_preimage.ts deleted file mode 100644 index 0aed310a4e0e..000000000000 --- a/yarn-project/circuits.js/src/structs/function_leaf_preimage.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { FunctionSelector } from '@aztec/foundation/abi'; -import { Fr } from '@aztec/foundation/fields'; -import { BufferReader } from '@aztec/foundation/serialize'; - -import { serializeToBuffer } from '../utils/serialize.js'; - -/** - * A class representing the "preimage" of a function tree leaf. - * @see abis/function_leaf_preimage.hpp - */ -export class FunctionLeafPreimage { - constructor( - /** - * Function selector. - */ - public functionSelector: FunctionSelector, - /** - * Indicates whether the function is only callable by self or not. - */ - public isInternal: boolean, - /** - * Indicates whether the function is private or public. - */ - public isPrivate: boolean, - /** - * Verification key hash of the function. - */ - public vkHash: Fr, - /** - * Hash of the ACIR of the function. - */ - public acirHash: Fr, - ) {} - - /** - * Serialize this as a buffer. - * @returns The buffer. - */ - toBuffer(): Buffer { - return serializeToBuffer(this.functionSelector, this.isInternal, this.isPrivate, this.vkHash, this.acirHash); - } - - /** - * Deserializes from a buffer or reader, corresponding to a write in cpp. - * @param buffer - Buffer or reader to read from. - * @returns A new instance of FunctionLeafPreimage. - */ - static fromBuffer(buffer: Buffer | BufferReader): FunctionLeafPreimage { - const reader = BufferReader.asReader(buffer); - return new FunctionLeafPreimage( - reader.readObject(FunctionSelector), - reader.readBoolean(), - reader.readBoolean(), - Fr.fromBuffer(reader), - Fr.fromBuffer(reader), - ); - } -} diff --git a/yarn-project/circuits.js/src/structs/global_variables.ts b/yarn-project/circuits.js/src/structs/global_variables.ts deleted file mode 100644 index f93af7b67eab..000000000000 --- a/yarn-project/circuits.js/src/structs/global_variables.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { Fr } from '@aztec/foundation/fields'; -import { BufferReader } from '@aztec/foundation/serialize'; - -import { FieldsOf } from '../index.js'; -import { serializeToBuffer } from '../utils/index.js'; - -/** - * Global variables of the L2 block. - */ -export class GlobalVariables { - constructor( - /** - * ChainId for the L2 block. - */ - public chainId: Fr, - /** - * version for the L2 block. - */ - public version: Fr, - /** - * Block number of the L2 block. - */ - public blockNumber: Fr, - /** - * Timestamp of the L2 block. - */ - public timestamp: Fr, - ) {} - - static from(fields: FieldsOf): GlobalVariables { - return new GlobalVariables(...GlobalVariables.getFields(fields)); - } - - static empty(): GlobalVariables { - return new GlobalVariables(Fr.ZERO, Fr.ZERO, Fr.ZERO, Fr.ZERO); - } - - static fromBuffer(buffer: Buffer | BufferReader): GlobalVariables { - const reader = BufferReader.asReader(buffer); - return new GlobalVariables( - Fr.fromBuffer(reader), - Fr.fromBuffer(reader), - Fr.fromBuffer(reader), - Fr.fromBuffer(reader), - ); - } - - static fromJSON(obj: any): GlobalVariables { - return new GlobalVariables( - Fr.fromString(obj.chainId), - Fr.fromString(obj.version), - Fr.fromString(obj.blockNumber), - Fr.fromString(obj.timestamp), - ); - } - - static getFields(fields: FieldsOf) { - return [fields.chainId, fields.version, fields.blockNumber, fields.timestamp] as const; - } - - toBuffer() { - return serializeToBuffer(...GlobalVariables.getFields(this)); - } - - toJSON() { - return { - chainId: this.chainId.toString(), - version: this.version.toString(), - blockNumber: this.blockNumber.toString(), - timestamp: this.timestamp.toString(), - }; - } -} diff --git a/yarn-project/circuits.js/src/structs/kernel/combined_accumulated_data.test.ts b/yarn-project/circuits.js/src/structs/kernel/combined_accumulated_data.test.ts deleted file mode 100644 index ed7561351564..000000000000 --- a/yarn-project/circuits.js/src/structs/kernel/combined_accumulated_data.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { makeAccumulatedData, makeFinalAccumulatedData } from '../../tests/factories.js'; -import { CombinedAccumulatedData, FinalAccumulatedData } from './combined_accumulated_data.js'; - -describe('CombinedAccumulatedData', () => { - it('Data after serialization and deserialization is equal to the original', () => { - const original = makeAccumulatedData(); - const afterSerialization = CombinedAccumulatedData.fromBuffer(original.toBuffer()); - expect(original).toEqual(afterSerialization); - }); -}); - -describe('FinalAccumulatedData', () => { - it('Data after serialization and deserialization is equal to the original', () => { - const original = makeFinalAccumulatedData(); - const afterSerialization = FinalAccumulatedData.fromBuffer(original.toBuffer()); - expect(original).toEqual(afterSerialization); - }); -}); diff --git a/yarn-project/circuits.js/src/structs/kernel/combined_constant_data.ts b/yarn-project/circuits.js/src/structs/kernel/combined_constant_data.ts deleted file mode 100644 index 34f10df67619..000000000000 --- a/yarn-project/circuits.js/src/structs/kernel/combined_constant_data.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { BufferReader } from '@aztec/foundation/serialize'; - -import { serializeToBuffer } from '../../utils/serialize.js'; -import { TxContext } from '../tx_context.js'; -import { HistoricBlockData } from './historic_block_data.js'; - -/** - * Data that is constant/not modified by neither of the kernels. - */ -export class CombinedConstantData { - constructor( - /** - * Roots of the trees relevant for both kernel circuits. - */ - public blockData: HistoricBlockData, - /** - * Context of the transaction. - */ - public txContext: TxContext, - ) {} - - toBuffer() { - return serializeToBuffer(this.blockData, this.txContext); - } - - /** - * Deserializes from a buffer or reader, corresponding to a write in cpp. - * @param buffer - Buffer or buffer reader to read from. - * @returns A new instance of CombinedConstantData. - */ - static fromBuffer(buffer: Buffer | BufferReader): CombinedConstantData { - const reader = BufferReader.asReader(buffer); - return new CombinedConstantData(reader.readObject(HistoricBlockData), reader.readObject(TxContext)); - } - - static empty() { - return new CombinedConstantData(HistoricBlockData.empty(), TxContext.empty()); - } -} diff --git a/yarn-project/circuits.js/src/structs/kernel/historic_block_data.test.ts b/yarn-project/circuits.js/src/structs/kernel/historic_block_data.test.ts deleted file mode 100644 index 9179c979ca40..000000000000 --- a/yarn-project/circuits.js/src/structs/kernel/historic_block_data.test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { HistoricBlockData } from './historic_block_data.js'; - -describe('HistoricBlockData', () => { - it('serializes to buffer and back', () => { - const historicBlockData = HistoricBlockData.random(); - const serialized = historicBlockData.toBuffer(); - const deserialized = HistoricBlockData.fromBuffer(serialized); - expect(deserialized).toEqual(historicBlockData); - }); - - it('serializes to string and back', () => { - const historicBlockData = HistoricBlockData.random(); - const serialized = historicBlockData.toString(); - const deserialized = HistoricBlockData.fromString(serialized); - expect(deserialized).toEqual(historicBlockData); - }); -}); diff --git a/yarn-project/circuits.js/src/structs/kernel/previous_kernel_data.ts b/yarn-project/circuits.js/src/structs/kernel/previous_kernel_data.ts deleted file mode 100644 index f03ad99fde86..000000000000 --- a/yarn-project/circuits.js/src/structs/kernel/previous_kernel_data.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { Fr } from '@aztec/foundation/fields'; -import { BufferReader, Tuple } from '@aztec/foundation/serialize'; - -import { VK_TREE_HEIGHT, makeTuple } from '../../index.js'; -import { serializeToBuffer } from '../../utils/serialize.js'; -import { Proof, makeEmptyProof } from '../proof.js'; -import { UInt32 } from '../shared.js'; -import { VerificationKey } from '../verification_key.js'; -import { KernelCircuitPublicInputs } from './public_inputs.js'; - -/** - * Data of the previous kernel iteration in the chain of kernels. - */ -export class PreviousKernelData { - constructor( - /** - * Public inputs of the previous kernel. - */ - public publicInputs: KernelCircuitPublicInputs, - /** - * Proof of the previous kernel. - */ - public proof: Proof, - /** - * Verification key of the previous kernel. - */ - public vk: VerificationKey, - /** - * Index of the previous kernel's vk in a tree of vks. - */ - public vkIndex: UInt32, - /** - * Sibling path of the previous kernel's vk in a tree of vks. - */ - public vkPath: Tuple, - ) {} - - /** - * Serialize this as a buffer. - * @returns The buffer. - */ - toBuffer() { - return serializeToBuffer(this.publicInputs, this.proof, this.vk, this.vkIndex, this.vkPath); - } - - /** - * Deserializes from a buffer or reader, corresponding to a write in cpp. - * @param buffer - Buffer or reader to read from. - * @returns The deserialized instance. - */ - static fromBuffer(buffer: Buffer | BufferReader): PreviousKernelData { - const reader = BufferReader.asReader(buffer); - return new this( - reader.readObject(KernelCircuitPublicInputs), - reader.readObject(Proof), - reader.readObject(VerificationKey), - reader.readNumber(), - reader.readArray(VK_TREE_HEIGHT, Fr), - ); - } - - /** - * Creates an empty instance, valid enough to be accepted by circuits. - * @returns The empty instance. - */ - static empty(): PreviousKernelData { - return new PreviousKernelData( - KernelCircuitPublicInputs.empty(), - makeEmptyProof(), - VerificationKey.makeFake(), - 0, - makeTuple(VK_TREE_HEIGHT, Fr.zero), - ); - } -} diff --git a/yarn-project/circuits.js/src/structs/public_call_request.ts b/yarn-project/circuits.js/src/structs/public_call_request.ts deleted file mode 100644 index b8cb2cacd501..000000000000 --- a/yarn-project/circuits.js/src/structs/public_call_request.ts +++ /dev/null @@ -1,124 +0,0 @@ -import { BufferReader } from '@aztec/foundation/serialize'; - -import { computeVarArgsHash } from '../abis/abis.js'; -import { FieldsOf } from '../index.js'; -import { serializeToBuffer } from '../utils/serialize.js'; -import { CallerContext } from './call_request.js'; -import { - AztecAddress, - CallContext, - CallRequest, - Fr, - FunctionData, - PublicCallStackItem, - PublicCircuitPublicInputs, - Vector, -} from './index.js'; - -/** - * Represents a request to call a public function from a private function. Serialization is - * equivalent to a public call stack item, but without the result fields. - */ -export class PublicCallRequest { - constructor( - /** - *Address of the contract on which the function is invoked. - */ - public contractAddress: AztecAddress, - /** - * Data identifying the function being called. - */ - public functionData: FunctionData, - /** - * Context of the public call. - */ - public callContext: CallContext, - /** - * Function arguments. - */ - public args: Fr[], - /** - * Optional side effect counter tracking position of this event in tx execution. - */ - public sideEffectCounter?: number, - ) {} - - /** - * Serialize this as a buffer. - * @returns The buffer. - */ - toBuffer() { - return serializeToBuffer(this.contractAddress, this.functionData, this.callContext, new Vector(this.args)); - } - - /** - * Deserialize this from a buffer. - * @param buffer - The bufferable type from which to deserialize. - * @returns The deserialized instance of PublicCallRequest. - */ - static fromBuffer(buffer: Buffer | BufferReader) { - const reader = BufferReader.asReader(buffer); - return new PublicCallRequest( - new AztecAddress(reader.readBytes(32)), - FunctionData.fromBuffer(reader), - CallContext.fromBuffer(reader), - reader.readVector(Fr), - ); - } - - /** - * Create PublicCallRequest from a fields dictionary. - * @param fields - The dictionary. - * @returns A PublicCallRequest object. - */ - static from(fields: FieldsOf): PublicCallRequest { - return new PublicCallRequest(...PublicCallRequest.getFields(fields)); - } - - /** - * Serialize into a field array. Low-level utility. - * @param fields - Object with fields. - * @returns The array. - */ - static getFields(fields: FieldsOf) { - return [ - fields.contractAddress, - fields.functionData, - fields.callContext, - fields.args, - fields.sideEffectCounter, - ] as const; - } - - /** - * Creates a new PublicCallStackItem by populating with zeroes all fields related to result in the public circuit output. - * @returns A PublicCallStackItem instance with the same contract address, function data, call context, and args. - */ - toPublicCallStackItem() { - const publicInputs = PublicCircuitPublicInputs.empty(); - publicInputs.callContext = this.callContext; - publicInputs.argsHash = this.getArgsHash(); - return new PublicCallStackItem(this.contractAddress, this.functionData, publicInputs, true); - } - - /** - * Creates a new CallRequest with values of the calling contract. - * @returns A CallRequest instance with the contract address, caller context, and the hash of the call stack item. - */ - toCallRequest() { - const item = this.toPublicCallStackItem(); - const callerContractAddress = this.callContext.msgSender; - const callerContext = this.callContext.isDelegateCall - ? new CallerContext(this.callContext.msgSender, this.callContext.storageContractAddress) - : CallerContext.empty(); - return new CallRequest(item.hash(), callerContractAddress, callerContext); - } - - /** - * Returns the hash of the arguments for this request. - * @returns Hash of the arguments for this request. - */ - getArgsHash() { - return computeVarArgsHash(this.args); - } -} diff --git a/yarn-project/circuits.js/src/structs/read_request_membership_witness.test.ts b/yarn-project/circuits.js/src/structs/read_request_membership_witness.test.ts deleted file mode 100644 index ebda8f78924c..000000000000 --- a/yarn-project/circuits.js/src/structs/read_request_membership_witness.test.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { makeReadRequestMembershipWitness } from '../tests/factories.js'; -import { ReadRequestMembershipWitness } from './read_request_membership_witness.js'; - -describe('ReadRequestMembershipWitness', () => { - it('Data after serialization and deserialization is equal to the original', () => { - const original = makeReadRequestMembershipWitness(0); - const buf = original.toBuffer(); - const afterSerialization = ReadRequestMembershipWitness.fromBuffer(buf); - expect(original).toEqual(afterSerialization); - }); -}); diff --git a/yarn-project/circuits.js/src/structs/rollup/append_only_tree_snapshot.ts b/yarn-project/circuits.js/src/structs/rollup/append_only_tree_snapshot.ts deleted file mode 100644 index 5bc2aaa19c83..000000000000 --- a/yarn-project/circuits.js/src/structs/rollup/append_only_tree_snapshot.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { Fr } from '@aztec/foundation/fields'; -import { BufferReader } from '@aztec/foundation/serialize'; - -import { serializeToBuffer } from '../../utils/serialize.js'; -import { STRING_ENCODING, UInt32 } from '../shared.js'; - -/** - * Snapshot of an append only tree. - * - * Used in circuits to verify that tree insertions are performed correctly. - */ -export class AppendOnlyTreeSnapshot { - constructor( - /** - * Root of the append only tree when taking the snapshot. - */ - public root: Fr, - /** - * Index of the next available leaf in the append only tree. - * - * Note: We include the next available leaf index in the snapshot so that the snapshot can be used to verify that - * the insertion was performed at the correct place. If we only verified tree root then it could happen that - * some leaves would get overwritten and the tree root check would still pass. - * TLDR: We need to store the next available leaf index to ensure that the "append only" property was - * preserved when verifying state transitions. - */ - public nextAvailableLeafIndex: UInt32, - ) {} - - toBuffer() { - return serializeToBuffer(this.root, this.nextAvailableLeafIndex); - } - - toString(): string { - return this.toBuffer().toString(STRING_ENCODING); - } - - static fromBuffer(buffer: Buffer | BufferReader): AppendOnlyTreeSnapshot { - const reader = BufferReader.asReader(buffer); - return new AppendOnlyTreeSnapshot(Fr.fromBuffer(reader), reader.readNumber()); - } - - static fromString(str: string): AppendOnlyTreeSnapshot { - return AppendOnlyTreeSnapshot.fromBuffer(Buffer.from(str, STRING_ENCODING)); - } - - static empty() { - return new AppendOnlyTreeSnapshot(Fr.ZERO, 0); - } -} diff --git a/yarn-project/circuits.js/src/structs/rollup/merge_rollup.ts b/yarn-project/circuits.js/src/structs/rollup/merge_rollup.ts deleted file mode 100644 index 2db17d911a29..000000000000 --- a/yarn-project/circuits.js/src/structs/rollup/merge_rollup.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { serializeToBuffer } from '../../utils/serialize.js'; -import { PreviousRollupData } from './previous_rollup_data.js'; - -/** - * Represents inputs of the merge rollup circuit. - */ -export class MergeRollupInputs { - constructor( - /** - * Previous rollup data from the 2 merge or base rollup circuits that preceded this merge rollup circuit. - */ - public previousRollupData: [PreviousRollupData, PreviousRollupData], - ) {} - - toBuffer() { - return serializeToBuffer(this.previousRollupData); - } -} diff --git a/yarn-project/circuits.js/src/structs/shared.ts b/yarn-project/circuits.js/src/structs/shared.ts deleted file mode 100644 index 449e1189a040..000000000000 --- a/yarn-project/circuits.js/src/structs/shared.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { Bufferable, serializeToBuffer } from '../utils/serialize.js'; - -/** - * Implementation of a vector. Matches how we are serializing and deserializing vectors in cpp (length in the first position, followed by the items). - */ -export class Vector { - constructor( - /** - * Items in the vector. - */ - public items: T[], - ) {} - - toBuffer() { - return serializeToBuffer(this.items.length, this.items); - } - - toFriendlyJSON() { - return this.items; - } -} - -/** - * A type alias for a 32-bit unsigned integer. - */ -export type UInt32 = number; - -/** - * CircuitType replaces ComposerType for now. When using Plonk, CircuitType is equivalent to the information of the proving system that will be used - * to construct a proof. In the future Aztec zk stack, more information must be specified (e.g., the curve over which circuits are constructed; - * Plonk vs Honk; zk-SNARK or just SNARK; etc). - */ -export enum CircuitType { - STANDARD = 0, - ULTRA = 1, -} - -/** - * Rollup types. - */ -export enum RollupTypes { - Base = 0, - Merge = 1, - Root = 2, -} - -/** - * String encoding of serialized buffer data - */ -export const STRING_ENCODING: BufferEncoding = 'hex'; diff --git a/yarn-project/circuits.js/src/structs/tx_request.ts b/yarn-project/circuits.js/src/structs/tx_request.ts deleted file mode 100644 index 5e251120e04e..000000000000 --- a/yarn-project/circuits.js/src/structs/tx_request.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { AztecAddress } from '@aztec/foundation/aztec-address'; -import { Fr } from '@aztec/foundation/fields'; -import { BufferReader } from '@aztec/foundation/serialize'; - -import { FieldsOf } from '../utils/jsUtils.js'; -import { serializeToBuffer } from '../utils/serialize.js'; -import { FunctionData } from './function_data.js'; -import { TxContext } from './tx_context.js'; - -/** - * Transaction request. - * @see cpp/src/aztec3/circuits/abis/tx_request.hpp. - */ -export class TxRequest { - constructor( - /** - * Sender. - */ - public origin: AztecAddress, - /** - * Function data representing the function to call. - */ - public functionData: FunctionData, - /** - * Pedersen hash of function arguments. - */ - public argsHash: Fr, - /** - * Transaction context. - */ - public txContext: TxContext, - ) {} - - static getFields(fields: FieldsOf) { - return [fields.origin, fields.functionData, fields.argsHash, fields.txContext] as const; - } - - static from(fields: FieldsOf): TxRequest { - return new TxRequest(...TxRequest.getFields(fields)); - } - - /** - * Serialize as a buffer. - * @returns The buffer. - */ - toBuffer() { - const fields = TxRequest.getFields(this); - return serializeToBuffer([...fields]); - } - - /** - * Deserializes from a buffer or reader, corresponding to a write in cpp. - * @param buffer - Buffer to read from. - * @returns The deserialized TxRequest object. - */ - static fromBuffer(buffer: Buffer | BufferReader): TxRequest { - const reader = BufferReader.asReader(buffer); - return new TxRequest( - reader.readObject(AztecAddress), - reader.readObject(FunctionData), - Fr.fromBuffer(reader), - reader.readObject(TxContext), - ); - } -} diff --git a/yarn-project/circuits.js/src/structs/verification_key.test.ts b/yarn-project/circuits.js/src/structs/verification_key.test.ts deleted file mode 100644 index 7dd17b375dca..000000000000 --- a/yarn-project/circuits.js/src/structs/verification_key.test.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { VerificationKey } from './verification_key.js'; - -describe('structs/verification_key', () => { - // The VK below was grabbed from the Aztec.nr contract artifact child_contract.json - it(`can deserialize vk built by noir`, () => { - const serialized = `0000000200000800000000740000000f00000003515f3109623eb3c25aa5b16a1a79fd558bac7a7ce62c4560a8c537c77ce80dd339128d1d37b6582ee9e6df9567efb64313471dfa18f520f9ce53161b50dbf7731bc5f900000003515f322bc4cce83a486a92c92fd59bd84e0f92595baa639fc2ed86b00ffa0dfded2a092a669a3bdb7a273a015eda494457cc7ed5236f26cee330c290d45a33b9daa94800000003515f332729426c008c085a81bd34d8ef12dd31e80130339ef99d50013a89e4558eee6d0fa4ffe2ee7b7b62eb92608b2251ac31396a718f9b34978888789042b790a30100000003515f342be6b6824a913eb7a57b03cb1ee7bfb4de02f2f65fe8a4e97baa7766ddb353a82a8a25c49dc63778cd9fe96173f12a2bc77f3682f4c4448f98f1df82c75234a100000003515f351f85760d6ab567465aadc2f180af9eae3800e6958fec96aef53fd8a7b195d7c000c6267a0dd5cfc22b3fe804f53e266069c0e36f51885baec1e7e67650c62e170000000c515f41524954484d455449430d9d0f8ece2aa12012fa21e6e5c859e97bd5704e5c122064a66051294bc5e04213f61f54a0ebdf6fee4d4a6ecf693478191de0c2899bcd8e86a636c8d3eff43400000003515f43224a99d02c86336737c8dd5b746c40d2be6aead8393889a76a18d664029096e90f7fe81adcc92a74350eada9622ac453f49ebac24a066a1f83b394df54dfa0130000000c515f46495845445f42415345060e8a013ed289c2f9fd7473b04f6594b138ddb4b4cf6b901622a14088f04b8d2c83ff74fce56e3d5573b99c7b26d85d5046ce0c6559506acb7a675e7713eb3a00000007515f4c4f4749430721a91cb8da4b917e054f72147e1760cfe0ef3d45090ac0f4961d84ec1996961a25e787b26bd8b50b1a99450f77a424a83513c2b33af268cd253b0587ff50c700000003515f4d05dbd8623b8652511e1eb38d38887a69eceb082f807514f09e127237c5213b401b9325b48c6c225968002318095f89d0ef9cf629b2b7f0172e03bc39aacf6ed800000007515f52414e474504b57a3805e41df328f5ca9aefa40fad5917391543b7b65c6476e60b8f72e9ad07c92f3b3e11c8feae96dedc4b14a6226ef3201244f37cfc1ee5b96781f48d2b000000075349474d415f3125001d1954a18571eaa007144c5a567bb0d2be4def08a8be918b8c05e3b27d312c59ed41e09e144eab5de77ca89a2fd783be702a47c951d3112e3de02ce6e47c000000075349474d415f3223994e6a23618e60fa01c449a7ab88378709197e186d48d604bfb6931ffb15ad11c5ec7a0700570f80088fd5198ab5d5c227f2ad2a455a6edeec024156bb7beb000000075349474d415f3300cda5845f23468a13275d18bddae27c6bb189cf9aa95b6a03a0cb6688c7e8d829639b45cf8607c525cc400b55ebf90205f2f378626dc3406cc59b2d1b474fba000000075349474d415f342d299e7928496ea2d37f10b43afd6a80c90a33b483090d18069ffa275eedb2fc2f82121e8de43dc036d99b478b6227ceef34248939987a19011f065d8b5cef5c0000000010000000000000000100000002000000030000000400000005000000060000000700000008000000090000000a0000000b0000000c0000000d0000000e0000000f`; - const vk = VerificationKey.fromBuffer(Buffer.from(serialized, 'hex')); - expect(vk.circuitSize).toBeGreaterThan(100); - }); -}); diff --git a/yarn-project/circuits.js/src/structs/verification_key.ts b/yarn-project/circuits.js/src/structs/verification_key.ts deleted file mode 100644 index fbd384444588..000000000000 --- a/yarn-project/circuits.js/src/structs/verification_key.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { BufferReader } from '@aztec/foundation/serialize'; - -import times from 'lodash.times'; - -import { serializeToBuffer } from '../utils/serialize.js'; -import { Fq } from './index.js'; -import { CircuitType } from './shared.js'; - -/** - * Curve data. - */ -export class G1AffineElement { - /** - * Element's x coordinate. - */ - public x: Fq; - /** - * Element's y coordinate. - */ - public y: Fq; - - constructor(x: Fq | bigint, y: Fq | bigint) { - this.x = typeof x === 'bigint' ? new Fq(x) : x; - this.y = typeof y === 'bigint' ? new Fq(y) : y; - } - /** - * Serialize as a buffer. - * @returns The buffer. - */ - toBuffer() { - return serializeToBuffer(this.x, this.y); - } - - /** - * Deserializes from a buffer or reader, corresponding to a write in cpp. - * @param buffer - Buffer or BufferReader to read from. - * @returns The G1AffineElement. - */ - static fromBuffer(buffer: Buffer | BufferReader): G1AffineElement { - const reader = BufferReader.asReader(buffer); - return new G1AffineElement(Fq.fromBuffer(reader), Fq.fromBuffer(reader)); - } -} - -/** - * Used store and serialize a key-value map of commitments where key is the name of the commitment and value is - * the commitment itself. The name can be e.g. Q_1, Q_2, SIGMA_1 etc. - */ -export class CommitmentMap { - constructor( - /** - * An object used to store the commitments. - */ - public record: { [name: string]: G1AffineElement }, - ) {} - - /** - * Serialize as a buffer. - * @returns The buffer. - */ - toBuffer() { - const values = Object.entries(this.record); - return serializeToBuffer(values.length, ...values.flat()); - } - - /** - * Deserializes from a buffer or reader, corresponding to a write in cpp. - * @param buffer - Buffer or BufferReader to read from. - * @returns The CommitmentMap. - */ - static fromBuffer(buffer: Buffer | BufferReader): CommitmentMap { - const reader = BufferReader.asReader(buffer); - return new CommitmentMap(reader.readMap(G1AffineElement)); - } -} - -/** - * Kate commitment key object for verifying pairing equations. - * @see proof_system/verification_key/verification_key.hpp - */ -export class VerificationKey { - constructor( - /** - * For Plonk, this is equivalent to the proving system used to prove and verify. - */ - public circuitType: CircuitType, - /** - * The number of gates in this circuit. - */ - public circuitSize: number, - /** - * The number of public inputs in this circuit. - */ - public numPublicInputs: number, - /** - * The commitments for this circuit. - */ - public commitments: Record, - /** - * Contains a recursive proof? - */ - public containsRecursiveProof: boolean, - /** - * Recursion stack. - */ - public recursiveProofPublicInputIndices: number[], - ) {} - - /** - * Serialize as a buffer. - * @returns The buffer. - */ - toBuffer() { - return serializeToBuffer( - this.circuitType, - this.circuitSize, - this.numPublicInputs, - new CommitmentMap(this.commitments), - this.containsRecursiveProof, - serializeToBuffer(this.recursiveProofPublicInputIndices.length, this.recursiveProofPublicInputIndices), - ); - } - - /** - * Deserializes from a buffer or reader, corresponding to a write in cpp. - * @param buffer - Buffer to read from. - * @returns The VerificationKey. - */ - static fromBuffer(buffer: Buffer | BufferReader): VerificationKey { - const reader = BufferReader.asReader(buffer); - return new VerificationKey( - reader.readNumber(), - reader.readNumber(), - reader.readNumber(), - reader.readObject(CommitmentMap).record, - reader.readBoolean(), - reader.readNumberVector(), - ); - } - - /** - * Builds a fake verification key that should be accepted by circuits. - * @returns A fake verification key. - */ - static makeFake(): VerificationKey { - return new VerificationKey( - CircuitType.ULTRA, // This is entirely arbitrary - 2048, - 116, - {}, // Empty set of commitments - false, - times(16, i => i), - ); - } -} diff --git a/yarn-project/circuits.js/src/tests/factories.ts b/yarn-project/circuits.js/src/tests/factories.ts deleted file mode 100644 index 3df6e72dccd1..000000000000 --- a/yarn-project/circuits.js/src/tests/factories.ts +++ /dev/null @@ -1,968 +0,0 @@ -import { AztecAddress } from '@aztec/foundation/aztec-address'; -import { EthAddress } from '@aztec/foundation/eth-address'; -import { numToUInt32BE } from '@aztec/foundation/serialize'; - -import { SchnorrSignature } from '../barretenberg/index.js'; -import { - ARGS_LENGTH, - AggregationObject, - AppendOnlyTreeSnapshot, - BaseOrMergeRollupPublicInputs, - BaseRollupInputs, - CONTRACT_SUBTREE_SIBLING_PATH_LENGTH, - CONTRACT_TREE_HEIGHT, - CallContext, - CallRequest, - CallerContext, - CircuitType, - CombinedAccumulatedData, - CombinedConstantData, - ConstantRollupData, - ContractDeploymentData, - ContractStorageRead, - ContractStorageUpdateRequest, - FUNCTION_TREE_HEIGHT, - FinalAccumulatedData, - Fq, - Fr, - FunctionData, - FunctionSelector, - G1AffineElement, - HISTORIC_BLOCKS_TREE_HEIGHT, - HistoricBlockData, - KERNELS_PER_BASE_ROLLUP, - KernelCircuitPublicInputs, - L1_TO_L2_MSG_SUBTREE_SIBLING_PATH_LENGTH, - MAX_NEW_COMMITMENTS_PER_CALL, - MAX_NEW_COMMITMENTS_PER_TX, - MAX_NEW_CONTRACTS_PER_TX, - MAX_NEW_L2_TO_L1_MSGS_PER_CALL, - MAX_NEW_L2_TO_L1_MSGS_PER_TX, - MAX_NEW_NULLIFIERS_PER_BASE_ROLLUP, - MAX_NEW_NULLIFIERS_PER_CALL, - MAX_NEW_NULLIFIERS_PER_TX, - MAX_OPTIONALLY_REVEALED_DATA_LENGTH_PER_TX, - MAX_PENDING_READ_REQUESTS_PER_CALL, - MAX_PENDING_READ_REQUESTS_PER_TX, - MAX_PRIVATE_CALL_STACK_LENGTH_PER_CALL, - MAX_PRIVATE_CALL_STACK_LENGTH_PER_TX, - MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL, - MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX, - MAX_PUBLIC_DATA_READS_PER_BASE_ROLLUP, - MAX_PUBLIC_DATA_READS_PER_CALL, - MAX_PUBLIC_DATA_READS_PER_TX, - MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_BASE_ROLLUP, - MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL, - MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, - MAX_READ_REQUESTS_PER_CALL, - MAX_READ_REQUESTS_PER_TX, - MembershipWitness, - MergeRollupInputs, - NOTE_HASH_SUBTREE_SIBLING_PATH_LENGTH, - NOTE_HASH_TREE_HEIGHT, - NULLIFIER_SUBTREE_SIBLING_PATH_LENGTH, - NULLIFIER_TREE_HEIGHT, - NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP, - NUM_FIELDS_PER_SHA256, - NewContractData, - NullifierLeafPreimage, - OptionallyRevealedData, - PUBLIC_DATA_TREE_HEIGHT, - Point, - PreviousKernelData, - PreviousRollupData, - PrivateCallData, - PrivateCallStackItem, - PrivateCircuitPublicInputs, - PrivateKernelInputsInit, - PrivateKernelInputsInner, - PrivateKernelPublicInputsFinal, - Proof, - PublicCallData, - PublicCallRequest, - PublicCallStackItem, - PublicCircuitPublicInputs, - PublicDataRead, - PublicDataUpdateRequest, - PublicKernelInputs, - RETURN_VALUES_LENGTH, - ROLLUP_VK_TREE_HEIGHT, - ReadRequestMembershipWitness, - RollupTypes, - RootRollupInputs, - RootRollupPublicInputs, - TxContext, - TxRequest, - VK_TREE_HEIGHT, - VerificationKey, - WitnessedPublicCallData, - makeHalfFullTuple, - makeTuple, - range, -} from '../index.js'; -import { GlobalVariables } from '../structs/global_variables.js'; - -/** - * Creates an arbitrary tx context with the given seed. - * @param seed - The seed to use for generating the tx context. - * @returns A tx context. - */ -export function makeTxContext(seed: number): TxContext { - // @todo @LHerskind should probably take value for chainId as it will be verified later. - // @todo @LHerskind should probably take value for version as it will be verified later. - return new TxContext(false, false, true, makeContractDeploymentData(seed), Fr.ZERO, Fr.ZERO); -} - -/** - * Creates an arbitrary combined historic tree roots object from the given seed. - * Note: "Combined" indicates that it's the combined output of both private and public circuit flows. - * @param seed - The seed to use for generating the combined historic tree roots. - * @returns A combined historic tree roots object. - */ -export function makeHistoricBlockData(seed: number): HistoricBlockData { - return new HistoricBlockData( - fr(seed), - fr(seed + 1), - fr(seed + 2), - fr(seed + 3), - fr(seed + 4), - fr(seed + 5), - fr(seed + 6), - fr(seed + 7), - ); -} - -/** - * Creates arbitrary constant data with the given seed. - * @param seed - The seed to use for generating the constant data. - * @returns A constant data object. - */ -export function makeConstantData(seed = 1): CombinedConstantData { - return new CombinedConstantData(makeHistoricBlockData(seed), makeTxContext(seed + 4)); -} - -/** - * Creates arbitrary selector from the given seed. - * @param seed - The seed to use for generating the selector. - * @returns A selector. - */ -export function makeSelector(seed: number): FunctionSelector { - return new FunctionSelector(seed); -} - -/** - * Creates arbitrary public data update request. - * @param seed - The seed to use for generating the public data update request. - * @returns A public data update request. - */ -export function makePublicDataUpdateRequest(seed = 1): PublicDataUpdateRequest { - return new PublicDataUpdateRequest(fr(seed), fr(seed + 1), fr(seed + 2)); -} - -/** - * Creates empty public data update request. - * @returns An empty public data update request. - */ -export function makeEmptyPublicDataUpdateRequest(): PublicDataUpdateRequest { - return new PublicDataUpdateRequest(fr(0), fr(0), fr(0)); -} - -/** - * Creates arbitrary public data read. - * @param seed - The seed to use for generating the public data read. - * @returns A public data read. - */ -export function makePublicDataRead(seed = 1): PublicDataRead { - return new PublicDataRead(fr(seed), fr(seed + 1)); -} - -/** - * Creates empty public data read. - * @returns An empty public data read. - */ -export function makeEmptyPublicDataRead(): PublicDataRead { - return new PublicDataRead(fr(0), fr(0)); -} - -/** - * Creates arbitrary contract storage update request. - * @param seed - The seed to use for generating the contract storage update request. - * @returns A contract storage update request. - */ -export function makeContractStorageUpdateRequest(seed = 1): ContractStorageUpdateRequest { - return new ContractStorageUpdateRequest(fr(seed), fr(seed + 1), fr(seed + 2)); -} - -/** - * Creates arbitrary contract storage read. - * @param seed - The seed to use for generating the contract storage read. - * @returns A contract storage read. - */ -export function makeContractStorageRead(seed = 1): ContractStorageRead { - return new ContractStorageRead(fr(seed), fr(seed + 1)); -} - -/** - * Creates arbitrary accumulated data. - * @param seed - The seed to use for generating the accumulated data. - * @returns An accumulated data. - */ -export function makeAccumulatedData(seed = 1, full = false): CombinedAccumulatedData { - const tupleGenerator = full ? makeTuple : makeHalfFullTuple; - - return new CombinedAccumulatedData( - makeAggregationObject(seed), - tupleGenerator(MAX_READ_REQUESTS_PER_TX, fr, seed + 0x80), - tupleGenerator(MAX_PENDING_READ_REQUESTS_PER_TX, fr, seed + 0x80), - tupleGenerator(MAX_NEW_COMMITMENTS_PER_TX, fr, seed + 0x100), - tupleGenerator(MAX_NEW_NULLIFIERS_PER_TX, fr, seed + 0x200), - tupleGenerator(MAX_NEW_NULLIFIERS_PER_TX, fr, seed + 0x300), - tupleGenerator(MAX_PRIVATE_CALL_STACK_LENGTH_PER_TX, makeCallRequest, seed + 0x400), - tupleGenerator(MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX, makeCallRequest, seed + 0x500), - tupleGenerator(MAX_NEW_L2_TO_L1_MSGS_PER_TX, fr, seed + 0x600), - tupleGenerator(2, fr, seed + 0x700), // encrypted logs hash - tupleGenerator(2, fr, seed + 0x800), // unencrypted logs hash - fr(seed + 0x900), // encrypted_log_preimages_length - fr(seed + 0xa00), // unencrypted_log_preimages_length - tupleGenerator(MAX_NEW_CONTRACTS_PER_TX, makeNewContractData, seed + 0xb00), - tupleGenerator(MAX_OPTIONALLY_REVEALED_DATA_LENGTH_PER_TX, makeOptionallyRevealedData, seed + 0xc00), - tupleGenerator(MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, makePublicDataUpdateRequest, seed + 0xd00), - tupleGenerator(MAX_PUBLIC_DATA_READS_PER_TX, makePublicDataRead, seed + 0xe00), - ); -} - -/** - * Creates arbitrary final accumulated data. - * @param seed - The seed to use for generating the final accumulated data. - * @returns A final accumulated data. - */ -export function makeFinalAccumulatedData(seed = 1, full = false): FinalAccumulatedData { - const tupleGenerator = full ? makeTuple : makeHalfFullTuple; - - return new FinalAccumulatedData( - makeAggregationObject(seed), - tupleGenerator(MAX_NEW_COMMITMENTS_PER_TX, fr, seed + 0x100), - tupleGenerator(MAX_NEW_NULLIFIERS_PER_TX, fr, seed + 0x200), - tupleGenerator(MAX_NEW_NULLIFIERS_PER_TX, fr, seed + 0x300), - tupleGenerator(MAX_PRIVATE_CALL_STACK_LENGTH_PER_TX, makeCallRequest, seed + 0x400), - tupleGenerator(MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX, makeCallRequest, seed + 0x500), - tupleGenerator(MAX_NEW_L2_TO_L1_MSGS_PER_TX, fr, seed + 0x600), - tupleGenerator(2, fr, seed + 0x700), // encrypted logs hash - tupleGenerator(2, fr, seed + 0x800), // unencrypted logs hash - fr(seed + 0x900), // encrypted_log_preimages_length - fr(seed + 0xa00), // unencrypted_log_preimages_length - tupleGenerator(MAX_NEW_CONTRACTS_PER_TX, makeNewContractData, seed + 0xb00), - tupleGenerator(MAX_OPTIONALLY_REVEALED_DATA_LENGTH_PER_TX, makeOptionallyRevealedData, seed + 0xc00), - ); -} - -/** - * Creates arbitrary contract data. - * @param seed - The seed to use for generating the contract data. - * @returns A contract data. - */ -export function makeNewContractData(seed = 1): NewContractData { - return new NewContractData(makeAztecAddress(seed), makeEthAddress(seed + 1), fr(seed + 2)); -} - -/** - * Creates arbitrary optionally revealed data. - * @param seed - The seed to use for generating the optionally revealed data. - * @returns An optionally revealed data. - */ -export function makeOptionallyRevealedData(seed = 1): OptionallyRevealedData { - return new OptionallyRevealedData( - fr(seed), - new FunctionData(makeSelector(seed + 1), false, true, true), - fr(seed + 2), - makeEthAddress(seed + 3), - true, - false, - true, - false, - ); -} - -/** - * Creates arbitrary aggregation object. - * @param seed - The seed to use for generating the aggregation object. - * @returns An aggregation object. - */ -export function makeAggregationObject(seed = 1): AggregationObject { - return new AggregationObject( - new G1AffineElement(new Fq(BigInt(seed)), new Fq(BigInt(seed + 1))), - new G1AffineElement(new Fq(BigInt(seed + 0x100)), new Fq(BigInt(seed + 0x101))), - makeTuple(4, fr, seed + 2), - range(6, seed + 6), - ); -} - -/** - * Creates arbitrary call context. - * @param seed - The seed to use for generating the call context. - * @param storageContractAddress - The storage contract address set on the call context. - * @returns A call context. - */ -export function makeCallContext(seed = 0, storageContractAddress = makeAztecAddress(seed + 1)): CallContext { - return new CallContext( - makeAztecAddress(seed), - storageContractAddress, - makeEthAddress(seed + 2), - makeSelector(seed + 3), - false, - false, - false, - ); -} - -/** - * Creates arbitrary public circuit public inputs. - * @param seed - The seed to use for generating the public circuit public inputs. - * @param storageContractAddress - The storage contract address set on the call context. - * @returns Public circuit public inputs. - */ -export function makePublicCircuitPublicInputs( - seed = 0, - storageContractAddress?: AztecAddress, - full = false, -): PublicCircuitPublicInputs { - const tupleGenerator = full ? makeTuple : makeHalfFullTuple; - - return new PublicCircuitPublicInputs( - makeCallContext(seed, storageContractAddress), - fr(seed + 0x100), - tupleGenerator(RETURN_VALUES_LENGTH, fr, seed + 0x200), - tupleGenerator(MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL, makeContractStorageUpdateRequest, seed + 0x400), - tupleGenerator(MAX_PUBLIC_DATA_READS_PER_CALL, makeContractStorageRead, seed + 0x500), - tupleGenerator(MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL, fr, seed + 0x600), - tupleGenerator(MAX_NEW_COMMITMENTS_PER_CALL, fr, seed + 0x700), - tupleGenerator(MAX_NEW_NULLIFIERS_PER_CALL, fr, seed + 0x800), - tupleGenerator(MAX_NEW_L2_TO_L1_MSGS_PER_CALL, fr, seed + 0x900), - tupleGenerator(2, fr, seed + 0x901), - fr(seed + 0x902), - makeHistoricBlockData(seed + 0xa00), - makeAztecAddress(seed + 0xb01), - ); -} - -/** - * Creates arbitrary kernel circuit public inputs. - * @param seed - The seed to use for generating the kernel circuit public inputs. - * @returns Kernel circuit public inputs. - */ -export function makeKernelPublicInputs(seed = 1, fullAccumulatedData = true): KernelCircuitPublicInputs { - return new KernelCircuitPublicInputs( - makeAccumulatedData(seed, fullAccumulatedData), - makeConstantData(seed + 0x100), - true, - ); -} - -/** - * Creates arbitrary final ordering kernel circuit public inputs. - * @param seed - The seed to use for generating the final ordering kernel circuit public inputs. - * @returns Final ordering kernel circuit public inputs. - */ -export function makePrivateKernelPublicInputsFinal(seed = 1): PrivateKernelPublicInputsFinal { - return new PrivateKernelPublicInputsFinal(makeFinalAccumulatedData(seed, true), makeConstantData(seed + 0x100)); -} - -/** - * Creates a public call request for testing. - * @param seed - The seed. - * @returns Public call request. - */ -export function makePublicCallRequest(seed = 1): PublicCallRequest { - return new PublicCallRequest( - makeAztecAddress(seed), - new FunctionData(makeSelector(seed + 0x1), false, false, false), - makeCallContext(seed + 0x2, makeAztecAddress(seed)), - makeTuple(ARGS_LENGTH, fr, seed + 0x10), - ); -} - -/** - * Creates a uint8 vector of a given size filled with a given value. - * @param size - The size of the vector. - * @param fill - The value to fill the vector with. - * @returns A uint8 vector. - */ -export function makeDynamicSizeBuffer(size: number, fill: number) { - return new Proof(Buffer.alloc(size, fill)); -} - -/** - * Creates arbitrary/mocked membership witness where the sibling paths is an array of fields in an ascending order starting from `start`. - * @param size - The size of the membership witness. - * @param start - The start of the membership witness. - * @returns A membership witness. - */ -export function makeMembershipWitness(size: N, start: number): MembershipWitness { - return new MembershipWitness(size, BigInt(start), makeTuple(size, fr, start)); -} - -/** - * Creates arbitrary/mocked membership witness where the sibling paths is an array of fields in an ascending order starting from `start`. - * @param start - The start of the membership witness. - * @returns A non-transient read request membership witness. - */ -export function makeReadRequestMembershipWitness(start: number): ReadRequestMembershipWitness { - return new ReadRequestMembershipWitness( - new Fr(start), - makeTuple(NOTE_HASH_TREE_HEIGHT, fr, start + 1), - false, - new Fr(0), - ); -} - -/** - * Creates empty membership witness where the sibling paths is an array of fields filled with zeros. - * @param start - The start of the membership witness. - * @returns Non-transient empty read request membership witness. - */ -export function makeEmptyReadRequestMembershipWitness(): ReadRequestMembershipWitness { - return new ReadRequestMembershipWitness(new Fr(0), makeTuple(NOTE_HASH_TREE_HEIGHT, Fr.zero), false, new Fr(0)); -} - -/** - * Creates arbitrary/mocked verification key. - * @returns A verification key. - */ -export function makeVerificationKey(): VerificationKey { - return new VerificationKey( - CircuitType.STANDARD, - 101, // arbitrary - 102, // arbitrary - { - A: new G1AffineElement(new Fq(0x200), new Fq(0x300)), - }, - /* recursive proof */ true, - range(5, 400), - ); -} - -/** - * Creates an arbitrary point in a curve. - * @param seed - Seed to generate the point values. - * @returns A point. - */ -export function makePoint(seed = 1): Point { - return new Point(fr(seed), fr(seed + 1)); -} - -/** - * Makes arbitrary previous kernel data. - * @param seed - The seed to use for generating the previous kernel data. - * @param kernelPublicInputs - The kernel public inputs to use for generating the previous kernel data. - * @returns A previous kernel data. - */ -export function makePreviousKernelData(seed = 1, kernelPublicInputs?: KernelCircuitPublicInputs): PreviousKernelData { - return new PreviousKernelData( - kernelPublicInputs ?? makeKernelPublicInputs(seed, true), - new Proof(Buffer.alloc(16, seed + 0x80)), - makeVerificationKey(), - 0x42, - makeTuple(VK_TREE_HEIGHT, fr, 0x1000), - ); -} - -/** - * Makes arbitrary proof. - * @param seed - The seed to use for generating/mocking the proof. - * @returns A proof. - */ -export function makeProof(seed = 1) { - return makeDynamicSizeBuffer(16, seed); -} - -/** - * Makes arbitrary private kernel inputs - initial call. - * @param seed - The seed to use for generating the private kernel inputs. - * @returns Private kernel inputs. - */ -export function makePrivateKernelInputsInit(seed = 1): PrivateKernelInputsInit { - return new PrivateKernelInputsInit(makeTxRequest(seed), makePrivateCallData(seed + 0x1000)); -} - -/** - * Makes arbitrary private kernel inputs - inner call. - * @param seed - The seed to use for generating the private kernel inputs. - * @returns Private kernel inputs. - */ -export function makePrivateKernelInputsInner(seed = 1): PrivateKernelInputsInner { - return new PrivateKernelInputsInner(makePreviousKernelData(seed), makePrivateCallData(seed + 0x1000)); -} - -/** - * Makes arbitrary call stack item. - * @param seed - The seed to use for generating the call stack item. - * @returns A call stack item. - */ -export function makeCallerContext(seed = 1): CallerContext { - return new CallerContext(makeAztecAddress(seed), makeAztecAddress(seed + 0x1)); -} - -/** - * Makes arbitrary call stack item. - * @param seed - The seed to use for generating the call stack item. - * @returns A call stack item. - */ -export function makeCallRequest(seed = 1): CallRequest { - return new CallRequest(fr(seed), makeAztecAddress(seed + 0x1), makeCallerContext(seed + 0x2)); -} - -/** - * Makes arbitrary public call stack item. - * @param seed - The seed to use for generating the public call stack item. - * @returns A public call stack item. - */ -export function makePublicCallStackItem(seed = 1, full = false): PublicCallStackItem { - const callStackItem = new PublicCallStackItem( - makeAztecAddress(seed), - // in the public kernel, function can't be a constructor or private - new FunctionData(makeSelector(seed + 0x1), false, false, false), - makePublicCircuitPublicInputs(seed + 0x10, undefined, full), - false, - ); - callStackItem.publicInputs.callContext.storageContractAddress = callStackItem.contractAddress; - return callStackItem; -} - -/** - * Makes arbitrary public call data. - * @param seed - The seed to use for generating the public call data. - * @returns A public call data. - */ -export function makePublicCallData(seed = 1, full = false): PublicCallData { - const publicCallData = new PublicCallData( - makePublicCallStackItem(seed, full), - makeTuple(MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL, makeCallRequest, seed + 0x300), - makeProof(), - fr(seed + 1), - fr(seed + 2), - ); - - return publicCallData; -} - -/** - * Makes arbitrary witnessed public call data. - * @param seed - The seed to use for generating the witnessed public call data. - * @returns A witnessed public call data. - */ -export function makeWitnessedPublicCallData(seed = 1): WitnessedPublicCallData { - return new WitnessedPublicCallData( - makePublicCallData(seed), - range(MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, seed + 0x100).map(x => - makeMembershipWitness(PUBLIC_DATA_TREE_HEIGHT, x), - ), - makeTuple(MAX_PUBLIC_DATA_READS_PER_TX, x => makeMembershipWitness(PUBLIC_DATA_TREE_HEIGHT, x), seed + 0x200), - fr(seed + 0x300), - ); -} - -/** - * Makes arbitrary public kernel inputs. - * @param seed - The seed to use for generating the public kernel inputs. - * @returns Public kernel inputs. - */ -export function makePublicKernelInputs(seed = 1): PublicKernelInputs { - return new PublicKernelInputs(makePreviousKernelData(seed), makePublicCallData(seed + 0x1000)); -} - -/** - * Makes arbitrary public kernel inputs. - * @param seed - The seed to use for generating the public kernel inputs. - * @param tweak - An optional function to tweak the output before computing hashes. - * @returns Public kernel inputs. - */ -export function makePublicKernelInputsWithTweak( - seed = 1, - tweak?: (publicKernelInputs: PublicKernelInputs) => void, -): PublicKernelInputs { - const kernelCircuitPublicInputs = makeKernelPublicInputs(seed, false); - const previousKernel = makePreviousKernelData(seed, kernelCircuitPublicInputs); - const publicCall = makePublicCallData(seed + 0x1000); - const publicKernelInputs = new PublicKernelInputs(previousKernel, publicCall); - if (tweak) { - tweak(publicKernelInputs); - } - // Set the call stack item for this circuit iteration at the top of the call stack - publicKernelInputs.previousKernel.publicInputs.end.publicCallStack[MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX - 1] = - new CallRequest( - publicCall.callStackItem.hash(), - publicCall.callStackItem.publicInputs.callContext.msgSender, - makeCallerContext(seed + 0x100), - ); - return publicKernelInputs; -} - -/** - * Makes arbitrary tx request. - * @param seed - The seed to use for generating the tx request. - * @returns A tx request. - */ -export function makeTxRequest(seed = 1): TxRequest { - return TxRequest.from({ - origin: makeAztecAddress(seed), - functionData: new FunctionData(makeSelector(seed + 0x100), false, true, true), - argsHash: fr(seed + 0x200), - txContext: makeTxContext(seed + 0x400), - }); -} - -/** - * Makes arbitrary private call data. - * @param seed - The seed to use for generating the private call data. - * @returns A private call data. - */ -export function makePrivateCallData(seed = 1): PrivateCallData { - return PrivateCallData.from({ - callStackItem: makePrivateCallStackItem(seed), - privateCallStack: makeTuple(MAX_PRIVATE_CALL_STACK_LENGTH_PER_CALL, makeCallRequest, seed + 0x10), - publicCallStack: makeTuple(MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL, makeCallRequest, seed + 0x20), - proof: new Proof(Buffer.alloc(16).fill(seed + 0x50)), - vk: makeVerificationKey(), - functionLeafMembershipWitness: makeMembershipWitness(FUNCTION_TREE_HEIGHT, seed + 0x30), - contractLeafMembershipWitness: makeMembershipWitness(CONTRACT_TREE_HEIGHT, seed + 0x20), - readRequestMembershipWitnesses: makeTuple( - MAX_READ_REQUESTS_PER_CALL, - makeReadRequestMembershipWitness, - seed + 0x70, - ), - portalContractAddress: makeEthAddress(seed + 0x40).toField(), - acirHash: fr(seed + 0x60), - }); -} - -/** - * Makes arbitrary private call stack item. - * @param seed - The seed to use for generating the private call stack item. - * @returns A private call stack item. - */ -export function makePrivateCallStackItem(seed = 1): PrivateCallStackItem { - return new PrivateCallStackItem( - makeAztecAddress(seed), - new FunctionData(makeSelector(seed + 0x1), false, true, true), - makePrivateCircuitPublicInputs(seed + 0x10), - false, - ); -} - -/** - * Makes arbitrary private circuit public inputs. - * @param seed - The seed to use for generating the private circuit public inputs. - * @returns A private circuit public inputs. - */ -export function makePrivateCircuitPublicInputs(seed = 0): PrivateCircuitPublicInputs { - return PrivateCircuitPublicInputs.from({ - callContext: new CallContext( - makeAztecAddress(seed + 1), - makeAztecAddress(seed + 2), - new EthAddress(numToUInt32BE(seed + 3, /* eth address is 20 bytes */ 20)), - makeSelector(seed + 4), - true, - true, - true, - ), - argsHash: fr(seed + 0x100), - returnValues: makeTuple(RETURN_VALUES_LENGTH, fr, seed + 0x200), - readRequests: makeTuple(MAX_READ_REQUESTS_PER_CALL, fr, seed + 0x300), - pendingReadRequests: makeTuple(MAX_PENDING_READ_REQUESTS_PER_CALL, fr, seed + 0x310), - newCommitments: makeTuple(MAX_NEW_COMMITMENTS_PER_CALL, fr, seed + 0x400), - newNullifiers: makeTuple(MAX_NEW_NULLIFIERS_PER_CALL, fr, seed + 0x500), - nullifiedCommitments: makeTuple(MAX_NEW_NULLIFIERS_PER_CALL, fr, seed + 0x510), - privateCallStackHashes: makeTuple(MAX_PRIVATE_CALL_STACK_LENGTH_PER_CALL, fr, seed + 0x600), - publicCallStackHashes: makeTuple(MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL, fr, seed + 0x700), - newL2ToL1Msgs: makeTuple(MAX_NEW_L2_TO_L1_MSGS_PER_CALL, fr, seed + 0x800), - encryptedLogsHash: makeTuple(NUM_FIELDS_PER_SHA256, fr, seed + 0x900), - unencryptedLogsHash: makeTuple(NUM_FIELDS_PER_SHA256, fr, seed + 0xa00), - encryptedLogPreimagesLength: fr(seed + 0xb00), - unencryptedLogPreimagesLength: fr(seed + 0xc00), - historicBlockData: makeHistoricBlockData(seed + 0xd00), - contractDeploymentData: makeContractDeploymentData(seed + 0xe00), - chainId: fr(seed + 0x1400), - version: fr(seed + 0x1500), - }); -} - -/** - * Makes arbitrary contract deployment data. - * @param seed - The seed to use for generating the contract deployment data. - * @returns A contract deployment data. - */ -export function makeContractDeploymentData(seed = 1) { - return new ContractDeploymentData( - makePoint(seed), - fr(seed + 1), - fr(seed + 2), - fr(seed + 3), - makeEthAddress(seed + 4), - ); -} - -/** - * Makes global variables. - * @param seed - The seed to use for generating the global variables. - * @param blockNumber - The block number to use for generating the global variables. - * If blockNumber is undefined, it will be set to seed + 2. - * @returns Global variables. - */ -export function makeGlobalVariables(seed = 1, blockNumber: number | undefined = undefined): GlobalVariables { - if (blockNumber !== undefined) { - return new GlobalVariables(fr(seed), fr(seed + 1), fr(blockNumber), fr(seed + 3)); - } - return new GlobalVariables(fr(seed), fr(seed + 1), fr(seed + 2), fr(seed + 3)); -} - -/** - * Makes constant base rollup data. - * @param seed - The seed to use for generating the constant base rollup data. - * @param blockNumber - The block number to use for generating the global variables. - * @returns A constant base rollup data. - */ -export function makeConstantBaseRollupData( - seed = 1, - globalVariables: GlobalVariables | undefined = undefined, -): ConstantRollupData { - return ConstantRollupData.from({ - startHistoricBlocksTreeRootsSnapshot: makeAppendOnlyTreeSnapshot(seed + 0x300), - privateKernelVkTreeRoot: fr(seed + 0x401), - publicKernelVkTreeRoot: fr(seed + 0x402), - baseRollupVkHash: fr(seed + 0x403), - mergeRollupVkHash: fr(seed + 0x404), - globalVariables: globalVariables ?? makeGlobalVariables(seed + 0x405), - }); -} - -/** - * Makes arbitrary append only tree snapshot. - * @param seed - The seed to use for generating the append only tree snapshot. - * @returns An append only tree snapshot. - */ -export function makeAppendOnlyTreeSnapshot(seed = 1): AppendOnlyTreeSnapshot { - return new AppendOnlyTreeSnapshot(fr(seed), seed); -} - -/** - * Makes arbitrary eth address. - * @param seed - The seed to use for generating the eth address. - * @returns An eth address. - */ -export function makeEthAddress(seed = 1): EthAddress { - return new EthAddress(Buffer.alloc(20, seed)); -} - -/** - * Creates a buffer of a given size filled with a given value. - * @param size - The size of the buffer to create. - * @param fill - The value to fill the buffer with. - * @returns A buffer of a given size filled with a given value. - */ -export function makeBytes(size = 32, fill = 1): Buffer { - return Buffer.alloc(size, fill); -} - -/** - * Makes arbitrary aztec address. - * @param seed - The seed to use for generating the aztec address. - * @returns An aztec address. - */ -export function makeAztecAddress(seed = 1): AztecAddress { - return new AztecAddress(fr(seed).toBuffer()); -} - -/** - * Makes arbitrary Schnorr signature. - * @param seed - The seed to use for generating the Schnorr signature. - * @returns A Schnorr signature. - */ -export function makeSchnorrSignature(seed = 1): SchnorrSignature { - return new SchnorrSignature(Buffer.alloc(SchnorrSignature.SIZE, seed)); -} - -/** - * Makes arbitrary base or merge rollup circuit public inputs. - * @param seed - The seed to use for generating the base rollup circuit public inputs. - * @param blockNumber - The block number to use for generating the base rollup circuit public inputs. - * @returns A base or merge rollup circuit public inputs. - */ -export function makeBaseOrMergeRollupPublicInputs( - seed = 0, - globalVariables: GlobalVariables | undefined = undefined, -): BaseOrMergeRollupPublicInputs { - return new BaseOrMergeRollupPublicInputs( - RollupTypes.Base, - new Fr(0n), - makeAggregationObject(seed + 0x100), - makeConstantBaseRollupData(seed + 0x200, globalVariables), - makeAppendOnlyTreeSnapshot(seed + 0x300), - makeAppendOnlyTreeSnapshot(seed + 0x400), - makeAppendOnlyTreeSnapshot(seed + 0x500), - makeAppendOnlyTreeSnapshot(seed + 0x600), - makeAppendOnlyTreeSnapshot(seed + 0x700), - makeAppendOnlyTreeSnapshot(seed + 0x800), - fr(seed + 0x900), - fr(seed + 0x1000), - [fr(seed + 0x901), fr(seed + 0x902)], - ); -} - -/** - * Makes arbitrary previous rollup data. - * @param seed - The seed to use for generating the previous rollup data. - * @param globalVariables - The global variables to use when generating the previous rollup data. - * @returns A previous rollup data. - */ -export function makePreviousRollupData( - seed = 0, - globalVariables: GlobalVariables | undefined = undefined, -): PreviousRollupData { - return new PreviousRollupData( - makeBaseOrMergeRollupPublicInputs(seed, globalVariables), - makeDynamicSizeBuffer(16, seed + 0x50), - makeVerificationKey(), - seed + 0x110, - makeMembershipWitness(ROLLUP_VK_TREE_HEIGHT, seed + 0x120), - ); -} - -/** - * Makes root rollup inputs. - * @param seed - The seed to use for generating the root rollup inputs. - * @param blockNumber - The block number to use for generating the root rollup inputs. - * @returns A root rollup inputs. - */ -export function makeRootRollupInputs(seed = 0, globalVariables?: GlobalVariables): RootRollupInputs { - return new RootRollupInputs( - [makePreviousRollupData(seed, globalVariables), makePreviousRollupData(seed + 0x1000, globalVariables)], - makeTuple(NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP, fr, 0x2100), - makeTuple(L1_TO_L2_MSG_SUBTREE_SIBLING_PATH_LENGTH, fr, 0x2100), - makeAppendOnlyTreeSnapshot(seed + 0x2200), - makeAppendOnlyTreeSnapshot(seed + 0x2200), - makeTuple(HISTORIC_BLOCKS_TREE_HEIGHT, fr, 0x2400), - ); -} - -/** - * Makes root rollup public inputs. - * @param seed - The seed to use for generating the root rollup public inputs. - * @param blockNumber - The block number to use for generating the root rollup public inputs. - * if blockNumber is undefined, it will be set to seed + 2. - * @returns A root rollup public inputs. - */ -export function makeRootRollupPublicInputs( - seed = 0, - globalVariables: GlobalVariables | undefined = undefined, -): RootRollupPublicInputs { - return RootRollupPublicInputs.from({ - endAggregationObject: makeAggregationObject(seed), - globalVariables: globalVariables ?? makeGlobalVariables((seed += 0x100)), - startNoteHashTreeSnapshot: makeAppendOnlyTreeSnapshot((seed += 0x100)), - endNoteHashTreeSnapshot: makeAppendOnlyTreeSnapshot((seed += 0x100)), - startNullifierTreeSnapshot: makeAppendOnlyTreeSnapshot((seed += 0x100)), - endNullifierTreeSnapshot: makeAppendOnlyTreeSnapshot((seed += 0x100)), - startContractTreeSnapshot: makeAppendOnlyTreeSnapshot((seed += 0x100)), - endContractTreeSnapshot: makeAppendOnlyTreeSnapshot((seed += 0x100)), - startPublicDataTreeRoot: fr((seed += 0x100)), - endPublicDataTreeRoot: fr((seed += 0x100)), - startTreeOfHistoricNoteHashTreeRootsSnapshot: makeAppendOnlyTreeSnapshot((seed += 0x100)), - endTreeOfHistoricNoteHashTreeRootsSnapshot: makeAppendOnlyTreeSnapshot((seed += 0x100)), - startTreeOfHistoricContractTreeRootsSnapshot: makeAppendOnlyTreeSnapshot((seed += 0x100)), - endTreeOfHistoricContractTreeRootsSnapshot: makeAppendOnlyTreeSnapshot((seed += 0x100)), - startL1ToL2MessagesTreeSnapshot: makeAppendOnlyTreeSnapshot((seed += 0x100)), - endL1ToL2MessagesTreeSnapshot: makeAppendOnlyTreeSnapshot((seed += 0x100)), - startTreeOfHistoricL1ToL2MessagesTreeRootsSnapshot: makeAppendOnlyTreeSnapshot((seed += 0x100)), - endTreeOfHistoricL1ToL2MessagesTreeRootsSnapshot: makeAppendOnlyTreeSnapshot((seed += 0x100)), - startHistoricBlocksTreeSnapshot: makeAppendOnlyTreeSnapshot((seed += 0x100)), - endHistoricBlocksTreeSnapshot: makeAppendOnlyTreeSnapshot((seed += 0x100)), - calldataHash: [new Fr(1n), new Fr(2n)], - l1ToL2MessagesHash: [new Fr(3n), new Fr(4n)], - }); -} - -/** - * Makes arbitrary merge rollup inputs. - * @param seed - The seed to use for generating the merge rollup inputs. - * @returns A merge rollup inputs. - */ -export function makeMergeRollupInputs(seed = 0): MergeRollupInputs { - return new MergeRollupInputs([makePreviousRollupData(seed), makePreviousRollupData(seed + 0x1000)]); -} - -/** - * Makes arbitrary base rollup inputs. - * @param seed - The seed to use for generating the base rollup inputs. - * @returns A base rollup inputs. - */ -export function makeBaseRollupInputs(seed = 0): BaseRollupInputs { - const kernelData = makeTuple(KERNELS_PER_BASE_ROLLUP, x => makePreviousKernelData(seed + (x + 1) * 0x100)); - - const startNoteHashTreeSnapshot = makeAppendOnlyTreeSnapshot(seed + 0x100); - const startNullifierTreeSnapshot = makeAppendOnlyTreeSnapshot(seed + 0x200); - const startContractTreeSnapshot = makeAppendOnlyTreeSnapshot(seed + 0x300); - const startPublicDataTreeRoot = fr(seed + 0x400); - const startHistoricBlocksTreeSnapshot = makeAppendOnlyTreeSnapshot(seed + 0x500); - - const lowNullifierLeafPreimages = makeTuple( - MAX_NEW_NULLIFIERS_PER_BASE_ROLLUP, - x => new NullifierLeafPreimage(fr(x), fr(x + 0x100), x + 0x200), - seed + 0x1000, - ); - - const lowNullifierMembershipWitness = makeTuple( - MAX_NEW_NULLIFIERS_PER_BASE_ROLLUP, - x => makeMembershipWitness(NULLIFIER_TREE_HEIGHT, x), - seed + 0x2000, - ); - - const newCommitmentsSubtreeSiblingPath = makeTuple(NOTE_HASH_SUBTREE_SIBLING_PATH_LENGTH, fr, seed + 0x3000); - const newNullifiersSubtreeSiblingPath = makeTuple(NULLIFIER_SUBTREE_SIBLING_PATH_LENGTH, fr, seed + 0x4000); - const newContractsSubtreeSiblingPath = makeTuple(CONTRACT_SUBTREE_SIBLING_PATH_LENGTH, fr, seed + 0x5000); - - const newPublicDataUpdateRequestsSiblingPaths = makeTuple( - MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_BASE_ROLLUP, - x => makeTuple(PUBLIC_DATA_TREE_HEIGHT, fr, x), - seed + 0x6000, - ); - - const newPublicDataReadsSiblingPaths = makeTuple( - MAX_PUBLIC_DATA_READS_PER_BASE_ROLLUP, - x => makeTuple(PUBLIC_DATA_TREE_HEIGHT, fr, x), - seed + 0x6000, - ); - - const historicBlocksTreeRootMembershipWitnesses = makeTuple(KERNELS_PER_BASE_ROLLUP, x => - makeMembershipWitness(HISTORIC_BLOCKS_TREE_HEIGHT, seed + x * 0x1000 + 0x7000), - ); - - const constants = makeConstantBaseRollupData(0x100); - - return BaseRollupInputs.from({ - kernelData, - lowNullifierMembershipWitness, - startNoteHashTreeSnapshot, - startNullifierTreeSnapshot, - startContractTreeSnapshot, - startPublicDataTreeRoot, - startHistoricBlocksTreeSnapshot, - lowNullifierLeafPreimages, - newCommitmentsSubtreeSiblingPath, - newNullifiersSubtreeSiblingPath, - newContractsSubtreeSiblingPath, - newPublicDataUpdateRequestsSiblingPaths, - newPublicDataReadsSiblingPaths, - historicBlocksTreeRootMembershipWitnesses, - constants, - }); -} - -/** - * TODO: Since the max value check is currently disabled this function is pointless. Should it be removed? - * Test only. Easy to identify big endian field serialize. - * @param n - The number. - * @returns The field. - */ -export function fr(n: number): Fr { - return new Fr(BigInt(n)); -} diff --git a/yarn-project/circuits.js/src/types/contract_function_dao.ts b/yarn-project/circuits.js/src/types/contract_function_dao.ts deleted file mode 100644 index 84675ecb65e7..000000000000 --- a/yarn-project/circuits.js/src/types/contract_function_dao.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { FunctionArtifact } from '@aztec/foundation/abi'; - -import { FunctionSelector } from '../index.js'; - -/** - * A contract function Data Access Object (DAO). - * Extends the FunctionArtifact interface, adding a 'selector' property. - * The 'selector' is a unique identifier for the function within the contract. - */ -export interface ContractFunctionDao extends FunctionArtifact { - /** - * Unique identifier for a contract function. - */ - selector: FunctionSelector; -} diff --git a/yarn-project/circuits.js/src/types/deployment_info.ts b/yarn-project/circuits.js/src/types/deployment_info.ts deleted file mode 100644 index a8abba471262..000000000000 --- a/yarn-project/circuits.js/src/types/deployment_info.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { CompleteAddress, Fr } from '../index.js'; - -/** - * Represents the data generated as part of contract deployment. - */ -export type DeploymentInfo = { - /** - * The complete address of the deployed contract. - */ - completeAddress: CompleteAddress; - /** - * The contract's constructor hash. - */ - constructorHash: Fr; - /** - * The root of the contract's function tree. - */ - functionTreeRoot: Fr; -}; diff --git a/yarn-project/circuits.js/src/types/grumpkin_private_key.ts b/yarn-project/circuits.js/src/types/grumpkin_private_key.ts deleted file mode 100644 index 8a394773730d..000000000000 --- a/yarn-project/circuits.js/src/types/grumpkin_private_key.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { GrumpkinScalar } from '../index.js'; - -/** A type alias for private key which belongs to the scalar field of Grumpkin curve. */ -export type GrumpkinPrivateKey = GrumpkinScalar; diff --git a/yarn-project/circuits.js/src/types/index.ts b/yarn-project/circuits.js/src/types/index.ts deleted file mode 100644 index 12a0bb40a85c..000000000000 --- a/yarn-project/circuits.js/src/types/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -export * from './contract_function_dao.js'; -export * from './deployment_info.js'; -export * from './partial_address.js'; -export * from './grumpkin_private_key.js'; -export * from './public_key.js'; diff --git a/yarn-project/circuits.js/src/types/partial_address.ts b/yarn-project/circuits.js/src/types/partial_address.ts deleted file mode 100644 index e99d3786536a..000000000000 --- a/yarn-project/circuits.js/src/types/partial_address.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { Fr } from '@aztec/foundation/fields'; - -/** - * A type which along with public key forms a preimage of a contract address. See the link bellow for more details - * https://github.com/AztecProtocol/aztec-packages/blob/master/docs/docs/concepts/foundation/accounts/keys.md#addresses-partial-addresses-and-public-keys - */ -export type PartialAddress = Fr; diff --git a/yarn-project/circuits.js/src/types/public_key.ts b/yarn-project/circuits.js/src/types/public_key.ts deleted file mode 100644 index 1a985a9a6a28..000000000000 --- a/yarn-project/circuits.js/src/types/public_key.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { Point } from '@aztec/foundation/fields'; - -/** Represents a user public key. */ -export type PublicKey = Point; diff --git a/yarn-project/circuits.js/src/utils/index.ts b/yarn-project/circuits.js/src/utils/index.ts deleted file mode 100644 index bd7fd7dc2231..000000000000 --- a/yarn-project/circuits.js/src/utils/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './serialize.js'; -export { BufferReader } from '@aztec/foundation/serialize'; diff --git a/yarn-project/circuits.js/src/utils/jsUtils.ts b/yarn-project/circuits.js/src/utils/jsUtils.ts deleted file mode 100644 index a6a2e5b8bb15..000000000000 --- a/yarn-project/circuits.js/src/utils/jsUtils.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { Tuple } from '@aztec/foundation/serialize'; - -export type { FieldsOf } from '@aztec/foundation/types'; - -/** - * Create an array over an integer range. - * @param n - The number of integers. - * @param offset - The starting number. - * @returns The array of numbers. - */ -export function range(n: number, offset = 0) { - const ret: number[] = []; - for (let i = 0; i < n; i++) { - ret.push(offset + i); - } - return ret; -} - -/** - * Create an array over an integer range, filled with a function 'fn'. - * This is used over e.g. lodash because it resolved to a tuple type, needed for our fixed array type safety. - * @param n - The number of integers. - * @param fn - The generator function. - * @returns The array of numbers. - */ -export function makeTuple(length: N, fn: (i: number) => T, offset = 0) { - return Array.from({ length }, (v: any, i: number) => fn(i + offset)) as Tuple; -} - -/** - * Create an array over an integer range, filled with a function 'fn'. However, the latter half of the array are set to zeros. - * see `makeTuple` above. - * @param n - The number of integers. - * @param fn - The generator function. - * @returns The array of numbers. - */ -export function makeHalfFullTuple(length: N, fn: (i: number) => T, offset = 0) { - return Array.from({ length }, (v: any, i: number) => (i < length / 2 ? fn(i + offset) : fn(0))) as Tuple; -} - -/** - * Assert a member of an object is a certain length. - * @param obj - An object. - * @param member - A member string. - * @param length - The length. - */ -export function assertMemberLength< - F extends string, - T extends { - [f in F]: { - /** - * A property which the tested member of the object T has to have. - */ - length: number; - }; - }, ->(obj: T, member: F, length: number) { - if (obj[member].length !== length) { - throw new Error(`Expected ${member} to have length ${length} but was ${obj[member].length}`); - } -} - -/** - * Assert all subarrays in a member of an object are a certain length. - * @param obj - An object. - * @param member - A member string. - * @param length - The expected length for each subarray. - */ -export function assertItemsLength< - F extends string, - T extends { - [f in F]: { - /** - * A property which the tested member of the object T has to have. - */ - length: number; - }[]; - }, ->(obj: T, member: F, length: number) { - const arrays = obj[member]; - for (let i = 0; i < arrays.length; i++) { - if (arrays[i].length !== length) { - throw new Error(`Expected ${member}[${i}] to have length ${length} but was ${arrays[i].length}`); - } - } -}