@aztec/simulator 0.42.0 → 0.44.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 (191) hide show
  1. package/dest/acvm/oracle/oracle.d.ts +5 -2
  2. package/dest/acvm/oracle/oracle.d.ts.map +1 -1
  3. package/dest/acvm/oracle/oracle.js +25 -8
  4. package/dest/acvm/oracle/typed_oracle.d.ts +7 -4
  5. package/dest/acvm/oracle/typed_oracle.d.ts.map +1 -1
  6. package/dest/acvm/oracle/typed_oracle.js +14 -5
  7. package/dest/avm/avm_execution_environment.d.ts +2 -0
  8. package/dest/avm/avm_execution_environment.d.ts.map +1 -1
  9. package/dest/avm/avm_execution_environment.js +9 -4
  10. package/dest/avm/avm_gas.d.ts.map +1 -1
  11. package/dest/avm/avm_gas.js +3 -1
  12. package/dest/avm/avm_memory_types.d.ts.map +1 -1
  13. package/dest/avm/avm_memory_types.js +2 -4
  14. package/dest/avm/avm_simulator.d.ts.map +1 -1
  15. package/dest/avm/avm_simulator.js +2 -3
  16. package/dest/avm/fixtures/index.d.ts +10 -3
  17. package/dest/avm/fixtures/index.d.ts.map +1 -1
  18. package/dest/avm/fixtures/index.js +9 -11
  19. package/dest/avm/journal/journal.d.ts +57 -66
  20. package/dest/avm/journal/journal.d.ts.map +1 -1
  21. package/dest/avm/journal/journal.js +97 -131
  22. package/dest/avm/journal/nullifiers.d.ts +21 -8
  23. package/dest/avm/journal/nullifiers.d.ts.map +1 -1
  24. package/dest/avm/journal/nullifiers.js +26 -8
  25. package/dest/avm/journal/public_storage.d.ts +4 -0
  26. package/dest/avm/journal/public_storage.d.ts.map +1 -1
  27. package/dest/avm/journal/public_storage.js +10 -1
  28. package/dest/avm/opcodes/accrued_substate.d.ts +2 -2
  29. package/dest/avm/opcodes/accrued_substate.d.ts.map +1 -1
  30. package/dest/avm/opcodes/accrued_substate.js +39 -24
  31. package/dest/avm/opcodes/arithmetic.d.ts.map +1 -1
  32. package/dest/avm/opcodes/arithmetic.js +12 -9
  33. package/dest/avm/opcodes/bitwise.d.ts.map +1 -1
  34. package/dest/avm/opcodes/bitwise.js +11 -8
  35. package/dest/avm/opcodes/comparators.d.ts.map +1 -1
  36. package/dest/avm/opcodes/comparators.js +7 -5
  37. package/dest/avm/opcodes/contract.d.ts.map +1 -1
  38. package/dest/avm/opcodes/contract.js +20 -24
  39. package/dest/avm/opcodes/control_flow.d.ts.map +1 -1
  40. package/dest/avm/opcodes/control_flow.js +4 -2
  41. package/dest/avm/opcodes/ec_add.d.ts +19 -0
  42. package/dest/avm/opcodes/ec_add.d.ts.map +1 -0
  43. package/dest/avm/opcodes/ec_add.js +78 -0
  44. package/dest/avm/opcodes/external_calls.d.ts.map +1 -1
  45. package/dest/avm/opcodes/external_calls.js +19 -29
  46. package/dest/avm/opcodes/hashing.d.ts.map +1 -1
  47. package/dest/avm/opcodes/hashing.js +10 -2
  48. package/dest/avm/opcodes/instruction_impl.d.ts.map +1 -1
  49. package/dest/avm/opcodes/instruction_impl.js +4 -2
  50. package/dest/avm/opcodes/memory.d.ts +1 -1
  51. package/dest/avm/opcodes/memory.d.ts.map +1 -1
  52. package/dest/avm/opcodes/memory.js +14 -12
  53. package/dest/avm/opcodes/multi_scalar_mul.d.ts +16 -0
  54. package/dest/avm/opcodes/multi_scalar_mul.d.ts.map +1 -0
  55. package/dest/avm/opcodes/multi_scalar_mul.js +95 -0
  56. package/dest/avm/opcodes/storage.d.ts +1 -1
  57. package/dest/avm/opcodes/storage.d.ts.map +1 -1
  58. package/dest/avm/opcodes/storage.js +11 -8
  59. package/dest/avm/serialization/bytecode_serialization.d.ts.map +1 -1
  60. package/dest/avm/serialization/bytecode_serialization.js +5 -1
  61. package/dest/avm/serialization/instruction_serialization.d.ts +3 -1
  62. package/dest/avm/serialization/instruction_serialization.d.ts.map +1 -1
  63. package/dest/avm/serialization/instruction_serialization.js +4 -2
  64. package/dest/avm/test_utils.d.ts +14 -0
  65. package/dest/avm/test_utils.d.ts.map +1 -0
  66. package/dest/avm/test_utils.js +36 -0
  67. package/dest/client/client_execution_context.d.ts +17 -5
  68. package/dest/client/client_execution_context.d.ts.map +1 -1
  69. package/dest/client/client_execution_context.js +32 -18
  70. package/dest/client/execution_note_cache.d.ts.map +1 -1
  71. package/dest/client/execution_note_cache.js +1 -1
  72. package/dest/client/execution_result.d.ts +2 -1
  73. package/dest/client/execution_result.d.ts.map +1 -1
  74. package/dest/client/execution_result.js +1 -1
  75. package/dest/client/index.d.ts +2 -0
  76. package/dest/client/index.d.ts.map +1 -1
  77. package/dest/client/index.js +3 -1
  78. package/dest/client/simulator.d.ts +4 -3
  79. package/dest/client/simulator.d.ts.map +1 -1
  80. package/dest/client/simulator.js +17 -9
  81. package/dest/client/view_data_oracle.d.ts +2 -0
  82. package/dest/client/view_data_oracle.d.ts.map +1 -1
  83. package/dest/client/view_data_oracle.js +7 -1
  84. package/dest/mocks/fixtures.d.ts.map +1 -1
  85. package/dest/mocks/fixtures.js +3 -2
  86. package/dest/public/abstract_phase_manager.d.ts +11 -11
  87. package/dest/public/abstract_phase_manager.d.ts.map +1 -1
  88. package/dest/public/abstract_phase_manager.js +84 -59
  89. package/dest/public/app_logic_phase_manager.d.ts +3 -3
  90. package/dest/public/app_logic_phase_manager.d.ts.map +1 -1
  91. package/dest/public/app_logic_phase_manager.js +4 -3
  92. package/dest/public/db_interfaces.d.ts +1 -0
  93. package/dest/public/db_interfaces.d.ts.map +1 -1
  94. package/dest/public/execution.d.ts +28 -40
  95. package/dest/public/execution.d.ts.map +1 -1
  96. package/dest/public/execution.js +1 -51
  97. package/dest/public/executor.d.ts +9 -4
  98. package/dest/public/executor.d.ts.map +1 -1
  99. package/dest/public/executor.js +38 -27
  100. package/dest/public/hints_builder.d.ts +1 -1
  101. package/dest/public/index.d.ts +6 -6
  102. package/dest/public/index.d.ts.map +1 -1
  103. package/dest/public/index.js +7 -7
  104. package/dest/public/phase_manager_factory.d.ts +3 -3
  105. package/dest/public/phase_manager_factory.d.ts.map +1 -1
  106. package/dest/public/phase_manager_factory.js +5 -5
  107. package/dest/public/public_db_sources.d.ts +3 -1
  108. package/dest/public/public_db_sources.d.ts.map +1 -1
  109. package/dest/public/public_db_sources.js +54 -8
  110. package/dest/public/public_processor.d.ts +5 -2
  111. package/dest/public/public_processor.d.ts.map +1 -1
  112. package/dest/public/public_processor.js +143 -125
  113. package/dest/public/setup_phase_manager.d.ts +3 -3
  114. package/dest/public/setup_phase_manager.d.ts.map +1 -1
  115. package/dest/public/setup_phase_manager.js +3 -3
  116. package/dest/public/side_effect_trace.d.ts +86 -0
  117. package/dest/public/side_effect_trace.d.ts.map +1 -0
  118. package/dest/public/side_effect_trace.js +222 -0
  119. package/dest/public/side_effect_trace_interface.d.ts +36 -0
  120. package/dest/public/side_effect_trace_interface.d.ts.map +1 -0
  121. package/dest/public/side_effect_trace_interface.js +2 -0
  122. package/dest/public/tail_phase_manager.d.ts +3 -3
  123. package/dest/public/tail_phase_manager.d.ts.map +1 -1
  124. package/dest/public/tail_phase_manager.js +3 -3
  125. package/dest/public/teardown_phase_manager.d.ts +3 -3
  126. package/dest/public/teardown_phase_manager.d.ts.map +1 -1
  127. package/dest/public/teardown_phase_manager.js +4 -3
  128. package/dest/public/transitional_adaptors.d.ts +2 -6
  129. package/dest/public/transitional_adaptors.d.ts.map +1 -1
  130. package/dest/public/transitional_adaptors.js +1 -43
  131. package/package.json +18 -9
  132. package/src/acvm/oracle/oracle.ts +46 -9
  133. package/src/acvm/oracle/typed_oracle.ts +37 -7
  134. package/src/avm/avm_execution_environment.ts +10 -3
  135. package/src/avm/avm_gas.ts +2 -0
  136. package/src/avm/avm_memory_types.ts +1 -3
  137. package/src/avm/avm_simulator.ts +2 -3
  138. package/src/avm/fixtures/index.ts +19 -14
  139. package/src/avm/journal/journal.ts +127 -231
  140. package/src/avm/journal/nullifiers.ts +30 -13
  141. package/src/avm/journal/public_storage.ts +10 -0
  142. package/src/avm/opcodes/accrued_substate.ts +60 -23
  143. package/src/avm/opcodes/arithmetic.ts +17 -8
  144. package/src/avm/opcodes/bitwise.ts +13 -8
  145. package/src/avm/opcodes/comparators.ts +9 -4
  146. package/src/avm/opcodes/contract.ts +22 -26
  147. package/src/avm/opcodes/control_flow.ts +3 -1
  148. package/src/avm/opcodes/ec_add.ts +92 -0
  149. package/src/avm/opcodes/external_calls.ts +20 -36
  150. package/src/avm/opcodes/hashing.ts +11 -1
  151. package/src/avm/opcodes/instruction_impl.ts +4 -1
  152. package/src/avm/opcodes/memory.ts +18 -11
  153. package/src/avm/opcodes/multi_scalar_mul.ts +114 -0
  154. package/src/avm/opcodes/storage.ts +10 -10
  155. package/src/avm/serialization/bytecode_serialization.ts +4 -0
  156. package/src/avm/serialization/instruction_serialization.ts +2 -0
  157. package/src/avm/test_utils.ts +53 -0
  158. package/src/client/client_execution_context.ts +55 -21
  159. package/src/client/execution_note_cache.ts +0 -1
  160. package/src/client/execution_result.ts +2 -1
  161. package/src/client/index.ts +2 -0
  162. package/src/client/simulator.ts +26 -10
  163. package/src/client/view_data_oracle.ts +8 -0
  164. package/src/mocks/fixtures.ts +2 -1
  165. package/src/public/abstract_phase_manager.ts +99 -70
  166. package/src/public/app_logic_phase_manager.ts +3 -2
  167. package/src/public/db_interfaces.ts +2 -0
  168. package/src/public/execution.ts +35 -94
  169. package/src/public/executor.ts +56 -40
  170. package/src/public/index.ts +6 -12
  171. package/src/public/phase_manager_factory.ts +6 -6
  172. package/src/public/public_db_sources.ts +62 -7
  173. package/src/public/public_processor.ts +15 -9
  174. package/src/public/setup_phase_manager.ts +2 -2
  175. package/src/public/side_effect_trace.ts +323 -0
  176. package/src/public/side_effect_trace_interface.ts +41 -0
  177. package/src/public/tail_phase_manager.ts +2 -2
  178. package/src/public/teardown_phase_manager.ts +3 -2
  179. package/src/public/transitional_adaptors.ts +2 -60
  180. package/dest/avm/journal/trace.d.ts +0 -33
  181. package/dest/avm/journal/trace.d.ts.map +0 -1
  182. package/dest/avm/journal/trace.js +0 -151
  183. package/dest/avm/journal/trace_types.d.ts +0 -51
  184. package/dest/avm/journal/trace_types.d.ts.map +0 -1
  185. package/dest/avm/journal/trace_types.js +0 -6
  186. package/dest/public/utils.d.ts +0 -8
  187. package/dest/public/utils.d.ts.map +0 -1
  188. package/dest/public/utils.js +0 -38
  189. package/src/avm/journal/trace.ts +0 -184
  190. package/src/avm/journal/trace_types.ts +0 -88
  191. package/src/public/utils.ts +0 -39
