@aztec/txe 4.0.0-nightly.20250907 → 4.0.0-nightly.20260107

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 +1 -1
  3. package/dest/constants.d.ts +3 -0
  4. package/dest/constants.d.ts.map +1 -0
  5. package/dest/constants.js +2 -0
  6. package/dest/index.d.ts +1 -1
  7. package/dest/index.d.ts.map +1 -1
  8. package/dest/index.js +8 -4
  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 +12 -12
  13. package/dest/oracle/txe_oracle_public_context.d.ts.map +1 -1
  14. package/dest/oracle/txe_oracle_public_context.js +30 -34
  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/{txe_service/txe_service.js → rpc_translator.js} +201 -124
  21. package/dest/state_machine/archiver.d.ts +34 -13
  22. package/dest/state_machine/archiver.d.ts.map +1 -1
  23. package/dest/state_machine/archiver.js +111 -16
  24. package/dest/state_machine/dummy_p2p_client.d.ts +5 -2
  25. package/dest/state_machine/dummy_p2p_client.d.ts.map +1 -1
  26. package/dest/state_machine/dummy_p2p_client.js +9 -1
  27. package/dest/state_machine/global_variable_builder.d.ts +5 -16
  28. package/dest/state_machine/global_variable_builder.d.ts.map +1 -1
  29. package/dest/state_machine/global_variable_builder.js +15 -22
  30. package/dest/state_machine/index.d.ts +5 -5
  31. package/dest/state_machine/index.d.ts.map +1 -1
  32. package/dest/state_machine/index.js +17 -21
  33. package/dest/state_machine/mock_epoch_cache.d.ts +6 -5
  34. package/dest/state_machine/mock_epoch_cache.d.ts.map +1 -1
  35. package/dest/state_machine/mock_epoch_cache.js +8 -7
  36. package/dest/state_machine/synchronizer.d.ts +5 -4
  37. package/dest/state_machine/synchronizer.d.ts.map +1 -1
  38. package/dest/state_machine/synchronizer.js +5 -4
  39. package/dest/txe_session.d.ts +42 -46
  40. package/dest/txe_session.d.ts.map +1 -1
  41. package/dest/txe_session.js +241 -93
  42. package/dest/util/encoding.d.ts +623 -24
  43. package/dest/util/encoding.d.ts.map +1 -1
  44. package/dest/util/encoding.js +1 -1
  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_data_provider.js → txe_contract_store.js} +4 -4
  53. package/dest/util/txe_public_contract_data_source.d.ts +8 -6
  54. package/dest/util/txe_public_contract_data_source.d.ts.map +1 -1
  55. package/dest/util/txe_public_contract_data_source.js +14 -12
  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 +45 -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 +18 -17
  63. package/src/bin/index.ts +1 -1
  64. package/src/constants.ts +3 -0
  65. package/src/index.ts +20 -20
  66. package/src/oracle/interfaces.ts +86 -0
  67. package/src/oracle/txe_oracle_public_context.ts +37 -75
  68. package/src/oracle/txe_oracle_top_level_context.ts +716 -0
  69. package/src/{txe_service/txe_service.ts → rpc_translator.ts} +261 -125
  70. package/src/state_machine/archiver.ts +147 -29
  71. package/src/state_machine/dummy_p2p_client.ts +13 -2
  72. package/src/state_machine/global_variable_builder.ts +24 -41
  73. package/src/state_machine/index.ts +24 -21
  74. package/src/state_machine/mock_epoch_cache.ts +12 -11
  75. package/src/state_machine/synchronizer.ts +8 -7
  76. package/src/txe_session.ts +416 -115
  77. package/src/util/encoding.ts +1 -1
  78. package/src/util/{txe_account_data_provider.ts → txe_account_store.ts} +1 -1
  79. package/src/util/{txe_contract_data_provider.ts → txe_contract_store.ts} +5 -4
  80. package/src/util/txe_public_contract_data_source.ts +16 -13
  81. package/src/utils/block_creation.ts +94 -0
  82. package/src/utils/tx_effect_creation.ts +38 -0
  83. package/dest/oracle/txe_oracle.d.ts +0 -124
  84. package/dest/oracle/txe_oracle.d.ts.map +0 -1
  85. package/dest/oracle/txe_oracle.js +0 -770
  86. package/dest/oracle/txe_typed_oracle.d.ts +0 -42
  87. package/dest/oracle/txe_typed_oracle.d.ts.map +0 -1
  88. package/dest/oracle/txe_typed_oracle.js +0 -83
  89. package/dest/txe_constants.d.ts +0 -2
  90. package/dest/txe_constants.d.ts.map +0 -1
  91. package/dest/txe_constants.js +0 -7
  92. package/dest/txe_service/txe_service.d.ts +0 -231
  93. package/dest/txe_service/txe_service.d.ts.map +0 -1
  94. package/dest/util/txe_account_data_provider.d.ts +0 -10
  95. package/dest/util/txe_account_data_provider.d.ts.map +0 -1
  96. package/dest/util/txe_contract_data_provider.d.ts +0 -11
  97. package/dest/util/txe_contract_data_provider.d.ts.map +0 -1
  98. package/src/oracle/txe_oracle.ts +0 -1287
  99. package/src/oracle/txe_typed_oracle.ts +0 -142
  100. package/src/txe_constants.ts +0 -9
