diff --git a/barretenberg/cpp/src/barretenberg/crypto/aes128/c_bind.cpp b/barretenberg/cpp/src/barretenberg/crypto/aes128/c_bind.cpp index dee106779f2..1b30cdedbb6 100644 --- a/barretenberg/cpp/src/barretenberg/crypto/aes128/c_bind.cpp +++ b/barretenberg/cpp/src/barretenberg/crypto/aes128/c_bind.cpp @@ -1,18 +1,21 @@ +#include "c_bind.hpp" #include "aes128.hpp" -#include "barretenberg/common/wasm_export.hpp" +#include "barretenberg/common/serialize.hpp" -WASM_EXPORT void aes__encrypt_buffer_cbc(uint8_t* in, uint8_t* iv, const uint8_t* key, const size_t length, uint8_t* r) +WASM_EXPORT void aes_encrypt_buffer_cbc( + uint8_t const* in, uint8_t const* iv, uint8_t const* key, uint32_t const* length, uint8_t** r) { - crypto::aes128::encrypt_buffer_cbc(in, iv, key, length); - for (size_t i = 0; i < length; ++i) { - r[i] = in[i]; - } + auto len = ntohl(*length); + crypto::aes128::encrypt_buffer_cbc((uint8_t*)in, (uint8_t*)iv, key, len); + std::vector result(in, in + len); + *r = to_heap_buffer(result); } -WASM_EXPORT void aes__decrypt_buffer_cbc(uint8_t* in, uint8_t* iv, const uint8_t* key, const size_t length, uint8_t* r) +WASM_EXPORT void aes_decrypt_buffer_cbc( + uint8_t const* in, uint8_t const* iv, uint8_t const* key, uint32_t const* length, uint8_t** r) { - crypto::aes128::decrypt_buffer_cbc(in, iv, key, length); - for (size_t i = 0; i < length; ++i) { - r[i] = in[i]; - } + auto len = ntohl(*length); + crypto::aes128::decrypt_buffer_cbc((uint8_t*)in, (uint8_t*)iv, key, len); + std::vector result(in, in + len); + *r = to_heap_buffer(result); } diff --git a/barretenberg/cpp/src/barretenberg/crypto/aes128/c_bind.hpp b/barretenberg/cpp/src/barretenberg/crypto/aes128/c_bind.hpp new file mode 100644 index 00000000000..e1c6c513a93 --- /dev/null +++ b/barretenberg/cpp/src/barretenberg/crypto/aes128/c_bind.hpp @@ -0,0 +1,11 @@ +#pragma once +#include +#include +#include +#include + +WASM_EXPORT void aes_encrypt_buffer_cbc( + uint8_t const* input, uint8_t const* iv, uint8_t const* key, uint32_t const* length, uint8_t** r); + +WASM_EXPORT void aes_decrypt_buffer_cbc( + uint8_t const* input, uint8_t const* iv, uint8_t const* key, uint32_t const* length, uint8_t** r); diff --git a/barretenberg/cpp/src/barretenberg/crypto/pedersen_hash/c_bind.cpp b/barretenberg/cpp/src/barretenberg/crypto/pedersen_hash/c_bind.cpp index 6f51283ed9b..3f4d41567a8 100644 --- a/barretenberg/cpp/src/barretenberg/crypto/pedersen_hash/c_bind.cpp +++ b/barretenberg/cpp/src/barretenberg/crypto/pedersen_hash/c_bind.cpp @@ -14,4 +14,14 @@ WASM_EXPORT void pedersen_hash(uint8_t const* inputs_buffer, uint32_t const* has auto r = crypto::pedersen_hash::hash(to_hash, ctx); barretenberg::fr::serialize_to_buffer(r, output); } + +WASM_EXPORT void pedersen_hash_buffer(uint8_t const* input_buffer, uint32_t const* hash_index, uint8_t* output) +{ + std::vector to_hash; + read(input_buffer, to_hash); + crypto::GeneratorContext ctx; + ctx.offset = static_cast(ntohl(*hash_index)); + auto r = crypto::pedersen_hash::hash_buffer(to_hash, ctx); + barretenberg::fr::serialize_to_buffer(r, output); +} } \ No newline at end of file diff --git a/barretenberg/cpp/src/barretenberg/crypto/pedersen_hash/c_bind.hpp b/barretenberg/cpp/src/barretenberg/crypto/pedersen_hash/c_bind.hpp index 869418762d2..7369e743c19 100644 --- a/barretenberg/cpp/src/barretenberg/crypto/pedersen_hash/c_bind.hpp +++ b/barretenberg/cpp/src/barretenberg/crypto/pedersen_hash/c_bind.hpp @@ -8,4 +8,6 @@ extern "C" { using namespace barretenberg; WASM_EXPORT void pedersen_hash(fr::vec_in_buf inputs_buffer, uint32_t const* hash_index, fr::out_buf output); + +WASM_EXPORT void pedersen_hash_buffer(uint8_t const* input_buffer, uint32_t const* hash_index, fr::out_buf output); } \ No newline at end of file diff --git a/barretenberg/exports.json b/barretenberg/exports.json index 0c6856e3c87..4491016c8f8 100644 --- a/barretenberg/exports.json +++ b/barretenberg/exports.json @@ -35,6 +35,26 @@ ], "isAsync": false }, + { + "functionName": "pedersen_hash_buffer", + "inArgs": [ + { + "name": "input_buffer", + "type": "const uint8_t *" + }, + { + "name": "hash_index", + "type": "const uint32_t *" + } + ], + "outArgs": [ + { + "name": "output", + "type": "fr::out_buf" + } + ], + "isAsync": false + }, { "functionName": "blake2s", "inArgs": [ @@ -274,6 +294,62 @@ ], "isAsync": false }, + { + "functionName": "aes_encrypt_buffer_cbc", + "inArgs": [ + { + "name": "input", + "type": "const uint8_t *" + }, + { + "name": "iv", + "type": "const uint8_t *" + }, + { + "name": "key", + "type": "const uint8_t *" + }, + { + "name": "length", + "type": "const uint32_t *" + } + ], + "outArgs": [ + { + "name": "r", + "type": "uint8_t **" + } + ], + "isAsync": false + }, + { + "functionName": "aes_decrypt_buffer_cbc", + "inArgs": [ + { + "name": "input", + "type": "const uint8_t *" + }, + { + "name": "iv", + "type": "const uint8_t *" + }, + { + "name": "key", + "type": "const uint8_t *" + }, + { + "name": "length", + "type": "const uint32_t *" + } + ], + "outArgs": [ + { + "name": "r", + "type": "uint8_t **" + } + ], + "isAsync": false + }, { "functionName": "srs_init_srs", "inArgs": [ diff --git a/barretenberg/scripts/c_bind_files.txt b/barretenberg/scripts/c_bind_files.txt index a84057549ba..255fcd4f5ad 100644 --- a/barretenberg/scripts/c_bind_files.txt +++ b/barretenberg/scripts/c_bind_files.txt @@ -2,6 +2,7 @@ ./cpp/src/barretenberg/crypto/pedersen_hash/c_bind.hpp ./cpp/src/barretenberg/crypto/blake2s/c_bind.hpp ./cpp/src/barretenberg/crypto/schnorr/c_bind.hpp +./cpp/src/barretenberg/crypto/aes128/c_bind.hpp ./cpp/src/barretenberg/srs/c_bind.hpp ./cpp/src/barretenberg/examples/c_bind.hpp ./cpp/src/barretenberg/common/c_bind.hpp diff --git a/barretenberg/ts/src/barretenberg/__snapshots__/pedersen.test.ts.snap b/barretenberg/ts/src/barretenberg/__snapshots__/pedersen.test.ts.snap new file mode 100644 index 00000000000..f8bbf136471 --- /dev/null +++ b/barretenberg/ts/src/barretenberg/__snapshots__/pedersen.test.ts.snap @@ -0,0 +1,156 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`pedersen sync pedersenCommit 1`] = ` +Point { + "x": Fr { + "value": Uint8Array [ + 40, + 159, + 125, + 144, + 234, + 153, + 219, + 166, + 76, + 75, + 47, + 51, + 253, + 27, + 9, + 101, + 2, + 145, + 223, + 38, + 43, + 114, + 5, + 21, + 90, + 97, + 2, + 6, + 219, + 97, + 109, + 152, + ], + }, + "y": Fr { + "value": Uint8Array [ + 5, + 175, + 199, + 200, + 35, + 67, + 88, + 76, + 19, + 203, + 45, + 50, + 137, + 153, + 67, + 200, + 57, + 87, + 22, + 209, + 141, + 173, + 205, + 189, + 23, + 215, + 206, + 3, + 174, + 112, + 128, + 11, + ], + }, +} +`; + +exports[`pedersen sync pedersenHash 1`] = ` +Fr { + "value": Uint8Array [ + 4, + 194, + 53, + 42, + 6, + 13, + 74, + 193, + 205, + 251, + 96, + 62, + 188, + 67, + 39, + 181, + 118, + 69, + 151, + 35, + 22, + 20, + 246, + 29, + 36, + 91, + 243, + 87, + 114, + 192, + 134, + 150, + ], +} +`; + +exports[`pedersen sync pedersenHashBuffer 1`] = ` +Fr { + "value": Uint8Array [ + 43, + 213, + 196, + 82, + 160, + 201, + 113, + 98, + 41, + 79, + 201, + 223, + 208, + 241, + 224, + 157, + 14, + 9, + 201, + 95, + 165, + 237, + 63, + 241, + 73, + 251, + 222, + 243, + 102, + 203, + 81, + 249, + ], +} +`; diff --git a/barretenberg/ts/src/barretenberg/blake2s.test.ts b/barretenberg/ts/src/barretenberg/blake2s.test.ts new file mode 100644 index 00000000000..23c6f9d678f --- /dev/null +++ b/barretenberg/ts/src/barretenberg/blake2s.test.ts @@ -0,0 +1,70 @@ +import { Barretenberg, BarretenbergSync } from './index.js'; +import { Buffer32, Fr } from '../types/index.js'; + +describe('blake2s async', () => { + let api: Barretenberg; + + beforeAll(async () => { + api = await Barretenberg.new(1); + }); + + afterAll(async () => { + await api.destroy(); + }); + + it('blake2s', async () => { + const input = Buffer.from('abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789'); + const expected = Buffer32.fromBuffer( + new Uint8Array([ + 0x44, 0xdd, 0xdb, 0x39, 0xbd, 0xb2, 0xaf, 0x80, 0xc1, 0x47, 0x89, 0x4c, 0x1d, 0x75, 0x6a, 0xda, 0x3d, 0x1c, + 0x2a, 0xc2, 0xb1, 0x00, 0x54, 0x1e, 0x04, 0xfe, 0x87, 0xb4, 0xa5, 0x9e, 0x12, 0x43, + ]), + ); + const result = await api.blake2s(input); + expect(result).toEqual(expected); + }); + + it('blake2sToField', async () => { + const input = Buffer.from('abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789'); + const expected = Fr.fromBufferReduce( + new Uint8Array([ + 0x44, 0xdd, 0xdb, 0x39, 0xbd, 0xb2, 0xaf, 0x80, 0xc1, 0x47, 0x89, 0x4c, 0x1d, 0x75, 0x6a, 0xda, 0x3d, 0x1c, + 0x2a, 0xc2, 0xb1, 0x00, 0x54, 0x1e, 0x04, 0xfe, 0x87, 0xb4, 0xa5, 0x9e, 0x12, 0x43, + ]), + ); + const result = await api.blake2sToField(input); + expect(result).toEqual(expected); + }); +}); + +describe('blake2s sync', () => { + let api: BarretenbergSync; + + beforeAll(async () => { + api = await BarretenbergSync.new(); + }); + + it('blake2s', () => { + const input = Buffer.from('abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789'); + const expected = Buffer32.fromBuffer( + new Uint8Array([ + 0x44, 0xdd, 0xdb, 0x39, 0xbd, 0xb2, 0xaf, 0x80, 0xc1, 0x47, 0x89, 0x4c, 0x1d, 0x75, 0x6a, 0xda, 0x3d, 0x1c, + 0x2a, 0xc2, 0xb1, 0x00, 0x54, 0x1e, 0x04, 0xfe, 0x87, 0xb4, 0xa5, 0x9e, 0x12, 0x43, + ]), + ); + const result = api.blake2s(input); + expect(result).toEqual(expected); + }); + + it('blake2sToField', () => { + const input = Buffer.from('abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789'); + const expected = Fr.fromBufferReduce( + new Uint8Array([ + 0x44, 0xdd, 0xdb, 0x39, 0xbd, 0xb2, 0xaf, 0x80, 0xc1, 0x47, 0x89, 0x4c, 0x1d, 0x75, 0x6a, 0xda, 0x3d, 0x1c, + 0x2a, 0xc2, 0xb1, 0x00, 0x54, 0x1e, 0x04, 0xfe, 0x87, 0xb4, 0xa5, 0x9e, 0x12, 0x43, + ]), + ); + const result = api.blake2sToField(input); + expect(result).toEqual(expected); + }); +}); diff --git a/barretenberg/ts/src/barretenberg_api/common.test.ts b/barretenberg/ts/src/barretenberg/common.test.ts similarity index 89% rename from barretenberg/ts/src/barretenberg_api/common.test.ts rename to barretenberg/ts/src/barretenberg/common.test.ts index 1e1381829b5..5697b255859 100644 --- a/barretenberg/ts/src/barretenberg_api/common.test.ts +++ b/barretenberg/ts/src/barretenberg/common.test.ts @@ -1,4 +1,4 @@ -import { Barretenberg } from '../barretenberg/index.js'; +import { Barretenberg } from './index.js'; describe('env', () => { let api: Barretenberg; diff --git a/barretenberg/ts/src/barretenberg/index.ts b/barretenberg/ts/src/barretenberg/index.ts index 6ae070d4882..384117c7409 100644 --- a/barretenberg/ts/src/barretenberg/index.ts +++ b/barretenberg/ts/src/barretenberg/index.ts @@ -1,8 +1,7 @@ import { proxy } from 'comlink'; -import { BarretenbergApi } from '../barretenberg_api/index.js'; -import { BarretenbergBinder } from '../barretenberg_binder/index.js'; +import { BarretenbergApi, BarretenbergApiSync } from '../barretenberg_api/index.js'; import { createMainWorker } from '../barretenberg_wasm/barretenberg_wasm_main/factory/node/index.js'; -import { BarretenbergWasmMainWorker } from '../barretenberg_wasm/barretenberg_wasm_main/index.js'; +import { BarretenbergWasmMain, BarretenbergWasmMainWorker } from '../barretenberg_wasm/barretenberg_wasm_main/index.js'; import { getRemoteBarretenbergWasm } from '../barretenberg_wasm/helpers/index.js'; import { BarretenbergWasmWorker } from '../barretenberg_wasm/index.js'; import createDebug from 'debug'; @@ -14,8 +13,8 @@ const debug = createDebug('bb.js:wasm'); * It extends the generated api, and provides a static constructor "new" to compose components. */ export class Barretenberg extends BarretenbergApi { - private constructor(private worker: any, private wasm: BarretenbergWasmWorker) { - super(new BarretenbergBinder(wasm)); + private constructor(private worker: any, wasm: BarretenbergWasmWorker) { + super(wasm); } /** @@ -40,3 +39,28 @@ export class Barretenberg extends BarretenbergApi { await this.worker.terminate(); } } + +let barretenbergSyncSingleton: Promise; + +export class BarretenbergSync extends BarretenbergApiSync { + private constructor(wasm: BarretenbergWasmMain) { + super(wasm); + } + + static async new() { + const wasm = new BarretenbergWasmMain(); + await wasm.init(1); + return new BarretenbergSync(wasm); + } + + static getSingleton() { + if (!barretenbergSyncSingleton) { + barretenbergSyncSingleton = BarretenbergSync.new(); + } + return barretenbergSyncSingleton; + } + + getWasm() { + return this.wasm; + } +} diff --git a/barretenberg/ts/src/barretenberg/pedersen.test.ts b/barretenberg/ts/src/barretenberg/pedersen.test.ts new file mode 100644 index 00000000000..4b0150ab4db --- /dev/null +++ b/barretenberg/ts/src/barretenberg/pedersen.test.ts @@ -0,0 +1,39 @@ +import { BarretenbergSync } from './index.js'; +import { Timer } from '../benchmark/timer.js'; +import { Fr } from '../types/index.js'; + +describe('pedersen sync', () => { + let api: BarretenbergSync; + + beforeAll(async () => { + api = await BarretenbergSync.new(); + }); + + it('pedersenHash', () => { + const result = api.pedersenHash([new Fr(4n), new Fr(8n)], 7); + expect(result).toMatchSnapshot(); + }); + + it('pedersenHashBuffer', () => { + const input = Buffer.alloc(123); + input.writeUint32BE(321, 0); + input.writeUint32BE(456, 119); + const r = api.pedersenHashBuffer(input, 0); + expect(r).toMatchSnapshot(); + }); + + it('pedersenCommit', () => { + const result = api.pedersenCommit([new Fr(4n), new Fr(8n), new Fr(12n)]); + expect(result).toMatchSnapshot(); + }); + + it.skip('pedersenCommit perf test', () => { + const loops = 1000; + const fields = Array.from({ length: loops * 2 }).map(() => Fr.random()); + const t = new Timer(); + for (let i = 0; i < loops; ++i) { + api.pedersenCommit([fields[i * 2], fields[i * 2 + 1]]); + } + console.log(t.us() / loops); + }); +}); diff --git a/barretenberg/ts/src/barretenberg_api/schnorr.test.ts b/barretenberg/ts/src/barretenberg/schnorr.test.ts similarity index 99% rename from barretenberg/ts/src/barretenberg_api/schnorr.test.ts rename to barretenberg/ts/src/barretenberg/schnorr.test.ts index e98e5583afa..7945cbce3b2 100644 --- a/barretenberg/ts/src/barretenberg_api/schnorr.test.ts +++ b/barretenberg/ts/src/barretenberg/schnorr.test.ts @@ -1,6 +1,6 @@ import { TextEncoder } from 'util'; import { Buffer128, Buffer32, Fq, Fr, Point } from '../types/index.js'; -import { Barretenberg } from '../barretenberg/index.js'; +import { Barretenberg } from './index.js'; import { asyncMap } from '../async_map/index.js'; describe('schnorr', () => { diff --git a/barretenberg/ts/src/barretenberg_api/blake2s.test.ts b/barretenberg/ts/src/barretenberg_api/blake2s.test.ts deleted file mode 100644 index 7f0257ef2a2..00000000000 --- a/barretenberg/ts/src/barretenberg_api/blake2s.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { Barretenberg } from '../barretenberg/index.js'; -import { Buffer32, Fr } from '../types/index.js'; - -describe('blake2s', () => { - let api: Barretenberg; - - beforeAll(async () => { - api = await Barretenberg.new(1); - }); - - afterAll(async () => { - await api.destroy(); - }); - - it('blake2s', async () => { - const input = Buffer.from('abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789'); - const expected = Buffer32.fromBuffer( - new Uint8Array([ - 0x44, 0xdd, 0xdb, 0x39, 0xbd, 0xb2, 0xaf, 0x80, 0xc1, 0x47, 0x89, 0x4c, 0x1d, 0x75, 0x6a, 0xda, 0x3d, 0x1c, - 0x2a, 0xc2, 0xb1, 0x00, 0x54, 0x1e, 0x04, 0xfe, 0x87, 0xb4, 0xa5, 0x9e, 0x12, 0x43, - ]), - ); - const result = await api.blake2s(input); - expect(result).toEqual(expected); - }); - - it('blake2sToField', async () => { - const input = Buffer.from('abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789'); - const expected = Fr.fromBufferReduce( - new Uint8Array([ - 0x44, 0xdd, 0xdb, 0x39, 0xbd, 0xb2, 0xaf, 0x80, 0xc1, 0x47, 0x89, 0x4c, 0x1d, 0x75, 0x6a, 0xda, 0x3d, 0x1c, - 0x2a, 0xc2, 0xb1, 0x00, 0x54, 0x1e, 0x04, 0xfe, 0x87, 0xb4, 0xa5, 0x9e, 0x12, 0x43, - ]), - ); - const result = await api.blake2sToField(input); - expect(result).toEqual(expected); - }); -}); diff --git a/barretenberg/ts/src/barretenberg_api/index.ts b/barretenberg/ts/src/barretenberg_api/index.ts index 5612d740654..b47f0d8f0c7 100644 --- a/barretenberg/ts/src/barretenberg_api/index.ts +++ b/barretenberg/ts/src/barretenberg_api/index.ts @@ -1,95 +1,162 @@ // WARNING: FILE CODE GENERATED BY BINDGEN UTILITY. DO NOT EDIT! /* eslint-disable @typescript-eslint/no-unused-vars */ -import { BarretenbergBinder } from '../barretenberg_binder/index.js'; +import { BarretenbergWasmWorker, BarretenbergWasm } from '../barretenberg_wasm/index.js'; import { BufferDeserializer, NumberDeserializer, VectorDeserializer, BoolDeserializer, StringDeserializer, + serializeBufferable, + OutputType, } from '../serialize/index.js'; import { Fr, Fq, Point, Buffer32, Buffer128, Ptr } from '../types/index.js'; export class BarretenbergApi { - constructor(public binder: BarretenbergBinder) {} - - async destroy() { - await this.binder.wasm.destroy(); - } + constructor(protected wasm: BarretenbergWasmWorker) {} async pedersenCommit(inputsBuffer: Fr[]): Promise { - const result = await this.binder.callWasmExport('pedersen_commit', [inputsBuffer], [Point]); - return result[0]; + const inArgs = [inputsBuffer].map(serializeBufferable); + const outTypes: OutputType[] = [Point]; + const result = await this.wasm.callWasmExport( + 'pedersen_commit', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; } async pedersenHash(inputsBuffer: Fr[], hashIndex: number): Promise { - const result = await this.binder.callWasmExport('pedersen_hash', [inputsBuffer, hashIndex], [Fr]); - return result[0]; + const inArgs = [inputsBuffer, hashIndex].map(serializeBufferable); + const outTypes: OutputType[] = [Fr]; + const result = await this.wasm.callWasmExport( + 'pedersen_hash', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; + } + + async pedersenHashBuffer(inputBuffer: Uint8Array, hashIndex: number): Promise { + const inArgs = [inputBuffer, hashIndex].map(serializeBufferable); + const outTypes: OutputType[] = [Fr]; + const result = await this.wasm.callWasmExport( + 'pedersen_hash_buffer', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; } async blake2s(data: Uint8Array): Promise { - const result = await this.binder.callWasmExport('blake2s', [data], [Buffer32]); - return result[0]; + const inArgs = [data].map(serializeBufferable); + const outTypes: OutputType[] = [Buffer32]; + const result = await this.wasm.callWasmExport( + 'blake2s', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; } async blake2sToField(data: Uint8Array): Promise { - const result = await this.binder.callWasmExport('blake2s_to_field_', [data], [Fr]); - return result[0]; + const inArgs = [data].map(serializeBufferable); + const outTypes: OutputType[] = [Fr]; + const result = await this.wasm.callWasmExport( + 'blake2s_to_field_', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; } async schnorrComputePublicKey(privateKey: Fr): Promise { - const result = await this.binder.callWasmExport('schnorr_compute_public_key', [privateKey], [Point]); - return result[0]; + const inArgs = [privateKey].map(serializeBufferable); + const outTypes: OutputType[] = [Point]; + const result = await this.wasm.callWasmExport( + 'schnorr_compute_public_key', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; } async schnorrNegatePublicKey(publicKeyBuffer: Point): Promise { - const result = await this.binder.callWasmExport('schnorr_negate_public_key', [publicKeyBuffer], [Point]); - return result[0]; + const inArgs = [publicKeyBuffer].map(serializeBufferable); + const outTypes: OutputType[] = [Point]; + const result = await this.wasm.callWasmExport( + 'schnorr_negate_public_key', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; } async schnorrConstructSignature(message: Uint8Array, privateKey: Fr): Promise<[Buffer32, Buffer32]> { - const result = await this.binder.callWasmExport( + const inArgs = [message, privateKey].map(serializeBufferable); + const outTypes: OutputType[] = [Buffer32, Buffer32]; + const result = await this.wasm.callWasmExport( 'schnorr_construct_signature', - [message, privateKey], - [Buffer32, Buffer32], + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), ); - return result as any; + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out as any; } async schnorrVerifySignature(message: Uint8Array, pubKey: Point, sigS: Buffer32, sigE: Buffer32): Promise { - const result = await this.binder.callWasmExport( + const inArgs = [message, pubKey, sigS, sigE].map(serializeBufferable); + const outTypes: OutputType[] = [BoolDeserializer()]; + const result = await this.wasm.callWasmExport( 'schnorr_verify_signature', - [message, pubKey, sigS, sigE], - [BoolDeserializer()], + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), ); - return result[0]; + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; } async schnorrMultisigCreateMultisigPublicKey(privateKey: Fq): Promise { - const result = await this.binder.callWasmExport( + const inArgs = [privateKey].map(serializeBufferable); + const outTypes: OutputType[] = [Buffer128]; + const result = await this.wasm.callWasmExport( 'schnorr_multisig_create_multisig_public_key', - [privateKey], - [Buffer128], + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), ); - return result[0]; + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; } async schnorrMultisigValidateAndCombineSignerPubkeys(signerPubkeyBuf: Buffer128[]): Promise<[Point, boolean]> { - const result = await this.binder.callWasmExport( + const inArgs = [signerPubkeyBuf].map(serializeBufferable); + const outTypes: OutputType[] = [Point, BoolDeserializer()]; + const result = await this.wasm.callWasmExport( 'schnorr_multisig_validate_and_combine_signer_pubkeys', - [signerPubkeyBuf], - [Point, BoolDeserializer()], + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), ); - return result as any; + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out as any; } async schnorrMultisigConstructSignatureRound1(): Promise<[Buffer128, Buffer128]> { - const result = await this.binder.callWasmExport( + const inArgs = [].map(serializeBufferable); + const outTypes: OutputType[] = [Buffer128, Buffer128]; + const result = await this.wasm.callWasmExport( 'schnorr_multisig_construct_signature_round_1', - [], - [Buffer128, Buffer128], + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), ); - return result as any; + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out as any; } async schnorrMultisigConstructSignatureRound2( @@ -99,12 +166,17 @@ export class BarretenbergApi { signerPubkeysBuf: Buffer128[], roundOnePublicBuf: Buffer128[], ): Promise<[Fq, boolean]> { - const result = await this.binder.callWasmExport( + const inArgs = [message, privateKey, signerRoundOnePrivateBuf, signerPubkeysBuf, roundOnePublicBuf].map( + serializeBufferable, + ); + const outTypes: OutputType[] = [Fq, BoolDeserializer()]; + const result = await this.wasm.callWasmExport( 'schnorr_multisig_construct_signature_round_2', - [message, privateKey, signerRoundOnePrivateBuf, signerPubkeysBuf, roundOnePublicBuf], - [Fq, BoolDeserializer()], + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), ); - return result as any; + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out as any; } async schnorrMultisigCombineSignatures( @@ -113,72 +185,146 @@ export class BarretenbergApi { roundOneBuf: Buffer128[], roundTwoBuf: Fq[], ): Promise<[Buffer32, Buffer32, boolean]> { - const result = await this.binder.callWasmExport( + const inArgs = [message, signerPubkeysBuf, roundOneBuf, roundTwoBuf].map(serializeBufferable); + const outTypes: OutputType[] = [Buffer32, Buffer32, BoolDeserializer()]; + const result = await this.wasm.callWasmExport( 'schnorr_multisig_combine_signatures', - [message, signerPubkeysBuf, roundOneBuf, roundTwoBuf], - [Buffer32, Buffer32, BoolDeserializer()], + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out as any; + } + + async aesEncryptBufferCbc(input: Uint8Array, iv: Uint8Array, key: Uint8Array, length: number): Promise { + const inArgs = [input, iv, key, length].map(serializeBufferable); + const outTypes: OutputType[] = [BufferDeserializer()]; + const result = await this.wasm.callWasmExport( + 'aes_encrypt_buffer_cbc', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; + } + + async aesDecryptBufferCbc(input: Uint8Array, iv: Uint8Array, key: Uint8Array, length: number): Promise { + const inArgs = [input, iv, key, length].map(serializeBufferable); + const outTypes: OutputType[] = [BufferDeserializer()]; + const result = await this.wasm.callWasmExport( + 'aes_decrypt_buffer_cbc', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), ); - return result as any; + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; } async srsInitSrs(pointsBuf: Uint8Array, numPoints: number, g2PointBuf: Uint8Array): Promise { - const result = await this.binder.callWasmExport('srs_init_srs', [pointsBuf, numPoints, g2PointBuf], []); + const inArgs = [pointsBuf, numPoints, g2PointBuf].map(serializeBufferable); + const outTypes: OutputType[] = []; + const result = await this.wasm.callWasmExport( + 'srs_init_srs', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); return; } async examplesSimpleCreateAndVerifyProof(): Promise { - const result = await this.binder.callWasmExport( + const inArgs = [].map(serializeBufferable); + const outTypes: OutputType[] = [BoolDeserializer()]; + const result = await this.wasm.callWasmExport( 'examples_simple_create_and_verify_proof', - [], - [BoolDeserializer()], + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), ); - return result[0]; + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; } async testThreads(threads: number, iterations: number): Promise { - const result = await this.binder.callWasmExport('test_threads', [threads, iterations], [NumberDeserializer()]); - return result[0]; + const inArgs = [threads, iterations].map(serializeBufferable); + const outTypes: OutputType[] = [NumberDeserializer()]; + const result = await this.wasm.callWasmExport( + 'test_threads', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; } async commonInitSlabAllocator(circuitSize: number): Promise { - const result = await this.binder.callWasmExport('common_init_slab_allocator', [circuitSize], []); + const inArgs = [circuitSize].map(serializeBufferable); + const outTypes: OutputType[] = []; + const result = await this.wasm.callWasmExport( + 'common_init_slab_allocator', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); return; } async acirGetCircuitSizes(constraintSystemBuf: Uint8Array): Promise<[number, number, number]> { - const result = await this.binder.callWasmExport( + const inArgs = [constraintSystemBuf].map(serializeBufferable); + const outTypes: OutputType[] = [NumberDeserializer(), NumberDeserializer(), NumberDeserializer()]; + const result = await this.wasm.callWasmExport( 'acir_get_circuit_sizes', - [constraintSystemBuf], - [NumberDeserializer(), NumberDeserializer(), NumberDeserializer()], + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), ); - return result as any; + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out as any; } async acirNewAcirComposer(sizeHint: number): Promise { - const result = await this.binder.callWasmExport('acir_new_acir_composer', [sizeHint], [Ptr]); - return result[0]; + const inArgs = [sizeHint].map(serializeBufferable); + const outTypes: OutputType[] = [Ptr]; + const result = await this.wasm.callWasmExport( + 'acir_new_acir_composer', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; } async acirDeleteAcirComposer(acirComposerPtr: Ptr): Promise { - const result = await this.binder.callWasmExport('acir_delete_acir_composer', [acirComposerPtr], []); + const inArgs = [acirComposerPtr].map(serializeBufferable); + const outTypes: OutputType[] = []; + const result = await this.wasm.callWasmExport( + 'acir_delete_acir_composer', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); return; } async acirCreateCircuit(acirComposerPtr: Ptr, constraintSystemBuf: Uint8Array, sizeHint: number): Promise { - const result = await this.binder.callWasmExport( + const inArgs = [acirComposerPtr, constraintSystemBuf, sizeHint].map(serializeBufferable); + const outTypes: OutputType[] = []; + const result = await this.wasm.callWasmExport( 'acir_create_circuit', - [acirComposerPtr, constraintSystemBuf, sizeHint], - [], + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); return; } async acirInitProvingKey(acirComposerPtr: Ptr, constraintSystemBuf: Uint8Array): Promise { - const result = await this.binder.callWasmExport( + const inArgs = [acirComposerPtr, constraintSystemBuf].map(serializeBufferable); + const outTypes: OutputType[] = []; + const result = await this.wasm.callWasmExport( 'acir_init_proving_key', - [acirComposerPtr, constraintSystemBuf], - [], + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); return; } @@ -188,49 +334,75 @@ export class BarretenbergApi { witnessBuf: Uint8Array, isRecursive: boolean, ): Promise { - const result = await this.binder.callWasmExport( + const inArgs = [acirComposerPtr, constraintSystemBuf, witnessBuf, isRecursive].map(serializeBufferable); + const outTypes: OutputType[] = [BufferDeserializer()]; + const result = await this.wasm.callWasmExport( 'acir_create_proof', - [acirComposerPtr, constraintSystemBuf, witnessBuf, isRecursive], - [BufferDeserializer()], + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), ); - return result[0]; + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; } async acirLoadVerificationKey(acirComposerPtr: Ptr, vkBuf: Uint8Array): Promise { - const result = await this.binder.callWasmExport('acir_load_verification_key', [acirComposerPtr, vkBuf], []); + const inArgs = [acirComposerPtr, vkBuf].map(serializeBufferable); + const outTypes: OutputType[] = []; + const result = await this.wasm.callWasmExport( + 'acir_load_verification_key', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); return; } async acirInitVerificationKey(acirComposerPtr: Ptr): Promise { - const result = await this.binder.callWasmExport('acir_init_verification_key', [acirComposerPtr], []); + const inArgs = [acirComposerPtr].map(serializeBufferable); + const outTypes: OutputType[] = []; + const result = await this.wasm.callWasmExport( + 'acir_init_verification_key', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); return; } async acirGetVerificationKey(acirComposerPtr: Ptr): Promise { - const result = await this.binder.callWasmExport( + const inArgs = [acirComposerPtr].map(serializeBufferable); + const outTypes: OutputType[] = [BufferDeserializer()]; + const result = await this.wasm.callWasmExport( 'acir_get_verification_key', - [acirComposerPtr], - [BufferDeserializer()], + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), ); - return result[0]; + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; } async acirVerifyProof(acirComposerPtr: Ptr, proofBuf: Uint8Array, isRecursive: boolean): Promise { - const result = await this.binder.callWasmExport( + const inArgs = [acirComposerPtr, proofBuf, isRecursive].map(serializeBufferable); + const outTypes: OutputType[] = [BoolDeserializer()]; + const result = await this.wasm.callWasmExport( 'acir_verify_proof', - [acirComposerPtr, proofBuf, isRecursive], - [BoolDeserializer()], + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), ); - return result[0]; + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; } async acirGetSolidityVerifier(acirComposerPtr: Ptr): Promise { - const result = await this.binder.callWasmExport( + const inArgs = [acirComposerPtr].map(serializeBufferable); + const outTypes: OutputType[] = [StringDeserializer()]; + const result = await this.wasm.callWasmExport( 'acir_get_solidity_verifier', - [acirComposerPtr], - [StringDeserializer()], + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), ); - return result[0]; + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; } async acirSerializeProofIntoFields( @@ -238,20 +410,443 @@ export class BarretenbergApi { proofBuf: Uint8Array, numInnerPublicInputs: number, ): Promise { - const result = await this.binder.callWasmExport( + const inArgs = [acirComposerPtr, proofBuf, numInnerPublicInputs].map(serializeBufferable); + const outTypes: OutputType[] = [VectorDeserializer(Fr)]; + const result = await this.wasm.callWasmExport( 'acir_serialize_proof_into_fields', - [acirComposerPtr, proofBuf, numInnerPublicInputs], - [VectorDeserializer(Fr)], + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), ); - return result[0]; + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; } async acirSerializeVerificationKeyIntoFields(acirComposerPtr: Ptr): Promise<[Fr[], Fr]> { - const result = await this.binder.callWasmExport( + const inArgs = [acirComposerPtr].map(serializeBufferable); + const outTypes: OutputType[] = [VectorDeserializer(Fr), Fr]; + const result = await this.wasm.callWasmExport( + 'acir_serialize_verification_key_into_fields', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out as any; + } +} +export class BarretenbergApiSync { + constructor(protected wasm: BarretenbergWasm) {} + + pedersenCommit(inputsBuffer: Fr[]): Point { + const inArgs = [inputsBuffer].map(serializeBufferable); + const outTypes: OutputType[] = [Point]; + const result = this.wasm.callWasmExport( + 'pedersen_commit', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; + } + + pedersenHash(inputsBuffer: Fr[], hashIndex: number): Fr { + const inArgs = [inputsBuffer, hashIndex].map(serializeBufferable); + const outTypes: OutputType[] = [Fr]; + const result = this.wasm.callWasmExport( + 'pedersen_hash', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; + } + + pedersenHashBuffer(inputBuffer: Uint8Array, hashIndex: number): Fr { + const inArgs = [inputBuffer, hashIndex].map(serializeBufferable); + const outTypes: OutputType[] = [Fr]; + const result = this.wasm.callWasmExport( + 'pedersen_hash_buffer', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; + } + + blake2s(data: Uint8Array): Buffer32 { + const inArgs = [data].map(serializeBufferable); + const outTypes: OutputType[] = [Buffer32]; + const result = this.wasm.callWasmExport( + 'blake2s', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; + } + + blake2sToField(data: Uint8Array): Fr { + const inArgs = [data].map(serializeBufferable); + const outTypes: OutputType[] = [Fr]; + const result = this.wasm.callWasmExport( + 'blake2s_to_field_', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; + } + + schnorrComputePublicKey(privateKey: Fr): Point { + const inArgs = [privateKey].map(serializeBufferable); + const outTypes: OutputType[] = [Point]; + const result = this.wasm.callWasmExport( + 'schnorr_compute_public_key', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; + } + + schnorrNegatePublicKey(publicKeyBuffer: Point): Point { + const inArgs = [publicKeyBuffer].map(serializeBufferable); + const outTypes: OutputType[] = [Point]; + const result = this.wasm.callWasmExport( + 'schnorr_negate_public_key', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; + } + + schnorrConstructSignature(message: Uint8Array, privateKey: Fr): [Buffer32, Buffer32] { + const inArgs = [message, privateKey].map(serializeBufferable); + const outTypes: OutputType[] = [Buffer32, Buffer32]; + const result = this.wasm.callWasmExport( + 'schnorr_construct_signature', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out as any; + } + + schnorrVerifySignature(message: Uint8Array, pubKey: Point, sigS: Buffer32, sigE: Buffer32): boolean { + const inArgs = [message, pubKey, sigS, sigE].map(serializeBufferable); + const outTypes: OutputType[] = [BoolDeserializer()]; + const result = this.wasm.callWasmExport( + 'schnorr_verify_signature', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; + } + + schnorrMultisigCreateMultisigPublicKey(privateKey: Fq): Buffer128 { + const inArgs = [privateKey].map(serializeBufferable); + const outTypes: OutputType[] = [Buffer128]; + const result = this.wasm.callWasmExport( + 'schnorr_multisig_create_multisig_public_key', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; + } + + schnorrMultisigValidateAndCombineSignerPubkeys(signerPubkeyBuf: Buffer128[]): [Point, boolean] { + const inArgs = [signerPubkeyBuf].map(serializeBufferable); + const outTypes: OutputType[] = [Point, BoolDeserializer()]; + const result = this.wasm.callWasmExport( + 'schnorr_multisig_validate_and_combine_signer_pubkeys', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out as any; + } + + schnorrMultisigConstructSignatureRound1(): [Buffer128, Buffer128] { + const inArgs = [].map(serializeBufferable); + const outTypes: OutputType[] = [Buffer128, Buffer128]; + const result = this.wasm.callWasmExport( + 'schnorr_multisig_construct_signature_round_1', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out as any; + } + + schnorrMultisigConstructSignatureRound2( + message: Uint8Array, + privateKey: Fq, + signerRoundOnePrivateBuf: Buffer128, + signerPubkeysBuf: Buffer128[], + roundOnePublicBuf: Buffer128[], + ): [Fq, boolean] { + const inArgs = [message, privateKey, signerRoundOnePrivateBuf, signerPubkeysBuf, roundOnePublicBuf].map( + serializeBufferable, + ); + const outTypes: OutputType[] = [Fq, BoolDeserializer()]; + const result = this.wasm.callWasmExport( + 'schnorr_multisig_construct_signature_round_2', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out as any; + } + + schnorrMultisigCombineSignatures( + message: Uint8Array, + signerPubkeysBuf: Buffer128[], + roundOneBuf: Buffer128[], + roundTwoBuf: Fq[], + ): [Buffer32, Buffer32, boolean] { + const inArgs = [message, signerPubkeysBuf, roundOneBuf, roundTwoBuf].map(serializeBufferable); + const outTypes: OutputType[] = [Buffer32, Buffer32, BoolDeserializer()]; + const result = this.wasm.callWasmExport( + 'schnorr_multisig_combine_signatures', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out as any; + } + + aesEncryptBufferCbc(input: Uint8Array, iv: Uint8Array, key: Uint8Array, length: number): Uint8Array { + const inArgs = [input, iv, key, length].map(serializeBufferable); + const outTypes: OutputType[] = [BufferDeserializer()]; + const result = this.wasm.callWasmExport( + 'aes_encrypt_buffer_cbc', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; + } + + aesDecryptBufferCbc(input: Uint8Array, iv: Uint8Array, key: Uint8Array, length: number): Uint8Array { + const inArgs = [input, iv, key, length].map(serializeBufferable); + const outTypes: OutputType[] = [BufferDeserializer()]; + const result = this.wasm.callWasmExport( + 'aes_decrypt_buffer_cbc', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; + } + + srsInitSrs(pointsBuf: Uint8Array, numPoints: number, g2PointBuf: Uint8Array): void { + const inArgs = [pointsBuf, numPoints, g2PointBuf].map(serializeBufferable); + const outTypes: OutputType[] = []; + const result = this.wasm.callWasmExport( + 'srs_init_srs', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return; + } + + examplesSimpleCreateAndVerifyProof(): boolean { + const inArgs = [].map(serializeBufferable); + const outTypes: OutputType[] = [BoolDeserializer()]; + const result = this.wasm.callWasmExport( + 'examples_simple_create_and_verify_proof', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; + } + + testThreads(threads: number, iterations: number): number { + const inArgs = [threads, iterations].map(serializeBufferable); + const outTypes: OutputType[] = [NumberDeserializer()]; + const result = this.wasm.callWasmExport( + 'test_threads', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; + } + + commonInitSlabAllocator(circuitSize: number): void { + const inArgs = [circuitSize].map(serializeBufferable); + const outTypes: OutputType[] = []; + const result = this.wasm.callWasmExport( + 'common_init_slab_allocator', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return; + } + + acirGetCircuitSizes(constraintSystemBuf: Uint8Array): [number, number, number] { + const inArgs = [constraintSystemBuf].map(serializeBufferable); + const outTypes: OutputType[] = [NumberDeserializer(), NumberDeserializer(), NumberDeserializer()]; + const result = this.wasm.callWasmExport( + 'acir_get_circuit_sizes', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out as any; + } + + acirNewAcirComposer(sizeHint: number): Ptr { + const inArgs = [sizeHint].map(serializeBufferable); + const outTypes: OutputType[] = [Ptr]; + const result = this.wasm.callWasmExport( + 'acir_new_acir_composer', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; + } + + acirDeleteAcirComposer(acirComposerPtr: Ptr): void { + const inArgs = [acirComposerPtr].map(serializeBufferable); + const outTypes: OutputType[] = []; + const result = this.wasm.callWasmExport( + 'acir_delete_acir_composer', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return; + } + + acirCreateCircuit(acirComposerPtr: Ptr, constraintSystemBuf: Uint8Array, sizeHint: number): void { + const inArgs = [acirComposerPtr, constraintSystemBuf, sizeHint].map(serializeBufferable); + const outTypes: OutputType[] = []; + const result = this.wasm.callWasmExport( + 'acir_create_circuit', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return; + } + + acirInitProvingKey(acirComposerPtr: Ptr, constraintSystemBuf: Uint8Array): void { + const inArgs = [acirComposerPtr, constraintSystemBuf].map(serializeBufferable); + const outTypes: OutputType[] = []; + const result = this.wasm.callWasmExport( + 'acir_init_proving_key', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return; + } + + acirCreateProof( + acirComposerPtr: Ptr, + constraintSystemBuf: Uint8Array, + witnessBuf: Uint8Array, + isRecursive: boolean, + ): Uint8Array { + const inArgs = [acirComposerPtr, constraintSystemBuf, witnessBuf, isRecursive].map(serializeBufferable); + const outTypes: OutputType[] = [BufferDeserializer()]; + const result = this.wasm.callWasmExport( + 'acir_create_proof', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; + } + + acirLoadVerificationKey(acirComposerPtr: Ptr, vkBuf: Uint8Array): void { + const inArgs = [acirComposerPtr, vkBuf].map(serializeBufferable); + const outTypes: OutputType[] = []; + const result = this.wasm.callWasmExport( + 'acir_load_verification_key', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return; + } + + acirInitVerificationKey(acirComposerPtr: Ptr): void { + const inArgs = [acirComposerPtr].map(serializeBufferable); + const outTypes: OutputType[] = []; + const result = this.wasm.callWasmExport( + 'acir_init_verification_key', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return; + } + + acirGetVerificationKey(acirComposerPtr: Ptr): Uint8Array { + const inArgs = [acirComposerPtr].map(serializeBufferable); + const outTypes: OutputType[] = [BufferDeserializer()]; + const result = this.wasm.callWasmExport( + 'acir_get_verification_key', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; + } + + acirVerifyProof(acirComposerPtr: Ptr, proofBuf: Uint8Array, isRecursive: boolean): boolean { + const inArgs = [acirComposerPtr, proofBuf, isRecursive].map(serializeBufferable); + const outTypes: OutputType[] = [BoolDeserializer()]; + const result = this.wasm.callWasmExport( + 'acir_verify_proof', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; + } + + acirGetSolidityVerifier(acirComposerPtr: Ptr): string { + const inArgs = [acirComposerPtr].map(serializeBufferable); + const outTypes: OutputType[] = [StringDeserializer()]; + const result = this.wasm.callWasmExport( + 'acir_get_solidity_verifier', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; + } + + acirSerializeProofIntoFields(acirComposerPtr: Ptr, proofBuf: Uint8Array, numInnerPublicInputs: number): Fr[] { + const inArgs = [acirComposerPtr, proofBuf, numInnerPublicInputs].map(serializeBufferable); + const outTypes: OutputType[] = [VectorDeserializer(Fr)]; + const result = this.wasm.callWasmExport( + 'acir_serialize_proof_into_fields', + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), + ); + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out[0]; + } + + acirSerializeVerificationKeyIntoFields(acirComposerPtr: Ptr): [Fr[], Fr] { + const inArgs = [acirComposerPtr].map(serializeBufferable); + const outTypes: OutputType[] = [VectorDeserializer(Fr), Fr]; + const result = this.wasm.callWasmExport( 'acir_serialize_verification_key_into_fields', - [acirComposerPtr], - [VectorDeserializer(Fr), Fr], + inArgs, + outTypes.map(t => t.SIZE_IN_BYTES), ); - return result as any; + const out = result.map((r, i) => outTypes[i].fromBuffer(r)); + return out as any; } } diff --git a/barretenberg/ts/src/barretenberg_binder/index.ts b/barretenberg/ts/src/barretenberg_binder/index.ts deleted file mode 100644 index 5ca0a3e1b68..00000000000 --- a/barretenberg/ts/src/barretenberg_binder/index.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { BarretenbergWasm, BarretenbergWasmWorker } from '../barretenberg_wasm/index.js'; -import { HeapAllocator } from './heap_allocator.js'; -import { Bufferable, OutputType } from '../serialize/index.js'; -import { asyncMap } from '../async_map/index.js'; -// import createDebug from 'debug'; - -// const debug = createDebug('bb.js:barretenberg_binder'); - -/** - * Calls a WASM export function, handles allocating/freeing of memory, and serializing/deserializing to types. - * - * Notes on function binding ABI: - * All functions can have an arbitrary number of input and output args. - * All arguments must be pointers. - * Input args are determined by being const or pointer to const. - * Output args must come after input args. - * All input data is big-endian. - * All output data is big-endian, except output heap alloc pointers. - * As integer types are converted to/from big-endian form, we shouldn't have to worry about memory alignment. (SURE?) - * All functions should return void. - * This binding function is responsible for allocating argument memory (including output memory). - * Variable length output args are allocated on the heap, and the resulting pointer is written to the output arg ptr, - * hence the above statement remains true. - * Binding will free any variable length output args that were allocated on the heap. - */ -export class BarretenbergBinder { - constructor(public wasm: BarretenbergWasm | BarretenbergWasmWorker) {} - - async callWasmExport(funcName: string, inArgs: Bufferable[], outTypes: OutputType[]) { - const alloc = new HeapAllocator(this.wasm); - const inPtrs = await alloc.copyToMemory(inArgs); - const outPtrs = await alloc.getOutputPtrs(outTypes); - await this.wasm.call(funcName, ...inPtrs, ...outPtrs); - const outArgs = await this.deserializeOutputArgs(outTypes, outPtrs, alloc); - await alloc.freeAll(); - return outArgs; - } - - private deserializeOutputArgs(outTypes: OutputType[], outPtrs: number[], alloc: HeapAllocator) { - return asyncMap(outTypes, async (t, i) => { - if (t.SIZE_IN_BYTES) { - const slice = await this.wasm.getMemorySlice(outPtrs[i], outPtrs[i] + t.SIZE_IN_BYTES); - return t.fromBuffer(slice); - } - const slice = await this.wasm.getMemorySlice(outPtrs[i], outPtrs[i] + 4); - const ptr = new DataView(slice.buffer, slice.byteOffset, slice.byteLength).getUint32(0, true); - - // Add our heap buffer to the dealloc list. - alloc.addOutputPtr(ptr); - - // The length will be found in the first 4 bytes of the buffer, big endian. See to_heap_buffer. - const lslice = await this.wasm.getMemorySlice(ptr, ptr + 4); - const length = new DataView(lslice.buffer, lslice.byteOffset, lslice.byteLength).getUint32(0, false); - - const buf = await this.wasm.getMemorySlice(ptr + 4, ptr + 4 + length); - return t.fromBuffer(buf); - }); - } -} diff --git a/barretenberg/ts/src/barretenberg_binder/heap_allocator.ts b/barretenberg/ts/src/barretenberg_wasm/barretenberg_wasm_main/heap_allocator.ts similarity index 61% rename from barretenberg/ts/src/barretenberg_binder/heap_allocator.ts rename to barretenberg/ts/src/barretenberg_wasm/barretenberg_wasm_main/heap_allocator.ts index 08c508e2082..390b32ed0d8 100644 --- a/barretenberg/ts/src/barretenberg_binder/heap_allocator.ts +++ b/barretenberg/ts/src/barretenberg_wasm/barretenberg_wasm_main/heap_allocator.ts @@ -1,6 +1,4 @@ -import { Bufferable, serializeBufferable, OutputType } from '../serialize/index.js'; -import { BarretenbergWasm, BarretenbergWasmWorker } from '../barretenberg_wasm/index.js'; -import { asyncMap } from '../async_map/index.js'; +import { type BarretenbergWasmMain } from './index.js'; /** * Keeps track of heap allocations so they can be easily freed. @@ -15,33 +13,33 @@ export class HeapAllocator { private inScratchRemaining = 1024; private outScratchRemaining = 1024; - constructor(private wasm: BarretenbergWasm | BarretenbergWasmWorker) {} + constructor(private wasm: BarretenbergWasmMain) {} - async copyToMemory(bufferable: Bufferable[]) { - return await asyncMap(bufferable.map(serializeBufferable), async buf => { + copyToMemory(buffers: Uint8Array[]) { + return buffers.map(buf => { if (buf.length <= this.inScratchRemaining) { const ptr = (this.inScratchRemaining -= buf.length); - await this.wasm.writeMemory(ptr, buf); + this.wasm.writeMemory(ptr, buf); return ptr; } else { - const ptr = await this.wasm.call('bbmalloc', buf.length); - await this.wasm.writeMemory(ptr, buf); + const ptr = this.wasm.call('bbmalloc', buf.length); + this.wasm.writeMemory(ptr, buf); this.allocs.push(ptr); return ptr; } }); } - async getOutputPtrs(objs: OutputType[]) { - return await asyncMap(objs, async obj => { + getOutputPtrs(outLens: (number | undefined)[]) { + return outLens.map(len => { // If the obj is variable length, we need a 4 byte ptr to write the serialized data address to. // WARNING: 4 only works with WASM as it has 32 bit memory. - const size = obj.SIZE_IN_BYTES || 4; + const size = len || 4; if (size <= this.outScratchRemaining) { return (this.outScratchRemaining -= size); } else { - const ptr = await this.wasm.call('bbmalloc', size); + const ptr = this.wasm.call('bbmalloc', size); this.allocs.push(ptr); return ptr; } @@ -54,9 +52,9 @@ export class HeapAllocator { } } - async freeAll() { + freeAll() { for (const ptr of this.allocs) { - await this.wasm.call('bbfree', ptr); + this.wasm.call('bbfree', ptr); } } } diff --git a/barretenberg/ts/src/barretenberg_wasm/barretenberg_wasm_main/index.ts b/barretenberg/ts/src/barretenberg_wasm/barretenberg_wasm_main/index.ts index 9cc157552da..a3610705363 100644 --- a/barretenberg/ts/src/barretenberg_wasm/barretenberg_wasm_main/index.ts +++ b/barretenberg/ts/src/barretenberg_wasm/barretenberg_wasm_main/index.ts @@ -6,6 +6,7 @@ import { fetchCode } from '../fetch_code/index.js'; import { createThreadWorker } from '../barretenberg_wasm_thread/factory/node/index.js'; import { type BarretenbergWasmThreadWorker } from '../barretenberg_wasm_thread/index.js'; import { BarretenbergWasmBase } from '../barretenberg_wasm_base/index.js'; +import { HeapAllocator } from './heap_allocator.js'; const debug = createDebug('bb.js:wasm'); @@ -105,6 +106,35 @@ export class BarretenbergWasmMain extends BarretenbergWasmBase { }; /* eslint-enable camelcase */ } + + callWasmExport(funcName: string, inArgs: Uint8Array[], outLens: (number | undefined)[]) { + const alloc = new HeapAllocator(this); + const inPtrs = alloc.copyToMemory(inArgs); + const outPtrs = alloc.getOutputPtrs(outLens); + this.call(funcName, ...inPtrs, ...outPtrs); + const outArgs = this.getOutputArgs(outLens, outPtrs, alloc); + alloc.freeAll(); + return outArgs; + } + + private getOutputArgs(outLens: (number | undefined)[], outPtrs: number[], alloc: HeapAllocator) { + return outLens.map((len, i) => { + if (len) { + return this.getMemorySlice(outPtrs[i], outPtrs[i] + len); + } + const slice = this.getMemorySlice(outPtrs[i], outPtrs[i] + 4); + const ptr = new DataView(slice.buffer, slice.byteOffset, slice.byteLength).getUint32(0, true); + + // Add our heap buffer to the dealloc list. + alloc.addOutputPtr(ptr); + + // The length will be found in the first 4 bytes of the buffer, big endian. See to_heap_buffer. + const lslice = this.getMemorySlice(ptr, ptr + 4); + const length = new DataView(lslice.buffer, lslice.byteOffset, lslice.byteLength).getUint32(0, false); + + return this.getMemorySlice(ptr + 4, ptr + 4 + length); + }); + } } /** diff --git a/barretenberg/ts/src/bindgen/typescript.ts b/barretenberg/ts/src/bindgen/typescript.ts index ada050d1ce2..b62453b95ae 100644 --- a/barretenberg/ts/src/bindgen/typescript.ts +++ b/barretenberg/ts/src/bindgen/typescript.ts @@ -9,27 +9,39 @@ export function generateTypeScriptCode(filename: string) { let output = `// WARNING: FILE CODE GENERATED BY BINDGEN UTILITY. DO NOT EDIT! /* eslint-disable @typescript-eslint/no-unused-vars */ -import { BarretenbergBinder } from '../barretenberg_binder/index.js'; -import { BufferDeserializer, NumberDeserializer, VectorDeserializer, BoolDeserializer, StringDeserializer } from '../serialize/index.js'; +import { BarretenbergWasmWorker, BarretenbergWasm } from '../barretenberg_wasm/index.js'; +import { BufferDeserializer, NumberDeserializer, VectorDeserializer, BoolDeserializer, StringDeserializer, serializeBufferable, OutputType } from '../serialize/index.js'; import { Fr, Fq, Point, Buffer32, Buffer128, Ptr } from '../types/index.js'; +`; + + output += generateClass(functionDeclarations); + output += generateSyncClass(functionDeclarations); + + return output; +} + +function generateClass(functionDeclarations: FunctionDeclaration[]) { + let output = ` export class BarretenbergApi { - constructor(public binder: BarretenbergBinder) {} + constructor(protected wasm: BarretenbergWasmWorker) {} - async destroy() { - await this.binder.wasm.destroy(); - } `; for (const { functionName, inArgs, outArgs } of functionDeclarations) { try { const parameters = inArgs.map(({ name, type }) => `${toCamelCase(name)}: ${mapType(type)}`).join(', '); - const inArgsVar = `[${inArgs.map(arg => toCamelCase(arg.name)).join(', ')}]`; - const outTypesVar = `[${outArgs.map(arg => mapDeserializer(arg.type)).join(', ')}]`; - const wasmCall = `const result = await this.binder.callWasmExport('${functionName}', ${inArgsVar}, ${outTypesVar});`; + const inArgsVar = `const inArgs = [${inArgs + .map(arg => toCamelCase(arg.name)) + .join(', ')}].map(serializeBufferable);`; + const outTypesVar = `const outTypes: OutputType[] = [${outArgs + .map(arg => mapDeserializer(arg.type)) + .join(', ')}];`; + const wasmCall = `const result = await this.wasm.callWasmExport('${functionName}', inArgs, outTypes.map(t=>t.SIZE_IN_BYTES));`; + const outVar = `const out = result.map((r, i) => outTypes[i].fromBuffer(r));`; const n = outArgs.length; - const returnStmt = n === 0 ? 'return;' : n === 1 ? 'return result[0];' : 'return result as any;'; + const returnStmt = n === 0 ? 'return;' : n === 1 ? 'return out[0];' : 'return out as any;'; const returnType = outArgs.length === 0 ? 'void' @@ -39,7 +51,57 @@ export class BarretenbergApi { output += ` async ${toCamelCase(functionName)}(${parameters}): Promise<${returnType}> { + ${inArgsVar} + ${outTypesVar} + ${wasmCall} + ${outVar} + ${returnStmt} + } +`; + } catch (err: any) { + throw new Error(`Function ${functionName}: ${err.message}`); + } + } + + output += `}`; + + return output; +} + +function generateSyncClass(functionDeclarations: FunctionDeclaration[]) { + let output = ` +export class BarretenbergApiSync { + constructor(protected wasm: BarretenbergWasm) {} + +`; + + for (const { functionName, inArgs, outArgs } of functionDeclarations) { + try { + const parameters = inArgs.map(({ name, type }) => `${toCamelCase(name)}: ${mapType(type)}`).join(', '); + const inArgsVar = `const inArgs = [${inArgs + .map(arg => toCamelCase(arg.name)) + .join(', ')}].map(serializeBufferable);`; + const outTypesVar = `const outTypes: OutputType[] = [${outArgs + .map(arg => mapDeserializer(arg.type)) + .join(', ')}];`; + const wasmCall = `const result = this.wasm.callWasmExport('${functionName}', inArgs, outTypes.map(t=>t.SIZE_IN_BYTES));`; + const outVar = `const out = result.map((r, i) => outTypes[i].fromBuffer(r));`; + + const n = outArgs.length; + const returnStmt = n === 0 ? 'return;' : n === 1 ? 'return out[0];' : 'return out as any;'; + const returnType = + outArgs.length === 0 + ? 'void' + : outArgs.length === 1 + ? `${mapType(outArgs[0].type)}` + : `[${outArgs.map(a => mapType(a.type)).join(', ')}]`; + + output += ` + ${toCamelCase(functionName)}(${parameters}): ${returnType} { + ${inArgsVar} + ${outTypesVar} ${wasmCall} + ${outVar} ${returnStmt} } `; diff --git a/barretenberg/ts/src/index.ts b/barretenberg/ts/src/index.ts index b088e2a2ce5..49ce2404202 100644 --- a/barretenberg/ts/src/index.ts +++ b/barretenberg/ts/src/index.ts @@ -1,4 +1,3 @@ export { Crs } from './crs/index.js'; -export { Barretenberg } from './barretenberg/index.js'; +export { Barretenberg, BarretenbergSync } from './barretenberg/index.js'; export { RawBuffer, Fr } from './types/index.js'; -export { Pedersen } from './pedersen/index.js'; diff --git a/barretenberg/ts/src/pedersen/index.ts b/barretenberg/ts/src/pedersen/index.ts deleted file mode 100644 index 41d557571b3..00000000000 --- a/barretenberg/ts/src/pedersen/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './pedersen.js'; diff --git a/barretenberg/ts/src/pedersen/pedersen.test.ts b/barretenberg/ts/src/pedersen/pedersen.test.ts deleted file mode 100644 index 12721e3d630..00000000000 --- a/barretenberg/ts/src/pedersen/pedersen.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { Pedersen } from './pedersen.js'; -import { Timer } from '../benchmark/timer.js'; -import { Fr } from '../types/index.js'; - -describe('pedersen sync', () => { - it('pedersenHash', async () => { - const pedersen = await Pedersen.new(); - const result = pedersen.pedersenHash([new Fr(4n).toBuffer(), new Fr(8n).toBuffer()], 7); - expect(result).toEqual( - new Fr(2152386650411553803409271316104075950536496387580531018130718456431861859990n).toBuffer(), - ); - }); - - it('pedersenCommit', async () => { - const pedersen = await Pedersen.new(); - const result = pedersen.pedersenCommit([new Fr(4n).toBuffer(), new Fr(8n).toBuffer(), new Fr(12n).toBuffer()]); - expect(result).toEqual([ - new Fr(18374309251862457296563484909553154519357910650678202211610516068880120638872n).toBuffer(), - new Fr(2572141322478528249692953821523229170092797347760799983831061874108357705739n).toBuffer(), - ]); - }); - - it.skip('pedersenCommit perf test', async () => { - const pedersen = await Pedersen.new(); - const loops = 1000; - const fields = Array.from({ length: loops * 2 }).map(() => Fr.random()); - const t = new Timer(); - for (let i = 0; i < loops; ++i) { - pedersen.pedersenCommit([fields[i * 2].toBuffer(), fields[i * 2 + 1].toBuffer()]); - } - console.log(t.us() / loops); - }); -}); diff --git a/barretenberg/ts/src/pedersen/pedersen.ts b/barretenberg/ts/src/pedersen/pedersen.ts deleted file mode 100644 index be9028cbd86..00000000000 --- a/barretenberg/ts/src/pedersen/pedersen.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { BarretenbergWasmMain } from '../barretenberg_wasm/barretenberg_wasm_main/index.js'; -import { numToUInt32BE, serializeBufferArrayToVector } from '../serialize/serialize.js'; - -export class Pedersen { - constructor(public wasm: BarretenbergWasmMain) {} - - static async new() { - const wasm = new BarretenbergWasmMain(); - await wasm.init(1); - return new Pedersen(wasm); - } - - pedersenHash(inputs: Uint8Array[], hashIndex = 0) { - const SCRATCH_SPACE_SIZE = 1024; - - const data = serializeBufferArrayToVector(inputs); - - let inputPtr = 0; - if (data.length > SCRATCH_SPACE_SIZE - 4) { - inputPtr = this.wasm.call('bbmalloc', data.length); - } - this.wasm.writeMemory(inputPtr, data); - this.wasm.writeMemory(SCRATCH_SPACE_SIZE - 4, numToUInt32BE(hashIndex)); - - const outputPtr = 0; - this.wasm.call('pedersen_hash', inputPtr, SCRATCH_SPACE_SIZE - 4, outputPtr); - const hashOutput = this.wasm.getMemorySlice(0, 32); - - if (inputPtr !== 0) { - this.wasm.call('bbfree', inputPtr); - } - - return hashOutput; - } - - pedersenCommit(inputs: Uint8Array[]) { - const SCRATCH_SPACE_SIZE = 1024; - - const data = serializeBufferArrayToVector(inputs); - - let inputPtr = 0; - if (data.length > SCRATCH_SPACE_SIZE) { - inputPtr = this.wasm.call('bbmalloc', data.length); - } - this.wasm.writeMemory(inputPtr, data); - - const outputPtr = 0; - this.wasm.call('pedersen_commit', inputPtr, outputPtr); - const hashOutput = this.wasm.getMemorySlice(0, 64); - - if (inputPtr !== 0) { - this.wasm.call('bbfree', inputPtr); - } - - return [hashOutput.slice(0, 32), hashOutput.slice(32, 64)]; - } -} diff --git a/yarn-project/acir-simulator/package.json b/yarn-project/acir-simulator/package.json index c1a7dda3a84..82bc63e4a88 100644 --- a/yarn-project/acir-simulator/package.json +++ b/yarn-project/acir-simulator/package.json @@ -42,7 +42,6 @@ "@aztec/merkle-tree": "workspace:^", "@aztec/noir-contracts": "workspace:^", "@jest/globals": "^29.5.0", - "@rushstack/eslint-patch": "^1.1.4", "@types/jest": "^29.5.0", "@types/levelup": "^5.1.3", "@types/memdown": "^3.0.2", diff --git a/yarn-project/acir-simulator/src/client/private_execution.test.ts b/yarn-project/acir-simulator/src/client/private_execution.test.ts index 61ac920141e..3edeb1b70cd 100644 --- a/yarn-project/acir-simulator/src/client/private_execution.test.ts +++ b/yarn-project/acir-simulator/src/client/private_execution.test.ts @@ -1,6 +1,5 @@ import { CallContext, - CircuitsWasm, CompleteAddress, ContractDeploymentData, EMPTY_NULLIFIED_COMMITMENT, @@ -144,11 +143,11 @@ describe('Private Execution test suite', () => { const hashFields = (data: Fr[]) => Fr.fromBuffer(pedersenHash(data.map(f => f.toBuffer()))); - beforeAll(async () => { + beforeAll(() => { logger = createDebugLogger('aztec:test:private_execution'); - ownerCompleteAddress = await CompleteAddress.fromPrivateKeyAndPartialAddress(ownerPk, Fr.random()); - recipientCompleteAddress = await CompleteAddress.fromPrivateKeyAndPartialAddress(recipientPk, Fr.random()); + ownerCompleteAddress = CompleteAddress.fromPrivateKeyAndPartialAddress(ownerPk, Fr.random()); + recipientCompleteAddress = CompleteAddress.fromPrivateKeyAndPartialAddress(recipientPk, Fr.random()); owner = ownerCompleteAddress.address; recipient = recipientCompleteAddress.address; @@ -364,8 +363,7 @@ describe('Private Execution test suite', () => { expect(result.nestedExecutions[0].callStackItem.publicInputs.returnValues[0]).toEqual(new Fr(privateIncrement)); // check that Aztec.nr calculated the call stack item hash like cpp does - const wasm = await CircuitsWasm.get(); - const expectedCallStackItemHash = computeCallStackItemHash(wasm, result.nestedExecutions[0].callStackItem); + const expectedCallStackItemHash = computeCallStackItemHash(result.nestedExecutions[0].callStackItem); expect(result.callStackItem.publicInputs.privateCallStack[0]).toEqual(expectedCallStackItemHash); }); }); @@ -549,10 +547,7 @@ describe('Private Execution test suite', () => { sideEffectCounter: 0, }); - const publicCallRequestHash = computeCallStackItemHash( - await CircuitsWasm.get(), - publicCallRequest.toPublicCallStackItem(), - ); + const publicCallRequestHash = computeCallStackItemHash(publicCallRequest.toPublicCallStackItem()); expect(result.enqueuedPublicFunctionCalls).toHaveLength(1); expect(result.enqueuedPublicFunctionCalls[0]).toEqual(publicCallRequest); diff --git a/yarn-project/acir-simulator/src/client/simulator.test.ts b/yarn-project/acir-simulator/src/client/simulator.test.ts index e24d2de37a2..ea4878704e2 100644 --- a/yarn-project/acir-simulator/src/client/simulator.test.ts +++ b/yarn-project/acir-simulator/src/client/simulator.test.ts @@ -22,8 +22,8 @@ describe('Simulator', () => { const hashFields = (data: Fr[]) => Fr.fromBuffer(pedersenHash(data.map(f => f.toBuffer()))); - beforeAll(async () => { - ownerCompleteAddress = await CompleteAddress.fromPrivateKeyAndPartialAddress(ownerPk, Fr.random()); + beforeAll(() => { + ownerCompleteAddress = CompleteAddress.fromPrivateKeyAndPartialAddress(ownerPk, Fr.random()); owner = ownerCompleteAddress.address; }); diff --git a/yarn-project/acir-simulator/src/client/simulator.ts b/yarn-project/acir-simulator/src/client/simulator.ts index 092fa49b735..73a44bf4000 100644 --- a/yarn-project/acir-simulator/src/client/simulator.ts +++ b/yarn-project/acir-simulator/src/client/simulator.ts @@ -75,7 +75,7 @@ export class AcirSimulator { ); } - const curve = await Grumpkin.new(); + const curve = new Grumpkin(); const historicBlockData = await this.db.getHistoricBlockData(); const callContext = new CallContext( @@ -94,7 +94,7 @@ export class AcirSimulator { callContext, historicBlockData, request.authWitnesses, - await PackedArgsCache.create(request.packedArguments), + PackedArgsCache.create(request.packedArguments), new ExecutionNoteCache(), new SideEffectCounter(), this.db, diff --git a/yarn-project/acir-simulator/src/client/unconstrained_execution.test.ts b/yarn-project/acir-simulator/src/client/unconstrained_execution.test.ts index 8cfdf278a2b..6abcd8a2bc6 100644 --- a/yarn-project/acir-simulator/src/client/unconstrained_execution.test.ts +++ b/yarn-project/acir-simulator/src/client/unconstrained_execution.test.ts @@ -28,8 +28,8 @@ describe('Unconstrained Execution test suite', () => { return new Note([new Fr(amount), owner.toField(), Fr.random()]); }; - beforeEach(async () => { - const ownerCompleteAddress = await CompleteAddress.fromPrivateKeyAndPartialAddress(ownerPk, Fr.random()); + beforeEach(() => { + const ownerCompleteAddress = CompleteAddress.fromPrivateKeyAndPartialAddress(ownerPk, Fr.random()); owner = ownerCompleteAddress.address; oracle.getCompleteAddress.mockImplementation((address: AztecAddress) => { diff --git a/yarn-project/acir-simulator/src/common/packed_args_cache.ts b/yarn-project/acir-simulator/src/common/packed_args_cache.ts index fc120f7daf7..09995363b41 100644 --- a/yarn-project/acir-simulator/src/common/packed_args_cache.ts +++ b/yarn-project/acir-simulator/src/common/packed_args_cache.ts @@ -1,4 +1,4 @@ -import { CircuitsWasm, Fr } from '@aztec/circuits.js'; +import { Fr } from '@aztec/circuits.js'; import { PackedArguments } from '@aztec/types'; /** @@ -7,7 +7,7 @@ import { PackedArguments } from '@aztec/types'; export class PackedArgsCache { private cache: Map; - constructor(initialArguments: PackedArguments[] = [], private wasm: CircuitsWasm) { + constructor(initialArguments: PackedArguments[] = []) { this.cache = new Map(); for (const initialArg of initialArguments) { this.cache.set(initialArg.hash.value, initialArg.args); @@ -19,9 +19,8 @@ export class PackedArgsCache { * @param initialArguments - The initial arguments to add to the cache. * @returns The new packed arguments cache. */ - public static async create(initialArguments: PackedArguments[] = []): Promise { - const wasm = await CircuitsWasm.get(); - return new PackedArgsCache(initialArguments, wasm); + public static create(initialArguments: PackedArguments[] = []) { + return new PackedArgsCache(initialArguments); } /** diff --git a/yarn-project/acir-simulator/src/public/executor.ts b/yarn-project/acir-simulator/src/public/executor.ts index ca626a1812b..8298aaed90b 100644 --- a/yarn-project/acir-simulator/src/public/executor.ts +++ b/yarn-project/acir-simulator/src/public/executor.ts @@ -97,7 +97,7 @@ export class PublicExecutor { // Functions can request to pack arguments before calling other functions. // We use this cache to hold the packed arguments. - const packedArgs = await PackedArgsCache.create([]); + const packedArgs = PackedArgsCache.create([]); const sideEffectCounter = new SideEffectCounter(); diff --git a/yarn-project/archiver/package.json b/yarn-project/archiver/package.json index 368309c1bb7..6d0c6491c3a 100644 --- a/yarn-project/archiver/package.json +++ b/yarn-project/archiver/package.json @@ -49,7 +49,6 @@ }, "devDependencies": { "@jest/globals": "^29.5.0", - "@rushstack/eslint-patch": "^1.2.0", "@types/debug": "^4.1.7", "@types/jest": "^29.5.0", "@types/node": "^18.15.11", diff --git a/yarn-project/aztec-faucet/package.json b/yarn-project/aztec-faucet/package.json index fcf3526dbd5..dfbd3ab364d 100644 --- a/yarn-project/aztec-faucet/package.json +++ b/yarn-project/aztec-faucet/package.json @@ -41,7 +41,6 @@ }, "devDependencies": { "@jest/globals": "^29.5.0", - "@rushstack/eslint-patch": "^1.1.4", "@types/jest": "^29.5.0", "@types/node": "^18.7.23", "jest": "^29.5.0", diff --git a/yarn-project/aztec-node/package.json b/yarn-project/aztec-node/package.json index 7e0fed0de53..b9c9454a972 100644 --- a/yarn-project/aztec-node/package.json +++ b/yarn-project/aztec-node/package.json @@ -51,7 +51,6 @@ }, "devDependencies": { "@jest/globals": "^29.5.0", - "@rushstack/eslint-patch": "^1.1.4", "@types/jest": "^29.5.0", "@types/leveldown": "^4.0.4", "@types/levelup": "^5.1.2", diff --git a/yarn-project/aztec-sandbox/src/bin/index.ts b/yarn-project/aztec-sandbox/src/bin/index.ts index 7ee0228b2fa..5ddfdd32562 100644 --- a/yarn-project/aztec-sandbox/src/bin/index.ts +++ b/yarn-project/aztec-sandbox/src/bin/index.ts @@ -74,7 +74,7 @@ async function main() { const registeredAccounts = await pxe.getRegisteredAccounts(); for (const account of accounts) { - const completeAddress = await account.account.getCompleteAddress(); + const completeAddress = account.account.getCompleteAddress(); if (registeredAccounts.find(a => a.equals(completeAddress))) { accountStrings.push(` Address: ${completeAddress.address.toString()}\n`); accountStrings.push(` Partial Address: ${completeAddress.partialAddress.toString()}\n`); diff --git a/yarn-project/aztec.js/package.json b/yarn-project/aztec.js/package.json index c0008cd00c4..2be692b3475 100644 --- a/yarn-project/aztec.js/package.json +++ b/yarn-project/aztec.js/package.json @@ -49,7 +49,6 @@ }, "devDependencies": { "@jest/globals": "^29.5.0", - "@rushstack/eslint-patch": "^1.1.4", "@types/jest": "^29.5.0", "@types/lodash.every": "^4.6.7", "@types/lodash.partition": "^4.6.0", diff --git a/yarn-project/aztec.js/src/account/contract/base_account_contract.ts b/yarn-project/aztec.js/src/account/contract/base_account_contract.ts index d749a767fe8..c0123c8ad14 100644 --- a/yarn-project/aztec.js/src/account/contract/base_account_contract.ts +++ b/yarn-project/aztec.js/src/account/contract/base_account_contract.ts @@ -11,7 +11,7 @@ import { AccountContract } from './index.js'; */ export abstract class BaseAccountContract implements AccountContract { abstract getAuthWitnessProvider(address: CompleteAddress): AuthWitnessProvider; - abstract getDeploymentArgs(): Promise; + abstract getDeploymentArgs(): any[]; constructor(private artifact: ContractArtifact) {} @@ -19,7 +19,7 @@ export abstract class BaseAccountContract implements AccountContract { return this.artifact; } - getInterface(address: CompleteAddress, nodeInfo: NodeInfo): Promise { - return Promise.resolve(new DefaultAccountInterface(this.getAuthWitnessProvider(address), address, nodeInfo)); + getInterface(address: CompleteAddress, nodeInfo: NodeInfo): AccountInterface { + return new DefaultAccountInterface(this.getAuthWitnessProvider(address), address, nodeInfo); } } diff --git a/yarn-project/aztec.js/src/account/contract/ecdsa_account_contract.ts b/yarn-project/aztec.js/src/account/contract/ecdsa_account_contract.ts index d238b8c417f..8820fbced7f 100644 --- a/yarn-project/aztec.js/src/account/contract/ecdsa_account_contract.ts +++ b/yarn-project/aztec.js/src/account/contract/ecdsa_account_contract.ts @@ -16,8 +16,8 @@ export class EcdsaAccountContract extends BaseAccountContract { super(EcdsaAccountContractArtifact as ContractArtifact); } - async getDeploymentArgs() { - const signingPublicKey = await Ecdsa.new().then(e => e.computePublicKey(this.signingPrivateKey)); + getDeploymentArgs() { + const signingPublicKey = new Ecdsa().computePublicKey(this.signingPrivateKey); return [signingPublicKey.subarray(0, 32), signingPublicKey.subarray(32, 64)]; } @@ -30,9 +30,9 @@ export class EcdsaAccountContract extends BaseAccountContract { class EcdsaAuthWitnessProvider implements AuthWitnessProvider { constructor(private signingPrivateKey: Buffer) {} - async createAuthWitness(message: Fr): Promise { - const ecdsa = await Ecdsa.new(); + createAuthWitness(message: Fr): Promise { + const ecdsa = new Ecdsa(); const signature = ecdsa.constructSignature(message.toBuffer(), this.signingPrivateKey); - return new AuthWitness(message, [...signature.r, ...signature.s]); + return Promise.resolve(new AuthWitness(message, [...signature.r, ...signature.s])); } } diff --git a/yarn-project/aztec.js/src/account/contract/index.ts b/yarn-project/aztec.js/src/account/contract/index.ts index 611721b64c8..f0ac2fcd717 100644 --- a/yarn-project/aztec.js/src/account/contract/index.ts +++ b/yarn-project/aztec.js/src/account/contract/index.ts @@ -22,7 +22,7 @@ export interface AccountContract { /** * Returns the deployment arguments for this instance. */ - getDeploymentArgs(): Promise; + getDeploymentArgs(): any[]; /** * Returns the account interface for this account contract given a deployment at the provided address. @@ -32,6 +32,6 @@ export interface AccountContract { * @param nodeInfo - Info on the chain where it is deployed. * @returns An account interface instance for creating tx requests and authorizing actions. */ - getInterface(address: CompleteAddress, nodeInfo: NodeInfo): Promise; + getInterface(address: CompleteAddress, nodeInfo: NodeInfo): AccountInterface; } // docs:end:account-contract-interface diff --git a/yarn-project/aztec.js/src/account/contract/schnorr_account_contract.ts b/yarn-project/aztec.js/src/account/contract/schnorr_account_contract.ts index 2f963a468de..cd6cec3791b 100644 --- a/yarn-project/aztec.js/src/account/contract/schnorr_account_contract.ts +++ b/yarn-project/aztec.js/src/account/contract/schnorr_account_contract.ts @@ -16,8 +16,8 @@ export class SchnorrAccountContract extends BaseAccountContract { super(SchnorrAccountContractArtifact as ContractArtifact); } - async getDeploymentArgs() { - const signingPublicKey = await Schnorr.new().then(e => e.computePublicKey(this.signingPrivateKey)); + getDeploymentArgs() { + const signingPublicKey = new Schnorr().computePublicKey(this.signingPrivateKey); return [signingPublicKey.x, signingPublicKey.y]; } @@ -30,9 +30,9 @@ export class SchnorrAccountContract extends BaseAccountContract { class SchnorrAuthWitnessProvider implements AuthWitnessProvider { constructor(private signingPrivateKey: GrumpkinPrivateKey) {} - async createAuthWitness(message: Fr): Promise { - const schnorr = await Schnorr.new(); + createAuthWitness(message: Fr): Promise { + const schnorr = new Schnorr(); const signature = schnorr.constructSignature(message.toBuffer(), this.signingPrivateKey).toBuffer(); - return new AuthWitness(message, [...signature]); + return Promise.resolve(new AuthWitness(message, [...signature])); } } diff --git a/yarn-project/aztec.js/src/account/contract/single_key_account_contract.ts b/yarn-project/aztec.js/src/account/contract/single_key_account_contract.ts index 63cfc44524e..c2b1bffa2fb 100644 --- a/yarn-project/aztec.js/src/account/contract/single_key_account_contract.ts +++ b/yarn-project/aztec.js/src/account/contract/single_key_account_contract.ts @@ -18,8 +18,8 @@ export class SingleKeyAccountContract extends BaseAccountContract { super(SchnorrSingleKeyAccountContractArtifact as ContractArtifact); } - getDeploymentArgs(): Promise { - return Promise.resolve([]); + getDeploymentArgs(): any[] { + return []; } getAuthWitnessProvider({ partialAddress }: CompleteAddress): AuthWitnessProvider { @@ -35,11 +35,11 @@ export class SingleKeyAccountContract extends BaseAccountContract { class SingleKeyAuthWitnessProvider implements AuthWitnessProvider { constructor(private privateKey: GrumpkinPrivateKey, private partialAddress: PartialAddress) {} - async createAuthWitness(message: Fr): Promise { - const schnorr = await Schnorr.new(); + createAuthWitness(message: Fr): Promise { + const schnorr = new Schnorr(); const signature = schnorr.constructSignature(message.toBuffer(), this.privateKey); - const publicKey = await generatePublicKey(this.privateKey); + const publicKey = generatePublicKey(this.privateKey); const witness = [...publicKey.toFields(), ...signature.toBuffer(), this.partialAddress]; - return new AuthWitness(message, witness); + return Promise.resolve(new AuthWitness(message, witness)); } } diff --git a/yarn-project/aztec.js/src/account/defaults/default_interface.ts b/yarn-project/aztec.js/src/account/defaults/default_interface.ts index f59bbdf7dae..ff981933292 100644 --- a/yarn-project/aztec.js/src/account/defaults/default_interface.ts +++ b/yarn-project/aztec.js/src/account/defaults/default_interface.ts @@ -27,9 +27,11 @@ export class DefaultAccountInterface implements AccountInterface { createTxExecutionRequest(executions: FunctionCall[]): Promise { return this.entrypoint.createTxExecutionRequest(executions); } + createAuthWitness(message: Fr): Promise { return this.authWitnessProvider.createAuthWitness(message); } + getCompleteAddress(): CompleteAddress { return this.address; } diff --git a/yarn-project/aztec.js/src/account/index.ts b/yarn-project/aztec.js/src/account/index.ts index 9c240bba333..eab0d934492 100644 --- a/yarn-project/aztec.js/src/account/index.ts +++ b/yarn-project/aztec.js/src/account/index.ts @@ -119,6 +119,6 @@ export async function getWallet( throw new Error(`Account ${address} not found`); } const nodeInfo = await pxe.getNodeInfo(); - const entrypoint = await accountContract.getInterface(completeAddress, nodeInfo); + const entrypoint = accountContract.getInterface(completeAddress, nodeInfo); return new AccountWallet(pxe, entrypoint); } diff --git a/yarn-project/aztec.js/src/account/manager/index.ts b/yarn-project/aztec.js/src/account/manager/index.ts index ace65bf7999..00ac6ec9395 100644 --- a/yarn-project/aztec.js/src/account/manager/index.ts +++ b/yarn-project/aztec.js/src/account/manager/index.ts @@ -40,9 +40,9 @@ export class AccountManager { } } - protected async getEncryptionPublicKey() { + protected getEncryptionPublicKey() { if (!this.encryptionPublicKey) { - this.encryptionPublicKey = await generatePublicKey(this.encryptionPrivateKey); + this.encryptionPublicKey = generatePublicKey(this.encryptionPrivateKey); } return this.encryptionPublicKey; } @@ -53,7 +53,7 @@ export class AccountManager { */ public async getAccount(): Promise { const nodeInfo = await this.pxe.getNodeInfo(); - const completeAddress = await this.getCompleteAddress(); + const completeAddress = this.getCompleteAddress(); return this.accountContract.getInterface(completeAddress, nodeInfo); } @@ -62,12 +62,12 @@ export class AccountManager { * Does not require the account to be deployed or registered. * @returns The address, partial address, and encryption public key. */ - public async getCompleteAddress(): Promise { + public getCompleteAddress(): CompleteAddress { if (!this.completeAddress) { - const encryptionPublicKey = await generatePublicKey(this.encryptionPrivateKey); - const contractDeploymentInfo = await getContractDeploymentInfo( + const encryptionPublicKey = generatePublicKey(this.encryptionPrivateKey); + const contractDeploymentInfo = getContractDeploymentInfo( this.accountContract.getContractArtifact(), - await this.accountContract.getDeploymentArgs(), + this.accountContract.getDeploymentArgs(), this.salt!, encryptionPublicKey, ); @@ -109,9 +109,9 @@ export class AccountManager { if (!this.deployMethod) { if (!this.salt) throw new Error(`Cannot deploy account contract without known salt.`); await this.#register(); - const encryptionPublicKey = await this.getEncryptionPublicKey(); + const encryptionPublicKey = this.getEncryptionPublicKey(); const deployer = new ContractDeployer(this.accountContract.getContractArtifact(), this.pxe, encryptionPublicKey); - const args = await this.accountContract.getDeploymentArgs(); + const args = this.accountContract.getDeploymentArgs(); this.deployMethod = deployer.deploy(...args); } return this.deployMethod; @@ -147,7 +147,7 @@ export class AccountManager { } async #register(): Promise { - const completeAddress = await this.getCompleteAddress(); + const completeAddress = this.getCompleteAddress(); await this.pxe.registerAccount(this.encryptionPrivateKey, completeAddress.partialAddress); return completeAddress; } diff --git a/yarn-project/aztec.js/src/contract_deployer/deploy_method.ts b/yarn-project/aztec.js/src/contract_deployer/deploy_method.ts index d2ad1a95416..b1536f90b45 100644 --- a/yarn-project/aztec.js/src/contract_deployer/deploy_method.ts +++ b/yarn-project/aztec.js/src/contract_deployer/deploy_method.ts @@ -67,7 +67,7 @@ export class DeployMethod extends Bas const { chainId, protocolVersion } = await this.pxe.getNodeInfo(); - const { completeAddress, constructorHash, functionTreeRoot } = await getContractDeploymentInfo( + const { completeAddress, constructorHash, functionTreeRoot } = getContractDeploymentInfo( this.artifact, this.args, contractAddressSalt, diff --git a/yarn-project/aztec.js/src/utils/cheat_codes.ts b/yarn-project/aztec.js/src/utils/cheat_codes.ts index 9833ef02398..7cca38d7ff5 100644 --- a/yarn-project/aztec.js/src/utils/cheat_codes.ts +++ b/yarn-project/aztec.js/src/utils/cheat_codes.ts @@ -1,4 +1,4 @@ -import { AztecAddress, CircuitsWasm, EthAddress, Fr } from '@aztec/circuits.js'; +import { AztecAddress, EthAddress, Fr } from '@aztec/circuits.js'; import { toBigIntBE, toHex } from '@aztec/foundation/bigint-buffer'; import { keccak, pedersenHash } from '@aztec/foundation/crypto'; import { createDebugLogger } from '@aztec/foundation/log'; @@ -21,9 +21,9 @@ export class CheatCodes { public aztec: AztecCheatCodes, ) {} - static async create(rpcUrl: string, pxe: PXE): Promise { + static create(rpcUrl: string, pxe: PXE): CheatCodes { const ethCheatCodes = new EthCheatCodes(rpcUrl); - const aztecCheatCodes = new AztecCheatCodes(pxe, await CircuitsWasm.get(), ethCheatCodes); + const aztecCheatCodes = new AztecCheatCodes(pxe, ethCheatCodes); return new CheatCodes(ethCheatCodes, aztecCheatCodes); } } @@ -211,10 +211,6 @@ export class AztecCheatCodes { * The PXE Service to use for interacting with the chain */ public pxe: PXE, - /** - * The circuits wasm module used for pedersen hashing - */ - public wasm: CircuitsWasm, /** * The eth cheat codes. */ diff --git a/yarn-project/aztec.js/src/utils/pub_key.ts b/yarn-project/aztec.js/src/utils/pub_key.ts index 14b317569de..5e04f00a1e2 100644 --- a/yarn-project/aztec.js/src/utils/pub_key.ts +++ b/yarn-project/aztec.js/src/utils/pub_key.ts @@ -6,7 +6,7 @@ import { Grumpkin } from '@aztec/circuits.js/barretenberg'; * @param privateKey - The private key. * @returns The generated public key. */ -export async function generatePublicKey(privateKey: GrumpkinPrivateKey): Promise { - const grumpkin = await Grumpkin.new(); +export function generatePublicKey(privateKey: GrumpkinPrivateKey): PublicKey { + const grumpkin = new Grumpkin(); return grumpkin.mul(grumpkin.generator(), privateKey); } diff --git a/yarn-project/canary/package.json b/yarn-project/canary/package.json index 8952f796622..dc95e326550 100644 --- a/yarn-project/canary/package.json +++ b/yarn-project/canary/package.json @@ -41,9 +41,6 @@ "typescript": "^5.0.4", "viem": "^1.2.5" }, - "devDependencies": { - "@rushstack/eslint-patch": "^1.1.4" - }, "files": [ "dest", "src", diff --git a/yarn-project/circuits.js/package.json b/yarn-project/circuits.js/package.json index 120d66964e5..cf92e53a361 100644 --- a/yarn-project/circuits.js/package.json +++ b/yarn-project/circuits.js/package.json @@ -39,6 +39,7 @@ "rootDir": "./src" }, "dependencies": { + "@aztec/bb.js": "portal:../../barretenberg/ts", "@aztec/foundation": "workspace:^", "@msgpack/msgpack": "^3.0.0-beta2", "@noble/curves": "^1.0.0", diff --git a/yarn-project/circuits.js/src/abis/abis.test.ts b/yarn-project/circuits.js/src/abis/abis.test.ts index 79413a36c10..76ab742fa12 100644 --- a/yarn-project/circuits.js/src/abis/abis.test.ts +++ b/yarn-project/circuits.js/src/abis/abis.test.ts @@ -18,7 +18,6 @@ import { makeTxRequest, makeVerificationKey, } from '../tests/factories.js'; -import { CircuitsWasm } from '../wasm/circuits_wasm.js'; import { computeBlockHashWithGlobals, computeCallStackItemHash, @@ -44,11 +43,6 @@ import { } from './abis.js'; describe('abis wasm bindings', () => { - let wasm: CircuitsWasm; - beforeAll(async () => { - wasm = await CircuitsWasm.get(); - }); - it('hashes a tx request', () => { const txRequest = makeTxRequest(); const hash = hashTxRequest(txRequest); @@ -63,7 +57,7 @@ describe('abis wasm bindings', () => { it('hashes VK', () => { const vk = makeVerificationKey(); - const res = hashVK(wasm, vk.toBuffer()); + const res = hashVK(vk.toBuffer()); expect(res).toMatchSnapshot(); }); @@ -74,7 +68,7 @@ describe('abis wasm bindings', () => { }); it('computes function tree root', () => { - const res = computeFunctionTreeRoot(wasm, [new Fr(0n), new Fr(0n), new Fr(0n), new Fr(0n)]); + const res = computeFunctionTreeRoot([new Fr(0n), new Fr(0n), new Fr(0n), new Fr(0n)]); expect(res).toMatchSnapshot(); }); @@ -215,13 +209,13 @@ describe('abis wasm bindings', () => { it('compute private call stack item hash', () => { const item = makePrivateCallStackItem(); - const hash = computeCallStackItemHash(wasm, item); + const hash = computeCallStackItemHash(item); expect(hash).toMatchSnapshot(); }); it('compute public call stack item hash', () => { const item = makePublicCallStackItem(); - const hash = computeCallStackItemHash(wasm, item); + const hash = computeCallStackItemHash(item); expect(hash).toMatchSnapshot(); }); diff --git a/yarn-project/circuits.js/src/abis/abis.ts b/yarn-project/circuits.js/src/abis/abis.ts index bd9740cc1a0..961795ae1a3 100644 --- a/yarn-project/circuits.js/src/abis/abis.ts +++ b/yarn-project/circuits.js/src/abis/abis.ts @@ -1,15 +1,17 @@ import { padArrayEnd } from '@aztec/foundation/collection'; -import { keccak, pedersenHash } from '@aztec/foundation/crypto'; -import { numToUInt32BE } from '@aztec/foundation/serialize'; -import { IWasmModule } from '@aztec/foundation/wasm'; +import { keccak, pedersenHash, pedersenHashBuffer } from '@aztec/foundation/crypto'; +import { numToUInt8, numToUInt16BE, numToUInt32BE } from '@aztec/foundation/serialize'; import { Buffer } from 'buffer'; import chunk from 'lodash.chunk'; import { AztecAddress, + CallContext, CompleteAddress, ContractDeploymentData, + ContractStorageRead, + ContractStorageUpdateRequest, FUNCTION_SELECTOR_NUM_BYTES, FUNCTION_TREE_HEIGHT, Fr, @@ -18,50 +20,22 @@ import { GeneratorIndex, GlobalVariables, NewContractData, + PRIVATE_CIRCUIT_PUBLIC_INPUTS_HASH_INPUT_LENGTH, + PUBLIC_CIRCUIT_PUBLIC_INPUTS_HASH_INPUT_LENGTH, PrivateCallStackItem, + PrivateCircuitPublicInputs, PublicCallStackItem, + PublicCircuitPublicInputs, PublicKey, TxContext, TxRequest, + VerificationKey, } from '../index.js'; import { boolToBuffer } from '../utils/serialize.js'; -import { MerkleTreeRootCalculator } from './merkle_tree_root_calculator.js'; - -/** - * Synchronously calls a wasm function. - * @param wasm - The wasm wrapper. - * @param fnName - The name of the function to call. - * @param input - The input buffer or object serializable to a buffer. - * @param expectedOutputLength - The expected length of the output buffer. - * @returns The output buffer. - */ -function wasmSyncCall( - wasm: IWasmModule, - fnName: string, - input: - | Buffer - | { - /** - * Signature of the target serialization function. - */ - toBuffer: () => Buffer; - }, - expectedOutputLength: number, -): Buffer { - const inputData: Buffer = input instanceof Buffer ? input : input.toBuffer(); - const outputBuf = wasm.call('bbmalloc', expectedOutputLength); - const inputBuf = wasm.call('bbmalloc', inputData.length); - wasm.writeMemory(inputBuf, inputData); - wasm.call(fnName, inputBuf, outputBuf); - const buf = Buffer.from(wasm.getMemorySlice(outputBuf, outputBuf + expectedOutputLength)); - wasm.call('bbfree', outputBuf); - wasm.call('bbfree', inputBuf); - return buf; -} +import { MerkleTreeCalculator } from './merkle_tree_calculator.js'; /** * Computes a hash of a transaction request. - * @param wasm - A module providing low-level wasm access. * @param txRequest - The transaction request. * @returns The hash of the transaction request. */ @@ -71,7 +45,6 @@ export function hashTxRequest(txRequest: TxRequest): Buffer { /** * Computes a function selector from a given function signature. - * @param wasm - A module providing low-level wasm access. * @param funcSig - The function signature. * @returns The function selector. */ @@ -81,22 +54,52 @@ export function computeFunctionSelector(funcSig: string): Buffer { /** * Computes a hash of a given verification key. - * @param wasm - A module providing low-level wasm access. * @param vkBuf - The verification key. * @returns The hash of the verification key. */ -export function hashVK(wasm: IWasmModule, vkBuf: Buffer) { - return wasmSyncCall(wasm, 'abis__hash_vk', vkBuf, 32); +export function hashVK(vkBuf: Buffer) { + const vk = VerificationKey.fromBuffer(vkBuf); + const toHash = Buffer.concat([ + numToUInt8(vk.circuitType), + numToUInt16BE(5), // fr::coset_generator(0)? + numToUInt32BE(vk.circuitSize), + numToUInt32BE(vk.numPublicInputs), + ...Object.values(vk.commitments) + .map(e => [e.y.toBuffer(), e.x.toBuffer()]) + .flat(), + // Montgomery form of fr::one()? Not sure. But if so, why? + Buffer.from('1418144d5b080fcac24cdb7649bdadf246a6cb2426e324bedb94fb05118f023a', 'hex'), + ]); + return pedersenHashBuffer(toHash); + // barretenberg::evaluation_domain eval_domain = barretenberg::evaluation_domain(circuit_size); + + // std::vector preimage_data; + + // preimage_data.push_back(static_cast(proof_system::CircuitType(circuit_type))); + + // const uint256_t domain = eval_domain.domain; // montgomery form of circuit_size + // const uint256_t generator = eval_domain.generator; //coset_generator(0) + // const uint256_t public_inputs = num_public_inputs; + + // write(preimage_data, static_cast(uint256_t(generator))); // maybe 1? + // write(preimage_data, static_cast(uint256_t(domain))); // try circuit_size + // write(preimage_data, static_cast(public_inputs)); + // for (const auto& [tag, selector] : commitments) { + // write(preimage_data, selector.y); + // write(preimage_data, selector.x); + // } + + // write(preimage_data, eval_domain.root); // fr::one() + + // return crypto::pedersen_hash::hash_buffer(preimage_data, hash_index); } /** * Computes a function leaf from a given preimage. - * @param wasm - A module providing low-level wasm access. * @param fnLeaf - The function leaf preimage. * @returns The function leaf. */ export function computeFunctionLeaf(fnLeaf: FunctionLeafPreimage): Fr { - // return Fr.fromBuffer(wasmSyncCall(wasm, 'abis__compute_function_leaf', fnLeaf, 32)); return Fr.fromBuffer( pedersenHash( [ @@ -114,22 +117,30 @@ export function computeFunctionLeaf(fnLeaf: FunctionLeafPreimage): Fr { // The "zero leaf" of the function tree is the hash of 5 zero fields. // TODO: Why can we not just use a zero field as the zero leaf? Complicates things perhaps unnecessarily? const functionTreeZeroLeaf = pedersenHash(new Array(5).fill(Buffer.alloc(32))); -const functionTreeRootCalculator = new MerkleTreeRootCalculator(FUNCTION_TREE_HEIGHT, functionTreeZeroLeaf); +const functionTreeRootCalculator = new MerkleTreeCalculator(FUNCTION_TREE_HEIGHT, functionTreeZeroLeaf); + +/** + * Computes a function tree from function leaves. + * @param fnLeaves - The function leaves to be included in the contract function tree. + * @returns All nodes of the tree. + */ +export function computeFunctionTree(fnLeaves: Fr[]) { + const leaves = fnLeaves.map(fr => fr.toBuffer()); + return functionTreeRootCalculator.computeTree(leaves).map(b => Fr.fromBuffer(b)); +} /** * Computes a function tree root from function leaves. - * @param wasm - A module providing low-level wasm access. * @param fnLeaves - The function leaves to be included in the contract function tree. * @returns The function tree root. */ -export function computeFunctionTreeRoot(wasm: IWasmModule, fnLeaves: Fr[]) { +export function computeFunctionTreeRoot(fnLeaves: Fr[]) { const leaves = fnLeaves.map(fr => fr.toBuffer()); return Fr.fromBuffer(functionTreeRootCalculator.computeTreeRoot(leaves)); } /** * Computes a constructor hash. - * @param wasm - A module providing low-level wasm access. * @param functionData - Constructor's function data. * @param argsHash - Constructor's arguments hashed. * @param constructorVKHash - Hash of the constructor's verification key. @@ -146,7 +157,6 @@ export function hashConstructor(functionData: FunctionData, argsHash: Fr, constr /** * Computes a complete address. - * @param wasm - A module providing low-level wasm access. * @param deployerPubKey - The pubkey of the contract deployer. * @param contractAddrSalt - The salt used as one of the inputs of the contract address computation. * @param fnTreeRoot - The function tree root of the contract being deployed. @@ -187,7 +197,6 @@ function computePartialAddress(contractAddrSalt: Fr, fnTreeRoot: Fr, constructor /** * Computes a contract address from its partial address and the pubkey. - * @param wasm - A module providing low-level wasm access. * @param partial - The salt used as one of the inputs of the contract address computation. * @param fnTreeRoot - The function tree root of the contract being deployed. * @param constructorHash - The hash of the constructor. @@ -203,7 +212,6 @@ export function computeContractAddressFromPartial(pubKey: PublicKey, partialAddr /** * Computes a commitment nonce, which will be used to create a unique commitment. - * @param wasm - A module providing low-level wasm access. * @param nullifierZero - The first nullifier in the tx. * @param commitmentIndex - The index of the commitment. * @returns A commitment nonce. @@ -217,7 +225,6 @@ export function computeCommitmentNonce(nullifierZero: Fr, commitmentIndex: numbe /** * Computes a siloed commitment, given the contract address and the commitment itself. * A siloed commitment effectively namespaces a commitment to a specific contract. - * @param wasm - A module providing low-level wasm access. * @param contract - The contract address * @param innerCommitment - The commitment to silo. * @returns A siloed commitment. @@ -230,7 +237,6 @@ export function siloCommitment(contract: AztecAddress, innerCommitment: Fr): Fr /** * Computes a unique commitment. It includes a nonce which contains data that guarantees the commitment will be unique. - * @param wasm - A module providing low-level wasm access. * @param nonce - The contract address. * @param siloedCommitment - An siloed commitment. * @returns A unique commitment. @@ -242,7 +248,6 @@ export function computeUniqueCommitment(nonce: Fr, siloedCommitment: Fr): Fr { /** * Computes a siloed nullifier, given the contract address and the inner nullifier. * A siloed nullifier effectively namespaces a nullifier to a specific contract. - * @param wasm - A module providing low-level wasm access. * @param contract - The contract address. * @param innerNullifier - The nullifier to silo. * @returns A siloed nullifier. @@ -253,7 +258,6 @@ export function siloNullifier(contract: AztecAddress, innerNullifier: Fr): Fr { /** * Computes the block hash given the blocks globals and roots. - * @param wasm - A module providing low-level wasm access. * @param globals - The global variables to put into the block hash. * @param noteHashTree - The root of the note hash tree. * @param nullifierTreeRoot - The root of the nullifier tree. @@ -282,7 +286,6 @@ export function computeBlockHashWithGlobals( /** * Computes the block hash given the blocks globals and roots. - * @param wasm - A module providing low-level wasm access. * @param globalsHash - The global variables hash to put into the block hash. * @param noteHashTree - The root of the note hash tree. * @param nullifierTreeRoot - The root of the nullifier tree. @@ -316,7 +319,6 @@ export function computeBlockHash( /** * Computes the globals hash given the globals. - * @param wasm - A module providing low-level wasm access. * @param globals - The global variables to put into the block hash. * @returns The globals hash. */ @@ -336,7 +338,6 @@ export function computeGlobalsHash(globals: GlobalVariables): Fr { /** * Computes a public data tree value ready for insertion. - * @param wasm - A module providing low-level wasm access. * @param value - Raw public data tree value to hash into a tree-insertion-ready value. * @returns Value hash into a tree-insertion-ready value. @@ -347,7 +348,6 @@ export function computePublicDataTreeValue(value: Fr): Fr { /** * Computes a public data tree index from contract address and storage slot. - * @param wasm - A module providing low-level wasm access. * @param contractAddress - Contract where insertion is occurring. * @param storageSlot - Storage slot where insertion is occurring. * @returns Public data tree index computed from contract address and storage slot. @@ -364,7 +364,6 @@ const ARGS_HASH_CHUNK_COUNT = 16; /** * Computes the hash of a list of arguments. - * @param wasm - A module providing low-level wasm access. * @param args - Arguments to hash. * @returns Pedersen hash of the arguments. */ @@ -373,31 +372,32 @@ export function computeVarArgsHash(args: Fr[]) { if (args.length > ARGS_HASH_CHUNK_SIZE * ARGS_HASH_CHUNK_COUNT) throw new Error(`Cannot hash more than ${ARGS_HASH_CHUNK_SIZE * ARGS_HASH_CHUNK_COUNT} arguments`); - const wasmComputeVarArgs = (args: Fr[]) => - Fr.fromBuffer( - pedersenHash( - args.map(a => a.toBuffer()), - GeneratorIndex.FUNCTION_ARGS, - ), - ); - let chunksHashes = chunk(args, ARGS_HASH_CHUNK_SIZE).map(c => { if (c.length < ARGS_HASH_CHUNK_SIZE) { c = padArrayEnd(c, Fr.ZERO, ARGS_HASH_CHUNK_SIZE); } - return wasmComputeVarArgs(c); + return Fr.fromBuffer( + pedersenHash( + c.map(a => a.toBuffer()), + GeneratorIndex.FUNCTION_ARGS, + ), + ); }); if (chunksHashes.length < ARGS_HASH_CHUNK_COUNT) { chunksHashes = padArrayEnd(chunksHashes, Fr.ZERO, ARGS_HASH_CHUNK_COUNT); } - return wasmComputeVarArgs(chunksHashes); + return Fr.fromBuffer( + pedersenHash( + chunksHashes.map(a => a.toBuffer()), + GeneratorIndex.FUNCTION_ARGS, + ), + ); } /** * Computes a contract leaf of the given contract. - * @param wasm - Relevant WASM wrapper. * @param cd - The contract data of the deployed contract. * @returns The contract leaf. */ @@ -415,7 +415,6 @@ export function computeContractLeaf(cd: NewContractData): Fr { /** * Computes tx hash of a given transaction request. - * @param wasm - Relevant WASM wrapper. * @param txRequest - The signed transaction request. * @returns The transaction hash. */ @@ -490,63 +489,168 @@ function computeContractDeploymentDataHash(data: ContractDeploymentData): Fr { /** * Computes a call stack item hash. - * @param wasm - Relevant WASM wrapper. * @param callStackItem - The call stack item. * @returns The call stack item hash. */ -export function computeCallStackItemHash( - wasm: IWasmModule, - callStackItem: PrivateCallStackItem | PublicCallStackItem, -): Fr { +export function computeCallStackItemHash(callStackItem: PrivateCallStackItem | PublicCallStackItem): Fr { if (callStackItem instanceof PrivateCallStackItem) { - return computePrivateCallStackItemHash(wasm, callStackItem); + return computePrivateCallStackItemHash(callStackItem); } else if (callStackItem instanceof PublicCallStackItem) { - return computePublicCallStackItemHash(wasm, callStackItem); + return computePublicCallStackItemHash(callStackItem); } else { throw new Error(`Unexpected call stack item type`); } } +/** + * + */ +function computeCallContextHash(input: CallContext) { + return pedersenHash( + [ + input.msgSender.toBuffer(), + input.storageContractAddress.toBuffer(), + input.portalContractAddress.toBuffer(), + input.functionSelector.toBuffer(), + boolToBuffer(input.isDelegateCall, 32), + boolToBuffer(input.isStaticCall, 32), + boolToBuffer(input.isContractDeployment, 32), + ], + GeneratorIndex.CALL_CONTEXT, + ); +} + +/** + * + */ +function computePrivateInputsHash(input: PrivateCircuitPublicInputs) { + const toHash = [ + computeCallContextHash(input.callContext), + input.argsHash.toBuffer(), + ...input.returnValues.map(fr => fr.toBuffer()), + ...input.readRequests.map(fr => fr.toBuffer()), + ...input.pendingReadRequests.map(fr => fr.toBuffer()), + ...input.newCommitments.map(fr => fr.toBuffer()), + ...input.newNullifiers.map(fr => fr.toBuffer()), + ...input.nullifiedCommitments.map(fr => fr.toBuffer()), + ...input.privateCallStack.map(fr => fr.toBuffer()), + ...input.publicCallStack.map(fr => fr.toBuffer()), + ...input.newL2ToL1Msgs.map(fr => fr.toBuffer()), + ...input.encryptedLogsHash.map(fr => fr.toBuffer()), + ...input.unencryptedLogsHash.map(fr => fr.toBuffer()), + input.encryptedLogPreimagesLength.toBuffer(), + input.unencryptedLogPreimagesLength.toBuffer(), + input.historicBlockData.noteHashTreeRoot.toBuffer(), + input.historicBlockData.nullifierTreeRoot.toBuffer(), + input.historicBlockData.contractTreeRoot.toBuffer(), + input.historicBlockData.l1ToL2MessagesTreeRoot.toBuffer(), + input.historicBlockData.blocksTreeRoot.toBuffer(), + input.historicBlockData.publicDataTreeRoot.toBuffer(), + input.historicBlockData.globalVariablesHash.toBuffer(), + computeContractDeploymentDataHash(input.contractDeploymentData).toBuffer(), + input.chainId.toBuffer(), + input.version.toBuffer(), + ]; + if (toHash.length != PRIVATE_CIRCUIT_PUBLIC_INPUTS_HASH_INPUT_LENGTH) { + throw new Error('Incorrect number of input fields when hashing PrivateCircuitPublicInputs'); + } + return pedersenHash(toHash, GeneratorIndex.PRIVATE_CIRCUIT_PUBLIC_INPUTS); +} + /** * Computes a call stack item hash. - * @param wasm - Relevant WASM wrapper. * @param callStackItem - The call stack item. * @returns The call stack item hash. */ -export function computePrivateCallStackItemHash(wasm: IWasmModule, callStackItem: PrivateCallStackItem): Fr { - const value = wasmSyncCall(wasm, 'abis__compute_private_call_stack_item_hash', callStackItem, 32); - return Fr.fromBuffer(value); - // return Fr.fromBuffer( - // pedersenHashWithHashIndex( - // [ - // callStackItem.contractAddress.toBuffer(), - // computeFunctionDataHash(callStackItem.functionData).toBuffer(), - // computePublicInputsHash(callStackItem.publicInputs).toBuffer(), - // ], - // GeneratorIndex.CALL_STACK_ITEM, - // ), - // ); +export function computePrivateCallStackItemHash(callStackItem: PrivateCallStackItem): Fr { + return Fr.fromBuffer( + pedersenHash( + [ + callStackItem.contractAddress.toBuffer(), + computeFunctionDataHash(callStackItem.functionData).toBuffer(), + computePrivateInputsHash(callStackItem.publicInputs), + ], + GeneratorIndex.CALL_STACK_ITEM, + ), + ); +} + +/** + * + */ +function computeContractStorageUpdateRequestHash(input: ContractStorageUpdateRequest) { + return pedersenHash( + [input.storageSlot.toBuffer(), input.oldValue.toBuffer(), input.newValue.toBuffer()], + GeneratorIndex.PUBLIC_DATA_UPDATE_REQUEST, + ); +} + +/** + * + */ +function computeContractStorageReadsHash(input: ContractStorageRead) { + return pedersenHash([input.storageSlot.toBuffer(), input.currentValue.toBuffer()], GeneratorIndex.PUBLIC_DATA_READ); +} + +/** + * + */ +function computePublicInputsHash(input: PublicCircuitPublicInputs) { + const toHash = [ + computeCallContextHash(input.callContext), + input.argsHash.toBuffer(), + ...input.returnValues.map(fr => fr.toBuffer()), + ...input.contractStorageUpdateRequests.map(computeContractStorageUpdateRequestHash), + ...input.contractStorageReads.map(computeContractStorageReadsHash), + ...input.publicCallStack.map(fr => fr.toBuffer()), + ...input.newCommitments.map(fr => fr.toBuffer()), + ...input.newNullifiers.map(fr => fr.toBuffer()), + ...input.newL2ToL1Msgs.map(fr => fr.toBuffer()), + ...input.unencryptedLogsHash.map(fr => fr.toBuffer()), + input.unencryptedLogPreimagesLength.toBuffer(), + input.historicBlockData.noteHashTreeRoot.toBuffer(), + input.historicBlockData.nullifierTreeRoot.toBuffer(), + input.historicBlockData.contractTreeRoot.toBuffer(), + input.historicBlockData.l1ToL2MessagesTreeRoot.toBuffer(), + input.historicBlockData.blocksTreeRoot.toBuffer(), + input.historicBlockData.publicDataTreeRoot.toBuffer(), + input.historicBlockData.globalVariablesHash.toBuffer(), + input.proverAddress.toBuffer(), + ]; + if (toHash.length != PUBLIC_CIRCUIT_PUBLIC_INPUTS_HASH_INPUT_LENGTH) { + throw new Error('Incorrect number of input fields when hashing PublicCircuitPublicInputs'); + } + return pedersenHash(toHash, GeneratorIndex.PUBLIC_CIRCUIT_PUBLIC_INPUTS); } /** * Computes a call stack item hash. - * @param wasm - Relevant WASM wrapper. * @param callStackItem - The call stack item. * @returns The call stack item hash. */ -export function computePublicCallStackItemHash(wasm: IWasmModule, callStackItem: PublicCallStackItem): Fr { - const value = wasmSyncCall(wasm, 'abis__compute_public_call_stack_item_hash', callStackItem, 32); - return Fr.fromBuffer(value); - // return Fr.fromBuffer( - // pedersenHashWithHashIndex( - // [ - // callStackItem.contractAddress.toBuffer(), - // callStackItem.functionData.toBuffer(), - // callStackItem.publicInputs.toBuffer(), - // ], - // GeneratorIndex.CALL_STACK_ITEM, - // ), - // ); +export function computePublicCallStackItemHash({ + contractAddress, + functionData, + publicInputs, + isExecutionRequest, +}: PublicCallStackItem): Fr { + if (isExecutionRequest) { + const { callContext, argsHash } = publicInputs; + publicInputs = PublicCircuitPublicInputs.empty(); + publicInputs.callContext = callContext; + publicInputs.argsHash = argsHash; + } + + return Fr.fromBuffer( + pedersenHash( + [ + contractAddress.toBuffer(), + computeFunctionDataHash(functionData).toBuffer(), + computePublicInputsHash(publicInputs), + ], + GeneratorIndex.CALL_STACK_ITEM, + ), + ); } /** 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 new file mode 100644 index 00000000000..1be2f815b50 --- /dev/null +++ b/yarn-project/circuits.js/src/abis/merkle_tree_calculator.test.ts @@ -0,0 +1,40 @@ +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 new file mode 100644 index 00000000000..a4de23b3911 --- /dev/null +++ b/yarn-project/circuits.js/src/abis/merkle_tree_calculator.ts @@ -0,0 +1,57 @@ +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/barretenberg/crypto/aes128/index.test.ts b/yarn-project/circuits.js/src/barretenberg/crypto/aes128/index.test.ts index e8a1f91b533..9b8afc328e2 100644 --- a/yarn-project/circuits.js/src/barretenberg/crypto/aes128/index.test.ts +++ b/yarn-project/circuits.js/src/barretenberg/crypto/aes128/index.test.ts @@ -1,16 +1,12 @@ -import { CircuitsWasm } from '@aztec/circuits.js'; - import { createCipheriv, createDecipheriv, randomBytes } from 'crypto'; import { Aes128 } from './index.js'; describe('aes128', () => { - let barretenberg!: CircuitsWasm; let aes128!: Aes128; - beforeAll(async () => { - barretenberg = await CircuitsWasm.get(); - aes128 = new Aes128(barretenberg); + beforeAll(() => { + aes128 = new Aes128(); }); it('should correctly encrypt input', () => { diff --git a/yarn-project/circuits.js/src/barretenberg/crypto/aes128/index.ts b/yarn-project/circuits.js/src/barretenberg/crypto/aes128/index.ts index 8d92a2779ab..20e0e133b9c 100644 --- a/yarn-project/circuits.js/src/barretenberg/crypto/aes128/index.ts +++ b/yarn-project/circuits.js/src/barretenberg/crypto/aes128/index.ts @@ -1,13 +1,15 @@ -import { IWasmModule } from '@aztec/foundation/wasm'; +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 { - constructor(private wasm: IWasmModule) {} - /** * Encrypt a buffer using AES-128-CBC. * @param data - Data to encrypt. @@ -25,26 +27,10 @@ export class Aes128 { paddingBuffer.fill(numPaddingBytes); } const input = Buffer.concat([data, paddingBuffer]); - const mem = this.wasm.call('bbmalloc', input.length + key.length + iv.length + input.length); - this.wasm.writeMemory(mem, input); - this.wasm.writeMemory(mem + input.length, iv); - this.wasm.writeMemory(mem + input.length + iv.length, key); - this.wasm.call( - 'aes__encrypt_buffer_cbc', - mem, - mem + input.length, - mem + input.length + iv.length, - input.length, - mem + input.length + iv.length + key.length, - ); - const result: Buffer = Buffer.from( - this.wasm.getMemorySlice( - mem + input.length + key.length + iv.length, - mem + input.length + key.length + iv.length + input.length, - ), + + return Buffer.from( + api.aesEncryptBufferCbc(new RawBuffer(input), new RawBuffer(iv), new RawBuffer(key), input.length), ); - this.wasm.call('bbfree', mem); - return result; } /** @@ -55,25 +41,8 @@ export class Aes128 { * @returns Decrypted data. */ public decryptBufferCBC(data: Uint8Array, iv: Uint8Array, key: Uint8Array) { - const mem = this.wasm.call('bbmalloc', data.length + key.length + iv.length + data.length); - this.wasm.writeMemory(mem, data); - this.wasm.writeMemory(mem + data.length, iv); - this.wasm.writeMemory(mem + data.length + iv.length, key); - this.wasm.call( - 'aes__decrypt_buffer_cbc', - mem, - mem + data.length, - mem + data.length + iv.length, - data.length, - mem + data.length + iv.length + key.length, - ); - const result: Buffer = Buffer.from( - this.wasm.getMemorySlice( - mem + data.length + key.length + iv.length, - mem + data.length + key.length + iv.length + data.length, - ), + return Buffer.from( + api.aesDecryptBufferCbc(new RawBuffer(data), new RawBuffer(iv), new RawBuffer(key), data.length), ); - this.wasm.call('bbfree', mem); - return result; } } 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 index a05f16f9b8c..57a61da3124 100644 --- a/yarn-project/circuits.js/src/barretenberg/crypto/ecdsa/index.test.ts +++ b/yarn-project/circuits.js/src/barretenberg/crypto/ecdsa/index.test.ts @@ -1,20 +1,18 @@ import { TextEncoder } from 'util'; -import { CircuitsWasm } from '../../../index.js'; import { Ecdsa } from './index.js'; describe('ecdsa', () => { let ecdsa!: Ecdsa; - beforeAll(async () => { - const wasm = await CircuitsWasm.get(); - ecdsa = new Ecdsa(wasm); + 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, + 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); @@ -28,7 +26,7 @@ describe('ecdsa', () => { 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, + 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); diff --git a/yarn-project/circuits.js/src/barretenberg/crypto/ecdsa/index.ts b/yarn-project/circuits.js/src/barretenberg/crypto/ecdsa/index.ts index 6efa8cc5568..e52933eccf4 100644 --- a/yarn-project/circuits.js/src/barretenberg/crypto/ecdsa/index.ts +++ b/yarn-project/circuits.js/src/barretenberg/crypto/ecdsa/index.ts @@ -1,33 +1,25 @@ -import { IWasmModule } from '@aztec/foundation/wasm'; +import { BarretenbergSync } from '@aztec/bb.js'; -import { CircuitsWasm } from '../../../index.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 { - /** - * Creates a new Ecdsa instance. - * @returns New Ecdsa instance. - */ - public static async new() { - return new this(await CircuitsWasm.get()); - } - - constructor(private wasm: IWasmModule) {} - /** * Computes a secp256k1 public key from a private key. * @param privateKey - Secp256k1 private key. * @returns A secp256k1 public key. */ public computePublicKey(privateKey: Buffer): Buffer { - this.wasm.writeMemory(0, privateKey); - this.wasm.call('ecdsa__compute_public_key', 0, 32); - return Buffer.from(this.wasm.getMemorySlice(32, 96)); + wasm.writeMemory(0, privateKey); + wasm.call('ecdsa__compute_public_key', 0, 32); + return Buffer.from(wasm.getMemorySlice(32, 96)); } /** @@ -37,15 +29,15 @@ export class Ecdsa { * @returns An ECDSA signature of the form (r, s, v). */ public constructSignature(msg: Uint8Array, privateKey: Buffer) { - const mem = this.wasm.call('bbmalloc', msg.length); - this.wasm.writeMemory(0, privateKey); - this.wasm.writeMemory(mem, msg); - this.wasm.call('ecdsa__construct_signature', mem, msg.length, 0, 32, 64, 96); + 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(this.wasm.getMemorySlice(32, 64)), - Buffer.from(this.wasm.getMemorySlice(64, 96)), - Buffer.from(this.wasm.getMemorySlice(96, 97)), + Buffer.from(wasm.getMemorySlice(32, 64)), + Buffer.from(wasm.getMemorySlice(64, 96)), + Buffer.from(wasm.getMemorySlice(96, 97)), ); } @@ -56,14 +48,14 @@ export class Ecdsa { * @returns The secp256k1 public key of the signer. */ public recoverPublicKey(msg: Uint8Array, sig: EcdsaSignature): Buffer { - const mem = this.wasm.call('bbmalloc', msg.length); - this.wasm.writeMemory(0, sig.r); - this.wasm.writeMemory(32, sig.s); - this.wasm.writeMemory(64, sig.v); - this.wasm.writeMemory(mem, msg); - this.wasm.call('ecdsa__recover_public_key_from_signature', mem, msg.length, 0, 32, 64, 65); + 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(this.wasm.getMemorySlice(65, 129)); + return Buffer.from(wasm.getMemorySlice(65, 129)); } /** @@ -74,12 +66,12 @@ export class Ecdsa { * @returns True or false. */ public verifySignature(msg: Uint8Array, pubKey: Buffer, sig: EcdsaSignature) { - const mem = this.wasm.call('bbmalloc', msg.length); - this.wasm.writeMemory(0, pubKey); - this.wasm.writeMemory(64, sig.r); - this.wasm.writeMemory(96, sig.s); - this.wasm.writeMemory(128, sig.v); - this.wasm.writeMemory(mem, msg); - return this.wasm.call('ecdsa__verify_signature', mem, msg.length, 0, 64, 96, 128) ? true : false; + 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/grumpkin/index.test.ts b/yarn-project/circuits.js/src/barretenberg/crypto/grumpkin/index.test.ts index 2a79d619b98..154ab39075f 100644 --- a/yarn-project/circuits.js/src/barretenberg/crypto/grumpkin/index.test.ts +++ b/yarn-project/circuits.js/src/barretenberg/crypto/grumpkin/index.test.ts @@ -1,17 +1,15 @@ import { createDebugLogger } from '@aztec/foundation/log'; -import { CircuitsWasm, GrumpkinScalar, Point } from '../../../index.js'; +import { GrumpkinScalar, Point } from '../../../index.js'; import { Grumpkin } from './index.js'; const debug = createDebugLogger('bb:grumpkin_test'); describe('grumpkin', () => { - let barretenberg!: CircuitsWasm; let grumpkin!: Grumpkin; - beforeAll(async () => { - barretenberg = await CircuitsWasm.get(); - grumpkin = new Grumpkin(barretenberg); + beforeAll(() => { + grumpkin = new Grumpkin(); }); it('should correctly perform scalar muls', () => { diff --git a/yarn-project/circuits.js/src/barretenberg/crypto/grumpkin/index.ts b/yarn-project/circuits.js/src/barretenberg/crypto/grumpkin/index.ts index 35a0cb068e5..a41c0af1fa0 100644 --- a/yarn-project/circuits.js/src/barretenberg/crypto/grumpkin/index.ts +++ b/yarn-project/circuits.js/src/barretenberg/crypto/grumpkin/index.ts @@ -1,24 +1,15 @@ +import { BarretenbergSync } from '@aztec/bb.js'; import { Fr, Point } from '@aztec/foundation/fields'; -import { IWasmModule } from '@aztec/foundation/wasm'; -import { CircuitsWasm, GrumpkinScalar } from '../../../index.js'; +import { GrumpkinScalar } from '../../../index.js'; -// TODO: Establish if these needs high performance and consider refactoring and using the grumpkin curve in pedersen ts. +const api = await BarretenbergSync.getSingleton(); +const wasm = api.getWasm(); /** * Grumpkin elliptic curve operations. */ export class Grumpkin { - /** - * Creates a new Grumpkin instance. - * @returns New Grumpkin instance. - */ - public static async new() { - return new this(await CircuitsWasm.get()); - } - - constructor(private wasm: IWasmModule) {} - // prettier-ignore static generator = Point.fromBuffer(Buffer.from([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -42,10 +33,10 @@ export class Grumpkin { * @returns Result of the multiplication. */ public mul(point: Point, scalar: GrumpkinScalar): Point { - this.wasm.writeMemory(0, point.toBuffer()); - this.wasm.writeMemory(64, scalar.toBuffer()); - this.wasm.call('ecc_grumpkin__mul', 0, 64, 96); - return Point.fromBuffer(Buffer.from(this.wasm.getMemorySlice(96, 160))); + 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))); } /** @@ -58,16 +49,16 @@ export class Grumpkin { const concatenatedPoints: Buffer = Buffer.concat(points.map(point => point.toBuffer())); const pointsByteLength = points.length * Point.SIZE_IN_BYTES; - const mem = this.wasm.call('bbmalloc', pointsByteLength * 2); + const mem = wasm.call('bbmalloc', pointsByteLength * 2); - this.wasm.writeMemory(mem, concatenatedPoints); - this.wasm.writeMemory(0, scalar.toBuffer()); - this.wasm.call('ecc_grumpkin__batch_mul', mem, 0, points.length, mem + pointsByteLength); + 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( - this.wasm.getMemorySlice(mem + pointsByteLength, mem + pointsByteLength + pointsByteLength), + wasm.getMemorySlice(mem + pointsByteLength, mem + pointsByteLength + pointsByteLength), ); - this.wasm.call('bbfree', mem); + wasm.call('bbfree', mem); const parsedResult: Point[] = []; for (let i = 0; i < pointsByteLength; i += 64) { @@ -81,8 +72,8 @@ export class Grumpkin { * @returns Random field element. */ public getRandomFr(): Fr { - this.wasm.call('ecc_grumpkin__get_random_scalar_mod_circuit_modulus', 0); - return Fr.fromBuffer(Buffer.from(this.wasm.getMemorySlice(0, 32))); + wasm.call('ecc_grumpkin__get_random_scalar_mod_circuit_modulus', 0); + return Fr.fromBuffer(Buffer.from(wasm.getMemorySlice(0, 32))); } /** @@ -91,8 +82,8 @@ export class Grumpkin { * @returns Buffer representation of the field element. */ public reduce512BufferToFr(uint512Buf: Buffer): Fr { - this.wasm.writeMemory(0, uint512Buf); - this.wasm.call('ecc_grumpkin__reduce512_buffer_mod_circuit_modulus', 0, 64); - return Fr.fromBuffer(Buffer.from(this.wasm.getMemorySlice(64, 96))); + 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/schnorr/index.test.ts b/yarn-project/circuits.js/src/barretenberg/crypto/schnorr/index.test.ts index c5a2b7b8687..db2e2101e6e 100644 --- a/yarn-project/circuits.js/src/barretenberg/crypto/schnorr/index.test.ts +++ b/yarn-project/circuits.js/src/barretenberg/crypto/schnorr/index.test.ts @@ -1,19 +1,19 @@ import { TextEncoder } from 'util'; -import { CircuitsWasm, GrumpkinScalar } from '../../../index.js'; +import { GrumpkinScalar } from '../../../index.js'; import { Schnorr } from './index.js'; describe('schnorr', () => { let schnorr!: Schnorr; - beforeAll(async () => { - schnorr = new Schnorr(await CircuitsWasm.get()); + 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, + 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); @@ -27,7 +27,7 @@ describe('schnorr', () => { 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, + 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); diff --git a/yarn-project/circuits.js/src/barretenberg/crypto/schnorr/index.ts b/yarn-project/circuits.js/src/barretenberg/crypto/schnorr/index.ts index e850d63e1d3..4ab41700e7d 100644 --- a/yarn-project/circuits.js/src/barretenberg/crypto/schnorr/index.ts +++ b/yarn-project/circuits.js/src/barretenberg/crypto/schnorr/index.ts @@ -1,34 +1,27 @@ +import { BarretenbergSync } from '@aztec/bb.js'; import { numToUInt32BE } from '@aztec/foundation/serialize'; -import { IWasmModule } from '@aztec/foundation/wasm'; -import { CircuitsWasm, GrumpkinPrivateKey, Point, PublicKey } from '../../../index.js'; +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 { - /** - * Creates a new Schnorr instance. - * @returns New Schnorr instance. - */ - public static async new() { - return new this(await CircuitsWasm.get()); - } - - constructor(private wasm: IWasmModule) {} - /** * Computes a grumpkin public key from a private key. * @param privateKey - The private key. * @returns A grumpkin public key. */ public computePublicKey(privateKey: GrumpkinPrivateKey): PublicKey { - this.wasm.writeMemory(0, privateKey.toBuffer()); - this.wasm.call('schnorr_compute_public_key', 0, 32); - return Point.fromBuffer(Buffer.from(this.wasm.getMemorySlice(32, 96))); + wasm.writeMemory(0, privateKey.toBuffer()); + wasm.call('schnorr_compute_public_key', 0, 32); + return Point.fromBuffer(Buffer.from(wasm.getMemorySlice(32, 96))); } /** @@ -38,12 +31,12 @@ export class Schnorr { * @returns A Schnorr signature of the form (s, e). */ public constructSignature(msg: Uint8Array, privateKey: GrumpkinPrivateKey) { - const mem = this.wasm.call('bbmalloc', msg.length + 4); - this.wasm.writeMemory(0, privateKey.toBuffer()); - this.wasm.writeMemory(mem, Buffer.concat([numToUInt32BE(msg.length), msg])); - this.wasm.call('schnorr_construct_signature', mem, 0, 32, 64); + 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(this.wasm.getMemorySlice(32, 96))); + return new SchnorrSignature(Buffer.from(wasm.getMemorySlice(32, 96))); } /** @@ -54,13 +47,13 @@ export class Schnorr { * @returns True or false. */ public verifySignature(msg: Uint8Array, pubKey: PublicKey, sig: SchnorrSignature) { - const mem = this.wasm.call('bbmalloc', msg.length + 4); - this.wasm.writeMemory(0, pubKey.toBuffer()); - this.wasm.writeMemory(64, sig.s); - this.wasm.writeMemory(96, sig.e); - this.wasm.writeMemory(mem, Buffer.concat([numToUInt32BE(msg.length), msg])); - this.wasm.call('schnorr_verify_signature', mem, 0, 64, 96, 128); - const result = this.wasm.getMemorySlice(128, 129); + 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/secp256k1/index.test.ts b/yarn-project/circuits.js/src/barretenberg/crypto/secp256k1/index.test.ts index 801b45d796e..9da5a362323 100644 --- a/yarn-project/circuits.js/src/barretenberg/crypto/secp256k1/index.test.ts +++ b/yarn-project/circuits.js/src/barretenberg/crypto/secp256k1/index.test.ts @@ -1,6 +1,5 @@ import { randomBytes } from '@aztec/foundation/crypto'; -import { CircuitsWasm } from '../../../index.js'; import { Ecdsa } from '../ecdsa/index.js'; import { Secp256k1 } from './index.js'; @@ -8,10 +7,9 @@ describe('secp256k1', () => { let secp256k1!: Secp256k1; let ecdsa!: Ecdsa; - beforeAll(async () => { - const wasm = await CircuitsWasm.get(); - secp256k1 = new Secp256k1(wasm); - ecdsa = new Ecdsa(wasm); + beforeAll(() => { + secp256k1 = new Secp256k1(); + ecdsa = new Ecdsa(); }); it('should correctly compute public key', () => { diff --git a/yarn-project/circuits.js/src/barretenberg/crypto/secp256k1/index.ts b/yarn-project/circuits.js/src/barretenberg/crypto/secp256k1/index.ts index 28c3554e26e..a388ce602fb 100644 --- a/yarn-project/circuits.js/src/barretenberg/crypto/secp256k1/index.ts +++ b/yarn-project/circuits.js/src/barretenberg/crypto/secp256k1/index.ts @@ -1,21 +1,12 @@ -import { IWasmModule } from '@aztec/foundation/wasm'; +import { BarretenbergSync } from '@aztec/bb.js'; -import { CircuitsWasm } from '../../../index.js'; +const api = await BarretenbergSync.getSingleton(); +const wasm = api.getWasm(); /** * Secp256k1 elliptic curve operations. */ export class Secp256k1 { - /** - * Creates a new Secp256k1 instance. - * @returns New Secp256k1 instance. - */ - public static async new() { - return new this(await CircuitsWasm.get()); - } - - constructor(private wasm: IWasmModule) {} - // prettier-ignore static generator = Buffer.from([ 0x79, 0xbe, 0x66, 0x7e, 0xf9, 0xdc, 0xbb, 0xac, 0x55, 0xa0, 0x62, 0x95, 0xce, 0x87, 0x0b, 0x07, @@ -39,10 +30,10 @@ export class Secp256k1 { * @returns Result of the multiplication. */ public mul(point: Uint8Array, scalar: Uint8Array) { - this.wasm.writeMemory(0, point); - this.wasm.writeMemory(64, scalar); - this.wasm.call('ecc_secp256k1__mul', 0, 64, 96); - return Buffer.from(this.wasm.getMemorySlice(96, 160)); + wasm.writeMemory(0, point); + wasm.writeMemory(64, scalar); + wasm.call('ecc_secp256k1__mul', 0, 64, 96); + return Buffer.from(wasm.getMemorySlice(96, 160)); } /** @@ -50,8 +41,8 @@ export class Secp256k1 { * @returns Random field element. */ public getRandomFr() { - this.wasm.call('ecc_secp256k1__get_random_scalar_mod_circuit_modulus', 0); - return Buffer.from(this.wasm.getMemorySlice(0, 32)); + wasm.call('ecc_secp256k1__get_random_scalar_mod_circuit_modulus', 0); + return Buffer.from(wasm.getMemorySlice(0, 32)); } /** @@ -60,8 +51,8 @@ export class Secp256k1 { * @returns Buffer representation of the field element. */ public reduce512BufferToFr(uint512Buf: Buffer) { - this.wasm.writeMemory(0, uint512Buf); - this.wasm.call('ecc_secp256k1__reduce512_buffer_mod_circuit_modulus', 0, 64); - return Buffer.from(this.wasm.getMemorySlice(64, 96)); + 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/contract/contract_deployment_info.ts b/yarn-project/circuits.js/src/contract/contract_deployment_info.ts index 5914d6c840b..38a15d1cfcc 100644 --- a/yarn-project/circuits.js/src/contract/contract_deployment_info.ts +++ b/yarn-project/circuits.js/src/contract/contract_deployment_info.ts @@ -6,7 +6,7 @@ import { } from '@aztec/circuits.js/abis'; import { ContractArtifact, FunctionSelector, encodeArguments } from '@aztec/foundation/abi'; -import { CircuitsWasm, DeploymentInfo, Fr, FunctionData, PublicKey } from '../index.js'; +import { DeploymentInfo, Fr, FunctionData, PublicKey } from '../index.js'; import { generateFunctionLeaves, hashVKStr, isConstructor } from './contract_tree/contract_tree.js'; /** @@ -17,12 +17,12 @@ import { generateFunctionLeaves, hashVKStr, isConstructor } from './contract_tre * @param publicKey - The account public key * @returns - The contract deployment info */ -export async function getContractDeploymentInfo( +export function getContractDeploymentInfo( artifact: ContractArtifact, args: any[], contractAddressSalt: Fr, publicKey: PublicKey, -): Promise { +): DeploymentInfo { const constructorArtifact = artifact.functions.find(isConstructor); if (!constructorArtifact) { throw new Error('Cannot find constructor in the artifact.'); @@ -31,15 +31,14 @@ export async function getContractDeploymentInfo( throw new Error('Missing verification key for the constructor.'); } - const wasm = await CircuitsWasm.get(); - const vkHash = hashVKStr(constructorArtifact.verificationKey, wasm); + 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(wasm, leaves); + const functionTreeRoot = computeFunctionTreeRoot(leaves); const functionData = FunctionData.fromAbi(constructorArtifact); const flatArgs = encodeArguments(constructorArtifact, args); const argsHash = computeVarArgsHash(flatArgs); diff --git a/yarn-project/circuits.js/src/contract/contract_tree/contract_tree.ts b/yarn-project/circuits.js/src/contract/contract_tree/contract_tree.ts index b74a372849b..f8da811530e 100644 --- a/yarn-project/circuits.js/src/contract/contract_tree/contract_tree.ts +++ b/yarn-project/circuits.js/src/contract/contract_tree/contract_tree.ts @@ -1,4 +1,4 @@ -import { CircuitsWasm, ContractFunctionDao, Fr, FunctionData, FunctionLeafPreimage } from '@aztec/circuits.js'; +import { ContractFunctionDao, Fr, FunctionData, FunctionLeafPreimage } from '@aztec/circuits.js'; import { computeFunctionLeaf, hashVK } from '@aztec/circuits.js/abis'; import { FunctionSelector, FunctionType } from '@aztec/foundation/abi'; @@ -11,9 +11,9 @@ import { FunctionSelector, FunctionType } from '@aztec/foundation/abi'; * @param wasm - An instance of CircuitsWasm class used for hashing. * @returns A Promise resolving to a Buffer containing the hash of the verification key. */ -export function hashVKStr(vk: string, wasm: CircuitsWasm) { +export function hashVKStr(vk: string) { // TODO - check consistent encoding - return hashVK(wasm, Buffer.from(vk, 'hex')); + return hashVK(Buffer.from(vk, 'hex')); } /** diff --git a/yarn-project/circuits.js/src/kernel/private_kernel.test.ts b/yarn-project/circuits.js/src/kernel/private_kernel.test.ts index 3ac47d213ae..6f8eb2c28fa 100644 --- a/yarn-project/circuits.js/src/kernel/private_kernel.test.ts +++ b/yarn-project/circuits.js/src/kernel/private_kernel.test.ts @@ -1,11 +1,10 @@ import times from 'lodash.times'; -import { computeFunctionTreeRoot } from '../abis/abis.js'; +import { computeFunctionTree, computeFunctionTreeRoot } from '../abis/abis.js'; import { privateKernelDummyPreviousKernel } from '../cbind/circuits.gen.js'; import { FUNCTION_TREE_HEIGHT } from '../cbind/constants.gen.js'; import { fr } from '../tests/factories.js'; import { CircuitsWasm } from '../wasm/circuits_wasm.js'; -import { computeFunctionTree } from './private_kernel.js'; describe('kernel/private_kernel', () => { let wasm: CircuitsWasm; @@ -21,12 +20,12 @@ describe('kernel/private_kernel', () => { it('computes function tree', () => { const numLeaves = 4; const leaves = times(numLeaves, i => fr(i)); - const tree = computeFunctionTree(wasm, leaves); + const tree = computeFunctionTree(leaves); expect(tree).toHaveLength(2 ** (FUNCTION_TREE_HEIGHT + 1) - 1); expect(tree.slice(0, numLeaves)).toEqual(leaves); const root = tree[tree.length - 1]; - expect(root).toEqual(computeFunctionTreeRoot(wasm, leaves)); + expect(root).toEqual(computeFunctionTreeRoot(leaves)); }); }); diff --git a/yarn-project/circuits.js/src/kernel/private_kernel.ts b/yarn-project/circuits.js/src/kernel/private_kernel.ts index a1f0e254fde..d78658ca7aa 100644 --- a/yarn-project/circuits.js/src/kernel/private_kernel.ts +++ b/yarn-project/circuits.js/src/kernel/private_kernel.ts @@ -1,39 +1 @@ -import { BufferReader } from '@aztec/foundation/serialize'; - -import { Buffer } from 'buffer'; - -import { FUNCTION_TREE_HEIGHT, Fr } from '../index.js'; -import { serializeBufferArrayToVector } from '../utils/serialize.js'; -import { CircuitsWasm } from '../wasm/index.js'; - export { privateKernelSimOrdering, privateKernelSimInit, privateKernelSimInner } from '../cbind/circuits.gen.js'; - -/** - * Computes contract's function tree from the given leaves. - * @param wasm - The circuits wasm instance. - * @param leaves - The leaves of the function tree. - * @returns All of a function tree's nodes. - */ -export function computeFunctionTree(wasm: CircuitsWasm, leaves: Fr[]): Fr[] { - // Size of the tree is 2^height times size of each element, - // plus 4 for the size used in the std::vector serialization - const outputBufSize = 2 ** (FUNCTION_TREE_HEIGHT + 1) * Fr.SIZE_IN_BYTES + 4; - - // Allocate memory for the input and output buffers, and populate input buffer - const inputVector = serializeBufferArrayToVector(leaves.map(fr => fr.toBuffer())); - const inputBufPtr = wasm.call('bbmalloc', inputVector.length); - const outputBufPtr = wasm.call('bbmalloc', outputBufSize * 100); - wasm.writeMemory(inputBufPtr, inputVector); - - // Run and read outputs - wasm.call('abis__compute_function_tree', inputBufPtr, outputBufPtr); - const outputBuf = Buffer.from(wasm.getMemorySlice(outputBufPtr, outputBufPtr + outputBufSize)); - const reader = new BufferReader(outputBuf); - const output = reader.readVector(Fr); - - // Free memory - wasm.call('bbfree', outputBufPtr); - wasm.call('bbfree', inputBufPtr); - - return output; -} diff --git a/yarn-project/circuits.js/src/kernel/public_kernel.test.ts b/yarn-project/circuits.js/src/kernel/public_kernel.test.ts index c8b28c2daa7..7859802e98d 100644 --- a/yarn-project/circuits.js/src/kernel/public_kernel.test.ts +++ b/yarn-project/circuits.js/src/kernel/public_kernel.test.ts @@ -11,7 +11,7 @@ import { makePublicDataRead, makePublicKernelInputsWithTweak } from '../tests/fa describe('kernel/public_kernel', () => { it('simulates public kernel circuit with previous public kernel', async function () { - const input = await makePublicKernelInputsWithTweak(1, input => { + const input = makePublicKernelInputsWithTweak(1, input => { input.publicCall.callStackItem.functionData.isConstructor = false; input.publicCall.callStackItem.functionData.isPrivate = false; input.previousKernel.publicInputs.isPrivate = false; @@ -21,7 +21,7 @@ describe('kernel/public_kernel', () => { }); it('simulates public kernel circuit with previous private kernel', async function () { - const input = await makePublicKernelInputsWithTweak(1, input => { + const input = makePublicKernelInputsWithTweak(1, input => { input.previousKernel.publicInputs.isPrivate = true; input.previousKernel.publicInputs.end.privateCallStack = makeTuple(MAX_PRIVATE_CALL_STACK_LENGTH_PER_TX, Fr.zero); }); @@ -30,7 +30,7 @@ describe('kernel/public_kernel', () => { }); it('simulating public kernel circuit fails when aggregating proofs will overflow', async function () { - const input = await makePublicKernelInputsWithTweak(1, input => { + const input = makePublicKernelInputsWithTweak(1, input => { input.publicCall.callStackItem.functionData.isConstructor = false; input.publicCall.callStackItem.functionData.isPrivate = false; input.previousKernel.publicInputs.isPrivate = false; diff --git a/yarn-project/circuits.js/src/structs/call_stack_item.ts b/yarn-project/circuits.js/src/structs/call_stack_item.ts index 581fc315f41..5a6ac6422c7 100644 --- a/yarn-project/circuits.js/src/structs/call_stack_item.ts +++ b/yarn-project/circuits.js/src/structs/call_stack_item.ts @@ -1,7 +1,6 @@ import { AztecAddress } from '@aztec/foundation/aztec-address'; import { computePublicCallStackItemHash } from '../abis/abis.js'; -import { CircuitsWasm } from '../index.js'; import { serializeToBuffer } from '../utils/serialize.js'; import { FunctionData } from './function_data.js'; import { PrivateCircuitPublicInputs } from './private_circuit_public_inputs.js'; @@ -102,7 +101,7 @@ export class PublicCallStackItem { * Computes this call stack item hash. * @returns Hash. */ - public async hash() { - return computePublicCallStackItemHash(await CircuitsWasm.get(), this); + public hash() { + return computePublicCallStackItemHash(this); } } diff --git a/yarn-project/circuits.js/src/structs/complete_address.ts b/yarn-project/circuits.js/src/structs/complete_address.ts index e0f86e1419d..b2fd575e4d5 100644 --- a/yarn-project/circuits.js/src/structs/complete_address.ts +++ b/yarn-project/circuits.js/src/structs/complete_address.ts @@ -4,7 +4,7 @@ import { BufferReader } from '@aztec/foundation/serialize'; import { computeContractAddressFromPartial } from '../abis/abis.js'; import { Grumpkin } from '../barretenberg/index.js'; -import { CircuitsWasm, GrumpkinPrivateKey, PartialAddress, PublicKey } from '../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. @@ -47,12 +47,8 @@ export class CompleteAddress { return new CompleteAddress(address, pubKey, partialAddress); } - static async fromPrivateKeyAndPartialAddress( - privateKey: GrumpkinPrivateKey, - partialAddress: Fr, - ): Promise { - const wasm = await CircuitsWasm.get(); - const grumpkin = new Grumpkin(wasm); + 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); diff --git a/yarn-project/circuits.js/src/structs/kernel/index.test.ts b/yarn-project/circuits.js/src/structs/kernel/index.test.ts index efc97550c87..5340d727234 100644 --- a/yarn-project/circuits.js/src/structs/kernel/index.test.ts +++ b/yarn-project/circuits.js/src/structs/kernel/index.test.ts @@ -71,7 +71,7 @@ describe('structs/kernel', () => { }); it(`serializes and prints public_kernel_inputs`, async () => { - const kernelInputs = await makePublicKernelInputs(); + const kernelInputs = makePublicKernelInputs(); await expectSerializeToMatchSnapshot( kernelInputs.toBuffer(), 'abis__test_roundtrip_serialize_public_kernel_inputs', diff --git a/yarn-project/circuits.js/src/tests/factories.ts b/yarn-project/circuits.js/src/tests/factories.ts index 67b8cf4391e..6e15d1ec6d1 100644 --- a/yarn-project/circuits.js/src/tests/factories.ts +++ b/yarn-project/circuits.js/src/tests/factories.ts @@ -14,7 +14,6 @@ import { CONTRACT_TREE_HEIGHT, CallContext, CircuitType, - CircuitsWasm, CombinedAccumulatedData, CombinedConstantData, ConstantRollupData, @@ -515,7 +514,7 @@ export function makePublicCallStackItem(seed = 1, full = false): PublicCallStack * @param seed - The seed to use for generating the public call data. * @returns A public call data. */ -export async function makePublicCallData(seed = 1, full = false): Promise { +export function makePublicCallData(seed = 1, full = false): PublicCallData { const publicCallData = new PublicCallData( makePublicCallStackItem(seed, full), makeTuple(MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL, makePublicCallStackItem, seed + 0x300), @@ -541,10 +540,9 @@ export async function makePublicCallData(seed = 1, full = false): Promise computeCallStackItemHash(wasm!, preimage), + preimage => computeCallStackItemHash(preimage), ); return publicCallData; @@ -555,9 +553,9 @@ export async function makePublicCallData(seed = 1, full = false): Promise { +export function makeWitnessedPublicCallData(seed = 1): WitnessedPublicCallData { return new WitnessedPublicCallData( - await makePublicCallData(seed), + makePublicCallData(seed), range(MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, seed + 0x100).map(x => makeMembershipWitness(PUBLIC_DATA_TREE_HEIGHT, x), ), @@ -571,8 +569,8 @@ export async function makeWitnessedPublicCallData(seed = 1): Promise { - return new PublicKernelInputs(makePreviousKernelData(seed), await makePublicCallData(seed + 0x1000)); +export function makePublicKernelInputs(seed = 1): PublicKernelInputs { + return new PublicKernelInputs(makePreviousKernelData(seed), makePublicCallData(seed + 0x1000)); } /** @@ -581,20 +579,19 @@ export async function makePublicKernelInputs(seed = 1): Promise void, -): Promise { +): PublicKernelInputs { const kernelCircuitPublicInputs = makeKernelPublicInputs(seed, false); const publicKernelInputs = new PublicKernelInputs( makePreviousKernelData(seed, kernelCircuitPublicInputs), - await makePublicCallData(seed + 0x1000), + makePublicCallData(seed + 0x1000), ); if (tweak) tweak(publicKernelInputs); // Set the call stack item for this circuit iteration at the top of the call stack - const wasm = await CircuitsWasm.get(); publicKernelInputs.previousKernel.publicInputs.end.publicCallStack[MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX - 1] = - computeCallStackItemHash(wasm, publicKernelInputs.publicCall.callStackItem); + computeCallStackItemHash(publicKernelInputs.publicCall.callStackItem); return publicKernelInputs; } diff --git a/yarn-project/cli/package.json b/yarn-project/cli/package.json index f1304f5fe44..59959de4f74 100644 --- a/yarn-project/cli/package.json +++ b/yarn-project/cli/package.json @@ -53,7 +53,6 @@ }, "devDependencies": { "@jest/globals": "^29.5.0", - "@rushstack/eslint-patch": "^1.1.4", "@types/jest": "^29.5.0", "@types/lodash.startcase": "^4.4.7", "@types/node": "^18.7.23", diff --git a/yarn-project/cli/src/index.ts b/yarn-project/cli/src/index.ts index a33f13ae89c..fc002937fa6 100644 --- a/yarn-project/cli/src/index.ts +++ b/yarn-project/cli/src/index.ts @@ -129,18 +129,18 @@ export function getProgram(log: LogFn, debugLogger: DebugLogger): Command { '-m, --mnemonic', 'An optional mnemonic string used for the private key generation. If not provided, random private key will be generated.', ) - .action(async options => { + .action(options => { let privKey; let publicKey; if (options.mnemonic) { const acc = mnemonicToAccount(options.mnemonic); // TODO(#2052): This reduction is not secure enough. TACKLE THIS ISSUE BEFORE MAINNET. const key = GrumpkinScalar.fromBufferWithReduction(Buffer.from(acc.getHdKey().privateKey!)); - publicKey = await generatePublicKey(key); + publicKey = generatePublicKey(key); } else { const key = GrumpkinScalar.random(); privKey = key.toString(true); - publicKey = await generatePublicKey(key); + publicKey = generatePublicKey(key); } log(`\nPrivate Key: ${privKey}\nPublic Key: ${publicKey.toString()}\n`); }); @@ -174,7 +174,7 @@ export function getProgram(log: LogFn, debugLogger: DebugLogger): Command { const actualPrivateKey = privateKey ?? GrumpkinScalar.random(); const account = getSchnorrAccount(client, actualPrivateKey, actualPrivateKey, accountCreationSalt); - const { address, publicKey, partialAddress } = await account.getCompleteAddress(); + const { address, publicKey, partialAddress } = account.getCompleteAddress(); const tx = await account.deploy(); const txHash = await tx.getTxHash(); debugLogger(`Account contract tx sent with hash ${txHash}`); diff --git a/yarn-project/end-to-end/package.json b/yarn-project/end-to-end/package.json index 3c6adc367f0..9c4d1b93c3f 100644 --- a/yarn-project/end-to-end/package.json +++ b/yarn-project/end-to-end/package.json @@ -71,7 +71,6 @@ "winston": "^3.10.0" }, "devDependencies": { - "@rushstack/eslint-patch": "^1.1.4", "concurrently": "^7.6.0" }, "files": [ diff --git a/yarn-project/end-to-end/src/e2e_2_pxes.test.ts b/yarn-project/end-to-end/src/e2e_2_pxes.test.ts index ad21409a9de..179230468d1 100644 --- a/yarn-project/end-to-end/src/e2e_2_pxes.test.ts +++ b/yarn-project/end-to-end/src/e2e_2_pxes.test.ts @@ -254,7 +254,7 @@ describe('e2e_2_pxes', () => { it('permits migrating an account from one PXE to another', async () => { const privateKey = GrumpkinScalar.random(); const account = getUnsafeSchnorrAccount(pxeA, privateKey, Fr.random()); - const completeAddress = await account.getCompleteAddress(); + const completeAddress = account.getCompleteAddress(); const wallet = await account.waitDeploy(); await expect(wallet.isAccountStateSynchronized(completeAddress.address)).resolves.toBe(true); diff --git a/yarn-project/end-to-end/src/e2e_account_contracts.test.ts b/yarn-project/end-to-end/src/e2e_account_contracts.test.ts index d66139c8a93..ee501fa57e7 100644 --- a/yarn-project/end-to-end/src/e2e_account_contracts.test.ts +++ b/yarn-project/end-to-end/src/e2e_account_contracts.test.ts @@ -62,7 +62,7 @@ function itShouldBehaveLikeAnAccountContract( }, 60_000); it('fails to call a function using an invalid signature', async () => { - const accountAddress = await account.getCompleteAddress(); + const accountAddress = account.getCompleteAddress(); const { wallet: invalidWallet } = await walletSetup( context.pxe, encryptionPrivateKey, diff --git a/yarn-project/end-to-end/src/e2e_deploy_contract.test.ts b/yarn-project/end-to-end/src/e2e_deploy_contract.test.ts index e9383e81b77..dac1cbd909f 100644 --- a/yarn-project/end-to-end/src/e2e_deploy_contract.test.ts +++ b/yarn-project/end-to-end/src/e2e_deploy_contract.test.ts @@ -38,7 +38,7 @@ describe('e2e_deploy_contract', () => { it('should deploy a contract', async () => { const publicKey = accounts[0].publicKey; const salt = Fr.random(); - const deploymentData = await getContractDeploymentInfo(TestContractArtifact, [], salt, publicKey); + const deploymentData = getContractDeploymentInfo(TestContractArtifact, [], salt, publicKey); const deployer = new ContractDeployer(TestContractArtifact, pxe, publicKey); const tx = deployer.deploy().send({ contractAddressSalt: salt }); logger(`Tx sent with hash ${await tx.getTxHash()}`); diff --git a/yarn-project/end-to-end/src/e2e_escrow_contract.test.ts b/yarn-project/end-to-end/src/e2e_escrow_contract.test.ts index 97a1fb488de..6e1361238bd 100644 --- a/yarn-project/end-to-end/src/e2e_escrow_contract.test.ts +++ b/yarn-project/end-to-end/src/e2e_escrow_contract.test.ts @@ -53,9 +53,9 @@ describe('e2e_escrow_contract', () => { // Generate private key for escrow contract, register key in pxe service, and deploy // Note that we need to register it first if we want to emit an encrypted note for it in the constructor escrowPrivateKey = GrumpkinScalar.random(); - escrowPublicKey = await generatePublicKey(escrowPrivateKey); + escrowPublicKey = generatePublicKey(escrowPrivateKey); const salt = Fr.random(); - const deployInfo = await getContractDeploymentInfo(EscrowContractArtifact, [owner], salt, escrowPublicKey); + const deployInfo = getContractDeploymentInfo(EscrowContractArtifact, [owner], salt, escrowPublicKey); await pxe.registerAccount(escrowPrivateKey, deployInfo.completeAddress.partialAddress); escrowContract = await EscrowContract.deployWithPublicKey(escrowPublicKey, wallet, owner) diff --git a/yarn-project/end-to-end/src/e2e_multiple_accounts_1_enc_key.test.ts b/yarn-project/end-to-end/src/e2e_multiple_accounts_1_enc_key.test.ts index 9cb2bd8b16d..693d722eb30 100644 --- a/yarn-project/end-to-end/src/e2e_multiple_accounts_1_enc_key.test.ts +++ b/yarn-project/end-to-end/src/e2e_multiple_accounts_1_enc_key.test.ts @@ -44,14 +44,14 @@ describe('e2e_multiple_accounts_1_enc_key', () => { const signingPrivateKey = GrumpkinScalar.random(); const account = getSchnorrAccount(pxe, encryptionPrivateKey, signingPrivateKey); const wallet = await account.waitDeploy({ interval: 0.1 }); - const { address } = await account.getCompleteAddress(); + const { address } = account.getCompleteAddress(); wallets.push(wallet); accounts.push(address); } logger('Account contracts deployed'); // Verify that all accounts use the same encryption key - const encryptionPublicKey = await generatePublicKey(encryptionPrivateKey); + const encryptionPublicKey = generatePublicKey(encryptionPrivateKey); // Disregard sandbox accounts let keyAccounts: CompleteAddress[]; diff --git a/yarn-project/end-to-end/src/e2e_p2p_network.test.ts b/yarn-project/end-to-end/src/e2e_p2p_network.test.ts index f5cb8042091..794769e131d 100644 --- a/yarn-project/end-to-end/src/e2e_p2p_network.test.ts +++ b/yarn-project/end-to-end/src/e2e_p2p_network.test.ts @@ -127,8 +127,7 @@ describe('e2e_p2p_network', () => { const txs: DeploySentTx[] = []; for (let i = 0; i < numTxs; i++) { const salt = Fr.random(); - const origin = (await getContractDeploymentInfo(TestContractArtifact, [], salt, publicKey)).completeAddress - .address; + const origin = getContractDeploymentInfo(TestContractArtifact, [], salt, publicKey).completeAddress.address; const deployer = new ContractDeployer(TestContractArtifact, pxe, publicKey); const tx = deployer.deploy().send({ contractAddressSalt: salt }); logger(`Tx sent with hash ${await tx.getTxHash()}`); @@ -153,12 +152,9 @@ describe('e2e_p2p_network', () => { const rpcConfig = getRpcConfig(); const pxeService = await createPXEService(node, rpcConfig, {}, true); - const keyPair = ConstantKeyPair.random(await Grumpkin.new()); - const completeAddress = await CompleteAddress.fromPrivateKeyAndPartialAddress( - await keyPair.getPrivateKey(), - Fr.random(), - ); - await pxeService.registerAccount(await keyPair.getPrivateKey(), completeAddress.partialAddress); + const keyPair = ConstantKeyPair.random(new Grumpkin()); + const completeAddress = CompleteAddress.fromPrivateKeyAndPartialAddress(keyPair.getPrivateKey(), Fr.random()); + await pxeService.registerAccount(keyPair.getPrivateKey(), completeAddress.partialAddress); const txs = await submitTxsTo(pxeService, completeAddress.address, numTxs, completeAddress.publicKey); return { diff --git a/yarn-project/end-to-end/src/fixtures/utils.ts b/yarn-project/end-to-end/src/fixtures/utils.ts index e2056369a18..09cf92c932b 100644 --- a/yarn-project/end-to-end/src/fixtures/utils.ts +++ b/yarn-project/end-to-end/src/fixtures/utils.ts @@ -196,7 +196,7 @@ async function setupWithSandbox(account: Account, config: AztecNodeConfig, logge walletClient, publicClient, }; - const cheatCodes = await CheatCodes.create(config.rpcUrl, pxeClient!); + const cheatCodes = CheatCodes.create(config.rpcUrl, pxeClient!); const teardown = () => Promise.resolve(); return { aztecNode, @@ -287,7 +287,7 @@ export async function setup(numberOfAccounts = 1, opts: SetupOptions = {}): Prom const { pxe, accounts, wallets } = await setupPXEService(numberOfAccounts, aztecNode!, logger); - const cheatCodes = await CheatCodes.create(config.rpcUrl, pxe!); + const cheatCodes = CheatCodes.create(config.rpcUrl, pxe!); const teardown = async () => { if (aztecNode instanceof AztecNodeService) await aztecNode?.stop(); diff --git a/yarn-project/end-to-end/src/guides/dapp_testing.test.ts b/yarn-project/end-to-end/src/guides/dapp_testing.test.ts index ee03c984ba6..6a19ee36ba7 100644 --- a/yarn-project/end-to-end/src/guides/dapp_testing.test.ts +++ b/yarn-project/end-to-end/src/guides/dapp_testing.test.ts @@ -99,7 +99,7 @@ describe('guides/dapp/testing', () => { pxe = createPXEClient(PXE_URL); owner = await createAccount(pxe); testContract = await TestContract.deploy(owner).send().deployed(); - cheats = await CheatCodes.create(ETHEREUM_HOST, pxe); + cheats = CheatCodes.create(ETHEREUM_HOST, pxe); }, 30_000); it('warps time to 1h into the future', async () => { @@ -141,7 +141,7 @@ describe('guides/dapp/testing', () => { await token.methods.redeem_shield(ownerAddress, 100n, secret).send().wait(); // docs:start:calc-slot - cheats = await CheatCodes.create(ETHEREUM_HOST, pxe); + cheats = CheatCodes.create(ETHEREUM_HOST, pxe); // The balances mapping is defined on storage slot 3 and is indexed by user address ownerSlot = cheats.aztec.computeSlotInMap(3n, ownerAddress); // docs:end:calc-slot diff --git a/yarn-project/end-to-end/src/guides/writing_an_account_contract.test.ts b/yarn-project/end-to-end/src/guides/writing_an_account_contract.test.ts index 867c1f998d2..ce67b832016 100644 --- a/yarn-project/end-to-end/src/guides/writing_an_account_contract.test.ts +++ b/yarn-project/end-to-end/src/guides/writing_an_account_contract.test.ts @@ -25,18 +25,18 @@ class SchnorrHardcodedKeyAccountContract extends BaseAccountContract { super(SchnorrHardcodedAccountContractArtifact); } - getDeploymentArgs(): Promise { + getDeploymentArgs(): any[] { // This contract does not require any arguments in its constructor. - return Promise.resolve([]); + return []; } getAuthWitnessProvider(_address: CompleteAddress): AuthWitnessProvider { const privateKey = this.privateKey; return { - async createAuthWitness(message: Fr): Promise { - const signer = await Schnorr.new(); + createAuthWitness(message: Fr): Promise { + const signer = new Schnorr(); const signature = signer.constructSignature(message.toBuffer(), privateKey); - return new AuthWitness(message, [...signature.toBuffer()]); + return Promise.resolve(new AuthWitness(message, [...signature.toBuffer()])); }, }; } diff --git a/yarn-project/end-to-end/src/shared/browser.ts b/yarn-project/end-to-end/src/shared/browser.ts index 050c5f4f814..72b064bc903 100644 --- a/yarn-project/end-to-end/src/shared/browser.ts +++ b/yarn-project/end-to-end/src/shared/browser.ts @@ -99,7 +99,7 @@ export const browserTestSuite = (setup: () => Server, pageLogger: AztecJs.DebugL const privateKey = GrumpkinScalar.fromString(privateKeyString); const account = getUnsafeSchnorrAccount(pxe, privateKey); await account.waitDeploy(); - const completeAddress = await account.getCompleteAddress(); + const completeAddress = account.getCompleteAddress(); const addressString = completeAddress.address.toString(); console.log(`Created Account: ${addressString}`); return addressString; diff --git a/yarn-project/ethereum/package.json b/yarn-project/ethereum/package.json index 30600a60103..97f9aa6ce8d 100644 --- a/yarn-project/ethereum/package.json +++ b/yarn-project/ethereum/package.json @@ -31,7 +31,6 @@ }, "devDependencies": { "@jest/globals": "^29.5.0", - "@rushstack/eslint-patch": "^1.1.4", "@types/jest": "^29.5.0", "@types/node": "^18.14.6", "jest": "^29.5.0", diff --git a/yarn-project/foundation/package.json b/yarn-project/foundation/package.json index d71d41889d5..112b7421a3e 100644 --- a/yarn-project/foundation/package.json +++ b/yarn-project/foundation/package.json @@ -79,7 +79,6 @@ }, "devDependencies": { "@jest/globals": "^29.5.0", - "@rushstack/eslint-patch": "^1.1.4", "@types/bn.js": "^5.1.3", "@types/debug": "^4.1.7", "@types/detect-node": "^2.0.0", diff --git a/yarn-project/foundation/src/crypto/pedersen/__snapshots__/index.test.ts.snap b/yarn-project/foundation/src/crypto/pedersen/__snapshots__/index.test.ts.snap new file mode 100644 index 00000000000..b650a488bcb --- /dev/null +++ b/yarn-project/foundation/src/crypto/pedersen/__snapshots__/index.test.ts.snap @@ -0,0 +1,41 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`pedersen pedersen hash buffer 1`] = ` +{ + "data": [ + 43, + 213, + 196, + 82, + 160, + 201, + 113, + 98, + 41, + 79, + 201, + 223, + 208, + 241, + 224, + 157, + 14, + 9, + 201, + 95, + 165, + 237, + 63, + 241, + 73, + 251, + 222, + 243, + 102, + 203, + 81, + 249, + ], + "type": "Buffer", +} +`; diff --git a/yarn-project/foundation/src/crypto/pedersen/index.test.ts b/yarn-project/foundation/src/crypto/pedersen/index.test.ts index 0640c13d0b1..1d152a917d0 100644 --- a/yarn-project/foundation/src/crypto/pedersen/index.test.ts +++ b/yarn-project/foundation/src/crypto/pedersen/index.test.ts @@ -1,5 +1,5 @@ import { toBufferBE } from '../../bigint-buffer/index.js'; -import { pedersenCommit, pedersenHash } from './index.js'; +import { pedersenCommit, pedersenHash, pedersenHashBuffer } from './index.js'; describe('pedersen', () => { it('pedersen commit', () => { @@ -27,4 +27,12 @@ describe('pedersen', () => { const r = pedersenHash([toBufferBE(1n, 32), toBufferBE(1n, 32)], 5); expect(r).toEqual(Buffer.from('1c446df60816b897cda124524e6b03f36df0cec333fad87617aab70d7861daa6', 'hex')); }); + + it('pedersen hash buffer', () => { + const input = Buffer.alloc(123); + input.writeUint32BE(321, 0); + input.writeUint32BE(456, 119); + const r = pedersenHashBuffer(input); + expect(r).toMatchSnapshot(); + }); }); diff --git a/yarn-project/foundation/src/crypto/pedersen/pedersen.wasm.ts b/yarn-project/foundation/src/crypto/pedersen/pedersen.wasm.ts index 86fd96e882d..2a117ea5519 100644 --- a/yarn-project/foundation/src/crypto/pedersen/pedersen.wasm.ts +++ b/yarn-project/foundation/src/crypto/pedersen/pedersen.wasm.ts @@ -1,6 +1,8 @@ -import { Pedersen } from '@aztec/bb.js'; +import { BarretenbergSync, Fr } from '@aztec/bb.js'; -const pedersen = await Pedersen.new(); +// 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(); /** * Create a pedersen commitment (point) from an array of input fields. @@ -11,8 +13,10 @@ export function pedersenCommit(input: Buffer[]) { throw new Error('All input buffers must be <= 32 bytes.'); } input = input.map(i => (i.length < 32 ? Buffer.concat([Buffer.alloc(32 - i.length, 0), i]) : i)); - const [x, y] = pedersen.pedersenCommit(input); - return [Buffer.from(x), Buffer.from(y)]; + const point = api.pedersenCommit(input.map(i => new Fr(i))); + // toBuffer returns Uint8Arrays (browser/worker-boundary friendly). + // TODO: rename toTypedArray()? + return [Buffer.from(point.x.toBuffer()), Buffer.from(point.y.toBuffer())]; } /** @@ -24,5 +28,19 @@ export function pedersenHash(input: Buffer[], index = 0) { throw new Error('All input buffers must be <= 32 bytes.'); } input = input.map(i => (i.length < 32 ? Buffer.concat([Buffer.alloc(32 - i.length, 0), i]) : i)); - return Buffer.from(pedersen.pedersenHash(input, index)); + return Buffer.from( + api + .pedersenHash( + input.map(i => new Fr(i)), + index, + ) + .toBuffer(), + ); +} + +/** + * Create a pedersen hash from an arbitrary length buffer. + */ +export function pedersenHashBuffer(input: Buffer, index = 0) { + return Buffer.from(api.pedersenHashBuffer(input, index).toBuffer()); } diff --git a/yarn-project/foundation/src/serialize/free_funcs.ts b/yarn-project/foundation/src/serialize/free_funcs.ts index 6f4242582c6..20391615cb3 100644 --- a/yarn-project/foundation/src/serialize/free_funcs.ts +++ b/yarn-project/foundation/src/serialize/free_funcs.ts @@ -15,6 +15,17 @@ export function boolToByte(b: boolean) { return buf; } +/** + * @param n - The input number to be converted to a big-endian unsigned 16-bit integer Buffer. + * @param bufferSize - Optional, the size of the output Buffer (default is 2). + * @returns A Buffer containing the big-endian unsigned 16-bit integer representation of the input number. + */ +export function numToUInt16BE(n: number, bufferSize = 2) { + const buf = Buffer.alloc(bufferSize); + buf.writeUInt16BE(n, bufferSize - 2); + return buf; +} + /** * Convert a number into a 4-byte little-endian unsigned integer buffer. * The input number is serialized as an unsigned 32-bit integer in little-endian byte order, diff --git a/yarn-project/key-store/package.json b/yarn-project/key-store/package.json index 231b98260dd..1809771981c 100644 --- a/yarn-project/key-store/package.json +++ b/yarn-project/key-store/package.json @@ -37,7 +37,6 @@ }, "devDependencies": { "@jest/globals": "^29.5.0", - "@rushstack/eslint-patch": "^1.1.4", "@types/jest": "^29.5.0", "@types/node": "^18.7.23", "jest": "^29.5.0", diff --git a/yarn-project/key-store/src/key_pair.ts b/yarn-project/key-store/src/key_pair.ts index ac65dac2104..961b2f5dc24 100644 --- a/yarn-project/key-store/src/key_pair.ts +++ b/yarn-project/key-store/src/key_pair.ts @@ -43,6 +43,6 @@ export class ConstantKeyPair implements KeyPair { } public getPrivateKey() { - return Promise.resolve(this.privateKey); + return this.privateKey; } } diff --git a/yarn-project/key-store/src/test_key_store.ts b/yarn-project/key-store/src/test_key_store.ts index cf1b1a957a5..865fb9d75ee 100644 --- a/yarn-project/key-store/src/test_key_store.ts +++ b/yarn-project/key-store/src/test_key_store.ts @@ -37,7 +37,7 @@ export class TestKeyStore implements KeyStore { public getAccountPrivateKey(pubKey: PublicKey): Promise { const account = this.getAccount(pubKey); - return account.getPrivateKey(); + return Promise.resolve(account.getPrivateKey()); } /** diff --git a/yarn-project/merkle-tree/package.json b/yarn-project/merkle-tree/package.json index f35d957b9f4..abd7a1cb91c 100644 --- a/yarn-project/merkle-tree/package.json +++ b/yarn-project/merkle-tree/package.json @@ -41,7 +41,6 @@ }, "devDependencies": { "@jest/globals": "^29.5.0", - "@rushstack/eslint-patch": "^1.1.4", "@types/jest": "^29.5.0", "@types/levelup": "^5.1.2", "@types/memdown": "^3.0.1", diff --git a/yarn-project/noir-compiler/package.json b/yarn-project/noir-compiler/package.json index 8c808520b02..41d4f904a19 100644 --- a/yarn-project/noir-compiler/package.json +++ b/yarn-project/noir-compiler/package.json @@ -65,7 +65,6 @@ }, "devDependencies": { "@jest/globals": "^29.5.0", - "@rushstack/eslint-patch": "^1.1.4", "@types/fs-extra": "^11.0.1", "@types/jest": "^29.5.0", "@types/lodash.camelcase": "^4.3.7", diff --git a/yarn-project/noir-contracts/package.json b/yarn-project/noir-contracts/package.json index ec1249fe8a7..72e06885b0a 100644 --- a/yarn-project/noir-contracts/package.json +++ b/yarn-project/noir-contracts/package.json @@ -38,7 +38,6 @@ "devDependencies": { "@aztec/noir-compiler": "workspace:^", "@jest/globals": "^29.5.0", - "@rushstack/eslint-patch": "^1.1.4", "@types/jest": "^29.5.0", "@types/lodash.camelcase": "^4.3.7", "@types/lodash.omit": "^4.5.7", diff --git a/yarn-project/noir-protocol-circuits/package.json b/yarn-project/noir-protocol-circuits/package.json index 0903e46da51..9040614a1e8 100644 --- a/yarn-project/noir-protocol-circuits/package.json +++ b/yarn-project/noir-protocol-circuits/package.json @@ -42,7 +42,6 @@ "@aztec/merkle-tree": "workspace:^", "@aztec/types": "workspace:^", "@jest/globals": "^29.5.0", - "@rushstack/eslint-patch": "^1.1.4", "@types/jest": "^29.5.0", "@types/node": "^18.7.23", "jest": "^29.5.0", diff --git a/yarn-project/noir-protocol-circuits/src/index.test.ts b/yarn-project/noir-protocol-circuits/src/index.test.ts index 3e85e308ef2..cf46aba0e10 100644 --- a/yarn-project/noir-protocol-circuits/src/index.test.ts +++ b/yarn-project/noir-protocol-circuits/src/index.test.ts @@ -464,24 +464,24 @@ describe('Noir compatibility tests (interop_testing.nr)', () => { expect(fnLeaf.toString()).toMatchSnapshot(); }); - it('Public call stack item matches noir', async () => { + it('Public call stack item matches noir', () => { const contractAddress = AztecAddress.fromField(new Fr(1)); const functionData = new FunctionData(new FunctionSelector(2), false, false, false); const appPublicInputs = PublicCircuitPublicInputs.empty(); appPublicInputs.newCommitments[0] = new Fr(1); const publicCallStackItem = new PublicCallStackItem(contractAddress, functionData, appPublicInputs, false); - expect((await publicCallStackItem.hash()).toString()).toMatchSnapshot(); + expect(publicCallStackItem.hash().toString()).toMatchSnapshot(); }); - it('Public call stack item request matches noir', async () => { + it('Public call stack item request matches noir', () => { const contractAddress = AztecAddress.fromField(new Fr(1)); const functionData = new FunctionData(new FunctionSelector(2), false, false, false); const appPublicInputs = PublicCircuitPublicInputs.empty(); appPublicInputs.newCommitments[0] = new Fr(1); const publicCallStackItem = new PublicCallStackItem(contractAddress, functionData, appPublicInputs, true); - expect((await publicCallStackItem.hash()).toString()).toMatchSnapshot(); + expect(publicCallStackItem.hash().toString()).toMatchSnapshot(); }); }); diff --git a/yarn-project/noir-protocol-circuits/src/noir_test_gen.test.ts b/yarn-project/noir-protocol-circuits/src/noir_test_gen.test.ts index 602a8b32ad5..d096a8704b6 100644 --- a/yarn-project/noir-protocol-circuits/src/noir_test_gen.test.ts +++ b/yarn-project/noir-protocol-circuits/src/noir_test_gen.test.ts @@ -1,16 +1,14 @@ import { AztecAddress, CONTRACT_TREE_HEIGHT, - CircuitsWasm, EthAddress, FunctionLeafPreimage, FunctionSelector, NOTE_HASH_TREE_HEIGHT, NewContractData, - computeFunctionTree, computeFunctionTreeData, } from '@aztec/circuits.js'; -import { computeContractLeaf, computeFunctionLeaf } from '@aztec/circuits.js/abis'; +import { computeContractLeaf, computeFunctionLeaf, computeFunctionTree } from '@aztec/circuits.js/abis'; import { Fr } from '@aztec/foundation/fields'; import { Pedersen, StandardTree } from '@aztec/merkle-tree'; import { MerkleTreeId } from '@aztec/types'; @@ -28,12 +26,6 @@ describe('Data generation for noir tests', () => { let functionLeaf: Fr; let functionTreeRoot: Fr; - let wasm: CircuitsWasm; - - beforeAll(async () => { - wasm = await CircuitsWasm.get(); - }); - it('Computes function leaf', () => { const functionLeafPreimage = new FunctionLeafPreimage(selector, false, true, vkHash, acirHash); @@ -43,7 +35,7 @@ describe('Data generation for noir tests', () => { }); it('Computes function tree data', () => { - const tree = computeFunctionTree(wasm, [functionLeaf]); + const tree = computeFunctionTree([functionLeaf]); const functionTreeData = computeFunctionTreeData(tree, 0); diff --git a/yarn-project/p2p-bootstrap/package.json b/yarn-project/p2p-bootstrap/package.json index e5f3c5b61bf..42c952327c5 100644 --- a/yarn-project/p2p-bootstrap/package.json +++ b/yarn-project/p2p-bootstrap/package.json @@ -31,7 +31,6 @@ }, "devDependencies": { "@jest/globals": "^29.5.0", - "@rushstack/eslint-patch": "^1.1.4", "@types/jest": "^29.5.0", "@types/node": "^18.14.6", "jest": "^29.5.0", diff --git a/yarn-project/p2p/package.json b/yarn-project/p2p/package.json index 19a4bd74f49..7c1cc96b3aa 100644 --- a/yarn-project/p2p/package.json +++ b/yarn-project/p2p/package.json @@ -54,7 +54,6 @@ }, "devDependencies": { "@jest/globals": "^29.5.0", - "@rushstack/eslint-patch": "^1.1.4", "@types/jest": "^29.5.0", "@types/lodash.times": "^4.3.7", "@types/node": "^18.14.6", diff --git a/yarn-project/prover-client/package.json b/yarn-project/prover-client/package.json index f52b8a4494f..615bc2e4b8d 100644 --- a/yarn-project/prover-client/package.json +++ b/yarn-project/prover-client/package.json @@ -35,7 +35,6 @@ }, "devDependencies": { "@jest/globals": "^29.5.0", - "@rushstack/eslint-patch": "^1.1.4", "@types/jest": "^29.5.0", "@types/node": "^18.7.23", "jest": "^29.5.0", diff --git a/yarn-project/pxe/package.json b/yarn-project/pxe/package.json index 37b929e7323..1fe51c30058 100644 --- a/yarn-project/pxe/package.json +++ b/yarn-project/pxe/package.json @@ -51,7 +51,6 @@ }, "devDependencies": { "@jest/globals": "^29.5.0", - "@rushstack/eslint-patch": "^1.1.4", "@types/jest": "^29.5.0", "@types/lodash.omit": "^4.5.7", "@types/lodash.partition": "^4.6.0", diff --git a/yarn-project/pxe/src/contract_data_oracle/index.ts b/yarn-project/pxe/src/contract_data_oracle/index.ts index 9713c5cf2ba..56eeaf60c59 100644 --- a/yarn-project/pxe/src/contract_data_oracle/index.ts +++ b/yarn-project/pxe/src/contract_data_oracle/index.ts @@ -1,4 +1,4 @@ -import { AztecAddress, CircuitsWasm, MembershipWitness, VK_TREE_HEIGHT } from '@aztec/circuits.js'; +import { AztecAddress, MembershipWitness, VK_TREE_HEIGHT } from '@aztec/circuits.js'; import { FunctionDebugMetadata, FunctionSelector, getFunctionDebugMetadata } from '@aztec/foundation/abi'; import { ContractDatabase, StateInfoProvider } from '@aztec/types'; @@ -155,8 +155,7 @@ export class ContractDataOracle { throw new Error(`Unknown contract: ${contractAddress}`); } - const wasm = await CircuitsWasm.get(); - tree = new ContractTree(contract, this.stateProvider, wasm); + tree = new ContractTree(contract, this.stateProvider); this.trees.push(tree); } return tree; diff --git a/yarn-project/pxe/src/contract_tree/index.ts b/yarn-project/pxe/src/contract_tree/index.ts index 81546f39baf..8726daf8295 100644 --- a/yarn-project/pxe/src/contract_tree/index.ts +++ b/yarn-project/pxe/src/contract_tree/index.ts @@ -1,6 +1,5 @@ import { CONTRACT_TREE_HEIGHT, - CircuitsWasm, EthAddress, FUNCTION_TREE_HEIGHT, Fr, @@ -8,7 +7,6 @@ import { MembershipWitness, NewContractConstructor, NewContractData, - computeFunctionTree, computeFunctionTreeData, generateFunctionLeaves, hashVKStr, @@ -18,6 +16,7 @@ import { import { computeCompleteAddress, computeContractLeaf, + computeFunctionTree, computeFunctionTreeRoot, computeVarArgsHash, hashConstructor, @@ -44,7 +43,6 @@ export class ContractTree { */ public readonly contract: ContractDao, private stateInfoProvider: StateInfoProvider, - private wasm: CircuitsWasm, /** * Data associated with the contract constructor for a new contract. */ @@ -66,7 +64,7 @@ export class ContractTree { * @param node - An instance of the AztecNode class representing the current node. * @returns A new ContractTree instance containing the contract data and computed values. */ - public static async new( + public static new( artifact: ContractArtifact, args: Fr[], portalContract: EthAddress, @@ -74,7 +72,6 @@ export class ContractTree { from: PublicKey, node: AztecNode, ) { - const wasm = await CircuitsWasm.get(); const constructorArtifact = artifact.functions.find(isConstructor); if (!constructorArtifact) { throw new Error('Constructor not found.'); @@ -88,9 +85,9 @@ export class ContractTree { selector: FunctionSelector.fromNameAndParameters(f.name, f.parameters), })); const leaves = generateFunctionLeaves(functions); - const root = computeFunctionTreeRoot(wasm, leaves); + const root = computeFunctionTreeRoot(leaves); const functionData = FunctionData.fromAbi(constructorArtifact); - const vkHash = hashVKStr(constructorArtifact.verificationKey, wasm); + const vkHash = hashVKStr(constructorArtifact.verificationKey); const argsHash = computeVarArgsHash(args); const constructorHash = hashConstructor(functionData, argsHash, vkHash); @@ -106,7 +103,7 @@ export class ContractTree { functionData, vkHash, }; - return new ContractTree(contractDao, node, wasm, NewContractConstructor); + return new ContractTree(contractDao, node, NewContractConstructor); } /** @@ -172,7 +169,7 @@ export class ContractTree { public getFunctionTreeRoot() { if (!this.functionTreeRoot) { const leaves = this.getFunctionLeaves(); - this.functionTreeRoot = computeFunctionTreeRoot(this.wasm, leaves); + this.functionTreeRoot = computeFunctionTreeRoot(leaves); } return Promise.resolve(this.functionTreeRoot); } @@ -197,7 +194,7 @@ export class ContractTree { if (!this.functionTree) { const leaves = this.getFunctionLeaves(); - this.functionTree = computeFunctionTree(this.wasm, leaves); + this.functionTree = computeFunctionTree(leaves); } const functionTreeData = computeFunctionTreeData(this.functionTree, functionIndex); return Promise.resolve( diff --git a/yarn-project/pxe/src/note_processor/note_processor.test.ts b/yarn-project/pxe/src/note_processor/note_processor.test.ts index 207850ee757..d766a04c336 100644 --- a/yarn-project/pxe/src/note_processor/note_processor.test.ts +++ b/yarn-project/pxe/src/note_processor/note_processor.test.ts @@ -1,5 +1,5 @@ import { AcirSimulator } from '@aztec/acir-simulator'; -import { CircuitsWasm, Fr, MAX_NEW_COMMITMENTS_PER_TX } from '@aztec/circuits.js'; +import { Fr, MAX_NEW_COMMITMENTS_PER_TX } from '@aztec/circuits.js'; import { Grumpkin } from '@aztec/circuits.js/barretenberg'; import { pedersenHash } from '@aztec/foundation/crypto'; import { Point } from '@aztec/foundation/fields'; @@ -28,7 +28,6 @@ import { NoteProcessor } from './note_processor.js'; const TXS_PER_BLOCK = 4; describe('Note Processor', () => { - let wasm: CircuitsWasm; let grumpkin: Grumpkin; let database: Database; let aztecNode: ReturnType>; @@ -110,9 +109,8 @@ describe('Note Processor', () => { return { blockContexts, encryptedLogsArr, ownedL1NotePayloads }; }; - beforeAll(async () => { - wasm = await CircuitsWasm.get(); - grumpkin = new Grumpkin(wasm); + beforeAll(() => { + grumpkin = new Grumpkin(); owner = ConstantKeyPair.random(grumpkin); }); diff --git a/yarn-project/pxe/src/note_processor/note_processor.ts b/yarn-project/pxe/src/note_processor/note_processor.ts index 385b4ee0c0d..00011f0e39f 100644 --- a/yarn-project/pxe/src/note_processor/note_processor.ts +++ b/yarn-project/pxe/src/note_processor/note_processor.ts @@ -94,7 +94,7 @@ export class NoteProcessor { } const blocksAndNotes: ProcessedData[] = []; - const curve = await Grumpkin.new(); + const curve = new Grumpkin(); // Iterate over both blocks and encrypted logs. for (let blockIndex = 0; blockIndex < encryptedL2BlockLogs.length; ++blockIndex) { diff --git a/yarn-project/pxe/src/pxe_service/create_pxe_service.ts b/yarn-project/pxe/src/pxe_service/create_pxe_service.ts index 4fc15e58f6f..04eddd7db48 100644 --- a/yarn-project/pxe/src/pxe_service/create_pxe_service.ts +++ b/yarn-project/pxe/src/pxe_service/create_pxe_service.ts @@ -43,7 +43,7 @@ export async function createPXEService( : undefined : useLogSuffix; - keyStore = keyStore || new TestKeyStore(await Grumpkin.new()); + keyStore = keyStore || new TestKeyStore(new Grumpkin()); db = db || new MemoryDB(logSuffix); const server = new PXEService(keyStore, aztecNode, db, config, logSuffix); diff --git a/yarn-project/pxe/src/pxe_service/pxe_service.ts b/yarn-project/pxe/src/pxe_service/pxe_service.ts index 26aec37b47a..4af7a2f6f2d 100644 --- a/yarn-project/pxe/src/pxe_service/pxe_service.ts +++ b/yarn-project/pxe/src/pxe_service/pxe_service.ts @@ -120,7 +120,7 @@ export class PXEService implements PXE { } public async registerAccount(privKey: GrumpkinPrivateKey, partialAddress: PartialAddress): Promise { - const completeAddress = await CompleteAddress.fromPrivateKeyAndPartialAddress(privKey, partialAddress); + const completeAddress = CompleteAddress.fromPrivateKeyAndPartialAddress(privKey, partialAddress); const wasAdded = await this.db.addCompleteAddress(completeAddress); if (wasAdded) { const pubKey = this.keyStore.addAccount(privKey); diff --git a/yarn-project/pxe/src/pxe_service/test/pxe_service.test.ts b/yarn-project/pxe/src/pxe_service/test/pxe_service.test.ts index a980b0efa18..e265d99a898 100644 --- a/yarn-project/pxe/src/pxe_service/test/pxe_service.test.ts +++ b/yarn-project/pxe/src/pxe_service/test/pxe_service.test.ts @@ -11,8 +11,8 @@ import { PXEServiceConfig } from '../../index.js'; import { PXEService } from '../pxe_service.js'; import { pxeTestSuite } from './pxe_test_suite.js'; -async function createPXEService(): Promise { - const keyStore = new TestKeyStore(await Grumpkin.new()); +function createPXEService(): Promise { + const keyStore = new TestKeyStore(new Grumpkin()); const node = mock(); const db = new MemoryDB(); const config: PXEServiceConfig = { l2BlockPollingIntervalMS: 100, l2StartingBlock: INITIAL_L2_BLOCK_NUM }; @@ -31,7 +31,7 @@ async function createPXEService(): Promise { }; node.getL1ContractAddresses.mockResolvedValue(mockedContracts); - return new PXEService(keyStore, node, db, config); + return Promise.resolve(new PXEService(keyStore, node, db, config)); } pxeTestSuite('PXEService', createPXEService); @@ -42,8 +42,8 @@ describe('PXEService', () => { let db: MemoryDB; let config: PXEServiceConfig; - beforeEach(async () => { - keyStore = new TestKeyStore(await Grumpkin.new()); + beforeEach(() => { + keyStore = new TestKeyStore(new Grumpkin()); node = mock(); db = new MemoryDB(); config = { l2BlockPollingIntervalMS: 100, l2StartingBlock: INITIAL_L2_BLOCK_NUM }; diff --git a/yarn-project/pxe/src/pxe_service/test/pxe_test_suite.ts b/yarn-project/pxe/src/pxe_service/test/pxe_test_suite.ts index fdc21c69941..d23da97d651 100644 --- a/yarn-project/pxe/src/pxe_service/test/pxe_test_suite.ts +++ b/yarn-project/pxe/src/pxe_service/test/pxe_test_suite.ts @@ -12,13 +12,10 @@ export const pxeTestSuite = (testName: string, pxeSetup: () => Promise) => }, 120_000); it('registers an account and returns it as an account only and not as a recipient', async () => { - const keyPair = ConstantKeyPair.random(await Grumpkin.new()); - const completeAddress = await CompleteAddress.fromPrivateKeyAndPartialAddress( - await keyPair.getPrivateKey(), - Fr.random(), - ); + const keyPair = ConstantKeyPair.random(new Grumpkin()); + const completeAddress = CompleteAddress.fromPrivateKeyAndPartialAddress(keyPair.getPrivateKey(), Fr.random()); - await pxe.registerAccount(await keyPair.getPrivateKey(), completeAddress.partialAddress); + await pxe.registerAccount(keyPair.getPrivateKey(), completeAddress.partialAddress); // Check that the account is correctly registered using the getAccounts and getRecipients methods const accounts = await pxe.getRegisteredAccounts(); @@ -52,14 +49,11 @@ export const pxeTestSuite = (testName: string, pxeSetup: () => Promise) => }); it('does not throw when registering the same account twice (just ignores the second attempt)', async () => { - const keyPair = ConstantKeyPair.random(await Grumpkin.new()); - const completeAddress = await CompleteAddress.fromPrivateKeyAndPartialAddress( - await keyPair.getPrivateKey(), - Fr.random(), - ); + const keyPair = ConstantKeyPair.random(new Grumpkin()); + const completeAddress = CompleteAddress.fromPrivateKeyAndPartialAddress(keyPair.getPrivateKey(), Fr.random()); - await pxe.registerAccount(await keyPair.getPrivateKey(), completeAddress.partialAddress); - await pxe.registerAccount(await keyPair.getPrivateKey(), completeAddress.partialAddress); + await pxe.registerAccount(keyPair.getPrivateKey(), completeAddress.partialAddress); + await pxe.registerAccount(keyPair.getPrivateKey(), completeAddress.partialAddress); }); it('cannot register a recipient with the same aztec address but different pub key or partial address', async () => { diff --git a/yarn-project/pxe/src/synchronizer/synchronizer.test.ts b/yarn-project/pxe/src/synchronizer/synchronizer.test.ts index 29833507e2b..2179fecc524 100644 --- a/yarn-project/pxe/src/synchronizer/synchronizer.test.ts +++ b/yarn-project/pxe/src/synchronizer/synchronizer.test.ts @@ -102,10 +102,10 @@ describe('Synchronizer', () => { aztecNode.getBlockNumber.mockResolvedValueOnce(1); // Manually adding account to database so that we can call synchronizer.isAccountStateSynchronized - const keyStore = new TestKeyStore(await Grumpkin.new()); + const keyStore = new TestKeyStore(new Grumpkin()); const privateKey = GrumpkinScalar.random(); keyStore.addAccount(privateKey); - const completeAddress = await CompleteAddress.fromPrivateKeyAndPartialAddress(privateKey, Fr.random()); + const completeAddress = CompleteAddress.fromPrivateKeyAndPartialAddress(privateKey, Fr.random()); await database.addCompleteAddress(completeAddress); // Add the account which will add the note processor to the synchronizer diff --git a/yarn-project/scripts/package.json b/yarn-project/scripts/package.json index d228efbe325..0cd62ac8545 100644 --- a/yarn-project/scripts/package.json +++ b/yarn-project/scripts/package.json @@ -31,7 +31,6 @@ }, "devDependencies": { "@jest/globals": "^29.5.0", - "@rushstack/eslint-patch": "^1.1.4", "@types/jest": "^29.5.0", "@types/lodash.pick": "^4.4.7", "@types/node": "^18.14.6", diff --git a/yarn-project/sequencer-client/package.json b/yarn-project/sequencer-client/package.json index 6b9944c3dfd..0f72abfb8ea 100644 --- a/yarn-project/sequencer-client/package.json +++ b/yarn-project/sequencer-client/package.json @@ -51,7 +51,6 @@ }, "devDependencies": { "@jest/globals": "^29.5.0", - "@rushstack/eslint-patch": "^1.1.4", "@types/jest": "^29.5.0", "@types/levelup": "^5.1.2", "@types/lodash.chunk": "^4.2.7", diff --git a/yarn-project/sequencer-client/src/sequencer/public_processor.test.ts b/yarn-project/sequencer-client/src/sequencer/public_processor.test.ts index 64a36de4d09..a087fff98b3 100644 --- a/yarn-project/sequencer-client/src/sequencer/public_processor.test.ts +++ b/yarn-project/sequencer-client/src/sequencer/public_processor.test.ts @@ -3,7 +3,6 @@ import { ARGS_LENGTH, AztecAddress, CallContext, - CircuitsWasm, CombinedAccumulatedData, EthAddress, Fr, @@ -116,11 +115,6 @@ describe('public_processor', () => { describe('with actual circuits', () => { let publicKernel: PublicKernelCircuitSimulator; - let wasm: CircuitsWasm; - - beforeAll(async () => { - wasm = await CircuitsWasm.get(); - }); beforeEach(() => { const path = times(PUBLIC_DATA_TREE_HEIGHT, i => Buffer.alloc(32, i)); @@ -146,7 +140,7 @@ describe('public_processor', () => { it('runs a tx with enqueued public calls', async function () { const callRequests: PublicCallRequest[] = [makePublicCallRequest(0x100), makePublicCallRequest(0x100)]; const callStackItems = await Promise.all(callRequests.map(call => call.toPublicCallStackItem())); - const callStackHashes = callStackItems.map(call => computeCallStackItemHash(wasm, call)); + const callStackHashes = callStackItems.map(call => computeCallStackItemHash(call)); const kernelOutput = makePrivateKernelPublicInputsFinal(0x10); kernelOutput.end.publicCallStack = padArrayEnd(callStackHashes, Fr.ZERO, MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX); @@ -176,7 +170,7 @@ describe('public_processor', () => { it('runs a tx with an enqueued public call with nested execution', async function () { const callRequest: PublicCallRequest = makePublicCallRequest(0x100); const callStackItem = callRequest.toPublicCallStackItem(); - const callStackHash = computeCallStackItemHash(wasm, callStackItem); + const callStackHash = computeCallStackItemHash(callStackItem); const kernelOutput = makePrivateKernelPublicInputsFinal(0x10); kernelOutput.end.publicCallStack = padArrayEnd([callStackHash], Fr.ZERO, MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX); diff --git a/yarn-project/sequencer-client/src/sequencer/public_processor.ts b/yarn-project/sequencer-client/src/sequencer/public_processor.ts index cfdb541af78..e8274752ee5 100644 --- a/yarn-project/sequencer-client/src/sequencer/public_processor.ts +++ b/yarn-project/sequencer-client/src/sequencer/public_processor.ts @@ -8,7 +8,6 @@ import { } from '@aztec/acir-simulator'; import { AztecAddress, - CircuitsWasm, CombinedAccumulatedData, ContractStorageRead, ContractStorageUpdateRequest, @@ -249,10 +248,9 @@ export class PublicProcessor { this.blockData.publicDataTreeRoot = Fr.fromBuffer(publicDataTreeInfo.root); const callStackPreimages = await this.getPublicCallStackPreimages(result); - const wasm = await CircuitsWasm.get(); const publicCallStack = mapTuple(callStackPreimages, item => - item.isEmpty() ? Fr.zero() : computeCallStackItemHash(wasm, item), + item.isEmpty() ? Fr.zero() : computeCallStackItemHash(item), ); // TODO(https://github.com/AztecProtocol/aztec-packages/issues/1165) --> set this in Noir diff --git a/yarn-project/types/package.json b/yarn-project/types/package.json index 3bac04d8fd7..3a7aa2092ff 100644 --- a/yarn-project/types/package.json +++ b/yarn-project/types/package.json @@ -44,7 +44,6 @@ }, "devDependencies": { "@jest/globals": "^29.5.0", - "@rushstack/eslint-patch": "^1.1.4", "@types/jest": "^29.5.0", "@types/lodash.clonedeep": "^4.5.7", "@types/lodash.isequal": "^4.5.6", diff --git a/yarn-project/types/src/keys/key_pair.ts b/yarn-project/types/src/keys/key_pair.ts index d8b43186049..43809c2ad7a 100644 --- a/yarn-project/types/src/keys/key_pair.ts +++ b/yarn-project/types/src/keys/key_pair.ts @@ -16,5 +16,5 @@ export interface KeyPair { * The function returns a Promise that resolves to a Buffer containing the private key. * @returns A Promise that resolves to a Buffer containing the private key. */ - getPrivateKey(): Promise; + getPrivateKey(): GrumpkinPrivateKey; } diff --git a/yarn-project/types/src/logs/l1_note_payload/encrypt_buffer.test.ts b/yarn-project/types/src/logs/l1_note_payload/encrypt_buffer.test.ts index 2d79f54489a..b34baa4fb01 100644 --- a/yarn-project/types/src/logs/l1_note_payload/encrypt_buffer.test.ts +++ b/yarn-project/types/src/logs/l1_note_payload/encrypt_buffer.test.ts @@ -1,4 +1,4 @@ -import { CircuitsWasm, GrumpkinScalar } from '@aztec/circuits.js'; +import { GrumpkinScalar } from '@aztec/circuits.js'; import { Grumpkin } from '@aztec/circuits.js/barretenberg'; import { randomBytes } from '@aztec/foundation/crypto'; @@ -7,8 +7,8 @@ import { decryptBuffer, deriveAESSecret, encryptBuffer } from './encrypt_buffer. describe('encrypt buffer', () => { let grumpkin: Grumpkin; - beforeAll(async () => { - grumpkin = new Grumpkin(await CircuitsWasm.get()); + beforeAll(() => { + grumpkin = new Grumpkin(); }); it('derive shared secret', () => { diff --git a/yarn-project/types/src/logs/l1_note_payload/l1_note_payload.test.ts b/yarn-project/types/src/logs/l1_note_payload/l1_note_payload.test.ts index 0c06f70eadf..d5a909fe779 100644 --- a/yarn-project/types/src/logs/l1_note_payload/l1_note_payload.test.ts +++ b/yarn-project/types/src/logs/l1_note_payload/l1_note_payload.test.ts @@ -1,4 +1,3 @@ -import { CircuitsWasm } from '@aztec/circuits.js'; import { Grumpkin } from '@aztec/circuits.js/barretenberg'; import { GrumpkinScalar, Point } from '@aztec/foundation/fields'; @@ -7,8 +6,8 @@ import { L1NotePayload } from './l1_note_payload.js'; describe('L1 Note Payload', () => { let grumpkin: Grumpkin; - beforeAll(async () => { - grumpkin = new Grumpkin(await CircuitsWasm.get()); + beforeAll(() => { + grumpkin = new Grumpkin(); }); it('convert to and from buffer', () => { diff --git a/yarn-project/world-state/package.json b/yarn-project/world-state/package.json index 36c704cd0ae..f25d93f0394 100644 --- a/yarn-project/world-state/package.json +++ b/yarn-project/world-state/package.json @@ -41,7 +41,6 @@ }, "devDependencies": { "@jest/globals": "^29.5.0", - "@rushstack/eslint-patch": "^1.1.4", "@types/jest": "^29.5.0", "@types/levelup": "^5.1.2", "@types/lodash.times": "^4.3.7", diff --git a/yarn-project/yarn.lock b/yarn-project/yarn.lock index 463d5afc30d..7c5aeefb570 100644 --- a/yarn-project/yarn.lock +++ b/yarn-project/yarn.lock @@ -68,7 +68,6 @@ __metadata: "@aztec/types": "workspace:^" "@jest/globals": ^29.5.0 "@noir-lang/acvm_js": 0.30.0 - "@rushstack/eslint-patch": ^1.1.4 "@types/jest": ^29.5.0 "@types/levelup": ^5.1.3 "@types/memdown": ^3.0.2 @@ -95,7 +94,6 @@ __metadata: "@aztec/l1-artifacts": "workspace:^" "@aztec/types": "workspace:^" "@jest/globals": ^29.5.0 - "@rushstack/eslint-patch": ^1.2.0 "@types/debug": ^4.1.7 "@types/jest": ^29.5.0 "@types/lodash.omit": ^4.5.7 @@ -124,7 +122,6 @@ __metadata: "@aztec/ethereum": "workspace:^" "@aztec/foundation": "workspace:^" "@jest/globals": ^29.5.0 - "@rushstack/eslint-patch": ^1.1.4 "@types/jest": ^29.5.0 "@types/node": ^18.7.23 jest: ^29.5.0 @@ -155,7 +152,6 @@ __metadata: "@aztec/types": "workspace:^" "@aztec/world-state": "workspace:^" "@jest/globals": ^29.5.0 - "@rushstack/eslint-patch": ^1.1.4 "@types/jest": ^29.5.0 "@types/leveldown": ^4.0.4 "@types/levelup": ^5.1.2 @@ -235,7 +231,6 @@ __metadata: "@aztec/foundation": "workspace:^" "@aztec/types": "workspace:^" "@jest/globals": ^29.5.0 - "@rushstack/eslint-patch": ^1.1.4 "@types/jest": ^29.5.0 "@types/lodash.every": ^4.6.7 "@types/lodash.partition": ^4.6.0 @@ -293,6 +288,19 @@ __metadata: languageName: node linkType: hard +"@aztec/bb.js@portal:../../barretenberg/ts::locator=%40aztec%2Fcircuits.js%40workspace%3Acircuits.js": + version: 0.0.0-use.local + resolution: "@aztec/bb.js@portal:../../barretenberg/ts::locator=%40aztec%2Fcircuits.js%40workspace%3Acircuits.js" + dependencies: + comlink: ^4.4.1 + commander: ^10.0.1 + debug: ^4.3.4 + tslib: ^2.4.0 + bin: + bb.js: ./dest/node/main.js + languageName: node + linkType: soft + "@aztec/bb.js@portal:../../barretenberg/ts::locator=%40aztec%2Ffoundation%40workspace%3Afoundation": version: 0.0.0-use.local resolution: "@aztec/bb.js@portal:../../barretenberg/ts::locator=%40aztec%2Ffoundation%40workspace%3Afoundation" @@ -317,7 +325,6 @@ __metadata: "@aztec/l1-artifacts": "workspace:^" "@aztec/noir-contracts": "workspace:^" "@jest/globals": ^29.5.0 - "@rushstack/eslint-patch": ^1.1.4 "@types/jest": ^29.5.0 "@types/koa-static": ^4.0.2 "@types/node": ^18.7.23 @@ -337,6 +344,7 @@ __metadata: version: 0.0.0-use.local resolution: "@aztec/circuits.js@workspace:circuits.js" dependencies: + "@aztec/bb.js": "portal:../../barretenberg/ts" "@aztec/foundation": "workspace:^" "@jest/globals": ^29.5.0 "@msgpack/msgpack": ^3.0.0-beta2 @@ -380,7 +388,6 @@ __metadata: "@jest/globals": ^29.5.0 "@libp2p/peer-id-factory": ^3.0.4 "@ltd/j-toml": ^1.38.0 - "@rushstack/eslint-patch": ^1.1.4 "@types/jest": ^29.5.0 "@types/lodash.startcase": ^4.4.7 "@types/node": ^18.7.23 @@ -431,7 +438,6 @@ __metadata: "@aztec/world-state": "workspace:^" "@jest/globals": ^29.5.0 "@noble/curves": ^1.0.0 - "@rushstack/eslint-patch": ^1.1.4 "@types/fs-extra": ^11.0.2 "@types/jest": ^29.5.0 "@types/koa": ^2.13.9 @@ -472,7 +478,6 @@ __metadata: dependencies: "@aztec/foundation": "workspace:^" "@jest/globals": ^29.5.0 - "@rushstack/eslint-patch": ^1.1.4 "@types/jest": ^29.5.0 "@types/node": ^18.14.6 dotenv: ^16.0.3 @@ -493,7 +498,6 @@ __metadata: "@jest/globals": ^29.5.0 "@koa/cors": ^4.0.0 "@noble/curves": ^1.2.0 - "@rushstack/eslint-patch": ^1.1.4 "@types/bn.js": ^5.1.3 "@types/debug": ^4.1.7 "@types/detect-node": ^2.0.0 @@ -553,7 +557,6 @@ __metadata: "@aztec/foundation": "workspace:^" "@aztec/types": "workspace:^" "@jest/globals": ^29.5.0 - "@rushstack/eslint-patch": ^1.1.4 "@types/jest": ^29.5.0 "@types/node": ^18.7.23 jest: ^29.5.0 @@ -582,7 +585,6 @@ __metadata: "@aztec/foundation": "workspace:^" "@aztec/types": "workspace:^" "@jest/globals": ^29.5.0 - "@rushstack/eslint-patch": ^1.1.4 "@types/jest": ^29.5.0 "@types/levelup": ^5.1.2 "@types/memdown": ^3.0.1 @@ -608,7 +610,6 @@ __metadata: "@ltd/j-toml": ^1.38.0 "@noir-lang/noir_wasm": 0.18.0-6ca33a2.aztec "@noir-lang/source-resolver": 0.18.0-6ca33a2.aztec - "@rushstack/eslint-patch": ^1.1.4 "@types/fs-extra": ^11.0.1 "@types/jest": ^29.5.0 "@types/lodash.camelcase": ^4.3.7 @@ -649,7 +650,6 @@ __metadata: "@aztec/foundation": "workspace:^" "@aztec/noir-compiler": "workspace:^" "@jest/globals": ^29.5.0 - "@rushstack/eslint-patch": ^1.1.4 "@types/jest": ^29.5.0 "@types/lodash.camelcase": ^4.3.7 "@types/lodash.omit": ^4.5.7 @@ -682,7 +682,6 @@ __metadata: "@noir-lang/backend_barretenberg": ^0.7.10 "@noir-lang/noir_js": ^0.16.0 "@noir-lang/noirc_abi": ^0.16.0 - "@rushstack/eslint-patch": ^1.1.4 "@types/jest": ^29.5.0 "@types/node": ^18.7.23 jest: ^29.5.0 @@ -702,7 +701,6 @@ __metadata: "@aztec/foundation": "workspace:^" "@aztec/p2p": "workspace:^" "@jest/globals": ^29.5.0 - "@rushstack/eslint-patch": ^1.1.4 "@types/jest": ^29.5.0 "@types/node": ^18.14.6 dotenv: ^16.0.3 @@ -733,7 +731,6 @@ __metadata: "@libp2p/peer-id": ^3.0.2 "@libp2p/peer-id-factory": ^3.0.3 "@libp2p/tcp": ^8.0.4 - "@rushstack/eslint-patch": ^1.1.4 "@types/jest": ^29.5.0 "@types/lodash.times": ^4.3.7 "@types/node": ^18.14.6 @@ -756,7 +753,6 @@ __metadata: dependencies: "@aztec/foundation": "workspace:^" "@jest/globals": ^29.5.0 - "@rushstack/eslint-patch": ^1.1.4 "@types/jest": ^29.5.0 "@types/node": ^18.7.23 jest: ^29.5.0 @@ -780,7 +776,6 @@ __metadata: "@aztec/noir-protocol-circuits": "workspace:^" "@aztec/types": "workspace:^" "@jest/globals": ^29.5.0 - "@rushstack/eslint-patch": ^1.1.4 "@types/jest": ^29.5.0 "@types/lodash.omit": ^4.5.7 "@types/lodash.partition": ^4.6.0 @@ -811,7 +806,6 @@ __metadata: "@aztec/foundation": "workspace:^" "@aztec/types": "workspace:^" "@jest/globals": ^29.5.0 - "@rushstack/eslint-patch": ^1.1.4 "@types/jest": ^29.5.0 "@types/lodash.pick": ^4.4.7 "@types/node": ^18.14.6 @@ -844,7 +838,6 @@ __metadata: "@aztec/types": "workspace:^" "@aztec/world-state": "workspace:^" "@jest/globals": ^29.5.0 - "@rushstack/eslint-patch": ^1.1.4 "@types/jest": ^29.5.0 "@types/levelup": ^5.1.2 "@types/lodash.chunk": ^4.2.7 @@ -880,7 +873,6 @@ __metadata: "@aztec/ethereum": "workspace:^" "@aztec/foundation": "workspace:^" "@jest/globals": ^29.5.0 - "@rushstack/eslint-patch": ^1.1.4 "@types/jest": ^29.5.0 "@types/lodash.clonedeep": ^4.5.7 "@types/lodash.isequal": ^4.5.6 @@ -908,7 +900,6 @@ __metadata: "@aztec/merkle-tree": "workspace:^" "@aztec/types": "workspace:^" "@jest/globals": ^29.5.0 - "@rushstack/eslint-patch": ^1.1.4 "@types/jest": ^29.5.0 "@types/levelup": ^5.1.2 "@types/lodash.times": ^4.3.7 @@ -3836,13 +3827,6 @@ __metadata: languageName: node linkType: hard -"@rushstack/eslint-patch@npm:^1.1.4, @rushstack/eslint-patch@npm:^1.2.0": - version: 1.3.2 - resolution: "@rushstack/eslint-patch@npm:1.3.2" - checksum: 010c87ef2d901faaaf70ea1bf86fd3e7b74f24e23205f836e9a32790bca2076afe5de58ded03c35cb482f83691c8d22b1a0c34291b075bfe81afd26cfa5d14cc - languageName: node - linkType: hard - "@safe-global/safe-apps-provider@npm:^0.15.2": version: 0.15.2 resolution: "@safe-global/safe-apps-provider@npm:0.15.2"