@aztec/txe 2.1.0-rc.9 → 3.0.0-devnet.2

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