@aztec/simulator 0.55.0 → 0.56.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 (171) hide show
  1. package/dest/avm/avm_execution_environment.d.ts +0 -8
  2. package/dest/avm/avm_execution_environment.d.ts.map +1 -1
  3. package/dest/avm/avm_execution_environment.js +1 -19
  4. package/dest/avm/avm_gas.d.ts +2 -2
  5. package/dest/avm/avm_gas.d.ts.map +1 -1
  6. package/dest/avm/avm_gas.js +31 -115
  7. package/dest/avm/avm_machine_state.d.ts.map +1 -1
  8. package/dest/avm/avm_machine_state.js +6 -6
  9. package/dest/avm/avm_memory_types.d.ts +35 -7
  10. package/dest/avm/avm_memory_types.d.ts.map +1 -1
  11. package/dest/avm/avm_memory_types.js +25 -11
  12. package/dest/avm/avm_simulator.d.ts.map +1 -1
  13. package/dest/avm/avm_simulator.js +5 -6
  14. package/dest/avm/bytecode_utils.d.ts +1 -2
  15. package/dest/avm/bytecode_utils.d.ts.map +1 -1
  16. package/dest/avm/bytecode_utils.js +3 -17
  17. package/dest/avm/fixtures/index.d.ts +4 -16
  18. package/dest/avm/fixtures/index.d.ts.map +1 -1
  19. package/dest/avm/fixtures/index.js +9 -25
  20. package/dest/avm/journal/index.d.ts +0 -1
  21. package/dest/avm/journal/index.d.ts.map +1 -1
  22. package/dest/avm/journal/index.js +1 -2
  23. package/dest/avm/journal/journal.d.ts +4 -4
  24. package/dest/avm/journal/journal.d.ts.map +1 -1
  25. package/dest/avm/journal/journal.js +14 -13
  26. package/dest/avm/opcodes/bitwise.d.ts +10 -4
  27. package/dest/avm/opcodes/bitwise.d.ts.map +1 -1
  28. package/dest/avm/opcodes/bitwise.js +17 -11
  29. package/dest/avm/opcodes/commitment.js +2 -2
  30. package/dest/avm/opcodes/comparators.js +2 -2
  31. package/dest/avm/opcodes/conversion.d.ts +3 -2
  32. package/dest/avm/opcodes/conversion.d.ts.map +1 -1
  33. package/dest/avm/opcodes/conversion.js +18 -11
  34. package/dest/avm/opcodes/environment_getters.d.ts +27 -63
  35. package/dest/avm/opcodes/environment_getters.d.ts.map +1 -1
  36. package/dest/avm/opcodes/environment_getters.js +75 -80
  37. package/dest/avm/opcodes/hashing.d.ts +7 -5
  38. package/dest/avm/opcodes/hashing.d.ts.map +1 -1
  39. package/dest/avm/opcodes/hashing.js +40 -24
  40. package/dest/avm/opcodes/index.d.ts +3 -0
  41. package/dest/avm/opcodes/index.d.ts.map +1 -1
  42. package/dest/avm/opcodes/index.js +4 -1
  43. package/dest/avm/opcodes/instruction_impl.d.ts +0 -26
  44. package/dest/avm/opcodes/instruction_impl.d.ts.map +1 -1
  45. package/dest/avm/opcodes/instruction_impl.js +1 -51
  46. package/dest/avm/opcodes/memory.d.ts +7 -2
  47. package/dest/avm/opcodes/memory.d.ts.map +1 -1
  48. package/dest/avm/opcodes/memory.js +23 -6
  49. package/dest/avm/opcodes/multi_scalar_mul.d.ts.map +1 -1
  50. package/dest/avm/opcodes/multi_scalar_mul.js +7 -6
  51. package/dest/avm/serialization/bytecode_serialization.d.ts.map +1 -1
  52. package/dest/avm/serialization/bytecode_serialization.js +5 -24
  53. package/dest/avm/serialization/instruction_serialization.d.ts +48 -60
  54. package/dest/avm/serialization/instruction_serialization.d.ts.map +1 -1
  55. package/dest/avm/serialization/instruction_serialization.js +50 -63
  56. package/dest/avm/test_utils.d.ts +8 -8
  57. package/dest/avm/test_utils.d.ts.map +1 -1
  58. package/dest/avm/test_utils.js +15 -15
  59. package/dest/client/simulator.d.ts +1 -1
  60. package/dest/client/test_utils.d.ts.map +1 -1
  61. package/dest/client/test_utils.js +12 -6
  62. package/dest/client/unconstrained_execution.d.ts +2 -2
  63. package/dest/client/unconstrained_execution.d.ts.map +1 -1
  64. package/dest/client/unconstrained_execution.js +3 -3
  65. package/dest/public/enqueued_call_simulator.d.ts +43 -0
  66. package/dest/public/enqueued_call_simulator.d.ts.map +1 -0
  67. package/dest/public/enqueued_call_simulator.js +155 -0
  68. package/dest/public/enqueued_calls_processor.d.ts +44 -0
  69. package/dest/public/enqueued_calls_processor.d.ts.map +1 -0
  70. package/dest/public/enqueued_calls_processor.js +218 -0
  71. package/dest/public/execution.d.ts +4 -9
  72. package/dest/public/execution.d.ts.map +1 -1
  73. package/dest/public/execution.js +5 -10
  74. package/dest/public/executor.d.ts +3 -5
  75. package/dest/public/executor.d.ts.map +1 -1
  76. package/dest/public/executor.js +5 -9
  77. package/dest/public/hints_builder.d.ts +4 -3
  78. package/dest/public/hints_builder.d.ts.map +1 -1
  79. package/dest/public/hints_builder.js +4 -4
  80. package/dest/public/index.d.ts +3 -2
  81. package/dest/public/index.d.ts.map +1 -1
  82. package/dest/public/index.js +3 -3
  83. package/dest/public/public_db_sources.d.ts +17 -24
  84. package/dest/public/public_db_sources.d.ts.map +1 -1
  85. package/dest/public/public_db_sources.js +58 -65
  86. package/dest/public/public_kernel.d.ts +3 -9
  87. package/dest/public/public_kernel.d.ts.map +1 -1
  88. package/dest/public/public_kernel.js +13 -40
  89. package/dest/public/public_kernel_circuit_simulator.d.ts +5 -11
  90. package/dest/public/public_kernel_circuit_simulator.d.ts.map +1 -1
  91. package/dest/public/public_kernel_tail_simulator.d.ts +19 -0
  92. package/dest/public/public_kernel_tail_simulator.d.ts.map +1 -0
  93. package/dest/public/public_kernel_tail_simulator.js +45 -0
  94. package/dest/public/public_processor.d.ts +8 -5
  95. package/dest/public/public_processor.d.ts.map +1 -1
  96. package/dest/public/public_processor.js +31 -48
  97. package/dest/public/public_processor_metrics.d.ts +3 -3
  98. package/dest/public/public_processor_metrics.d.ts.map +1 -1
  99. package/dest/public/public_processor_metrics.js +1 -1
  100. package/dest/public/side_effect_trace.d.ts.map +1 -1
  101. package/dest/public/side_effect_trace.js +4 -8
  102. package/package.json +9 -9
  103. package/src/avm/avm_execution_environment.ts +1 -21
  104. package/src/avm/avm_gas.ts +30 -114
  105. package/src/avm/avm_machine_state.ts +5 -5
  106. package/src/avm/avm_memory_types.ts +31 -9
  107. package/src/avm/avm_simulator.ts +4 -5
  108. package/src/avm/bytecode_utils.ts +2 -17
  109. package/src/avm/fixtures/index.ts +12 -44
  110. package/src/avm/journal/index.ts +0 -1
  111. package/src/avm/journal/journal.ts +13 -18
  112. package/src/avm/opcodes/bitwise.ts +14 -10
  113. package/src/avm/opcodes/commitment.ts +1 -1
  114. package/src/avm/opcodes/comparators.ts +2 -2
  115. package/src/avm/opcodes/conversion.ts +19 -10
  116. package/src/avm/opcodes/environment_getters.ts +72 -99
  117. package/src/avm/opcodes/hashing.ts +47 -22
  118. package/src/avm/opcodes/index.ts +3 -0
  119. package/src/avm/opcodes/instruction_impl.ts +0 -62
  120. package/src/avm/opcodes/memory.ts +20 -6
  121. package/src/avm/opcodes/multi_scalar_mul.ts +6 -6
  122. package/src/avm/serialization/bytecode_serialization.ts +11 -33
  123. package/src/avm/serialization/instruction_serialization.ts +5 -18
  124. package/src/avm/test_utils.ts +20 -16
  125. package/src/client/test_utils.ts +36 -9
  126. package/src/client/unconstrained_execution.ts +3 -8
  127. package/src/public/enqueued_call_simulator.ts +336 -0
  128. package/src/public/enqueued_calls_processor.ts +388 -0
  129. package/src/public/execution.ts +5 -12
  130. package/src/public/executor.ts +4 -12
  131. package/src/public/hints_builder.ts +14 -12
  132. package/src/public/index.ts +3 -2
  133. package/src/public/public_db_sources.ts +62 -67
  134. package/src/public/public_kernel.ts +15 -49
  135. package/src/public/public_kernel_circuit_simulator.ts +6 -10
  136. package/src/public/public_kernel_tail_simulator.ts +106 -0
  137. package/src/public/public_processor.ts +61 -86
  138. package/src/public/public_processor_metrics.ts +3 -3
  139. package/src/public/side_effect_trace.ts +5 -12
  140. package/dest/avm/journal/host_storage.d.ts +0 -13
  141. package/dest/avm/journal/host_storage.d.ts.map +0 -1
  142. package/dest/avm/journal/host_storage.js +0 -13
  143. package/dest/avm/opcodes/context_getters.d.ts +0 -15
  144. package/dest/avm/opcodes/context_getters.d.ts.map +0 -1
  145. package/dest/avm/opcodes/context_getters.js +0 -19
  146. package/dest/public/abstract_phase_manager.d.ts +0 -93
  147. package/dest/public/abstract_phase_manager.d.ts.map +0 -1
  148. package/dest/public/abstract_phase_manager.js +0 -285
  149. package/dest/public/app_logic_phase_manager.d.ts +0 -25
  150. package/dest/public/app_logic_phase_manager.d.ts.map +0 -1
  151. package/dest/public/app_logic_phase_manager.js +0 -52
  152. package/dest/public/phase_manager_factory.d.ts +0 -18
  153. package/dest/public/phase_manager_factory.d.ts.map +0 -1
  154. package/dest/public/phase_manager_factory.js +0 -56
  155. package/dest/public/setup_phase_manager.d.ts +0 -25
  156. package/dest/public/setup_phase_manager.d.ts.map +0 -1
  157. package/dest/public/setup_phase_manager.js +0 -39
  158. package/dest/public/tail_phase_manager.d.ts +0 -23
  159. package/dest/public/tail_phase_manager.d.ts.map +0 -1
  160. package/dest/public/tail_phase_manager.js +0 -50
  161. package/dest/public/teardown_phase_manager.d.ts +0 -27
  162. package/dest/public/teardown_phase_manager.d.ts.map +0 -1
  163. package/dest/public/teardown_phase_manager.js +0 -56
  164. package/src/avm/journal/host_storage.ts +0 -14
  165. package/src/avm/opcodes/context_getters.ts +0 -23
  166. package/src/public/abstract_phase_manager.ts +0 -522
  167. package/src/public/app_logic_phase_manager.ts +0 -81
  168. package/src/public/phase_manager_factory.ts +0 -126
  169. package/src/public/setup_phase_manager.ts +0 -61
  170. package/src/public/tail_phase_manager.ts +0 -127
  171. package/src/public/teardown_phase_manager.ts +0 -86
