@aztec/txe 3.0.0-canary.a9708bd → 3.0.0-devnet.2-patch.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 (89) hide show
  1. package/dest/bin/index.d.ts +1 -1
  2. package/dest/bin/index.js +1 -1
  3. package/dest/index.d.ts +1 -1
  4. package/dest/index.d.ts.map +1 -1
  5. package/dest/index.js +5 -2
  6. package/dest/oracle/interfaces.d.ts +55 -0
  7. package/dest/oracle/interfaces.d.ts.map +1 -0
  8. package/dest/oracle/interfaces.js +3 -0
  9. package/dest/oracle/txe_oracle_public_context.d.ts +11 -11
  10. package/dest/oracle/txe_oracle_public_context.d.ts.map +1 -1
  11. package/dest/oracle/txe_oracle_public_context.js +30 -32
  12. package/dest/oracle/txe_oracle_top_level_context.d.ts +57 -0
  13. package/dest/oracle/txe_oracle_top_level_context.d.ts.map +1 -0
  14. package/dest/oracle/txe_oracle_top_level_context.js +432 -0
  15. package/dest/{txe_service/txe_service.d.ts → rpc_translator.d.ts} +40 -31
  16. package/dest/rpc_translator.d.ts.map +1 -0
  17. package/dest/{txe_service/txe_service.js → rpc_translator.js} +172 -125
  18. package/dest/state_machine/archiver.d.ts +18 -9
  19. package/dest/state_machine/archiver.d.ts.map +1 -1
  20. package/dest/state_machine/archiver.js +21 -4
  21. package/dest/state_machine/dummy_p2p_client.d.ts +5 -2
  22. package/dest/state_machine/dummy_p2p_client.d.ts.map +1 -1
  23. package/dest/state_machine/dummy_p2p_client.js +6 -0
  24. package/dest/state_machine/global_variable_builder.d.ts +3 -15
  25. package/dest/state_machine/global_variable_builder.d.ts.map +1 -1
  26. package/dest/state_machine/global_variable_builder.js +3 -22
  27. package/dest/state_machine/index.d.ts +2 -2
  28. package/dest/state_machine/index.d.ts.map +1 -1
  29. package/dest/state_machine/index.js +8 -6
  30. package/dest/state_machine/mock_epoch_cache.d.ts +6 -5
  31. package/dest/state_machine/mock_epoch_cache.d.ts.map +1 -1
  32. package/dest/state_machine/mock_epoch_cache.js +8 -7
  33. package/dest/state_machine/synchronizer.d.ts +5 -4
  34. package/dest/state_machine/synchronizer.d.ts.map +1 -1
  35. package/dest/state_machine/synchronizer.js +5 -4
  36. package/dest/txe_session.d.ts +36 -46
  37. package/dest/txe_session.d.ts.map +1 -1
  38. package/dest/txe_session.js +200 -82
  39. package/dest/util/encoding.d.ts +24 -24
  40. package/dest/util/encoding.d.ts.map +1 -1
  41. package/dest/util/encoding.js +1 -1
  42. package/dest/util/expected_failure_error.d.ts +1 -1
  43. package/dest/util/expected_failure_error.d.ts.map +1 -1
  44. package/dest/util/txe_account_data_provider.d.ts +1 -1
  45. package/dest/util/txe_account_data_provider.d.ts.map +1 -1
  46. package/dest/util/txe_contract_data_provider.d.ts +3 -2
  47. package/dest/util/txe_contract_data_provider.d.ts.map +1 -1
  48. package/dest/util/txe_contract_data_provider.js +1 -1
  49. package/dest/util/txe_public_contract_data_source.d.ts +8 -6
  50. package/dest/util/txe_public_contract_data_source.d.ts.map +1 -1
  51. package/dest/util/txe_public_contract_data_source.js +14 -12
  52. package/dest/utils/block_creation.d.ts +14 -0
  53. package/dest/utils/block_creation.d.ts.map +1 -0
  54. package/dest/utils/block_creation.js +24 -0
  55. package/dest/utils/tx_effect_creation.d.ts +6 -0
  56. package/dest/utils/tx_effect_creation.d.ts.map +1 -0
  57. package/dest/utils/tx_effect_creation.js +16 -0
  58. package/package.json +18 -17
  59. package/src/bin/index.ts +1 -1
  60. package/src/index.ts +5 -8
  61. package/src/oracle/interfaces.ts +84 -0
  62. package/src/oracle/txe_oracle_public_context.ts +38 -71
  63. package/src/oracle/txe_oracle_top_level_context.ts +667 -0
  64. package/src/{txe_service/txe_service.ts → rpc_translator.ts} +222 -128
  65. package/src/state_machine/archiver.ts +33 -13
  66. package/src/state_machine/dummy_p2p_client.ts +10 -1
  67. package/src/state_machine/global_variable_builder.ts +7 -41
  68. package/src/state_machine/index.ts +10 -8
  69. package/src/state_machine/mock_epoch_cache.ts +12 -11
  70. package/src/state_machine/synchronizer.ts +8 -7
  71. package/src/txe_session.ts +305 -92
  72. package/src/util/encoding.ts +1 -1
  73. package/src/util/txe_contract_data_provider.ts +2 -1
  74. package/src/util/txe_public_contract_data_source.ts +16 -13
  75. package/src/utils/block_creation.ts +64 -0
  76. package/src/utils/tx_effect_creation.ts +38 -0
  77. package/dest/oracle/txe_oracle.d.ts +0 -124
  78. package/dest/oracle/txe_oracle.d.ts.map +0 -1
  79. package/dest/oracle/txe_oracle.js +0 -770
  80. package/dest/oracle/txe_typed_oracle.d.ts +0 -42
  81. package/dest/oracle/txe_typed_oracle.d.ts.map +0 -1
  82. package/dest/oracle/txe_typed_oracle.js +0 -83
  83. package/dest/txe_constants.d.ts +0 -2
  84. package/dest/txe_constants.d.ts.map +0 -1
  85. package/dest/txe_constants.js +0 -7
  86. package/dest/txe_service/txe_service.d.ts.map +0 -1
  87. package/src/oracle/txe_oracle.ts +0 -1287
  88. package/src/oracle/txe_typed_oracle.ts +0 -142
  89. package/src/txe_constants.ts +0 -9
