@aztec/simulator 0.40.1 → 0.42.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 (234) 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 +6 -2
  5. package/dest/acvm/oracle/oracle.d.ts.map +1 -1
  6. package/dest/acvm/oracle/oracle.js +31 -19
  7. package/dest/acvm/oracle/typed_oracle.d.ts +8 -11
  8. package/dest/acvm/oracle/typed_oracle.d.ts.map +1 -1
  9. package/dest/acvm/oracle/typed_oracle.js +17 -5
  10. package/dest/acvm/serialize.js +2 -2
  11. package/dest/avm/avm_execution_environment.d.ts +4 -3
  12. package/dest/avm/avm_execution_environment.d.ts.map +1 -1
  13. package/dest/avm/avm_execution_environment.js +7 -5
  14. package/dest/avm/avm_gas.d.ts +1 -5
  15. package/dest/avm/avm_gas.d.ts.map +1 -1
  16. package/dest/avm/avm_gas.js +67 -73
  17. package/dest/avm/avm_simulator.d.ts +5 -0
  18. package/dest/avm/avm_simulator.d.ts.map +1 -1
  19. package/dest/avm/avm_simulator.js +12 -4
  20. package/dest/avm/errors.d.ts +6 -0
  21. package/dest/avm/errors.d.ts.map +1 -1
  22. package/dest/avm/errors.js +10 -1
  23. package/dest/avm/fixtures/index.d.ts +3 -0
  24. package/dest/avm/fixtures/index.d.ts.map +1 -1
  25. package/dest/avm/fixtures/index.js +15 -3
  26. package/dest/avm/index.d.ts +2 -0
  27. package/dest/avm/index.d.ts.map +1 -0
  28. package/dest/avm/index.js +2 -0
  29. package/dest/avm/journal/host_storage.d.ts +1 -1
  30. package/dest/avm/journal/host_storage.d.ts.map +1 -1
  31. package/dest/avm/journal/journal.d.ts +4 -3
  32. package/dest/avm/journal/journal.d.ts.map +1 -1
  33. package/dest/avm/journal/journal.js +10 -11
  34. package/dest/avm/journal/nullifiers.d.ts +17 -5
  35. package/dest/avm/journal/nullifiers.d.ts.map +1 -1
  36. package/dest/avm/journal/nullifiers.js +27 -10
  37. package/dest/avm/journal/public_storage.d.ts +19 -6
  38. package/dest/avm/journal/public_storage.d.ts.map +1 -1
  39. package/dest/avm/journal/public_storage.js +30 -12
  40. package/dest/avm/journal/trace.d.ts +2 -0
  41. package/dest/avm/journal/trace.d.ts.map +1 -1
  42. package/dest/avm/journal/trace.js +7 -1
  43. package/dest/avm/journal/trace_types.d.ts +1 -0
  44. package/dest/avm/journal/trace_types.d.ts.map +1 -1
  45. package/dest/avm/journal/trace_types.js +1 -1
  46. package/dest/avm/opcodes/accrued_substate.d.ts.map +1 -1
  47. package/dest/avm/opcodes/accrued_substate.js +6 -7
  48. package/dest/avm/opcodes/arithmetic.d.ts +1 -7
  49. package/dest/avm/opcodes/arithmetic.d.ts.map +1 -1
  50. package/dest/avm/opcodes/arithmetic.js +1 -12
  51. package/dest/avm/opcodes/conversion.js +2 -2
  52. package/dest/avm/opcodes/external_calls.d.ts +2 -2
  53. package/dest/avm/opcodes/external_calls.d.ts.map +1 -1
  54. package/dest/avm/opcodes/external_calls.js +25 -13
  55. package/dest/avm/opcodes/instruction.d.ts +1 -1
  56. package/dest/avm/opcodes/instruction.d.ts.map +1 -1
  57. package/dest/avm/opcodes/instruction.js +6 -4
  58. package/dest/avm/opcodes/memory.d.ts +0 -4
  59. package/dest/avm/opcodes/memory.d.ts.map +1 -1
  60. package/dest/avm/opcodes/memory.js +1 -7
  61. package/dest/avm/opcodes/storage.d.ts +0 -12
  62. package/dest/avm/opcodes/storage.d.ts.map +1 -1
  63. package/dest/avm/opcodes/storage.js +3 -18
  64. package/dest/avm/serialization/bytecode_serialization.js +2 -2
  65. package/dest/client/client_execution_context.d.ts +30 -20
  66. package/dest/client/client_execution_context.d.ts.map +1 -1
  67. package/dest/client/client_execution_context.js +59 -39
  68. package/dest/client/db_oracle.d.ts +17 -12
  69. package/dest/client/db_oracle.d.ts.map +1 -1
  70. package/dest/client/execution_note_cache.js +2 -2
  71. package/dest/client/execution_result.d.ts +17 -2
  72. package/dest/client/execution_result.d.ts.map +1 -1
  73. package/dest/client/execution_result.js +32 -4
  74. package/dest/client/private_execution.d.ts +2 -3
  75. package/dest/client/private_execution.d.ts.map +1 -1
  76. package/dest/client/private_execution.js +22 -8
  77. package/dest/client/simulator.d.ts +0 -16
  78. package/dest/client/simulator.d.ts.map +1 -1
  79. package/dest/client/simulator.js +13 -30
  80. package/dest/client/unconstrained_execution.d.ts +2 -3
  81. package/dest/client/unconstrained_execution.d.ts.map +1 -1
  82. package/dest/client/unconstrained_execution.js +5 -7
  83. package/dest/client/view_data_oracle.d.ts +12 -10
  84. package/dest/client/view_data_oracle.d.ts.map +1 -1
  85. package/dest/client/view_data_oracle.js +17 -11
  86. package/dest/common/index.d.ts +1 -0
  87. package/dest/common/index.d.ts.map +1 -1
  88. package/dest/common/index.js +2 -1
  89. package/dest/common/return_values.d.ts +11 -0
  90. package/dest/common/return_values.d.ts.map +1 -0
  91. package/dest/common/return_values.js +13 -0
  92. package/dest/index.d.ts +3 -1
  93. package/dest/index.d.ts.map +1 -1
  94. package/dest/index.js +4 -2
  95. package/dest/mocks/fixtures.d.ts +15 -10
  96. package/dest/mocks/fixtures.d.ts.map +1 -1
  97. package/dest/mocks/fixtures.js +22 -17
  98. package/dest/{simulator → providers}/acvm_native.d.ts.map +1 -1
  99. package/dest/{simulator → providers}/acvm_native.js +13 -14
  100. package/dest/providers/acvm_wasm.d.ts.map +1 -0
  101. package/dest/providers/acvm_wasm.js +15 -0
  102. package/dest/providers/index.d.ts.map +1 -0
  103. package/dest/{simulator → providers}/index.js +1 -1
  104. package/dest/{simulator → providers}/simulation_provider.d.ts.map +1 -1
  105. package/dest/{simulator → providers}/simulation_provider.js +1 -1
  106. package/dest/public/abstract_phase_manager.d.ts +43 -42
  107. package/dest/public/abstract_phase_manager.d.ts.map +1 -1
  108. package/dest/public/abstract_phase_manager.js +81 -103
  109. package/dest/public/app_logic_phase_manager.d.ts +7 -8
  110. package/dest/public/app_logic_phase_manager.d.ts.map +1 -1
  111. package/dest/public/app_logic_phase_manager.js +14 -14
  112. package/dest/public/{db.d.ts → db_interfaces.d.ts} +3 -3
  113. package/dest/public/db_interfaces.d.ts.map +1 -0
  114. package/dest/public/db_interfaces.js +2 -0
  115. package/dest/public/execution.d.ts +17 -14
  116. package/dest/public/execution.d.ts.map +1 -1
  117. package/dest/public/execution.js +1 -1
  118. package/dest/public/executor.d.ts +3 -30
  119. package/dest/public/executor.d.ts.map +1 -1
  120. package/dest/public/executor.js +32 -279
  121. package/dest/public/fee_payment.d.ts +11 -0
  122. package/dest/public/fee_payment.d.ts.map +1 -0
  123. package/dest/public/fee_payment.js +24 -0
  124. package/dest/public/hints_builder.d.ts +3 -2
  125. package/dest/public/hints_builder.d.ts.map +1 -1
  126. package/dest/public/hints_builder.js +8 -4
  127. package/dest/public/index.d.ts +4 -2
  128. package/dest/public/index.d.ts.map +1 -1
  129. package/dest/public/index.js +5 -3
  130. package/dest/public/phase_manager_factory.d.ts +1 -1
  131. package/dest/public/phase_manager_factory.d.ts.map +1 -1
  132. package/dest/public/{public_executor.d.ts → public_db_sources.d.ts} +3 -2
  133. package/dest/public/public_db_sources.d.ts.map +1 -0
  134. package/dest/public/public_db_sources.js +198 -0
  135. package/dest/public/public_kernel.js +14 -14
  136. package/dest/public/public_processor.d.ts +8 -6
  137. package/dest/public/public_processor.d.ts.map +1 -1
  138. package/dest/public/public_processor.js +48 -29
  139. package/dest/public/setup_phase_manager.d.ts +7 -9
  140. package/dest/public/setup_phase_manager.d.ts.map +1 -1
  141. package/dest/public/setup_phase_manager.js +11 -20
  142. package/dest/public/tail_phase_manager.d.ts +5 -11
  143. package/dest/public/tail_phase_manager.d.ts.map +1 -1
  144. package/dest/public/tail_phase_manager.js +16 -36
  145. package/dest/public/teardown_phase_manager.d.ts +7 -9
  146. package/dest/public/teardown_phase_manager.d.ts.map +1 -1
  147. package/dest/public/teardown_phase_manager.js +15 -21
  148. package/dest/public/transitional_adaptors.d.ts +3 -2
  149. package/dest/public/transitional_adaptors.d.ts.map +1 -1
  150. package/dest/public/transitional_adaptors.js +24 -8
  151. package/dest/public/utils.d.ts +2 -2
  152. package/dest/public/utils.d.ts.map +1 -1
  153. package/dest/public/utils.js +21 -14
  154. package/package.json +12 -9
  155. package/src/acvm/acvm.ts +0 -3
  156. package/src/acvm/oracle/oracle.ts +53 -27
  157. package/src/acvm/oracle/typed_oracle.ts +25 -16
  158. package/src/acvm/serialize.ts +1 -1
  159. package/src/avm/avm_execution_environment.ts +9 -5
  160. package/src/avm/avm_gas.ts +66 -73
  161. package/src/avm/avm_simulator.ts +14 -3
  162. package/src/avm/errors.ts +10 -0
  163. package/src/avm/fixtures/index.ts +22 -2
  164. package/src/avm/index.ts +1 -0
  165. package/src/avm/journal/host_storage.ts +1 -1
  166. package/src/avm/journal/journal.ts +15 -14
  167. package/src/avm/journal/nullifiers.ts +27 -14
  168. package/src/avm/journal/public_storage.ts +30 -16
  169. package/src/avm/journal/trace.ts +12 -0
  170. package/src/avm/journal/trace_types.ts +1 -0
  171. package/src/avm/opcodes/accrued_substate.ts +5 -6
  172. package/src/avm/opcodes/arithmetic.ts +1 -14
  173. package/src/avm/opcodes/conversion.ts +1 -1
  174. package/src/avm/opcodes/external_calls.ts +26 -10
  175. package/src/avm/opcodes/instruction.ts +5 -3
  176. package/src/avm/opcodes/memory.ts +1 -8
  177. package/src/avm/opcodes/storage.ts +3 -20
  178. package/src/avm/serialization/bytecode_serialization.ts +1 -1
  179. package/src/client/client_execution_context.ts +70 -44
  180. package/src/client/db_oracle.ts +18 -12
  181. package/src/client/execution_note_cache.ts +1 -1
  182. package/src/client/execution_result.ts +41 -3
  183. package/src/client/private_execution.ts +38 -20
  184. package/src/client/simulator.ts +11 -32
  185. package/src/client/unconstrained_execution.ts +9 -12
  186. package/src/client/view_data_oracle.ts +20 -12
  187. package/src/common/index.ts +1 -0
  188. package/src/common/return_values.ts +18 -0
  189. package/src/index.ts +3 -1
  190. package/src/mocks/fixtures.ts +31 -33
  191. package/src/{simulator → providers}/acvm_native.ts +21 -19
  192. package/src/{simulator → providers}/acvm_wasm.ts +2 -16
  193. package/src/public/abstract_phase_manager.ts +146 -207
  194. package/src/public/app_logic_phase_manager.ts +23 -39
  195. package/src/public/{db.ts → db_interfaces.ts} +2 -2
  196. package/src/public/execution.ts +17 -14
  197. package/src/public/executor.ts +51 -391
  198. package/src/public/fee_payment.ts +26 -0
  199. package/src/public/hints_builder.ts +17 -3
  200. package/src/public/index.ts +4 -2
  201. package/src/public/phase_manager_factory.ts +1 -1
  202. package/src/public/{public_executor.ts → public_db_sources.ts} +3 -2
  203. package/src/public/public_kernel.ts +24 -24
  204. package/src/public/public_processor.ts +82 -38
  205. package/src/public/setup_phase_manager.ts +20 -45
  206. package/src/public/tail_phase_manager.ts +18 -68
  207. package/src/public/teardown_phase_manager.ts +22 -41
  208. package/src/public/transitional_adaptors.ts +24 -13
  209. package/src/public/utils.ts +20 -14
  210. package/dest/client/logs_cache.d.ts +0 -33
  211. package/dest/client/logs_cache.d.ts.map +0 -1
  212. package/dest/client/logs_cache.js +0 -59
  213. package/dest/public/db.d.ts.map +0 -1
  214. package/dest/public/db.js +0 -2
  215. package/dest/public/public_execution_context.d.ts +0 -121
  216. package/dest/public/public_execution_context.d.ts.map +0 -1
  217. package/dest/public/public_execution_context.js +0 -214
  218. package/dest/public/public_executor.d.ts.map +0 -1
  219. package/dest/public/public_executor.js +0 -197
  220. package/dest/public/state_actions.d.ts +0 -39
  221. package/dest/public/state_actions.d.ts.map +0 -1
  222. package/dest/public/state_actions.js +0 -80
  223. package/dest/simulator/acvm_wasm.d.ts.map +0 -1
  224. package/dest/simulator/acvm_wasm.js +0 -22
  225. package/dest/simulator/index.d.ts.map +0 -1
  226. package/src/client/logs_cache.ts +0 -65
  227. package/src/public/public_execution_context.ts +0 -289
  228. package/src/public/state_actions.ts +0 -102
  229. /package/dest/{simulator → providers}/acvm_native.d.ts +0 -0
  230. /package/dest/{simulator → providers}/acvm_wasm.d.ts +0 -0
  231. /package/dest/{simulator → providers}/index.d.ts +0 -0
  232. /package/dest/{simulator → providers}/simulation_provider.d.ts +0 -0
  233. /package/src/{simulator → providers}/index.ts +0 -0
  234. /package/src/{simulator → providers}/simulation_provider.ts +0 -0
