@aztec/simulator 0.41.0 → 0.43.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 (243) hide show
  1. package/dest/acvm/acvm.d.ts +2 -2
  2. package/dest/acvm/acvm.d.ts.map +1 -1
  3. package/dest/acvm/acvm.js +3 -3
  4. package/dest/acvm/oracle/oracle.d.ts +7 -4
  5. package/dest/acvm/oracle/oracle.d.ts.map +1 -1
  6. package/dest/acvm/oracle/oracle.js +32 -12
  7. package/dest/acvm/oracle/typed_oracle.d.ts +6 -3
  8. package/dest/acvm/oracle/typed_oracle.d.ts.map +1 -1
  9. package/dest/acvm/oracle/typed_oracle.js +15 -6
  10. package/dest/acvm/serialize.js +2 -2
  11. package/dest/avm/avm_gas.d.ts +1 -5
  12. package/dest/avm/avm_gas.d.ts.map +1 -1
  13. package/dest/avm/avm_gas.js +69 -73
  14. package/dest/avm/avm_memory_types.d.ts.map +1 -1
  15. package/dest/avm/avm_memory_types.js +2 -4
  16. package/dest/avm/avm_simulator.d.ts +5 -0
  17. package/dest/avm/avm_simulator.d.ts.map +1 -1
  18. package/dest/avm/avm_simulator.js +8 -1
  19. package/dest/avm/fixtures/index.d.ts +6 -0
  20. package/dest/avm/fixtures/index.d.ts.map +1 -1
  21. package/dest/avm/fixtures/index.js +18 -1
  22. package/dest/avm/index.d.ts +2 -0
  23. package/dest/avm/index.d.ts.map +1 -0
  24. package/dest/avm/index.js +2 -0
  25. package/dest/avm/journal/host_storage.d.ts +1 -1
  26. package/dest/avm/journal/host_storage.d.ts.map +1 -1
  27. package/dest/avm/journal/journal.d.ts +5 -3
  28. package/dest/avm/journal/journal.d.ts.map +1 -1
  29. package/dest/avm/journal/journal.js +23 -14
  30. package/dest/avm/journal/trace.d.ts +3 -1
  31. package/dest/avm/journal/trace.d.ts.map +1 -1
  32. package/dest/avm/journal/trace.js +8 -1
  33. package/dest/avm/journal/trace_types.d.ts +5 -0
  34. package/dest/avm/journal/trace_types.d.ts.map +1 -1
  35. package/dest/avm/journal/trace_types.js +1 -5
  36. package/dest/avm/opcodes/accrued_substate.d.ts +2 -2
  37. package/dest/avm/opcodes/accrued_substate.d.ts.map +1 -1
  38. package/dest/avm/opcodes/accrued_substate.js +36 -21
  39. package/dest/avm/opcodes/arithmetic.d.ts +1 -7
  40. package/dest/avm/opcodes/arithmetic.d.ts.map +1 -1
  41. package/dest/avm/opcodes/arithmetic.js +12 -20
  42. package/dest/avm/opcodes/bitwise.d.ts.map +1 -1
  43. package/dest/avm/opcodes/bitwise.js +11 -8
  44. package/dest/avm/opcodes/comparators.d.ts.map +1 -1
  45. package/dest/avm/opcodes/comparators.js +7 -5
  46. package/dest/avm/opcodes/contract.d.ts.map +1 -1
  47. package/dest/avm/opcodes/contract.js +20 -24
  48. package/dest/avm/opcodes/control_flow.d.ts.map +1 -1
  49. package/dest/avm/opcodes/control_flow.js +4 -2
  50. package/dest/avm/opcodes/conversion.js +2 -2
  51. package/dest/avm/opcodes/ec_add.d.ts +19 -0
  52. package/dest/avm/opcodes/ec_add.d.ts.map +1 -0
  53. package/dest/avm/opcodes/ec_add.js +78 -0
  54. package/dest/avm/opcodes/external_calls.d.ts.map +1 -1
  55. package/dest/avm/opcodes/external_calls.js +11 -5
  56. package/dest/avm/opcodes/hashing.d.ts.map +1 -1
  57. package/dest/avm/opcodes/hashing.js +10 -2
  58. package/dest/avm/opcodes/instruction.d.ts +1 -1
  59. package/dest/avm/opcodes/instruction.d.ts.map +1 -1
  60. package/dest/avm/opcodes/instruction.js +6 -4
  61. package/dest/avm/opcodes/instruction_impl.d.ts.map +1 -1
  62. package/dest/avm/opcodes/instruction_impl.js +4 -2
  63. package/dest/avm/opcodes/memory.d.ts +1 -5
  64. package/dest/avm/opcodes/memory.d.ts.map +1 -1
  65. package/dest/avm/opcodes/memory.js +14 -18
  66. package/dest/avm/opcodes/multi_scalar_mul.d.ts +16 -0
  67. package/dest/avm/opcodes/multi_scalar_mul.d.ts.map +1 -0
  68. package/dest/avm/opcodes/multi_scalar_mul.js +95 -0
  69. package/dest/avm/opcodes/storage.d.ts +1 -6
  70. package/dest/avm/opcodes/storage.d.ts.map +1 -1
  71. package/dest/avm/opcodes/storage.js +11 -14
  72. package/dest/avm/serialization/bytecode_serialization.d.ts.map +1 -1
  73. package/dest/avm/serialization/bytecode_serialization.js +6 -2
  74. package/dest/avm/serialization/instruction_serialization.d.ts +3 -1
  75. package/dest/avm/serialization/instruction_serialization.d.ts.map +1 -1
  76. package/dest/avm/serialization/instruction_serialization.js +4 -2
  77. package/dest/client/client_execution_context.d.ts +24 -20
  78. package/dest/client/client_execution_context.d.ts.map +1 -1
  79. package/dest/client/client_execution_context.js +52 -55
  80. package/dest/client/db_oracle.d.ts +7 -1
  81. package/dest/client/db_oracle.d.ts.map +1 -1
  82. package/dest/client/execution_note_cache.d.ts +0 -17
  83. package/dest/client/execution_note_cache.d.ts.map +1 -1
  84. package/dest/client/execution_note_cache.js +1 -24
  85. package/dest/client/execution_result.d.ts +8 -4
  86. package/dest/client/execution_result.d.ts.map +1 -1
  87. package/dest/client/execution_result.js +16 -6
  88. package/dest/client/private_execution.d.ts +2 -3
  89. package/dest/client/private_execution.d.ts.map +1 -1
  90. package/dest/client/private_execution.js +20 -9
  91. package/dest/client/simulator.d.ts +2 -17
  92. package/dest/client/simulator.d.ts.map +1 -1
  93. package/dest/client/simulator.js +24 -33
  94. package/dest/client/unconstrained_execution.d.ts +2 -3
  95. package/dest/client/unconstrained_execution.d.ts.map +1 -1
  96. package/dest/client/unconstrained_execution.js +5 -7
  97. package/dest/client/view_data_oracle.d.ts +2 -0
  98. package/dest/client/view_data_oracle.d.ts.map +1 -1
  99. package/dest/client/view_data_oracle.js +7 -1
  100. package/dest/index.d.ts +3 -1
  101. package/dest/index.d.ts.map +1 -1
  102. package/dest/index.js +4 -2
  103. package/dest/mocks/fixtures.d.ts +14 -10
  104. package/dest/mocks/fixtures.d.ts.map +1 -1
  105. package/dest/mocks/fixtures.js +22 -16
  106. package/dest/{simulator → providers}/acvm_native.d.ts.map +1 -1
  107. package/dest/{simulator → providers}/acvm_native.js +13 -14
  108. package/dest/providers/acvm_wasm.d.ts.map +1 -0
  109. package/dest/providers/acvm_wasm.js +15 -0
  110. package/dest/providers/index.d.ts.map +1 -0
  111. package/dest/{simulator → providers}/index.js +1 -1
  112. package/dest/{simulator → providers}/simulation_provider.d.ts.map +1 -1
  113. package/dest/{simulator → providers}/simulation_provider.js +1 -1
  114. package/dest/public/abstract_phase_manager.d.ts +53 -53
  115. package/dest/public/abstract_phase_manager.d.ts.map +1 -1
  116. package/dest/public/abstract_phase_manager.js +146 -153
  117. package/dest/public/app_logic_phase_manager.d.ts +8 -9
  118. package/dest/public/app_logic_phase_manager.d.ts.map +1 -1
  119. package/dest/public/app_logic_phase_manager.js +15 -15
  120. package/dest/public/{db.d.ts → db_interfaces.d.ts} +4 -3
  121. package/dest/public/db_interfaces.d.ts.map +1 -0
  122. package/dest/public/db_interfaces.js +2 -0
  123. package/dest/public/execution.d.ts +16 -23
  124. package/dest/public/execution.d.ts.map +1 -1
  125. package/dest/public/execution.js +1 -51
  126. package/dest/public/executor.d.ts +4 -31
  127. package/dest/public/executor.d.ts.map +1 -1
  128. package/dest/public/executor.js +40 -283
  129. package/dest/public/fee_payment.d.ts +11 -0
  130. package/dest/public/fee_payment.d.ts.map +1 -0
  131. package/dest/public/fee_payment.js +24 -0
  132. package/dest/public/hints_builder.d.ts +2 -1
  133. package/dest/public/hints_builder.d.ts.map +1 -1
  134. package/dest/public/hints_builder.js +6 -2
  135. package/dest/public/index.d.ts +8 -6
  136. package/dest/public/index.d.ts.map +1 -1
  137. package/dest/public/index.js +9 -7
  138. package/dest/public/phase_manager_factory.d.ts +4 -4
  139. package/dest/public/phase_manager_factory.d.ts.map +1 -1
  140. package/dest/public/phase_manager_factory.js +5 -5
  141. package/dest/public/{public_executor.d.ts → public_db_sources.d.ts} +6 -3
  142. package/dest/public/public_db_sources.d.ts.map +1 -0
  143. package/dest/public/public_db_sources.js +244 -0
  144. package/dest/public/public_kernel.js +14 -14
  145. package/dest/public/public_processor.d.ts +6 -4
  146. package/dest/public/public_processor.d.ts.map +1 -1
  147. package/dest/public/public_processor.js +48 -30
  148. package/dest/public/setup_phase_manager.d.ts +8 -10
  149. package/dest/public/setup_phase_manager.d.ts.map +1 -1
  150. package/dest/public/setup_phase_manager.js +12 -21
  151. package/dest/public/tail_phase_manager.d.ts +7 -13
  152. package/dest/public/tail_phase_manager.d.ts.map +1 -1
  153. package/dest/public/tail_phase_manager.js +17 -37
  154. package/dest/public/teardown_phase_manager.d.ts +8 -10
  155. package/dest/public/teardown_phase_manager.d.ts.map +1 -1
  156. package/dest/public/teardown_phase_manager.js +16 -22
  157. package/dest/public/transitional_adaptors.d.ts +2 -2
  158. package/dest/public/transitional_adaptors.d.ts.map +1 -1
  159. package/dest/public/transitional_adaptors.js +14 -6
  160. package/package.json +12 -9
  161. package/src/acvm/acvm.ts +0 -3
  162. package/src/acvm/oracle/oracle.ts +68 -16
  163. package/src/acvm/oracle/typed_oracle.ts +31 -6
  164. package/src/acvm/serialize.ts +1 -1
  165. package/src/avm/avm_gas.ts +68 -73
  166. package/src/avm/avm_memory_types.ts +1 -3
  167. package/src/avm/avm_simulator.ts +9 -0
  168. package/src/avm/fixtures/index.ts +24 -0
  169. package/src/avm/index.ts +1 -0
  170. package/src/avm/journal/host_storage.ts +1 -1
  171. package/src/avm/journal/journal.ts +32 -22
  172. package/src/avm/journal/trace.ts +9 -0
  173. package/src/avm/journal/trace_types.ts +4 -0
  174. package/src/avm/opcodes/accrued_substate.ts +53 -20
  175. package/src/avm/opcodes/arithmetic.ts +18 -22
  176. package/src/avm/opcodes/bitwise.ts +13 -8
  177. package/src/avm/opcodes/comparators.ts +9 -4
  178. package/src/avm/opcodes/contract.ts +22 -26
  179. package/src/avm/opcodes/control_flow.ts +3 -1
  180. package/src/avm/opcodes/conversion.ts +1 -1
  181. package/src/avm/opcodes/ec_add.ts +92 -0
  182. package/src/avm/opcodes/external_calls.ts +11 -3
  183. package/src/avm/opcodes/hashing.ts +11 -1
  184. package/src/avm/opcodes/instruction.ts +5 -3
  185. package/src/avm/opcodes/instruction_impl.ts +4 -1
  186. package/src/avm/opcodes/memory.ts +19 -19
  187. package/src/avm/opcodes/multi_scalar_mul.ts +114 -0
  188. package/src/avm/opcodes/storage.ts +10 -17
  189. package/src/avm/serialization/bytecode_serialization.ts +5 -1
  190. package/src/avm/serialization/instruction_serialization.ts +2 -0
  191. package/src/client/client_execution_context.ts +76 -60
  192. package/src/client/db_oracle.ts +8 -1
  193. package/src/client/execution_note_cache.ts +0 -28
  194. package/src/client/execution_result.ts +21 -7
  195. package/src/client/private_execution.ts +36 -21
  196. package/src/client/simulator.ts +25 -35
  197. package/src/client/unconstrained_execution.ts +9 -12
  198. package/src/client/view_data_oracle.ts +8 -0
  199. package/src/index.ts +3 -1
  200. package/src/mocks/fixtures.ts +30 -32
  201. package/src/{simulator → providers}/acvm_native.ts +21 -19
  202. package/src/{simulator → providers}/acvm_wasm.ts +2 -16
  203. package/src/public/abstract_phase_manager.ts +209 -258
  204. package/src/public/app_logic_phase_manager.ts +24 -40
  205. package/src/public/{db.ts → db_interfaces.ts} +4 -2
  206. package/src/public/execution.ts +15 -77
  207. package/src/public/executor.ts +61 -399
  208. package/src/public/fee_payment.ts +26 -0
  209. package/src/public/hints_builder.ts +6 -0
  210. package/src/public/index.ts +8 -12
  211. package/src/public/phase_manager_factory.ts +7 -7
  212. package/src/public/{public_executor.ts → public_db_sources.ts} +65 -9
  213. package/src/public/public_kernel.ts +24 -24
  214. package/src/public/public_processor.ts +81 -40
  215. package/src/public/setup_phase_manager.ts +21 -46
  216. package/src/public/tail_phase_manager.ts +19 -67
  217. package/src/public/teardown_phase_manager.ts +23 -42
  218. package/src/public/transitional_adaptors.ts +41 -5
  219. package/dest/public/db.d.ts.map +0 -1
  220. package/dest/public/db.js +0 -2
  221. package/dest/public/public_execution_context.d.ts +0 -121
  222. package/dest/public/public_execution_context.d.ts.map +0 -1
  223. package/dest/public/public_execution_context.js +0 -214
  224. package/dest/public/public_executor.d.ts.map +0 -1
  225. package/dest/public/public_executor.js +0 -197
  226. package/dest/public/state_actions.d.ts +0 -39
  227. package/dest/public/state_actions.d.ts.map +0 -1
  228. package/dest/public/state_actions.js +0 -80
  229. package/dest/public/utils.d.ts +0 -8
  230. package/dest/public/utils.d.ts.map +0 -1
  231. package/dest/public/utils.js +0 -31
  232. package/dest/simulator/acvm_wasm.d.ts.map +0 -1
  233. package/dest/simulator/acvm_wasm.js +0 -22
  234. package/dest/simulator/index.d.ts.map +0 -1
  235. package/src/public/public_execution_context.ts +0 -289
  236. package/src/public/state_actions.ts +0 -102
  237. package/src/public/utils.ts +0 -33
  238. /package/dest/{simulator → providers}/acvm_native.d.ts +0 -0
  239. /package/dest/{simulator → providers}/acvm_wasm.d.ts +0 -0
  240. /package/dest/{simulator → providers}/index.d.ts +0 -0
  241. /package/dest/{simulator → providers}/simulation_provider.d.ts +0 -0
  242. /package/src/{simulator → providers}/index.ts +0 -0
  243. /package/src/{simulator → providers}/simulation_provider.ts +0 -0