@@ -1,4 +1,5 @@
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';
@@ -7,48 +8,83 @@ import {
7
8
  AddressDataProvider,
8
9
  CapsuleDataProvider,
9
10
  NoteDataProvider,
11
+ PXEOracleInterface,
10
12
  PrivateEventDataProvider,
11
13
  TaggingDataProvider,
12
14
  } from '@aztec/pxe/server';
13
- import type { PrivateContextInputs } from '@aztec/stdlib/kernel';
14
- import { makeGlobalVariables } from '@aztec/stdlib/testing';
15
- import type { UInt32 } from '@aztec/stdlib/types';
16
-
17
- import { TXE } from './oracle/txe_oracle.js';
15
+ import {
16
+ ExecutionNoteCache,
17
+ ExecutionTaggingIndexCache,
18
+ HashedValuesCache,
19
+ type IPrivateExecutionOracle,
20
+ type IUtilityExecutionOracle,
21
+ PrivateExecutionOracle,
22
+ UtilityExecutionOracle,
23
+ } from '@aztec/pxe/simulator';
24
+ import { FunctionSelector } from '@aztec/stdlib/abi';
25
+ import type { AuthWitness } from '@aztec/stdlib/auth-witness';
26
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
27
+ import { Body, L2Block } from '@aztec/stdlib/block';
28
+ import { GasSettings } from '@aztec/stdlib/gas';
29
+ import { computeProtocolNullifier } from '@aztec/stdlib/hash';
30
+ import { PrivateContextInputs } from '@aztec/stdlib/kernel';
31
+ import { makeAppendOnlyTreeSnapshot, makeGlobalVariables } from '@aztec/stdlib/testing';
32
+ import { CallContext, GlobalVariables, TxContext } from '@aztec/stdlib/tx';
33
+
34
+ import { z } from 'zod';
35
+
36
+ import type { IAvmExecutionOracle, ITxeExecutionOracle } from './oracle/interfaces.js';
18
37
  import { TXEOraclePublicContext } from './oracle/txe_oracle_public_context.js';
19
- import type { TXETypedOracle } from './oracle/txe_typed_oracle.js';
38
+ import { TXEOracleTopLevelContext } from './oracle/txe_oracle_top_level_context.js';
39
+ import { RPCTranslator } from './rpc_translator.js';
20
40
  import { TXEStateMachine } from './state_machine/index.js';
21
- import { TXEService } from './txe_service/txe_service.js';
22
41
  import type { ForeignCallArgs, ForeignCallResult } from './util/encoding.js';
23
42
  import { TXEAccountDataProvider } from './util/txe_account_data_provider.js';
24
43
  import { TXEContractDataProvider } from './util/txe_contract_data_provider.js';
44
+ import {
45
+ getSingleTxBlockRequestHash,
46
+ insertTxEffectIntoWorldTrees,
47
+ makeTXEBlockHeader,
48
+ } from './utils/block_creation.js';
49
+ import { makeTxEffect } from './utils/tx_effect_creation.js';
25
50
 
