@aztec/txe 0.0.0-test.1 → 0.0.1-commit.b655e406

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 (86) hide show
  1. package/dest/bin/index.js +3 -2
  2. package/dest/index.d.ts.map +1 -1
  3. package/dest/index.js +78 -49
  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 +34 -0
  8. package/dest/oracle/txe_oracle_public_context.d.ts.map +1 -0
  9. package/dest/oracle/txe_oracle_public_context.js +124 -0
  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/rpc_translator.d.ts +237 -0
  14. package/dest/rpc_translator.d.ts.map +1 -0
  15. package/dest/rpc_translator.js +617 -0
  16. package/dest/state_machine/archiver.d.ts +61 -0
  17. package/dest/state_machine/archiver.d.ts.map +1 -0
  18. package/dest/state_machine/archiver.js +118 -0
  19. package/dest/state_machine/dummy_p2p_client.d.ts +52 -0
  20. package/dest/state_machine/dummy_p2p_client.d.ts.map +1 -0
  21. package/dest/state_machine/dummy_p2p_client.js +133 -0
  22. package/dest/state_machine/global_variable_builder.d.ts +9 -0
  23. package/dest/state_machine/global_variable_builder.d.ts.map +1 -0
  24. package/dest/state_machine/global_variable_builder.js +10 -0
  25. package/dest/state_machine/index.d.ts +16 -0
  26. package/dest/state_machine/index.d.ts.map +1 -0
  27. package/dest/state_machine/index.js +51 -0
  28. package/dest/state_machine/mock_epoch_cache.d.ts +25 -0
  29. package/dest/state_machine/mock_epoch_cache.d.ts.map +1 -0
  30. package/dest/state_machine/mock_epoch_cache.js +50 -0
  31. package/dest/state_machine/synchronizer.d.ts +32 -0
  32. package/dest/state_machine/synchronizer.d.ts.map +1 -0
  33. package/dest/state_machine/synchronizer.js +58 -0
  34. package/dest/txe_session.d.ts +67 -0
  35. package/dest/txe_session.d.ts.map +1 -0
  36. package/dest/txe_session.js +253 -0
  37. package/dest/util/encoding.d.ts +26 -8
  38. package/dest/util/encoding.d.ts.map +1 -1
  39. package/dest/util/encoding.js +65 -10
  40. package/dest/util/txe_contract_data_provider.d.ts +12 -0
  41. package/dest/util/txe_contract_data_provider.d.ts.map +1 -0
  42. package/dest/util/txe_contract_data_provider.js +22 -0
  43. package/dest/util/txe_public_contract_data_source.d.ts +8 -8
  44. package/dest/util/txe_public_contract_data_source.d.ts.map +1 -1
  45. package/dest/util/txe_public_contract_data_source.js +36 -57
  46. package/dest/utils/block_creation.d.ts +13 -0
  47. package/dest/utils/block_creation.d.ts.map +1 -0
  48. package/dest/utils/block_creation.js +24 -0
  49. package/dest/utils/tx_effect_creation.d.ts +5 -0
  50. package/dest/utils/tx_effect_creation.d.ts.map +1 -0
  51. package/dest/utils/tx_effect_creation.js +16 -0
  52. package/package.json +27 -22
  53. package/src/bin/index.ts +3 -2
  54. package/src/index.ts +92 -64
  55. package/src/oracle/interfaces.ts +83 -0
  56. package/src/oracle/txe_oracle_public_context.ts +165 -0
  57. package/src/oracle/txe_oracle_top_level_context.ts +658 -0
  58. package/src/rpc_translator.ts +1013 -0
  59. package/src/state_machine/archiver.ts +151 -0
  60. package/src/state_machine/dummy_p2p_client.ts +197 -0
  61. package/src/state_machine/global_variable_builder.ts +20 -0
  62. package/src/state_machine/index.ts +77 -0
  63. package/src/state_machine/mock_epoch_cache.ts +67 -0
  64. package/src/state_machine/synchronizer.ts +87 -0
  65. package/src/txe_session.ts +432 -0
  66. package/src/util/encoding.ts +84 -10
  67. package/src/util/txe_contract_data_provider.ts +36 -0
  68. package/src/util/txe_public_contract_data_source.ts +40 -56
  69. package/src/utils/block_creation.ts +62 -0
  70. package/src/utils/tx_effect_creation.ts +37 -0
  71. package/dest/node/txe_node.d.ts +0 -358
  72. package/dest/node/txe_node.d.ts.map +0 -1
  73. package/dest/node/txe_node.js +0 -504
  74. package/dest/oracle/txe_oracle.d.ts +0 -152
  75. package/dest/oracle/txe_oracle.d.ts.map +0 -1
  76. package/dest/oracle/txe_oracle.js +0 -833
  77. package/dest/txe_service/txe_service.d.ts +0 -212
  78. package/dest/txe_service/txe_service.d.ts.map +0 -1
  79. package/dest/txe_service/txe_service.js +0 -572
  80. package/dest/util/txe_world_state_db.d.ts +0 -14
  81. package/dest/util/txe_world_state_db.d.ts.map +0 -1
  82. package/dest/util/txe_world_state_db.js +0 -27
  83. package/src/node/txe_node.ts +0 -725
  84. package/src/oracle/txe_oracle.ts +0 -1241
  85. package/src/txe_service/txe_service.ts +0 -749
  86. package/src/util/txe_world_state_db.ts +0 -38