@@ -1,54 +1,97 @@
1
- import { AztecAddress, Fr } from '@aztec/aztec.js';
1
+ import { BlockNumber } from '@aztec/foundation/branded-types';
2
+ import { Fr } from '@aztec/foundation/curves/bn254';
2
3
  import { type Logger, createLogger } from '@aztec/foundation/log';
3
4
  import { KeyStore } from '@aztec/key-store';
4
5
  import { openTmpStore } from '@aztec/kv-store/lmdb-v2';
5
6
  import type { ProtocolContract } from '@aztec/protocol-contracts';
6
7
  import {
7
- AddressDataProvider,
8
- CapsuleDataProvider,
9
- NoteDataProvider,
10
- PrivateEventDataProvider,
11
- TaggingDataProvider,
8
+ AddressStore,
9
+ CapsuleStore,
10
+ NoteService,
11
+ NoteStore,
12
+ PrivateEventStore,
13
+ RecipientTaggingStore,
14
+ SenderAddressBookStore,
15
+ SenderTaggingStore,
12
16
  } from '@aztec/pxe/server';
13
- import type { PrivateContextInputs } from '@aztec/stdlib/kernel';
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';
14
41
  import { makeGlobalVariables } from '@aztec/stdlib/testing';
15
- import type { UInt32 } from '@aztec/stdlib/types';
42
+ import { CallContext, GlobalVariables, TxContext } from '@aztec/stdlib/tx';
43
+
44
+ import { z } from 'zod';
16
45
 
17
- import { TXE } from './oracle/txe_oracle.js';
46
+ import { DEFAULT_ADDRESS } from './constants.js';
47
+ import type { IAvmExecutionOracle, ITxeExecutionOracle } from './oracle/interfaces.js';
18
48
  import { TXEOraclePublicContext } from './oracle/txe_oracle_public_context.js';
19
- import type { TXETypedOracle } from './oracle/txe_typed_oracle.js';
49
+ import { TXEOracleTopLevelContext } from './oracle/txe_oracle_top_level_context.js';
50
+ import { RPCTranslator } from './rpc_translator.js';
20
51
  import { TXEStateMachine } from './state_machine/index.js';
21
- import { TXEService } from './txe_service/txe_service.js';
22
52
  import type { ForeignCallArgs, ForeignCallResult } from './util/encoding.js';
23
- import { TXEAccountDataProvider } from './util/txe_account_data_provider.js';
24
- import { TXEContractDataProvider } from './util/txe_contract_data_provider.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';
25
57
 
26
58
  /**
27
- * A TXE Session can be ine one of four states, which change as the test progresses and different oracles are called.
28
- * The current state determines which oracles are available.
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.
29
61
  */
