@aztec/simulator 3.0.0-nightly.20251205 → 3.0.0-nightly.20251206

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 (69) hide show
  1. package/dest/public/avm/avm_simulator.d.ts +1 -1
  2. package/dest/public/avm/avm_simulator.d.ts.map +1 -1
  3. package/dest/public/avm/avm_simulator.js +5 -4
  4. package/dest/public/avm/errors.d.ts +7 -1
  5. package/dest/public/avm/errors.d.ts.map +1 -1
  6. package/dest/public/avm/errors.js +14 -2
  7. package/dest/public/avm/opcodes/addressing_mode.js +2 -2
  8. package/dest/public/avm/opcodes/misc.js +2 -2
  9. package/dest/public/avm/revert_reason.d.ts +1 -1
  10. package/dest/public/avm/revert_reason.d.ts.map +1 -1
  11. package/dest/public/avm/revert_reason.js +3 -2
  12. package/dest/public/avm/serialization/bytecode_serialization.d.ts +1 -1
  13. package/dest/public/avm/serialization/bytecode_serialization.d.ts.map +1 -1
  14. package/dest/public/avm/serialization/bytecode_serialization.js +9 -6
  15. package/dest/public/debug_fn_name.d.ts +14 -1
  16. package/dest/public/debug_fn_name.d.ts.map +1 -1
  17. package/dest/public/debug_fn_name.js +19 -0
  18. package/dest/public/fixtures/public_tx_simulation_tester.d.ts +8 -2
  19. package/dest/public/fixtures/public_tx_simulation_tester.d.ts.map +1 -1
  20. package/dest/public/fixtures/public_tx_simulation_tester.js +12 -4
  21. package/dest/public/fixtures/simple_contract_data_source.d.ts +2 -2
  22. package/dest/public/fixtures/simple_contract_data_source.d.ts.map +1 -1
  23. package/dest/public/fixtures/simple_contract_data_source.js +4 -4
  24. package/dest/public/fixtures/token_test.d.ts +6 -2
  25. package/dest/public/fixtures/token_test.d.ts.map +1 -1
  26. package/dest/public/fixtures/token_test.js +12 -10
  27. package/dest/public/index.d.ts +2 -2
  28. package/dest/public/index.d.ts.map +1 -1
  29. package/dest/public/index.js +1 -1
  30. package/dest/public/public_processor/public_processor.d.ts +5 -5
  31. package/dest/public/public_processor/public_processor.d.ts.map +1 -1
  32. package/dest/public/public_processor/public_processor.js +13 -12
  33. package/dest/public/public_tx_simulator/cpp_public_tx_simulator.d.ts +6 -34
  34. package/dest/public/public_tx_simulator/cpp_public_tx_simulator.d.ts.map +1 -1
  35. package/dest/public/public_tx_simulator/cpp_public_tx_simulator.js +22 -139
  36. package/dest/public/public_tx_simulator/cpp_public_tx_simulator_with_hinted_dbs.d.ts +42 -0
  37. package/dest/public/public_tx_simulator/cpp_public_tx_simulator_with_hinted_dbs.d.ts.map +1 -0
  38. package/dest/public/public_tx_simulator/cpp_public_tx_simulator_with_hinted_dbs.js +86 -0
  39. package/dest/public/public_tx_simulator/cpp_vs_ts_public_tx_simulator.d.ts +30 -0
  40. package/dest/public/public_tx_simulator/cpp_vs_ts_public_tx_simulator.d.ts.map +1 -0
  41. package/dest/public/public_tx_simulator/cpp_vs_ts_public_tx_simulator.js +170 -0
  42. package/dest/public/public_tx_simulator/index.d.ts +2 -1
  43. package/dest/public/public_tx_simulator/index.d.ts.map +1 -1
  44. package/dest/public/public_tx_simulator/index.js +1 -0
  45. package/dest/public/public_tx_simulator/public_tx_simulator.d.ts +2 -2
  46. package/dest/public/public_tx_simulator/public_tx_simulator.d.ts.map +1 -1
  47. package/dest/public/public_tx_simulator/public_tx_simulator.js +7 -3
  48. package/dest/public/state_manager/state_manager.d.ts +6 -1
  49. package/dest/public/state_manager/state_manager.d.ts.map +1 -1
  50. package/dest/public/state_manager/state_manager.js +4 -1
  51. package/package.json +16 -16
  52. package/src/public/avm/avm_simulator.ts +7 -4
  53. package/src/public/avm/errors.ts +16 -2
  54. package/src/public/avm/opcodes/addressing_mode.ts +2 -2
  55. package/src/public/avm/opcodes/misc.ts +2 -2
  56. package/src/public/avm/revert_reason.ts +5 -2
  57. package/src/public/avm/serialization/bytecode_serialization.ts +17 -6
  58. package/src/public/debug_fn_name.ts +25 -0
  59. package/src/public/fixtures/public_tx_simulation_tester.ts +27 -6
  60. package/src/public/fixtures/simple_contract_data_source.ts +5 -7
  61. package/src/public/fixtures/token_test.ts +17 -8
  62. package/src/public/index.ts +5 -1
  63. package/src/public/public_processor/public_processor.ts +16 -16
  64. package/src/public/public_tx_simulator/cpp_public_tx_simulator.ts +23 -174
  65. package/src/public/public_tx_simulator/cpp_public_tx_simulator_with_hinted_dbs.ts +132 -0
  66. package/src/public/public_tx_simulator/cpp_vs_ts_public_tx_simulator.ts +240 -0
  67. package/src/public/public_tx_simulator/index.ts +1 -0
  68. package/src/public/public_tx_simulator/public_tx_simulator.ts +10 -6
  69. package/src/public/state_manager/state_manager.ts +8 -1
