@aztec/sequencer-client 0.34.0 → 0.35.1

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 (98) hide show
  1. package/dest/client/sequencer-client.d.ts.map +1 -1
  2. package/dest/client/sequencer-client.js +3 -3
  3. package/dest/config.d.ts.map +1 -1
  4. package/dest/config.js +84 -7
  5. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  6. package/dest/global_variable_builder/global_builder.js +4 -3
  7. package/dest/index.d.ts +0 -1
  8. package/dest/index.d.ts.map +1 -1
  9. package/dest/index.js +1 -2
  10. package/dest/sequencer/sequencer.d.ts +6 -7
  11. package/dest/sequencer/sequencer.d.ts.map +1 -1
  12. package/dest/sequencer/sequencer.js +10 -11
  13. package/dest/tx_validator/aggregate_tx_validator.d.ts +7 -0
  14. package/dest/tx_validator/aggregate_tx_validator.d.ts.map +1 -0
  15. package/dest/tx_validator/aggregate_tx_validator.js +23 -0
  16. package/dest/tx_validator/double_spend_validator.d.ts +11 -0
  17. package/dest/tx_validator/double_spend_validator.d.ts.map +1 -0
  18. package/dest/tx_validator/double_spend_validator.js +50 -0
  19. package/dest/tx_validator/gas_validator.d.ts +12 -0
  20. package/dest/tx_validator/gas_validator.d.ts.map +1 -0
  21. package/dest/tx_validator/gas_validator.js +62 -0
  22. package/dest/tx_validator/metadata_validator.d.ts +8 -0
  23. package/dest/tx_validator/metadata_validator.d.ts.map +1 -0
  24. package/dest/tx_validator/metadata_validator.js +50 -0
  25. package/dest/tx_validator/phases_validator.d.ts +13 -0
  26. package/dest/tx_validator/phases_validator.d.ts.map +1 -0
  27. package/dest/tx_validator/phases_validator.js +73 -0
  28. package/dest/tx_validator/tx_validator_factory.d.ts +13 -0
  29. package/dest/tx_validator/tx_validator_factory.d.ts.map +1 -0
  30. package/dest/tx_validator/tx_validator_factory.js +21 -0
  31. package/package.json +14 -13
  32. package/src/client/sequencer-client.ts +2 -3
  33. package/src/config.ts +93 -7
  34. package/src/global_variable_builder/global_builder.ts +3 -2
  35. package/src/index.ts +0 -1
  36. package/src/sequencer/sequencer.ts +27 -20
  37. package/src/tx_validator/aggregate_tx_validator.ts +24 -0
  38. package/src/tx_validator/double_spend_validator.ts +65 -0
  39. package/src/tx_validator/gas_validator.ts +81 -0
  40. package/src/tx_validator/metadata_validator.ts +60 -0
  41. package/src/tx_validator/phases_validator.ts +101 -0
  42. package/src/tx_validator/tx_validator_factory.ts +37 -0
  43. package/dest/sequencer/abstract_phase_manager.d.ts +0 -77
  44. package/dest/sequencer/abstract_phase_manager.d.ts.map +0 -1
  45. package/dest/sequencer/abstract_phase_manager.js +0 -307
  46. package/dest/sequencer/app_logic_phase_manager.d.ts +0 -28
  47. package/dest/sequencer/app_logic_phase_manager.d.ts.map +0 -1
  48. package/dest/sequencer/app_logic_phase_manager.js +0 -41
  49. package/dest/sequencer/hints_builder.d.ts +0 -23
  50. package/dest/sequencer/hints_builder.d.ts.map +0 -1
  51. package/dest/sequencer/hints_builder.js +0 -62
  52. package/dest/sequencer/phase_manager_factory.d.ts +0 -18
  53. package/dest/sequencer/phase_manager_factory.d.ts.map +0 -1
  54. package/dest/sequencer/phase_manager_factory.js +0 -56
  55. package/dest/sequencer/public_processor.d.ts +0 -54
  56. package/dest/sequencer/public_processor.d.ts.map +0 -1
  57. package/dest/sequencer/public_processor.js +0 -142
  58. package/dest/sequencer/setup_phase_manager.d.ts +0 -28
  59. package/dest/sequencer/setup_phase_manager.d.ts.map +0 -1
  60. package/dest/sequencer/setup_phase_manager.js +0 -30
  61. package/dest/sequencer/tail_phase_manager.d.ts +0 -29
  62. package/dest/sequencer/tail_phase_manager.d.ts.map +0 -1
  63. package/dest/sequencer/tail_phase_manager.js +0 -52
  64. package/dest/sequencer/teardown_phase_manager.d.ts +0 -28
  65. package/dest/sequencer/teardown_phase_manager.d.ts.map +0 -1
  66. package/dest/sequencer/teardown_phase_manager.js +0 -30
  67. package/dest/sequencer/tx_validator.d.ts +0 -29
  68. package/dest/sequencer/tx_validator.d.ts.map +0 -1
  69. package/dest/sequencer/tx_validator.js +0 -174
  70. package/dest/sequencer/tx_validator_factory.d.ts +0 -12
  71. package/dest/sequencer/tx_validator_factory.d.ts.map +0 -1
  72. package/dest/sequencer/tx_validator_factory.js +0 -17
  73. package/dest/sequencer/utils.d.ts +0 -8
  74. package/dest/sequencer/utils.d.ts.map +0 -1
  75. package/dest/sequencer/utils.js +0 -29
  76. package/dest/simulator/index.d.ts +0 -31
  77. package/dest/simulator/index.d.ts.map +0 -1
  78. package/dest/simulator/index.js +0 -2
  79. package/dest/simulator/public_executor.d.ts +0 -79
  80. package/dest/simulator/public_executor.d.ts.map +0 -1
  81. package/dest/simulator/public_executor.js +0 -198
  82. package/dest/simulator/public_kernel.d.ts +0 -37
  83. package/dest/simulator/public_kernel.d.ts.map +0 -1
  84. package/dest/simulator/public_kernel.js +0 -97
  85. package/src/sequencer/abstract_phase_manager.ts +0 -549
  86. package/src/sequencer/app_logic_phase_manager.ts +0 -62
  87. package/src/sequencer/hints_builder.ts +0 -119
  88. package/src/sequencer/phase_manager_factory.ts +0 -126
  89. package/src/sequencer/public_processor.ts +0 -209
  90. package/src/sequencer/setup_phase_manager.ts +0 -50
  91. package/src/sequencer/tail_phase_manager.ts +0 -111
  92. package/src/sequencer/teardown_phase_manager.ts +0 -50
  93. package/src/sequencer/tx_validator.ts +0 -265
  94. package/src/sequencer/tx_validator_factory.ts +0 -32
  95. package/src/sequencer/utils.ts +0 -31
  96. package/src/simulator/index.ts +0 -36
  97. package/src/simulator/public_executor.ts +0 -267
  98. package/src/simulator/public_kernel.ts +0 -139
