@aztec/simulator 0.69.1 → 0.71.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/dest/acvm/acvm.d.ts +1 -2
  2. package/dest/acvm/acvm.d.ts.map +1 -1
  3. package/dest/acvm/acvm.js +12 -2
  4. package/dest/acvm/deserialize.d.ts +9 -0
  5. package/dest/acvm/deserialize.d.ts.map +1 -1
  6. package/dest/acvm/deserialize.js +12 -1
  7. package/dest/acvm/index.d.ts +1 -1
  8. package/dest/acvm/index.d.ts.map +1 -1
  9. package/dest/acvm/index.js +2 -2
  10. package/dest/acvm/oracle/oracle.d.ts +9 -5
  11. package/dest/acvm/oracle/oracle.d.ts.map +1 -1
  12. package/dest/acvm/oracle/oracle.js +44 -22
  13. package/dest/acvm/oracle/typed_oracle.d.ts +11 -17
  14. package/dest/acvm/oracle/typed_oracle.d.ts.map +1 -1
  15. package/dest/acvm/oracle/typed_oracle.js +25 -23
  16. package/dest/avm/avm_simulator.d.ts.map +1 -1
  17. package/dest/avm/avm_simulator.js +7 -1
  18. package/dest/avm/fixtures/index.d.ts +2 -3
  19. package/dest/avm/fixtures/index.d.ts.map +1 -1
  20. package/dest/avm/fixtures/index.js +4 -4
  21. package/dest/avm/journal/journal.d.ts +3 -4
  22. package/dest/avm/journal/journal.d.ts.map +1 -1
  23. package/dest/avm/journal/journal.js +11 -10
  24. package/dest/avm/journal/nullifiers.d.ts +1 -1
  25. package/dest/avm/journal/nullifiers.d.ts.map +1 -1
  26. package/dest/avm/journal/public_storage.d.ts +1 -1
  27. package/dest/avm/journal/public_storage.d.ts.map +1 -1
  28. package/dest/avm/opcodes/memory.d.ts.map +1 -1
  29. package/dest/avm/opcodes/memory.js +9 -5
  30. package/dest/client/client_execution_context.d.ts +29 -18
  31. package/dest/client/client_execution_context.d.ts.map +1 -1
  32. package/dest/client/client_execution_context.js +42 -29
  33. package/dest/client/db_oracle.d.ts +55 -16
  34. package/dest/client/db_oracle.d.ts.map +1 -1
  35. package/dest/client/db_oracle.js +1 -1
  36. package/dest/client/execution_note_cache.d.ts +27 -4
  37. package/dest/client/execution_note_cache.d.ts.map +1 -1
  38. package/dest/client/execution_note_cache.js +62 -12
  39. package/dest/client/index.d.ts +11 -3
  40. package/dest/client/index.d.ts.map +1 -1
  41. package/dest/client/index.js +11 -4
  42. package/dest/client/private_execution.d.ts +3 -2
  43. package/dest/client/private_execution.d.ts.map +1 -1
  44. package/dest/client/private_execution.js +10 -8
  45. package/dest/client/simulator.d.ts +4 -2
  46. package/dest/client/simulator.d.ts.map +1 -1
  47. package/dest/client/simulator.js +14 -9
  48. package/dest/client/unconstrained_execution.d.ts +2 -1
  49. package/dest/client/unconstrained_execution.d.ts.map +1 -1
  50. package/dest/client/unconstrained_execution.js +10 -5
  51. package/dest/client/view_data_oracle.d.ts +7 -10
  52. package/dest/client/view_data_oracle.d.ts.map +1 -1
  53. package/dest/client/view_data_oracle.js +38 -19
  54. package/dest/common/hashed_values_cache.d.ts +28 -0
  55. package/dest/common/hashed_values_cache.d.ts.map +1 -0
  56. package/dest/common/{packed_values_cache.js → hashed_values_cache.js} +22 -22
  57. package/dest/common/index.d.ts +1 -1
  58. package/dest/common/index.js +1 -1
  59. package/dest/common/message_load_oracle_inputs.d.ts +15 -0
  60. package/dest/common/message_load_oracle_inputs.d.ts.map +1 -0
  61. package/dest/common/message_load_oracle_inputs.js +15 -0
  62. package/dest/common/simulation_provider.d.ts +19 -0
  63. package/dest/common/simulation_provider.d.ts.map +1 -0
  64. package/dest/common/simulation_provider.js +27 -0
  65. package/dest/common.d.ts +2 -0
  66. package/dest/common.d.ts.map +1 -0
  67. package/dest/common.js +2 -0
  68. package/dest/providers/acvm_native.d.ts +5 -2
  69. package/dest/providers/acvm_native.d.ts.map +1 -1
  70. package/dest/providers/acvm_native.js +5 -2
  71. package/dest/providers/acvm_wasm.d.ts +8 -2
  72. package/dest/providers/acvm_wasm.d.ts.map +1 -1
  73. package/dest/providers/acvm_wasm.js +31 -5
  74. package/dest/providers/acvm_wasm_with_blobs.d.ts +14 -2
  75. package/dest/providers/acvm_wasm_with_blobs.d.ts.map +1 -1
  76. package/dest/providers/acvm_wasm_with_blobs.js +25 -5
  77. package/dest/providers/factory.d.ts +1 -1
  78. package/dest/providers/factory.d.ts.map +1 -1
  79. package/dest/providers/factory.js +1 -1
  80. package/dest/providers/index.d.ts +1 -1
  81. package/dest/providers/index.d.ts.map +1 -1
  82. package/dest/providers/index.js +2 -2
  83. package/dest/public/db_interfaces.d.ts +1 -1
  84. package/dest/public/db_interfaces.d.ts.map +1 -1
  85. package/dest/public/fixtures/index.d.ts +3 -3
  86. package/dest/public/fixtures/index.d.ts.map +1 -1
  87. package/dest/public/fixtures/index.js +52 -23
  88. package/dest/public/public_db_sources.d.ts +2 -1
  89. package/dest/public/public_db_sources.d.ts.map +1 -1
  90. package/dest/public/public_db_sources.js +2 -2
  91. package/dest/public/public_processor.d.ts +3 -3
  92. package/dest/public/public_processor.d.ts.map +1 -1
  93. package/dest/public/public_processor.js +9 -9
  94. package/dest/public/public_tx_context.d.ts +3 -7
  95. package/dest/public/public_tx_context.d.ts.map +1 -1
  96. package/dest/public/public_tx_context.js +7 -20
  97. package/dest/public/public_tx_simulator.d.ts +1 -1
  98. package/dest/public/public_tx_simulator.d.ts.map +1 -1
  99. package/dest/public/public_tx_simulator.js +7 -7
  100. package/{src/index.ts → dest/server.d.ts} +1 -2
  101. package/dest/server.d.ts.map +1 -0
  102. package/dest/server.js +6 -0
  103. package/package.json +11 -12
  104. package/src/acvm/acvm.ts +20 -3
  105. package/src/acvm/deserialize.ts +12 -0
  106. package/src/acvm/index.ts +1 -1
  107. package/src/acvm/oracle/oracle.ts +90 -28
  108. package/src/acvm/oracle/typed_oracle.ts +41 -24
  109. package/src/avm/avm_simulator.ts +6 -0
  110. package/src/avm/fixtures/index.ts +5 -4
  111. package/src/avm/journal/journal.ts +9 -9
  112. package/src/avm/journal/nullifiers.ts +1 -1
  113. package/src/avm/journal/public_storage.ts +1 -1
  114. package/src/avm/opcodes/memory.ts +8 -4
  115. package/src/client/client_execution_context.ts +47 -30
  116. package/src/client/db_oracle.ts +68 -17
  117. package/src/client/execution_note_cache.ts +67 -14
  118. package/src/client/index.ts +11 -3
  119. package/src/client/private_execution.ts +22 -18
  120. package/src/client/simulator.ts +21 -8
  121. package/src/client/unconstrained_execution.ts +21 -14
  122. package/src/client/view_data_oracle.ts +53 -19
  123. package/src/common/hashed_values_cache.ts +55 -0
  124. package/src/common/index.ts +1 -1
  125. package/src/common/message_load_oracle_inputs.ts +15 -0
  126. package/src/common/simulation_provider.ts +45 -0
  127. package/src/common.ts +1 -0
  128. package/src/providers/acvm_native.ts +12 -2
  129. package/src/providers/acvm_wasm.ts +36 -9
  130. package/src/providers/acvm_wasm_with_blobs.ts +35 -10
  131. package/src/providers/factory.ts +1 -1
  132. package/src/providers/index.ts +1 -1
  133. package/src/public/db_interfaces.ts +1 -1
  134. package/src/public/fixtures/index.ts +66 -36
  135. package/src/public/public_db_sources.ts +3 -6
  136. package/src/public/public_processor.ts +14 -7
  137. package/src/public/public_tx_context.ts +6 -19
  138. package/src/public/public_tx_simulator.ts +6 -6
  139. package/{dest/index.d.ts → src/server.ts} +0 -3
  140. package/dest/common/packed_values_cache.d.ts +0 -28
  141. package/dest/common/packed_values_cache.d.ts.map +0 -1
  142. package/dest/index.d.ts.map +0 -1
  143. package/dest/index.js +0 -8
  144. package/dest/providers/simulation_provider.d.ts +0 -9
  145. package/dest/providers/simulation_provider.d.ts.map +0 -1
  146. package/dest/providers/simulation_provider.js +0 -2
  147. package/src/common/packed_values_cache.ts +0 -55
  148. package/src/providers/simulation_provider.ts +0 -10