@@ -1,522 +0,0 @@
1
- import {
2
- AVM_REQUEST,
3
- type AvmProvingRequest,
4
- MerkleTreeId,
5
- type NestedProcessReturnValues,
6
- type PublicExecutionRequest,
7
- type PublicKernelNonTailRequest,
8
- PublicKernelType,
9
- type PublicProvingRequest,
10
- type SimulationError,
11
- type Tx,
12
- type UnencryptedFunctionL2Logs,
13
- } from '@aztec/circuit-types';
14
- import {
15
- type AvmExecutionHints,
16
- AztecAddress,
17
- ContractStorageRead,
18
- ContractStorageUpdateRequest,
19
- Fr,
20
- FunctionData,
21
- Gas,
22
- type GlobalVariables,
23
- type Header,
24
- type KernelCircuitPublicInputs,
25
- L2ToL1Message,
26
- LogHash,
27
- MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_CALL,
28
- MAX_L2_TO_L1_MSGS_PER_CALL,
29
- MAX_NOTE_HASHES_PER_CALL,
30
- MAX_NOTE_HASH_READ_REQUESTS_PER_CALL,
31
- MAX_NULLIFIERS_PER_CALL,
32
- MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_CALL,
33
- MAX_NULLIFIER_READ_REQUESTS_PER_CALL,
34
- MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL,
35
- MAX_PUBLIC_DATA_READS_PER_CALL,
36
- MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL,
37
- MAX_UNENCRYPTED_LOGS_PER_CALL,
38
- NESTED_RECURSIVE_PROOF_LENGTH,
39
- NoteHash,
40
- Nullifier,
41
- PublicCallData,
42
- PublicCallRequest,
43
- PublicCallStackItem,
44
- PublicCircuitPublicInputs,
45
- PublicKernelCircuitPrivateInputs,
46
- type PublicKernelCircuitPublicInputs,
47
- PublicKernelData,
48
- ReadRequest,
49
- RevertCode,
50
- TreeLeafReadRequest,
51
- makeEmptyProof,
52
- makeEmptyRecursiveProof,
53
- } from '@aztec/circuits.js';
54
- import { computeVarArgsHash } from '@aztec/circuits.js/hash';
55
- import { padArrayEnd } from '@aztec/foundation/collection';
56
- import { type DebugLogger, createDebugLogger } from '@aztec/foundation/log';
57
- import {
58
- type ProtocolArtifact,
59
- ProtocolCircuitVkIndexes,
60
- ProtocolCircuitVks,
61
- getVKIndex,
62
- getVKSiblingPath,
63
- } from '@aztec/noir-protocol-circuits-types';
64
- import {
65
- type PublicExecutionResult,
66
- type PublicExecutor,
67
- accumulateReturnValues,
68
- isPublicExecutionResult,
69
- } from '@aztec/simulator';
70
- import { type MerkleTreeOperations } from '@aztec/world-state';
71
-
72
- import { HintsBuilder } from './hints_builder.js';
73
- import { type PublicKernelCircuitSimulator } from './public_kernel_circuit_simulator.js';
74
-
75
- export const PhaseIsRevertible: Record<PublicKernelType, boolean> = {
76
- [PublicKernelType.NON_PUBLIC]: false,
77
- [PublicKernelType.SETUP]: false,
78
- [PublicKernelType.APP_LOGIC]: true,
79
- [PublicKernelType.TEARDOWN]: true,
80
- [PublicKernelType.TAIL]: false,
81
- };
82
-
83
- export type PublicProvingInformation = {
84
- functionName: string; // informational only
85
- calldata: Fr[];
86
- bytecode: Buffer;
87
- inputs: PublicKernelCircuitPrivateInputs;
88
- avmHints: AvmExecutionHints;
89
- };
90
-
91
- export function makeAvmProvingRequest(
92
- info: PublicProvingInformation,
93
- kernelType: PublicKernelNonTailRequest['type'],
94
- ): AvmProvingRequest {
95
- return {
96
- type: AVM_REQUEST,
97
- functionName: info.functionName,
98
- bytecode: info.bytecode,
99
- calldata: info.calldata,
100
- avmHints: info.avmHints,
101
- kernelRequest: {
102
- type: kernelType,
103
- inputs: info.inputs,
104
- },
105
- };
106
- }
107
-
108
- export type TxPublicCallsResult = {
109
- /** Inputs to be used for proving */
110
- publicProvingInformation: PublicProvingInformation[];
111
- /** The public kernel output at the end of the Tx */
112
- kernelOutput: PublicKernelCircuitPublicInputs;
113
- /** The last circuit ran by this phase */
114
- lastKernelArtifact: ProtocolArtifact;
115
- /** Unencrypted logs generated during the execution of this Tx */
116
- newUnencryptedLogs: UnencryptedFunctionL2Logs[];
117
- /** Revert reason, if any */
118
- revertReason?: SimulationError;
119
- /** Return values of simulating complete callstack */
120
- returnValues: NestedProcessReturnValues[];
121
- /** Gas used during the execution this Tx */
122
- gasUsed?: Gas;
123
- };
124
-
125
- export type PhaseResult = {
126
- /** The collection of public proving requests */
127
- publicProvingRequests: PublicProvingRequest[];
128
- /** The output of the public kernel circuit simulation for this phase */
129
- publicKernelOutput: PublicKernelCircuitPublicInputs;
130
- /** The last circuit ran by this phase */
131
- lastKernelArtifact: ProtocolArtifact;
132
- /** The final output of the public kernel circuit for this phase */
133
- finalKernelOutput?: KernelCircuitPublicInputs;
134
- /** Revert reason, if any */
135
- revertReason?: SimulationError;
136
- /** Return values of simulating complete callstack */
137
- returnValues: NestedProcessReturnValues[];
138
- /** Gas used during the execution this phase */
139
- gasUsed?: Gas;
140
- };
141
-
142
- export abstract class AbstractPhaseManager {
143
- protected hintsBuilder: HintsBuilder;
144
- protected log: DebugLogger;
145
- constructor(
146
- protected db: MerkleTreeOperations,
147
- protected publicExecutor: PublicExecutor,
148
- protected publicKernel: PublicKernelCircuitSimulator,
149
- protected globalVariables: GlobalVariables,
150
- protected historicalHeader: Header,
151
- public phase: PublicKernelType,
152
- ) {
153
- this.hintsBuilder = new HintsBuilder(db);
154
- this.log = createDebugLogger(`aztec:sequencer:${phase}`);
155
- }
156
-
157
- /**
158
- * @param tx - the tx to be processed
159
- * @param publicKernelPublicInputs - the output of the public kernel circuit for the previous phase
160
- */
161
- abstract handle(
162
- tx: Tx,
163
- publicKernelPublicInputs: PublicKernelCircuitPublicInputs,
164
- previousKernelArtifact: ProtocolArtifact,
165
- ): Promise<PhaseResult>;
166
-
167
- public static extractEnqueuedPublicCallsByPhase(tx: Tx): Record<PublicKernelType, PublicExecutionRequest[]> {
168
- const teardownRequest = tx.getPublicTeardownExecutionRequest();
169
- return {
170
- [PublicKernelType.NON_PUBLIC]: [],
171
- [PublicKernelType.SETUP]: tx.getNonRevertiblePublicExecutionRequests(),
172
- [PublicKernelType.APP_LOGIC]: tx.getRevertiblePublicExecutionRequests(),
173
- [PublicKernelType.TEARDOWN]: teardownRequest ? [teardownRequest] : [],
174
- [PublicKernelType.TAIL]: [],
175
- };
176
- }
177
-
178
- protected extractEnqueuedPublicCalls(tx: Tx): PublicExecutionRequest[] {
179
- const calls = AbstractPhaseManager.extractEnqueuedPublicCallsByPhase(tx)[this.phase];
180
-
181
- return calls;
182
- }
183
-
184
- protected async processEnqueuedPublicCalls(
185
- tx: Tx,
186
- previousPublicKernelOutput: PublicKernelCircuitPublicInputs,
187
- previousKernelArtifact: ProtocolArtifact,
188
- ): Promise<TxPublicCallsResult> {
189
- const enqueuedCalls = [...this.extractEnqueuedPublicCalls(tx)].reverse();
190
-
191
- if (!enqueuedCalls || !enqueuedCalls.length) {
192
- return {
193
- publicProvingInformation: [],
194
- kernelOutput: previousPublicKernelOutput,
195
- lastKernelArtifact: previousKernelArtifact,
196
- newUnencryptedLogs: [],
197
- returnValues: [],
198
- gasUsed: Gas.empty(),
199
- };
200
- }
201
-
202
- // TODO(#1684): Should multiple separately enqueued public calls be treated as
203
- // separate public callstacks to be proven by separate public kernel sequences
204
- // and submitted separately to the base rollup?
205
-
206
- const provingInformationList: PublicProvingInformation[] = [];
207
- const newUnencryptedFunctionLogs: UnencryptedFunctionL2Logs[] = [];
208
- // Transaction fee is zero for all phases except teardown
209
- const transactionFee = this.getTransactionFee(tx, previousPublicKernelOutput);
210
- let gasUsed = Gas.empty();
211
- let kernelPublicOutput: PublicKernelCircuitPublicInputs = previousPublicKernelOutput;
212
-
213
- const enqueuedCallResults = [];
214
-
215
- for (const enqueuedCall of enqueuedCalls) {
216
- const executionStack: (PublicExecutionRequest | PublicExecutionResult)[] = [enqueuedCall];
217
-
218
- // Keep track of which result is for the top/enqueued call
219
- let enqueuedExecutionResult: PublicExecutionResult | undefined;
220
-
221
- while (executionStack.length) {
222
- const current = executionStack.pop()!;
223
- const isExecutionRequest = !isPublicExecutionResult(current);
224
- const result = isExecutionRequest
225
- ? await this.publicExecutor.simulate(
226
- /*executionRequest=*/ current,
227
- this.globalVariables,
228
- /*availableGas=*/ this.getAvailableGas(tx, kernelPublicOutput),
229
- tx.data.constants.txContext,
230
- /*pendingNullifiers=*/ this.getSiloedPendingNullifiers(kernelPublicOutput),
231
- transactionFee,
232
- /*startSideEffectCounter=*/ AbstractPhaseManager.getMaxSideEffectCounter(kernelPublicOutput) + 1,
233
- // NOTE: startSideEffectCounter is not the same as the executionRequest's sideEffectCounter
234
- // (which counts the request itself)
235
- )
236
- : current;
237
-
238
- // Accumulate gas used in this execution
239
- gasUsed = gasUsed.add(Gas.from(result.startGasLeft).sub(Gas.from(result.endGasLeft)));
240
-
241
- // Sanity check for a current upstream assumption.
242
- // Consumers of the result seem to expect "reverted <=> revertReason !== undefined".
243
- const functionSelector = result.executionRequest.callContext.functionSelector.toString();
244
- if (result.reverted && !result.revertReason) {
245
- throw new Error(
246
- `Simulation of ${result.executionRequest.contractAddress.toString()}:${functionSelector}(${
247
- result.functionName
248
- }) reverted with no reason.`,
249
- );
250
- }
251
-
252
- if (result.reverted && !PhaseIsRevertible[this.phase]) {
253
- this.log.debug(
254
- `Simulation error on ${result.executionRequest.contractAddress.toString()}:${functionSelector}(${
255
- result.functionName
256
- }) with reason: ${result.revertReason}`,
257
- );
258
- throw result.revertReason;
259
- }
260
-
261
- if (isExecutionRequest) {
262
- newUnencryptedFunctionLogs.push(result.allUnencryptedLogs);
263
- }
264
- executionStack.push(...result.nestedExecutions);
265
-
266
- // Simulate the public kernel circuit.
267
- this.log.debug(
268
- `Running public kernel circuit for ${result.executionRequest.contractAddress.toString()}:${functionSelector}(${
269
- result.functionName
270
- })`,
271
- );
272
- const callData = await this.getPublicCallData(result, isExecutionRequest);
273
- const [privateInputs, publicInputs, artifact] = await this.runKernelCircuit(
274
- kernelPublicOutput,
275
- previousKernelArtifact,
276
- callData,
277
- );
278
- kernelPublicOutput = publicInputs;
279
- previousKernelArtifact = artifact;
280
-
281
- // Capture the inputs for later proving in the AVM and kernel.
282
- const publicProvingInformation: PublicProvingInformation = {
283
- functionName: result.functionName,
284
- calldata: result.calldata,
285
- bytecode: result.bytecode!,
286
- inputs: privateInputs,
287
- avmHints: result.avmCircuitHints,
288
- };
289
- provingInformationList.push(publicProvingInformation);
290
-
291
- // Sanity check: Note we can't expect them to just be equal, because e.g.
292
- // if the simulator reverts in app logic, it "resets" and result.reverted will be false when we run teardown,
293
- // but the kernel carries the reverted flag forward. But if the simulator reverts, so should the kernel.
294
- if (result.reverted && kernelPublicOutput.revertCode.isOK()) {
295
- throw new Error(
296
- `Public kernel circuit did not revert on ${result.executionRequest.contractAddress.toString()}:${functionSelector}(${
297
- result.functionName
298
- }), but simulator did.`,
299
- );
300
- }
301
-
302
- // We know the phase is revertible due to the above check.
303
- // So safely return the revert reason and the kernel output (which has had its revertible side effects dropped)
304
- if (result.reverted) {
305
- this.log.debug(
306
- `Reverting on ${result.executionRequest.contractAddress.toString()}:${functionSelector}(${
307
- result.functionName
308
- }) with reason: ${result.revertReason}`,
309
- );
310
- // TODO(@spalladino): Check gasUsed is correct. The AVM should take care of setting gasLeft to zero upon a revert.
311
- return {
312
- publicProvingInformation: [],
313
- kernelOutput: kernelPublicOutput,
314
- lastKernelArtifact: previousKernelArtifact,
315
- newUnencryptedLogs: [],
316
- revertReason: result.revertReason,
317
- returnValues: [],
318
- gasUsed,
319
- };
320
- }
321
-
322
- if (!enqueuedExecutionResult) {
323
- enqueuedExecutionResult = result;
324
- }
325
-
326
- enqueuedCallResults.push(accumulateReturnValues(enqueuedExecutionResult));
327
- }
328
- }
329
-
330
- return {
331
- publicProvingInformation: provingInformationList,
332
- kernelOutput: kernelPublicOutput,
333
- lastKernelArtifact: previousKernelArtifact,
334
- newUnencryptedLogs: newUnencryptedFunctionLogs,
335
- returnValues: enqueuedCallResults,
336
- gasUsed,
337
- };
338
- }
339
-
340
- /** Returns all pending private and public nullifiers. */
341
- private getSiloedPendingNullifiers(ko: PublicKernelCircuitPublicInputs) {
342
- return [...ko.end.nullifiers, ...ko.endNonRevertibleData.nullifiers].filter(n => !n.isEmpty());
343
- }
344
-
345
- protected getAvailableGas(tx: Tx, previousPublicKernelOutput: PublicKernelCircuitPublicInputs) {
346
- return tx.data.constants.txContext.gasSettings
347
- .getLimits() // No need to subtract teardown limits since they are already included in end.gasUsed
348
- .sub(previousPublicKernelOutput.end.gasUsed)
349
- .sub(previousPublicKernelOutput.endNonRevertibleData.gasUsed);
350
- }
351
-
352
- protected getTransactionFee(_tx: Tx, _previousPublicKernelOutput: PublicKernelCircuitPublicInputs) {
353
- return Fr.ZERO;
354
- }
355
-
356
- private async runKernelCircuit(
357
- previousOutput: PublicKernelCircuitPublicInputs,
358
- previousCircuit: ProtocolArtifact,
359
- callData: PublicCallData,
360
- ): Promise<[PublicKernelCircuitPrivateInputs, PublicKernelCircuitPublicInputs, ProtocolArtifact]> {
361
- const previousKernel = this.getPreviousKernelData(previousOutput, previousCircuit);
362
-
363
- // We take a deep copy (clone) of these inputs to be passed to the prover
364
- const inputs = new PublicKernelCircuitPrivateInputs(previousKernel, callData);
365
- switch (this.phase) {
366
- case PublicKernelType.SETUP:
367
- return [inputs.clone(), await this.publicKernel.publicKernelCircuitSetup(inputs), 'PublicKernelSetupArtifact'];
368
- case PublicKernelType.APP_LOGIC:
369
- return [
370
- inputs.clone(),
371
- await this.publicKernel.publicKernelCircuitAppLogic(inputs),
372
- 'PublicKernelAppLogicArtifact',
373
- ];
374
- case PublicKernelType.TEARDOWN:
375
- return [
376
- inputs.clone(),
377
- await this.publicKernel.publicKernelCircuitTeardown(inputs),
378
- 'PublicKernelTeardownArtifact',
379
- ];
380
- default:
381
- throw new Error(`No public kernel circuit for inputs`);
382
- }
383
- }
384
-
385
- protected getPreviousKernelData(
386
- previousOutput: PublicKernelCircuitPublicInputs,
387
- previousCircuit: ProtocolArtifact,
388
- ): PublicKernelData {
389
- // The proof is not used in simulation
390
- const proof = makeEmptyRecursiveProof(NESTED_RECURSIVE_PROOF_LENGTH);
391
-
392
- const vk = ProtocolCircuitVks[previousCircuit];
393
- const vkIndex = ProtocolCircuitVkIndexes[previousCircuit];
394
-
395
- const leafIndex = getVKIndex(vk);
396
-
397
- return new PublicKernelData(previousOutput, proof, vk, vkIndex, getVKSiblingPath(leafIndex));
398
- }
399
-
400
- protected async getPublicCallStackItem(result: PublicExecutionResult, isExecutionRequest = false) {
401
- const publicDataTreeInfo = await this.db.getTreeInfo(MerkleTreeId.PUBLIC_DATA_TREE);
402
- this.historicalHeader.state.partial.publicDataTree.root = Fr.fromBuffer(publicDataTreeInfo.root);
403
-
404
- const publicCircuitPublicInputs = PublicCircuitPublicInputs.from({
405
- callContext: result.executionRequest.callContext,
406
- proverAddress: AztecAddress.ZERO,
407
- argsHash: computeVarArgsHash(result.executionRequest.args),
408
- noteHashes: padArrayEnd(result.noteHashes, NoteHash.empty(), MAX_NOTE_HASHES_PER_CALL),
409
- nullifiers: padArrayEnd(result.nullifiers, Nullifier.empty(), MAX_NULLIFIERS_PER_CALL),
410
- l2ToL1Msgs: padArrayEnd(result.l2ToL1Messages, L2ToL1Message.empty(), MAX_L2_TO_L1_MSGS_PER_CALL),
411
- startSideEffectCounter: result.startSideEffectCounter,
412
- endSideEffectCounter: result.endSideEffectCounter,
413
- returnsHash: computeVarArgsHash(result.returnValues),
414
- noteHashReadRequests: padArrayEnd(
415
- result.noteHashReadRequests,
416
- TreeLeafReadRequest.empty(),
417
- MAX_NOTE_HASH_READ_REQUESTS_PER_CALL,
418
- ),
419
- nullifierReadRequests: padArrayEnd(
420
- result.nullifierReadRequests,
421
- ReadRequest.empty(),
422
- MAX_NULLIFIER_READ_REQUESTS_PER_CALL,
423
- ),
424
- nullifierNonExistentReadRequests: padArrayEnd(
425
- result.nullifierNonExistentReadRequests,
426
- ReadRequest.empty(),
427
- MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_CALL,
428
- ),
429
- l1ToL2MsgReadRequests: padArrayEnd(
430
- result.l1ToL2MsgReadRequests,
431
- TreeLeafReadRequest.empty(),
432
- MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_CALL,
433
- ),
434
- contractStorageReads: padArrayEnd(
435
- result.contractStorageReads,
436
- ContractStorageRead.empty(),
437
- MAX_PUBLIC_DATA_READS_PER_CALL,
438
- ),
439
- contractStorageUpdateRequests: padArrayEnd(
440
- result.contractStorageUpdateRequests,
441
- ContractStorageUpdateRequest.empty(),
442
- MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL,
443
- ),
444
- publicCallRequests: padArrayEnd(
445
- result.publicCallRequests,
446
- PublicCallRequest.empty(),
447
- MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL,
448
- ),
449
- unencryptedLogsHashes: padArrayEnd(result.unencryptedLogsHashes, LogHash.empty(), MAX_UNENCRYPTED_LOGS_PER_CALL),
450
- historicalHeader: this.historicalHeader,
451
- globalVariables: this.globalVariables,
452
- startGasLeft: Gas.from(result.startGasLeft),
453
- endGasLeft: Gas.from(result.endGasLeft),
454
- transactionFee: result.transactionFee,
455
- // TODO(@just-mitch): need better mapping from simulator to revert code.
456
- revertCode: result.reverted ? RevertCode.APP_LOGIC_REVERTED : RevertCode.OK,
457
- });
458
-
459
- return new PublicCallStackItem(
460
- result.executionRequest.contractAddress,
461
- new FunctionData(result.executionRequest.callContext.functionSelector, false),
462
- publicCircuitPublicInputs,
463
- isExecutionRequest,
464
- );
465
- }
466
-
467
- /**
468
- * Looks at the side effects of a transaction and returns the highest counter
469
- * @param tx - A transaction
470
- * @returns The highest side effect counter in the transaction so far
471
- */
472
- static getMaxSideEffectCounter(inputs: PublicKernelCircuitPublicInputs): number {
473
- const sideEffectCounters = [
474
- ...inputs.endNonRevertibleData.noteHashes,
475
- ...inputs.endNonRevertibleData.nullifiers,
476
- ...inputs.endNonRevertibleData.noteEncryptedLogsHashes,
477
- ...inputs.endNonRevertibleData.encryptedLogsHashes,
478
- ...inputs.endNonRevertibleData.unencryptedLogsHashes,
479
- ...inputs.endNonRevertibleData.publicCallStack,
480
- ...inputs.endNonRevertibleData.publicDataUpdateRequests,
481
- ...inputs.end.noteHashes,
482
- ...inputs.end.nullifiers,
483
- ...inputs.end.noteEncryptedLogsHashes,
484
- ...inputs.end.encryptedLogsHashes,
485
- ...inputs.end.unencryptedLogsHashes,
486
- ...inputs.end.publicCallStack,
487
- ...inputs.end.publicDataUpdateRequests,
488
- ];
489
-
490
- let max = 0;
491
- for (const sideEffect of sideEffectCounters) {
492
- if ('counter' in sideEffect) {
493
- max = Math.max(max, sideEffect.counter);
494
- } else {
495
- throw new Error('Unknown side effect type');
496
- }
497
- }
498
-
499
- return max;
500
- }
501
-
502
- protected getBytecodeHash(_result: PublicExecutionResult) {
503
- // TODO: Determine how to calculate bytecode hash. Circuits just check it isn't zero for now.
504
- // See https://github.com/AztecProtocol/aztec3-packages/issues/378
505
- const bytecodeHash = new Fr(1n);
506
- return Promise.resolve(bytecodeHash);
507
- }
508
-
509
- /**
510
- * Calculates the PublicCircuitOutput for this execution result along with its proof,
511
- * and assembles a PublicCallData object from it.
512
- * @param result - The execution result.
513
- * @param preimages - The preimages of the callstack items.
514
- * @param isExecutionRequest - Whether the current callstack item should be considered a public fn execution request.
515
- * @returns A corresponding PublicCallData object.
516
- */
517
- protected async getPublicCallData(result: PublicExecutionResult, isExecutionRequest = false) {
518
- const bytecodeHash = await this.getBytecodeHash(result);
519
- const callStackItem = await this.getPublicCallStackItem(result, isExecutionRequest);
520
- return new PublicCallData(callStackItem, makeEmptyProof(), bytecodeHash);
521
- }
522
- }
@@ -1,81 +0,0 @@
1
- import { PublicKernelType, type PublicProvingRequest, type Tx } from '@aztec/circuit-types';
2
- import { type GlobalVariables, type Header, type PublicKernelCircuitPublicInputs } from '@aztec/circuits.js';
3
- import { type ProtocolArtifact } from '@aztec/noir-protocol-circuits-types';
4
- import { type PublicExecutor, type PublicStateDB } from '@aztec/simulator';
5
- import { type MerkleTreeOperations } from '@aztec/world-state';
6
-
7
- import { AbstractPhaseManager, makeAvmProvingRequest } from './abstract_phase_manager.js';
8
- import { type ContractsDataSourcePublicDB } from './public_db_sources.js';
9
- import { type PublicKernelCircuitSimulator } from './public_kernel_circuit_simulator.js';
10
-
11
- /**
12
- * The phase manager responsible for performing the fee preparation phase.
13
- */
14
- export class AppLogicPhaseManager extends AbstractPhaseManager {
15
- constructor(
16
- db: MerkleTreeOperations,
17
- publicExecutor: PublicExecutor,
18
- publicKernel: PublicKernelCircuitSimulator,
19
- globalVariables: GlobalVariables,
20
- historicalHeader: Header,
21
- protected publicContractsDB: ContractsDataSourcePublicDB,
22
- protected publicStateDB: PublicStateDB,
23
- phase: PublicKernelType = PublicKernelType.APP_LOGIC,
24
- ) {
25
- super(db, publicExecutor, publicKernel, globalVariables, historicalHeader, phase);
26
- }
27
-
28
- override async handle(
29
- tx: Tx,
30
- previousPublicKernelOutput: PublicKernelCircuitPublicInputs,
31
- previousCircuit: ProtocolArtifact,
32
- ) {
33
- this.log.verbose(`Processing tx ${tx.getTxHash()}`);
34
- // add new contracts to the contracts db so that their functions may be found and called
35
- // TODO(#4073): This is catching only private deployments, when we add public ones, we'll
36
- // have to capture contracts emitted in that phase as well.
37
- // TODO(@spalladino): Should we allow emitting contracts in the fee preparation phase?
38
- // TODO(#6464): Should we allow emitting contracts in the private setup phase?
39
- // if so, this should only add contracts that were deployed during private app logic.
40
- await this.publicContractsDB.addNewContracts(tx);
41
- const {
42
- publicProvingInformation,
43
- kernelOutput,
44
- lastKernelArtifact,
45
- newUnencryptedLogs,
46
- revertReason,
47
- returnValues,
48
- gasUsed,
49
- } = await this.processEnqueuedPublicCalls(tx, previousPublicKernelOutput, previousCircuit).catch(
50
- // if we throw for any reason other than simulation, we need to rollback and drop the TX
51
- async err => {
52
- await this.publicStateDB.rollbackToCommit();
53
- throw err;
54
- },
55
- );
56
-
57
- if (revertReason) {
58
- // TODO(#6464): Should we allow emitting contracts in the private setup phase?
59
- // if so, this is removing contracts deployed in private setup
60
- await this.publicContractsDB.removeNewContracts(tx);
61
- await this.publicStateDB.rollbackToCheckpoint();
62
- tx.filterRevertedLogs(kernelOutput);
63
- } else {
64
- tx.unencryptedLogs.addFunctionLogs(newUnencryptedLogs);
65
- // TODO(#6470): we should be adding contracts deployed in those logs to the publicContractsDB
66
- }
67
-
68
- // Return a list of app logic proving requests
69
- const publicProvingRequests: PublicProvingRequest[] = publicProvingInformation.map(info => {
70
- return makeAvmProvingRequest(info, PublicKernelType.APP_LOGIC);
71
- });
72
- return {
73
- publicProvingRequests,
74
- publicKernelOutput: kernelOutput,
75
- lastKernelArtifact,
76
- revertReason,
77
- returnValues,
78
- gasUsed,
79
- };
80
- }
81
- }