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