@@ -1,25 +1,52 @@
1
1
  import { foreignCallHandler } from '@aztec/noir-protocol-circuits-types/client';
2
2
  import { type NoirCompiledCircuit } from '@aztec/types/noir';
3
3
 
4
- import { executeCircuit } from '@noir-lang/acvm_js';
4
+ import initACVM, { type ExecutionError, executeCircuit } from '@noir-lang/acvm_js';
5
+ import initAbi from '@noir-lang/noirc_abi';
5
6
  import { type WitnessMap } from '@noir-lang/types';
6
7
 
7
- import { type SimulationProvider } from './simulation_provider.js';
8
+ import { type ACIRCallback, acvm } from '../acvm/acvm.js';
9
+ import { type ACVMWitness } from '../acvm/acvm_types.js';
10
+ import { type SimulationProvider, parseErrorPayload } from '../common/simulation_provider.js';
8
11
 
9
12
  export class WASMSimulator implements SimulationProvider {
10
- async simulateCircuit(input: WitnessMap, compiledCircuit: NoirCompiledCircuit): Promise<WitnessMap> {
13
+ async init(): Promise<void> {
14
+ // If these are available, then we are in the
15
+ // web environment. For the node environment, this
16
+ // is a no-op.
17
+ if (typeof initAbi === 'function') {
18
+ /** @ts-expect-error The node bundle doesn't include these default imports, so TS complains */
19
+ await Promise.all([initAbi(), initACVM()]);
20
+ }
21
+ }
22
+
23
+ async executeProtocolCircuit(input: WitnessMap, compiledCircuit: NoirCompiledCircuit): Promise<WitnessMap> {
24
+ await this.init();
11
25
  // Execute the circuit on those initial witness values
12
26
  //
13
27
  // Decode the bytecode from base64 since the acvm does not know about base64 encoding
14
28
  const decodedBytecode = Buffer.from(compiledCircuit.bytecode, 'base64');
15
29
  //
16
30
  // Execute the circuit
17
- const _witnessMap = await executeCircuit(
18
- decodedBytecode,
19
- input,
20
- foreignCallHandler, // handle calls to debug_log
21
- );
31
+ try {
32
+ const _witnessMap = await executeCircuit(
33
+ decodedBytecode,
34
+ input,
35
+ foreignCallHandler, // handle calls to debug_log
36
+ );
37
+
38
+ return _witnessMap;
39
+ } catch (err) {
40
+ // Typescript types catched errors as unknown or any, so we need to narrow its type to check if it has raw assertion payload.
41
+ if (typeof err === 'object' && err !== null && 'rawAssertionPayload' in err) {
42
+ throw parseErrorPayload(compiledCircuit.abi, err as ExecutionError);
43
+ }
44
+ throw new Error(`Circuit execution failed: ${err}`);
45
+ }
46
+ }
22
47
 
23
- return _witnessMap;
48
+ async executeUserCircuit(acir: Buffer, initialWitness: ACVMWitness, callback: ACIRCallback) {
49
+ await this.init();
50
+ return acvm(acir, initialWitness, callback);
24
51
  }
25
52
  }
@@ -1,25 +1,50 @@
1
- import { foreignCallHandler } from '@aztec/noir-protocol-circuits-types';
1
+ import { foreignCallHandler } from '@aztec/noir-protocol-circuits-types/server';
2
2
  import { type NoirCompiledCircuit } from '@aztec/types/noir';
3
3
 
4
- import { executeCircuit } from '@noir-lang/acvm_js';
4
+ import { type ExecutionError, executeCircuit } from '@noir-lang/acvm_js';
5
5
  import { type WitnessMap } from '@noir-lang/types';
6
6
 
7
- import { type SimulationProvider } from './simulation_provider.js';
7
+ import { type ACIRCallback, type ACIRExecutionResult } from '../acvm/acvm.js';
8
+ import { type ACVMWitness } from '../acvm/acvm_types.js';
9
+ import { type SimulationProvider, parseErrorPayload } from '../common/simulation_provider.js';
8
10
 
11
+ /**
12
+ * A simulation provider that uses the WASM simulator with the ability to handle blobs via the foreign call handler.
13
+ * This class is temporary while brillig cannot handle the blob math, and it is kept separate
14
+ * because the zkg commitment library used in the blob code is not browser compatible.
15
+ *
16
+ * It is only used in the context of server-side code executing simulated protocol circuits.
17
+ */
9
18
  export class WASMSimulatorWithBlobs implements SimulationProvider {
10
- async simulateCircuit(input: WitnessMap, compiledCircuit: NoirCompiledCircuit): Promise<WitnessMap> {
19
+ async executeProtocolCircuit(input: WitnessMap, compiledCircuit: NoirCompiledCircuit): Promise<WitnessMap> {
11
20
  // Execute the circuit on those initial witness values
12
21
  //
13
22
  // Decode the bytecode from base64 since the acvm does not know about base64 encoding
14
23
  const decodedBytecode = Buffer.from(compiledCircuit.bytecode, 'base64');
15
24
  //
16
25
  // Execute the circuit
17
- const _witnessMap = await executeCircuit(
18
- decodedBytecode,
19
- input,
20
- foreignCallHandler, // handle calls to debug_log and evaluate_blobs mock
21
- );
26
+ try {
27
+ const _witnessMap = await executeCircuit(
28
+ decodedBytecode,
29
+ input,
30
+ foreignCallHandler, // handle calls to debug_log and evaluate_blobs mock
31
+ );
22
32
 
23
- return _witnessMap;
33
+ return _witnessMap;
34
+ } catch (err) {
35
+ // Typescript types catched errors as unknown or any, so we need to narrow its type to check if it has raw assertion payload.
36
+ if (typeof err === 'object' && err !== null && 'rawAssertionPayload' in err) {
37
+ throw parseErrorPayload(compiledCircuit.abi, err as ExecutionError);
38
+ }
39
+ throw new Error(`Circuit execution failed: ${err}`);
40
+ }
41
+ }
42
+
43
+ executeUserCircuit(
44
+ _acir: Buffer,
45
+ _initialWitness: ACVMWitness,
46
+ _callback: ACIRCallback,
47
+ ): Promise<ACIRExecutionResult> {
48
+ throw new Error('Not implemented');
24
49
  }
25
50
  }
@@ -2,9 +2,9 @@ import { type Logger, createLogger } from '@aztec/foundation/log';
2
2
 
3
3
  import { promises as fs } from 'fs';
4
4
 
5
+ import { type SimulationProvider } from '../common/simulation_provider.js';
5
6
  import { NativeACVMSimulator } from './acvm_native.js';
6
7
  import { WASMSimulator } from './acvm_wasm.js';
7
- import { type SimulationProvider } from './simulation_provider.js';
8
8
 
9
9
  export type SimulationProviderConfig = {
10
10
  acvmBinaryPath?: string;
@@ -1,4 +1,4 @@
1
1
  export * from './acvm_native.js';
2
2
  export * from './acvm_wasm_with_blobs.js';
3
- export * from './simulation_provider.js';
3
+ export * from '../common/simulation_provider.js';
4
4
  export * from './factory.js';
@@ -7,7 +7,7 @@ import {
7
7
  import { type AztecAddress } from '@aztec/foundation/aztec-address';
8
8
  import { type Fr } from '@aztec/foundation/fields';
9
9
 
10
- import { type MessageLoadOracleInputs } from '../acvm/index.js';
10
+ import { type MessageLoadOracleInputs } from '../common/message_load_oracle_inputs.js';
11
11
 
12
12
  /**
13
13
  * Database interface for providing access to public state.
@@ -32,25 +32,25 @@ import { AztecAddress } from '@aztec/foundation/aztec-address';
32
32
  import { Fr, Point } from '@aztec/foundation/fields';
33
33
  import { openTmpStore } from '@aztec/kv-store/lmdb';
34
34
  import { AvmTestContractArtifact } from '@aztec/noir-contracts.js/AvmTest';
35
- import {
36
- AvmEphemeralForest,
37
- AvmSimulator,
38
- PublicEnqueuedCallSideEffectTrace,
39
- PublicTxSimulator,
40
- WorldStateDB,
41
- } from '@aztec/simulator';
42
- import { NoopTelemetryClient } from '@aztec/telemetry-client/noop';
43
35
  import { MerkleTrees } from '@aztec/world-state';
44
36
 
45
37
  import { strict as assert } from 'assert';
46
38
 
47
39
  import { initContext, initExecutionEnvironment, initPersistableStateManager } from '../../avm/fixtures/index.js';
40
+ import { AvmEphemeralForest, AvmSimulator } from '../../server.js';
41
+ import { PublicEnqueuedCallSideEffectTrace } from '../enqueued_call_side_effect_trace.js';
42
+ import { WorldStateDB } from '../public_db_sources.js';
43
+ import { PublicTxSimulator } from '../public_tx_simulator.js';
48
44
 
49
45
  const TIMESTAMP = new Fr(99833);
50
46
 
51
47
  export async function simulateAvmTestContractGenerateCircuitInputs(
52
- functionName: string,
53
- args: Fr[] = [],
48
+ setupFunctionNames: string[],
49
+ setupArgs: Fr[][] = [],
50
+ appFunctionNames: string[],
51
+ appArgs: Fr[][] = [],
52
+ teardownFunctionName?: string,
53
+ teardownArgs: Fr[] = [],
54
54
  expectRevert: boolean = false,
55
55
  contractDataSource = new MockedAvmTestContractDataSource(),
56
56
  assertionErrString?: string,
@@ -58,30 +58,42 @@ export async function simulateAvmTestContractGenerateCircuitInputs(
58
58
  const globals = GlobalVariables.empty();
59
59
  globals.timestamp = TIMESTAMP;
60
60
 
61
- const merkleTrees = await (await MerkleTrees.new(openTmpStore(), new NoopTelemetryClient())).fork();
61
+ const merkleTrees = await (await MerkleTrees.new(openTmpStore())).fork();
62
62
  await contractDataSource.deployContracts(merkleTrees);
63
63
  const worldStateDB = new WorldStateDB(merkleTrees, contractDataSource);
64
64
 
65
- const simulator = new PublicTxSimulator(
66
- merkleTrees,
67
- worldStateDB,
68
- new NoopTelemetryClient(),
69
- globals,
70
- /*doMerkleOperations=*/ true,
71
- );
65
+ const simulator = new PublicTxSimulator(merkleTrees, worldStateDB, globals, /*doMerkleOperations=*/ true);
72
66
 
73
67
  const sender = AztecAddress.random();
74
- const functionSelector = getAvmTestContractFunctionSelector(functionName);
75
- args = [functionSelector.toField(), ...args];
76
68
  const callContext = new CallContext(
77
69
  sender,
78
70
  contractDataSource.firstContractInstance.address,
79
71
  contractDataSource.fnSelector,
80
72
  /*isStaticCall=*/ false,
81
73
  );
82
- const executionRequest = new PublicExecutionRequest(callContext, args);
74
+ const setupExecutionRequests: PublicExecutionRequest[] = [];
75
+ for (let i = 0; i < setupFunctionNames.length; i++) {
76
+ const functionSelector = getAvmTestContractFunctionSelector(setupFunctionNames[i]);
77
+ const fnArgs = [functionSelector.toField(), ...setupArgs[i]];
78
+ const executionRequest = new PublicExecutionRequest(callContext, fnArgs);
79
+ setupExecutionRequests.push(executionRequest);
80
+ }
81
+ const appExecutionRequests: PublicExecutionRequest[] = [];
82
+ for (let i = 0; i < appFunctionNames.length; i++) {
83
+ const functionSelector = getAvmTestContractFunctionSelector(appFunctionNames[i]);
84
+ const fnArgs = [functionSelector.toField(), ...appArgs[i]];
85
+ const executionRequest = new PublicExecutionRequest(callContext, fnArgs);
86
+ appExecutionRequests.push(executionRequest);
87
+ }
83
88
 
84
- const tx: Tx = createTxForPublicCall(executionRequest);
89
+ let teardownExecutionRequest: PublicExecutionRequest | undefined = undefined;
90
+ if (teardownFunctionName) {
91
+ const functionSelector = getAvmTestContractFunctionSelector(teardownFunctionName);
92
+ const fnArgs = [functionSelector.toField(), ...teardownArgs];
93
+ teardownExecutionRequest = new PublicExecutionRequest(callContext, fnArgs);
94
+ }
95
+
96
+ const tx: Tx = createTxForPublicCalls(setupExecutionRequests, appExecutionRequests, teardownExecutionRequest);
85
97
 
86
98
  const avmResult = await simulator.simulate(tx);
87
99
 
@@ -109,7 +121,7 @@ export async function simulateAvmTestContractCall(
109
121
  const globals = GlobalVariables.empty();
110
122
  globals.timestamp = TIMESTAMP;
111
123
 
112
- const merkleTrees = await (await MerkleTrees.new(openTmpStore(), new NoopTelemetryClient())).fork();
124
+ const merkleTrees = await (await MerkleTrees.new(openTmpStore())).fork();
113
125
  await contractDataSource.deployContracts(merkleTrees);
114
126
  const worldStateDB = new WorldStateDB(merkleTrees, contractDataSource);
115
127
 
@@ -141,27 +153,39 @@ export async function simulateAvmTestContractCall(
141
153
  }
142
154
 
143
155
  /**
144
- * Craft a carrier transaction for a public call for simulation by PublicTxSimulator.
156
+ * Craft a carrier transaction for some public calls for simulation by PublicTxSimulator.
145
157
  */
146
- export function createTxForPublicCall(
147
- executionRequest: PublicExecutionRequest,
158
+ export function createTxForPublicCalls(
159
+ setupExecutionRequests: PublicExecutionRequest[],
160
+ appExecutionRequests: PublicExecutionRequest[],
161
+ teardownExecutionRequest?: PublicExecutionRequest,
148
162
  gasUsedByPrivate: Gas = Gas.empty(),
149
- isTeardown: boolean = false,
150
163
  ): Tx {
151
- const callRequest = executionRequest.toCallRequest();
164
+ assert(
165
+ setupExecutionRequests.length > 0 || appExecutionRequests.length > 0 || teardownExecutionRequest !== undefined,
166
+ "Can't create public tx with no enqueued calls",
167
+ );
168
+ const setupCallRequests = setupExecutionRequests.map(er => er.toCallRequest());
169
+ const appCallRequests = appExecutionRequests.map(er => er.toCallRequest());
152
170
  // use max limits
153
171
  const gasLimits = new Gas(DEFAULT_GAS_LIMIT, MAX_L2_GAS_PER_TX_PUBLIC_PORTION);
154
172
 
155
173
  const forPublic = PartialPrivateTailPublicInputsForPublic.empty();
156
174
  // TODO(#9269): Remove this fake nullifier method as we move away from 1st nullifier as hash.
157
175
  forPublic.nonRevertibleAccumulatedData.nullifiers[0] = Fr.random(); // fake tx nullifier
158
- if (isTeardown) {
159
- forPublic.publicTeardownCallRequest = callRequest;
160
- } else {
161
- forPublic.revertibleAccumulatedData.publicCallRequests[0] = callRequest;
176
+
177
+ // We reverse order because the simulator expects it to be like a "stack" of calls to pop from
178
+ for (let i = setupCallRequests.length - 1; i >= 0; i--) {
179
+ forPublic.nonRevertibleAccumulatedData.publicCallRequests[i] = setupCallRequests[i];
180
+ }
181
+ for (let i = appCallRequests.length - 1; i >= 0; i--) {
182
+ forPublic.revertibleAccumulatedData.publicCallRequests[i] = appCallRequests[i];
183
+ }
184
+ if (teardownExecutionRequest) {
185
+ forPublic.publicTeardownCallRequest = teardownExecutionRequest.toCallRequest();
162
186
  }
163
187
 
164
- const teardownGasLimits = isTeardown ? gasLimits : Gas.empty();
188
+ const teardownGasLimits = teardownExecutionRequest ? gasLimits : Gas.empty();
165
189
  const gasSettings = new GasSettings(gasLimits, teardownGasLimits, GasFees.empty(), GasFees.empty());
166
190
  const txContext = new TxContext(Fr.zero(), Fr.zero(), gasSettings);
167
191
  const constantData = new TxConstantData(BlockHeader.empty(), txContext, Fr.zero(), Fr.zero());
@@ -173,9 +197,15 @@ export function createTxForPublicCall(
173
197
  AztecAddress.zero(),
174
198
  forPublic,
175
199
  );
176
- const tx = isTeardown ? Tx.newWithTxData(txData, executionRequest) : Tx.newWithTxData(txData);
177
- if (!isTeardown) {
178
- tx.enqueuedPublicFunctionCalls[0] = executionRequest;
200
+ const tx = Tx.newWithTxData(txData, teardownExecutionRequest);
201
+
202
+ // Reverse order because the simulator expects it to be like a "stack" of calls to pop from.
203
+ // Also push app calls before setup calls for this reason.
204
+ for (let i = appExecutionRequests.length - 1; i >= 0; i--) {
205
+ tx.enqueuedPublicFunctionCalls.push(appExecutionRequests[i]);
206
+ }
207
+ for (let i = setupExecutionRequests.length - 1; i >= 0; i--) {
208
+ tx.enqueuedPublicFunctionCalls.push(setupExecutionRequests[i]);
179
209
  }
180
210
 
181
211
  return tx;
@@ -24,12 +24,9 @@ import { createLogger } from '@aztec/foundation/log';
24
24
  import { Timer } from '@aztec/foundation/timer';
25
25
  import { ContractClassRegisteredEvent } from '@aztec/protocol-contracts/class-registerer';
26
26
  import { ContractInstanceDeployedEvent } from '@aztec/protocol-contracts/instance-deployer';
27
- import {
28
- type CommitmentsDB,
29
- MessageLoadOracleInputs,
30
- type PublicContractsDB,
31
- type PublicStateDB,
32
- } from '@aztec/simulator';
27
+
28
+ import { MessageLoadOracleInputs } from '../common/message_load_oracle_inputs.js';
29
+ import { type CommitmentsDB, type PublicContractsDB, type PublicStateDB } from './db_interfaces.js';
33
30
 
34
31
  /**
35
32
  * Implements the PublicContractsDB using a ContractDataSource.
@@ -27,7 +27,14 @@ import { createLogger } from '@aztec/foundation/log';
27
27
  import { type DateProvider, Timer, elapsed, executeTimeout } from '@aztec/foundation/timer';
28
28
  import { ProtocolContractAddress } from '@aztec/protocol-contracts';
29
29
  import { ContractClassRegisteredEvent } from '@aztec/protocol-contracts/class-registerer';
30
- import { Attributes, type TelemetryClient, type Traceable, type Tracer, trackSpan } from '@aztec/telemetry-client';
30
+ import {
31
+ Attributes,
32
+ type TelemetryClient,
33
+ type Traceable,
34
+ type Tracer,
35
+ getTelemetryClient,
36
+ trackSpan,
37
+ } from '@aztec/telemetry-client';
31
38
 
32
39
  import { computeFeePayerBalanceLeafSlot, computeFeePayerBalanceStorageSlot } from './fee_payment.js';
33
40
  import { WorldStateDB } from './public_db_sources.js';
@@ -41,7 +48,7 @@ export class PublicProcessorFactory {
41
48
  constructor(
42
49
  private contractDataSource: ContractDataSource,
43
50
  private dateProvider: DateProvider,
44
- private telemetryClient: TelemetryClient,
51
+ private telemetryClient: TelemetryClient = getTelemetryClient(),
45
52
  ) {}
46
53
 
47
54
  /**
@@ -63,10 +70,10 @@ export class PublicProcessorFactory {
63
70
  const publicTxSimulator = this.createPublicTxSimulator(
64
71
  merkleTree,
65
72
  worldStateDB,
66
- this.telemetryClient,
67
73
  globalVariables,
68
74
  /*doMerkleOperations=*/ true,
69
75
  enforceFeePayment,
76
+ this.telemetryClient,
70
77
  );
71
78
 
72
79
  return new PublicProcessor(
@@ -83,18 +90,18 @@ export class PublicProcessorFactory {
83
90
  protected createPublicTxSimulator(
84
91
  db: MerkleTreeWriteOperations,
85
92
  worldStateDB: WorldStateDB,
86
- telemetryClient: TelemetryClient,
87
93
  globalVariables: GlobalVariables,
88
94
  doMerkleOperations: boolean,
89
95
  enforceFeePayment: boolean,
96
+ telemetryClient: TelemetryClient,
90
97
  ) {
91
98
  return new PublicTxSimulator(
92
99
  db,
93
100
  worldStateDB,
94
- telemetryClient,
95
101
  globalVariables,
96
102
  doMerkleOperations,
97
103
  enforceFeePayment,
104
+ telemetryClient,
98
105
  );
99
106
  }
100
107
  }
@@ -119,7 +126,7 @@ export class PublicProcessor implements Traceable {
119
126
  protected worldStateDB: WorldStateDB,
120
127
  protected publicTxSimulator: PublicTxSimulator,
121
128
  private dateProvider: DateProvider,
122
- telemetryClient: TelemetryClient,
129
+ telemetryClient: TelemetryClient = getTelemetryClient(),
123
130
  private log = createLogger('simulator:public-processor'),
124
131
  ) {
125
132
  this.metrics = new PublicProcessorMetrics(telemetryClient, 'PublicProcessor');
@@ -290,7 +297,7 @@ export class PublicProcessor implements Traceable {
290
297
  return [result, failed, returns];
291
298
  }
292
299
 
293
- @trackSpan('PublicProcessor.processTx', tx => ({ [Attributes.TX_HASH]: tx.tryGetTxHash()?.toString() }))
300
+ @trackSpan('PublicProcessor.processTx', tx => ({ [Attributes.TX_HASH]: tx.getTxHash().toString() }))
294
301
  private async processTx(tx: Tx, deadline?: Date): Promise<[ProcessedTx, NestedProcessReturnValues[]]> {
295
302
  const [time, [processedTx, returnValues]] = await elapsed(() => this.processTxWithinDeadline(tx, deadline));
296
303
 
@@ -7,7 +7,7 @@ import {
7
7
  type SimulationError,
8
8
  type Tx,
9
9
  TxExecutionPhase,
10
- TxHash,
10
+ type TxHash,
11
11
  } from '@aztec/circuit-types';
12
12
  import {
13
13
  AvmCircuitInputs,
@@ -61,6 +61,7 @@ export class PublicTxContext {
61
61
  public avmProvingRequest: AvmProvingRequest | undefined; // FIXME(dbanks12): remove
62
62
 
63
63
  constructor(
64
+ public readonly txHash: TxHash,
64
65
  public readonly state: PhaseStateManager,
65
66
  private readonly globalVariables: GlobalVariables,
66
67
  private readonly startStateReference: StateReference,
@@ -103,12 +104,14 @@ export class PublicTxContext {
103
104
  previousAccumulatedDataArrayLengths,
104
105
  );
105
106
 
107
+ const firstNullifier = nonRevertibleAccumulatedDataFromPrivate.nullifiers[0];
108
+
106
109
  // Transaction level state manager that will be forked for revertible phases.
107
110
  const txStateManager = await AvmPersistableStateManager.create(
108
111
  worldStateDB,
109
112
  enqueuedCallTrace,
110
113
  doMerkleOperations,
111
- fetchTxHash(nonRevertibleAccumulatedDataFromPrivate),
114
+ firstNullifier,
112
115
  );
113
116
 
114
117
  const gasSettings = tx.data.constants.txContext.gasSettings;
@@ -117,6 +120,7 @@ export class PublicTxContext {
117
120
  const gasAllocatedToPublic = applyMaxToAvailableGas(gasSettings.gasLimits.sub(gasUsedByPrivate));
118
121
 
119
122
  return new PublicTxContext(
123
+ tx.getTxHash(),
120
124
  new PhaseStateManager(txStateManager),
121
125
  globalVariables,
122
126
  await db.getStateReference(),
@@ -188,14 +192,6 @@ export class PublicTxContext {
188
192
  return this.revertCode;
189
193
  }
190
194
 
191
- /**
192
- * Construct & return transaction hash.
193
- * @returns The transaction's hash.
194
- */
195
- getTxHash(): TxHash {
196
- return fetchTxHash(this.nonRevertibleAccumulatedDataFromPrivate);
197
- }
198
-
199
195
  /**
200
196
  * Are there any call requests for the speciiied phase?
201
197
  */
@@ -452,12 +448,3 @@ function applyMaxToAvailableGas(availableGas: Gas) {
452
448
  /*l2Gas=*/ Math.min(availableGas.l2Gas, MAX_L2_GAS_PER_TX_PUBLIC_PORTION),
453
449
  );
454
450
  }
455
-
456
- function fetchTxHash(nonRevertibleAccumulatedData: PrivateToPublicAccumulatedData): TxHash {
457
- // Private kernel functions are executed client side and for this reason tx hash is already set as first nullifier
458
- const firstNullifier = nonRevertibleAccumulatedData.nullifiers[0];
459
- if (!firstNullifier || firstNullifier.isZero()) {
460
- throw new Error(`Cannot get tx hash since first nullifier is missing`);
461
- }
462
- return new TxHash(firstNullifier);
463
- }
@@ -14,7 +14,7 @@ import { type Fr, type Gas, type GlobalVariables, type PublicCallRequest, type R
14
14
  import { type Logger, createLogger } from '@aztec/foundation/log';
15
15
  import { Timer } from '@aztec/foundation/timer';
16
16
  import { ProtocolContractAddress } from '@aztec/protocol-contracts';
17
- import { Attributes, type TelemetryClient, type Tracer, trackSpan } from '@aztec/telemetry-client';
17
+ import { Attributes, type TelemetryClient, type Tracer, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
18
18
 
19
19
  import { strict as assert } from 'assert';
20
20
 
@@ -53,10 +53,10 @@ export class PublicTxSimulator {
53
53
  constructor(
54
54
  private db: MerkleTreeReadOperations,
55
55
  private worldStateDB: WorldStateDB,
56
- telemetryClient: TelemetryClient,
57
56
  private globalVariables: GlobalVariables,
58
57
  private doMerkleOperations: boolean = false,
59
58
  private enforceFeePayment: boolean = true,
59
+ telemetryClient: TelemetryClient = getTelemetryClient(),
60
60
  ) {
61
61
  this.log = createLogger(`simulator:public_tx_simulator`);
62
62
  this.metrics = new ExecutorMetrics(telemetryClient, 'PublicTxSimulator');
@@ -219,8 +219,8 @@ export class PublicTxSimulator {
219
219
  const callRequests = context.getCallRequestsForPhase(phase);
220
220
  const executionRequests = context.getExecutionRequestsForPhase(phase);
221
221
 
222
- this.log.debug(`Processing phase ${TxExecutionPhase[phase]} for tx ${context.getTxHash()}`, {
223
- txHash: context.getTxHash().toString(),
222
+ this.log.debug(`Processing phase ${TxExecutionPhase[phase]} for tx ${context.txHash}`, {
223
+ txHash: context.txHash.toString(),
224
224
  phase: TxExecutionPhase[phase],
225
225
  callRequests: callRequests.length,
226
226
  executionRequests: executionRequests.length,
@@ -266,7 +266,7 @@ export class PublicTxSimulator {
266
266
  * @returns The result of execution.
267
267
  */
268
268
  @trackSpan('PublicTxSimulator.simulateEnqueuedCall', (phase, context, _callRequest, executionRequest) => ({
269
- [Attributes.TX_HASH]: context.getTxHash().toString(),
269
+ [Attributes.TX_HASH]: context.txHash.toString(),
270
270
  [Attributes.TARGET_ADDRESS]: executionRequest.callContext.contractAddress.toString(),
271
271
  [Attributes.SENDER_ADDRESS]: executionRequest.callContext.msgSender.toString(),
272
272
  [Attributes.SIMULATOR_PHASE]: TxExecutionPhase[phase].toString(),
@@ -294,7 +294,7 @@ export class PublicTxSimulator {
294
294
  const gasUsed = allocatedGas.sub(result.gasLeft); // by enqueued call
295
295
  context.consumeGas(phase, gasUsed);
296
296
  this.log.debug(
297
- `Simulated enqueued public call consumed ${gasUsed.l2Gas} L2 gas ending with ${result.gasLeft.l2Gas} L2 gas left.`,
297
+ `Simulated enqueued public call (${fnName}) consumed ${gasUsed.l2Gas} L2 gas ending with ${result.gasLeft.l2Gas} L2 gas left.`,
298
298
  );
299
299
 
300
300
  stateManager.traceEnqueuedCall(callRequest, executionRequest.args, result.reverted);
@@ -1,8 +1,5 @@
1
- export * from './acvm/index.js';
2
1
  export * from './avm/index.js';
3
- export * from './client/index.js';
4
2
  export * from './common/index.js';
5
3
  export * from './public/index.js';
6
4
  export * from './providers/index.js';
7
5
  export * from './stats/index.js';
8
- //# sourceMappingURL=index.d.ts.map
@@ -1,28 +0,0 @@
1
- import { PackedValues } from '@aztec/circuit-types';
2
- import { Fr } from '@aztec/circuits.js';
3
- /**
4
- * A cache for packed values (arguments, returns) during transaction execution.
5
- */
6
- export declare class PackedValuesCache {
7
- private cache;
8
- constructor(initialArguments?: PackedValues[]);
9
- /**
10
- * Creates a new packed values cache.
11
- * @param initialArguments - The initial arguments to add to the cache.
12
- * @returns The new packed values cache.
13
- */
14
- static create(initialArguments?: PackedValues[]): PackedValuesCache;
15
- /**
16
- * Unpacks packed values.
17
- * @param hash - The hash of the packed values.
18
- * @returns The unpacked values.
19
- */
20
- unpack(hash: Fr): Fr[];
21
- /**
22
- * Packs values.
23
- * @param values - The values to pack.
24
- * @returns The hash of the packed values.
25
- */
26
- pack(values: Fr[]): Fr;
27
- }
28
- //# sourceMappingURL=packed_values_cache.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"packed_values_cache.d.ts","sourceRoot":"","sources":["../../src/common/packed_values_cache.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,EAAE,EAAE,MAAM,oBAAoB,CAAC;AAExC;;GAEG;AACH,qBAAa,iBAAiB;IAC5B,OAAO,CAAC,KAAK,CAAoB;gBAErB,gBAAgB,GAAE,YAAY,EAAO;IAOjD;;;;OAIG;WACW,MAAM,CAAC,gBAAgB,GAAE,YAAY,EAAO;IAI1D;;;;OAIG;IACI,MAAM,CAAC,IAAI,EAAE,EAAE,GAAG,EAAE,EAAE;IAW7B;;;;OAIG;IACI,IAAI,CAAC,MAAM,EAAE,EAAE,EAAE;CAQzB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,mBAAmB,CAAC;AAClC,cAAc,mBAAmB,CAAC;AAClC,cAAc,mBAAmB,CAAC;AAClC,cAAc,sBAAsB,CAAC;AACrC,cAAc,kBAAkB,CAAC"}
package/dest/index.js DELETED
@@ -1,8 +0,0 @@
1
- export * from './acvm/index.js';
2
- export * from './avm/index.js';
3
- export * from './client/index.js';
4
- export * from './common/index.js';
5
- export * from './public/index.js';
6
- export * from './providers/index.js';
7
- export * from './stats/index.js';
8
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsY0FBYyxpQkFBaUIsQ0FBQztBQUNoQyxjQUFjLGdCQUFnQixDQUFDO0FBQy9CLGNBQWMsbUJBQW1CLENBQUM7QUFDbEMsY0FBYyxtQkFBbUIsQ0FBQztBQUNsQyxjQUFjLG1CQUFtQixDQUFDO0FBQ2xDLGNBQWMsc0JBQXNCLENBQUM7QUFDckMsY0FBYyxrQkFBa0IsQ0FBQyJ9
@@ -1,9 +0,0 @@
1
- import { type NoirCompiledCircuit } from '@aztec/types/noir';
2
- import { type WitnessMap } from '@noir-lang/types';
3
- /**
4
- * Low level simulation interface
5
- */
6
- export interface SimulationProvider {
7
- simulateCircuit(input: WitnessMap, compiledCircuit: NoirCompiledCircuit): Promise<WitnessMap>;
8
- }
9
- //# sourceMappingURL=simulation_provider.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"simulation_provider.d.ts","sourceRoot":"","sources":["../../src/providers/simulation_provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAE7D,OAAO,EAAE,KAAK,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC,eAAe,CAAC,KAAK,EAAE,UAAU,EAAE,eAAe,EAAE,mBAAmB,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;CAC/F"}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2ltdWxhdGlvbl9wcm92aWRlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wcm92aWRlcnMvc2ltdWxhdGlvbl9wcm92aWRlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiIn0=
@@ -1,55 +0,0 @@
1
- import { PackedValues } from '@aztec/circuit-types';
2
- import { Fr } from '@aztec/circuits.js';
3
-
4
- /**
5
- * A cache for packed values (arguments, returns) during transaction execution.
6
- */
7
- export class PackedValuesCache {
8
- private cache: Map<bigint, Fr[]>;
9
-
10
- constructor(initialArguments: PackedValues[] = []) {
11
- this.cache = new Map();
12
- for (const initialArg of initialArguments) {
13
- this.cache.set(initialArg.hash.toBigInt(), initialArg.values);
14
- }
15
- }
16
-
17
- /**
18
- * Creates a new packed values cache.
19
- * @param initialArguments - The initial arguments to add to the cache.
20
- * @returns The new packed values cache.
21
- */
22
- public static create(initialArguments: PackedValues[] = []) {
23
- return new PackedValuesCache(initialArguments);
24
- }
25
-
26
- /**
27
- * Unpacks packed values.
28
- * @param hash - The hash of the packed values.
29
- * @returns The unpacked values.
30
- */
31
- public unpack(hash: Fr): Fr[] {
32
- if (hash.equals(Fr.ZERO)) {
33
- return [];
34
- }
35
- const packedValues = this.cache.get(hash.value);
36
- if (!packedValues) {
37
- throw new Error(`Packed values for hash ${hash.toString()} not found in cache`);
38
- }
39
- return packedValues;
40
- }
41
-
42
- /**
43
- * Packs values.
44
- * @param values - The values to pack.
45
- * @returns The hash of the packed values.
46
- */
47
- public pack(values: Fr[]) {
48
- if (values.length === 0) {
49
- return Fr.ZERO;
50
- }
51
- const packedValues = PackedValues.fromValues(values);
52
- this.cache.set(packedValues.hash.value, packedValues.values);
53
- return packedValues.hash;
54
- }
55
- }