@aztec/txe 0.0.0-test.0 → 0.0.1-commit.03f7ef2

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