@aztec/txe 0.0.1-fake-ceab37513c → 0.0.6-commit.a2d1860fe9

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