@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,274 +1,16 @@
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 { type AvmSimulationStats } from '@aztec/circuit-types/stats';
2
+ import { Fr, type Gas, type GlobalVariables, type Header, type Nullifier, type TxContext } from '@aztec/circuits.js';
11
3
  import { createDebugLogger } from '@aztec/foundation/log';
4
+ import { Timer } from '@aztec/foundation/timer';
12
5
 
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
6
  import { AvmContext } from '../avm/avm_context.js';
20
7
  import { AvmMachineState } from '../avm/avm_machine_state.js';
21
8
  import { AvmSimulator } from '../avm/avm_simulator.js';
22
9
  import { HostStorage } from '../avm/journal/host_storage.js';
23
10
  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';
11
+ import { type CommitmentsDB, type PublicContractsDB, type PublicStateDB } from './db_interfaces.js';
29
12
  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
- }
13
+ import { convertAvmResultsToPxResult, createAvmExecutionEnvironment } from './transitional_adaptors.js';
272
14
 
273
15
  /**
274
16
  * Handles execution of public functions.
@@ -281,7 +23,8 @@ export class PublicExecutor {
281
23
  private readonly header: Header,
282
24
  ) {}
283
25
 
284
- private readonly log = createDebugLogger('aztec:simulator:public_executor');
26
+ static readonly log = createDebugLogger('aztec:simulator:public_executor');
27
+
285
28
  /**
286
29
  * Executes a public execution request.
287
30
  * @param execution - The execution to run.
@@ -295,30 +38,69 @@ export class PublicExecutor {
295
38
  txContext: TxContext,
296
39
  pendingNullifiers: Nullifier[],
297
40
  transactionFee: Fr = Fr.ZERO,
298
- sideEffectCounter: number = 0,
41
+ startSideEffectCounter: number = 0,
299
42
  ): 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([]);
43
+ const address = execution.contractAddress;
44
+ const selector = execution.functionSelector;
45
+ const startGas = availableGas;
46
+ const fnName = await this.contractsDb.getDebugFunctionName(address, selector);
47
+
48
+ PublicExecutor.log.verbose(`[AVM] Executing public external function ${fnName}.`);
49
+ const timer = new Timer();
50
+
51
+ // Temporary code to construct the AVM context
52
+ // These data structures will permeate across the simulator when the public executor is phased out
53
+ const hostStorage = new HostStorage(this.stateDb, this.contractsDb, this.commitmentsDb);
303
54
 
304
- const context = new PublicExecutionContext(
55
+ const worldStateJournal = new AvmPersistableStateManager(hostStorage);
56
+ for (const nullifier of pendingNullifiers) {
57
+ worldStateJournal.nullifiers.cache.appendSiloed(nullifier.value);
58
+ }
59
+ worldStateJournal.trace.accessCounter = startSideEffectCounter;
60
+
61
+ const executionEnv = createAvmExecutionEnvironment(
305
62
  execution,
306
63
  this.header,
307
64
  globalVariables,
308
- packedArgs,
309
- new SideEffectCounter(sideEffectCounter),
310
- this.stateDb,
311
- this.contractsDb,
312
- this.commitmentsDb,
313
- availableGas,
314
- transactionFee,
315
65
  txContext.gasSettings,
316
- pendingNullifiers,
66
+ transactionFee,
67
+ );
68
+
69
+ const machineState = new AvmMachineState(startGas);
70
+ const avmContext = new AvmContext(worldStateJournal, executionEnv, machineState);
71
+ const simulator = new AvmSimulator(avmContext);
72
+ const avmResult = await simulator.execute();
73
+ const bytecode = simulator.getBytecode();
74
+
75
+ // Commit the journals state to the DBs since this is a top-level execution.
76
+ // Observe that this will write all the state changes to the DBs, not only the latest for each slot.
77
+ // However, the underlying DB keep a cache and will only write the latest state to disk.
78
+ await avmContext.persistableState.publicStorage.commitToDB();
79
+
80
+ PublicExecutor.log.verbose(
81
+ `[AVM] ${fnName} returned, reverted: ${avmResult.reverted}${
82
+ avmResult.reverted ? ', reason: ' + avmResult.revertReason : ''
83
+ }.`,
84
+ {
85
+ eventName: 'avm-simulation',
86
+ appCircuitName: fnName ?? 'unknown',
87
+ duration: timer.ms(),
88
+ bytecodeSize: bytecode!.length,
89
+ } satisfies AvmSimulationStats,
317
90
  );
318
91
 
319
- const executionResult = await executePublicFunction(context, /*nested=*/ false);
92
+ const executionResult = convertAvmResultsToPxResult(
93
+ avmResult,
94
+ startSideEffectCounter,
95
+ execution,
96
+ startGas,
97
+ avmContext,
98
+ bytecode,
99
+ );
320
100
 