30
- enum SessionState {
62
+ type SessionState =
31
63
  /**
32
64
  * The top-level state is the default state, before any other state has been entered. This is where contracts can be
33
65
  * deployed, accounts created, blocks mined, etc.
34
66
  */
35
- TOP_LEVEL,
67
+ | {
68
+ name: 'TOP_LEVEL';
69
+ }
36
70
  /**
37
- * The private state is entered via the `private_context` function. In this state the PXE oracles that `#[private]`
71
+ * The private state is entered via the `private_context` function. In this state the PXE oracles that `#[external("private")]`
38
72
  * functions use are available, such as those related to note retrieval, notification of side-effects, capsule access,
39
73
  * etc. */
40
- PRIVATE,
74
+ | {
75
+ name: 'PRIVATE';
76
+ nextBlockGlobalVariables: GlobalVariables;
77
+ protocolNullifier: Fr;
78
+ noteCache: ExecutionNoteCache;
79
+ taggingIndexCache: ExecutionTaggingIndexCache;
80
+ }
41
81
  /**
42
- * The public state is entered via the `public_context` function. In this state the AVM opcodes that `#[public]`
82
+ * The public state is entered via the `public_context` function. In this state the AVM opcodes that `#[external("public")]`
43
83
  * functions execute are resolved as oracles by TXE, since Noir tests are not transpiled. */
44
- PUBLIC,
84
+ | {
85
+ name: 'PUBLIC';
86
+ }
45
87
  /**
46
- * The utility state is entered via the `utility_context` function. In this state the PXE oracles that `#[utility]`
88
+ * The utility state is entered via the `utility_context` function. In this state the PXE oracles that `#[external("utility")]`
47
89
  * functions use are available, such as those related to (unconstrained) note retrieval, capsule access, public
48
90
  * storage reads, etc.
49
91
  */
50
- UTILITY,
51
- }
92
+ | {
93
+ name: 'UTILITY';
94
+ };
52
95
 