@@ -0,0 +1,240 @@
1
+ import { type Logger, createLogger, logLevel } from '@aztec/foundation/log';
2
+ import { writeTestData } from '@aztec/foundation/testing/files';
3
+ import { avmSimulate } from '@aztec/native';
4
+ import { ProtocolContractsList } from '@aztec/protocol-contracts';
5
+ import {
6
+ AvmFastSimulationInputs,
7
+ AvmTxHint,
8
+ type PublicSimulatorConfig,
9
+ PublicTxResult,
10
+ deserializeFromMessagePack,
11
+ } from '@aztec/stdlib/avm';
12
+ import { SimulationError } from '@aztec/stdlib/errors';
13
+ import type { MerkleTreeWriteOperations } from '@aztec/stdlib/trees';
14
+ import type { GlobalVariables, StateReference, Tx } from '@aztec/stdlib/tx';
15
+ import { WorldStateRevisionWithHandle } from '@aztec/stdlib/world-state';
16
+
17
+ import { strict as assert } from 'assert';
18
+
19
+ import type { ExecutorMetricsInterface } from '../executor_metrics_interface.js';
20
+ import type { PublicContractsDB } from '../public_db_sources.js';
21
+ import { ContractProviderForCpp } from './contract_provider_for_cpp.js';
22
+ import { PublicTxSimulator } from './public_tx_simulator.js';
23
+ import type {
24
+ MeasuredPublicTxSimulatorInterface,
25
+ PublicTxSimulatorInterface,
26
+ } from './public_tx_simulator_interface.js';
27
+
28
+ /**
29
+ * An implementation of PublicTxSimulator that first simulates in C++, then TS, an compares the results.
30
+ * The C++ simulator accesses the world state directly/natively within C++.
31
+ * For contract DB accesses, it makes callbacks through NAPI back to the TS PublicContractsDB cache.
32
+ */
33
+ export class CppVsTsPublicTxSimulator extends PublicTxSimulator implements PublicTxSimulatorInterface {
34
+ protected override log: Logger;
35
+
36
+ constructor(
37
+ merkleTree: MerkleTreeWriteOperations,
38
+ contractsDB: PublicContractsDB,
39
+ globalVariables: GlobalVariables,
40
+ config?: Partial<PublicSimulatorConfig>,
41
+ ) {
42
+ super(merkleTree, contractsDB, globalVariables, config);
43
+ this.log = createLogger(`simulator:cpp_public_tx_simulator`);
44
+ }
45
+
46
+ /**
47
+ * Simulate a transaction's public portion using the C++ avvm simulator.
48
+ *
49
+ * @param tx - The transaction to simulate.
50
+ * @returns The result of the transaction's public execution.
51
+ */
52
+ public override async simulate(tx: Tx): Promise<PublicTxResult> {
53
+ const txHash = this.computeTxHash(tx);
54
+ this.log.debug(`C++ simulation of ${tx.publicFunctionCalldata.length} public calls for tx ${txHash}`, {
55
+ txHash,
56
+ });
57
+
58
+ // Run TS simulation to generate hints and public inputs
59
+ this.log.debug(`Running TS simulation for tx ${txHash}`);
60
+
61
+ // create checkpoint for ws
62
+ let tsResult: PublicTxResult | undefined;
63
+ let tsStateRef: StateReference | undefined;
64
+ await this.merkleTree.createCheckpoint();
65
+ this.contractsDB.createCheckpoint();
66
+ try {
67
+ // Run the full TypeScript simulation using the parent class
68
+ // This will modify the merkle tree with the transaction's state changes
69
+ tsResult = await super.simulate(tx);
70
+ this.log.debug(`TS simulation completed for tx ${txHash}`);
71
+
72
+ tsStateRef = await this.merkleTree.getStateReference(); // capture tree roots for later comparsion
73
+ } catch (error: any) {
74
+ this.log.warn(`TS simulation failed, but still continuing with C++ simulation: ${error.message} ${error.stack}`);
75
+ } finally {
76
+ // revert checkpoint for ws and clear contract db changes
77
+ // (cpp should reapply exactly the same changes if there are no bugs)
78
+ await this.merkleTree.revertCheckpoint();
79
+ this.contractsDB.revertCheckpoint();
80
+ }
81
+
82
+ this.log.debug(`Running C++ simulation for tx ${txHash}`);
83
+
84
+ // Using the "as WorldStateRevisionWithHandle" is a bit of a "trust me bro", hence the assert.
85
+ let wsRevision = this.merkleTree.getRevision();
86
+ assert(
87
+ wsRevision instanceof WorldStateRevisionWithHandle,
88
+ 'CppPublicTxSimulator a real NativeWorldStateInstance with a handle to the C++ WorldState object',
89
+ );
90
+ const wsCppHandle = (wsRevision as WorldStateRevisionWithHandle).handle;
91
+ wsRevision = wsRevision.toWorldStateRevision(); // for msgpack serialization, we don't include the handle in the type
92
+
93
+ this.log.debug(`Running C++ simulation with world state revision ${JSON.stringify(wsRevision)}`);
94
+
95
+ // Create the fast simulation inputs
96
+ const txHint = AvmTxHint.fromTx(tx, this.globalVariables.gasFees);
97
+ const protocolContracts = ProtocolContractsList;
98
+ const fastSimInputs = new AvmFastSimulationInputs(
99
+ wsRevision,
100
+ this.config,
101
+ txHint,
102
+ this.globalVariables,
103
+ protocolContracts,
104
+ );
105
+
106
+ // Create contract provider for callbacks to TypeScript PublicContractsDB from C++
107
+ const contractProvider = new ContractProviderForCpp(this.contractsDB, this.globalVariables);
108
+
109
+ // Serialize to msgpack and call the C++ simulator
110
+ this.log.debug(`Serializing fast simulation inputs to msgpack...`);
111
+ const inputBuffer = fastSimInputs.serializeWithMessagePack();
112
+
113
+ let resultBuffer: Buffer;
114
+ try {
115
+ this.log.debug(`Calling C++ simulator for tx ${txHash}`);
116
+ resultBuffer = await avmSimulate(inputBuffer, contractProvider, wsCppHandle, logLevel);
117
+ } catch (error: any) {
118
+ throw new SimulationError(`C++ simulation failed: ${error.message}`, []);
119
+ }
120
+
121
+ // If we've reached this point, C++ succeeded during simulation,
122
+ // so we assert that TS also succeeded.
123
+ assert(tsResult !== undefined, 'TS simulation should have succeeded if C++ succeeded');
124
+ assert(tsStateRef !== undefined, 'TS state reference should have been captured if C++ succeeded');
125
+
126
+ // Deserialize the msgpack result
127
+ this.log.debug(`Deserializing C++ from buffer (size: ${resultBuffer.length})...`);
128
+ const cppResultJSON: object = deserializeFromMessagePack(resultBuffer);
129
+ // Write testdata if AZTEC_WRITE_TESTDATA=1.
130
+ writeTestData(
131
+ `barretenberg/cpp/src/barretenberg/vm2/testing/tx_result_${txHash}.testdata.bin`,
132
+ resultBuffer,
133
+ /*raw=*/ true,
134
+ );
135
+ this.log.debug(`Deserializing C++ result to PublicTxResult...`);
136
+ const cppResult = PublicTxResult.fromPlainObject(cppResultJSON);
137
+ this.log.debug(`Done.`);
138
+ assert(cppResult.revertCode.equals(tsResult.revertCode));
139
+ assert(cppResult.gasUsed.totalGas.equals(tsResult.gasUsed.totalGas));
140
+ assert(cppResult.gasUsed.publicGas.equals(tsResult.gasUsed.publicGas));
141
+ assert(cppResult.gasUsed.teardownGas.equals(tsResult.gasUsed.teardownGas));
142
+ assert(cppResult.gasUsed.billedGas.equals(tsResult.gasUsed.billedGas));
143
+ assert(cppResult.publicInputs.toBuffer().equals(tsResult.publicInputs.toBuffer()));
144
+
145
+ // TODO(fcarreiro): complete this.
146
+ // Check that C++ hints are a strict subset of TS hints.
147
+ // Then enable for misc tests and validate hints.
148
+ //if (this.config?.collectHints) {
149
+ //}
150
+
151
+ if (this.config?.collectCallMetadata) {
152
+ assert(cppResult.getAppLogicReturnValues().length === tsResult.getAppLogicReturnValues().length);
153
+ for (let i = 0; i < cppResult.getAppLogicReturnValues().length; i++) {
154
+ assert(cppResult.getAppLogicReturnValues()[i].equals(tsResult.getAppLogicReturnValues()[i]));
155
+ }
156
+ }
157
+ // Messages are still not ok for exceptional halts (they are not plumbed in C++).
158
+ const cppRevertReason = cppResult.findRevertReason() || {};
159
+ const tsRevertReason = tsResult.findRevertReason() || {};
160
+ const cppRevertReasonAsObject = JSON.parse(JSON.stringify(cppRevertReason));
161
+ const tsRevertReasonAsObject = JSON.parse(JSON.stringify(tsRevertReason));
162
+ if (JSON.stringify(cppRevertReasonAsObject) !== JSON.stringify(tsRevertReasonAsObject)) {
163
+ this.log.debug('cppResult.findRevertReason()', cppRevertReasonAsObject);
164
+ this.log.debug('tsResult.findRevertReason()', tsRevertReasonAsObject);
165
+ }
166
+ // TODO: dont compare the strings since this is not deterministic.
167
+
168
+ // Sometimes error messages are different between C++ and TS, so we omit in the default comparison
169
+ const cppRevertReasonWithoutMessage = { ...cppRevertReasonAsObject, originalMessage: undefined };
170
+ const tsRevertReasonWithoutMessage = { ...tsRevertReasonAsObject, originalMessage: undefined };
171
+ assert(JSON.stringify(cppRevertReasonWithoutMessage) === JSON.stringify(tsRevertReasonWithoutMessage));
172
+
173
+ const cppHasRevertMessage =
174
+ cppRevertReasonAsObject.originalMessage && cppRevertReasonAsObject.originalMessage.length > 0;
175
+ const tsHasRevertMessage =
176
+ tsRevertReasonAsObject.originalMessage && tsRevertReasonAsObject.originalMessage.length > 0;
177
+ // assert that if one of the error messages is non-empty, the other is
178
+ assert(
179
+ cppHasRevertMessage === tsHasRevertMessage,
180
+ 'One of the AVM simulators (C++ or TS) produced a revert message, but the other did not',
181
+ );
182
+ // Ideally, we'd love to be able to compare full error messages, but without a lot of work
183
+ // the two simulators will always be able to produce some differing errors.
184
+ // Commenting out the code below will enforce that the error messages are at least
185
+ // similar (one contains the other). Even this is not something we can guarantee.
186
+ //if (cppHasRevertMessage) {
187
+ // const cppRevertMessageContainsTs = cppRevertReasonAsObject.originalMessage.includes(
188
+ // tsRevertReasonAsObject.originalMessage,
189
+ // );
190
+ // const tsRevertMessageContainsCpp = tsRevertReasonAsObject.originalMessage.includes(
191
+ // cppRevertReasonAsObject.originalMessage,
192
+ // );
193
+ // assert(
194
+ // cppRevertMessageContainsTs || tsRevertMessageContainsCpp,
195
+ // 'The AVM simulators (C++ and TS) produced different revert messages (neither was a substring of the other)',
196
+ // );
197
+ //}
198
+
199
+ // Confirm that tree roots match
200
+ const cppStateRef = await this.merkleTree.getStateReference();
201
+ assert(
202
+ cppStateRef.equals(tsStateRef),
203
+ `Tree roots mismatch between TS and C++ public simulations for tx ${txHash}`,
204
+ );
205
+
206
+ this.log.debug(`C++ simulation completed for tx ${txHash}`, {
207
+ txHash,
208
+ reverted: !cppResult.revertCode.isOK(),
209
+ cppGasUsed: cppResult.gasUsed.totalGas.l2Gas,
210
+ });
211
+
212
+ return tsResult;
213
+ }
214
+ }
215
+
216
+ export class MeasuredCppVsTsPublicTxSimulator
217
+ extends CppVsTsPublicTxSimulator
218
+ implements MeasuredPublicTxSimulatorInterface
219
+ {
220
+ constructor(
221
+ merkleTree: MerkleTreeWriteOperations,
222
+ contractsDB: PublicContractsDB,
223
+ globalVariables: GlobalVariables,
224
+ protected readonly metrics: ExecutorMetricsInterface,
225
+ config?: Partial<PublicSimulatorConfig>,
226
+ ) {
227
+ super(merkleTree, contractsDB, globalVariables, config);
228
+ }
229
+
230
+ public override async simulate(tx: Tx, txLabel: string = 'unlabeledTx'): Promise<PublicTxResult> {
231
+ this.metrics.startRecordingTxSimulation(txLabel);
232
+ let result: PublicTxResult | undefined;
233
+ try {
234
+ result = await super.simulate(tx);
235
+ } finally {
236
+ this.metrics.stopRecordingTxSimulation(txLabel, result?.gasUsed, result?.revertCode);
237
+ }
238
+ return result;
239
+ }
240
+ }
@@ -1,4 +1,5 @@
1
1
  export * from './public_tx_simulator.js';