@@ -1,16 +1,10 @@
1
+ export * from './abstract_phase_manager.js';
1
2
  export * from './db_interfaces.js';
2
- export {
3
- type PublicExecution,
4
- type PublicExecutionResult,
5
- isPublicExecutionResult,
6
- collectPublicDataReads,
7
- collectPublicDataUpdateRequests,
8
- } from './execution.js';
3
+ export { isPublicExecutionResult, type PublicExecution, type PublicExecutionResult } from './execution.js';
9
4
  export { PublicExecutor } from './executor.js';
10
- export { PublicProcessor, PublicProcessorFactory } from './public_processor.js';
5
+ export * from './fee_payment.js';
6
+ export { HintsBuilder } from './hints_builder.js';
11
7
  export * from './public_db_sources.js';
12
- export * from './abstract_phase_manager.js';
13
- export * from './public_kernel_circuit_simulator.js';
14
8
  export * from './public_kernel.js';
15
- export { HintsBuilder } from './hints_builder.js';
16
- export * from './fee_payment.js';
9
+ export * from './public_kernel_circuit_simulator.js';
10
+ export { PublicProcessor, PublicProcessorFactory } from './public_processor.js';
@@ -1,9 +1,9 @@
1
- import { type Tx } from '@aztec/circuit-types';
1
+ import { PublicKernelType, type Tx } from '@aztec/circuit-types';
2
2
  import { type GlobalVariables, type Header, type PublicKernelCircuitPublicInputs } from '@aztec/circuits.js';
