@aztec/txe 0.0.0-test.1 → 0.0.1-commit.1142ef1

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 (100) hide show
  1. package/dest/bin/index.d.ts +1 -1
  2. package/dest/bin/index.js +3 -2
  3. package/dest/constants.d.ts +4 -0
  4. package/dest/constants.d.ts.map +1 -0
  5. package/dest/constants.js +3 -0
  6. package/dest/index.d.ts +1 -1
  7. package/dest/index.d.ts.map +1 -1
  8. package/dest/index.js +81 -51
  9. package/dest/oracle/interfaces.d.ts +57 -0
  10. package/dest/oracle/interfaces.d.ts.map +1 -0
  11. package/dest/oracle/interfaces.js +3 -0
  12. package/dest/oracle/txe_oracle_public_context.d.ts +34 -0
  13. package/dest/oracle/txe_oracle_public_context.d.ts.map +1 -0
  14. package/dest/oracle/txe_oracle_public_context.js +122 -0
  15. package/dest/oracle/txe_oracle_top_level_context.d.ts +65 -0
  16. package/dest/oracle/txe_oracle_top_level_context.d.ts.map +1 -0
  17. package/dest/oracle/txe_oracle_top_level_context.js +463 -0
  18. package/dest/rpc_translator.d.ts +246 -0
  19. package/dest/rpc_translator.d.ts.map +1 -0
  20. package/dest/rpc_translator.js +666 -0
  21. package/dest/state_machine/archiver.d.ts +80 -0
  22. package/dest/state_machine/archiver.d.ts.map +1 -0
  23. package/dest/state_machine/archiver.js +229 -0
  24. package/dest/state_machine/dummy_p2p_client.d.ts +55 -0
  25. package/dest/state_machine/dummy_p2p_client.d.ts.map +1 -0
  26. package/dest/state_machine/dummy_p2p_client.js +141 -0
  27. package/dest/state_machine/global_variable_builder.d.ts +11 -0
  28. package/dest/state_machine/global_variable_builder.d.ts.map +1 -0
  29. package/dest/state_machine/global_variable_builder.js +22 -0
  30. package/dest/state_machine/index.d.ts +16 -0
  31. package/dest/state_machine/index.d.ts.map +1 -0
  32. package/dest/state_machine/index.js +45 -0
  33. package/dest/state_machine/mock_epoch_cache.d.ts +27 -0
  34. package/dest/state_machine/mock_epoch_cache.d.ts.map +1 -0
  35. package/dest/state_machine/mock_epoch_cache.js +54 -0
  36. package/dest/state_machine/synchronizer.d.ts +33 -0
  37. package/dest/state_machine/synchronizer.d.ts.map +1 -0
  38. package/dest/state_machine/synchronizer.js +59 -0
  39. package/dest/txe_session.d.ts +73 -0
  40. package/dest/txe_session.d.ts.map +1 -0
  41. package/dest/txe_session.js +286 -0
  42. package/dest/util/encoding.d.ts +647 -30
  43. package/dest/util/encoding.d.ts.map +1 -1
  44. package/dest/util/encoding.js +66 -11
  45. package/dest/util/expected_failure_error.d.ts +1 -1
  46. package/dest/util/expected_failure_error.d.ts.map +1 -1
  47. package/dest/util/txe_account_store.d.ts +10 -0
  48. package/dest/util/txe_account_store.d.ts.map +1 -0
  49. package/dest/util/{txe_account_data_provider.js → txe_account_store.js} +1 -1
  50. package/dest/util/txe_contract_store.d.ts +12 -0
  51. package/dest/util/txe_contract_store.d.ts.map +1 -0
  52. package/dest/util/txe_contract_store.js +22 -0
  53. package/dest/util/txe_public_contract_data_source.d.ts +12 -11
  54. package/dest/util/txe_public_contract_data_source.d.ts.map +1 -1
  55. package/dest/util/txe_public_contract_data_source.js +37 -58
  56. package/dest/utils/block_creation.d.ts +28 -0
  57. package/dest/utils/block_creation.d.ts.map +1 -0
  58. package/dest/utils/block_creation.js +44 -0
  59. package/dest/utils/tx_effect_creation.d.ts +6 -0
  60. package/dest/utils/tx_effect_creation.d.ts.map +1 -0
  61. package/dest/utils/tx_effect_creation.js +16 -0
  62. package/package.json +30 -24
  63. package/src/bin/index.ts +3 -2
  64. package/src/constants.ts +4 -0
  65. package/src/index.ts +105 -74
  66. package/src/oracle/interfaces.ts +86 -0
  67. package/src/oracle/txe_oracle_public_context.ts +160 -0
  68. package/src/oracle/txe_oracle_top_level_context.ts +718 -0
  69. package/src/rpc_translator.ts +1083 -0
  70. package/src/state_machine/archiver.ts +294 -0
  71. package/src/state_machine/dummy_p2p_client.ts +209 -0
  72. package/src/state_machine/global_variable_builder.ts +38 -0
  73. package/src/state_machine/index.ts +78 -0
  74. package/src/state_machine/mock_epoch_cache.ts +72 -0
  75. package/src/state_machine/synchronizer.ts +88 -0
  76. package/src/txe_session.ts +525 -0
  77. package/src/util/encoding.ts +85 -11
  78. package/src/util/{txe_account_data_provider.ts → txe_account_store.ts} +1 -1
  79. package/src/util/txe_contract_store.ts +36 -0
  80. package/src/util/txe_public_contract_data_source.ts +43 -58
  81. package/src/utils/block_creation.ts +94 -0
  82. package/src/utils/tx_effect_creation.ts +38 -0
  83. package/dest/node/txe_node.d.ts +0 -358
  84. package/dest/node/txe_node.d.ts.map +0 -1
  85. package/dest/node/txe_node.js +0 -504
  86. package/dest/oracle/txe_oracle.d.ts +0 -152
  87. package/dest/oracle/txe_oracle.d.ts.map +0 -1
  88. package/dest/oracle/txe_oracle.js +0 -833
  89. package/dest/txe_service/txe_service.d.ts +0 -212
  90. package/dest/txe_service/txe_service.d.ts.map +0 -1
  91. package/dest/txe_service/txe_service.js +0 -572
  92. package/dest/util/txe_account_data_provider.d.ts +0 -10
  93. package/dest/util/txe_account_data_provider.d.ts.map +0 -1
  94. package/dest/util/txe_world_state_db.d.ts +0 -14
  95. package/dest/util/txe_world_state_db.d.ts.map +0 -1
  96. package/dest/util/txe_world_state_db.js +0 -27
  97. package/src/node/txe_node.ts +0 -725
  98. package/src/oracle/txe_oracle.ts +0 -1241
  99. package/src/txe_service/txe_service.ts +0 -749
  100. package/src/util/txe_world_state_db.ts +0 -38