53
96
  type MethodNames<T> = {
54
97
  [K in keyof T]: T[K] extends (...args: any[]) => any ? K : never;
@@ -58,67 +101,112 @@ type MethodNames<T> = {
58
101
  * The name of an oracle function that TXE supports, which are a combination of PXE oracles, non-transpiled AVM opcodes,
59
102
  * and custom TXE oracles.
60
103
  */
61
- export type TXEOracleFunctionName = MethodNames<TXEService>;
104
+ export type TXEOracleFunctionName = Exclude<
105
+ MethodNames<RPCTranslator>,
106
+ 'constructor' | 'handlerAsMisc' | 'handlerAsUtility' | 'handlerAsPrivate' | 'handlerAsAvm' | 'handlerAsTxe'
107
+ >;
62
108
 
63
109
  export interface TXESessionStateHandler {
64
- setTopLevelContext(): Promise<void>;
65
- setPublicContext(contractAddress?: AztecAddress): Promise<void>;
66
- setPrivateContext(contractAddress?: AztecAddress, historicalBlockNumber?: UInt32): Promise<PrivateContextInputs>;
67
- setUtilityContext(contractAddress?: AztecAddress): Promise<void>;
110
+ enterTopLevelState(): Promise<void>;
111
+ enterPublicState(contractAddress?: AztecAddress): Promise<void>;
112
+ enterPrivateState(contractAddress?: AztecAddress, anchorBlockNumber?: BlockNumber): Promise<PrivateContextInputs>;
113
+ enterUtilityState(contractAddress?: AztecAddress): Promise<void>;
68
114
  }
69
115
 
70
- const DEFAULT_ADDRESS = AztecAddress.fromNumber(42);
71
-
72
116
  /**
73
117
  * A `TXESession` corresponds to a Noir `#[test]` function, and handles all of its oracle calls, stores test-specific
74
118
  * state, etc., independent of all other tests running in parallel.
75
119
  */
76
120
  export class TXESession implements TXESessionStateHandler {
77
- state = SessionState.TOP_LEVEL;
121
+ private state: SessionState = { name: 'TOP_LEVEL' };
122
+ private authwits: Map<string, AuthWitness> = new Map();
78
123
 
79
124
  constructor(
80
125
  private logger: Logger,
81
126
  private stateMachine: TXEStateMachine,
82
- private oracleHandler: TXETypedOracle,
83
- private legacyTXEOracle: TXE,
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,
84
145
  ) {}
85
146
 
86
147
  static async init(protocolContracts: ProtocolContract[]) {
87
148
  const store = await openTmpStore('txe-session');
88
149
 
89
- const addressDataProvider = new AddressDataProvider(store);
90
- const privateEventDataProvider = new PrivateEventDataProvider(store);
91
- const contractDataProvider = new TXEContractDataProvider(store);
92
- const noteDataProvider = await NoteDataProvider.create(store);
93
- const taggingDataProvider = new TaggingDataProvider(store);
94
- const capsuleDataProvider = new CapsuleDataProvider(store);
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);
95
158
  const keyStore = new KeyStore(store);
96
- const accountDataProvider = new TXEAccountDataProvider(store);
159
+ const accountStore = new TXEAccountStore(store);
97
160
 
98
161
  // Register protocol contracts.
99
162
  for (const { contractClass, instance, artifact } of protocolContracts) {
100
- await contractDataProvider.addContractArtifact(contractClass.id, artifact);
101
- await contractDataProvider.addContractInstance(instance);
163
+ await contractStore.addContractArtifact(contractClass.id, artifact);
164
+ await contractStore.addContractInstance(instance);
102
165
  }
103
166
 
104
167
  const stateMachine = await TXEStateMachine.create(store);
105
168
 
106
- const txeOracle = new TXE(
107
- keyStore,
108
- contractDataProvider,
109
- noteDataProvider,
110
- capsuleDataProvider,
111
- taggingDataProvider,
112
- addressDataProvider,
113
- privateEventDataProvider,
114
- accountDataProvider,
115
- DEFAULT_ADDRESS,
116
- await stateMachine.synchronizer.nativeWorldStateService.fork(),
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(
117
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(),
118
189
  );
119
- await txeOracle.txeAdvanceBlocksBy(1);
190
+ await topLevelOracleHandler.txeAdvanceBlocksBy(1);
120
191
 
121
- return new TXESession(createLogger('txe:session'), stateMachine, txeOracle, txeOracle);
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
+ );
122
210
  }
123
211
 
124
212
  /**
@@ -128,94 +216,307 @@ export class TXESession implements TXESessionStateHandler {
128
216
  * @returns The oracle return values.
129
217
  */
130
218
  processFunction(functionName: TXEOracleFunctionName, inputs: ForeignCallArgs): Promise<ForeignCallResult> {
131
- return (new TXEService(this, this.oracleHandler) as any)[functionName](...inputs);
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
+ }
132
241
  }
133
242
 
134
- async setTopLevelContext(): Promise<void> {
135
- if (this.state == SessionState.PRIVATE) {
136
- await this.oracleHandler.txeAdvanceBlocksBy(1);
137
- this.oracleHandler.txeSetContractAddress(DEFAULT_ADDRESS);
138
- } else if (this.state == SessionState.PUBLIC) {
139
- const block = await (this.oracleHandler as TXEOraclePublicContext).close();
140
-
141
- await this.stateMachine.handleL2Block(block);
142
-
143
- this.legacyTXEOracle.baseFork = await this.stateMachine.synchronizer.nativeWorldStateService.fork();
144
- this.legacyTXEOracle.txeSetContractAddress(DEFAULT_ADDRESS);
145
- this.legacyTXEOracle.setBlockNumber(block.number + 1);
146
-
147
- this.oracleHandler = this.legacyTXEOracle;
148
- } else if (this.state == SessionState.UTILITY) {
149
- this.oracleHandler.txeSetContractAddress(DEFAULT_ADDRESS);
150
- } else if (this.state == SessionState.TOP_LEVEL) {
151
- throw new Error(`Expected to be in state other than ${SessionState[SessionState.TOP_LEVEL]}`);
152
- } else {
153
- throw new Error(`Unexpected state '${this.state}'`);
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
+ }
154
263
  }
155
264
 
156
- this.state = SessionState.TOP_LEVEL;
157
- this.logger.debug(`Entered state ${SessionState[this.state]}`);
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}`);
158
285
  }
159
286
 
160
- async setPublicContext(contractAddress?: AztecAddress): Promise<void> {
161
- this.assertInTopLevelState();
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
+ );
162
341
 
342
+ // We store the note and tagging index caches fed into the PrivateExecutionOracle (along with some other auxiliary
343
+ // data) in order to refer to it later, mimicking the way this object is used by the ContractFunctionSimulator. The
344
+ // difference resides in that the simulator has all information needed in order to run the simulation, while ours
345
+ // will be ongoing as the different oracles will be invoked from the Noir test, until eventually the private
346
+ // execution finishes.
347
+ this.state = { name: 'PRIVATE', nextBlockGlobalVariables, protocolNullifier, noteCache, taggingIndexCache };
348
+ this.logger.debug(`Entered state ${this.state.name}`);
349
+
350
+ return (this.oracleHandler as PrivateExecutionOracle).getPrivateContextInputs();
351
+ }
352
+
353
+ async enterPublicState(contractAddress?: AztecAddress) {
354
+ this.exitTopLevelState();
355
+
356
+ // The PublicContext will create a block with a single transaction in it, containing the effects of what was done in
357
+ // the test. The block therefore gets the *next* block number and timestamp.
358
+ const latestBlockNumber = (await this.stateMachine.node.getBlockHeader('latest'))!.globalVariables.blockNumber;
163
359
  const globalVariables = makeGlobalVariables(undefined, {
164
- blockNumber: await this.legacyTXEOracle.utilityGetBlockNumber(),
165
- timestamp: await this.legacyTXEOracle.utilityGetTimestamp(),
166
- version: await this.legacyTXEOracle.utilityGetVersion(),
167
- chainId: await this.legacyTXEOracle.utilityGetChainId(),
360
+ blockNumber: BlockNumber(latestBlockNumber + 1),
361
+ timestamp: this.nextBlockTimestamp,
362
+ version: this.version,
363
+ chainId: this.chainId,
168
364
  });
169
365
 
170
- const txRequestHash = new Fr(globalVariables.blockNumber + 6969);
171
-
172
366
  this.oracleHandler = new TXEOraclePublicContext(
173
367
  contractAddress ?? DEFAULT_ADDRESS,
174
368
  await this.stateMachine.synchronizer.nativeWorldStateService.fork(),
175
- txRequestHash,
369
+ getSingleTxBlockRequestHash(globalVariables.blockNumber),
176
370
  globalVariables,
177
371
  );
178
372
 
179
- this.state = SessionState.PUBLIC;
180
- this.logger.debug(`Entered state ${SessionState[this.state]}`);
373
+ this.state = { name: 'PUBLIC' };
374
+ this.logger.debug(`Entered state ${this.state.name}`);
181
375
  }
182
376
 
183
- async setPrivateContext(
184
- contractAddress?: AztecAddress,
185
- historicalBlockNumber?: UInt32,
186
- ): Promise<PrivateContextInputs> {
187
- this.assertInTopLevelState();
377
+ async enterUtilityState(contractAddress: AztecAddress = DEFAULT_ADDRESS) {
378
+ this.exitTopLevelState();
379
+
380
+ // There is no automatic message discovery and contract-driven syncing process in inlined private or utility
381
+ // contexts, which means that known nullifiers are also not searched for, since it is during the tagging sync that
382
+ // we perform this. We therefore search for known nullifiers now, as otherwise notes that were nullified would not
383
+ // be removed from the database.
384
+ // TODO(#12553): make the synchronizer sync here instead and remove this
385
+ await new NoteService(
386
+ this.noteStore,
387
+ this.stateMachine.node,
388
+ this.stateMachine.anchorBlockStore,
389
+ ).syncNoteNullifiers(contractAddress);
390
+
391
+ const anchorBlockHeader = await this.stateMachine.anchorBlockStore.getBlockHeader();
392
+
393
+ this.oracleHandler = new UtilityExecutionOracle(
394
+ contractAddress,
395
+ [],
396
+ [],
397
+ anchorBlockHeader,
398
+ this.contractStore,
399
+ this.noteStore,
400
+ this.keyStore,
401
+ this.addressStore,
402
+ this.stateMachine.node,
403
+ this.stateMachine.anchorBlockStore,
404
+ this.recipientTaggingStore,
405
+ this.senderAddressBookStore,
406
+ this.capsuleStore,
407
+ this.privateEventStore,
408
+ );
188
409
 
189
- if (contractAddress) {
190
- this.oracleHandler.txeSetContractAddress(contractAddress);
410
+ this.state = { name: 'UTILITY' };
411
+ this.logger.debug(`Entered state ${this.state.name}`);
412
+ }
413
+
414
+ private exitTopLevelState() {
415
+ if (this.state.name != 'TOP_LEVEL') {
416
+ throw new Error(`Expected to be in state 'TOP_LEVEL', but got '${this.state.name}' instead`);
191
417
  }
192
418
 
193
- const privateContextInputs = await this.oracleHandler.txeGetPrivateContextInputs(historicalBlockNumber);
419
+ // Note that while all public and private contexts do is build a single block that we then process when exiting
420
+ // those, the top level context performs a large number of actions not captured in the following 'close' call. Among
421
+ // others, it will create empty blocks (via `txeAdvanceBlocksBy` and `deploy`), create blocks with transactions via
422
+ // `txePrivateCallNewFlow` and `txePublicCallNewFlow`, add accounts to PXE via `txeAddAccount`, etc. This is a
423
+ // slight inconsistency in the working model of this class, but is not too bad.
424
+ // TODO: it's quite unfortunate that we need to capture the authwits created to later pass them again when the top
425
+ // level context is re-created. This is because authwits create a temporary utility context that'd otherwise reset
426
+ // the authwits if not persisted, so we'd not be able to pass more than one per execution.
427
+ // Ideally authwits would be passed alongside a contract call instead of pre-seeded.
428
+ [this.nextBlockTimestamp, this.authwits] = (this.oracleHandler as TXEOracleTopLevelContext).close();
429
+ }
194
430
 
195
- this.state = SessionState.PRIVATE;
196
- this.logger.debug(`Entered state ${SessionState[this.state]}`);
431
+ private async exitPrivateState() {
432
+ if (this.state.name != 'PRIVATE') {
433
+ throw new Error(`Expected to be in state 'PRIVATE', but got '${this.state.name}' instead`);
434
+ }
197
435
 
198
- return privateContextInputs;
199
- }
436
+ this.logger.debug('Exiting Private state, building block with collected side effects', {
437
+ blockNumber: this.state.nextBlockGlobalVariables.blockNumber,
438
+ });
200
439
 
201
- setUtilityContext(contractAddress?: AztecAddress): Promise<void> {
202
- this.assertInTopLevelState();
440
+ // We rely on the note cache to determine the effects of the transaction. This is incomplete as it doesn't private
441
+ // logs (other effects like enqueued public calls don't need to be considered since those are not allowed).
203
442
 
204
- if (contractAddress) {
205
- this.oracleHandler.txeSetContractAddress(contractAddress);
206
- }
443
+ const txEffect = await makeTxEffect(
444
+ this.state.noteCache,
445
+ this.state.protocolNullifier,
446
+ this.state.nextBlockGlobalVariables.blockNumber,
447
+ );
448
+
449
+ // We build a block holding just this transaction
450
+ const forkedWorldTrees = await this.stateMachine.synchronizer.nativeWorldStateService.fork();
451
+ await insertTxEffectIntoWorldTrees(txEffect, forkedWorldTrees);
207
452
 
208
- this.state = SessionState.UTILITY;
209
- this.logger.debug(`Entered state ${SessionState[this.state]}`);
453
+ const block = await makeTXEBlock(forkedWorldTrees, this.state.nextBlockGlobalVariables, [txEffect]);
454
+ await this.stateMachine.handleL2Block(block);
210
455
 
211
- return Promise.resolve();
456
+ await forkedWorldTrees.close();
457
+
458
+ this.logger.debug('Exited PublicContext with built block', {
459
+ blockNumber: block.number,
460
+ txEffects: block.body.txEffects,
461
+ });
212
462
  }
213
463
 
214
- private assertInTopLevelState() {
215
- if (this.state != SessionState.TOP_LEVEL) {
216
- throw new Error(
217
- `Expected to be in state ${SessionState[SessionState.TOP_LEVEL]}, but got '${SessionState[this.state]}' instead`,
218
- );
464
+ private async exitPublicState() {
465
+ if (this.state.name != 'PUBLIC') {
466
+ throw new Error(`Expected to be in state 'PUBLIC', but got '${this.state.name}' instead`);
219
467
  }
468
+
469
+ const block = await (this.oracleHandler as TXEOraclePublicContext).close();
470
+ await this.stateMachine.handleL2Block(block);
471
+ }
472
+
473
+ private exitUtilityContext() {
474
+ if (this.state.name != 'UTILITY') {
475
+ throw new Error(`Expected to be in state 'UTILITY', but got '${this.state.name}' instead`);
476
+ }
477
+ }
478
+
479
+ private utilityExecutorForContractSync(anchorBlock: any) {
480
+ return async (call: FunctionCall) => {
481
+ const entryPointArtifact = await this.contractStore.getFunctionArtifactWithDebugMetadata(call.to, call.selector);
482
+ if (entryPointArtifact.functionType !== FunctionType.UTILITY) {
483
+ throw new Error(`Cannot run ${entryPointArtifact.functionType} function as utility`);
484
+ }
485
+
486
+ try {
487
+ const oracle = new UtilityExecutionOracle(
488
+ call.to,
489
+ [],
490
+ [],
491
+ anchorBlock!,
492
+ this.contractStore,
493
+ this.noteStore,
494
+ this.keyStore,
495
+ this.addressStore,
496
+ this.stateMachine.node,
497
+ this.stateMachine.anchorBlockStore,
498
+ this.recipientTaggingStore,
499
+ this.senderAddressBookStore,
500
+ this.capsuleStore,
501
+ this.privateEventStore,
502
+ );
503
+ await new WASMSimulator()
504
+ .executeUserCircuit(toACVMWitness(0, call.args), entryPointArtifact, new Oracle(oracle).toACIRCallback())
505
+ .catch((err: Error) => {
506
+ err.message = resolveAssertionMessageFromError(err, entryPointArtifact);
507
+ throw new ExecutionError(
508
+ err.message,
509
+ {
510
+ contractAddress: call.to,
511
+ functionSelector: call.selector,
512
+ },
513
+ extractCallStack(err, entryPointArtifact.debug),
514
+ { cause: err },
515
+ );
516
+ });
517
+ } catch (err) {
518
+ throw createSimulationError(err instanceof Error ? err : new Error('Unknown error contract data sync'));
519
+ }
520
+ };
220
521
  }
221
522
  }
@@ -1,5 +1,5 @@
1
+ import { Fr } from '@aztec/foundation/curves/bn254';
1
2
  import type { EthAddress } from '@aztec/foundation/eth-address';
2
- import { Fr } from '@aztec/foundation/fields';
3
3
  import { hexToBuffer } from '@aztec/foundation/string';
4
4
  import { type ContractArtifact, ContractArtifactSchema } from '@aztec/stdlib/abi';
5
5
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
@@ -2,7 +2,7 @@ import type { AztecAsyncKVStore, AztecAsyncMap } from '@aztec/kv-store';
2
2
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
3
3
  import { CompleteAddress } from '@aztec/stdlib/contract';
4
4
 
5
- export class TXEAccountDataProvider {
5
+ export class TXEAccountStore {
6
6
  #accounts: AztecAsyncMap<string, Buffer>;
7
7
 
8
8
  constructor(store: AztecAsyncKVStore) {
@@ -1,14 +1,15 @@
1
- import { type ContractArtifact, Fr } from '@aztec/aztec.js';
2
- import { ContractDataProvider } from '@aztec/pxe/server';
1
+ import type { ContractArtifact } from '@aztec/aztec.js/abi';
2
+ import { Fr } from '@aztec/aztec.js/fields';
3
+ import { ContractStore } from '@aztec/pxe/server';
3
4
 
4
5
  export type ContractArtifactWithHash = ContractArtifact & { artifactHash: Fr };
5
6
 
6
7
  /*
7
- * A contract data provider that stores contract artifacts with their hashes. Since
8
+ * A contract store that stores contract artifacts with their hashes. Since
8
9
  * TXE typically deploys the same contract again and again for multiple tests, caching
9
10
  * the *very* expensive artifact hash computation improves testing speed significantly.
10
11
  */
11
- export class TXEContractDataProvider extends ContractDataProvider {
12
+ export class TXEContractStore extends ContractStore {
12
13
  #artifactHashes: Map<string, Buffer> = new Map();
13
14
 
14
15
  public override async addContractArtifact(