3
3
  import { type PublicExecutor, type PublicStateDB } from '@aztec/simulator';
4
4
  import { type MerkleTreeOperations } from '@aztec/world-state';
5
5
 
6
- import { type AbstractPhaseManager, PublicKernelPhase } from './abstract_phase_manager.js';
6
+ import { type AbstractPhaseManager } from './abstract_phase_manager.js';
7
7
  import { AppLogicPhaseManager } from './app_logic_phase_manager.js';
8
8
  import { type ContractsDataSourcePublicDB } from './public_db_sources.js';
9
9
  import { type PublicKernelCircuitSimulator } from './public_kernel_circuit_simulator.js';
@@ -12,7 +12,7 @@ import { TailPhaseManager } from './tail_phase_manager.js';
12
12
  import { TeardownPhaseManager } from './teardown_phase_manager.js';
13
13
 
14
14
  export class PhaseDidNotChangeError extends Error {
15
- constructor(phase: PublicKernelPhase) {
15
+ constructor(phase: PublicKernelType) {
16
16
  super(`Tried to advance the phase from [${phase}] when the circuit still needs [${phase}]`);
17
17
  }
18
18
  }
@@ -84,7 +84,7 @@ export class PhaseManagerFactory {
84
84
  if (output.needsSetup) {
85
85
  throw new CannotTransitionToSetupError();
86
86
  } else if (output.needsAppLogic) {
87
- if (currentPhaseManager.phase === PublicKernelPhase.APP_LOGIC) {
87
+ if (currentPhaseManager.phase === PublicKernelType.APP_LOGIC) {
88
88
  throw new PhaseDidNotChangeError(currentPhaseManager.phase);
89
89
  }
90
90
  return new AppLogicPhaseManager(
@@ -97,7 +97,7 @@ export class PhaseManagerFactory {
97
97
  publicStateDB,
98
98
  );
99
99
  } else if (output.needsTeardown) {
100
- if (currentPhaseManager.phase === PublicKernelPhase.TEARDOWN) {
100
+ if (currentPhaseManager.phase === PublicKernelType.TEARDOWN) {
101
101
  throw new PhaseDidNotChangeError(currentPhaseManager.phase);
102
102
  }
103
103
  return new TeardownPhaseManager(
@@ -109,7 +109,7 @@ export class PhaseManagerFactory {
109
109
  publicContractsDB,
110
110
  publicStateDB,
111
111
  );
112
- } else if (currentPhaseManager.phase !== PublicKernelPhase.TAIL) {
112
+ } else if (currentPhaseManager.phase !== PublicKernelType.TAIL) {
113
113
  return new TailPhaseManager(
114
114
  db,
115
115
  publicExecutor,
@@ -1,10 +1,11 @@
1
1
  import { MerkleTreeId, NullifierMembershipWitness, type Tx } from '@aztec/circuit-types';
2
+ import { type PublicDBAccessStats } from '@aztec/circuit-types/stats';
2
3
  import {
3
4
  type AztecAddress,
4
5
  ContractClassRegisteredEvent,
5
6
  ContractInstanceDeployedEvent,
6
7
  Fr,
7
- type FunctionSelector,
8
+ FunctionSelector,
8
9
  type L1_TO_L2_MSG_TREE_HEIGHT,
9
10
  type NULLIFIER_TREE_HEIGHT,
10
11
  type NullifierLeafPreimage,
@@ -12,7 +13,8 @@ import {
12
13
  } from '@aztec/circuits.js';
13
14
  import { computeL1ToL2MessageNullifier, computePublicDataTreeLeafSlot } from '@aztec/circuits.js/hash';
14
15
  import { createDebugLogger } from '@aztec/foundation/log';
15
- import { getCanonicalClassRegistererAddress } from '@aztec/protocol-contracts/class-registerer';
16
+ import { Timer } from '@aztec/foundation/timer';
17
+ import { ClassRegistererAddress } from '@aztec/protocol-contracts/class-registerer';
16
18
  import {
17
19
  type CommitmentsDB,
18
20
  MessageLoadOracleInputs,
@@ -45,7 +47,7 @@ export class ContractsDataSourcePublicDB implements PublicContractsDB {
45
47
  public addNewContracts(tx: Tx): Promise<void> {
46
48
  // Extract contract class and instance data from logs and add to cache for this block
47
49
  const logs = tx.unencryptedLogs.unrollLogs();
48
- ContractClassRegisteredEvent.fromLogs(logs, getCanonicalClassRegistererAddress()).forEach(e => {
50
+ ContractClassRegisteredEvent.fromLogs(logs, ClassRegistererAddress).forEach(e => {
49
51
  this.log.debug(`Adding class ${e.contractClassId.toString()} to public execution contract cache`);
50
52
  this.classCache.set(e.contractClassId.toString(), e.toContractClassPublic());
51
53
  });
@@ -68,7 +70,7 @@ export class ContractsDataSourcePublicDB implements PublicContractsDB {
68
70
  // Let's say we have two txs adding the same contract on the same block. If the 2nd one reverts,
69
71
  // wouldn't that accidentally remove the contract added on the first one?
70
72
  const logs = tx.unencryptedLogs.unrollLogs();
71
- ContractClassRegisteredEvent.fromLogs(logs, getCanonicalClassRegistererAddress()).forEach(e =>
73
+ ContractClassRegisteredEvent.fromLogs(logs, ClassRegistererAddress).forEach(e =>
72
74
  this.classCache.delete(e.contractClassId.toString()),
73
75
  );
74
76
  ContractInstanceDeployedEvent.fromLogs(logs).forEach(e => this.instanceCache.delete(e.address.toString()));
@@ -94,6 +96,22 @@ export class ContractsDataSourcePublicDB implements PublicContractsDB {
94
96
  }
95
97
  return contractClass.publicFunctions.find(f => f.selector.equals(selector))?.bytecode;
96
98
  }
99
+
100
+ public async getDebugFunctionName(address: AztecAddress, selector: FunctionSelector): Promise<string | undefined> {
101
+ const artifact = await this.db.getContractArtifact(address);
102
+ if (!artifact) {
103
+ return Promise.resolve(undefined);
104
+ }
105
+
106
+ const f = artifact.functions.find(f =>
107
+ FunctionSelector.fromNameAndParameters(f.name, f.parameters).equals(selector),
108
+ );
109
+ if (!f) {
110
+ return Promise.resolve(undefined);
111
+ }
112
+
113
+ return Promise.resolve(`${artifact.name}:${f.name}`);
114
+ }
97
115
  }
98
116
 
99
117
  /**
@@ -196,11 +214,14 @@ export class WorldStatePublicDB implements PublicStateDB {
196
214
  * Implements WorldState db using a world state database.
197
215
  */
198
216
  export class WorldStateDB implements CommitmentsDB {
217
+ private log = createDebugLogger('aztec:sequencer:world-state-db');
218
+
199
219
  constructor(private db: MerkleTreeOperations) {}
200
220
 
201
221
  public async getNullifierMembershipWitnessAtLatestBlock(
202
222
  nullifier: Fr,
203
223
  ): Promise<NullifierMembershipWitness | undefined> {
224
+ const timer = new Timer();
204
225
  const index = await this.db.findLeafIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBuffer());
205
226
  if (!index) {
206
227
  return undefined;
@@ -218,6 +239,12 @@ export class WorldStateDB implements CommitmentsDB {
218
239
  return undefined;
219
240
  }
220
241
 
242
+ this.log.debug(`[DB] Fetched nullifier membership`, {
243
+ eventName: 'public-db-access',
244
+ duration: timer.ms(),
245
+ operation: 'get-nullifier-membership-witness-at-latest-block',
246
+ } satisfies PublicDBAccessStats);
247
+
221
248
  return new NullifierMembershipWitness(BigInt(index), leafPreimage as NullifierLeafPreimage, siblingPath);
222
249
  }
223
250
 
@@ -232,6 +259,7 @@ export class WorldStateDB implements CommitmentsDB {
232
259
 
233
260
  // We iterate over messages until we find one whose nullifier is not in the nullifier tree --> we need to check
234
261
  // for nullifiers because messages can have duplicates.
262
+ const timer = new Timer();
235
263
  do {
236
264
  messageIndex = (await this.db.findLeafIndexAfter(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, messageHash, startIndex))!;
237
265
  if (messageIndex === undefined) {
@@ -249,18 +277,45 @@ export class WorldStateDB implements CommitmentsDB {
249
277
  messageIndex,
250
278
  );
251
279
 
280
+ this.log.debug(`[DB] Fetched L1 to L2 message membership`, {
281
+ eventName: 'public-db-access',
282
+ duration: timer.ms(),
283
+ operation: 'get-l1-to-l2-message-membership-witness',
284
+ } satisfies PublicDBAccessStats);
285
+
252
286
  return new MessageLoadOracleInputs<typeof L1_TO_L2_MSG_TREE_HEIGHT>(messageIndex, siblingPath);
253
287
  }
254
288
 
255
289
  public async getL1ToL2LeafValue(leafIndex: bigint): Promise<Fr | undefined> {
256
- return await this.db.getLeafValue(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, leafIndex);
290
+ const timer = new Timer();
291
+ const leafValue = await this.db.getLeafValue(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, leafIndex);
292
+ this.log.debug(`[DB] Fetched L1 to L2 message leaf value`, {
293
+ eventName: 'public-db-access',
294
+ duration: timer.ms(),
295
+ operation: 'get-l1-to-l2-message-leaf-value',
296
+ } satisfies PublicDBAccessStats);
297
+ return leafValue;
257
298
  }
258
299
 
259
300
  public async getCommitmentIndex(commitment: Fr): Promise<bigint | undefined> {
260
- return await this.db.findLeafIndex(MerkleTreeId.NOTE_HASH_TREE, commitment);
301
+ const timer = new Timer();
302
+ const index = await this.db.findLeafIndex(MerkleTreeId.NOTE_HASH_TREE, commitment);
303
+ this.log.debug(`[DB] Fetched commitment index`, {
304
+ eventName: 'public-db-access',
305
+ duration: timer.ms(),
306
+ operation: 'get-commitment-index',
307
+ } satisfies PublicDBAccessStats);
308
+ return index;
261
309
  }
262
310
 
263
311
  public async getNullifierIndex(nullifier: Fr): Promise<bigint | undefined> {
264
- return await this.db.findLeafIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBuffer());
312
+ const timer = new Timer();
313
+ const index = await this.db.findLeafIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBuffer());
314
+ this.log.debug(`[DB] Fetched nullifier index`, {
315
+ eventName: 'public-db-access',
316
+ duration: timer.ms(),
317
+ operation: 'get-nullifier-index',
318
+ } satisfies PublicDBAccessStats);
319
+ return index;
265
320
  }
266
321
  }
@@ -3,6 +3,7 @@ import {
3
3
  type FailedTx,
4
4
  NestedProcessReturnValues,
5
5
  type ProcessedTx,
6
+ PublicKernelType,
6
7
  type PublicProvingRequest,
7
8
  type SimulationError,
8
9
  Tx,
@@ -29,14 +30,11 @@ import {
29
30
  computeFeePayerBalanceLeafSlot,
30
31
  computeFeePayerBalanceStorageSlot,
31
32
  } from '@aztec/simulator';
33
+ import { Attributes, type TelemetryClient, type Tracer, trackSpan } from '@aztec/telemetry-client';
32
34
  import { type ContractDataSource } from '@aztec/types/contracts';
33
35
  import { type MerkleTreeOperations } from '@aztec/world-state';
34
36
 
35
- import {
36
- type AbstractPhaseManager,
37
- PublicKernelPhase,
38
- publicKernelPhaseToKernelType,
39
- } from './abstract_phase_manager.js';
37
+ import { type AbstractPhaseManager } from './abstract_phase_manager.js';
40
38
  import { PhaseManagerFactory } from './phase_manager_factory.js';
41
39
  import { ContractsDataSourcePublicDB, WorldStateDB, WorldStatePublicDB } from './public_db_sources.js';
42
40
  import { RealPublicKernelCircuitSimulator } from './public_kernel.js';
@@ -50,6 +48,7 @@ export class PublicProcessorFactory {
50
48
  private merkleTree: MerkleTreeOperations,
51
49
  private contractDataSource: ContractDataSource,
52
50
  private simulator: SimulationProvider,
51
+ private telemetryClient: TelemetryClient,
53
52
  ) {}
54
53
 
55
54
  /**
@@ -77,6 +76,7 @@ export class PublicProcessorFactory {
77
76
  historicalHeader,
78
77
  publicContractsDB,
79
78
  worldStatePublicDB,
79
+ this.telemetryClient,
80
80
  );
81
81
  }
82
82
  }
@@ -86,6 +86,7 @@ export class PublicProcessorFactory {
86
86
  * any public function calls in them. Txs with private calls only are unaffected.
87
87
  */
88
88
  export class PublicProcessor {
89
+ public readonly tracer: Tracer;
89
90
  constructor(
90
91
  protected db: MerkleTreeOperations,
91
92
  protected publicExecutor: PublicExecutor,
@@ -94,9 +95,11 @@ export class PublicProcessor {
94
95
  protected historicalHeader: Header,
95
96
  protected publicContractsDB: ContractsDataSourcePublicDB,
96
97
  protected publicStateDB: PublicStateDB,
97
-
98
+ telemetryClient: TelemetryClient,
98
99
  private log = createDebugLogger('aztec:sequencer:public-processor'),
99
- ) {}
100
+ ) {
101
+ this.tracer = telemetryClient.getTracer('PublicProcessor');
102
+ }
100
103
 
101
104
  /**
102
105
  * Run each tx through the public circuit and the public kernel circuit if needed.
@@ -211,6 +214,9 @@ export class PublicProcessor {
211
214
  return finalPublicDataUpdateRequests;
212
215
  }
213
216
 
217
+ @trackSpan('PublicProcessor.processTxWithPublicCalls', tx => ({
218
+ [Attributes.TX_HASH]: tx.getTxHash().toString(),
219
+ }))
214
220
  private async processTxWithPublicCalls(tx: Tx): Promise<[ProcessedTx, NestedProcessReturnValues[]]> {
215
221
  let returnValues: NestedProcessReturnValues[] = [];
216
222
  const publicProvingRequests: PublicProvingRequest[] = [];
@@ -231,8 +237,8 @@ export class PublicProcessor {
231
237
  const gasUsed: ProcessedTx['gasUsed'] = {};
232
238
  while (phase) {
233
239
  const output = await phase.handle(tx, publicKernelPublicInput);
234
- gasUsed[publicKernelPhaseToKernelType(phase.phase)] = output.gasUsed;
235
- if (phase.phase === PublicKernelPhase.APP_LOGIC) {
240
+ gasUsed[phase.phase] = output.gasUsed;
241
+ if (phase.phase === PublicKernelType.APP_LOGIC) {
236
242
  returnValues = output.returnValues;
237
243
  }
238
244
  publicProvingRequests.push(...output.publicProvingRequests);
@@ -3,7 +3,7 @@ import { type GlobalVariables, type Header, type PublicKernelCircuitPublicInputs
3
3
  import { type PublicExecutor, type PublicStateDB } from '@aztec/simulator';
4
4
  import { type MerkleTreeOperations } from '@aztec/world-state';
5
5
 
6
- import { AbstractPhaseManager, PublicKernelPhase, makeAvmProvingRequest } from './abstract_phase_manager.js';
6
+ import { AbstractPhaseManager, makeAvmProvingRequest } from './abstract_phase_manager.js';
7
7
  import { type ContractsDataSourcePublicDB } from './public_db_sources.js';
8
8
  import { type PublicKernelCircuitSimulator } from './public_kernel_circuit_simulator.js';
9
9
 
@@ -19,7 +19,7 @@ export class SetupPhaseManager extends AbstractPhaseManager {
19
19
  historicalHeader: Header,
20
20
  protected publicContractsDB: ContractsDataSourcePublicDB,
21
21
  protected publicStateDB: PublicStateDB,
22
- phase: PublicKernelPhase = PublicKernelPhase.SETUP,
22
+ phase: PublicKernelType = PublicKernelType.SETUP,
23
23
  ) {
24
24
  super(db, publicExecutor, publicKernel, globalVariables, historicalHeader, phase);
25
25
  }
@@ -0,0 +1,323 @@
1
+ import { UnencryptedFunctionL2Logs, UnencryptedL2Log } from '@aztec/circuit-types';
2
+ import {
3
+ AvmContractInstanceHint,
4
+ AvmExecutionHints,
5
+ AvmExternalCallHint,
6
+ AvmKeyValueHint,
7
+ AztecAddress,
8
+ CallContext,
9
+ ContractStorageRead,
10
+ ContractStorageUpdateRequest,
11
+ EthAddress,
12
+ Gas,
13
+ L2ToL1Message,
14
+ LogHash,
15
+ NoteHash,
16
+ Nullifier,
17
+ ReadRequest,
18
+ } from '@aztec/circuits.js';
19
+ import { EventSelector } from '@aztec/foundation/abi';
20
+ import { Fr } from '@aztec/foundation/fields';
21
+ import { type ContractInstanceWithAddress } from '@aztec/types/contracts';
22
+
23
+ import { type AvmExecutionEnvironment } from '../avm/avm_execution_environment.js';
24
+ import { type AvmContractCallResults } from '../avm/avm_message_call_result.js';
25
+ import { createSimulationError } from '../common/errors.js';
26
+ import { type PublicExecution, type PublicExecutionResult } from './execution.js';
27
+ import { type PublicSideEffectTraceInterface } from './side_effect_trace_interface.js';
28
+
29
+ export type TracedContractInstance = { exists: boolean } & ContractInstanceWithAddress;
30
+
31
+ export class PublicSideEffectTrace implements PublicSideEffectTraceInterface {
32
+ /** The side effect counter increments with every call to the trace. */
33
+ private sideEffectCounter: number; // kept as number until finalized for efficiency
34
+
35
+ private contractStorageReads: ContractStorageRead[] = [];
36
+ private contractStorageUpdateRequests: ContractStorageUpdateRequest[] = [];
37
+
38
+ private noteHashReadRequests: ReadRequest[] = [];
39
+ private newNoteHashes: NoteHash[] = [];
40
+
41
+ private nullifierReadRequests: ReadRequest[] = [];
42
+ private nullifierNonExistentReadRequests: ReadRequest[] = [];
43
+ private newNullifiers: Nullifier[] = [];
44
+
45
+ private l1ToL2MsgReadRequests: ReadRequest[] = [];
46
+ private newL2ToL1Messages: L2ToL1Message[] = [];
47
+
48
+ private unencryptedLogs: UnencryptedL2Log[] = [];
49
+ private allUnencryptedLogs: UnencryptedL2Log[] = [];
50
+ private unencryptedLogsHashes: LogHash[] = [];
51
+
52
+ private gotContractInstances: ContractInstanceWithAddress[] = [];
53
+
54
+ private nestedExecutions: PublicExecutionResult[] = [];
55
+
56
+ private avmCircuitHints: AvmExecutionHints;
57
+
58
+ constructor(
59
+ /** The counter of this trace's first side effect. */
60
+ public readonly startSideEffectCounter: number = 0,
61
+ ) {
62
+ this.sideEffectCounter = startSideEffectCounter;
63
+ this.avmCircuitHints = AvmExecutionHints.empty();
64
+ }
65
+
66
+ public fork() {
67
+ return new PublicSideEffectTrace(this.sideEffectCounter);
68
+ }
69
+
70
+ public getCounter() {
71
+ return this.sideEffectCounter;
72
+ }
73
+
74
+ private incrementSideEffectCounter() {
75
+ this.sideEffectCounter++;
76
+ }
77
+
78
+ public tracePublicStorageRead(storageAddress: Fr, slot: Fr, value: Fr, _exists: boolean, _cached: boolean) {
79
+ // TODO(4805): check if some threshold is reached for max storage reads
80
+ // (need access to parent length, or trace needs to be initialized with parent's contents)
81
+ // NOTE: exists and cached are unused for now but may be used for optimizations or kernel hints later
82
+ this.contractStorageReads.push(
83
+ new ContractStorageRead(slot, value, this.sideEffectCounter, AztecAddress.fromField(storageAddress)),
84
+ );
85
+ this.avmCircuitHints.storageValues.items.push(
86
+ new AvmKeyValueHint(/*key=*/ new Fr(this.sideEffectCounter), /*value=*/ value),
87
+ );
88
+ this.incrementSideEffectCounter();
89
+ }
90
+
91
+ public tracePublicStorageWrite(storageAddress: Fr, slot: Fr, value: Fr) {
92
+ // TODO(4805): check if some threshold is reached for max storage writes
93
+ // (need access to parent length, or trace needs to be initialized with parent's contents)
94
+ this.contractStorageUpdateRequests.push(
95
+ new ContractStorageUpdateRequest(slot, value, this.sideEffectCounter, storageAddress),
96
+ );
97
+ this.incrementSideEffectCounter();
98
+ }
99
+
100
+ public traceNoteHashCheck(_storageAddress: Fr, noteHash: Fr, _leafIndex: Fr, exists: boolean) {
101
+ // TODO(4805): check if some threshold is reached for max note hash checks
102
+ // NOTE: storageAddress is unused but will be important when an AVM circuit processes an entire enqueued call
103
+ // TODO(dbanks12): leafIndex is unused for now but later must be used by kernel to constrain that the kernel
104
+ // is in fact checking the leaf indicated by the user
105
+ this.noteHashReadRequests.push(new ReadRequest(noteHash, this.sideEffectCounter));
106
+ this.avmCircuitHints.noteHashExists.items.push(
107
+ new AvmKeyValueHint(/*key=*/ new Fr(this.sideEffectCounter), /*value=*/ new Fr(exists ? 1 : 0)),
108
+ );
109
+ this.incrementSideEffectCounter();
110
+ }
111
+
112
+ public traceNewNoteHash(_storageAddress: Fr, noteHash: Fr) {
113
+ // TODO(4805): check if some threshold is reached for max new note hash
114
+ // NOTE: storageAddress is unused but will be important when an AVM circuit processes an entire enqueued call
115
+ // TODO(dbanks12): non-existent note hashes should emit a read request of the note hash that actually
116
+ // IS there, and the AVM circuit should accept THAT noteHash as a hint. The circuit will then compare
117
+ // the noteHash against the one provided by the user code to determine what to return to the user (exists or not),
118
+ // and will then propagate the actually-present noteHash to its public inputs.
119
+ this.newNoteHashes.push(new NoteHash(noteHash, this.sideEffectCounter));
120
+ this.incrementSideEffectCounter();
121
+ }
122
+
123
+ public traceNullifierCheck(_storageAddress: Fr, nullifier: Fr, _leafIndex: Fr, exists: boolean, _isPending: boolean) {
124
+ // TODO(4805): check if some threshold is reached for max new nullifier
125
+ // NOTE: storageAddress is unused but will be important when an AVM circuit processes an entire enqueued call
126
+ // NOTE: isPending and leafIndex are unused for now but may be used for optimizations or kernel hints later
127
+ const readRequest = new ReadRequest(nullifier, this.sideEffectCounter);
128
+ if (exists) {
129
+ this.nullifierReadRequests.push(readRequest);
130
+ } else {
131
+ this.nullifierNonExistentReadRequests.push(readRequest);
132
+ }
133
+ this.avmCircuitHints.nullifierExists.items.push(
134
+ new AvmKeyValueHint(/*key=*/ new Fr(this.sideEffectCounter), /*value=*/ new Fr(exists ? 1 : 0)),
135
+ );
136
+ this.incrementSideEffectCounter();
137
+ }
138
+
139
+ public traceNewNullifier(_storageAddress: Fr, nullifier: Fr) {
140
+ // TODO(4805): check if some threshold is reached for max new nullifier
141
+ // NOTE: storageAddress is unused but will be important when an AVM circuit processes an entire enqueued call
142
+ this.newNullifiers.push(new Nullifier(nullifier, this.sideEffectCounter, /*noteHash=*/ Fr.ZERO));
143
+ this.incrementSideEffectCounter();
144
+ }
145
+
146
+ public traceL1ToL2MessageCheck(_contractAddress: Fr, msgHash: Fr, _msgLeafIndex: Fr, exists: boolean) {
147
+ // TODO(4805): check if some threshold is reached for max message reads
148
+ // NOTE: contractAddress is unused but will be important when an AVM circuit processes an entire enqueued call
149
+ // TODO(dbanks12): leafIndex is unused for now but later must be used by kernel to constrain that the kernel
150
+ // is in fact checking the leaf indicated by the user
151
+ this.l1ToL2MsgReadRequests.push(new ReadRequest(msgHash, this.sideEffectCounter));
152
+ this.avmCircuitHints.l1ToL2MessageExists.items.push(
153
+ new AvmKeyValueHint(/*key=*/ new Fr(this.sideEffectCounter), /*value=*/ new Fr(exists ? 1 : 0)),
154
+ );
155
+ this.incrementSideEffectCounter();
156
+ }
157
+
158
+ public traceNewL2ToL1Message(recipient: Fr, content: Fr) {
159
+ // TODO(4805): check if some threshold is reached for max messages
160
+ const recipientAddress = EthAddress.fromField(recipient);
161
+ this.newL2ToL1Messages.push(new L2ToL1Message(recipientAddress, content, this.sideEffectCounter));
162
+ this.incrementSideEffectCounter();
163
+ }
164
+
165
+ public traceUnencryptedLog(contractAddress: Fr, event: Fr, log: Fr[]) {
166
+ // TODO(4805): check if some threshold is reached for max logs
167
+ const ulog = new UnencryptedL2Log(
168
+ AztecAddress.fromField(contractAddress),
169
+ EventSelector.fromField(event),
170
+ Buffer.concat(log.map(f => f.toBuffer())),
171
+ );
172
+ const basicLogHash = Fr.fromBuffer(ulog.hash());
173
+ this.unencryptedLogs.push(ulog);
174
+ this.allUnencryptedLogs.push(ulog);
175
+ // TODO(6578): explain magic number 4 here
176
+ this.unencryptedLogsHashes.push(new LogHash(basicLogHash, this.sideEffectCounter, new Fr(ulog.length + 4)));
177
+ this.incrementSideEffectCounter();
178
+ }
179
+
180
+ public traceGetContractInstance(instance: TracedContractInstance) {
181
+ // TODO(4805): check if some threshold is reached for max contract instance retrievals
182
+ this.gotContractInstances.push(instance);
183
+ this.avmCircuitHints.contractInstances.items.push(
184
+ new AvmContractInstanceHint(
185
+ instance.address,
186
+ new Fr(instance.exists ? 1 : 0),
187
+ instance.salt,
188
+ instance.deployer,
189
+ instance.contractClassId,
190
+ instance.initializationHash,
191
+ instance.publicKeysHash,
192
+ ),
193
+ );
194
+ this.incrementSideEffectCounter();
195
+ }
196
+
197
+ /**
198
+ * Trace a nested call.
199
+ * Accept some results from a finished nested call's trace into this one.
200
+ */
201
+ public traceNestedCall(
202
+ /** The trace of the nested call. */
203
+ nestedCallTrace: PublicSideEffectTrace,
204
+ /** The execution environment of the nested call. */
205
+ nestedEnvironment: AvmExecutionEnvironment,
206
+ /** How much gas was available for this public execution. */
207
+ startGasLeft: Gas,
208
+ /** How much gas was left after this public execution. */
209
+ endGasLeft: Gas,
210
+ /** Bytecode used for this execution. */
211
+ bytecode: Buffer,
212
+ /** The call's results */
213
+ avmCallResults: AvmContractCallResults,
214
+ /** Function name for logging */
215
+ functionName: string = 'unknown',
216
+ ) {
217
+ const result = nestedCallTrace.toPublicExecutionResult(
218
+ nestedEnvironment,
219
+ startGasLeft,
220
+ endGasLeft,
221
+ bytecode,
222
+ avmCallResults,
223
+ functionName,
224
+ );
225
+ this.sideEffectCounter = result.endSideEffectCounter.toNumber();
226
+ // when a nested call returns, caller accepts its updated counter
227
+ this.allUnencryptedLogs.push(...result.allUnencryptedLogs.logs);
228
+ // NOTE: eventually if the AVM circuit processes an entire enqueued call,
229
+ // this function will accept all of the nested's side effects into this instance
230
+ this.nestedExecutions.push(result);
231
+
232
+ const gasUsed = new Gas(
233
+ result.startGasLeft.daGas - result.endGasLeft.daGas,
234
+ result.startGasLeft.l2Gas - result.endGasLeft.l2Gas,
235
+ );
236
+ this.avmCircuitHints.externalCalls.items.push(
237
+ new AvmExternalCallHint(/*success=*/ new Fr(result.reverted ? 0 : 1), result.returnValues, gasUsed),
238
+ );
239
+ }
240
+
241
+ /**
242
+ * Convert this trace to a PublicExecutionResult for use externally to the simulator.
243
+ */
244
+ public toPublicExecutionResult(
245
+ /** The execution environment of the nested call. */
246
+ avmEnvironment: AvmExecutionEnvironment,
247
+ /** How much gas was available for this public execution. */
248
+ startGasLeft: Gas,
249
+ /** How much gas was left after this public execution. */
250
+ endGasLeft: Gas,
251
+ /** Bytecode used for this execution. */
252
+ bytecode: Buffer,
253
+ /** The call's results */
254
+ avmCallResults: AvmContractCallResults,
255
+ /** Function name for logging */
256
+ functionName: string = 'unknown',
257
+ /** The side effect counter of the execution request itself */
258
+ requestSideEffectCounter: number = this.startSideEffectCounter,
259
+ ): PublicExecutionResult {
260
+ return {
261
+ execution: createPublicExecutionRequest(requestSideEffectCounter, avmEnvironment),
262
+
263
+ startSideEffectCounter: new Fr(this.startSideEffectCounter),
264
+ endSideEffectCounter: new Fr(this.sideEffectCounter),
265
+ startGasLeft,
266
+ endGasLeft,
267
+ transactionFee: avmEnvironment.transactionFee,
268
+
269
+ bytecode,
270
+ calldata: avmEnvironment.calldata,
271
+ returnValues: avmCallResults.output,
272
+ reverted: avmCallResults.reverted,
273
+ revertReason: avmCallResults.revertReason ? createSimulationError(avmCallResults.revertReason) : undefined,
274
+
275
+ contractStorageReads: this.contractStorageReads,
276
+ contractStorageUpdateRequests: this.contractStorageUpdateRequests,
277
+ noteHashReadRequests: this.noteHashReadRequests,
278
+ newNoteHashes: this.newNoteHashes,
279
+ nullifierReadRequests: this.nullifierReadRequests,
280
+ nullifierNonExistentReadRequests: this.nullifierNonExistentReadRequests,
281
+ newNullifiers: this.newNullifiers,
282
+ l1ToL2MsgReadRequests: this.l1ToL2MsgReadRequests,
283
+ newL2ToL1Messages: this.newL2ToL1Messages,
284
+ // correct the type on these now that they are finalized (lists won't grow)
285
+ unencryptedLogs: new UnencryptedFunctionL2Logs(this.unencryptedLogs),
286
+ allUnencryptedLogs: new UnencryptedFunctionL2Logs(this.allUnencryptedLogs),
287
+ unencryptedLogsHashes: this.unencryptedLogsHashes,
288
+ // TODO(dbanks12): process contract instance read requests in public kernel
289
+ //gotContractInstances: this.gotContractInstances,
290
+
291
+ nestedExecutions: this.nestedExecutions,
292
+
293
+ avmCircuitHints: this.avmCircuitHints,
294
+
295
+ functionName,
296
+ };
297
+ }
298
+ }
299
+
300
+ /**
301
+ * Helper function to create a public execution request from an AVM execution environment
302
+ */
303
+ function createPublicExecutionRequest(
304
+ requestSideEffectCounter: number,
305
+ avmEnvironment: AvmExecutionEnvironment,
306
+ ): PublicExecution {
307
+ const callContext = CallContext.from({
308
+ msgSender: avmEnvironment.sender,
309
+ storageContractAddress: avmEnvironment.storageAddress,
310
+ functionSelector: avmEnvironment.temporaryFunctionSelector,
311
+ isDelegateCall: avmEnvironment.isDelegateCall,
312
+ isStaticCall: avmEnvironment.isStaticCall,
313
+ sideEffectCounter: requestSideEffectCounter,
314
+ });
315
+ const execution: PublicExecution = {
316
+ contractAddress: avmEnvironment.address,
317
+ functionSelector: avmEnvironment.temporaryFunctionSelector,
318
+ callContext,
319
+ // execution request does not contain AvmContextInputs prefix
320
+ args: avmEnvironment.getCalldataWithoutPrefix(),
321
+ };
322
+ return execution;
323
+ }