2
+ export { CppPublicTxSimulator, TelemetryCppPublicTxSimulator } from './cpp_public_tx_simulator.js';
2
3
  export type { PublicTxSimulatorInterface } from './public_tx_simulator_interface.js';
3
4
  export { TelemetryPublicTxSimulator } from './telemetry_public_tx_simulator.js';
4
5
  export type { PublicTxResult, PublicSimulatorConfig as PublicTxSimulatorConfig } from '@aztec/stdlib/avm';
@@ -5,7 +5,7 @@ import { ProtocolContractAddress, ProtocolContractsList } from '@aztec/protocol-
5
5
  import { computeFeePayerBalanceStorageSlot } from '@aztec/protocol-contracts/fee-juice';
6
6
  import { AvmExecutionHints, AvmTxHint, PublicSimulatorConfig, PublicTxResult } from '@aztec/stdlib/avm';
7
7
  import { SimulationError } from '@aztec/stdlib/errors';
8
- import type { Gas } from '@aztec/stdlib/gas';
8
+ import { Gas } from '@aztec/stdlib/gas';
9
9
  import type { MerkleTreeWriteOperations } from '@aztec/stdlib/trees';
10
10
  import {
11
11
  type GlobalVariables,
@@ -129,7 +129,7 @@ export class PublicTxSimulator implements PublicTxSimulatorInterface {
129
129
  const setupResult = await this.simulatePhase(TxExecutionPhase.SETUP, context);
130
130
  if (setupResult.reverted) {
131
131
  throw new Error(
132
- `Setup phase reverted! The transaction will be thrown out. ${setupResult.revertReason?.message}`,
132
+ `[SETUP] UNRECOVERABLE ERROR! The transaction will be thrown out. ${setupResult.revertReason?.message}`,
133
133
  );
134
134
  }
135
135
  processedPhases.push(setupResult);
@@ -200,10 +200,15 @@ export class PublicTxSimulator implements PublicTxSimulatorInterface {
200
200
  const publicInputs = await context.generateAvmCircuitPublicInputs();
201
201
  const revertCode = context.getFinalRevertCode();
202
202
 
203
- // We only return the app logic phase information.
204
- const appLogicReturnValues =
203
+ // We only return the app logic phase information, and only 1 per phase.
204
+ const appLogicReturnValues: NestedProcessReturnValues[] =
205
205
  processedPhases.find(({ phase }) => phase === TxExecutionPhase.APP_LOGIC)?.returnValues ?? [];
206
206
 
207
+ // TODO(fcarreiro): This is a temporary backwards compatibility layer until we migrate to the C++ simulator.
208
+ if (context.revertReason !== undefined) {
209
+ (appLogicReturnValues as any).revertReason = context.revertReason;
210
+ }
211
+
207
212
  return new PublicTxResult(
208
213
  /*gasUsed=*/ {
209
214
  totalGas: context.getActualGasUsed(),
@@ -212,8 +217,7 @@ export class PublicTxSimulator implements PublicTxSimulatorInterface {
212
217
  billedGas: context.getTotalGasUsed(),
213
218
  },
214
219
  /*revertCode=*/ revertCode,
215
- /*revertReason=*/ context.revertReason,
216
- /*appLogicReturnValues=*/ appLogicReturnValues,
220
+ /*callStackMetadata=*/ appLogicReturnValues,
217
221
  /*logs=*/ context.state.getActiveStateManager().getLogs(),
218
222
  /*hints=*/ hints,
219
223
  /*publicInputs=*/ publicInputs,
@@ -11,6 +11,7 @@ import { Fr } from '@aztec/foundation/fields';
11
11
  import { jsonStringify } from '@aztec/foundation/json-rpc';
12
12
  import { type LogLevel, createLogger } from '@aztec/foundation/log';
13
13
  import { ProtocolContractAddress } from '@aztec/protocol-contracts';
14
+ import { FunctionSelector } from '@aztec/stdlib/abi';
14
15
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
15
16
  import type { ContractClassPublicWithCommitment, ContractInstanceWithAddress } from '@aztec/stdlib/contract';
16
17
  import { SerializableContractInstance } from '@aztec/stdlib/contract';
@@ -26,7 +27,7 @@ import { strict as assert } from 'assert';
26
27
 
27
28
  import type { AvmExecutionEnvironment } from '../avm/avm_execution_environment.js';
28
29
  import type { PublicContractsDBInterface } from '../db_interfaces.js';
29
- import { getPublicFunctionDebugName } from '../debug_fn_name.js';
30
+ import { getPublicFunctionDebugName, getPublicFunctionSelectorAndName } from '../debug_fn_name.js';
30
31
  import type { PublicTreesDB } from '../public_db_sources.js';
31
32
  import {
32
33
  L1ToL2MessageIndexOutOfRangeError,
@@ -532,6 +533,12 @@ export class PublicPersistableStateManager {
532
533
  return await getPublicFunctionDebugName(this.contractsDB, avmEnvironment.address, avmEnvironment.calldata);
533
534
  }
534
535
 
536
+ public async getPublicFunctionSelectorAndName(
537
+ avmEnvironment: AvmExecutionEnvironment,
538
+ ): Promise<{ functionSelector?: FunctionSelector; functionName?: string }> {
539
+ return await getPublicFunctionSelectorAndName(this.contractsDB, avmEnvironment.address, avmEnvironment.calldata);
540
+ }
541
+
535
542
  public async padTree(treeId: MerkleTreeId, leavesToInsert: number): Promise<void> {
536
543
  await this.treesDB.padTree(treeId, leavesToInsert);
537
544
  }