@@ -1,16 +1,17 @@
1
1
  import { type SimulationError, type UnencryptedFunctionL2Logs } from '@aztec/circuit-types';
2
2
  import {
3
+ type AvmExecutionHints,
3
4
  type ContractStorageRead,
4
5
  type ContractStorageUpdateRequest,
5
6
  type Fr,
6
7
  type L2ToL1Message,
8
+ type LogHash,
7
9
  type NoteHash,
8
10
  type Nullifier,
9
11
  type PublicCallRequest,
10
12
  PublicDataRead,
11
13
  PublicDataUpdateRequest,
12
14
  type ReadRequest,
13
- type SideEffect,
14
15
  } from '@aztec/circuits.js';
15
16
  import { computePublicDataTreeLeafSlot, computePublicDataTreeValue } from '@aztec/circuits.js/hash';
16
17
 
@@ -34,10 +35,14 @@ export interface PublicExecutionResult {
34
35
  endSideEffectCounter: Fr;
35
36
  /** The new nullifiers to be inserted into the nullifier tree. */
36
37
  newNullifiers: Nullifier[];
38
+ /** The note hash read requests emitted in this call. */
39
+ noteHashReadRequests: ReadRequest[];
37
40
  /** The nullifier read requests emitted in this call. */
38
41
  nullifierReadRequests: ReadRequest[];
39
42
  /** The nullifier non existent read requests emitted in this call. */
40
43
  nullifierNonExistentReadRequests: ReadRequest[];
44
+ /** L1 to L2 message read requests emitted in this call. */
45
+ l1ToL2MsgReadRequests: ReadRequest[];
41
46
  /** The contract storage reads performed by the function. */
42
47
  contractStorageReads: ContractStorageRead[];
43
48
  /** The contract storage update requests performed by the function. */
@@ -48,41 +53,39 @@ export interface PublicExecutionResult {
48
53
  * The hashed logs with side effect counter.
49
54
  * Note: required as we don't track the counter anywhere else.
50
55
  */
51
- unencryptedLogsHashes: SideEffect[];
56
+ unencryptedLogsHashes: LogHash[];
52
57
  /**
53
58
  * Unencrypted logs emitted during execution of this function call.
54
59
  * Note: These are preimages to `unencryptedLogsHashes`.
55
60
  */
56
61
  unencryptedLogs: UnencryptedFunctionL2Logs;
57
- /**
58
- * Length of the unencrypted log preimages emitted in this function call.
59
- */
60
- unencryptedLogPreimagesLength: Fr;
61
62
  /**
62
63
  * Unencrypted logs emitted during this call AND any nested calls.
63
64
  * Useful for maintaining correct ordering in ts.
64
65
  */
65
66
  allUnencryptedLogs: UnencryptedFunctionL2Logs;
66
- /**
67
- * Whether the execution reverted.
68
- */
67
+ /** Whether the execution reverted. */
69
68
  reverted: boolean;
70
- /**
71
- * The revert reason if the execution reverted.
72
- */
73
- revertReason: SimulationError | undefined;
69
+ /** The revert reason if the execution reverted. */
70
+ revertReason?: SimulationError;
74
71
  /** How much gas was available for this public execution. */
75
72
  startGasLeft: Gas;
76
73
  /** How much gas was left after this public execution. */
77
74
  endGasLeft: Gas;
78
75
  /** Transaction fee set for this tx. */
79
76
  transactionFee: Fr;
77
+ /** Bytecode used for this execution. */
78
+ bytecode?: Buffer;
79
+ /** Calldata used for this execution. */
80
+ calldata: Fr[];
81
+ /** Hints for proving AVM execution. */
82
+ avmHints: AvmExecutionHints;
80
83
  }
81
84
 
82
85
  /**
83
86
  * The execution of a public function.
84
87
  */
85
- export type PublicExecution = Pick<PublicCallRequest, 'contractAddress' | 'functionData' | 'callContext' | 'args'>;
88
+ export type PublicExecution = Pick<PublicCallRequest, 'contractAddress' | 'functionSelector' | 'callContext' | 'args'>;
86
89
 
87
90
  /**
88
91
  * Returns if the input is a public execution result and not just a public execution.
@@ -1,270 +1,14 @@
1
- import { UnencryptedFunctionL2Logs } from '@aztec/circuit-types';
2
- import {
3
- Fr,
4
- Gas,
5
- type GlobalVariables,
6
- type Header,
7
- type Nullifier,
8
- PublicCircuitPublicInputs,
9
- type TxContext,
10
- } from '@aztec/circuits.js';
1
+ import { Fr, type Gas, type GlobalVariables, type Header, type Nullifier, type TxContext } from '@aztec/circuits.js';
11
2
  import { createDebugLogger } from '@aztec/foundation/log';
12
3
 
13
- import { spawn } from 'child_process';
14
- import fs from 'fs/promises';
15
- import path from 'path';
16
-
17
- import { Oracle, acvm, extractCallStack, witnessMapToFields } from '../acvm/index.js';
18
4
  import { AvmContext } from '../avm/avm_context.js';
19
5
  import { AvmMachineState } from '../avm/avm_machine_state.js';
20
6
  import { AvmSimulator } from '../avm/avm_simulator.js';
21
7
  import { HostStorage } from '../avm/journal/host_storage.js';
22
8
  import { AvmPersistableStateManager } from '../avm/journal/index.js';
23
- import { AcirSimulator } from '../client/simulator.js';
24
- import { ExecutionError, createSimulationError } from '../common/errors.js';
25
- import { SideEffectCounter } from '../common/index.js';
26
- import { PackedValuesCache } from '../common/packed_values_cache.js';
27
- import { type CommitmentsDB, type PublicContractsDB, type PublicStateDB } from './db.js';
9
+ import { type CommitmentsDB, type PublicContractsDB, type PublicStateDB } from './db_interfaces.js';
28
10
  import { type PublicExecution, type PublicExecutionResult, checkValidStaticCall } from './execution.js';
29
- import { PublicExecutionContext } from './public_execution_context.js';
30
- import { convertAvmResultsToPxResult, createAvmExecutionEnvironment, isAvmBytecode } from './transitional_adaptors.js';
31
-
32
- /**
33
- * Execute a public function and return the execution result.
34
- */
35
- export async function executePublicFunction(
36
- context: PublicExecutionContext,
37
- nested: boolean,
38
- ): Promise<PublicExecutionResult> {
39
- const bytecode = await context.contractsDb.getBytecode(
40
- context.execution.contractAddress,
41
- context.execution.functionData.selector,
42
- );
43
- if (!bytecode) {
44
- throw new Error(
45
- `Bytecode not found for ${context.execution.contractAddress}:${context.execution.functionData.selector}`,
46
- );
47
- }
48
-
49
- if (isAvmBytecode(bytecode)) {
50
- return await executeTopLevelPublicFunctionAvm(context, bytecode);
51
- } else {
52
- return await executePublicFunctionAcvm(context, bytecode, nested);
53
- }
54
- }
55
-
56
- /**
57
- * Execute a top-level public function call (the first call in an enqueued-call/execution-request) in the AVM.
58
- * Translate the results back to the PublicExecutionResult format.
59
- */
60
- async function executeTopLevelPublicFunctionAvm(
61
- executionContext: PublicExecutionContext,
62
- bytecode: Buffer,
63
- ): Promise<PublicExecutionResult> {
64
- const address = executionContext.execution.contractAddress;
65
- const selector = executionContext.execution.functionData.selector;
66
- const startGas = executionContext.availableGas;
67
- const log = createDebugLogger('aztec:simulator:public_execution');
68
- log.verbose(`[AVM] Executing public external function ${address.toString()}:${selector}.`);
69
-
70
- // Temporary code to construct the AVM context
71
- // These data structures will permeate across the simulator when the public executor is phased out
72
- const hostStorage = new HostStorage(
73
- executionContext.stateDb,
74
- executionContext.contractsDb,
75
- executionContext.commitmentsDb,
76
- );
77
-
78
- // TODO(6207): add sideEffectCounter to persistableState construction
79
- // or modify the PersistableStateManager to manage rollbacks across enqueued-calls and transactions.
80
- const worldStateJournal = new AvmPersistableStateManager(hostStorage);
81
- const startSideEffectCounter = executionContext.execution.callContext.sideEffectCounter;
82
- for (const nullifier of executionContext.pendingNullifiers) {
83
- worldStateJournal.nullifiers.cache.appendSiloed(nullifier.value);
84
- }
85
- worldStateJournal.trace.accessCounter = startSideEffectCounter;
86
-
87
- const executionEnv = createAvmExecutionEnvironment(
88
- executionContext.execution,
89
- executionContext.header,
90
- executionContext.globalVariables,
91
- executionContext.gasSettings,
92
- executionContext.transactionFee,
93
- );
94
-
95
- const machineState = new AvmMachineState(startGas);
96
- const avmContext = new AvmContext(worldStateJournal, executionEnv, machineState);
97
- const simulator = new AvmSimulator(avmContext);
98
-
99
- const avmResult = await simulator.executeBytecode(bytecode);
100
-
101
- // Commit the journals state to the DBs since this is a top-level execution.
102
- // Observe that this will write all the state changes to the DBs, not only the latest for each slot.
103
- // However, the underlying DB keep a cache and will only write the latest state to disk.
104
- await avmContext.persistableState.publicStorage.commitToDB();
105
-
106
- log.verbose(
107
- `[AVM] ${address.toString()}:${selector} returned, reverted: ${avmResult.reverted}, reason: ${
108
- avmResult.revertReason
109
- }.`,
110
- );
111
-
112
- return convertAvmResultsToPxResult(
113
- avmResult,
114
- startSideEffectCounter,
115
- executionContext.execution,
116
- startGas,
117
- avmContext,
118
- );
119
- }
120
-
121
- async function executePublicFunctionAcvm(
122
- context: PublicExecutionContext,
123
- acir: Buffer,
124
- nested: boolean,
125
- ): Promise<PublicExecutionResult> {
126
- const execution = context.execution;
127
- const { contractAddress, functionData } = execution;
128
- const selector = functionData.selector;
129
- const log = createDebugLogger('aztec:simulator:public_execution');
130
- log.verbose(`[ACVM] Executing public external function ${contractAddress.toString()}:${selector}.`);
131
-
132
- const initialWitness = context.getInitialWitness();
133
- const acvmCallback = new Oracle(context);
134
-
135
- const { partialWitness, returnWitnessMap, reverted, revertReason } = await (async () => {
136
- try {
137
- const result = await acvm(await AcirSimulator.getSolver(), acir, initialWitness, acvmCallback);
138
- return {
139
- partialWitness: result.partialWitness,
140
- returnWitnessMap: result.returnWitness,
141
- reverted: false,
142
- revertReason: undefined,
143
- };
144
- } catch (err_) {
145
- const err = err_ as Error;
146
- const ee = new ExecutionError(
147
- err.message,
148
- {
149
- contractAddress,
150
- functionSelector: selector,
151
- },
152
- extractCallStack(err),
153
- { cause: err },
154
- );
155
-
156
- if (nested) {
157
- // If we're nested, throw the error so the parent can handle it
158
- throw ee;
159
- } else {
160
- return {
161
- partialWitness: undefined,
162
- returnWitnessMap: undefined,
163
- reverted: true,
164
- revertReason: createSimulationError(ee),
165
- };
166
- }
167
- }
168
- })();
169
-
170
- if (reverted) {
171
- return {
172
- execution,
173
- returnValues: [],
174
- newNoteHashes: [],
175
- newL2ToL1Messages: [],
176
- // TODO (side effects) get these values in the revert case from the vm
177
- startSideEffectCounter: Fr.ZERO,
178
- endSideEffectCounter: Fr.ZERO,
179
- newNullifiers: [],
180
- nullifierReadRequests: [],
181
- nullifierNonExistentReadRequests: [],
182
- contractStorageReads: [],
183
- contractStorageUpdateRequests: [],
184
- nestedExecutions: [],
185
- unencryptedLogsHashes: [],
186
- unencryptedLogs: UnencryptedFunctionL2Logs.empty(),
187
- unencryptedLogPreimagesLength: new Fr(4n), // empty logs have len 4
188
- allUnencryptedLogs: UnencryptedFunctionL2Logs.empty(),
189
- reverted,
190
- revertReason,
191
- startGasLeft: context.availableGas,
192
- endGasLeft: Gas.empty(),
193
- transactionFee: context.transactionFee,
194
- };
195
- }
196
-
197
- if (!partialWitness) {
198
- throw new Error('No partial witness returned from ACVM');
199
- }
200
-
201
- const returnWitness = witnessMapToFields(returnWitnessMap);
202
- const {
203
- returnsHash,
204
- nullifierReadRequests: nullifierReadRequestsPadded,
205
- nullifierNonExistentReadRequests: nullifierNonExistentReadRequestsPadded,
206
- newL2ToL1Msgs,
207
- newNoteHashes: newNoteHashesPadded,
208
- newNullifiers: newNullifiersPadded,
209
- startSideEffectCounter,
210
- endSideEffectCounter,
211
- unencryptedLogsHashes: unencryptedLogsHashesPadded,
212
- unencryptedLogPreimagesLength,
213
- } = PublicCircuitPublicInputs.fromFields(returnWitness);
214
- const returnValues = await context.unpackReturns(returnsHash);
215
-
216
- const nullifierReadRequests = nullifierReadRequestsPadded.filter(v => !v.isEmpty());
217
- const nullifierNonExistentReadRequests = nullifierNonExistentReadRequestsPadded.filter(v => !v.isEmpty());
218
- const newL2ToL1Messages = newL2ToL1Msgs.filter(v => !v.isEmpty());
219
- const newNoteHashes = newNoteHashesPadded.filter(v => !v.isEmpty());
220
- const newNullifiers = newNullifiersPadded.filter(v => !v.isEmpty());
221
- const unencryptedLogsHashes = unencryptedLogsHashesPadded.filter(v => !v.isEmpty());
222
-
223
- const { contractStorageReads, contractStorageUpdateRequests } = context.getStorageActionData();
224
-
225
- log.debug(
226
- `Contract storage reads: ${contractStorageReads
227
- .map(r => r.toFriendlyJSON() + ` - sec: ${r.sideEffectCounter}`)
228
- .join(', ')}`,
229
- );
230
- log.debug(
231
- `Contract storage update requests: ${contractStorageUpdateRequests
232
- .map(r => r.toFriendlyJSON() + ` - sec: ${r.sideEffectCounter}`)
233
- .join(', ')}`,
234
- );
235
-
236
- const nestedExecutions = context.getNestedExecutions();
237
- const unencryptedLogs = context.getUnencryptedLogs();
238
- const allUnencryptedLogs = context.getAllUnencryptedLogs();
239
-
240
- // TODO(palla/gas): We should be loading these values from the returned PublicCircuitPublicInputs
241
- const startGasLeft = context.availableGas;
242
- const endGasLeft = context.availableGas; // No gas consumption in non-AVM
243
-
244
- return {
245
- execution,
246
- newNoteHashes,
247
- newL2ToL1Messages,
248
- newNullifiers,
249
- startSideEffectCounter,
250
- endSideEffectCounter,
251
- nullifierReadRequests,
252
- nullifierNonExistentReadRequests,
253
- contractStorageReads,
254
- contractStorageUpdateRequests,
255
- returnValues,
256
- nestedExecutions,
257
- unencryptedLogsHashes,
258
- unencryptedLogs,
259
- unencryptedLogPreimagesLength,
260
- allUnencryptedLogs,
261
- reverted: false,
262
- revertReason: undefined,
263
- startGasLeft,
264
- endGasLeft,
265
- transactionFee: context.transactionFee,
266
- };
267
- }
11
+ import { convertAvmResultsToPxResult, createAvmExecutionEnvironment } from './transitional_adaptors.js';
268
12
 
269
13
  /**
270
14
  * Handles execution of public functions.
@@ -277,7 +21,8 @@ export class PublicExecutor {
277
21
  private readonly header: Header,
278
22
  ) {}
279
23
 
280
- private readonly log = createDebugLogger('aztec:simulator:public_executor');
24
+ static readonly log = createDebugLogger('aztec:simulator:public_executor');
25
+
281
26
  /**
282
27
  * Executes a public execution request.
283
28
  * @param execution - The execution to run.
@@ -293,28 +38,60 @@ export class PublicExecutor {
293
38
  transactionFee: Fr = Fr.ZERO,
294
39
  sideEffectCounter: number = 0,
295
40
  ): Promise<PublicExecutionResult> {
296
- // Functions can request to pack arguments before calling other functions.
297
- // We use this cache to hold the packed arguments.
298
- const packedArgs = PackedValuesCache.create([]);
41
+ const address = execution.contractAddress;
42
+ const selector = execution.functionSelector;
43
+ const startGas = availableGas;
44
+
45
+ PublicExecutor.log.verbose(`[AVM] Executing public external function ${address.toString()}:${selector}.`);
46
+
47
+ // Temporary code to construct the AVM context
48
+ // These data structures will permeate across the simulator when the public executor is phased out
49
+ const hostStorage = new HostStorage(this.stateDb, this.contractsDb, this.commitmentsDb);
50
+
51
+ const startSideEffectCounter = sideEffectCounter;
52
+ const worldStateJournal = new AvmPersistableStateManager(hostStorage);
53
+ for (const nullifier of pendingNullifiers) {
54
+ worldStateJournal.nullifiers.cache.appendSiloed(nullifier.value);
55
+ }
56
+ // All the subsequent side effects will have a counter larger than the call's start counter.
57
+ worldStateJournal.trace.accessCounter = startSideEffectCounter + 1;
299
58
 
300
- const context = new PublicExecutionContext(
59
+ const executionEnv = createAvmExecutionEnvironment(
301
60
  execution,
302
61
  this.header,
303
62
  globalVariables,
304
- packedArgs,
305
- new SideEffectCounter(sideEffectCounter),
306
- this.stateDb,
307
- this.contractsDb,
308
- this.commitmentsDb,
309
- availableGas,
310
- transactionFee,
311
63
  txContext.gasSettings,
312
- pendingNullifiers,
64
+ transactionFee,
65
+ );
66
+
67
+ const machineState = new AvmMachineState(startGas);
68
+ const avmContext = new AvmContext(worldStateJournal, executionEnv, machineState);
69
+ const simulator = new AvmSimulator(avmContext);
70
+ const avmResult = await simulator.execute();
71
+
72
+ // Commit the journals state to the DBs since this is a top-level execution.
73
+ // Observe that this will write all the state changes to the DBs, not only the latest for each slot.
74
+ // However, the underlying DB keep a cache and will only write the latest state to disk.
75
+ await avmContext.persistableState.publicStorage.commitToDB();
76
+
77
+ PublicExecutor.log.verbose(
78
+ `[AVM] ${address.toString()}:${selector} returned, reverted: ${avmResult.reverted}, reason: ${
79
+ avmResult.revertReason
80
+ }.`,
313
81
  );
314
82
 
315
- const executionResult = await executePublicFunction(context, /*nested=*/ false);
83
+ const executionResult = convertAvmResultsToPxResult(
84
+ avmResult,
85
+ startSideEffectCounter,
86
+ execution,
87
+ startGas,
88
+ avmContext,
89
+ simulator.getBytecode(),
90
+ );
316
91
 