321
- if (executionResult.execution.callContext.isStaticCall) {
101
+ // TODO(https://github.com/AztecProtocol/aztec-packages/issues/5818): is this really needed?
102
+ // should already be handled in simulation.
103
+ if (execution.callContext.isStaticCall) {
322
104
  checkValidStaticCall(
323
105
  executionResult.newNoteHashes,
324
106
  executionResult.newNullifiers,
@@ -330,124 +112,4 @@ export class PublicExecutor {
330
112
 
331
113
  return executionResult;
332
114
  }
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
115
  }
@@ -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,14 +1,10 @@
1
- export * from './db.js';
2
- export {
3
- type PublicExecution,
4
- type PublicExecutionResult,
5
- isPublicExecutionResult,
6
- collectPublicDataReads,
7
- collectPublicDataUpdateRequests,
8
- } from './execution.js';
9
- export { PublicExecutor } from './executor.js';
10
- export { PublicProcessor, PublicProcessorFactory } from './public_processor.js';
11
- export * from './public_executor.js';
12
1
  export * from './abstract_phase_manager.js';
13
- export * from './public_kernel_circuit_simulator.js';
2
+ export * from './db_interfaces.js';
3
+ export { isPublicExecutionResult, type PublicExecution, type PublicExecutionResult } from './execution.js';
4
+ export { PublicExecutor } from './executor.js';
5
+ export * from './fee_payment.js';
6
+ export { HintsBuilder } from './hints_builder.js';
7
+ export * from './public_db_sources.js';
14
8
  export * from './public_kernel.js';
9
+ export * from './public_kernel_circuit_simulator.js';
10
+ export { PublicProcessor, PublicProcessorFactory } from './public_processor.js';
@@ -1,18 +1,18 @@
1
- import { type Tx } from '@aztec/circuit-types';
1
+ import { PublicKernelType, type Tx } from '@aztec/circuit-types';
2
2
  import { type GlobalVariables, type Header, type PublicKernelCircuitPublicInputs } from '@aztec/circuits.js';
3
3
  import { type PublicExecutor, type PublicStateDB } from '@aztec/simulator';
4
4
  import { type MerkleTreeOperations } from '@aztec/world-state';
5
5
 
6
- import { type AbstractPhaseManager, PublicKernelPhase } from './abstract_phase_manager.js';
6
+ import { type AbstractPhaseManager } from './abstract_phase_manager.js';
7
7
  import { AppLogicPhaseManager } from './app_logic_phase_manager.js';
8
- 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';
12
12
  import { TeardownPhaseManager } from './teardown_phase_manager.js';
13
13
 
14
14
  export class PhaseDidNotChangeError extends Error {
15
- constructor(phase: PublicKernelPhase) {
15
+ constructor(phase: PublicKernelType) {
16
16
  super(`Tried to advance the phase from [${phase}] when the circuit still needs [${phase}]`);
17
17
  }
18
18
  }
@@ -84,7 +84,7 @@ export class PhaseManagerFactory {
84
84
  if (output.needsSetup) {
85
85
  throw new CannotTransitionToSetupError();
86
86
  } else if (output.needsAppLogic) {
87
- if (currentPhaseManager.phase === PublicKernelPhase.APP_LOGIC) {
87
+ if (currentPhaseManager.phase === PublicKernelType.APP_LOGIC) {
88
88
  throw new PhaseDidNotChangeError(currentPhaseManager.phase);
89
89
  }
90
90
  return new AppLogicPhaseManager(
@@ -97,7 +97,7 @@ export class PhaseManagerFactory {
97
97
  publicStateDB,
98
98
  );
99
99
  } else if (output.needsTeardown) {
100
- if (currentPhaseManager.phase === PublicKernelPhase.TEARDOWN) {
100
+ if (currentPhaseManager.phase === PublicKernelType.TEARDOWN) {
101
101
  throw new PhaseDidNotChangeError(currentPhaseManager.phase);
102
102
  }
103
103
  return new TeardownPhaseManager(
@@ -109,7 +109,7 @@ export class PhaseManagerFactory {
109
109
  publicContractsDB,
110
110
  publicStateDB,
111
111
  );
112
- } else if (currentPhaseManager.phase !== PublicKernelPhase.TAIL) {
112
+ } else if (currentPhaseManager.phase !== PublicKernelType.TAIL) {
113
113
  return new TailPhaseManager(
114
114
  db,
115
115
  publicExecutor,