@@ -1,549 +0,0 @@
1
- import { MerkleTreeId, type SimulationError, type Tx, type UnencryptedFunctionL2Logs } from '@aztec/circuit-types';
2
- import {
3
- AztecAddress,
4
- CallRequest,
5
- ContractStorageRead,
6
- ContractStorageUpdateRequest,
7
- Fr,
8
- type GlobalVariables,
9
- type Header,
10
- type KernelCircuitPublicInputs,
11
- L2ToL1Message,
12
- MAX_NEW_L2_TO_L1_MSGS_PER_CALL,
13
- MAX_NEW_NOTE_HASHES_PER_CALL,
14
- MAX_NEW_NULLIFIERS_PER_CALL,
15
- MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_CALL,
16
- MAX_NULLIFIER_READ_REQUESTS_PER_CALL,
17
- MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL,
18
- MAX_PUBLIC_DATA_READS_PER_CALL,
19
- MAX_PUBLIC_DATA_READS_PER_TX,
20
- MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL,
21
- MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX,
22
- MembershipWitness,
23
- type PrivateKernelTailCircuitPublicInputs,
24
- type Proof,
25
- PublicCallData,
26
- type PublicCallRequest,
27
- PublicCallStackItem,
28
- PublicCircuitPublicInputs,
29
- PublicDataRead,
30
- PublicDataUpdateRequest,
31
- PublicKernelCircuitPrivateInputs,
32
- type PublicKernelCircuitPublicInputs,
33
- PublicKernelData,
34
- RETURN_VALUES_LENGTH,
35
- ReadRequest,
36
- RevertCode,
37
- SideEffect,
38
- SideEffectLinkedToNoteHash,
39
- VK_TREE_HEIGHT,
40
- VerificationKey,
41
- makeEmptyProof,
42
- } from '@aztec/circuits.js';
43
- import { computeVarArgsHash } from '@aztec/circuits.js/hash';
44
- import {
45
- type AbiType,
46
- type DecodedReturn,
47
- type FunctionArtifact,
48
- type ProcessReturnValues,
49
- decodeReturnValues,
50
- } from '@aztec/foundation/abi';
51
- import { arrayNonEmptyLength, padArrayEnd } from '@aztec/foundation/collection';
52
- import { type DebugLogger, createDebugLogger } from '@aztec/foundation/log';
53
- import { type Tuple } from '@aztec/foundation/serialize';
54
- import {
55
- type PublicExecution,
56
- type PublicExecutionResult,
57
- type PublicExecutor,
58
- collectPublicDataReads,
59
- collectPublicDataUpdateRequests,
60
- isPublicExecutionResult,
61
- } from '@aztec/simulator';
62
- import { type MerkleTreeOperations } from '@aztec/world-state';
63
-
64
- import { type PublicKernelCircuitSimulator } from '../simulator/index.js';
65
- import { HintsBuilder } from './hints_builder.js';
66
- import { lastSideEffectCounter } from './utils.js';
67
-
68
- export enum PublicKernelPhase {
69
- SETUP = 'setup',
70
- APP_LOGIC = 'app-logic',
71
- TEARDOWN = 'teardown',
72
- TAIL = 'tail',
73
- }
74
-
75
- export const PhaseIsRevertible: Record<PublicKernelPhase, boolean> = {
76
- [PublicKernelPhase.SETUP]: false,
77
- [PublicKernelPhase.APP_LOGIC]: true,
78
- [PublicKernelPhase.TEARDOWN]: false,
79
- [PublicKernelPhase.TAIL]: false,
80
- };
81
-
82
- export abstract class AbstractPhaseManager {
83
- protected hintsBuilder: HintsBuilder;
84
- protected log: DebugLogger;
85
- constructor(
86
- protected db: MerkleTreeOperations,
87
- protected publicExecutor: PublicExecutor,
88
- protected publicKernel: PublicKernelCircuitSimulator,
89
- protected globalVariables: GlobalVariables,
90
- protected historicalHeader: Header,
91
- public phase: PublicKernelPhase,
92
- ) {
93
- this.hintsBuilder = new HintsBuilder(db);
94
- this.log = createDebugLogger(`aztec:sequencer:${phase}`);
95
- }
96
- /**
97
- *
98
- * @param tx - the tx to be processed
99
- * @param publicKernelPublicInputs - the output of the public kernel circuit for the previous phase
100
- * @param previousPublicKernelProof - the proof of the public kernel circuit for the previous phase
101
- */
102
- abstract handle(
103
- tx: Tx,
104
- publicKernelPublicInputs: PublicKernelCircuitPublicInputs,
105
- previousPublicKernelProof: Proof,
106
- ): Promise<{
107
- /**
108
- * the output of the public kernel circuit for this phase
109
- */
110
- publicKernelOutput: PublicKernelCircuitPublicInputs;
111
- /**
112
- * the final output of the public kernel circuit for this phase
113
- */
114
- finalKernelOutput?: KernelCircuitPublicInputs;
115
- /**
116
- * the proof of the public kernel circuit for this phase
117
- */
118
- publicKernelProof: Proof;
119
- /**
120
- * revert reason, if any
121
- */
122
- revertReason: SimulationError | undefined;
123
- returnValues: ProcessReturnValues;
124
- }>;
125
-
126
- public static extractEnqueuedPublicCallsByPhase(
127
- publicInputs: PrivateKernelTailCircuitPublicInputs,
128
- enqueuedPublicFunctionCalls: PublicCallRequest[],
129
- ): Record<PublicKernelPhase, PublicCallRequest[]> {
130
- const publicCallsStack = enqueuedPublicFunctionCalls.slice().reverse();
131
- const nonRevertibleCallStack = publicInputs.forPublic!.endNonRevertibleData.publicCallStack.filter(
132
- i => !i.isEmpty(),
133
- );
134
- const revertibleCallStack = publicInputs.forPublic!.end.publicCallStack.filter(i => !i.isEmpty());
135
-
136
- const callRequestsStack = publicCallsStack
137
- .map(call => call.toCallRequest())
138
- .filter(
139
- // filter out enqueued calls that are not in the public call stack
140
- // TODO mitch left a question about whether this is only needed when unit testing
141
- // with mock data
142
- call => revertibleCallStack.find(p => p.equals(call)) || nonRevertibleCallStack.find(p => p.equals(call)),
143
- );
144
-
145
- if (callRequestsStack.length === 0) {
146
- return {
147
- [PublicKernelPhase.SETUP]: [],
148
- [PublicKernelPhase.APP_LOGIC]: [],
149
- [PublicKernelPhase.TEARDOWN]: [],
150
- [PublicKernelPhase.TAIL]: [],
151
- };
152
- }
153
-
154
- // find the first call that is revertible
155
- const firstRevertibleCallIndex = callRequestsStack.findIndex(
156
- c => revertibleCallStack.findIndex(p => p.equals(c)) !== -1,
157
- );
158
-
159
- if (firstRevertibleCallIndex === 0) {
160
- return {
161
- [PublicKernelPhase.SETUP]: [],
162
- [PublicKernelPhase.APP_LOGIC]: publicCallsStack,
163
- [PublicKernelPhase.TEARDOWN]: [],
164
- [PublicKernelPhase.TAIL]: [],
165
- };
166
- } else if (firstRevertibleCallIndex === -1) {
167
- // there's no app logic, split the functions between setup (many) and teardown (just one function call)
168
- return {
169
- [PublicKernelPhase.SETUP]: publicCallsStack.slice(0, -1),
170
- [PublicKernelPhase.APP_LOGIC]: [],
171
- [PublicKernelPhase.TEARDOWN]: [publicCallsStack[publicCallsStack.length - 1]],
172
- [PublicKernelPhase.TAIL]: [],
173
- };
174
- } else {
175
- return {
176
- [PublicKernelPhase.SETUP]: publicCallsStack.slice(0, firstRevertibleCallIndex - 1),
177
- [PublicKernelPhase.APP_LOGIC]: publicCallsStack.slice(firstRevertibleCallIndex),
178
- [PublicKernelPhase.TEARDOWN]: [publicCallsStack[firstRevertibleCallIndex - 1]],
179
- [PublicKernelPhase.TAIL]: [],
180
- };
181
- }
182
- }
183
-
184
- protected extractEnqueuedPublicCalls(tx: Tx): PublicCallRequest[] {
185
- const calls = AbstractPhaseManager.extractEnqueuedPublicCallsByPhase(tx.data, tx.enqueuedPublicFunctionCalls)[
186
- this.phase
187
- ];
188
-
189
- return calls;
190
- }
191
-
192
- protected async processEnqueuedPublicCalls(
193
- tx: Tx,
194
- previousPublicKernelOutput: PublicKernelCircuitPublicInputs,
195
- previousPublicKernelProof: Proof,
196
- ): Promise<
197
- [
198
- PublicKernelCircuitPublicInputs,
199
- Proof,
200
- UnencryptedFunctionL2Logs[],
201
- SimulationError | undefined,
202
- ProcessReturnValues,
203
- ]
204
- > {
205
- let kernelOutput = previousPublicKernelOutput;
206
- let kernelProof = previousPublicKernelProof;
207
-
208
- const enqueuedCalls = this.extractEnqueuedPublicCalls(tx);
209
-
210
- if (!enqueuedCalls || !enqueuedCalls.length) {
211
- return [kernelOutput, kernelProof, [], undefined, undefined];
212
- }
213
-
214
- const newUnencryptedFunctionLogs: UnencryptedFunctionL2Logs[] = [];
215
-
216
- // TODO(#1684): Should multiple separately enqueued public calls be treated as
217
- // separate public callstacks to be proven by separate public kernel sequences
218
- // and submitted separately to the base rollup?
219
-
220
- const returns = [];
221
-
222
- for (const enqueuedCall of enqueuedCalls) {
223
- const executionStack: (PublicExecution | PublicExecutionResult)[] = [enqueuedCall];
224
-
225
- let currentReturn: DecodedReturn | undefined = undefined;
226
-
227
- // Keep track of which result is for the top/enqueued call
228
- let enqueuedExecutionResult: PublicExecutionResult | undefined;
229
-
230
- while (executionStack.length) {
231
- const current = executionStack.pop()!;
232
- const isExecutionRequest = !isPublicExecutionResult(current);
233
- const sideEffectCounter = lastSideEffectCounter(tx) + 1;
234
-
235
- const result = isExecutionRequest
236
- ? await this.publicExecutor.simulate(current, this.globalVariables, sideEffectCounter)
237
- : current;
238
-
239
- const functionSelector = result.execution.functionData.selector.toString();
240
- if (result.reverted && !PhaseIsRevertible[this.phase]) {
241
- this.log.debug(
242
- `Simulation error on ${result.execution.contractAddress.toString()}:${functionSelector} with reason: ${
243
- result.revertReason
244
- }`,
245
- );
246
- throw result.revertReason;
247
- }
248
-
249
- newUnencryptedFunctionLogs.push(result.unencryptedLogs);
250
-
251
- this.log.debug(
252
- `Running public kernel circuit for ${result.execution.contractAddress.toString()}:${functionSelector}`,
253
- );
254
- executionStack.push(...result.nestedExecutions);
255
- const callData = await this.getPublicCallData(result, isExecutionRequest);
256
-
257
- [kernelOutput, kernelProof] = await this.runKernelCircuit(kernelOutput, kernelProof, callData);
258
-
259
- // sanity check. Note we can't expect them to just be equal, because e.g.
260
- // if the simulator reverts in app logic, it "resets" and result.reverted will be false when we run teardown,
261
- // but the kernel carries the reverted flag forward. But if the simulator reverts, so should the kernel.
262
- if (result.reverted && kernelOutput.revertCode.isOK()) {
263
- throw new Error(
264
- `Public kernel circuit did not revert on ${result.execution.contractAddress.toString()}:${functionSelector}, but simulator did.`,
265
- );
266
- }
267
-
268
- // We know the phase is revertible due to the above check.
269
- // So safely return the revert reason and the kernel output (which has had its revertible side effects dropped)
270
- if (result.reverted) {
271
- this.log.debug(
272
- `Reverting on ${result.execution.contractAddress.toString()}:${functionSelector} with reason: ${
273
- result.revertReason
274
- }`,
275
- );
276
- return [kernelOutput, kernelProof, [], result.revertReason, undefined];
277
- }
278
-
279
- if (!enqueuedExecutionResult) {
280
- enqueuedExecutionResult = result;
281
-
282
- // Padding as the AVM is not always returning the expected return size (4)
283
- // which is expected by the kernel.
284
- const paddedReturn = padArrayEnd(result.returnValues, Fr.ZERO, RETURN_VALUES_LENGTH);
285
-
286
- // TODO(#5450) Need to use the proper return values here
287
- const returnTypes: AbiType[] = [{ kind: 'array', length: 4, type: { kind: 'field' } }];
288
- const mockArtifact = { returnTypes } as any as FunctionArtifact;
289
-
290
- currentReturn = decodeReturnValues(mockArtifact, paddedReturn);
291
- }
292
- }
293
- // HACK(#1622): Manually patches the ordering of public state actions
294
- // TODO(#757): Enforce proper ordering of public state actions
295
- patchPublicStorageActionOrdering(kernelOutput, enqueuedExecutionResult!, this.phase);
296
-
297
- returns.push(currentReturn);
298
- }
299
-
300
- // TODO(#3675): This should be done in a public kernel circuit
301
- removeRedundantPublicDataWrites(kernelOutput, this.phase);
302
-
303
- return [kernelOutput, kernelProof, newUnencryptedFunctionLogs, undefined, returns];
304
- }
305
-
306
- protected async runKernelCircuit(
307
- previousOutput: PublicKernelCircuitPublicInputs,
308
- previousProof: Proof,
309
- callData: PublicCallData,
310
- ): Promise<[PublicKernelCircuitPublicInputs, Proof]> {
311
- const output = await this.getKernelCircuitOutput(previousOutput, previousProof, callData);
312
- return [output, makeEmptyProof()];
313
- }
314
-
315
- protected getKernelCircuitOutput(
316
- previousOutput: PublicKernelCircuitPublicInputs,
317
- previousProof: Proof,
318
- callData: PublicCallData,
319
- ): Promise<PublicKernelCircuitPublicInputs> {
320
- const previousKernel = this.getPreviousKernelData(previousOutput, previousProof);
321
-
322
- const inputs = new PublicKernelCircuitPrivateInputs(previousKernel, callData);
323
- switch (this.phase) {
324
- case PublicKernelPhase.SETUP:
325
- return this.publicKernel.publicKernelCircuitSetup(inputs);
326
- case PublicKernelPhase.APP_LOGIC:
327
- return this.publicKernel.publicKernelCircuitAppLogic(inputs);
328
- case PublicKernelPhase.TEARDOWN:
329
- return this.publicKernel.publicKernelCircuitTeardown(inputs);
330
- default:
331
- throw new Error(`No public kernel circuit for inputs`);
332
- }
333
- }
334
-
335
- protected getPreviousKernelData(
336
- previousOutput: PublicKernelCircuitPublicInputs,
337
- previousProof: Proof,
338
- ): PublicKernelData {
339
- // TODO(@PhilWindle) Fix once we move this to prover-client
340
- const vk = VerificationKey.makeFake();
341
- const vkIndex = 0;
342
- const vkSiblingPath = MembershipWitness.random(VK_TREE_HEIGHT).siblingPath;
343
- return new PublicKernelData(previousOutput, previousProof, vk, vkIndex, vkSiblingPath);
344
- }
345
-
346
- protected async getPublicCircuitPublicInputs(result: PublicExecutionResult) {
347
- const publicDataTreeInfo = await this.db.getTreeInfo(MerkleTreeId.PUBLIC_DATA_TREE);
348
- this.historicalHeader.state.partial.publicDataTree.root = Fr.fromBuffer(publicDataTreeInfo.root);
349
-
350
- const callStackPreimages = await this.getPublicCallStackPreimages(result);
351
- const publicCallStackHashes = padArrayEnd(
352
- callStackPreimages.map(c => c.hash()),
353
- Fr.ZERO,
354
- MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL,
355
- );
356
-
357
- // TODO(https://github.com/AztecProtocol/aztec-packages/issues/1165) --> set this in Noir
358
- const unencryptedLogsHash = Fr.fromBuffer(result.unencryptedLogs.hash());
359
- const unencryptedLogPreimagesLength = new Fr(result.unencryptedLogs.getSerializedLength());
360
-
361
- return PublicCircuitPublicInputs.from({
362
- callContext: result.execution.callContext,
363
- proverAddress: AztecAddress.ZERO,
364
- argsHash: computeVarArgsHash(result.execution.args),
365
- newNoteHashes: padArrayEnd(result.newNoteHashes, SideEffect.empty(), MAX_NEW_NOTE_HASHES_PER_CALL),
366
- newNullifiers: padArrayEnd(result.newNullifiers, SideEffectLinkedToNoteHash.empty(), MAX_NEW_NULLIFIERS_PER_CALL),
367
- newL2ToL1Msgs: padArrayEnd(result.newL2ToL1Messages, L2ToL1Message.empty(), MAX_NEW_L2_TO_L1_MSGS_PER_CALL),
368
- startSideEffectCounter: result.startSideEffectCounter,
369
- endSideEffectCounter: result.endSideEffectCounter,
370
- returnValues: padArrayEnd(result.returnValues, Fr.ZERO, RETURN_VALUES_LENGTH),
371
- nullifierReadRequests: padArrayEnd(
372
- result.nullifierReadRequests,
373
- ReadRequest.empty(),
374
- MAX_NULLIFIER_READ_REQUESTS_PER_CALL,
375
- ),
376
- nullifierNonExistentReadRequests: padArrayEnd(
377
- result.nullifierNonExistentReadRequests,
378
- ReadRequest.empty(),
379
- MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_CALL,
380
- ),
381
- contractStorageReads: padArrayEnd(
382
- result.contractStorageReads,
383
- ContractStorageRead.empty(),
384
- MAX_PUBLIC_DATA_READS_PER_CALL,
385
- ),
386
- contractStorageUpdateRequests: padArrayEnd(
387
- result.contractStorageUpdateRequests,
388
- ContractStorageUpdateRequest.empty(),
389
- MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL,
390
- ),
391
- publicCallStackHashes,
392
- unencryptedLogsHash,
393
- unencryptedLogPreimagesLength,
394
- historicalHeader: this.historicalHeader,
395
- // TODO(@just-mitch): need better mapping from simulator to revert code.
396
- revertCode: result.reverted ? RevertCode.REVERTED : RevertCode.OK,
397
- });
398
- }
399
-
400
- protected async getPublicCallStackItem(result: PublicExecutionResult, isExecutionRequest = false) {
401
- return new PublicCallStackItem(
402
- result.execution.contractAddress,
403
- result.execution.functionData,
404
- await this.getPublicCircuitPublicInputs(result),
405
- isExecutionRequest,
406
- );
407
- }
408
-
409
- protected async getPublicCallStackPreimages(result: PublicExecutionResult): Promise<PublicCallStackItem[]> {
410
- const nested = result.nestedExecutions;
411
- if (nested.length > MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL) {
412
- throw new Error(
413
- `Public call stack size exceeded (max ${MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL}, got ${nested.length})`,
414
- );
415
- }
416
-
417
- return await Promise.all(nested.map(n => this.getPublicCallStackItem(n)));
418
- }
419
-
420
- protected getBytecodeHash(_result: PublicExecutionResult) {
421
- // TODO: Determine how to calculate bytecode hash. Circuits just check it isn't zero for now.
422
- // See https://github.com/AztecProtocol/aztec3-packages/issues/378
423
- const bytecodeHash = new Fr(1n);
424
- return Promise.resolve(bytecodeHash);
425
- }
426
-
427
- /**
428
- * Calculates the PublicCircuitOutput for this execution result along with its proof,
429
- * and assembles a PublicCallData object from it.
430
- * @param result - The execution result.
431
- * @param preimages - The preimages of the callstack items.
432
- * @param isExecutionRequest - Whether the current callstack item should be considered a public fn execution request.
433
- * @returns A corresponding PublicCallData object.
434
- */
435
- protected async getPublicCallData(result: PublicExecutionResult, isExecutionRequest = false) {
436
- const bytecodeHash = await this.getBytecodeHash(result);
437
- const callStackItem = await this.getPublicCallStackItem(result, isExecutionRequest);
438
- const publicCallRequests = (await this.getPublicCallStackPreimages(result)).map(c =>
439
- c.toCallRequest(callStackItem.publicInputs.callContext),
440
- );
441
- const publicCallStack = padArrayEnd(publicCallRequests, CallRequest.empty(), MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL);
442
- const portalContractAddress = result.execution.callContext.portalContractAddress.toField();
443
- return new PublicCallData(callStackItem, publicCallStack, makeEmptyProof(), portalContractAddress, bytecodeHash);
444
- }
445
- }
446
-
447
- function removeRedundantPublicDataWrites(publicInputs: PublicKernelCircuitPublicInputs, phase: PublicKernelPhase) {
448
- const lastWritesMap = new Map<string, boolean>();
449
- const patch = <N extends number>(requests: Tuple<PublicDataUpdateRequest, N>) =>
450
- requests.filter(write => {
451
- const leafSlot = write.leafSlot.toString();
452
- const exists = lastWritesMap.get(leafSlot);
453
- lastWritesMap.set(leafSlot, true);
454
- return !exists;
455
- });
456
-
457
- const [prev, curr] = PhaseIsRevertible[phase]
458
- ? [publicInputs.endNonRevertibleData, publicInputs.end]
459
- : [publicInputs.end, publicInputs.endNonRevertibleData];
460
-
461
- curr.publicDataUpdateRequests = padArrayEnd(
462
- patch(curr.publicDataUpdateRequests.reverse()).reverse(),
463
- PublicDataUpdateRequest.empty(),
464
- MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX,
465
- );
466
-
467
- prev.publicDataUpdateRequests = padArrayEnd(
468
- patch(prev.publicDataUpdateRequests.reverse()),
469
- PublicDataUpdateRequest.empty(),
470
- MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX,
471
- );
472
- }
473
-
474
- // HACK(#1622): this is a hack to fix ordering of public state in the call stack. Since the private kernel
475
- // cannot keep track of side effects that happen after or before a nested call, we override the public
476
- // state actions it emits with whatever we got from the simulator. As a sanity check, we at least verify
477
- // that the elements are the same, so we are only tweaking their ordering.
478
- // See yarn-project/end-to-end/src/e2e_ordering.test.ts
479
- // See https://github.com/AztecProtocol/aztec-packages/issues/1616
480
- // TODO(#757): Enforce proper ordering of public state actions
481
- /**
482
- * Patch the ordering of storage actions output from the public kernel.
483
- * @param publicInputs - to be patched here: public inputs to the kernel iteration up to this point
484
- * @param execResult - result of the top/first execution for this enqueued public call
485
- */
486
- function patchPublicStorageActionOrdering(
487
- publicInputs: PublicKernelCircuitPublicInputs,
488
- execResult: PublicExecutionResult,
489
- phase: PublicKernelPhase,
490
- ) {
491
- const { publicDataUpdateRequests } = PhaseIsRevertible[phase] ? publicInputs.end : publicInputs.endNonRevertibleData;
492
- const { publicDataReads } = publicInputs.validationRequests;
493
-
494
- // Convert ContractStorage* objects to PublicData* objects and sort them in execution order.
495
- // Note, this only pulls simulated reads/writes from the current phase,
496
- // so the returned result will be a subset of the public kernel output.
497
-
498
- const simPublicDataReads = collectPublicDataReads(execResult);
499
- // verify that each read is in the kernel output
500
- for (const read of simPublicDataReads) {
501
- if (!publicDataReads.find(item => item.equals(read))) {
502
- throw new Error(
503
- `Public data reads from simulator do not match those from public kernel.\nFrom simulator: ${simPublicDataReads
504
- .map(p => p.toFriendlyJSON())
505
- .join(', ')}\nFrom public kernel: ${publicDataReads.map(i => i.toFriendlyJSON()).join(', ')}`,
506
- );
507
- }
508
- }
509
-
510
- const simPublicDataUpdateRequests = collectPublicDataUpdateRequests(execResult);
511
- for (const update of simPublicDataUpdateRequests) {
512
- if (!publicDataUpdateRequests.find(item => item.equals(update))) {
513
- throw new Error(
514
- `Public data update requests from simulator do not match those from public kernel.\nFrom simulator: ${simPublicDataUpdateRequests
515
- .map(p => p.toFriendlyJSON())
516
- .join(', ')}\nFrom public kernel revertible: ${publicDataUpdateRequests
517
- .map(i => i.toFriendlyJSON())
518
- .join(', ')}`,
519
- );
520
- }
521
- }
522
- // We only want to reorder the items from the public inputs of the
523
- // most recently processed top/enqueued call.
524
-
525
- const effectSet = PhaseIsRevertible[phase] ? 'end' : 'endNonRevertibleData';
526
-
527
- const numReadsInKernel = arrayNonEmptyLength(publicDataReads, f => f.isEmpty());
528
- const numReadsBeforeThisEnqueuedCall = numReadsInKernel - simPublicDataReads.length;
529
- publicInputs.validationRequests.publicDataReads = padArrayEnd(
530
- [
531
- // do not mess with items from previous top/enqueued calls in kernel output
532
- ...publicInputs.validationRequests.publicDataReads.slice(0, numReadsBeforeThisEnqueuedCall),
533
- ...simPublicDataReads,
534
- ],
535
- PublicDataRead.empty(),
536
- MAX_PUBLIC_DATA_READS_PER_TX,
537
- );
538
-
539
- const numUpdatesInKernel = arrayNonEmptyLength(publicDataUpdateRequests, f => f.isEmpty());
540
- const numUpdatesBeforeThisEnqueuedCall = numUpdatesInKernel - simPublicDataUpdateRequests.length;
541
- publicInputs[effectSet].publicDataUpdateRequests = padArrayEnd(
542
- [
543
- ...publicInputs[effectSet].publicDataUpdateRequests.slice(0, numUpdatesBeforeThisEnqueuedCall),
544
- ...simPublicDataUpdateRequests,
545
- ],
546
- PublicDataUpdateRequest.empty(),
547
- MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX,
548
- );
549
- }
@@ -1,62 +0,0 @@
1
- import { type Tx } from '@aztec/circuit-types';
2
- import {
3
- type GlobalVariables,
4
- type Header,
5
- type Proof,
6
- type PublicKernelCircuitPublicInputs,
7
- } from '@aztec/circuits.js';
8
- import { type PublicExecutor, type PublicStateDB } from '@aztec/simulator';
9
- import { type MerkleTreeOperations } from '@aztec/world-state';
10
-
11
- import { type PublicKernelCircuitSimulator } from '../simulator/index.js';
12
- import { type ContractsDataSourcePublicDB } from '../simulator/public_executor.js';
13
- import { AbstractPhaseManager, PublicKernelPhase } from './abstract_phase_manager.js';
14
-
15
- /**
16
- * The phase manager responsible for performing the fee preparation phase.
17
- */
18
- export class AppLogicPhaseManager extends AbstractPhaseManager {
19
- constructor(
20
- protected db: MerkleTreeOperations,
21
- protected publicExecutor: PublicExecutor,
22
- protected publicKernel: PublicKernelCircuitSimulator,
23
- protected globalVariables: GlobalVariables,
24
- protected historicalHeader: Header,
25
- protected publicContractsDB: ContractsDataSourcePublicDB,
26
- protected publicStateDB: PublicStateDB,
27
- public phase: PublicKernelPhase = PublicKernelPhase.APP_LOGIC,
28
- ) {
29
- super(db, publicExecutor, publicKernel, globalVariables, historicalHeader, phase);
30
- }
31
-
32
- override async handle(
33
- tx: Tx,
34
- previousPublicKernelOutput: PublicKernelCircuitPublicInputs,
35
- previousPublicKernelProof: Proof,
36
- ) {
37
- // add new contracts to the contracts db so that their functions may be found and called
38
- // TODO(#4073): This is catching only private deployments, when we add public ones, we'll
39
- // have to capture contracts emitted in that phase as well.
40
- // TODO(@spalladino): Should we allow emitting contracts in the fee preparation phase?
41
- this.log.verbose(`Processing tx ${tx.getTxHash()}`);
42
- await this.publicContractsDB.addNewContracts(tx);
43
- const [publicKernelOutput, publicKernelProof, newUnencryptedFunctionLogs, revertReason, returnValues] =
44
- await this.processEnqueuedPublicCalls(tx, previousPublicKernelOutput, previousPublicKernelProof).catch(
45
- // if we throw for any reason other than simulation, we need to rollback and drop the TX
46
- async err => {
47
- await this.publicStateDB.rollbackToCommit();
48
- throw err;
49
- },
50
- );
51
-
52
- if (revertReason) {
53
- await this.publicContractsDB.removeNewContracts(tx);
54
- await this.publicStateDB.rollbackToCheckpoint();
55
- } else {
56
- tx.unencryptedLogs.addFunctionLogs(newUnencryptedFunctionLogs);
57
- await this.publicStateDB.checkpoint();
58
- }
59
-
60
- return { publicKernelOutput, publicKernelProof, revertReason, returnValues };
61
- }
62
- }