@@ -0,0 +1,88 @@
1
+ import { NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP } from '@aztec/constants';
2
+ import { BlockNumber } from '@aztec/foundation/branded-types';
3
+ import { Fr } from '@aztec/foundation/curves/bn254';
4
+ import type { L2BlockNew } from '@aztec/stdlib/block';
5
+ import type {
6
+ MerkleTreeReadOperations,
7
+ MerkleTreeWriteOperations,
8
+ SnapshotDataKeys,
9
+ WorldStateSynchronizer,
10
+ WorldStateSynchronizerStatus,
11
+ } from '@aztec/stdlib/interfaces/server';
12
+ import { NativeWorldStateService } from '@aztec/world-state/native';
13
+
14
+ export class TXESynchronizer implements WorldStateSynchronizer {
15
+ // This works when set to 1 as well.
16
+ private blockNumber = BlockNumber.ZERO;
17
+
18
+ constructor(public nativeWorldStateService: NativeWorldStateService) {}
19
+
20
+ static async create() {
21
+ const nativeWorldStateService = await NativeWorldStateService.tmp();
22
+
23
+ return new this(nativeWorldStateService);
24
+ }
25
+
26
+ public async handleL2Block(block: L2BlockNew) {
27
+ await this.nativeWorldStateService.handleL2BlockAndMessages(
28
+ block,
29
+ Array(NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP).fill(0).map(Fr.zero),
30
+ );
31
+
32
+ this.blockNumber = block.header.globalVariables.blockNumber;
33
+ }
34
+
35
+ /**
36
+ * Forces an immediate sync to an optionally provided minimum block number
37
+ * @param targetBlockNumber - The target block number that we must sync to. Will download unproven blocks if needed to reach it.
38
+ * @param skipThrowIfTargetNotReached - Whether to skip throwing if the target block number is not reached.
39
+ * @returns A promise that resolves with the block number the world state was synced to
40
+ */
41
+ public syncImmediate(_minBlockNumber?: BlockNumber, _skipThrowIfTargetNotReached?: boolean): Promise<BlockNumber> {
42
+ return Promise.resolve(this.blockNumber);
43
+ }
44
+
45
+ /** Returns an instance of MerkleTreeAdminOperations that will not include uncommitted data. */
46
+ public getCommitted(): MerkleTreeReadOperations {
47
+ return this.nativeWorldStateService.getCommitted();
48
+ }
49
+
50
+ /** Forks the world state at the given block number, defaulting to the latest one. */
51
+ public fork(block?: number): Promise<MerkleTreeWriteOperations> {
52
+ return this.nativeWorldStateService.fork(block ? BlockNumber(block) : undefined);
53
+ }
54
+
55
+ /** Gets a handle that allows reading the state as it was at the given block number. */
56
+ public getSnapshot(blockNumber: number): MerkleTreeReadOperations {
57
+ return this.nativeWorldStateService.getSnapshot(BlockNumber(blockNumber));
58
+ }
59
+
60
+ /** Backups the db to the target path. */
61
+ public backupTo(dstPath: string, compact?: boolean): Promise<Record<Exclude<SnapshotDataKeys, 'archiver'>, string>> {
62
+ return this.nativeWorldStateService.backupTo(dstPath, compact);
63
+ }
64
+
65
+ public start(): Promise<void> {
66
+ throw new Error('TXE Synchronizer does not implement "start"');
67
+ }
68
+
69
+ public status(): Promise<WorldStateSynchronizerStatus> {
70
+ throw new Error('TXE Synchronizer does not implement "status"');
71
+ }
72
+
73
+ public stop(): Promise<void> {
74
+ throw new Error('TXE Synchronizer does not implement "stop"');
75
+ }
76
+
77
+ public stopSync(): Promise<void> {
78
+ throw new Error('TXE Synchronizer does not implement "stopSync"');
79
+ }
80
+
81
+ public resumeSync(): void {
82
+ throw new Error('TXE Synchronizer does not implement "resumeSync"');
83
+ }
84
+
85
+ public clear(): Promise<void> {
86
+ throw new Error('TXE Synchronizer does not implement "clear"');
87
+ }
88
+ }
@@ -0,0 +1,525 @@
1
+ import { BlockNumber } from '@aztec/foundation/branded-types';
2
+ import { Fr } from '@aztec/foundation/curves/bn254';
3
+ import { type Logger, createLogger } from '@aztec/foundation/log';
4
+ import { KeyStore } from '@aztec/key-store';
5
+ import { openTmpStore } from '@aztec/kv-store/lmdb-v2';
6
+ import type { ProtocolContract } from '@aztec/protocol-contracts';
7
+ import {
8
+ AddressStore,
9
+ CapsuleStore,
10
+ NoteService,
11
+ NoteStore,
12
+ PrivateEventStore,
13
+ RecipientTaggingStore,
14
+ SenderAddressBookStore,
15
+ SenderTaggingStore,
16
+ } from '@aztec/pxe/server';
17
+ import {
18
+ ExecutionNoteCache,
19
+ ExecutionTaggingIndexCache,
20
+ HashedValuesCache,
21
+ type IPrivateExecutionOracle,
22
+ type IUtilityExecutionOracle,
23
+ Oracle,
24
+ PrivateExecutionOracle,
25
+ UtilityExecutionOracle,
26
+ } from '@aztec/pxe/simulator';
27
+ import {
28
+ ExecutionError,
29
+ WASMSimulator,
30
+ createSimulationError,
31
+ extractCallStack,
32
+ resolveAssertionMessageFromError,
33
+ toACVMWitness,
34
+ } from '@aztec/simulator/client';
35
+ import { FunctionCall, FunctionSelector, FunctionType } from '@aztec/stdlib/abi';
36
+ import type { AuthWitness } from '@aztec/stdlib/auth-witness';
37
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
38
+ import { GasSettings } from '@aztec/stdlib/gas';
39
+ import { computeProtocolNullifier } from '@aztec/stdlib/hash';
40
+ import { PrivateContextInputs } from '@aztec/stdlib/kernel';
41
+ import { makeGlobalVariables } from '@aztec/stdlib/testing';
42
+ import { CallContext, GlobalVariables, TxContext } from '@aztec/stdlib/tx';
43
+
44
+ import { z } from 'zod';
45
+
46
+ import { DEFAULT_ADDRESS, TXE_JOB_ID } from './constants.js';
47
+ import type { IAvmExecutionOracle, ITxeExecutionOracle } from './oracle/interfaces.js';
48
+ import { TXEOraclePublicContext } from './oracle/txe_oracle_public_context.js';
49
+ import { TXEOracleTopLevelContext } from './oracle/txe_oracle_top_level_context.js';
50
+ import { RPCTranslator } from './rpc_translator.js';
51
+ import { TXEStateMachine } from './state_machine/index.js';
52
+ import type { ForeignCallArgs, ForeignCallResult } from './util/encoding.js';
53
+ import { TXEAccountStore } from './util/txe_account_store.js';
54
+ import { TXEContractStore } from './util/txe_contract_store.js';
55
+ import { getSingleTxBlockRequestHash, insertTxEffectIntoWorldTrees, makeTXEBlock } from './utils/block_creation.js';
56
+ import { makeTxEffect } from './utils/tx_effect_creation.js';
57
+
58
+ /**
59
+ * A TXE Session can be in one of four states, which change as the test progresses and different oracles are called.
60
+ * The current state determines which oracles are available. Some states also have data associated with them.
61
+ */
62
+ type SessionState =
63
+ /**
64
+ * The top-level state is the default state, before any other state has been entered. This is where contracts can be
65
+ * deployed, accounts created, blocks mined, etc.
66
+ */
67
+ | {
68
+ name: 'TOP_LEVEL';
69
+ }
70
+ /**
71
+ * The private state is entered via the `private_context` function. In this state the PXE oracles that `#[external("private")]`
72
+ * functions use are available, such as those related to note retrieval, notification of side-effects, capsule access,
73
+ * etc. */
74
+ | {
75
+ name: 'PRIVATE';
76
+ nextBlockGlobalVariables: GlobalVariables;
77
+ protocolNullifier: Fr;
78
+ noteCache: ExecutionNoteCache;
79
+ taggingIndexCache: ExecutionTaggingIndexCache;
80
+ }
81
+ /**
82
+ * The public state is entered via the `public_context` function. In this state the AVM opcodes that `#[external("public")]`
83
+ * functions execute are resolved as oracles by TXE, since Noir tests are not transpiled. */
84
+ | {
85
+ name: 'PUBLIC';
86
+ }
87
+ /**
88
+ * The utility state is entered via the `utility_context` function. In this state the PXE oracles that `#[external("utility")]`
89
+ * functions use are available, such as those related to (unconstrained) note retrieval, capsule access, public
90
+ * storage reads, etc.
91
+ */
92
+ | {
93
+ name: 'UTILITY';
94
+ };
95
+
96
+ type MethodNames<T> = {
97
+ [K in keyof T]: T[K] extends (...args: any[]) => any ? K : never;
98
+ }[keyof T];
99
+
100
+ /**
101
+ * The name of an oracle function that TXE supports, which are a combination of PXE oracles, non-transpiled AVM opcodes,
102
+ * and custom TXE oracles.
103
+ */
104
+ export type TXEOracleFunctionName = Exclude<
105
+ MethodNames<RPCTranslator>,
106
+ 'constructor' | 'handlerAsMisc' | 'handlerAsUtility' | 'handlerAsPrivate' | 'handlerAsAvm' | 'handlerAsTxe'
107
+ >;
108
+
109
+ export interface TXESessionStateHandler {
110
+ enterTopLevelState(): Promise<void>;
111
+ enterPublicState(contractAddress?: AztecAddress): Promise<void>;
112
+ enterPrivateState(contractAddress?: AztecAddress, anchorBlockNumber?: BlockNumber): Promise<PrivateContextInputs>;
113
+ enterUtilityState(contractAddress?: AztecAddress): Promise<void>;
114
+ }
115
+
116
+ /**
117
+ * A `TXESession` corresponds to a Noir `#[test]` function, and handles all of its oracle calls, stores test-specific
118
+ * state, etc., independent of all other tests running in parallel.
119
+ */
120
+ export class TXESession implements TXESessionStateHandler {
121
+ private state: SessionState = { name: 'TOP_LEVEL' };
122
+ private authwits: Map<string, AuthWitness> = new Map();
123
+
124
+ constructor(
125
+ private logger: Logger,
126
+ private stateMachine: TXEStateMachine,
127
+ private oracleHandler:
128
+ | IUtilityExecutionOracle
129
+ | IPrivateExecutionOracle
130
+ | IAvmExecutionOracle
131
+ | ITxeExecutionOracle,
132
+ private contractStore: TXEContractStore,
133
+ private noteStore: NoteStore,
134
+ private keyStore: KeyStore,
135
+ private addressStore: AddressStore,
136
+ private accountStore: TXEAccountStore,
137
+ private senderTaggingStore: SenderTaggingStore,
138
+ private recipientTaggingStore: RecipientTaggingStore,
139
+ private senderAddressBookStore: SenderAddressBookStore,
140
+ private capsuleStore: CapsuleStore,
141
+ private privateEventStore: PrivateEventStore,
142
+ private chainId: Fr,
143
+ private version: Fr,
144
+ private nextBlockTimestamp: bigint,
145
+ ) {}
146
+
147
+ static async init(protocolContracts: ProtocolContract[]) {
148
+ const store = await openTmpStore('txe-session');
149
+
150
+ const addressStore = new AddressStore(store);
151
+ const privateEventStore = new PrivateEventStore(store);
152
+ const contractStore = new TXEContractStore(store);
153
+ const noteStore = await NoteStore.create(store);
154
+ const senderTaggingStore = new SenderTaggingStore(store);
155
+ const recipientTaggingStore = new RecipientTaggingStore(store);
156
+ const senderAddressBookStore = new SenderAddressBookStore(store);
157
+ const capsuleStore = new CapsuleStore(store);
158
+ const keyStore = new KeyStore(store);
159
+ const accountStore = new TXEAccountStore(store);
160
+
161
+ // Register protocol contracts.
162
+ for (const { contractClass, instance, artifact } of protocolContracts) {
163
+ await contractStore.addContractArtifact(contractClass.id, artifact);
164
+ await contractStore.addContractInstance(instance);
165
+ }
166
+
167
+ const stateMachine = await TXEStateMachine.create(store);
168
+
169
+ const nextBlockTimestamp = BigInt(Math.floor(new Date().getTime() / 1000));
170
+ const version = new Fr(await stateMachine.node.getVersion());
171
+ const chainId = new Fr(await stateMachine.node.getChainId());
172
+
173
+ const topLevelOracleHandler = new TXEOracleTopLevelContext(
174
+ stateMachine,
175
+ contractStore,
176
+ noteStore,
177
+ keyStore,
178
+ addressStore,
179
+ accountStore,
180
+ senderTaggingStore,
181
+ recipientTaggingStore,
182
+ senderAddressBookStore,
183
+ capsuleStore,
184
+ privateEventStore,
185
+ nextBlockTimestamp,
186
+ version,
187
+ chainId,
188
+ new Map(),
189
+ );
190
+ await topLevelOracleHandler.txeAdvanceBlocksBy(1);
191
+
192
+ return new TXESession(
193
+ createLogger('txe:session'),
194
+ stateMachine,
195
+ topLevelOracleHandler,
196
+ contractStore,
197
+ noteStore,
198
+ keyStore,
199
+ addressStore,
200
+ accountStore,
201
+ senderTaggingStore,
202
+ recipientTaggingStore,
203
+ senderAddressBookStore,
204
+ capsuleStore,
205
+ privateEventStore,
206
+ version,
207
+ chainId,
208
+ nextBlockTimestamp,
209
+ );
210
+ }
211
+
212
+ /**
213
+ * Processes an oracle function invoked by the Noir test associated to this session.
214
+ * @param functionName The name of the oracle.
215
+ * @param inputs The inputs of the oracle.
216
+ * @returns The oracle return values.
217
+ */
218
+ processFunction(functionName: TXEOracleFunctionName, inputs: ForeignCallArgs): Promise<ForeignCallResult> {
219
+ try {
220
+ const translator = new RPCTranslator(this, this.oracleHandler) as any;
221
+ // We perform a runtime validation to check that the function name corresponds to a real oracle handler.
222
+ const validatedFunctionName = z
223
+ .string()
224
+ .refine(fn => typeof translator[fn] === 'function' && !fn.startsWith('handlerAs') && fn !== 'constructor')
225
+ .parse(functionName) as TXEOracleFunctionName;
226
+
227
+ return translator[validatedFunctionName](...inputs);
228
+ } catch (error) {
229
+ if (error instanceof z.ZodError) {
230
+ throw new Error(`${functionName} does not correspond to any oracle handler available on RPCTranslator`);
231
+ } else if (error instanceof Error) {
232
+ throw new Error(
233
+ `Execution error while processing function ${functionName} in state ${this.state.name}: ${error.message}`,
234
+ );
235
+ } else {
236
+ throw new Error(
237
+ `Unknown execution error while processing function ${functionName} in state ${this.state.name}`,
238
+ );
239
+ }
240
+ }
241
+ }
242
+
243
+ async enterTopLevelState() {
244
+ switch (this.state.name) {
245
+ case 'PRIVATE': {
246
+ await this.exitPrivateState();
247
+ break;
248
+ }
249
+ case 'PUBLIC': {
250
+ await this.exitPublicState();
251
+ break;
252
+ }
253
+ case 'UTILITY': {
254
+ this.exitUtilityContext();
255
+ break;
256
+ }
257
+ case 'TOP_LEVEL': {
258
+ throw new Error(`Expected to be in state other than TOP_LEVEL`);
259
+ }
260
+ default: {
261
+ this.state satisfies never;
262
+ }
263
+ }
264
+
265
+ this.oracleHandler = new TXEOracleTopLevelContext(
266
+ this.stateMachine,
267
+ this.contractStore,
268
+ this.noteStore,
269
+ this.keyStore,
270
+ this.addressStore,
271
+ this.accountStore,
272
+ this.senderTaggingStore,
273
+ this.recipientTaggingStore,
274
+ this.senderAddressBookStore,
275
+ this.capsuleStore,
276
+ this.privateEventStore,
277
+ this.nextBlockTimestamp,
278
+ this.version,
279
+ this.chainId,
280
+ this.authwits,
281
+ );
282
+
283
+ this.state = { name: 'TOP_LEVEL' };
284
+ this.logger.debug(`Entered state ${this.state.name}`);
285
+ }
286
+
287
+ async enterPrivateState(
288
+ contractAddress: AztecAddress = DEFAULT_ADDRESS,
289
+ anchorBlockNumber?: BlockNumber,
290
+ ): Promise<PrivateContextInputs> {
291
+ this.exitTopLevelState();
292
+
293
+ await new NoteService(
294
+ this.noteStore,
295
+ this.stateMachine.node,
296
+ this.stateMachine.anchorBlockStore,
297
+ ).syncNoteNullifiers(contractAddress);
298
+
299
+ // Private execution has two associated block numbers: the anchor block (i.e. the historical block that is used to
300
+ // build the proof), and the *next* block, i.e. the one we'll create once the execution ends, and which will contain
301
+ // a single transaction with the effects of what was done in the test.
302
+ const anchorBlock = await this.stateMachine.node.getBlockHeader(anchorBlockNumber ?? 'latest');
303
+ const latestBlock = await this.stateMachine.node.getBlockHeader('latest');
304
+
305
+ const nextBlockGlobalVariables = makeGlobalVariables(undefined, {
306
+ blockNumber: BlockNumber(latestBlock!.globalVariables.blockNumber + 1),
307
+ timestamp: this.nextBlockTimestamp,
308
+ version: this.version,
309
+ chainId: this.chainId,
310
+ });
311
+
312
+ const txRequestHash = getSingleTxBlockRequestHash(nextBlockGlobalVariables.blockNumber);
313
+ const protocolNullifier = await computeProtocolNullifier(txRequestHash);
314
+ const noteCache = new ExecutionNoteCache(protocolNullifier);
315
+ const taggingIndexCache = new ExecutionTaggingIndexCache();
316
+
317
+ const utilityExecutor = this.utilityExecutorForContractSync(anchorBlock);
318
+ this.oracleHandler = new PrivateExecutionOracle(
319
+ Fr.ZERO,
320
+ new TxContext(this.chainId, this.version, GasSettings.empty()),
321
+ new CallContext(AztecAddress.ZERO, contractAddress, FunctionSelector.empty(), false),
322
+ anchorBlock!,
323
+ utilityExecutor,
324
+ [],
325
+ [],
326
+ new HashedValuesCache(),
327
+ noteCache,
328
+ taggingIndexCache,
329
+ this.contractStore,
330
+ this.noteStore,
331
+ this.keyStore,
332
+ this.addressStore,
333
+ this.stateMachine.node,
334
+ this.stateMachine.anchorBlockStore,
335
+ this.senderTaggingStore,
336
+ this.recipientTaggingStore,
337
+ this.senderAddressBookStore,
338
+ this.capsuleStore,
339
+ this.privateEventStore,
340
+ TXE_JOB_ID,
341
+ );
342
+
343
+ // We store the note and tagging index caches fed into the PrivateExecutionOracle (along with some other auxiliary
344
+ // data) in order to refer to it later, mimicking the way this object is used by the ContractFunctionSimulator. The
345
+ // difference resides in that the simulator has all information needed in order to run the simulation, while ours
346
+ // will be ongoing as the different oracles will be invoked from the Noir test, until eventually the private
347
+ // execution finishes.
348
+ this.state = { name: 'PRIVATE', nextBlockGlobalVariables, protocolNullifier, noteCache, taggingIndexCache };
349
+ this.logger.debug(`Entered state ${this.state.name}`);
350
+
351
+ return (this.oracleHandler as PrivateExecutionOracle).getPrivateContextInputs();
352
+ }
353
+
354
+ async enterPublicState(contractAddress?: AztecAddress) {
355
+ this.exitTopLevelState();
356
+
357
+ // The PublicContext will create a block with a single transaction in it, containing the effects of what was done in
358
+ // the test. The block therefore gets the *next* block number and timestamp.
359
+ const latestBlockNumber = (await this.stateMachine.node.getBlockHeader('latest'))!.globalVariables.blockNumber;
360
+ const globalVariables = makeGlobalVariables(undefined, {
361
+ blockNumber: BlockNumber(latestBlockNumber + 1),
362
+ timestamp: this.nextBlockTimestamp,
363
+ version: this.version,
364
+ chainId: this.chainId,
365
+ });
366
+
367
+ this.oracleHandler = new TXEOraclePublicContext(
368
+ contractAddress ?? DEFAULT_ADDRESS,
369
+ await this.stateMachine.synchronizer.nativeWorldStateService.fork(),
370
+ getSingleTxBlockRequestHash(globalVariables.blockNumber),
371
+ globalVariables,
372
+ );
373
+
374
+ this.state = { name: 'PUBLIC' };
375
+ this.logger.debug(`Entered state ${this.state.name}`);
376
+ }
377
+
378
+ async enterUtilityState(contractAddress: AztecAddress = DEFAULT_ADDRESS) {
379
+ this.exitTopLevelState();
380
+
381
+ // There is no automatic message discovery and contract-driven syncing process in inlined private or utility
382
+ // contexts, which means that known nullifiers are also not searched for, since it is during the tagging sync that
383
+ // we perform this. We therefore search for known nullifiers now, as otherwise notes that were nullified would not
384
+ // be removed from the database.
385
+ // TODO(#12553): make the synchronizer sync here instead and remove this
386
+ await new NoteService(
387
+ this.noteStore,
388
+ this.stateMachine.node,
389
+ this.stateMachine.anchorBlockStore,
390
+ ).syncNoteNullifiers(contractAddress);
391
+
392
+ const anchorBlockHeader = await this.stateMachine.anchorBlockStore.getBlockHeader();
393
+
394
+ this.oracleHandler = new UtilityExecutionOracle(
395
+ contractAddress,
396
+ [],
397
+ [],
398
+ anchorBlockHeader,
399
+ this.contractStore,
400
+ this.noteStore,
401
+ this.keyStore,
402
+ this.addressStore,
403
+ this.stateMachine.node,
404
+ this.stateMachine.anchorBlockStore,
405
+ this.recipientTaggingStore,
406
+ this.senderAddressBookStore,
407
+ this.capsuleStore,
408
+ this.privateEventStore,
409
+ TXE_JOB_ID,
410
+ );
411
+
412
+ this.state = { name: 'UTILITY' };
413
+ this.logger.debug(`Entered state ${this.state.name}`);
414
+ }
415
+
416
+ private exitTopLevelState() {
417
+ if (this.state.name != 'TOP_LEVEL') {
418
+ throw new Error(`Expected to be in state 'TOP_LEVEL', but got '${this.state.name}' instead`);
419
+ }
420
+
421
+ // Note that while all public and private contexts do is build a single block that we then process when exiting
422
+ // those, the top level context performs a large number of actions not captured in the following 'close' call. Among
423
+ // others, it will create empty blocks (via `txeAdvanceBlocksBy` and `deploy`), create blocks with transactions via
424
+ // `txePrivateCallNewFlow` and `txePublicCallNewFlow`, add accounts to PXE via `txeAddAccount`, etc. This is a
425
+ // slight inconsistency in the working model of this class, but is not too bad.
426
+ // TODO: it's quite unfortunate that we need to capture the authwits created to later pass them again when the top
427
+ // level context is re-created. This is because authwits create a temporary utility context that'd otherwise reset
428
+ // the authwits if not persisted, so we'd not be able to pass more than one per execution.
429
+ // Ideally authwits would be passed alongside a contract call instead of pre-seeded.
430
+ [this.nextBlockTimestamp, this.authwits] = (this.oracleHandler as TXEOracleTopLevelContext).close();
431
+ }
432
+
433
+ private async exitPrivateState() {
434
+ if (this.state.name != 'PRIVATE') {
435
+ throw new Error(`Expected to be in state 'PRIVATE', but got '${this.state.name}' instead`);
436
+ }
437
+
438
+ this.logger.debug('Exiting Private state, building block with collected side effects', {
439
+ blockNumber: this.state.nextBlockGlobalVariables.blockNumber,
440
+ });
441
+
442
+ // We rely on the note cache to determine the effects of the transaction. This is incomplete as it doesn't private
443
+ // logs (other effects like enqueued public calls don't need to be considered since those are not allowed).
444
+
445
+ const txEffect = await makeTxEffect(
446
+ this.state.noteCache,
447
+ this.state.protocolNullifier,
448
+ this.state.nextBlockGlobalVariables.blockNumber,
449
+ );
450
+
451
+ // We build a block holding just this transaction
452
+ const forkedWorldTrees = await this.stateMachine.synchronizer.nativeWorldStateService.fork();
453
+ await insertTxEffectIntoWorldTrees(txEffect, forkedWorldTrees);
454
+
455
+ const block = await makeTXEBlock(forkedWorldTrees, this.state.nextBlockGlobalVariables, [txEffect]);
456
+ await this.stateMachine.handleL2Block(block);
457
+
458
+ await forkedWorldTrees.close();
459
+
460
+ this.logger.debug('Exited PublicContext with built block', {
461
+ blockNumber: block.number,
462
+ txEffects: block.body.txEffects,
463
+ });
464
+ }
465
+
466
+ private async exitPublicState() {
467
+ if (this.state.name != 'PUBLIC') {
468
+ throw new Error(`Expected to be in state 'PUBLIC', but got '${this.state.name}' instead`);
469
+ }
470
+
471
+ const block = await (this.oracleHandler as TXEOraclePublicContext).close();
472
+ await this.stateMachine.handleL2Block(block);
473
+ }
474
+
475
+ private exitUtilityContext() {
476
+ if (this.state.name != 'UTILITY') {
477
+ throw new Error(`Expected to be in state 'UTILITY', but got '${this.state.name}' instead`);
478
+ }
479
+ }
480
+
481
+ private utilityExecutorForContractSync(anchorBlock: any) {
482
+ return async (call: FunctionCall) => {
483
+ const entryPointArtifact = await this.contractStore.getFunctionArtifactWithDebugMetadata(call.to, call.selector);
484
+ if (entryPointArtifact.functionType !== FunctionType.UTILITY) {
485
+ throw new Error(`Cannot run ${entryPointArtifact.functionType} function as utility`);
486
+ }
487
+
488
+ try {
489
+ const oracle = new UtilityExecutionOracle(
490
+ call.to,
491
+ [],
492
+ [],
493
+ anchorBlock!,
494
+ this.contractStore,
495
+ this.noteStore,
496
+ this.keyStore,
497
+ this.addressStore,
498
+ this.stateMachine.node,
499
+ this.stateMachine.anchorBlockStore,
500
+ this.recipientTaggingStore,
501
+ this.senderAddressBookStore,
502
+ this.capsuleStore,
503
+ this.privateEventStore,
504
+ TXE_JOB_ID,
505
+ );
506
+ await new WASMSimulator()
507
+ .executeUserCircuit(toACVMWitness(0, call.args), entryPointArtifact, new Oracle(oracle).toACIRCallback())
508
+ .catch((err: Error) => {
509
+ err.message = resolveAssertionMessageFromError(err, entryPointArtifact);
510
+ throw new ExecutionError(
511
+ err.message,
512
+ {
513
+ contractAddress: call.to,
514
+ functionSelector: call.selector,
515
+ },
516
+ extractCallStack(err, entryPointArtifact.debug),
517
+ { cause: err },
518
+ );
519
+ });
520
+ } catch (err) {
521
+ throw createSimulationError(err instanceof Error ? err : new Error('Unknown error contract data sync'));
522
+ }
523
+ };
524
+ }
525
+ }