@@ -0,0 +1,432 @@
1
+ import { Fr } from '@aztec/foundation/fields';
2
+ import { type Logger, createLogger } from '@aztec/foundation/log';
3
+ import { KeyStore } from '@aztec/key-store';
4
+ import { openTmpStore } from '@aztec/kv-store/lmdb-v2';
5
+ import type { ProtocolContract } from '@aztec/protocol-contracts';
6
+ import {
7
+ AddressDataProvider,
8
+ CapsuleDataProvider,
9
+ NoteDataProvider,
10
+ PXEOracleInterface,
11
+ PrivateEventDataProvider,
12
+ TaggingDataProvider,
13
+ } from '@aztec/pxe/server';
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';
31
+ import type { UInt32 } from '@aztec/stdlib/types';
32
+
33
+ import { z } from 'zod';
34
+
35
+ import type { IAvmExecutionOracle, ITxeExecutionOracle } from './oracle/interfaces.js';
36
+ import { TXEOraclePublicContext } from './oracle/txe_oracle_public_context.js';
37
+ import { TXEOracleTopLevelContext } from './oracle/txe_oracle_top_level_context.js';
38
+ import { RPCTranslator } from './rpc_translator.js';
39
+ import { TXEStateMachine } from './state_machine/index.js';
40
+ import type { ForeignCallArgs, ForeignCallResult } from './util/encoding.js';
41
+ import { TXEAccountDataProvider } from './util/txe_account_data_provider.js';
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';
49
+
50
+ /**
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.
53
+ */
54
+ type SessionState =
55
+ /**
56
+ * The top-level state is the default state, before any other state has been entered. This is where contracts can be
57
+ * deployed, accounts created, blocks mined, etc.
58
+ */
59
+ | {
60
+ name: 'TOP_LEVEL';
61
+ }
62
+ /**
63
+ * The private state is entered via the `private_context` function. In this state the PXE oracles that `#[external("private")]`
64
+ * functions use are available, such as those related to note retrieval, notification of side-effects, capsule access,
65
+ * etc. */
66
+ | {
67
+ name: 'PRIVATE';
68
+ nextBlockGlobalVariables: GlobalVariables;
69
+ txRequestHash: Fr;
70
+ noteCache: ExecutionNoteCache;
71
+ taggingIndexCache: ExecutionTaggingIndexCache;
72
+ }
73
+ /**
74
+ * The public state is entered via the `public_context` function. In this state the AVM opcodes that `#[external("public")]`
75
+ * functions execute are resolved as oracles by TXE, since Noir tests are not transpiled. */
76
+ | {
77
+ name: 'PUBLIC';
78
+ }
79
+ /**
80
+ * The utility state is entered via the `utility_context` function. In this state the PXE oracles that `#[external("utility")]`
81
+ * functions use are available, such as those related to (unconstrained) note retrieval, capsule access, public
82
+ * storage reads, etc.
83
+ */
84
+ | {
85
+ name: 'UTILITY';
86
+ };
87
+
88
+ type MethodNames<T> = {
89
+ [K in keyof T]: T[K] extends (...args: any[]) => any ? K : never;
90
+ }[keyof T];
91
+
92
+ /**
93
+ * The name of an oracle function that TXE supports, which are a combination of PXE oracles, non-transpiled AVM opcodes,
94
+ * and custom TXE oracles.
95
+ */
96
+ export type TXEOracleFunctionName = Exclude<
97
+ MethodNames<RPCTranslator>,
98
+ 'constructor' | 'handlerAsMisc' | 'handlerAsUtility' | 'handlerAsPrivate' | 'handlerAsAvm' | 'handlerAsTxe'
99
+ >;
100
+
101
+ export interface TXESessionStateHandler {
102
+ enterTopLevelState(): Promise<void>;
103
+ enterPublicState(contractAddress?: AztecAddress): Promise<void>;
104
+ enterPrivateState(contractAddress?: AztecAddress, anchorBlockNumber?: UInt32): Promise<PrivateContextInputs>;
105
+ enterUtilityState(contractAddress?: AztecAddress): Promise<void>;
106
+ }
107
+
108
+ const DEFAULT_ADDRESS = AztecAddress.fromNumber(42);
109
+
110
+ /**
111
+ * A `TXESession` corresponds to a Noir `#[test]` function, and handles all of its oracle calls, stores test-specific
112
+ * state, etc., independent of all other tests running in parallel.
113
+ */
114
+ export class TXESession implements TXESessionStateHandler {
115
+ private state: SessionState = { name: 'TOP_LEVEL' };
116
+ private authwits: Map<string, AuthWitness> = new Map();
117
+
118
+ constructor(
119
+ private logger: Logger,
120
+ private stateMachine: TXEStateMachine,
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,
134
+ ) {}
135
+
136
+ static async init(protocolContracts: ProtocolContract[]) {
137
+ const store = await openTmpStore('txe-session');
138
+
139
+ const addressDataProvider = new AddressDataProvider(store);
140
+ const privateEventDataProvider = new PrivateEventDataProvider(store);
141
+ const contractDataProvider = new TXEContractDataProvider(store);
142
+ const noteDataProvider = await NoteDataProvider.create(store);
143
+ const taggingDataProvider = new TaggingDataProvider(store);
144
+ const capsuleDataProvider = new CapsuleDataProvider(store);
145
+ const keyStore = new KeyStore(store);
146
+ const accountDataProvider = new TXEAccountDataProvider(store);
147
+
148
+ // Register protocol contracts.
149
+ for (const { contractClass, instance, artifact } of protocolContracts) {
150
+ await contractDataProvider.addContractArtifact(contractClass.id, artifact);
151
+ await contractDataProvider.addContractInstance(instance);
152
+ }
153
+
154
+ const stateMachine = await TXEStateMachine.create(store);
155
+
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,
162
+ keyStore,
163
+ contractDataProvider,
164
+ noteDataProvider,
165
+ capsuleDataProvider,
166
+ stateMachine.syncDataProvider,
167
+ taggingDataProvider,
168
+ addressDataProvider,
169
+ privateEventDataProvider,
170
+ );
171
+
172
+ const topLevelOracleHandler = new TXEOracleTopLevelContext(
173
+ stateMachine,
174
+ contractDataProvider,
175
+ keyStore,
176
+ addressDataProvider,
177
+ accountDataProvider,
178
+ pxeOracleInterface,
179
+ nextBlockTimestamp,
180
+ version,
181
+ chainId,
182
+ new Map(),
183
+ );
184
+ await topLevelOracleHandler.txeAdvanceBlocksBy(1);
185
+
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
+ );
199
+ }
200
+
201
+ /**
202
+ * Processes an oracle function invoked by the Noir test associated to this session.
203
+ * @param functionName The name of the oracle.
204
+ * @param inputs The inputs of the oracle.
205
+ * @returns The oracle return values.
206
+ */
207
+ processFunction(functionName: TXEOracleFunctionName, inputs: ForeignCallArgs): Promise<ForeignCallResult> {
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
+ }
230
+ }
231
+
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
+ }
252
+ }
253
+
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}`);
269
+ }
270
+
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
+ });
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;
331
+ const globalVariables = makeGlobalVariables(undefined, {
332
+ blockNumber: latestBlockNumber + 1,
333
+ timestamp: this.nextBlockTimestamp,
334
+ version: this.version,
335
+ chainId: this.chainId,
336
+ });
337
+
338
+ this.oracleHandler = new TXEOraclePublicContext(
339
+ contractAddress ?? DEFAULT_ADDRESS,
340
+ await this.stateMachine.synchronizer.nativeWorldStateService.fork(),
341
+ getSingleTxBlockRequestHash(globalVariables.blockNumber),
342
+ globalVariables,
343
+ );
344
+
345
+ this.state = { name: 'PUBLIC' };
346
+ this.logger.debug(`Entered state ${this.state.name}`);
347
+ }
348
+
349
+ async enterUtilityState(contractAddress: AztecAddress = DEFAULT_ADDRESS) {
350
+ this.exitTopLevelState();
351
+
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);
358
+
359
+ this.oracleHandler = new UtilityExecutionOracle(contractAddress, [], [], this.pxeOracleInterface);
360
+
361
+ this.state = { name: 'UTILITY' };
362
+ this.logger.debug(`Entered state ${this.state.name}`);
363
+ }
364
+
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
+ }
381
+
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`);
385
+ }
386
+
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
+ }
422
+
423
+ const block = await (this.oracleHandler as TXEOraclePublicContext).close();
424
+ await this.stateMachine.handleL2Block(block);
425
+ }
426
+
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`);
430
+ }
431
+ }
432
+ }
@@ -1,3 +1,4 @@
1
+ import type { EthAddress } from '@aztec/foundation/eth-address';
1
2
  import { Fr } from '@aztec/foundation/fields';
2
3
  import { hexToBuffer } from '@aztec/foundation/string';
3
4
  import { type ContractArtifact, ContractArtifactSchema } from '@aztec/stdlib/abi';
@@ -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
  }
@@ -0,0 +1,36 @@
1
+ import type { ContractArtifact } from '@aztec/aztec.js/abi';
2
+ import { Fr } from '@aztec/aztec.js/fields';
3
+ import { ContractDataProvider } from '@aztec/pxe/server';
4
+
5
+ export type ContractArtifactWithHash = ContractArtifact & { artifactHash: Fr };
6
+
7
+ /*
8
+ * A contract data provider that stores contract artifacts with their hashes. Since
9
+ * TXE typically deploys the same contract again and again for multiple tests, caching
10
+ * the *very* expensive artifact hash computation improves testing speed significantly.
11
+ */
12
+ export class TXEContractDataProvider extends ContractDataProvider {
13
+ #artifactHashes: Map<string, Buffer> = new Map();
14
+
15
+ public override async addContractArtifact(
16
+ id: Fr,
17
+ artifact: ContractArtifact | ContractArtifactWithHash,
18
+ ): Promise<void> {
19
+ if ('artifactHash' in artifact) {
20
+ this.#artifactHashes.set(id.toString(), artifact.artifactHash.toBuffer());
21
+ }
22
+ await super.addContractArtifact(id, artifact);
23
+ }
24
+
25
+ public override async getContractArtifact(
26
+ contractClassId: Fr,
27
+ ): Promise<ContractArtifact | ContractArtifactWithHash | undefined> {
28
+ const artifact = await super.getContractArtifact(contractClassId);
29
+ if (artifact && this.#artifactHashes.has(contractClassId.toString())) {
30
+ (artifact as ContractArtifactWithHash).artifactHash = Fr.fromBuffer(
31
+ this.#artifactHashes.get(contractClassId.toString())!,
32
+ );
33
+ }
34
+ return artifact;
35
+ }
36
+ }