diff --git a/docs/docs/aztec/smart_contracts/functions/attributes.md b/docs/docs/aztec/smart_contracts/functions/attributes.md index db8fe0a6ed5e..0ef59a9e9d75 100644 --- a/docs/docs/aztec/smart_contracts/functions/attributes.md +++ b/docs/docs/aztec/smart_contracts/functions/attributes.md @@ -92,7 +92,7 @@ To generate the environment, the simulator gets the block header from the [PXE d Once the execution environment is created, `runUtility` function is invoked on the simulator: -#include_code execute_utility_function yarn-project/simulator/src/private/simulator.ts typescript +#include_code execute_utility_function yarn-project/pxe/src/contract_function_simulator/contract_function_simulator.ts typescript This: diff --git a/docs/versioned_docs/version-Latest/aztec/smart_contracts/functions/attributes.md b/docs/versioned_docs/version-Latest/aztec/smart_contracts/functions/attributes.md index 8a185648b64a..31615c55a8b9 100644 --- a/docs/versioned_docs/version-Latest/aztec/smart_contracts/functions/attributes.md +++ b/docs/versioned_docs/version-Latest/aztec/smart_contracts/functions/attributes.md @@ -190,7 +190,7 @@ public async runUtility(call: FunctionCall, authwits: AuthWitness[], scopes?: Az }); const initialWitness = toACVMWitness(0, call.args); - const acirExecutionResult = await this.simulationProvider + const acirExecutionResult = await this.simulator .executeUserCircuit(initialWitness, entryPointArtifact, new Oracle(oracle)) .catch((err: Error) => { err.message = resolveAssertionMessageFromError(err, entryPointArtifact); diff --git a/yarn-project/bb-prover/src/prover/client/bb_private_kernel_prover.ts b/yarn-project/bb-prover/src/prover/client/bb_private_kernel_prover.ts index a3bac34aeab6..4cd07be2b180 100644 --- a/yarn-project/bb-prover/src/prover/client/bb_private_kernel_prover.ts +++ b/yarn-project/bb-prover/src/prover/client/bb_private_kernel_prover.ts @@ -16,7 +16,7 @@ import { } from '@aztec/noir-protocol-circuits-types/client'; import type { ArtifactProvider, ClientProtocolArtifact } from '@aztec/noir-protocol-circuits-types/types'; import type { Abi, WitnessMap } from '@aztec/noir-types'; -import type { SimulationProvider } from '@aztec/simulator/client'; +import type { CircuitSimulator } from '@aztec/simulator/client'; import type { PrivateKernelProver } from '@aztec/stdlib/interfaces/client'; import type { PrivateExecutionStep, @@ -37,7 +37,7 @@ import { mapProtocolArtifactNameToCircuitName } from '../../stats.js'; export abstract class BBPrivateKernelProver implements PrivateKernelProver { constructor( protected artifactProvider: ArtifactProvider, - protected simulationProvider: SimulationProvider, + protected simulator: CircuitSimulator, protected log = createLogger('bb-prover'), ) {} @@ -164,7 +164,7 @@ export abstract class BBPrivateKernelProver implements PrivateKernelProver { const witnessMap = convertInputs(inputs, compiledCircuit.abi); - const outputWitness = await this.simulationProvider + const outputWitness = await this.simulator .executeProtocolCircuit(witnessMap, compiledCircuit, foreignCallHandler) .catch((err: Error) => { this.log.debug(`Failed to simulate ${circuitType}`, { @@ -200,11 +200,7 @@ export abstract class BBPrivateKernelProver implements PrivateKernelProver { await this.artifactProvider.getClientCircuitArtifactByName(circuitType); const witnessMap = convertInputs(inputs, compiledCircuit.abi); - const outputWitness = await this.simulationProvider.executeProtocolCircuit( - witnessMap, - compiledCircuit, - foreignCallHandler, - ); + const outputWitness = await this.simulator.executeProtocolCircuit(witnessMap, compiledCircuit, foreignCallHandler); const output = convertOutputs(outputWitness.witness, compiledCircuit.abi); this.log.debug(`Generated witness for ${circuitType}`, { diff --git a/yarn-project/bb-prover/src/prover/client/native/bb_native_private_kernel_prover.ts b/yarn-project/bb-prover/src/prover/client/native/bb_native_private_kernel_prover.ts index 980871ed8426..d2e7b2551399 100644 --- a/yarn-project/bb-prover/src/prover/client/native/bb_native_private_kernel_prover.ts +++ b/yarn-project/bb-prover/src/prover/client/native/bb_native_private_kernel_prover.ts @@ -1,7 +1,7 @@ import { runInDirectory } from '@aztec/foundation/fs'; import { type Logger, createLogger } from '@aztec/foundation/log'; import { BundleArtifactProvider } from '@aztec/noir-protocol-circuits-types/client/bundle'; -import type { SimulationProvider } from '@aztec/simulator/server'; +import type { CircuitSimulator } from '@aztec/simulator/server'; import { type PrivateExecutionStep, serializePrivateExecutionSteps } from '@aztec/stdlib/kernel'; import type { ClientIvcProof } from '@aztec/stdlib/proofs'; @@ -21,19 +21,19 @@ export class BBNativePrivateKernelProver extends BBPrivateKernelProver { private bbBinaryPath: string, private bbWorkingDirectory: string, private skipCleanup: boolean, - protected override simulationProvider: SimulationProvider, + protected override simulator: CircuitSimulator, protected override log = createLogger('bb-prover:native'), ) { - super(new BundleArtifactProvider(), simulationProvider, log); + super(new BundleArtifactProvider(), simulator, log); } - public static async new(config: BBConfig, simulationProvider: SimulationProvider, log?: Logger) { + public static async new(config: BBConfig, simulator: CircuitSimulator, log?: Logger) { await fs.mkdir(config.bbWorkingDirectory, { recursive: true }); return new BBNativePrivateKernelProver( config.bbBinaryPath, config.bbWorkingDirectory, !!config.bbSkipCleanup, - simulationProvider, + simulator, log, ); } diff --git a/yarn-project/bb-prover/src/prover/client/wasm/bb_wasm_private_kernel_prover.ts b/yarn-project/bb-prover/src/prover/client/wasm/bb_wasm_private_kernel_prover.ts index 3486e14a8c71..d424e0b04767 100644 --- a/yarn-project/bb-prover/src/prover/client/wasm/bb_wasm_private_kernel_prover.ts +++ b/yarn-project/bb-prover/src/prover/client/wasm/bb_wasm_private_kernel_prover.ts @@ -3,7 +3,7 @@ import { createLogger } from '@aztec/foundation/log'; import { Timer } from '@aztec/foundation/timer'; import { serializeWitness } from '@aztec/noir-noirc_abi'; import type { ArtifactProvider } from '@aztec/noir-protocol-circuits-types/types'; -import type { SimulationProvider } from '@aztec/simulator/client'; +import type { CircuitSimulator } from '@aztec/simulator/client'; import type { PrivateExecutionStep } from '@aztec/stdlib/kernel'; import { ClientIvcProof } from '@aztec/stdlib/proofs'; @@ -14,11 +14,11 @@ import { BBPrivateKernelProver } from '../bb_private_kernel_prover.js'; export abstract class BBWASMPrivateKernelProver extends BBPrivateKernelProver { constructor( protected override artifactProvider: ArtifactProvider, - protected override simulationProvider: SimulationProvider, + protected override simulator: CircuitSimulator, private threads: number = 1, protected override log = createLogger('bb-prover:wasm'), ) { - super(artifactProvider, simulationProvider, log); + super(artifactProvider, simulator, log); } public override async createClientIvcProof(executionSteps: PrivateExecutionStep[]): Promise { diff --git a/yarn-project/bb-prover/src/prover/client/wasm/bundle.ts b/yarn-project/bb-prover/src/prover/client/wasm/bundle.ts index 92cb4e7a67a3..b61b40e66c5d 100644 --- a/yarn-project/bb-prover/src/prover/client/wasm/bundle.ts +++ b/yarn-project/bb-prover/src/prover/client/wasm/bundle.ts @@ -1,11 +1,11 @@ import { createLogger } from '@aztec/foundation/log'; import { BundleArtifactProvider } from '@aztec/noir-protocol-circuits-types/client/bundle'; -import type { SimulationProvider } from '@aztec/simulator/client'; +import type { CircuitSimulator } from '@aztec/simulator/client'; import { BBWASMPrivateKernelProver } from './bb_wasm_private_kernel_prover.js'; export class BBWASMBundlePrivateKernelProver extends BBWASMPrivateKernelProver { - constructor(simulationProvider: SimulationProvider, threads = 16, log = createLogger('bb-prover:wasm:bundle')) { - super(new BundleArtifactProvider(), simulationProvider, threads, log); + constructor(simulator: CircuitSimulator, threads = 16, log = createLogger('bb-prover:wasm:bundle')) { + super(new BundleArtifactProvider(), simulator, threads, log); } } diff --git a/yarn-project/bb-prover/src/prover/client/wasm/lazy.ts b/yarn-project/bb-prover/src/prover/client/wasm/lazy.ts index 5564c4aedc46..0be0a2b2d83f 100644 --- a/yarn-project/bb-prover/src/prover/client/wasm/lazy.ts +++ b/yarn-project/bb-prover/src/prover/client/wasm/lazy.ts @@ -1,11 +1,11 @@ import { createLogger } from '@aztec/foundation/log'; import { LazyArtifactProvider } from '@aztec/noir-protocol-circuits-types/client/lazy'; -import type { SimulationProvider } from '@aztec/simulator/client'; +import type { CircuitSimulator } from '@aztec/simulator/client'; import { BBWASMPrivateKernelProver } from './bb_wasm_private_kernel_prover.js'; export class BBWASMLazyPrivateKernelProver extends BBWASMPrivateKernelProver { - constructor(simulationProvider: SimulationProvider, threads = 16, log = createLogger('bb-prover:wasm:lazy')) { - super(new LazyArtifactProvider(), simulationProvider, threads, log); + constructor(simulator: CircuitSimulator, threads = 16, log = createLogger('bb-prover:wasm:lazy')) { + super(new LazyArtifactProvider(), simulator, threads, log); } } diff --git a/yarn-project/bb-prover/src/test/test_circuit_prover.ts b/yarn-project/bb-prover/src/test/test_circuit_prover.ts index f4abab9326d4..e9718827d081 100644 --- a/yarn-project/bb-prover/src/test/test_circuit_prover.ts +++ b/yarn-project/bb-prover/src/test/test_circuit_prover.ts @@ -36,7 +36,7 @@ import { } from '@aztec/noir-protocol-circuits-types/server'; import { ProtocolCircuitVks } from '@aztec/noir-protocol-circuits-types/server/vks'; import type { WitnessMap } from '@aztec/noir-types'; -import { type SimulationProvider, WASMSimulatorWithBlobs, emitCircuitSimulationStats } from '@aztec/simulator/server'; +import { type CircuitSimulator, WASMSimulatorWithBlobs, emitCircuitSimulationStats } from '@aztec/simulator/server'; import type { AvmCircuitInputs } from '@aztec/stdlib/avm'; import { type ProofAndVerificationKey, @@ -88,7 +88,7 @@ export class TestCircuitProver implements ServerCircuitProver { private logger = createLogger('bb-prover:test-prover'); constructor( - private simulationProvider?: SimulationProvider, + private simulator?: CircuitSimulator, private opts: TestDelay = { proverTestDelayType: 'fixed', proverTestDelayMs: 0 }, telemetry: TelemetryClient = getTelemetryClient(), ) { @@ -353,7 +353,7 @@ export class TestCircuitProver implements ServerCircuitProver { let witness: WitnessMap; if ( ['BlockRootRollupArtifact', 'SingleTxBlockRootRollupArtifact'].includes(artifactName) || - this.simulationProvider == undefined + this.simulator == undefined ) { // TODO(#10323): Native ACVM simulator does not support foreign call handler so we use the wasm simulator // when simulating block root rollup and single tx block root rollup circuits or when the native ACVM simulator @@ -367,7 +367,7 @@ export class TestCircuitProver implements ServerCircuitProver { ).witness; } else { witness = ( - await this.simulationProvider.executeProtocolCircuit( + await this.simulator.executeProtocolCircuit( witnessMap, getSimulatedServerCircuitArtifact(artifactName), undefined, // Native ACM simulator does not support foreign call handler diff --git a/yarn-project/end-to-end/src/bench/client_flows/data_extractor.ts b/yarn-project/end-to-end/src/bench/client_flows/data_extractor.ts index e674b121e7fe..4b7b58287317 100644 --- a/yarn-project/end-to-end/src/bench/client_flows/data_extractor.ts +++ b/yarn-project/end-to-end/src/bench/client_flows/data_extractor.ts @@ -16,13 +16,13 @@ import { type Log, type ProverType, ProxyLogger, generateBenchmark } from './ben type NativeProverConfig = { bbBinaryPath?: string; bbWorkingDirectory?: string }; async function createProver(config: NativeProverConfig = {}, log: Logger) { - const simulationProvider = new WASMSimulator(); + const simulator = new WASMSimulator(); if (!config.bbBinaryPath || !config.bbWorkingDirectory) { - return { prover: new BBWASMBundlePrivateKernelProver(simulationProvider, 16, log), type: 'wasm' as ProverType }; + return { prover: new BBWASMBundlePrivateKernelProver(simulator, 16, log), type: 'wasm' as ProverType }; } else { const bbConfig = config as Required; return { - prover: await BBNativePrivateKernelProver.new({ bbSkipCleanup: false, ...bbConfig }, simulationProvider, log), + prover: await BBNativePrivateKernelProver.new({ bbSkipCleanup: false, ...bbConfig }, simulator, log), type: 'native' as ProverType, }; } diff --git a/yarn-project/end-to-end/src/fixtures/utils.ts b/yarn-project/end-to-end/src/fixtures/utils.ts index 193dee47609d..d61f7148ca10 100644 --- a/yarn-project/end-to-end/src/fixtures/utils.ts +++ b/yarn-project/end-to-end/src/fixtures/utils.ts @@ -55,12 +55,12 @@ import { type ProverNode, type ProverNodeConfig, createProverNode } from '@aztec import { type PXEService, type PXEServiceConfig, - createPXEServiceWithSimulationProvider, + createPXEServiceWithSimulator, getPXEServiceConfig, } from '@aztec/pxe/server'; import type { SequencerClient } from '@aztec/sequencer-client'; import type { TestSequencerClient } from '@aztec/sequencer-client/test'; -import { MemoryCircuitRecorder, SimulationProviderRecorderWrapper, WASMSimulator } from '@aztec/simulator/client'; +import { MemoryCircuitRecorder, SimulatorRecorderWrapper, WASMSimulator } from '@aztec/simulator/client'; import { FileCircuitRecorder } from '@aztec/simulator/testing'; import { getContractClassFromArtifact, getContractInstanceFromDeployParams } from '@aztec/stdlib/contract'; import type { AztecNodeAdmin } from '@aztec/stdlib/interfaces/client'; @@ -171,17 +171,14 @@ export async function setupPXEService( pxeServiceConfig.dataDirectory = path.join(tmpdir(), randomBytes(8).toString('hex')); } - const simulationProvider = new WASMSimulator(); + const simulator = new WASMSimulator(); const recorder = process.env.CIRCUIT_RECORD_DIR ? new FileCircuitRecorder(process.env.CIRCUIT_RECORD_DIR) : new MemoryCircuitRecorder(); - const simulationProviderWithRecorder = new SimulationProviderRecorderWrapper(simulationProvider, recorder); - const pxe = await createPXEServiceWithSimulationProvider( - aztecNode, - simulationProviderWithRecorder, - pxeServiceConfig, - { useLogSuffix }, - ); + const simulatorWithRecorder = new SimulatorRecorderWrapper(simulator, recorder); + const pxe = await createPXEServiceWithSimulator(aztecNode, simulatorWithRecorder, pxeServiceConfig, { + useLogSuffix, + }); const teardown = async () => { if (!configuredDataDirectory) { diff --git a/yarn-project/prover-client/src/mocks/fixtures.ts b/yarn-project/prover-client/src/mocks/fixtures.ts index 3fe106a73ddc..c75b711138ac 100644 --- a/yarn-project/prover-client/src/mocks/fixtures.ts +++ b/yarn-project/prover-client/src/mocks/fixtures.ts @@ -5,7 +5,7 @@ import { EthAddress } from '@aztec/foundation/eth-address'; import { Fr } from '@aztec/foundation/fields'; import type { Logger } from '@aztec/foundation/log'; import { fileURLToPath } from '@aztec/foundation/url'; -import { NativeACVMSimulator, type SimulationProvider, WASMSimulatorWithBlobs } from '@aztec/simulator/server'; +import { type CircuitSimulator, NativeACVMSimulator, WASMSimulatorWithBlobs } from '@aztec/simulator/server'; import { AztecAddress } from '@aztec/stdlib/aztec-address'; import { GasFees } from '@aztec/stdlib/gas'; import type { MerkleTreeWriteOperations } from '@aztec/stdlib/interfaces/server'; @@ -64,10 +64,10 @@ export const getEnvironmentConfig = async (logger: Logger) => { } }; -export async function getSimulationProvider( +export async function getSimulator( config: { acvmWorkingDirectory: string | undefined; acvmBinaryPath: string | undefined }, logger?: Logger, -): Promise { +): Promise { if (config.acvmBinaryPath && config.acvmWorkingDirectory) { try { await fs.access(config.acvmBinaryPath, fs.constants.R_OK); diff --git a/yarn-project/prover-client/src/mocks/test_context.ts b/yarn-project/prover-client/src/mocks/test_context.ts index 592609b19351..3e16d816cad0 100644 --- a/yarn-project/prover-client/src/mocks/test_context.ts +++ b/yarn-project/prover-client/src/mocks/test_context.ts @@ -27,7 +27,7 @@ import { buildBlockWithCleanDB } from '../block_builder/light.js'; import { ProvingOrchestrator } from '../orchestrator/index.js'; import { BrokerCircuitProverFacade } from '../proving_broker/broker_prover_facade.js'; import { TestBroker } from '../test/mock_prover.js'; -import { getEnvironmentConfig, getSimulationProvider, makeGlobals, updateExpectedTreesFromTxs } from './fixtures.js'; +import { getEnvironmentConfig, getSimulator, makeGlobals, updateExpectedTreesFromTxs } from './fixtures.js'; export class TestContext { private headers: Map = new Map(); @@ -59,7 +59,7 @@ export class TestContext { logger: Logger, proverCount = 4, createProver: (bbConfig: BBProverConfig) => Promise = async (bbConfig: BBProverConfig) => - new TestCircuitProver(await getSimulationProvider(bbConfig, logger)), + new TestCircuitProver(await getSimulator(bbConfig, logger)), blockNumber = 1, ) { const directoriesToCleanup: string[] = []; diff --git a/yarn-project/prover-client/src/prover-client/prover-client.ts b/yarn-project/prover-client/src/prover-client/prover-client.ts index 5982d5edee67..13369febd509 100644 --- a/yarn-project/prover-client/src/prover-client/prover-client.ts +++ b/yarn-project/prover-client/src/prover-client/prover-client.ts @@ -154,9 +154,9 @@ export function buildServerCircuitProver( return BBNativeRollupProver.new(config, telemetry); } - const simulationProvider = config.acvmBinaryPath + const simulator = config.acvmBinaryPath ? new NativeACVMSimulator(config.acvmWorkingDirectory, config.acvmBinaryPath) : undefined; - return Promise.resolve(new TestCircuitProver(simulationProvider, config, telemetry)); + return Promise.resolve(new TestCircuitProver(simulator, config, telemetry)); } diff --git a/yarn-project/pxe/package.json b/yarn-project/pxe/package.json index 734c39bf5d21..55d338654e91 100644 --- a/yarn-project/pxe/package.json +++ b/yarn-project/pxe/package.json @@ -6,6 +6,7 @@ "./server": "./dest/entrypoints/server/index.js", "./client/lazy": "./dest/entrypoints/client/lazy/index.js", "./client/bundle": "./dest/entrypoints/client/bundle/index.js", + "./simulator": "./dest/contract_function_simulator/index.js", "./config": "./dest/config/index.js", "./testing": "./dest/test/pxe_test_suite.js" }, @@ -78,6 +79,7 @@ "viem": "2.23.7" }, "devDependencies": { + "@aztec/merkle-tree": "workspace:^", "@aztec/noir-test-contracts.js": "workspace:^", "@jest/globals": "^29.5.0", "@types/jest": "^29.5.0", diff --git a/yarn-project/simulator/src/private/simulator.ts b/yarn-project/pxe/src/contract_function_simulator/contract_function_simulator.ts similarity index 90% rename from yarn-project/simulator/src/private/simulator.ts rename to yarn-project/pxe/src/contract_function_simulator/contract_function_simulator.ts index 7149926ec932..2942cb22cd63 100644 --- a/yarn-project/simulator/src/private/simulator.ts +++ b/yarn-project/pxe/src/contract_function_simulator/contract_function_simulator.ts @@ -1,30 +1,37 @@ import { Fr } from '@aztec/foundation/fields'; import { type Logger, createLogger } from '@aztec/foundation/log'; +import { + type CircuitSimulator, + ExecutionError, + createSimulationError, + extractCallStack, + resolveAssertionMessageFromError, + toACVMWitness, + witnessMapToFields, +} from '@aztec/simulator/client'; import type { AbiDecoded, FunctionCall } from '@aztec/stdlib/abi'; import { FunctionSelector, FunctionType, decodeFromAbi } from '@aztec/stdlib/abi'; import type { AuthWitness } from '@aztec/stdlib/auth-witness'; import { AztecAddress } from '@aztec/stdlib/aztec-address'; import { CallContext, HashedValues, PrivateExecutionResult, TxExecutionRequest, collectNested } from '@aztec/stdlib/tx'; -import { ExecutionError, createSimulationError, resolveAssertionMessageFromError } from '../common/errors.js'; -import { Oracle, extractCallStack, toACVMWitness, witnessMapToFields } from './acvm/index.js'; import type { ExecutionDataProvider } from './execution_data_provider.js'; import { ExecutionNoteCache } from './execution_note_cache.js'; import { HashedValuesCache } from './hashed_values_cache.js'; -import { executePrivateFunction, verifyCurrentClassId } from './private_execution.js'; -import { PrivateExecutionOracle } from './private_execution_oracle.js'; -import type { SimulationProvider } from './providers/simulation_provider.js'; -import { UtilityExecutionOracle } from './utility_execution_oracle.js'; +import { Oracle } from './oracle/oracle.js'; +import { executePrivateFunction, verifyCurrentClassId } from './oracle/private_execution.js'; +import { PrivateExecutionOracle } from './oracle/private_execution_oracle.js'; +import { UtilityExecutionOracle } from './oracle/utility_execution_oracle.js'; /** - * The ACIR simulator. + * The contract function simulator. */ -export class AcirSimulator { +export class ContractFunctionSimulator { private log: Logger; constructor( private executionDataProvider: ExecutionDataProvider, - private simulationProvider: SimulationProvider, + private simulator: CircuitSimulator, ) { this.log = createLogger('simulator'); } @@ -83,7 +90,7 @@ export class AcirSimulator { HashedValuesCache.create(request.argsOfCalls), noteCache, this.executionDataProvider, - this.simulationProvider, + this.simulator, /*totalPublicArgsCount=*/ 0, startSideEffectCounter, undefined, @@ -92,7 +99,7 @@ export class AcirSimulator { try { const executionResult = await executePrivateFunction( - this.simulationProvider, + this.simulator, context, entryPointArtifact, contractAddress, @@ -144,8 +151,8 @@ export class AcirSimulator { }); const initialWitness = toACVMWitness(0, call.args); - const acirExecutionResult = await this.simulationProvider - .executeUserCircuit(initialWitness, entryPointArtifact, new Oracle(oracle)) + const acirExecutionResult = await this.simulator + .executeUserCircuit(initialWitness, entryPointArtifact, new Oracle(oracle).toACIRCallback()) .catch((err: Error) => { err.message = resolveAssertionMessageFromError(err, entryPointArtifact); throw new ExecutionError( diff --git a/yarn-project/simulator/src/private/execution_data_provider.ts b/yarn-project/pxe/src/contract_function_simulator/execution_data_provider.ts similarity index 95% rename from yarn-project/simulator/src/private/execution_data_provider.ts rename to yarn-project/pxe/src/contract_function_simulator/execution_data_provider.ts index ab8213512c20..e84e8e28ee5e 100644 --- a/yarn-project/simulator/src/private/execution_data_provider.ts +++ b/yarn-project/pxe/src/contract_function_simulator/execution_data_provider.ts @@ -15,8 +15,8 @@ import type { NoteStatus } from '@aztec/stdlib/note'; import { type MerkleTreeId, type NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees'; import type { BlockHeader, TxHash } from '@aztec/stdlib/tx'; -import type { NoteData } from './acvm/index.js'; -import type { MessageLoadOracleInputs } from './message_load_oracle_inputs.js'; +import type { MessageLoadOracleInputs } from './oracle/message_load_oracle_inputs.js'; +import type { NoteData } from './oracle/typed_oracle.js'; /** * Error thrown when a contract is not found in the database. @@ -146,12 +146,6 @@ export interface ExecutionDataProvider { secret: Fr, ): Promise>; - /** - * @param leafIndex the leaf to look up - * @returns The l1 to l2 leaf message hash or undefined if not found. - */ - getL1ToL2MessageHash(leafIndex: bigint): Promise; - /** * Retrieve the databases view of the Block Header object. * This structure is fed into the circuits simulator and is used to prove against certain historical roots. @@ -290,15 +284,8 @@ export interface ExecutionDataProvider { validateEnqueuedNotes(contractAddress: AztecAddress, notePendingValidationArrayBaseSlot: Fr): Promise; /** - * Gets note hash in the note hash tree at the given leaf index. - * @param leafIndex - the leaf to look up. - * @returns - The note hash at that index. Undefined if leaf index is not found. - */ - getNoteHash(leafIndex: bigint): Promise; - - /** - * Searches for a public log with the corresponding `tag` and returns it along with contextual transaction - * information. + * Searches for a log with the corresponding `tag` and returns it along with contextual transaction information. + * Returns null if no such log exists, and throws if more than one exists. * * @param tag - The log tag to search for. * @param contractAddress - The contract address to search for the log in. diff --git a/yarn-project/simulator/src/private/execution_note_cache.ts b/yarn-project/pxe/src/contract_function_simulator/execution_note_cache.ts similarity index 99% rename from yarn-project/simulator/src/private/execution_note_cache.ts rename to yarn-project/pxe/src/contract_function_simulator/execution_note_cache.ts index 0152a2057e26..e53c25069d37 100644 --- a/yarn-project/simulator/src/private/execution_note_cache.ts +++ b/yarn-project/pxe/src/contract_function_simulator/execution_note_cache.ts @@ -2,7 +2,7 @@ import { Fr } from '@aztec/foundation/fields'; import type { AztecAddress } from '@aztec/stdlib/aztec-address'; import { computeNoteHashNonce, computeUniqueNoteHash, siloNoteHash, siloNullifier } from '@aztec/stdlib/hash'; -import type { NoteData } from './acvm/index.js'; +import type { NoteData } from './oracle/typed_oracle.js'; interface PendingNote { note: NoteData; diff --git a/yarn-project/simulator/src/private/hashed_values_cache.ts b/yarn-project/pxe/src/contract_function_simulator/hashed_values_cache.ts similarity index 100% rename from yarn-project/simulator/src/private/hashed_values_cache.ts rename to yarn-project/pxe/src/contract_function_simulator/hashed_values_cache.ts diff --git a/yarn-project/pxe/src/contract_function_simulator/index.ts b/yarn-project/pxe/src/contract_function_simulator/index.ts new file mode 100644 index 000000000000..7f575ebb97b0 --- /dev/null +++ b/yarn-project/pxe/src/contract_function_simulator/index.ts @@ -0,0 +1,9 @@ +export { ExecutionNoteCache } from './execution_note_cache.js'; +export { HashedValuesCache } from './hashed_values_cache.js'; +export { pickNotes } from './pick_notes.js'; +export type { NoteData, TypedOracle } from './oracle/typed_oracle.js'; +export { MessageLoadOracleInputs } from './oracle/message_load_oracle_inputs.js'; +export { UtilityExecutionOracle } from './oracle/utility_execution_oracle.js'; +export { PrivateExecutionOracle } from './oracle/private_execution_oracle.js'; +export { Oracle } from './oracle/oracle.js'; +export { executePrivateFunction, extractPrivateCircuitPublicInputs } from './oracle/private_execution.js'; diff --git a/yarn-project/simulator/src/private/acvm/oracle/index.ts b/yarn-project/pxe/src/contract_function_simulator/oracle/index.ts similarity index 100% rename from yarn-project/simulator/src/private/acvm/oracle/index.ts rename to yarn-project/pxe/src/contract_function_simulator/oracle/index.ts diff --git a/yarn-project/simulator/src/private/message_load_oracle_inputs.ts b/yarn-project/pxe/src/contract_function_simulator/oracle/message_load_oracle_inputs.ts similarity index 100% rename from yarn-project/simulator/src/private/message_load_oracle_inputs.ts rename to yarn-project/pxe/src/contract_function_simulator/oracle/message_load_oracle_inputs.ts diff --git a/yarn-project/simulator/src/private/acvm/oracle/oracle.ts b/yarn-project/pxe/src/contract_function_simulator/oracle/oracle.ts similarity index 96% rename from yarn-project/simulator/src/private/acvm/oracle/oracle.ts rename to yarn-project/pxe/src/contract_function_simulator/oracle/oracle.ts index a66635805852..26b9de2c47cc 100644 --- a/yarn-project/simulator/src/private/acvm/oracle/oracle.ts +++ b/yarn-project/pxe/src/contract_function_simulator/oracle/oracle.ts @@ -1,25 +1,43 @@ import { Fr, Point } from '@aztec/foundation/fields'; +import { + type ACIRCallback, + type ACVMField, + arrayOfArraysToBoundedVecOfArrays, + bufferToBoundedVec, + fromBoundedVec, + fromUintArray, + fromUintBoundedVec, + toACVMField, + toACVMFieldSingleOrArray, +} from '@aztec/simulator/client'; import { EventSelector, FunctionSelector, NoteSelector } from '@aztec/stdlib/abi'; import { AztecAddress } from '@aztec/stdlib/aztec-address'; import { ContractClassLog, ContractClassLogFields, PublicLogWithTxData } from '@aztec/stdlib/logs'; import { MerkleTreeId } from '@aztec/stdlib/trees'; import { TxHash } from '@aztec/stdlib/tx'; -import type { ACVMField } from '../acvm_types.js'; -import { fromBoundedVec, fromUintArray, fromUintBoundedVec } from '../deserialize.js'; -import { - arrayOfArraysToBoundedVecOfArrays, - bufferToBoundedVec, - toACVMField, - toACVMFieldSingleOrArray, -} from '../serialize.js'; import type { TypedOracle } from './typed_oracle.js'; /** * A data source that has all the apis required by Aztec.nr. */ export class Oracle { - constructor(private typedOracle: TypedOracle) {} + private typedOracle: TypedOracle; + + constructor(typedOracle: TypedOracle) { + this.typedOracle = typedOracle; + } + + toACIRCallback(): ACIRCallback { + return Object.getOwnPropertyNames(Oracle.prototype) + .filter( + name => name !== 'constructor' && name != 'toACIRCallback' && typeof this[name as keyof Oracle] === 'function', + ) + .reduce((acc, name) => { + acc[name] = this[name as keyof Omit].bind(this); + return acc; + }, {} as ACIRCallback); + } getRandomField(): Promise { const val = this.typedOracle.getRandomField(); diff --git a/yarn-project/simulator/src/private/private_execution.test.ts b/yarn-project/pxe/src/contract_function_simulator/oracle/private_execution.test.ts similarity index 96% rename from yarn-project/simulator/src/private/private_execution.test.ts rename to yarn-project/pxe/src/contract_function_simulator/oracle/private_execution.test.ts index 9398911af6c8..3946a68a3b8a 100644 --- a/yarn-project/simulator/src/private/private_execution.test.ts +++ b/yarn-project/pxe/src/contract_function_simulator/oracle/private_execution.test.ts @@ -6,7 +6,7 @@ import { } from '@aztec/constants'; import { asyncMap } from '@aztec/foundation/async-map'; import { times } from '@aztec/foundation/collection'; -import { poseidon2Hash, poseidon2HashWithSeparator, randomInt } from '@aztec/foundation/crypto'; +import { poseidon2Hash, poseidon2HashWithSeparator, randomInt, sha256ToField } from '@aztec/foundation/crypto'; import { EthAddress } from '@aztec/foundation/eth-address'; import { Fr, GrumpkinScalar } from '@aztec/foundation/fields'; import { type Logger, createLogger } from '@aztec/foundation/log'; @@ -19,6 +19,7 @@ import { ParentContractArtifact } from '@aztec/noir-test-contracts.js/Parent'; import { PendingNoteHashesContractArtifact } from '@aztec/noir-test-contracts.js/PendingNoteHashes'; import { StatefulTestContractArtifact } from '@aztec/noir-test-contracts.js/StatefulTest'; import { TestContractArtifact } from '@aztec/noir-test-contracts.js/Test'; +import { WASMSimulator } from '@aztec/simulator/client'; import { type ContractArtifact, type FunctionArtifact, @@ -39,6 +40,7 @@ import { import { GasFees, GasSettings } from '@aztec/stdlib/gas'; import { computeNoteHashNonce, + computeSecretHash, computeUniqueNoteHash, computeVarArgsHash, deriveStorageSlotInMap, @@ -47,7 +49,7 @@ import { import { KeyValidationRequest, getNonEmptyItems } from '@aztec/stdlib/kernel'; import { computeAppNullifierSecretKey, deriveKeys } from '@aztec/stdlib/keys'; import { IndexedTaggingSecret } from '@aztec/stdlib/logs'; -import type { L1ToL2Message } from '@aztec/stdlib/messaging'; +import { L1Actor, L1ToL2Message, L2Actor } from '@aztec/stdlib/messaging'; import { Note } from '@aztec/stdlib/note'; import { makeHeader } from '@aztec/stdlib/testing'; import { AppendOnlyTreeSnapshot } from '@aztec/stdlib/trees'; @@ -64,19 +66,48 @@ import { jest } from '@jest/globals'; import { Matcher, type MatcherCreator, type MockProxy, mock } from 'jest-mock-extended'; import { toFunctionSelector } from 'viem'; -import { buildL1ToL2Message } from '../test/utils.js'; -import type { ExecutionDataProvider } from './execution_data_provider.js'; +import { ContractFunctionSimulator } from '../contract_function_simulator.js'; +import type { ExecutionDataProvider } from '../execution_data_provider.js'; import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js'; -import { WASMSimulator } from './providers/acvm_wasm.js'; -import { AcirSimulator } from './simulator.js'; jest.setTimeout(60_000); +/** + * Test utility function to craft an L1 to L2 message. + * @param selector - The cross chain message selector. + * @param contentPreimage - The args after the selector. + * @param targetContract - The contract to consume the message. + * @param secret - The secret to unlock the message. + * @param msgIndex - The index of the message in the L1 to L2 message tree. + * @returns The L1 to L2 message. + */ +export const buildL1ToL2Message = async ( + selector: string, + contentPreimage: Fr[], + targetContract: AztecAddress, + secret: Fr, + msgIndex: Fr | number, +) => { + // Write the selector into a buffer. + const selectorBuf = Buffer.from(selector, 'hex'); + + const content = sha256ToField([selectorBuf, ...contentPreimage]); + const secretHash = await computeSecretHash(secret); + + return new L1ToL2Message( + new L1Actor(EthAddress.random(), 1), + new L2Actor(targetContract, 1), + content, + secretHash, + new Fr(msgIndex), + ); +}; + describe('Private Execution test suite', () => { - const simulationProvider = new WASMSimulator(); + const simulator = new WASMSimulator(); let executionDataProvider: MockProxy; - let acirSimulator: AcirSimulator; + let acirSimulator: ContractFunctionSimulator; let header = BlockHeader.empty(); let logger: Logger; @@ -308,7 +339,7 @@ describe('Private Execution test suite', () => { }, ); - acirSimulator = new AcirSimulator(executionDataProvider, simulationProvider); + acirSimulator = new ContractFunctionSimulator(executionDataProvider, simulator); }); describe('no constructor', () => { diff --git a/yarn-project/simulator/src/private/private_execution.ts b/yarn-project/pxe/src/contract_function_simulator/oracle/private_execution.ts similarity index 93% rename from yarn-project/simulator/src/private/private_execution.ts rename to yarn-project/pxe/src/contract_function_simulator/oracle/private_execution.ts index 2d17e7b77851..d45de3a26564 100644 --- a/yarn-project/simulator/src/private/private_execution.ts +++ b/yarn-project/pxe/src/contract_function_simulator/oracle/private_execution.ts @@ -3,6 +3,14 @@ import { Fr } from '@aztec/foundation/fields'; import { createLogger } from '@aztec/foundation/log'; import { Timer } from '@aztec/foundation/timer'; import { ProtocolContractAddress } from '@aztec/protocol-contracts'; +import { + type ACVMWitness, + type CircuitSimulator, + ExecutionError, + extractCallStack, + resolveAssertionMessageFromError, + witnessMapToFields, +} from '@aztec/simulator/client'; import { type FunctionArtifact, type FunctionArtifactWithContractName, @@ -17,18 +25,15 @@ import { SharedMutableValues, SharedMutableValuesWithHash } from '@aztec/stdlib/ import type { CircuitWitnessGenerationStats } from '@aztec/stdlib/stats'; import { PrivateCallExecutionResult } from '@aztec/stdlib/tx'; -import { ExecutionError, resolveAssertionMessageFromError } from '../common/errors.js'; -import { witnessMapToFields } from './acvm/deserialize.js'; -import { type ACVMWitness, Oracle, extractCallStack } from './acvm/index.js'; -import type { ExecutionDataProvider } from './execution_data_provider.js'; +import type { ExecutionDataProvider } from '../execution_data_provider.js'; +import { Oracle } from './oracle.js'; import type { PrivateExecutionOracle } from './private_execution_oracle.js'; -import type { SimulationProvider } from './providers/simulation_provider.js'; /** * Execute a private function and return the execution result. */ export async function executePrivateFunction( - simulator: SimulationProvider, + simulator: CircuitSimulator, privateExecutionOracle: PrivateExecutionOracle, artifact: FunctionArtifactWithContractName, contractAddress: AztecAddress, @@ -41,7 +46,7 @@ export async function executePrivateFunction( const acvmCallback = new Oracle(privateExecutionOracle); const timer = new Timer(); const acirExecutionResult = await simulator - .executeUserCircuit(initialWitness, artifact, acvmCallback) + .executeUserCircuit(initialWitness, artifact, acvmCallback.toACIRCallback()) .catch((err: Error) => { err.message = resolveAssertionMessageFromError(err, artifact); throw new ExecutionError( diff --git a/yarn-project/simulator/src/private/private_execution_oracle.ts b/yarn-project/pxe/src/contract_function_simulator/oracle/private_execution_oracle.ts similarity index 97% rename from yarn-project/simulator/src/private/private_execution_oracle.ts rename to yarn-project/pxe/src/contract_function_simulator/oracle/private_execution_oracle.ts index 51c6d7e850e5..c30832e2c01b 100644 --- a/yarn-project/simulator/src/private/private_execution_oracle.ts +++ b/yarn-project/pxe/src/contract_function_simulator/oracle/private_execution_oracle.ts @@ -1,6 +1,7 @@ import { MAX_FR_CALLDATA_TO_ALL_ENQUEUED_CALLS, PRIVATE_CONTEXT_INPUTS_LENGTH } from '@aztec/constants'; import { Fr } from '@aztec/foundation/fields'; import { createLogger } from '@aztec/foundation/log'; +import { type CircuitSimulator, toACVMWitness } from '@aztec/simulator/client'; import { type FunctionAbi, type FunctionArtifact, @@ -24,13 +25,12 @@ import { type TxContext, } from '@aztec/stdlib/tx'; -import { type NoteData, toACVMWitness } from './acvm/index.js'; -import type { ExecutionDataProvider } from './execution_data_provider.js'; -import type { ExecutionNoteCache } from './execution_note_cache.js'; -import type { HashedValuesCache } from './hashed_values_cache.js'; -import { pickNotes } from './pick_notes.js'; +import type { ExecutionDataProvider } from '../execution_data_provider.js'; +import type { ExecutionNoteCache } from '../execution_note_cache.js'; +import type { HashedValuesCache } from '../hashed_values_cache.js'; +import { pickNotes } from '../pick_notes.js'; import { executePrivateFunction, verifyCurrentClassId } from './private_execution.js'; -import type { SimulationProvider } from './providers/simulation_provider.js'; +import type { NoteData } from './typed_oracle.js'; import { UtilityExecutionOracle } from './utility_execution_oracle.js'; /** @@ -71,7 +71,7 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle { private readonly executionCache: HashedValuesCache, private readonly noteCache: ExecutionNoteCache, executionDataProvider: ExecutionDataProvider, - private provider: SimulationProvider, + private simulator: CircuitSimulator, private totalPublicCalldataCount: number, protected sideEffectCounter: number = 0, log = createLogger('simulator:client_execution_context'), @@ -394,7 +394,7 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle { this.executionCache, this.noteCache, this.executionDataProvider, - this.provider, + this.simulator, this.totalPublicCalldataCount, sideEffectCounter, this.log, @@ -402,7 +402,7 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle { ); const childExecutionResult = await executePrivateFunction( - this.provider, + this.simulator, context, targetArtifact, targetContractAddress, diff --git a/yarn-project/simulator/src/private/acvm/oracle/typed_oracle.ts b/yarn-project/pxe/src/contract_function_simulator/oracle/typed_oracle.ts similarity index 99% rename from yarn-project/simulator/src/private/acvm/oracle/typed_oracle.ts rename to yarn-project/pxe/src/contract_function_simulator/oracle/typed_oracle.ts index 7f273d932b4f..9a880b0fcc04 100644 --- a/yarn-project/simulator/src/private/acvm/oracle/typed_oracle.ts +++ b/yarn-project/pxe/src/contract_function_simulator/oracle/typed_oracle.ts @@ -9,7 +9,7 @@ import type { Note, NoteStatus } from '@aztec/stdlib/note'; import { type MerkleTreeId, type NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees'; import type { BlockHeader, TxHash } from '@aztec/stdlib/tx'; -import type { MessageLoadOracleInputs } from '../../message_load_oracle_inputs.js'; +import type { MessageLoadOracleInputs } from './message_load_oracle_inputs.js'; /** * Information about a note needed during execution. diff --git a/yarn-project/simulator/src/private/utility_execution.test.ts b/yarn-project/pxe/src/contract_function_simulator/oracle/utility_execution.test.ts similarity index 90% rename from yarn-project/simulator/src/private/utility_execution.test.ts rename to yarn-project/pxe/src/contract_function_simulator/oracle/utility_execution.test.ts index dc5b3a33a8a2..d432a6953bff 100644 --- a/yarn-project/simulator/src/private/utility_execution.test.ts +++ b/yarn-project/pxe/src/contract_function_simulator/oracle/utility_execution.test.ts @@ -1,5 +1,6 @@ import { Fr } from '@aztec/foundation/fields'; import { StatefulTestContractArtifact } from '@aztec/noir-test-contracts.js/StatefulTest'; +import { WASMSimulator } from '@aztec/simulator/client'; import { FunctionCall, FunctionSelector, FunctionType, encodeArguments } from '@aztec/stdlib/abi'; import { AztecAddress } from '@aztec/stdlib/aztec-address'; import { CompleteAddress, type ContractInstance } from '@aztec/stdlib/contract'; @@ -8,15 +9,14 @@ import { BlockHeader } from '@aztec/stdlib/tx'; import { mock } from 'jest-mock-extended'; -import type { ExecutionDataProvider } from './execution_data_provider.js'; -import { WASMSimulator } from './providers/acvm_wasm.js'; -import { AcirSimulator } from './simulator.js'; +import { ContractFunctionSimulator } from '../contract_function_simulator.js'; +import type { ExecutionDataProvider } from '../execution_data_provider.js'; describe('Utility Execution test suite', () => { - const simulationProvider = new WASMSimulator(); + const simulator = new WASMSimulator(); let executionDataProvider: ReturnType>; - let acirSimulator: AcirSimulator; + let acirSimulator: ContractFunctionSimulator; beforeEach(() => { executionDataProvider = mock(); @@ -25,7 +25,7 @@ describe('Utility Execution test suite', () => { executionDataProvider.getChainId.mockResolvedValue(1); executionDataProvider.getVersion.mockResolvedValue(1); - acirSimulator = new AcirSimulator(executionDataProvider, simulationProvider); + acirSimulator = new ContractFunctionSimulator(executionDataProvider, simulator); }); describe('private token contract', () => { diff --git a/yarn-project/simulator/src/private/utility_execution_oracle.ts b/yarn-project/pxe/src/contract_function_simulator/oracle/utility_execution_oracle.ts similarity index 98% rename from yarn-project/simulator/src/private/utility_execution_oracle.ts rename to yarn-project/pxe/src/contract_function_simulator/oracle/utility_execution_oracle.ts index b37a7b7dd003..dee95cd518cc 100644 --- a/yarn-project/simulator/src/private/utility_execution_oracle.ts +++ b/yarn-project/pxe/src/contract_function_simulator/oracle/utility_execution_oracle.ts @@ -12,9 +12,9 @@ import type { NoteStatus } from '@aztec/stdlib/note'; import { type MerkleTreeId, type NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees'; import type { BlockHeader, Capsule, TxHash } from '@aztec/stdlib/tx'; -import { type NoteData, TypedOracle } from './acvm/index.js'; -import type { ExecutionDataProvider } from './execution_data_provider.js'; -import { pickNotes } from './pick_notes.js'; +import type { ExecutionDataProvider } from '../execution_data_provider.js'; +import { pickNotes } from '../pick_notes.js'; +import { type NoteData, TypedOracle } from './typed_oracle.js'; /** * The oracle for an execution of utility contract functions. diff --git a/yarn-project/simulator/src/private/pick_notes.test.ts b/yarn-project/pxe/src/contract_function_simulator/pick_notes.test.ts similarity index 100% rename from yarn-project/simulator/src/private/pick_notes.test.ts rename to yarn-project/pxe/src/contract_function_simulator/pick_notes.test.ts diff --git a/yarn-project/simulator/src/private/pick_notes.ts b/yarn-project/pxe/src/contract_function_simulator/pick_notes.ts similarity index 100% rename from yarn-project/simulator/src/private/pick_notes.ts rename to yarn-project/pxe/src/contract_function_simulator/pick_notes.ts diff --git a/yarn-project/pxe/src/entrypoints/client/bundle/utils.ts b/yarn-project/pxe/src/entrypoints/client/bundle/utils.ts index dcd5565a4f96..e267a27889b8 100644 --- a/yarn-project/pxe/src/entrypoints/client/bundle/utils.ts +++ b/yarn-project/pxe/src/entrypoints/client/bundle/utils.ts @@ -45,12 +45,12 @@ export async function createPXEService( const store = options.store ?? (await createStore('pxe_data', configWithContracts, storeLogger)); - const simulationProvider = new WASMSimulator(); + const simulator = new WASMSimulator(); const proverLogger = loggers.prover ? loggers.prover : createLogger('pxe:bb:wasm:bundle' + (logSuffix ? `:${logSuffix}` : '')); - const prover = options.prover ?? new BBWASMBundlePrivateKernelProver(simulationProvider, 16, proverLogger); + const prover = options.prover ?? new BBWASMBundlePrivateKernelProver(simulator, 16, proverLogger); const protocolContractsProvider = new BundledProtocolContractsProvider(); const pxeLogger = loggers.pxe ? loggers.pxe : createLogger('pxe:service' + (logSuffix ? `:${logSuffix}` : '')); @@ -58,7 +58,7 @@ export async function createPXEService( aztecNode, store, prover, - simulationProvider, + simulator, protocolContractsProvider, config, pxeLogger, diff --git a/yarn-project/pxe/src/entrypoints/client/lazy/utils.ts b/yarn-project/pxe/src/entrypoints/client/lazy/utils.ts index 90412821ec74..3425bbba141b 100644 --- a/yarn-project/pxe/src/entrypoints/client/lazy/utils.ts +++ b/yarn-project/pxe/src/entrypoints/client/lazy/utils.ts @@ -44,12 +44,12 @@ export async function createPXEService( const store = options.store ?? (await createStore('pxe_data', configWithContracts, storeLogger)); - const simulationProvider = new WASMSimulator(); + const simulator = new WASMSimulator(); const proverLogger = loggers.prover ? loggers.prover : createLogger('pxe:bb:wasm:bundle' + (logSuffix ? `:${logSuffix}` : '')); - const prover = options.prover ?? new BBWASMLazyPrivateKernelProver(simulationProvider, 16, proverLogger); + const prover = options.prover ?? new BBWASMLazyPrivateKernelProver(simulator, 16, proverLogger); const protocolContractsProvider = new LazyProtocolContractsProvider(); @@ -58,7 +58,7 @@ export async function createPXEService( aztecNode, store, prover, - simulationProvider, + simulator, protocolContractsProvider, config, pxeLogger, diff --git a/yarn-project/pxe/src/entrypoints/server/utils.ts b/yarn-project/pxe/src/entrypoints/server/utils.ts index 24d93ac2c6d4..7a7ddcc27043 100644 --- a/yarn-project/pxe/src/entrypoints/server/utils.ts +++ b/yarn-project/pxe/src/entrypoints/server/utils.ts @@ -4,9 +4,9 @@ import { randomBytes } from '@aztec/foundation/crypto'; import { type Logger, createLogger } from '@aztec/foundation/log'; import { BundledProtocolContractsProvider } from '@aztec/protocol-contracts/providers/bundle'; import { + type CircuitSimulator, MemoryCircuitRecorder, - type SimulationProvider, - SimulationProviderRecorderWrapper, + SimulatorRecorderWrapper, WASMSimulator, } from '@aztec/simulator/client'; import { FileCircuitRecorder } from '@aztec/simulator/testing'; @@ -30,26 +30,26 @@ export function createPXEService( config: PXEServiceConfig, options: PXECreationOptions = { loggers: {} }, ) { - const simulationProvider = new WASMSimulator(); + const simulator = new WASMSimulator(); const recorder = process.env.CIRCUIT_RECORD_DIR ? new FileCircuitRecorder(process.env.CIRCUIT_RECORD_DIR) : new MemoryCircuitRecorder(); - const simulationProviderWithRecorder = new SimulationProviderRecorderWrapper(simulationProvider, recorder); - return createPXEServiceWithSimulationProvider(aztecNode, simulationProviderWithRecorder, config, options); + const simulatorWithRecorder = new SimulatorRecorderWrapper(simulator, recorder); + return createPXEServiceWithSimulator(aztecNode, simulatorWithRecorder, config, options); } /** - * Create and start an PXEService instance with the given AztecNode, SimulationProvider and config. + * Create and start an PXEService instance with the given AztecNode, Simulator and config. * * @param aztecNode - The AztecNode instance to be used by the server. - * @param simulationProvider - The SimulationProvider to use + * @param simulator - The Simulator to use * @param config - The PXE Service Config to use * @param useLogSuffix - Whether to add a randomly generated suffix to the PXE debug logs. * @returns A Promise that resolves to the started PXEService instance. */ -export async function createPXEServiceWithSimulationProvider( +export async function createPXEServiceWithSimulator( aztecNode: AztecNode, - simulationProvider: SimulationProvider, + simulator: CircuitSimulator, config: PXEServiceConfig, options: PXECreationOptions = { loggers: {} }, ) { @@ -81,7 +81,7 @@ export async function createPXEServiceWithSimulationProvider( ? loggers.prover : createLogger('pxe:bb:native' + (logSuffix ? `:${logSuffix}` : '')); - const prover = await createProver(config, simulationProvider, proverLogger); + const prover = await createProver(config, simulator, proverLogger); const protocolContractsProvider = new BundledProtocolContractsProvider(); const pxeLogger = loggers.pxe ? loggers.pxe : createLogger('pxe:service' + (logSuffix ? `:${logSuffix}` : '')); @@ -89,7 +89,7 @@ export async function createPXEServiceWithSimulationProvider( aztecNode, options.store, prover, - simulationProvider, + simulator, protocolContractsProvider, config, pxeLogger, @@ -97,12 +97,12 @@ export async function createPXEServiceWithSimulationProvider( return pxe; } -function createProver(config: PXEServiceConfig, simulationProvider: SimulationProvider, logger?: Logger) { +function createProver(config: PXEServiceConfig, simulator: CircuitSimulator, logger?: Logger) { if (!config.bbBinaryPath || !config.bbWorkingDirectory) { - return new BBWASMBundlePrivateKernelProver(simulationProvider, 16, logger); + return new BBWASMBundlePrivateKernelProver(simulator, 16, logger); } else { const bbConfig = config as Required> & PXEServiceConfig; - return BBNativePrivateKernelProver.new({ bbSkipCleanup: false, ...bbConfig }, simulationProvider, logger); + return BBNativePrivateKernelProver.new({ bbSkipCleanup: false, ...bbConfig }, simulator, logger); } } diff --git a/yarn-project/pxe/src/pxe_oracle_interface/pxe_oracle_interface.ts b/yarn-project/pxe/src/pxe_oracle_interface/pxe_oracle_interface.ts index fe8455f78e3d..7ef0253776bd 100644 --- a/yarn-project/pxe/src/pxe_oracle_interface/pxe_oracle_interface.ts +++ b/yarn-project/pxe/src/pxe_oracle_interface/pxe_oracle_interface.ts @@ -3,7 +3,6 @@ import { timesParallel } from '@aztec/foundation/collection'; import { Fr, Point } from '@aztec/foundation/fields'; import { createLogger } from '@aztec/foundation/log'; import type { KeyStore } from '@aztec/key-store'; -import { type ExecutionDataProvider, MessageLoadOracleInputs } from '@aztec/simulator/client'; import { EventSelector, type FunctionArtifactWithContractName, @@ -31,6 +30,8 @@ import { MerkleTreeId, type NullifierMembershipWitness, PublicDataWitness } from import type { BlockHeader } from '@aztec/stdlib/tx'; import { TxHash } from '@aztec/stdlib/tx'; +import type { ExecutionDataProvider } from '../contract_function_simulator/execution_data_provider.js'; +import { MessageLoadOracleInputs } from '../contract_function_simulator/oracle/message_load_oracle_inputs.js'; import type { AddressDataProvider } from '../storage/address_data_provider/address_data_provider.js'; import type { CapsuleDataProvider } from '../storage/capsule_data_provider/capsule_data_provider.js'; import type { ContractDataProvider } from '../storage/contract_data_provider/contract_data_provider.js'; @@ -152,16 +153,6 @@ export class PXEOracleInterface implements ExecutionDataProvider { return new MessageLoadOracleInputs(messageIndex, siblingPath); } - // Only used in public. - public getL1ToL2MessageHash(_leafIndex: bigint): Promise { - throw new Error('Unimplemented in private!'); - } - - // We need this in public as part of the EXISTS calls - but isn't used in private - public getNoteHash(_leafIndex: bigint): Promise { - throw new Error('Unimplemented in private!'); - } - async getNullifierIndex(nullifier: Fr) { return await this.#findLeafIndex('latest', MerkleTreeId.NULLIFIER_TREE, nullifier); } diff --git a/yarn-project/pxe/src/pxe_service/pxe_service.ts b/yarn-project/pxe/src/pxe_service/pxe_service.ts index df665caf7f61..d87ac9475ebf 100644 --- a/yarn-project/pxe/src/pxe_service/pxe_service.ts +++ b/yarn-project/pxe/src/pxe_service/pxe_service.ts @@ -12,7 +12,7 @@ import { type ProtocolContractsProvider, protocolContractNames, } from '@aztec/protocol-contracts'; -import { AcirSimulator, type SimulationProvider, readCurrentClassId } from '@aztec/simulator/client'; +import type { CircuitSimulator } from '@aztec/simulator/client'; import { type ContractArtifact, EventSelector, @@ -73,6 +73,8 @@ import { inspect } from 'util'; import type { PXEServiceConfig } from '../config/index.js'; import { getPackageInfo } from '../config/package_info.js'; +import { ContractFunctionSimulator } from '../contract_function_simulator/contract_function_simulator.js'; +import { readCurrentClassId } from '../contract_function_simulator/oracle/private_execution.js'; import { PrivateKernelExecutionProver, type PrivateKernelExecutionProverConfig, @@ -106,7 +108,7 @@ export class PXEService implements PXE { private taggingDataProvider: TaggingDataProvider, private addressDataProvider: AddressDataProvider, private privateEventDataProvider: PrivateEventDataProvider, - private simulator: AcirSimulator, + private contractFunctionSimulator: ContractFunctionSimulator, private packageVersion: string, private proverEnabled: boolean, private proofCreator: PrivateKernelProver, @@ -126,7 +128,7 @@ export class PXEService implements PXE { node: AztecNode, store: AztecAsyncKVStore, proofCreator: PrivateKernelProver, - simulationProvider: SimulationProvider, + simulator: CircuitSimulator, protocolContractsProvider: ProtocolContractsProvider, config: PXEServiceConfig, loggerOrSuffix?: string | Logger, @@ -168,7 +170,7 @@ export class PXEService implements PXE { privateEventDataProvider, log, ); - const simulator = new AcirSimulator(pxeOracleInterface, simulationProvider); + const contractFunctionSimulator = new ContractFunctionSimulator(pxeOracleInterface, simulator); const jobQueue = new SerialQueue(); const pxeService = new PXEService( @@ -182,7 +184,7 @@ export class PXEService implements PXE { taggingDataProvider, addressDataProvider, privateEventDataProvider, - simulator, + contractFunctionSimulator, packageVersion, proverEnabled, proofCreator, @@ -342,7 +344,13 @@ export class PXEService implements PXE { const { origin: contractAddress, functionSelector } = txRequest; try { - const result = await this.simulator.run(txRequest, contractAddress, functionSelector, msgSender, scopes); + const result = await this.contractFunctionSimulator.run( + txRequest, + contractAddress, + functionSelector, + msgSender, + scopes, + ); this.log.debug(`Private simulation completed for ${contractAddress.toString()}:${functionSelector}`); return result; } catch (err) { @@ -363,7 +371,7 @@ export class PXEService implements PXE { */ async #simulateUtility(call: FunctionCall, authWitnesses?: AuthWitness[], scopes?: AztecAddress[]) { try { - return this.simulator.runUtility(call, authWitnesses ?? [], scopes); + return this.contractFunctionSimulator.runUtility(call, authWitnesses ?? [], scopes); } catch (err) { if (err instanceof SimulationError) { await enrichSimulationError(err, this.contractDataProvider, this.log); diff --git a/yarn-project/pxe/src/storage/note_data_provider/note_dao.ts b/yarn-project/pxe/src/storage/note_data_provider/note_dao.ts index 3784dea73ec6..7bc31ddd1ec1 100644 --- a/yarn-project/pxe/src/storage/note_data_provider/note_dao.ts +++ b/yarn-project/pxe/src/storage/note_data_provider/note_dao.ts @@ -1,11 +1,12 @@ import { toBigIntBE } from '@aztec/foundation/bigint-buffer'; import { Fr, Point } from '@aztec/foundation/fields'; import { BufferReader, serializeToBuffer } from '@aztec/foundation/serialize'; -import type { NoteData } from '@aztec/simulator/client'; import { AztecAddress } from '@aztec/stdlib/aztec-address'; import { Note } from '@aztec/stdlib/note'; import { TxHash } from '@aztec/stdlib/tx'; +import type { NoteData } from '../../contract_function_simulator/oracle/typed_oracle.js'; + /** * A Note Data Access Object, representing a note that was committed to the note hash tree, holding all of the * information required to use it during execution and manage its state. diff --git a/yarn-project/pxe/src/test/pxe_service.test.ts b/yarn-project/pxe/src/test/pxe_service.test.ts index cea906962dfc..5af148fead3d 100644 --- a/yarn-project/pxe/src/test/pxe_service.test.ts +++ b/yarn-project/pxe/src/test/pxe_service.test.ts @@ -5,7 +5,7 @@ import type { AztecAsyncKVStore } from '@aztec/kv-store'; import { openTmpStore } from '@aztec/kv-store/lmdb-v2'; import type { ProtocolContractsProvider } from '@aztec/protocol-contracts'; import { BundledProtocolContractsProvider } from '@aztec/protocol-contracts/providers/bundle'; -import { type SimulationProvider, WASMSimulator } from '@aztec/simulator/client'; +import { type CircuitSimulator, WASMSimulator } from '@aztec/simulator/client'; import { randomInBlock } from '@aztec/stdlib/block'; import type { AztecNode, PXE, PrivateKernelProver } from '@aztec/stdlib/interfaces/client'; import { mockTx } from '@aztec/stdlib/testing'; @@ -20,8 +20,8 @@ import { pxeTestSuite } from './pxe_test_suite.js'; async function createPXEService(): Promise { const kvStore = await openTmpStore('test'); const node = mock(); - const simulationProvider = new WASMSimulator(); - const kernelProver = new BBWASMBundlePrivateKernelProver(simulationProvider); + const simulator = new WASMSimulator(); + const kernelProver = new BBWASMBundlePrivateKernelProver(simulator); const protocolContractsProvider = new BundledProtocolContractsProvider(); const config: PXEServiceConfig = { l2BlockBatchSize: 200, @@ -52,7 +52,7 @@ async function createPXEService(): Promise { }; node.getL1ContractAddresses.mockResolvedValue(mockedContracts); - return await PXEService.create(node, kvStore, kernelProver, simulationProvider, protocolContractsProvider, config); + return await PXEService.create(node, kvStore, kernelProver, simulator, protocolContractsProvider, config); } pxeTestSuite('PXEService', createPXEService); @@ -60,7 +60,7 @@ pxeTestSuite('PXEService', createPXEService); describe('PXEService', () => { let kvStore: AztecAsyncKVStore; let node: MockProxy; - let simulationProvider: SimulationProvider; + let simulator: CircuitSimulator; let kernelProver: PrivateKernelProver; let config: PXEServiceConfig; let protocolContractsProvider: ProtocolContractsProvider; @@ -68,8 +68,8 @@ describe('PXEService', () => { beforeEach(async () => { kvStore = await openTmpStore('test'); node = mock(); - simulationProvider = new WASMSimulator(); - kernelProver = new BBWASMBundlePrivateKernelProver(simulationProvider); + simulator = new WASMSimulator(); + kernelProver = new BBWASMBundlePrivateKernelProver(simulator); protocolContractsProvider = new BundledProtocolContractsProvider(); config = { @@ -92,14 +92,7 @@ describe('PXEService', () => { txIndexInBlock: 0, }); - const pxe = await PXEService.create( - node, - kvStore, - kernelProver, - simulationProvider, - protocolContractsProvider, - config, - ); + const pxe = await PXEService.create(node, kvStore, kernelProver, simulator, protocolContractsProvider, config); await expect(pxe.sendTx(duplicateTx)).rejects.toThrow(/A settled tx with equal hash/); }); }); diff --git a/yarn-project/pxe/tsconfig.json b/yarn-project/pxe/tsconfig.json index 901dad372a0b..ddcba16ddda4 100644 --- a/yarn-project/pxe/tsconfig.json +++ b/yarn-project/pxe/tsconfig.json @@ -39,6 +39,9 @@ { "path": "../stdlib" }, + { + "path": "../merkle-tree" + }, { "path": "../noir-test-contracts.js" } diff --git a/yarn-project/sequencer-client/src/client/sequencer-client.ts b/yarn-project/sequencer-client/src/client/sequencer-client.ts index de07a7596d24..5322bb571438 100644 --- a/yarn-project/sequencer-client/src/client/sequencer-client.ts +++ b/yarn-project/sequencer-client/src/client/sequencer-client.ts @@ -46,7 +46,6 @@ export class SequencerClient { * @param l2BlockSource - Provides information about the previously published blocks. * @param l1ToL2MessageSource - Provides access to L1 to L2 messages. * @param prover - An instance of a block prover - * @param simulationProvider - An instance of a simulation provider * @returns A new running instance. */ public static async new( diff --git a/yarn-project/simulator/src/client.ts b/yarn-project/simulator/src/client.ts index 1d0666dc5726..55b01e351d27 100644 --- a/yarn-project/simulator/src/client.ts +++ b/yarn-project/simulator/src/client.ts @@ -1,6 +1,6 @@ -export * from './private/index.js'; -export { WASMSimulator } from './private/providers/acvm_wasm.js'; -export { SimulationProviderRecorderWrapper } from './private/providers/circuit_recording/simulation_provider_recorder_wrapper.js'; -export { MemoryCircuitRecorder } from './private/providers/circuit_recording/memory_circuit_recorder.js'; -export { type SimulationProvider, type DecodedError } from './private/providers/simulation_provider.js'; +export * from './private/acvm/index.js'; +export { WASMSimulator } from './private/acvm_wasm.js'; +export { SimulatorRecorderWrapper } from './private/circuit_recording/simulator_recorder_wrapper.js'; +export { MemoryCircuitRecorder } from './private/circuit_recording/memory_circuit_recorder.js'; +export { type CircuitSimulator, type DecodedError } from './private/circuit_simulator.js'; export * from './common/index.js'; diff --git a/yarn-project/simulator/src/private/acvm/acvm.ts b/yarn-project/simulator/src/private/acvm/acvm.ts index aa6b468c88c3..c937155115df 100644 --- a/yarn-project/simulator/src/private/acvm/acvm.ts +++ b/yarn-project/simulator/src/private/acvm/acvm.ts @@ -10,12 +10,11 @@ import type { NoirCallStack } from '@aztec/stdlib/errors'; import { resolveOpcodeLocations, traverseCauseChain } from '../../common/errors.js'; import type { ACVMWitness } from './acvm_types.js'; -import type { ORACLE_NAMES } from './oracle/index.js'; /** * The callback interface for the ACIR. */ -export type ACIRCallback = Record Promise>; +export type ACIRCallback = Record Promise>; export type ACIRCallbackStats = { times: number[] }; @@ -54,7 +53,7 @@ export async function acvm( (name: string, args: ForeignCallInput[]) => { try { logger.debug(`Oracle callback ${name}`); - const oracleFunction = callback[name as ORACLE_NAMES]; + const oracleFunction = callback[name]; if (!oracleFunction) { throw new Error(`Oracle callback ${name} not found`); } diff --git a/yarn-project/simulator/src/private/acvm/index.ts b/yarn-project/simulator/src/private/acvm/index.ts index b3c6a274ff2e..da14a535feab 100644 --- a/yarn-project/simulator/src/private/acvm/index.ts +++ b/yarn-project/simulator/src/private/acvm/index.ts @@ -1,5 +1,4 @@ export { extractCallStack, type ACIRCallback, type ACIRExecutionResult } from './acvm.js'; export * from './acvm_types.js'; export * from './deserialize.js'; -export * from './oracle/index.js'; export * from './serialize.js'; diff --git a/yarn-project/simulator/src/private/providers/acvm_native.ts b/yarn-project/simulator/src/private/acvm_native.ts similarity index 95% rename from yarn-project/simulator/src/private/providers/acvm_native.ts rename to yarn-project/simulator/src/private/acvm_native.ts index d9d8846e75dd..5c7be1e1ad2e 100644 --- a/yarn-project/simulator/src/private/providers/acvm_native.ts +++ b/yarn-project/simulator/src/private/acvm_native.ts @@ -9,9 +9,9 @@ import type { NoirCompiledCircuitWithName } from '@aztec/stdlib/noir'; import * as proc from 'child_process'; import { promises as fs } from 'fs'; -import type { ACIRCallback, ACIRExecutionResult } from '../acvm/acvm.js'; -import type { ACVMWitness } from '../acvm/acvm_types.js'; -import type { SimulationProvider } from './simulation_provider.js'; +import type { ACIRCallback, ACIRExecutionResult } from './acvm/acvm.js'; +import type { ACVMWitness } from './acvm/acvm_types.js'; +import type { CircuitSimulator } from './circuit_simulator.js'; const logger = createLogger('simulator:acvm-native'); @@ -137,7 +137,7 @@ export async function executeNativeCircuit( } } -export class NativeACVMSimulator implements SimulationProvider { +export class NativeACVMSimulator implements CircuitSimulator { constructor( private workingDirectory: string, private pathToAcvm: string, diff --git a/yarn-project/simulator/src/private/providers/acvm_wasm.ts b/yarn-project/simulator/src/private/acvm_wasm.ts similarity index 92% rename from yarn-project/simulator/src/private/providers/acvm_wasm.ts rename to yarn-project/simulator/src/private/acvm_wasm.ts index 3171b61e0c6d..93f1302ecee3 100644 --- a/yarn-project/simulator/src/private/providers/acvm_wasm.ts +++ b/yarn-project/simulator/src/private/acvm_wasm.ts @@ -5,12 +5,12 @@ import initAbi from '@aztec/noir-noirc_abi'; import type { FunctionArtifactWithContractName } from '@aztec/stdlib/abi'; import type { NoirCompiledCircuitWithName } from '@aztec/stdlib/noir'; -import { type ACIRCallback, type ACIRExecutionResult, acvm } from '../acvm/acvm.js'; -import type { ACVMWitness } from '../acvm/acvm_types.js'; +import { type ACIRCallback, type ACIRExecutionResult, acvm } from './acvm/acvm.js'; +import type { ACVMWitness } from './acvm/acvm_types.js'; import type { ACVMSuccess } from './acvm_native.js'; -import { type SimulationProvider, enrichNoirError } from './simulation_provider.js'; +import { type CircuitSimulator, enrichNoirError } from './circuit_simulator.js'; -export class WASMSimulator implements SimulationProvider { +export class WASMSimulator implements CircuitSimulator { constructor(protected log = createLogger('wasm-simulator')) {} async init(): Promise { diff --git a/yarn-project/simulator/src/private/providers/acvm_wasm_with_blobs.ts b/yarn-project/simulator/src/private/acvm_wasm_with_blobs.ts similarity index 82% rename from yarn-project/simulator/src/private/providers/acvm_wasm_with_blobs.ts rename to yarn-project/simulator/src/private/acvm_wasm_with_blobs.ts index 76b53b337c7a..6098fff2f798 100644 --- a/yarn-project/simulator/src/private/providers/acvm_wasm_with_blobs.ts +++ b/yarn-project/simulator/src/private/acvm_wasm_with_blobs.ts @@ -4,19 +4,19 @@ import type { WitnessMap } from '@aztec/noir-types'; import type { FunctionArtifactWithContractName } from '@aztec/stdlib/abi'; import type { NoirCompiledCircuitWithName } from '@aztec/stdlib/noir'; -import type { ACIRCallback, ACIRExecutionResult } from '../acvm/acvm.js'; -import type { ACVMWitness } from '../acvm/acvm_types.js'; +import type { ACIRCallback, ACIRExecutionResult } from './acvm/acvm.js'; +import type { ACVMWitness } from './acvm/acvm_types.js'; import type { ACVMSuccess } from './acvm_native.js'; -import { type SimulationProvider, enrichNoirError } from './simulation_provider.js'; +import { type CircuitSimulator, enrichNoirError } from './circuit_simulator.js'; /** - * A simulation provider that uses the WASM simulator with the ability to handle blobs via the foreign call handler. + * A circuit simulator that uses the WASM simulator with the ability to handle blobs via the foreign call handler. * This class is temporary while brillig cannot handle the blob math, and it is kept separate * because the zkg commitment library used in the blob code is not browser compatible. * * It is only used in the context of server-side code executing simulated protocol circuits. */ -export class WASMSimulatorWithBlobs implements SimulationProvider { +export class WASMSimulatorWithBlobs implements CircuitSimulator { async executeProtocolCircuit( input: WitnessMap, artifact: NoirCompiledCircuitWithName, diff --git a/yarn-project/simulator/src/private/providers/circuit_recording/circuit_recorder.ts b/yarn-project/simulator/src/private/circuit_recording/circuit_recorder.ts similarity index 96% rename from yarn-project/simulator/src/private/providers/circuit_recording/circuit_recorder.ts rename to yarn-project/simulator/src/private/circuit_recording/circuit_recorder.ts index 0870a15bab92..a3ea51790142 100644 --- a/yarn-project/simulator/src/private/providers/circuit_recording/circuit_recorder.ts +++ b/yarn-project/simulator/src/private/circuit_recording/circuit_recorder.ts @@ -3,9 +3,8 @@ import { createLogger } from '@aztec/foundation/log'; import { Timer } from '@aztec/foundation/timer'; import type { ForeignCallHandler, ForeignCallInput, ForeignCallOutput } from '@aztec/noir-acvm_js'; -import type { ACIRCallback } from '../../acvm/acvm.js'; -import type { ACVMWitness } from '../../acvm/acvm_types.js'; -import { Oracle } from '../../acvm/oracle/oracle.js'; +import type { ACIRCallback } from '../acvm/acvm.js'; +import type { ACVMWitness } from '../acvm/acvm_types.js'; export type OracleCall = { name: string; @@ -152,11 +151,11 @@ export class CircuitRecorder { */ #wrapUserCircuitCallback(callback: ACIRCallback): ACIRCallback { const recordingCallback: ACIRCallback = {} as ACIRCallback; - const oracleMethods = Object.getOwnPropertyNames(Oracle.prototype).filter(name => name !== 'constructor'); + const oracleMethods = Object.keys(callback); for (const name of oracleMethods) { const fn = callback[name as keyof ACIRCallback]; - if (!fn) { + if (!fn || typeof fn !== 'function') { throw new Error(`Oracle method ${name} not found when setting up recording callback`); } diff --git a/yarn-project/simulator/src/private/providers/circuit_recording/file_circuit_recorder.ts b/yarn-project/simulator/src/private/circuit_recording/file_circuit_recorder.ts similarity index 98% rename from yarn-project/simulator/src/private/providers/circuit_recording/file_circuit_recorder.ts rename to yarn-project/simulator/src/private/circuit_recording/file_circuit_recorder.ts index 5f3d36afedde..21580c78ea08 100644 --- a/yarn-project/simulator/src/private/providers/circuit_recording/file_circuit_recorder.ts +++ b/yarn-project/simulator/src/private/circuit_recording/file_circuit_recorder.ts @@ -1,7 +1,7 @@ import fs from 'fs/promises'; import path from 'path'; -import type { ACVMWitness } from '../../acvm/acvm_types.js'; +import type { ACVMWitness } from '../acvm/acvm_types.js'; import { CircuitRecorder, type CircuitRecording } from './circuit_recorder.js'; export class FileCircuitRecorder extends CircuitRecorder { diff --git a/yarn-project/simulator/src/private/providers/circuit_recording/memory_circuit_recorder.ts b/yarn-project/simulator/src/private/circuit_recording/memory_circuit_recorder.ts similarity index 100% rename from yarn-project/simulator/src/private/providers/circuit_recording/memory_circuit_recorder.ts rename to yarn-project/simulator/src/private/circuit_recording/memory_circuit_recorder.ts diff --git a/yarn-project/simulator/src/private/providers/circuit_recording/simulation_provider_recorder_wrapper.ts b/yarn-project/simulator/src/private/circuit_recording/simulator_recorder_wrapper.ts similarity index 87% rename from yarn-project/simulator/src/private/providers/circuit_recording/simulation_provider_recorder_wrapper.ts rename to yarn-project/simulator/src/private/circuit_recording/simulator_recorder_wrapper.ts index c2b13410d4b0..2a8062d01ffd 100644 --- a/yarn-project/simulator/src/private/providers/circuit_recording/simulation_provider_recorder_wrapper.ts +++ b/yarn-project/simulator/src/private/circuit_recording/simulator_recorder_wrapper.ts @@ -2,19 +2,19 @@ import type { ForeignCallHandler } from '@aztec/noir-protocol-circuits-types/typ import type { FunctionArtifactWithContractName } from '@aztec/stdlib/abi'; import type { NoirCompiledCircuitWithName } from '@aztec/stdlib/noir'; -import type { ACIRCallback, ACIRCallbackStats, ACIRExecutionResult } from '../../acvm/acvm.js'; -import type { ACVMWitness } from '../../acvm/acvm_types.js'; +import type { ACIRCallback, ACIRCallbackStats, ACIRExecutionResult } from '../acvm/acvm.js'; +import type { ACVMWitness } from '../acvm/acvm_types.js'; import type { ACVMSuccess } from '../acvm_native.js'; -import type { SimulationProvider } from '../simulation_provider.js'; +import type { CircuitSimulator } from '../circuit_simulator.js'; import type { CircuitRecorder } from './circuit_recorder.js'; /** - * Takes a simulation provider and wraps it in a circuit recorder. See CircuitRecorder for more details on how circuit + * Takes a circuit simulator and wraps it in a circuit recorder. See CircuitRecorder for more details on how circuit * recording works. */ -export class SimulationProviderRecorderWrapper implements SimulationProvider { +export class SimulatorRecorderWrapper implements CircuitSimulator { constructor( - private simulator: SimulationProvider, + private simulator: CircuitSimulator, private recorder: CircuitRecorder, ) {} diff --git a/yarn-project/simulator/src/private/providers/simulation_provider.ts b/yarn-project/simulator/src/private/circuit_simulator.ts similarity index 96% rename from yarn-project/simulator/src/private/providers/simulation_provider.ts rename to yarn-project/simulator/src/private/circuit_simulator.ts index e13afd95b071..7240e5156e46 100644 --- a/yarn-project/simulator/src/private/providers/simulation_provider.ts +++ b/yarn-project/simulator/src/private/circuit_simulator.ts @@ -4,14 +4,14 @@ import { parseDebugSymbols } from '@aztec/stdlib/abi'; import type { FunctionArtifactWithContractName } from '@aztec/stdlib/abi'; import type { NoirCompiledCircuit, NoirCompiledCircuitWithName } from '@aztec/stdlib/noir'; -import { type ACIRCallback, type ACIRExecutionResult, extractCallStack } from '../acvm/acvm.js'; -import type { ACVMWitness } from '../acvm/acvm_types.js'; +import { type ACIRCallback, type ACIRExecutionResult, extractCallStack } from './acvm/acvm.js'; +import type { ACVMWitness } from './acvm/acvm_types.js'; import type { ACVMSuccess } from './acvm_native.js'; /** * Low level simulation interface */ -export interface SimulationProvider { +export interface CircuitSimulator { /** * Execute a protocol circuit/generate a witness * @param input - The initial witness map defining all of the inputs to `circuit`. diff --git a/yarn-project/simulator/src/private/providers/factory.ts b/yarn-project/simulator/src/private/factory.ts similarity index 80% rename from yarn-project/simulator/src/private/providers/factory.ts rename to yarn-project/simulator/src/private/factory.ts index e41a92d46fe8..9363b17aa35e 100644 --- a/yarn-project/simulator/src/private/providers/factory.ts +++ b/yarn-project/simulator/src/private/factory.ts @@ -4,14 +4,14 @@ import { promises as fs } from 'fs'; import { NativeACVMSimulator } from './acvm_native.js'; import { WASMSimulator } from './acvm_wasm.js'; -import type { SimulationProvider } from './simulation_provider.js'; +import type { CircuitSimulator } from './circuit_simulator.js'; -export type SimulationProviderConfig = { +export type SimulatorConfig = { acvmBinaryPath?: string; acvmWorkingDirectory?: string; }; -export function getSimulationProviderConfigFromEnv() { +export function getSimulatorConfigFromEnv() { const { ACVM_BINARY_PATH, ACVM_WORKING_DIRECTORY } = process.env; return { acvmWorkingDirectory: ACVM_WORKING_DIRECTORY ? ACVM_WORKING_DIRECTORY : undefined, @@ -19,10 +19,10 @@ export function getSimulationProviderConfigFromEnv() { }; } -export async function createSimulationProvider( - config: SimulationProviderConfig, +export async function createSimulator( + config: SimulatorConfig, logger: Logger = createLogger('simulator'), -): Promise { +): Promise { if (config.acvmBinaryPath && config.acvmWorkingDirectory) { try { await fs.access(config.acvmBinaryPath, fs.constants.R_OK); diff --git a/yarn-project/simulator/src/private/index.ts b/yarn-project/simulator/src/private/index.ts deleted file mode 100644 index eab8310df065..000000000000 --- a/yarn-project/simulator/src/private/index.ts +++ /dev/null @@ -1,19 +0,0 @@ -export { AcirSimulator } from './simulator.js'; -export { - type ExecutionDataProvider, - ContractClassNotFoundError, - ContractNotFoundError, -} from './execution_data_provider.js'; -export * from './pick_notes.js'; -export { ExecutionNoteCache } from './execution_note_cache.js'; -export { extractPrivateCircuitPublicInputs, readCurrentClassId } from './private_execution.js'; -export { witnessMapToFields } from './acvm/deserialize.js'; -export { toACVMWitness } from './acvm/serialize.js'; -export { executePrivateFunction } from './private_execution.js'; -export { PrivateExecutionOracle } from './private_execution_oracle.js'; -export { UtilityExecutionOracle } from './utility_execution_oracle.js'; -export { extractCallStack } from './acvm/acvm.js'; -export { type NoteData, TypedOracle } from './acvm/oracle/typed_oracle.js'; -export { Oracle } from './acvm/oracle/oracle.js'; -export { HashedValuesCache } from './hashed_values_cache.js'; -export { MessageLoadOracleInputs } from './message_load_oracle_inputs.js'; diff --git a/yarn-project/simulator/src/server.ts b/yarn-project/simulator/src/server.ts index b254852949aa..d473b1381417 100644 --- a/yarn-project/simulator/src/server.ts +++ b/yarn-project/simulator/src/server.ts @@ -1,7 +1,8 @@ export * from './public/index.js'; -export { WASMSimulatorWithBlobs } from './private/providers/acvm_wasm_with_blobs.js'; -export { NativeACVMSimulator } from './private/providers/acvm_native.js'; -export { SimulationProviderRecorderWrapper } from './private/providers/circuit_recording/simulation_provider_recorder_wrapper.js'; -export { MemoryCircuitRecorder } from './private/providers/circuit_recording/memory_circuit_recorder.js'; -export { type SimulationProvider } from './private/providers/simulation_provider.js'; +export * from './private/acvm/index.js'; +export { WASMSimulatorWithBlobs } from './private/acvm_wasm_with_blobs.js'; +export { NativeACVMSimulator } from './private/acvm_native.js'; +export { SimulatorRecorderWrapper } from './private/circuit_recording/simulator_recorder_wrapper.js'; +export { MemoryCircuitRecorder } from './private/circuit_recording/memory_circuit_recorder.js'; +export { type CircuitSimulator, type DecodedError } from './private/circuit_simulator.js'; export * from './common/index.js'; diff --git a/yarn-project/simulator/src/test/utils.ts b/yarn-project/simulator/src/test/utils.ts deleted file mode 100644 index 0b872fb2f531..000000000000 --- a/yarn-project/simulator/src/test/utils.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { sha256ToField } from '@aztec/foundation/crypto'; -import { EthAddress } from '@aztec/foundation/eth-address'; -import { Fr } from '@aztec/foundation/fields'; -import type { AztecAddress } from '@aztec/stdlib/aztec-address'; -import { computeSecretHash } from '@aztec/stdlib/hash'; -import { L1Actor, L1ToL2Message, L2Actor } from '@aztec/stdlib/messaging'; - -/** - * Test utility function to craft an L1 to L2 message. - * @param selector - The cross chain message selector. - * @param contentPreimage - The args after the selector. - * @param targetContract - The contract to consume the message. - * @param secret - The secret to unlock the message. - * @returns The L1 to L2 message. - */ -export const buildL1ToL2Message = async ( - selector: string, - contentPreimage: Fr[], - targetContract: AztecAddress, - secret: Fr, - msgIndex: Fr | number, -) => { - // Write the selector into a buffer. - const selectorBuf = Buffer.from(selector, 'hex'); - - const content = sha256ToField([selectorBuf, ...contentPreimage]); - const secretHash = await computeSecretHash(secret); - - return new L1ToL2Message( - new L1Actor(EthAddress.random(), 1), - new L2Actor(targetContract, 1), - content, - secretHash, - new Fr(msgIndex), - ); -}; diff --git a/yarn-project/simulator/src/testing.ts b/yarn-project/simulator/src/testing.ts index e2116e9a0d5c..0aeaace19296 100644 --- a/yarn-project/simulator/src/testing.ts +++ b/yarn-project/simulator/src/testing.ts @@ -1 +1 @@ -export { FileCircuitRecorder } from './private/providers/circuit_recording/file_circuit_recorder.js'; +export { FileCircuitRecorder } from './private/circuit_recording/file_circuit_recorder.js'; diff --git a/yarn-project/txe/src/oracle/txe_oracle.ts b/yarn-project/txe/src/oracle/txe_oracle.ts index 4a4eb4892eef..712c3f16ca24 100644 --- a/yarn-project/txe/src/oracle/txe_oracle.ts +++ b/yarn-project/txe/src/oracle/txe_oracle.ts @@ -38,20 +38,17 @@ import { import { ExecutionNoteCache, HashedValuesCache, - type MessageLoadOracleInputs, + MessageLoadOracleInputs, type NoteData, Oracle, PrivateExecutionOracle, type TypedOracle, UtilityExecutionOracle, - WASMSimulator, executePrivateFunction, - extractCallStack, extractPrivateCircuitPublicInputs, pickNotes, - toACVMWitness, - witnessMapToFields, -} from '@aztec/simulator/client'; +} from '@aztec/pxe/simulator'; +import { WASMSimulator, extractCallStack, toACVMWitness, witnessMapToFields } from '@aztec/simulator/client'; import { createTxForPublicCalls } from '@aztec/simulator/public/fixtures'; import { ExecutionError, @@ -172,7 +169,7 @@ export class TXE implements TypedOracle { private node: AztecNode; - private simulationProvider = new WASMSimulator(); + private simulator = new WASMSimulator(); public noteCache: ExecutionNoteCache; @@ -872,8 +869,8 @@ export class TXE implements TypedOracle { const args = await this.loadFromExecutionCache(argsHash); const initialWitness = toACVMWitness(0, args); - const acirExecutionResult = await this.simulationProvider - .executeUserCircuit(initialWitness, entryPointArtifact, new Oracle(oracle)) + const acirExecutionResult = await this.simulator + .executeUserCircuit(initialWitness, entryPointArtifact, new Oracle(oracle).toACIRCallback()) .catch((err: Error) => { err.message = resolveAssertionMessageFromError(err, entryPointArtifact); throw new ExecutionError( @@ -929,8 +926,8 @@ export class TXE implements TypedOracle { const initialWitness = await this.getInitialWitness(artifact, argsHash, sideEffectCounter, isStaticCall); const acvmCallback = new Oracle(this); const timer = new Timer(); - const acirExecutionResult = await this.simulationProvider - .executeUserCircuit(initialWitness, artifact, acvmCallback) + const acirExecutionResult = await this.simulator + .executeUserCircuit(initialWitness, artifact, acvmCallback.toACIRCallback()) .catch((err: Error) => { err.message = resolveAssertionMessageFromError(err, artifact); @@ -1390,7 +1387,7 @@ export class TXE implements TypedOracle { HashedValuesCache.create(), noteCache, this.pxeOracleInterface, - this.simulationProvider, + this.simulator, 0, 1, ); @@ -1401,7 +1398,7 @@ export class TXE implements TypedOracle { let result; try { const executionResult = await executePrivateFunction( - this.simulationProvider, + this.simulator, context, artifact, targetContractAddress, diff --git a/yarn-project/txe/src/txe_service/txe_service.ts b/yarn-project/txe/src/txe_service/txe_service.ts index 93fe8fe256a2..c82a4a4f3bc5 100644 --- a/yarn-project/txe/src/txe_service/txe_service.ts +++ b/yarn-project/txe/src/txe_service/txe_service.ts @@ -4,7 +4,7 @@ import type { Logger } from '@aztec/foundation/log'; import { openTmpStore } from '@aztec/kv-store/lmdb-v2'; import type { ProtocolContract } from '@aztec/protocol-contracts'; import { enrichPublicSimulationError } from '@aztec/pxe/server'; -import type { TypedOracle } from '@aztec/simulator/client'; +import type { TypedOracle } from '@aztec/pxe/simulator'; import { type ContractArtifact, EventSelector, FunctionSelector, NoteSelector } from '@aztec/stdlib/abi'; import { PublicDataWrite } from '@aztec/stdlib/avm'; import { AztecAddress } from '@aztec/stdlib/aztec-address'; diff --git a/yarn-project/yarn.lock b/yarn-project/yarn.lock index bbfad6ca33e3..8eb22da30877 100644 --- a/yarn-project/yarn.lock +++ b/yarn-project/yarn.lock @@ -1236,6 +1236,7 @@ __metadata: "@aztec/foundation": "workspace:^" "@aztec/key-store": "workspace:^" "@aztec/kv-store": "workspace:^" + "@aztec/merkle-tree": "workspace:^" "@aztec/noir-protocol-circuits-types": "workspace:^" "@aztec/noir-test-contracts.js": "workspace:^" "@aztec/noir-types": "workspace:*"