@@ -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
  /**
@@ -145,11 +163,12 @@ export class WorldStatePublicDB implements PublicStateDB {
145
163
  * @param contract - Owner of the storage.
146
164
  * @param slot - Slot to read in the contract storage.
147
165
  * @param newValue - The new value to store.
166
+ * @returns The slot of the written leaf in the public data tree.
148
167
  */
149
- public storageWrite(contract: AztecAddress, slot: Fr, newValue: Fr): Promise<void> {
168
+ public storageWrite(contract: AztecAddress, slot: Fr, newValue: Fr): Promise<bigint> {
150
169
  const index = computePublicDataTreeLeafSlot(contract, slot).value;
151
170
  this.uncommittedWriteCache.set(index, newValue);
152
- return Promise.resolve();
171
+ return Promise.resolve(index);
153
172
  }
154
173
 
155
174
  /**
@@ -195,11 +214,14 @@ export class WorldStatePublicDB implements PublicStateDB {
195
214
  * Implements WorldState db using a world state database.
196
215
  */
197
216
  export class WorldStateDB implements CommitmentsDB {
217
+ private log = createDebugLogger('aztec:sequencer:world-state-db');
218
+
198
219
  constructor(private db: MerkleTreeOperations) {}
199
220
 
200
221
  public async getNullifierMembershipWitnessAtLatestBlock(
201
222
  nullifier: Fr,
202
223
  ): Promise<NullifierMembershipWitness | undefined> {
224
+ const timer = new Timer();
203
225
  const index = await this.db.findLeafIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBuffer());
204
226
  if (!index) {
205
227
  return undefined;
@@ -217,6 +239,12 @@ export class WorldStateDB implements CommitmentsDB {
217
239
  return undefined;
218
240
  }
219
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
+
220
248
  return new NullifierMembershipWitness(BigInt(index), leafPreimage as NullifierLeafPreimage, siblingPath);
221
249
  }
222
250
 
@@ -231,6 +259,7 @@ export class WorldStateDB implements CommitmentsDB {
231
259
 
232
260
  // We iterate over messages until we find one whose nullifier is not in the nullifier tree --> we need to check
233
261
  // for nullifiers because messages can have duplicates.
262
+ const timer = new Timer();
234
263
  do {
235
264
  messageIndex = (await this.db.findLeafIndexAfter(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, messageHash, startIndex))!;
236
265
  if (messageIndex === undefined) {
@@ -248,18 +277,45 @@ export class WorldStateDB implements CommitmentsDB {
248
277
  messageIndex,
249
278
  );
250
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
+
251
286
  return new MessageLoadOracleInputs<typeof L1_TO_L2_MSG_TREE_HEIGHT>(messageIndex, siblingPath);
252
287
  }
253
288
 
254
289
  public async getL1ToL2LeafValue(leafIndex: bigint): Promise<Fr | undefined> {
255
- 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;
256
298
  }
257
299
 
258
300
  public async getCommitmentIndex(commitment: Fr): Promise<bigint | undefined> {
259
- 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;
260
309
  }
261
310
 
262
311
  public async getNullifierIndex(nullifier: Fr): Promise<bigint | undefined> {
263
- 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;
264
320
  }
265
321
  }
@@ -8,18 +8,18 @@ import {
8
8
  import { createDebugLogger } from '@aztec/foundation/log';
9
9
  import { elapsed } from '@aztec/foundation/timer';
10
10
  import {
11
- PublicKernelAppLogicArtifact,
12
- PublicKernelSetupArtifact,
13
- PublicKernelTailArtifact,
14
- PublicKernelTeardownArtifact,
15
- convertPublicInnerRollupInputsToWitnessMap,
16
- convertPublicInnerRollupOutputFromWitnessMap,
17
- convertPublicSetupRollupInputsToWitnessMap,
18
- convertPublicSetupRollupOutputFromWitnessMap,
19
- convertPublicTailInputsToWitnessMap,
20
- convertPublicTailOutputFromWitnessMap,
21
- convertPublicTeardownRollupInputsToWitnessMap,
22
- convertPublicTeardownRollupOutputFromWitnessMap,
11
+ SimulatedPublicKernelAppLogicArtifact,
12
+ SimulatedPublicKernelSetupArtifact,
13
+ SimulatedPublicKernelTailArtifact,
14
+ SimulatedPublicKernelTeardownArtifact,
15
+ convertSimulatedPublicInnerInputsToWitnessMap,
16
+ convertSimulatedPublicInnerOutputFromWitnessMap,
17
+ convertSimulatedPublicSetupInputsToWitnessMap,
18
+ convertSimulatedPublicSetupOutputFromWitnessMap,
19
+ convertSimulatedPublicTailInputsToWitnessMap,
20
+ convertSimulatedPublicTailOutputFromWitnessMap,
21
+ convertSimulatedPublicTeardownInputsToWitnessMap,
22
+ convertSimulatedPublicTeardownOutputFromWitnessMap,
23
23
  } from '@aztec/noir-protocol-circuits-types';
24
24
  import { type SimulationProvider, WASMSimulator } from '@aztec/simulator';
25
25
 
@@ -47,11 +47,11 @@ export class RealPublicKernelCircuitSimulator implements PublicKernelCircuitSimu
47
47
  if (!input.previousKernel.publicInputs.needsSetup) {
48
48
  throw new Error(`Expected previous kernel inputs to need setup`);
49
49
  }
50
- const inputWitness = convertPublicSetupRollupInputsToWitnessMap(input);
50
+ const inputWitness = convertSimulatedPublicSetupInputsToWitnessMap(input);
51
51
  const [duration, witness] = await elapsed(() =>
52
- this.wasmSimulator.simulateCircuit(inputWitness, PublicKernelSetupArtifact),
52
+ this.wasmSimulator.simulateCircuit(inputWitness, SimulatedPublicKernelSetupArtifact),
53
53
  );
54
- const result = convertPublicSetupRollupOutputFromWitnessMap(witness);
54
+ const result = convertSimulatedPublicSetupOutputFromWitnessMap(witness);
55
55
  this.log.debug(`Simulated public kernel setup circuit`, {
56
56
  eventName: 'circuit-simulation',
57
57
  circuitName: 'public-kernel-setup',
@@ -73,11 +73,11 @@ export class RealPublicKernelCircuitSimulator implements PublicKernelCircuitSimu
73
73
  if (!input.previousKernel.publicInputs.needsAppLogic) {
74
74
  throw new Error(`Expected previous kernel inputs to need app logic`);
75
75
  }
76
- const inputWitness = convertPublicInnerRollupInputsToWitnessMap(input);
76
+ const inputWitness = convertSimulatedPublicInnerInputsToWitnessMap(input);
77
77
  const [duration, witness] = await elapsed(() =>
78
- this.wasmSimulator.simulateCircuit(inputWitness, PublicKernelAppLogicArtifact),
78
+ this.wasmSimulator.simulateCircuit(inputWitness, SimulatedPublicKernelAppLogicArtifact),
79
79
  );
80
- const result = convertPublicInnerRollupOutputFromWitnessMap(witness);
80
+ const result = convertSimulatedPublicInnerOutputFromWitnessMap(witness);
81
81
  this.log.debug(`Simulated public kernel app logic circuit`, {
82
82
  eventName: 'circuit-simulation',
83
83
  circuitName: 'public-kernel-app-logic',
@@ -99,11 +99,11 @@ export class RealPublicKernelCircuitSimulator implements PublicKernelCircuitSimu
99
99
  if (!input.previousKernel.publicInputs.needsTeardown) {
100
100
  throw new Error(`Expected previous kernel inputs to need teardown`);
101
101
  }
102
- const inputWitness = convertPublicTeardownRollupInputsToWitnessMap(input);
102
+ const inputWitness = convertSimulatedPublicTeardownInputsToWitnessMap(input);
103
103
  const [duration, witness] = await elapsed(() =>
104
- this.wasmSimulator.simulateCircuit(inputWitness, PublicKernelTeardownArtifact),
104
+ this.wasmSimulator.simulateCircuit(inputWitness, SimulatedPublicKernelTeardownArtifact),
105
105
  );
106
- const result = convertPublicTeardownRollupOutputFromWitnessMap(witness);
106
+ const result = convertSimulatedPublicTeardownOutputFromWitnessMap(witness);
107
107
  this.log.debug(`Simulated public kernel teardown circuit`, {
108
108
  eventName: 'circuit-simulation',
109
109
  circuitName: 'public-kernel-teardown',
@@ -122,11 +122,11 @@ export class RealPublicKernelCircuitSimulator implements PublicKernelCircuitSimu
122
122
  public async publicKernelCircuitTail(
123
123
  input: PublicKernelTailCircuitPrivateInputs,
124
124
  ): Promise<KernelCircuitPublicInputs> {
125
- const inputWitness = convertPublicTailInputsToWitnessMap(input);
125
+ const inputWitness = convertSimulatedPublicTailInputsToWitnessMap(input);
126
126
  const [duration, witness] = await elapsed(() =>
127
- this.wasmSimulator.simulateCircuit(inputWitness, PublicKernelTailArtifact),
127
+ this.wasmSimulator.simulateCircuit(inputWitness, SimulatedPublicKernelTailArtifact),
128
128
  );
129
- const result = convertPublicTailOutputFromWitnessMap(witness);
129
+ const result = convertSimulatedPublicTailOutputFromWitnessMap(witness);
130
130
  this.log.debug(`Simulated public kernel tail circuit`, {
131
131
  eventName: 'circuit-simulation',
132
132
  circuitName: 'public-kernel-tail',
@@ -3,30 +3,39 @@ import {
3
3
  type FailedTx,
4
4
  NestedProcessReturnValues,
5
5
  type ProcessedTx,
6
- type PublicKernelRequest,
6
+ PublicKernelType,
7
+ type PublicProvingRequest,
7
8
  type SimulationError,
8
9
  Tx,
9
10
  type TxValidator,
10
- makeEmptyProcessedTx,
11
11
  makeProcessedTx,
12
- toTxEffect,
13
12
  validateProcessedTx,
14
13
  } from '@aztec/circuit-types';
15
- import { type TxSequencerProcessingStats } from '@aztec/circuit-types/stats';
16
- import { type GlobalVariables, type Header, type KernelCircuitPublicInputs } from '@aztec/circuits.js';
14
+ import {
15
+ AztecAddress,
16
+ GAS_TOKEN_ADDRESS,
17
+ type GlobalVariables,
18
+ type Header,
19
+ type KernelCircuitPublicInputs,
20
+ MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX,
21
+ PROTOCOL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX,
22
+ PublicDataUpdateRequest,
23
+ } from '@aztec/circuits.js';
24
+ import { times } from '@aztec/foundation/collection';
17
25
  import { createDebugLogger } from '@aztec/foundation/log';
18
- import { Timer } from '@aztec/foundation/timer';
19
- import { PublicExecutor, type PublicStateDB, type SimulationProvider } from '@aztec/simulator';
26
+ import {
27
+ PublicExecutor,
28
+ type PublicStateDB,
29
+ type SimulationProvider,
30
+ computeFeePayerBalanceLeafSlot,
31
+ computeFeePayerBalanceStorageSlot,
32
+ } from '@aztec/simulator';
20
33
  import { type ContractDataSource } from '@aztec/types/contracts';
21
34
  import { type MerkleTreeOperations } from '@aztec/world-state';
22
35
 
23
- import {
24
- type AbstractPhaseManager,
25
- PublicKernelPhase,
26
- publicKernelPhaseToKernelType,
27
- } from './abstract_phase_manager.js';
36
+ import { type AbstractPhaseManager } from './abstract_phase_manager.js';
28
37
  import { PhaseManagerFactory } from './phase_manager_factory.js';
29
- import { ContractsDataSourcePublicDB, WorldStateDB, WorldStatePublicDB } from './public_executor.js';
38
+ import { ContractsDataSourcePublicDB, WorldStateDB, WorldStatePublicDB } from './public_db_sources.js';
30
39
  import { RealPublicKernelCircuitSimulator } from './public_kernel.js';
31
40
  import { type PublicKernelCircuitSimulator } from './public_kernel_circuit_simulator.js';
32
41
 
@@ -101,7 +110,7 @@ export class PublicProcessor {
101
110
  txs = txs.map(tx => Tx.clone(tx));
102
111
  const result: ProcessedTx[] = [];
103
112
  const failed: FailedTx[] = [];
104
- const returns: NestedProcessReturnValues[] = [];
113
+ let returns: NestedProcessReturnValues[] = [];
105
114
 
106
115
  for (const tx of txs) {
107
116
  // only process up to the limit of the block
@@ -112,7 +121,14 @@ export class PublicProcessor {
112
121
  const [processedTx, returnValues] = !tx.hasPublicCalls()
113
122
  ? [makeProcessedTx(tx, tx.data.toKernelCircuitPublicInputs(), tx.proof, [])]
114
123
  : await this.processTxWithPublicCalls(tx);
124
+
125
+ // Set fee payment update request into the processed tx
126
+ processedTx.finalPublicDataUpdateRequests = await this.createFinalDataUpdateRequests(processedTx);
127
+
128
+ // Commit the state updates from this transaction
129
+ await this.publicStateDB.commit();
115
130
  validateProcessedTx(processedTx);
131
+
116
132
  // Re-validate the transaction
117
133
  if (txValidator) {
118
134
  // Only accept processed transactions that are not double-spends,
@@ -129,10 +145,10 @@ export class PublicProcessor {
129
145
  await blockProver.addNewTx(processedTx);
130
146
  }
131
147
  result.push(processedTx);
132
- returns.push(returnValues?.[0] ?? new NestedProcessReturnValues([]));
148
+ returns = returns.concat(returnValues ?? []);
133
149
  } catch (err: any) {
134
150
  const errorMessage = err instanceof Error ? err.message : 'Unknown error';
135
- this.log.warn(`Failed to process tx ${tx.getTxHash()}: ${errorMessage}`);
151
+ this.log.warn(`Failed to process tx ${tx.getTxHash()}: ${errorMessage} ${err?.stack}`);
136
152
 
137
153
  failed.push({
138
154
  tx,
@@ -146,17 +162,55 @@ export class PublicProcessor {
146
162
  }
147
163
 
148
164
  /**
149
- * Makes an empty processed tx. Useful for padding a block to a power of two number of txs.
150
- * @returns A processed tx with empty data.
165
+ * Creates the final set of data update requests for the transaction. This includes the
166
+ * set of public data update requests as returned by the public kernel, plus a data update
167
+ * request for updating fee balance. It also updates the local public state db.
168
+ * See build_or_patch_payment_update_request in base_rollup_inputs.nr for more details.
151
169
  */
152
- public makeEmptyProcessedTx(): ProcessedTx {
153
- const { chainId, version } = this.globalVariables;
154
- return makeEmptyProcessedTx(this.historicalHeader.clone(), chainId, version);
170
+ private async createFinalDataUpdateRequests(tx: ProcessedTx) {
171
+ const finalPublicDataUpdateRequests = [
172
+ ...tx.data.end.publicDataUpdateRequests,
173
+ ...times(PROTOCOL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, () => PublicDataUpdateRequest.empty()),
174
+ ];
175
+
176
+ const feePayer = tx.data.feePayer;
177
+ if (feePayer.isZero()) {
178
+ return finalPublicDataUpdateRequests;
179
+ }
180
+
181
+ const gasToken = AztecAddress.fromBigInt(GAS_TOKEN_ADDRESS);
182
+ const balanceSlot = computeFeePayerBalanceStorageSlot(feePayer);
183
+ const leafSlot = computeFeePayerBalanceLeafSlot(feePayer);
184
+ const txFee = tx.data.getTransactionFee(this.globalVariables.gasFees);
185
+
186
+ this.log.debug(`Deducting ${txFee} balance in gas tokens for ${feePayer}`);
187
+
188
+ const existingBalanceWriteIndex = finalPublicDataUpdateRequests.findIndex(request =>
189
+ request.leafSlot.equals(leafSlot),
190
+ );
191
+
192
+ const balance =
193
+ existingBalanceWriteIndex > -1
194
+ ? finalPublicDataUpdateRequests[existingBalanceWriteIndex].newValue
195
+ : await this.publicStateDB.storageRead(gasToken, balanceSlot);
196
+
197
+ if (balance.lt(txFee)) {
198
+ throw new Error(`Not enough balance for fee payer to pay for transaction (got ${balance} needs ${txFee})`);
199
+ }
200
+
201
+ const updatedBalance = balance.sub(txFee);
202
+ await this.publicStateDB.storageWrite(gasToken, balanceSlot, updatedBalance);
203
+
204
+ finalPublicDataUpdateRequests[
205
+ existingBalanceWriteIndex > -1 ? existingBalanceWriteIndex : MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX
206
+ ] = new PublicDataUpdateRequest(leafSlot, updatedBalance, 0);
207
+
208
+ return finalPublicDataUpdateRequests;
155
209
  }
156
210
 
157
211
  private async processTxWithPublicCalls(tx: Tx): Promise<[ProcessedTx, NestedProcessReturnValues[]]> {
158
212
  let returnValues: NestedProcessReturnValues[] = [];
159
- const publicRequests: PublicKernelRequest[] = [];
213
+ const publicProvingRequests: PublicProvingRequest[] = [];
160
214
  let phase: AbstractPhaseManager | undefined = PhaseManagerFactory.phaseFromTx(
161
215
  tx,
162
216
  this.db,
@@ -168,22 +222,19 @@ export class PublicProcessor {
168
222
  this.publicStateDB,
169
223
  );
170
224
  this.log.debug(`Beginning processing in phase ${phase?.phase} for tx ${tx.getTxHash()}`);
171
- let proof = tx.proof;
172
225
  let publicKernelPublicInput = tx.data.toPublicKernelCircuitPublicInputs();
173
226
  let finalKernelOutput: KernelCircuitPublicInputs | undefined;
174
227
  let revertReason: SimulationError | undefined;
175
- const timer = new Timer();
176
228
  const gasUsed: ProcessedTx['gasUsed'] = {};
177
229
  while (phase) {
178
- const output = await phase.handle(tx, publicKernelPublicInput, proof);
179
- gasUsed[publicKernelPhaseToKernelType(phase.phase)] = output.gasUsed;
180
- if (phase.phase === PublicKernelPhase.APP_LOGIC) {
230
+ const output = await phase.handle(tx, publicKernelPublicInput);
231
+ gasUsed[phase.phase] = output.gasUsed;
232
+ if (phase.phase === PublicKernelType.APP_LOGIC) {
181
233
  returnValues = output.returnValues;
182
234
  }
183
- publicRequests.push(...output.kernelRequests);
235
+ publicProvingRequests.push(...output.publicProvingRequests);
184
236
  publicKernelPublicInput = output.publicKernelOutput;
185
237
  finalKernelOutput = output.finalKernelOutput;
186
- proof = output.publicKernelProof;
187
238
  revertReason ??= output.revertReason;
188
239
  phase = PhaseManagerFactory.phaseFromOutput(
189
240
  publicKernelPublicInput,
@@ -202,17 +253,7 @@ export class PublicProcessor {
202
253
  throw new Error('Final public kernel was not executed.');
203
254
  }
204
255
 
205
- const processedTx = makeProcessedTx(tx, finalKernelOutput, proof, publicRequests, revertReason, gasUsed);
206
-
207
- this.log.debug(`Processed public part of ${tx.getTxHash()}`, {
208
- eventName: 'tx-sequencer-processing',
209
- duration: timer.ms(),
210
- effectsSize: toTxEffect(processedTx).toBuffer().length,
211
- publicDataUpdateRequests:
212
- processedTx.data.end.publicDataUpdateRequests.filter(x => !x.leafSlot.isZero()).length ?? 0,
213
- ...tx.getStats(),
214
- } satisfies TxSequencerProcessingStats);
215
-
256
+ const processedTx = makeProcessedTx(tx, finalKernelOutput, tx.proof, publicProvingRequests, revertReason, gasUsed);
216
257
  return [processedTx, returnValues];
217
258
  }
218
259
  }
@@ -1,15 +1,10 @@
1
- import { type PublicKernelRequest, PublicKernelType, type Tx } from '@aztec/circuit-types';
2
- import {
3
- type GlobalVariables,
4
- type Header,
5
- type Proof,
6
- type PublicKernelCircuitPublicInputs,
7
- } from '@aztec/circuits.js';
1
+ import { PublicKernelType, type PublicProvingRequest, type Tx } from '@aztec/circuit-types';
2
+ import { type GlobalVariables, type Header, type PublicKernelCircuitPublicInputs } from '@aztec/circuits.js';
8
3
  import { type PublicExecutor, type PublicStateDB } from '@aztec/simulator';
9
4
  import { type MerkleTreeOperations } from '@aztec/world-state';
10
5
 
11
- import { AbstractPhaseManager, PublicKernelPhase } from './abstract_phase_manager.js';
12
- import { type ContractsDataSourcePublicDB } from './public_executor.js';
6
+ import { AbstractPhaseManager, makeAvmProvingRequest } from './abstract_phase_manager.js';
7
+ import { type ContractsDataSourcePublicDB } from './public_db_sources.js';
13
8
  import { type PublicKernelCircuitSimulator } from './public_kernel_circuit_simulator.js';
14
9
 
15
10
  /**
@@ -24,51 +19,31 @@ export class SetupPhaseManager extends AbstractPhaseManager {
24
19
  historicalHeader: Header,
25
20
  protected publicContractsDB: ContractsDataSourcePublicDB,
26
21
  protected publicStateDB: PublicStateDB,
27
- phase: PublicKernelPhase = PublicKernelPhase.SETUP,
22
+ phase: PublicKernelType = PublicKernelType.SETUP,
28
23
  ) {
29
24
  super(db, publicExecutor, publicKernel, globalVariables, historicalHeader, phase);
30
25
  }
31
26
 
32
- override async handle(
33
- tx: Tx,
34
- previousPublicKernelOutput: PublicKernelCircuitPublicInputs,
35
- previousPublicKernelProof: Proof,
36
- ) {
27
+ override async handle(tx: Tx, previousPublicKernelOutput: PublicKernelCircuitPublicInputs) {
37
28
  this.log.verbose(`Processing tx ${tx.getTxHash()}`);
38
- const [
39
- kernelInputs,
40
- publicKernelOutput,
41
- publicKernelProof,
42
- newUnencryptedFunctionLogs,
43
- revertReason,
44
- _returnValues,
45
- gasUsed,
46
- ] = await this.processEnqueuedPublicCalls(tx, previousPublicKernelOutput, previousPublicKernelProof).catch(
47
- // the abstract phase manager throws if simulation gives error in a non-revertible phase
48
- async err => {
49
- await this.publicStateDB.rollbackToCommit();
50
- throw err;
51
- },
52
- );
53
- tx.unencryptedLogs.addFunctionLogs(newUnencryptedFunctionLogs);
29
+ // TODO(#6464): Should we allow emitting contracts in the private setup phase?
30
+ // if so, this should only add contracts that were deployed during private app logic.
31
+ await this.publicContractsDB.addNewContracts(tx);
32
+ const { publicProvingInformation, kernelOutput, newUnencryptedLogs, revertReason, gasUsed } =
33
+ await this.processEnqueuedPublicCalls(tx, previousPublicKernelOutput).catch(
34
+ // the abstract phase manager throws if simulation gives error in a non-revertible phase
35
+ async err => {
36
+ await this.publicStateDB.rollbackToCommit();
37
+ throw err;
38
+ },
39
+ );
40
+ tx.unencryptedLogs.addFunctionLogs(newUnencryptedLogs);
54
41
  await this.publicStateDB.checkpoint();
55
42
 
56
43
  // Return a list of setup proving requests
57
- const kernelRequests = kernelInputs.map(input => {
58
- const request: PublicKernelRequest = {
59
- type: PublicKernelType.SETUP,
60
- inputs: input,
61
- };
62
- return request;
44
+ const publicProvingRequests: PublicProvingRequest[] = publicProvingInformation.map(info => {
45
+ return makeAvmProvingRequest(info, PublicKernelType.SETUP);
63
46
  });
64
- return {
65
- kernelRequests,
66
- kernelInputs,
67
- publicKernelOutput,
68
- publicKernelProof,
69
- revertReason,
70
- returnValues: [],
71
- gasUsed,
72
- };
47
+ return { publicProvingRequests, publicKernelOutput: kernelOutput, revertReason, returnValues: [], gasUsed };
73
48
  }
74
49
  }