26
51
  /**
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.
52
+ * A TXE Session can be in one of four states, which change as the test progresses and different oracles are called.
53
+ * The current state determines which oracles are available. Some states also have data associated with them.
29
54
  */
30
- enum SessionState {
55
+ type SessionState =
31
56
  /**
32
57
  * The top-level state is the default state, before any other state has been entered. This is where contracts can be
33
58
  * deployed, accounts created, blocks mined, etc.
34
59
  */
35
- TOP_LEVEL,
60
+ | {
61
+ name: 'TOP_LEVEL';
62
+ }
36
63
  /**
37
- * The private state is entered via the `private_context` function. In this state the PXE oracles that `#[private]`
64
+ * The private state is entered via the `private_context` function. In this state the PXE oracles that `#[external("private")]`
38
65
  * functions use are available, such as those related to note retrieval, notification of side-effects, capsule access,
39
66
  * etc. */
40
- PRIVATE,
67
+ | {
68
+ name: 'PRIVATE';
69
+ nextBlockGlobalVariables: GlobalVariables;
70
+ protocolNullifier: Fr;
71
+ noteCache: ExecutionNoteCache;
72
+ taggingIndexCache: ExecutionTaggingIndexCache;
73
+ }
41
74
  /**
42
- * The public state is entered via the `public_context` function. In this state the AVM opcodes that `#[public]`
75
+ * The public state is entered via the `public_context` function. In this state the AVM opcodes that `#[external("public")]`
43
76
  * functions execute are resolved as oracles by TXE, since Noir tests are not transpiled. */
44
- PUBLIC,
77
+ | {
78
+ name: 'PUBLIC';
79
+ }
45
80
  /**
46
- * The utility state is entered via the `utility_context` function. In this state the PXE oracles that `#[utility]`
81
+ * The utility state is entered via the `utility_context` function. In this state the PXE oracles that `#[external("utility")]`
47
82
  * functions use are available, such as those related to (unconstrained) note retrieval, capsule access, public
48
83
  * storage reads, etc.
49
84
  */
50
- UTILITY,
51
- }
85
+ | {
86
+ name: 'UTILITY';
87
+ };
52
88
 