317
- if (executionResult.execution.callContext.isStaticCall) {
92
+ // TODO(https://github.com/AztecProtocol/aztec-packages/issues/5818): is this really needed?
93
+ // should already be handled in simulation.
94
+ if (execution.callContext.isStaticCall) {
318
95
  checkValidStaticCall(
319
96
  executionResult.newNoteHashes,
320
97
  executionResult.newNullifiers,
@@ -326,121 +103,4 @@ export class PublicExecutor {
326
103
 
327
104
  return executionResult;
328
105
  }
329
-
330
- /**
331
- * These functions are currently housed in the temporary executor as it relies on access to
332
- * oracles like the contractsDB and this is the least intrusive way to achieve this.
333
- * When we remove this executor(tracking issue #4792) and have an interface that is compatible with the kernel circuits,
334
- * this will be moved to sequencer-client/prover.
335
- */
336
-
337
- /**
338
- * Generates a proof for an associated avm execution. This is currently only used for testing purposes,
339
- * as proof generation is not fully complete in the AVM yet.
340
- * @param execution - The execution to run.
341
- * @returns An AVM proof and the verification key.
342
- */
343
- public async getAvmProof(avmExecution: PublicExecution): Promise<Buffer[]> {
344
- // The paths for the barretenberg binary and the write path are hardcoded for now.
345
- const bbPath = path.resolve('../../barretenberg/cpp');
346
- const artifactsPath = path.resolve('target');
347
-
348
- // Create the directory if it does not exist
349
- await fs.rm(artifactsPath, { recursive: true, force: true });
350
- await fs.mkdir(artifactsPath, { recursive: true });
351
-
352
- const calldataPath = path.join(artifactsPath, 'calldata.bin');
353
- const bytecodePath = path.join(artifactsPath, 'avm_bytecode.bin');
354
- const proofPath = path.join(artifactsPath, 'proof');
355
-
356
- const { args, functionData, contractAddress } = avmExecution;
357
- const bytecode = await this.contractsDb.getBytecode(contractAddress, functionData.selector);
358
- // Write call data and bytecode to files.
359
- await fs.writeFile(
360
- calldataPath,
361
- args.map(c => c.toBuffer()),
362
- );
363
- await fs.writeFile(bytecodePath, bytecode!);
364
-
365
- const bbExec = path.join(bbPath, 'build', 'bin', 'bb');
366
- const bbArgs = ['avm_prove', '-b', bytecodePath, '-d', calldataPath, '-o', proofPath];
367
- this.log.debug(`calling '${bbExec} ${bbArgs.join(' ')}'`);
368
- const bbBinary = spawn(bbExec, bbArgs);
369
-
370
- // The binary writes the proof and the verification key to the write path.
371
- return new Promise((resolve, reject) => {
372
- let stdout: string = '';
373
- let stderr: string = '';
374
-
375
- bbBinary.on('close', () => {
376
- this.log.verbose(`Proof generation complete. Reading proof and vk from ${proofPath}.`);
377
- return resolve(Promise.all([fs.readFile(proofPath), fs.readFile(path.join(artifactsPath, 'vk'))]));
378
- });
379
-
380
- // Catch stdout.
381
- bbBinary.stdout.on('data', (data: Buffer) => {
382
- stdout += data.toString();
383
- });
384
- bbBinary.stdout.on('end', () => {
385
- if (stdout.length > 0) {
386
- this.log.debug(`stdout: ${stdout}`);
387
- }
388
- });
389
-
390
- // Catch stderr.
391
- bbBinary.stderr.on('data', (data: Buffer) => {
392
- stderr += data.toString();
393
- });
394
- bbBinary.stderr.on('end', () => {
395
- if (stderr.length > 0) {
396
- this.log.warn(`stderr: ${stderr}`);
397
- }
398
- });
399
-
400
- // Catch and propagate errors from spawning
401
- bbBinary.on('error', err => {
402
- reject(err);
403
- });
404
- });
405
- }
406
-
407
- /**
408
- * Verifies an AVM proof. This function is currently only used for testing purposes, as verification
409
- * is not fully complete in the AVM yet.
410
- * @param vk - The verification key to use.
411
- * @param proof - The proof to verify.
412
- * @returns True if the proof is valid, false otherwise.
413
- */
414
- async verifyAvmProof(vk: Buffer, proof: Buffer): Promise<boolean> {
415
- // The relative paths for the barretenberg binary and the write path are hardcoded for now.
416
- const bbPath = path.resolve('../../barretenberg/cpp');
417
- const artifactsPath = path.resolve('./target');
418
-
419
- const vkPath = path.join(artifactsPath, 'vk');
420
- const proofPath = path.join(artifactsPath, 'proof');
421
-
422
- // Write the verification key and the proof to files.
423
- await fs.writeFile(vkPath, vk);
424
- await fs.writeFile(proofPath, proof);
425
-
426
- const bbExec = path.join(bbPath, 'build', 'bin', 'bb');
427
- const bbArgs = ['avm_verify', '-p', proofPath];
428
- this.log.debug(`calling '${bbPath} ${bbArgs.join(' ')}'`);
429
- const bbBinary = spawn(bbExec, bbArgs);
430
-
431
- // The binary prints to stdout 1 if the proof is valid and 0 if it is not.
432
- return new Promise((resolve, reject) => {
433
- let result = Buffer.alloc(0);
434
- bbBinary.stdout.on('data', data => {
435
- result += data;
436
- });
437
- bbBinary.on('close', () => {
438
- resolve(result.toString() === '1');
439
- });
440
- // Catch and propagate errors from spawning
441
- bbBinary.on('error', err => {
442
- reject(err);
443
- });
444
- });
445
- }
446
106
  }
@@ -0,0 +1,26 @@
1
+ import { GAS_TOKEN_ADDRESS } from '@aztec/circuits.js';
2
+ import { computePublicDataTreeLeafSlot } from '@aztec/circuits.js/hash';
3
+ import { AztecAddress } from '@aztec/foundation/aztec-address';
4
+ import { Fr } from '@aztec/foundation/fields';
5
+ import { GasTokenArtifact } from '@aztec/protocol-contracts/gas-token';
6
+
7
+ import { computeSlotForMapping } from '../utils.js';
8
+
9
+ /**
10
+ * Computes the storage slot within the gas token contract for the balance of the fee payer.
11
+ */
12
+ export function computeFeePayerBalanceStorageSlot(feePayer: AztecAddress) {
13
+ return computeSlotForMapping(GasTokenArtifact.storageLayout.balances.slot, feePayer);
14
+ }
15
+
16
+ /**
17
+ * Computes the leaf slot in the public data tree for the balance of the fee payer in the gas token.
18
+ */
19
+ export function computeFeePayerBalanceLeafSlot(feePayer: AztecAddress): Fr {
20
+ if (feePayer.isZero()) {
21
+ return Fr.ZERO;
22
+ }
23
+ const gasToken = AztecAddress.fromBigInt(GAS_TOKEN_ADDRESS);
24
+ const balanceSlot = computeFeePayerBalanceStorageSlot(feePayer);
25
+ return computePublicDataTreeLeafSlot(gasToken, balanceSlot);
26
+ }
@@ -3,7 +3,7 @@ import {
3
3
  type Fr,
4
4
  type MAX_NEW_NULLIFIERS_PER_TX,
5
5
  type MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX,
6
- type MAX_NULLIFIER_READ_REQUESTS_PER_TX,
6
+ MAX_NULLIFIER_READ_REQUESTS_PER_TX,
7
7
  type MAX_PUBLIC_DATA_HINTS,
8
8
  type MAX_PUBLIC_DATA_READS_PER_TX,
9
9
  type MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX,
@@ -17,6 +17,7 @@ import {
17
17
  type PublicDataUpdateRequest,
18
18
  type ScopedReadRequest,
19
19
  buildNullifierNonExistentReadRequestHints,
20
+ buildPublicDataHint,
20
21
  buildPublicDataHints,
21
22
  buildPublicDataReadRequestHints,
22
23
  buildSiloedNullifierReadRequestHints,
@@ -27,11 +28,19 @@ import { type IndexedTreeId, type MerkleTreeOperations } from '@aztec/world-stat
27
28
  export class HintsBuilder {
28
29
  constructor(private db: MerkleTreeOperations) {}
29
30
 
30
- getNullifierReadRequestHints(
31
+ async getNullifierReadRequestHints(
31
32
  nullifierReadRequests: Tuple<ScopedReadRequest, typeof MAX_NULLIFIER_READ_REQUESTS_PER_TX>,
32
33
  pendingNullifiers: Tuple<Nullifier, typeof MAX_NEW_NULLIFIERS_PER_TX>,
33
34
  ) {
34
- return buildSiloedNullifierReadRequestHints(this, nullifierReadRequests, pendingNullifiers);
35
+ return (
36
+ await buildSiloedNullifierReadRequestHints(
37
+ this,
38
+ nullifierReadRequests,
39
+ pendingNullifiers,
40
+ MAX_NULLIFIER_READ_REQUESTS_PER_TX,
41
+ MAX_NULLIFIER_READ_REQUESTS_PER_TX,
42
+ )
43
+ ).hints;
35
44
  }
36
45
 
37
46
  getNullifierNonExistentReadRequestHints(
@@ -48,6 +57,11 @@ export class HintsBuilder {
48
57
  return buildPublicDataHints(this, publicDataReads, publicDataUpdateRequests);
49
58
  }
50
59
 
60
+ getPublicDataHint(dataAction: PublicDataRead | PublicDataUpdateRequest | bigint) {
61
+ const slot = typeof dataAction === 'bigint' ? dataAction : dataAction.leafSlot.toBigInt();
62
+ return buildPublicDataHint(this, slot);
63
+ }
64
+
51
65
  getPublicDataReadRequestHints(
52
66
  publicDataReads: Tuple<PublicDataRead, typeof MAX_PUBLIC_DATA_READS_PER_TX>,
53
67
  publicDataUpdateRequests: Tuple<PublicDataUpdateRequest, typeof MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX>,
@@ -1,4 +1,4 @@
1
- export * from './db.js';
1
+ export * from './db_interfaces.js';
2
2
  export {
3
3
  type PublicExecution,
4
4
  type PublicExecutionResult,
@@ -8,7 +8,9 @@ export {
8
8
  } from './execution.js';
9
9
  export { PublicExecutor } from './executor.js';
10
10
  export { PublicProcessor, PublicProcessorFactory } from './public_processor.js';
11
- export * from './public_executor.js';
11
+ export * from './public_db_sources.js';
12
12
  export * from './abstract_phase_manager.js';
13
13
  export * from './public_kernel_circuit_simulator.js';
14
14
  export * from './public_kernel.js';
15
+ export { HintsBuilder } from './hints_builder.js';
16
+ export * from './fee_payment.js';
@@ -5,7 +5,7 @@ import { type MerkleTreeOperations } from '@aztec/world-state';
5
5
 
6
6
  import { type AbstractPhaseManager, PublicKernelPhase } from './abstract_phase_manager.js';
7
7
  import { AppLogicPhaseManager } from './app_logic_phase_manager.js';
8
- import { type ContractsDataSourcePublicDB } from './public_executor.js';
8
+ import { type ContractsDataSourcePublicDB } from './public_db_sources.js';
9
9
  import { type PublicKernelCircuitSimulator } from './public_kernel_circuit_simulator.js';
10
10
  import { SetupPhaseManager } from './setup_phase_manager.js';
11
11
  import { TailPhaseManager } from './tail_phase_manager.js';
@@ -145,11 +145,12 @@ export class WorldStatePublicDB implements PublicStateDB {
145
145
  * @param contract - Owner of the storage.
146
146
  * @param slot - Slot to read in the contract storage.
147
147
  * @param newValue - The new value to store.
148
+ * @returns The slot of the written leaf in the public data tree.
148
149
  */
149
- public storageWrite(contract: AztecAddress, slot: Fr, newValue: Fr): Promise<void> {
150
+ public storageWrite(contract: AztecAddress, slot: Fr, newValue: Fr): Promise<bigint> {
150
151
  const index = computePublicDataTreeLeafSlot(contract, slot).value;
151
152
  this.uncommittedWriteCache.set(index, newValue);
152
- return Promise.resolve();
153
+ return Promise.resolve(index);
153
154
  }
154
155
 
155
156
  /**