53
89
  type MethodNames<T> = {
54
90
  [K in keyof T]: T[K] extends (...args: any[]) => any ? K : never;
@@ -58,13 +94,16 @@ type MethodNames<T> = {
58
94
  * The name of an oracle function that TXE supports, which are a combination of PXE oracles, non-transpiled AVM opcodes,
59
95
  * and custom TXE oracles.
60
96
  */
61
- export type TXEOracleFunctionName = MethodNames<TXEService>;
97
+ export type TXEOracleFunctionName = Exclude<
98
+ MethodNames<RPCTranslator>,
99
+ 'constructor' | 'handlerAsMisc' | 'handlerAsUtility' | 'handlerAsPrivate' | 'handlerAsAvm' | 'handlerAsTxe'
100
+ >;
62
101
 
63
102
  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>;
103
+ enterTopLevelState(): Promise<void>;
104
+ enterPublicState(contractAddress?: AztecAddress): Promise<void>;
105
+ enterPrivateState(contractAddress?: AztecAddress, anchorBlockNumber?: BlockNumber): Promise<PrivateContextInputs>;
106
+ enterUtilityState(contractAddress?: AztecAddress): Promise<void>;
68
107
  }
69
108
 
70
109
  const DEFAULT_ADDRESS = AztecAddress.fromNumber(42);
@@ -74,13 +113,25 @@ const DEFAULT_ADDRESS = AztecAddress.fromNumber(42);
74
113
  * state, etc., independent of all other tests running in parallel.
75
114
  */
76
115
  export class TXESession implements TXESessionStateHandler {
77
- state = SessionState.TOP_LEVEL;
116
+ private state: SessionState = { name: 'TOP_LEVEL' };
117
+ private authwits: Map<string, AuthWitness> = new Map();
78
118
 
79
119
  constructor(
80
120
  private logger: Logger,
81
121
  private stateMachine: TXEStateMachine,
82
- private oracleHandler: TXETypedOracle,
83
- private legacyTXEOracle: TXE,
122
+ private oracleHandler:
123
+ | IUtilityExecutionOracle
124
+ | IPrivateExecutionOracle
125
+ | IAvmExecutionOracle
126
+ | ITxeExecutionOracle,
127
+ private contractDataProvider: TXEContractDataProvider,
128
+ private keyStore: KeyStore,
129
+ private addressDataProvider: AddressDataProvider,
130
+ private accountDataProvider: TXEAccountDataProvider,
131
+ private chainId: Fr,
132
+ private version: Fr,
133
+ private nextBlockTimestamp: bigint,
134
+ private pxeOracleInterface: PXEOracleInterface,
84
135
  ) {}
85
136
 
86
137
  static async init(protocolContracts: ProtocolContract[]) {
@@ -103,22 +154,49 @@ export class TXESession implements TXESessionStateHandler {
103
154
 
104
155
  const stateMachine = await TXEStateMachine.create(store);
105
156
 
106
- const txeOracle = new TXE(
157
+ const nextBlockTimestamp = BigInt(Math.floor(new Date().getTime() / 1000));
158
+ const version = new Fr(await stateMachine.node.getVersion());
159
+ const chainId = new Fr(await stateMachine.node.getChainId());
160
+
161
+ const pxeOracleInterface = new PXEOracleInterface(
162
+ stateMachine.node,
107
163
  keyStore,
108
164
  contractDataProvider,
109
165
  noteDataProvider,
110
166
  capsuleDataProvider,
167
+ stateMachine.syncDataProvider,
111
168
  taggingDataProvider,
112
169
  addressDataProvider,
113
170
  privateEventDataProvider,
114
- accountDataProvider,
115
- DEFAULT_ADDRESS,
116
- await stateMachine.synchronizer.nativeWorldStateService.fork(),
171
+ );
172
+
173
+ const topLevelOracleHandler = new TXEOracleTopLevelContext(
117
174
  stateMachine,
175
+ contractDataProvider,
176
+ keyStore,
177
+ addressDataProvider,
178
+ accountDataProvider,
179
+ pxeOracleInterface,
180
+ nextBlockTimestamp,
181
+ version,
182
+ chainId,
183
+ new Map(),
118
184
  );
119
- await txeOracle.txeAdvanceBlocksBy(1);
185
+ await topLevelOracleHandler.txeAdvanceBlocksBy(1);
120
186
 
121
- return new TXESession(createLogger('txe:session'), stateMachine, txeOracle, txeOracle);
187
+ return new TXESession(
188
+ createLogger('txe:session'),
189
+ stateMachine,
190
+ topLevelOracleHandler,
191
+ contractDataProvider,
192
+ keyStore,
193
+ addressDataProvider,
194
+ accountDataProvider,
195
+ version,
196
+ chainId,
197
+ nextBlockTimestamp,
198
+ pxeOracleInterface,
199
+ );
122
200
  }
123
201
 
124
202
  /**
@@ -128,94 +206,229 @@ export class TXESession implements TXESessionStateHandler {
128
206
  * @returns The oracle return values.
129
207
  */
130
208
  processFunction(functionName: TXEOracleFunctionName, inputs: ForeignCallArgs): Promise<ForeignCallResult> {
131
- return (new TXEService(this, this.oracleHandler) as any)[functionName](...inputs);
209
+ try {
210
+ const translator = new RPCTranslator(this, this.oracleHandler) as any;
211
+ // We perform a runtime validation to check that the function name corresponds to a real oracle handler.
212
+ const validatedFunctionName = z
213
+ .string()
214
+ .refine(fn => typeof translator[fn] === 'function' && !fn.startsWith('handlerAs') && fn !== 'constructor')
215
+ .parse(functionName) as TXEOracleFunctionName;
216
+
217
+ return translator[validatedFunctionName](...inputs);
218
+ } catch (error) {
219
+ if (error instanceof z.ZodError) {
220
+ throw new Error(`${functionName} does not correspond to any oracle handler available on RPCTranslator`);
221
+ } else if (error instanceof Error) {
222
+ throw new Error(
223
+ `Execution error while processing function ${functionName} in state ${this.state.name}: ${error.message}`,
224
+ );
225
+ } else {
226
+ throw new Error(
227
+ `Unknown execution error while processing function ${functionName} in state ${this.state.name}`,
228
+ );
229
+ }
230
+ }
132
231
  }
133
232
 
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}'`);
233
+ async enterTopLevelState() {
234
+ switch (this.state.name) {
235
+ case 'PRIVATE': {
236
+ await this.exitPrivateState();
237
+ break;
238
+ }
239
+ case 'PUBLIC': {
240
+ await this.exitPublicState();
241
+ break;
242
+ }
243
+ case 'UTILITY': {
244
+ this.exitUtilityContext();
245
+ break;
246
+ }
247
+ case 'TOP_LEVEL': {
248
+ throw new Error(`Expected to be in state other than TOP_LEVEL`);
249
+ }
250
+ default: {
251
+ this.state satisfies never;
252
+ }
154
253
  }
155
254
 
156
- this.state = SessionState.TOP_LEVEL;
157
- this.logger.debug(`Entered state ${SessionState[this.state]}`);
255
+ this.oracleHandler = new TXEOracleTopLevelContext(
256
+ this.stateMachine,
257
+ this.contractDataProvider,
258
+ this.keyStore,
259
+ this.addressDataProvider,
260
+ this.accountDataProvider,
261
+ this.pxeOracleInterface,
262
+ this.nextBlockTimestamp,
263
+ this.version,
264
+ this.chainId,
265
+ this.authwits,
266
+ );
267
+
268
+ this.state = { name: 'TOP_LEVEL' };
269
+ this.logger.debug(`Entered state ${this.state.name}`);
158
270
  }
159
271
 
160
- async setPublicContext(contractAddress?: AztecAddress): Promise<void> {
161
- this.assertInTopLevelState();
272
+ async enterPrivateState(
273
+ contractAddress: AztecAddress = DEFAULT_ADDRESS,
274
+ anchorBlockNumber?: BlockNumber,
275
+ ): Promise<PrivateContextInputs> {
276
+ this.exitTopLevelState();
277
+
278
+ // There is no automatic message discovery and contract-driven syncing process in inlined private or utility
279
+ // contexts, which means that known nullifiers are also not searched for, since it is during the tagging sync that
280
+ // we perform this. We therefore search for known nullifiers now, as otherwise notes that were nullified would not
281
+ // be removed from the database.
282
+ // TODO(#12553): make the synchronizer sync here instead and remove this
283
+ await this.pxeOracleInterface.syncNoteNullifiers(contractAddress);
284
+
285
+ // Private execution has two associated block numbers: the anchor block (i.e. the historical block that is used to
286
+ // build the proof), and the *next* block, i.e. the one we'll create once the execution ends, and which will contain
287
+ // a single transaction with the effects of what was done in the test.
288
+ const anchorBlock = await this.stateMachine.node.getBlockHeader(anchorBlockNumber ?? 'latest');
289
+ const latestBlock = await this.stateMachine.node.getBlockHeader('latest');
290
+
291
+ const nextBlockGlobalVariables = makeGlobalVariables(undefined, {
292
+ blockNumber: BlockNumber(latestBlock!.globalVariables.blockNumber + 1),
293
+ timestamp: this.nextBlockTimestamp,
294
+ version: this.version,
295
+ chainId: this.chainId,
296
+ });
162
297
 
298
+ const txRequestHash = getSingleTxBlockRequestHash(nextBlockGlobalVariables.blockNumber);
299
+ const protocolNullifier = await computeProtocolNullifier(txRequestHash);
300
+ const noteCache = new ExecutionNoteCache(protocolNullifier);
301
+ const taggingIndexCache = new ExecutionTaggingIndexCache();
302
+
303
+ this.oracleHandler = new PrivateExecutionOracle(
304
+ Fr.ZERO,
305
+ new TxContext(this.chainId, this.version, GasSettings.empty()),
306
+ new CallContext(AztecAddress.ZERO, contractAddress, FunctionSelector.empty(), false),
307
+ anchorBlock!,
308
+ [],
309
+ [],
310
+ new HashedValuesCache(),
311
+ noteCache,
312
+ taggingIndexCache,
313
+ this.pxeOracleInterface,
314
+ );
315
+
316
+ // We store the note and tagging index caches fed into the PrivateExecutionOracle (along with some other auxiliary
317
+ // data) in order to refer to it later, mimicking the way this object is used by the ContractFunctionSimulator. The
318
+ // difference resides in that the simulator has all information needed in order to run the simulation, while ours
319
+ // will be ongoing as the different oracles will be invoked from the Noir test, until eventually the private
320
+ // execution finishes.
321
+ this.state = { name: 'PRIVATE', nextBlockGlobalVariables, protocolNullifier, noteCache, taggingIndexCache };
322
+ this.logger.debug(`Entered state ${this.state.name}`);
323
+
324
+ return (this.oracleHandler as PrivateExecutionOracle).getPrivateContextInputs();
325
+ }
326
+
327
+ async enterPublicState(contractAddress?: AztecAddress) {
328
+ this.exitTopLevelState();
329
+
330
+ // The PublicContext will create a block with a single transaction in it, containing the effects of what was done in
331
+ // the test. The block therefore gets the *next* block number and timestamp.
332
+ const latestBlockNumber = (await this.stateMachine.node.getBlockHeader('latest'))!.globalVariables.blockNumber;
163
333
  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(),
334
+ blockNumber: BlockNumber(latestBlockNumber + 1),
335
+ timestamp: this.nextBlockTimestamp,
336
+ version: this.version,
337
+ chainId: this.chainId,
168
338
  });
169
339
 
170
- const txRequestHash = new Fr(globalVariables.blockNumber + 6969);
171
-
172
340
  this.oracleHandler = new TXEOraclePublicContext(
173
341
  contractAddress ?? DEFAULT_ADDRESS,
174
342
  await this.stateMachine.synchronizer.nativeWorldStateService.fork(),
175
- txRequestHash,
343
+ getSingleTxBlockRequestHash(globalVariables.blockNumber),
176
344
  globalVariables,
177
345
  );
178
346
 
179
- this.state = SessionState.PUBLIC;
180
- this.logger.debug(`Entered state ${SessionState[this.state]}`);
347
+ this.state = { name: 'PUBLIC' };
348
+ this.logger.debug(`Entered state ${this.state.name}`);
181
349
  }
182
350
 
183
- async setPrivateContext(
184
- contractAddress?: AztecAddress,
185
- historicalBlockNumber?: UInt32,
186
- ): Promise<PrivateContextInputs> {
187
- this.assertInTopLevelState();
188
-
189
- if (contractAddress) {
190
- this.oracleHandler.txeSetContractAddress(contractAddress);
191
- }
351
+ async enterUtilityState(contractAddress: AztecAddress = DEFAULT_ADDRESS) {
352
+ this.exitTopLevelState();
192
353
 
193
- const privateContextInputs = await this.oracleHandler.txeGetPrivateContextInputs(historicalBlockNumber);
354
+ // There is no automatic message discovery and contract-driven syncing process in inlined private or utility
355
+ // contexts, which means that known nullifiers are also not searched for, since it is during the tagging sync that
356
+ // we perform this. We therefore search for known nullifiers now, as otherwise notes that were nullified would not
357
+ // be removed from the database.
358
+ // TODO(#12553): make the synchronizer sync here instead and remove this
359
+ await this.pxeOracleInterface.syncNoteNullifiers(contractAddress);
194
360
 
195
- this.state = SessionState.PRIVATE;
196
- this.logger.debug(`Entered state ${SessionState[this.state]}`);
361
+ this.oracleHandler = new UtilityExecutionOracle(contractAddress, [], [], this.pxeOracleInterface);
197
362
 
198
- return privateContextInputs;
363
+ this.state = { name: 'UTILITY' };
364
+ this.logger.debug(`Entered state ${this.state.name}`);
199
365
  }
200
366
 
201
- setUtilityContext(contractAddress?: AztecAddress): Promise<void> {
202
- this.assertInTopLevelState();
367
+ private exitTopLevelState() {
368
+ if (this.state.name != 'TOP_LEVEL') {
369
+ throw new Error(`Expected to be in state 'TOP_LEVEL', but got '${this.state.name}' instead`);
370
+ }
371
+
372
+ // Note that while all public and private contexts do is build a single block that we then process when exiting
373
+ // those, the top level context performs a large number of actions not captured in the following 'close' call. Among
374
+ // others, it will create empty blocks (via `txeAdvanceBlocksBy` and `deploy`), create blocks with transactions via
375
+ // `txePrivateCallNewFlow` and `txePublicCallNewFlow`, add accounts to PXE via `txeAddAccount`, etc. This is a
376
+ // slight inconsistency in the working model of this class, but is not too bad.
377
+ // TODO: it's quite unfortunate that we need to capture the authwits created to later pass them again when the top
378
+ // level context is re-created. This is because authwits create a temporary utility context that'd otherwise reset
379
+ // the authwits if not persisted, so we'd not be able to pass more than one per execution.
380
+ // Ideally authwits would be passed alongside a contract call instead of pre-seeded.
381
+ [this.nextBlockTimestamp, this.authwits] = (this.oracleHandler as TXEOracleTopLevelContext).close();
382
+ }
203
383
 
204
- if (contractAddress) {
205
- this.oracleHandler.txeSetContractAddress(contractAddress);
384
+ private async exitPrivateState() {
385
+ if (this.state.name != 'PRIVATE') {
386
+ throw new Error(`Expected to be in state 'PRIVATE', but got '${this.state.name}' instead`);
206
387
  }
207
388
 
208
- this.state = SessionState.UTILITY;
209
- this.logger.debug(`Entered state ${SessionState[this.state]}`);
389
+ this.logger.debug('Exiting Private state, building block with collected side effects', {
390
+ blockNumber: this.state.nextBlockGlobalVariables.blockNumber,
391
+ });
392
+
393
+ // We rely on the note cache to determine the effects of the transaction. This is incomplete as it doesn't private
394
+ // logs (other effects like enqueued public calls don't need to be considered since those are not allowed).
395
+ const txEffect = await makeTxEffect(
396
+ this.state.noteCache,
397
+ this.state.protocolNullifier,
398
+ this.state.nextBlockGlobalVariables.blockNumber,
399
+ );
400
+
401
+ // We build a block holding just this transaction
402
+ const forkedWorldTrees = await this.stateMachine.synchronizer.nativeWorldStateService.fork();
403
+ await insertTxEffectIntoWorldTrees(txEffect, forkedWorldTrees);
404
+
405
+ const block = new L2Block(
406
+ makeAppendOnlyTreeSnapshot(),
407
+ await makeTXEBlockHeader(forkedWorldTrees, this.state.nextBlockGlobalVariables),
408
+ new Body([txEffect]),
409
+ );
410
+ await this.stateMachine.handleL2Block(block);
411
+
412
+ await forkedWorldTrees.close();
413
+
414
+ this.logger.debug('Exited PublicContext with built block', {
415
+ blockNumber: block.number,
416
+ txEffects: block.body.txEffects,
417
+ });
418
+ }
419
+
420
+ private async exitPublicState() {
421
+ if (this.state.name != 'PUBLIC') {
422
+ throw new Error(`Expected to be in state 'PUBLIC', but got '${this.state.name}' instead`);
423
+ }
210
424
 
211
- return Promise.resolve();
425
+ const block = await (this.oracleHandler as TXEOraclePublicContext).close();
426
+ await this.stateMachine.handleL2Block(block);
212
427
  }
213
428
 
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
- );
429
+ private exitUtilityContext() {
430
+ if (this.state.name != 'UTILITY') {
431
+ throw new Error(`Expected to be in state 'UTILITY', but got '${this.state.name}' instead`);
219
432
  }
220
433
  }
221
434
  }
@@ -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';
@@ -1,4 +1,5 @@
1
- import { type ContractArtifact, Fr } from '@aztec/aztec.js';
1
+ import type { ContractArtifact } from '@aztec/aztec.js/abi';
2
+ import { Fr } from '@aztec/aztec.js/fields';
2
3
  import { ContractDataProvider } from '@aztec/pxe/server';
3
4
 
4
5
  export type ContractArtifactWithHash = ContractArtifact & { artifactHash: Fr };
@@ -1,4 +1,6 @@
1
- import { Fr } from '@aztec/foundation/fields';
1
+ import { BlockNumber } from '@aztec/foundation/branded-types';
2
+ import { Fr } from '@aztec/foundation/curves/bn254';
3
+ import type { ContractDataProvider } from '@aztec/pxe/server';
2
4
  import { type ContractArtifact, FunctionSelector, FunctionType } from '@aztec/stdlib/abi';
3
5
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
4
6
  import {
@@ -10,22 +12,23 @@ import {
10
12
  getContractClassPrivateFunctionFromArtifact,
11
13
  } from '@aztec/stdlib/contract';
12
14
 
13
- import type { TXE } from '../oracle/txe_oracle.js';
14
-
15
15
  export class TXEPublicContractDataSource implements ContractDataSource {
16
16
  #privateFunctionsRoot: Map<string, Buffer> = new Map();
17
- constructor(private txeOracle: TXE) {}
17
+ constructor(
18
+ private blockNumber: BlockNumber,
19
+ private contractDataProvider: ContractDataProvider,
20
+ ) {}
18
21
 
19
- getBlockNumber(): Promise<number> {
20
- return this.txeOracle.utilityGetBlockNumber();
22
+ getBlockNumber(): Promise<BlockNumber> {
23
+ return Promise.resolve(this.blockNumber);
21
24
  }
22
25
 
23
26
  async getContractClass(id: Fr): Promise<ContractClassPublic | undefined> {
24
- const contractClass = await this.txeOracle.getContractDataProvider().getContractClass(id);
27
+ const contractClass = await this.contractDataProvider.getContractClass(id);
25
28
  if (!contractClass) {
26
29
  return;
27
30
  }
28
- const artifact = await this.txeOracle.getContractDataProvider().getContractArtifact(id);
31
+ const artifact = await this.contractDataProvider.getContractArtifact(id);
29
32
  if (!artifact) {
30
33
  return;
31
34
  }
@@ -55,12 +58,12 @@ export class TXEPublicContractDataSource implements ContractDataSource {
55
58
  }
56
59
 
57
60
  async getBytecodeCommitment(id: Fr): Promise<Fr | undefined> {
58
- const contractClass = await this.txeOracle.getContractDataProvider().getContractClass(id);
61
+ const contractClass = await this.contractDataProvider.getContractClass(id);
59
62
  return contractClass && computePublicBytecodeCommitment(contractClass.packedBytecode);
60
63
  }
61
64
 
62
65
  async getContract(address: AztecAddress): Promise<ContractInstanceWithAddress | undefined> {
63
- const instance = await this.txeOracle.getContractDataProvider().getContractInstance(address);
66
+ const instance = await this.contractDataProvider.getContractInstance(address);
64
67
  return instance && { ...instance, address };
65
68
  }
66
69
 
@@ -69,12 +72,12 @@ export class TXEPublicContractDataSource implements ContractDataSource {
69
72
  }
70
73
 
71
74
  async getContractArtifact(address: AztecAddress): Promise<ContractArtifact | undefined> {
72
- const instance = await this.txeOracle.getContractDataProvider().getContractInstance(address);
73
- return instance && this.txeOracle.getContractDataProvider().getContractArtifact(instance.currentContractClassId);
75
+ const instance = await this.contractDataProvider.getContractInstance(address);
76
+ return instance && this.contractDataProvider.getContractArtifact(instance.currentContractClassId);
74
77
  }
75
78
 
76
79
  async getDebugFunctionName(address: AztecAddress, selector: FunctionSelector): Promise<string | undefined> {
77
- return await this.txeOracle.getContractDataProvider().getDebugFunctionName(address, selector);
80
+ return await this.contractDataProvider.getDebugFunctionName(address, selector);
78
81
  }
79
82
 
80
83
  registerContractFunctionSignatures(_signatures: []): Promise<void> {
@@ -0,0 +1,64 @@
1
+ import {
2
+ MAX_NOTE_HASHES_PER_TX,
3
+ MAX_NULLIFIERS_PER_TX,
4
+ NULLIFIER_SUBTREE_HEIGHT,
5
+ NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP,
6
+ } from '@aztec/constants';
7
+ import { BlockNumber } from '@aztec/foundation/branded-types';
8
+ import { padArrayEnd } from '@aztec/foundation/collection';
9
+ import { Fr } from '@aztec/foundation/curves/bn254';
10
+ import { L2BlockHeader } from '@aztec/stdlib/block';
11
+ import { makeContentCommitment } from '@aztec/stdlib/testing';
12
+ import { AppendOnlyTreeSnapshot, MerkleTreeId, type MerkleTreeWriteOperations } from '@aztec/stdlib/trees';
13
+ import { GlobalVariables, TxEffect } from '@aztec/stdlib/tx';
14
+
15
+ /**
16
+ * Returns a transaction request hash that is valid for transactions that are the only ones in a block.
17
+ * @param blockNumber The number for the block in which there is a single transaction.
18
+ * @returns The transaction request hash.
19
+ */
20
+ export function getSingleTxBlockRequestHash(blockNumber: BlockNumber): Fr {
21
+ return new Fr(blockNumber + 9999); // Why does this need to be a high number? Why do small numbered nullifiers already exist?
22
+ }
23
+
24
+ export async function insertTxEffectIntoWorldTrees(
25
+ txEffect: TxEffect,
26
+ worldTrees: MerkleTreeWriteOperations,
27
+ ): Promise<void> {
28
+ await worldTrees.appendLeaves(
29
+ MerkleTreeId.NOTE_HASH_TREE,
30
+ padArrayEnd(txEffect.noteHashes, Fr.ZERO, MAX_NOTE_HASHES_PER_TX),
31
+ );
32
+
33
+ await worldTrees.batchInsert(
34
+ MerkleTreeId.NULLIFIER_TREE,
35
+ padArrayEnd(txEffect.nullifiers, Fr.ZERO, MAX_NULLIFIERS_PER_TX).map(nullifier => nullifier.toBuffer()),
36
+ NULLIFIER_SUBTREE_HEIGHT,
37
+ );
38
+
39
+ await worldTrees.appendLeaves(
40
+ MerkleTreeId.L1_TO_L2_MESSAGE_TREE,
41
+ padArrayEnd<Fr, number>(txEffect.l2ToL1Msgs, Fr.ZERO, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP),
42
+ );
43
+
44
+ // We do not need to add public data writes because we apply them as we go.
45
+ }
46
+
47
+ export async function makeTXEBlockHeader(
48
+ worldTrees: MerkleTreeWriteOperations,
49
+ globalVariables: GlobalVariables,
50
+ ): Promise<L2BlockHeader> {
51
+ const stateReference = await worldTrees.getStateReference();
52
+ const archiveInfo = await worldTrees.getTreeInfo(MerkleTreeId.ARCHIVE);
53
+
54
+ return new L2BlockHeader(
55
+ new AppendOnlyTreeSnapshot(new Fr(archiveInfo.root), Number(archiveInfo.size)),
56
+ makeContentCommitment(),
57
+ stateReference,
58
+ globalVariables,
59
+ Fr.ZERO,
60
+ Fr.ZERO,
61
+ Fr.ZERO,
62
+ Fr.ZERO,
63
+ );
64
+ }