@aztec/txe 0.0.1-commit.7b97ef96e → 0.0.1-commit.7cbc774

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 (126) hide show
  1. package/dest/ContractClassRegistry-KKNT527R.js +3 -0
  2. package/dest/ContractClassRegistry-KKNT527R.js.map +7 -0
  3. package/dest/ContractInstanceRegistry-GSKBNL3Q.js +3 -0
  4. package/dest/ContractInstanceRegistry-GSKBNL3Q.js.map +7 -0
  5. package/dest/FeeJuice-GUJ5O6GB.js +3 -0
  6. package/dest/FeeJuice-GUJ5O6GB.js.map +7 -0
  7. package/dest/MultiCallEntrypoint-ZQPCKVKL.js +3 -0
  8. package/dest/MultiCallEntrypoint-ZQPCKVKL.js.map +7 -0
  9. package/dest/SchnorrAccount-QIXE5DXA.js +3 -0
  10. package/dest/SchnorrAccount-QIXE5DXA.js.map +7 -0
  11. package/dest/bin/check_txe_oracle_version.d.ts +2 -0
  12. package/dest/bin/check_txe_oracle_version.d.ts.map +1 -0
  13. package/dest/bin/check_txe_oracle_version.js +32 -0
  14. package/dest/bin/index.js +3 -30
  15. package/dest/bin/index.js.map +7 -0
  16. package/dest/chunk-BJVAAXNA.js +3 -0
  17. package/dest/chunk-BJVAAXNA.js.map +7 -0
  18. package/dest/chunk-DF6RMOC6.js +304 -0
  19. package/dest/chunk-DF6RMOC6.js.map +7 -0
  20. package/dest/chunk-PPJTNNUG.js +265 -0
  21. package/dest/chunk-PPJTNNUG.js.map +7 -0
  22. package/dest/constants.d.ts +3 -1
  23. package/dest/constants.d.ts.map +1 -1
  24. package/dest/constants.js +5 -0
  25. package/dest/dispatcher_pool.d.ts +67 -0
  26. package/dest/dispatcher_pool.d.ts.map +1 -0
  27. package/dest/dispatcher_pool.js +284 -0
  28. package/dest/index.d.ts +188 -7
  29. package/dest/index.d.ts.map +1 -1
  30. package/dest/index.js +160 -119
  31. package/dest/metafile.json +38147 -0
  32. package/dest/msgpackr_fr_extension.d.ts +2 -0
  33. package/dest/msgpackr_fr_extension.d.ts.map +1 -0
  34. package/dest/msgpackr_fr_extension.js +21 -0
  35. package/dest/oracle/interfaces.d.ts +40 -28
  36. package/dest/oracle/interfaces.d.ts.map +1 -1
  37. package/dest/oracle/txe_oracle_public_context.d.ts +18 -13
  38. package/dest/oracle/txe_oracle_public_context.d.ts.map +1 -1
  39. package/dest/oracle/txe_oracle_public_context.js +27 -12
  40. package/dest/oracle/txe_oracle_top_level_context.d.ts +38 -22
  41. package/dest/oracle/txe_oracle_top_level_context.d.ts.map +1 -1
  42. package/dest/oracle/txe_oracle_top_level_context.js +141 -72
  43. package/dest/oracle/txe_private_execution_oracle.d.ts +17 -0
  44. package/dest/oracle/txe_private_execution_oracle.d.ts.map +1 -0
  45. package/dest/oracle/txe_private_execution_oracle.js +15 -0
  46. package/dest/rpc_server.d.ts +14 -0
  47. package/dest/rpc_server.d.ts.map +1 -0
  48. package/dest/rpc_server.js +78 -0
  49. package/dest/rpc_translator.d.ts +139 -83
  50. package/dest/rpc_translator.d.ts.map +1 -1
  51. package/dest/rpc_translator.js +574 -238
  52. package/dest/server.bundle.js +3 -0
  53. package/dest/server.bundle.js.map +7 -0
  54. package/dest/state_machine/archiver.d.ts +4 -4
  55. package/dest/state_machine/archiver.d.ts.map +1 -1
  56. package/dest/state_machine/archiver.js +22 -20
  57. package/dest/state_machine/dummy_p2p_client.d.ts +14 -8
  58. package/dest/state_machine/dummy_p2p_client.d.ts.map +1 -1
  59. package/dest/state_machine/dummy_p2p_client.js +17 -5
  60. package/dest/state_machine/global_variable_builder.d.ts +9 -4
  61. package/dest/state_machine/global_variable_builder.d.ts.map +1 -1
  62. package/dest/state_machine/global_variable_builder.js +9 -3
  63. package/dest/state_machine/index.d.ts +7 -3
  64. package/dest/state_machine/index.d.ts.map +1 -1
  65. package/dest/state_machine/index.js +23 -5
  66. package/dest/state_machine/mock_epoch_cache.d.ts +18 -3
  67. package/dest/state_machine/mock_epoch_cache.d.ts.map +1 -1
  68. package/dest/state_machine/mock_epoch_cache.js +35 -2
  69. package/dest/state_machine/synchronizer.d.ts +5 -5
  70. package/dest/state_machine/synchronizer.d.ts.map +1 -1
  71. package/dest/state_machine/synchronizer.js +4 -4
  72. package/dest/txe_oracle_version.d.ts +17 -0
  73. package/dest/txe_oracle_version.d.ts.map +1 -0
  74. package/dest/txe_oracle_version.js +14 -0
  75. package/dest/txe_session.d.ts +69 -6
  76. package/dest/txe_session.d.ts.map +1 -1
  77. package/dest/txe_session.js +170 -35
  78. package/dest/utils/encoding.d.ts +191 -0
  79. package/dest/utils/encoding.d.ts.map +1 -0
  80. package/dest/{util → utils}/encoding.js +7 -2
  81. package/dest/{util → utils}/expected_failure_error.d.ts +1 -1
  82. package/dest/utils/expected_failure_error.d.ts.map +1 -0
  83. package/dest/{util → utils}/txe_account_store.d.ts +1 -1
  84. package/dest/utils/txe_account_store.d.ts.map +1 -0
  85. package/dest/utils/txe_public_contract_data_source.d.ts +20 -0
  86. package/dest/utils/txe_public_contract_data_source.d.ts.map +1 -0
  87. package/dest/{util → utils}/txe_public_contract_data_source.js +1 -3
  88. package/dest/worker.bundle.js +3 -0
  89. package/dest/worker.bundle.js.map +7 -0
  90. package/dest/worker.d.ts +2 -0
  91. package/dest/worker.d.ts.map +1 -0
  92. package/dest/worker.js +92 -0
  93. package/package.json +37 -21
  94. package/src/bin/check_txe_oracle_version.ts +37 -0
  95. package/src/bin/index.ts +11 -2
  96. package/src/constants.ts +6 -0
  97. package/src/dispatcher_pool.ts +316 -0
  98. package/src/index.ts +178 -126
  99. package/src/msgpackr_fr_extension.ts +23 -0
  100. package/src/oracle/interfaces.ts +48 -34
  101. package/src/oracle/txe_oracle_public_context.ts +42 -12
  102. package/src/oracle/txe_oracle_top_level_context.ts +176 -83
  103. package/src/oracle/txe_private_execution_oracle.ts +30 -0
  104. package/src/rpc_server.ts +87 -0
  105. package/src/rpc_translator.ts +654 -319
  106. package/src/state_machine/archiver.ts +33 -18
  107. package/src/state_machine/dummy_p2p_client.ts +32 -12
  108. package/src/state_machine/global_variable_builder.ts +18 -3
  109. package/src/state_machine/index.ts +25 -6
  110. package/src/state_machine/mock_epoch_cache.ts +46 -3
  111. package/src/state_machine/synchronizer.ts +5 -5
  112. package/src/txe_oracle_version.ts +17 -0
  113. package/src/txe_session.ts +269 -37
  114. package/src/{util → utils}/encoding.ts +8 -2
  115. package/src/{util → utils}/txe_public_contract_data_source.ts +0 -2
  116. package/src/worker.ts +98 -0
  117. package/dest/util/encoding.d.ts +0 -720
  118. package/dest/util/encoding.d.ts.map +0 -1
  119. package/dest/util/expected_failure_error.d.ts.map +0 -1
  120. package/dest/util/txe_account_store.d.ts.map +0 -1
  121. package/dest/util/txe_public_contract_data_source.d.ts +0 -20
  122. package/dest/util/txe_public_contract_data_source.d.ts.map +0 -1
  123. /package/dest/{util → utils}/expected_failure_error.js +0 -0
  124. /package/dest/{util → utils}/txe_account_store.js +0 -0
  125. /package/src/{util → utils}/expected_failure_error.ts +0 -0
  126. /package/src/{util → utils}/txe_account_store.ts +0 -0
@@ -2,11 +2,12 @@ import { BlockNumber } from '@aztec/foundation/branded-types';
2
2
  import { Fr } from '@aztec/foundation/curves/bn254';
3
3
  import { type Logger, createLogger } from '@aztec/foundation/log';
4
4
  import { KeyStore } from '@aztec/key-store';
5
- import { openTmpStore } from '@aztec/kv-store/lmdb-v2';
6
- import type { AccessScopes } from '@aztec/pxe/client/lazy';
5
+ import type { AztecAsyncKVStore } from '@aztec/kv-store';
6
+ import { openEphemeralStore } from '@aztec/kv-store/lmdb-v2';
7
7
  import {
8
8
  AddressStore,
9
9
  AnchorBlockStore,
10
+ CapsuleService,
10
11
  CapsuleStore,
11
12
  ContractStore,
12
13
  JobCoordinator,
@@ -24,7 +25,6 @@ import {
24
25
  type IPrivateExecutionOracle,
25
26
  type IUtilityExecutionOracle,
26
27
  Oracle,
27
- PrivateExecutionOracle,
28
28
  UtilityExecutionOracle,
29
29
  } from '@aztec/pxe/simulator';
30
30
  import {
@@ -35,28 +35,31 @@ import {
35
35
  resolveAssertionMessageFromError,
36
36
  toACVMWitness,
37
37
  } from '@aztec/simulator/client';
38
+ import { STANDARD_AUTH_REGISTRY_ADDRESS } from '@aztec/standard-contracts/auth-registry/constants';
38
39
  import { FunctionCall, FunctionSelector, FunctionType } from '@aztec/stdlib/abi';
39
40
  import type { AuthWitness } from '@aztec/stdlib/auth-witness';
40
41
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
41
- import { GasSettings } from '@aztec/stdlib/gas';
42
+ import type { GasSettings } from '@aztec/stdlib/gas';
42
43
  import { computeProtocolNullifier } from '@aztec/stdlib/hash';
43
44
  import { PrivateContextInputs } from '@aztec/stdlib/kernel';
44
45
  import { makeGlobalVariables } from '@aztec/stdlib/testing';
45
- import { CallContext, GlobalVariables, TxContext } from '@aztec/stdlib/tx';
46
+ import { CallContext, GlobalVariables, OFFCHAIN_MESSAGE_IDENTIFIER, TxContext } from '@aztec/stdlib/tx';
46
47
 
47
48
  import { z } from 'zod';
48
49
 
49
- import { DEFAULT_ADDRESS } from './constants.js';
50
+ import { DEFAULT_ADDRESS, MAX_OFFCHAIN_EFFECTS_PER_TXE_QUERY, MAX_OFFCHAIN_EFFECT_LEN } from './constants.js';
50
51
  import type { IAvmExecutionOracle, ITxeExecutionOracle } from './oracle/interfaces.js';
51
52
  import { TXEOraclePublicContext } from './oracle/txe_oracle_public_context.js';
52
53
  import { TXEOracleTopLevelContext } from './oracle/txe_oracle_top_level_context.js';
54
+ import { TXEPrivateExecutionOracle } from './oracle/txe_private_execution_oracle.js';
53
55
  import { RPCTranslator } from './rpc_translator.js';
54
56
  import { TXEArchiver } from './state_machine/archiver.js';
55
57
  import { TXEStateMachine } from './state_machine/index.js';
56
- import type { ForeignCallArgs, ForeignCallResult } from './util/encoding.js';
57
- import { TXEAccountStore } from './util/txe_account_store.js';
58
+ import { TXE_ORACLE_VERSION_MAJOR, TXE_ORACLE_VERSION_MINOR } from './txe_oracle_version.js';
58
59
  import { getSingleTxBlockRequestHash, insertTxEffectIntoWorldTrees, makeTXEBlock } from './utils/block_creation.js';
60
+ import type { ForeignCallArgs, ForeignCallResult } from './utils/encoding.js';
59
61
  import { makeTxEffect } from './utils/tx_effect_creation.js';
62
+ import { TXEAccountStore } from './utils/txe_account_store.js';
60
63
 
61
64
  /**
62
65
  * A TXE Session can be in one of four states, which change as the test progresses and different oracles are called.
@@ -109,10 +112,80 @@ export type TXEOracleFunctionName = Exclude<
109
112
  >;
110
113
 
111
114
  export interface TXESessionStateHandler {
115
+ /** Records the TXE oracle version reported by the Noir test code for diagnostics. */
116
+ setTxeOracleVersion(major: number, minor: number): void;
117
+
112
118
  enterTopLevelState(): Promise<void>;
113
119
  enterPublicState(contractAddress?: AztecAddress): Promise<void>;
114
- enterPrivateState(contractAddress?: AztecAddress, anchorBlockNumber?: BlockNumber): Promise<PrivateContextInputs>;
120
+ enterPrivateState(
121
+ contractAddress: AztecAddress | undefined,
122
+ anchorBlockNumber: BlockNumber | undefined,
123
+ gasSettings: GasSettings,
124
+ ): Promise<PrivateContextInputs>;
115
125
  enterUtilityState(contractAddress?: AztecAddress): Promise<void>;
126
+
127
+ // TODO(F-335): Exposing the job info is abstraction breakage - drop the following 2 functions.
128
+ cycleJob(): Promise<string>;
129
+ getCurrentJob(): string;
130
+
131
+ /**
132
+ * Runs an executor-style top-level call (private/public call, utility execution) with last-call tracking.
133
+ */
134
+ withTopLevelCallTracking<T>(work: () => Promise<{ result: T; txHash?: Fr }>): Promise<T>;
135
+
136
+ /**
137
+ * Captures a raw offchain effect payload for consumption from test environment. Called by the `emit_offchain_effect`
138
+ * oracle handler whenever a contract function emits an offchain message, at any call depth.
139
+ */
140
+ recordOffchainEffect(data: Fr[]): void;
141
+
142
+ /**
143
+ * Returns the raw offchain effect payloads emitted by the last top-level call. Each payload follows the protocol
144
+ * convention documented on `OFFCHAIN_MESSAGE_IDENTIFIER`, i.e. `[identifier, recipient, ...ciphertext]`. Decoding into
145
+ * `OffchainMessage` structs happens on the Noir side of the test helper. Marks the buffer as queried so the
146
+ * unqueried-messages warning doesn't fire on the next reset.
147
+ */
148
+ getLastCallOffchainEffects(): { effects: Fr[][] };
149
+
150
+ /**
151
+ * Returns the context of the last top-level call: its tx hash (`Fr.ZERO` if the call was tx-less) and the anchor
152
+ * block timestamp captured at the start of the call. Does *not* mark the buffer as queried — context reads are
153
+ * metadata, not effect consumption.
154
+ */
155
+ getLastCallContext(): { txHash: Fr; anchorBlockTimestamp: bigint };
156
+ }
157
+
158
+ /**
159
+ * Session state tracking the most recently completed top-level call: the offchain effect buffer it produced, and the
160
+ * call's context (tx hash + anchor block timestamp). The context is refreshed on every top-level call, independently
161
+ * of whether the call produced offchain effects.
162
+ */
163
+ interface LastCallState {
164
+ /**
165
+ * Raw offchain effect payloads emitted by the currently-executing (or most recently completed) top-level call. Wiped
166
+ * at the start of every top-level entry point, appended to on every `emit_offchain_effect` oracle invocation.
167
+ */
168
+ offchainEffects: Fr[][];
169
+ /**
170
+ * Tracks whether the test has queried `effects` since the last reset. If a new top-level call clobbers the buffer
171
+ * without it being queried first, any accumulated messages are lost and we emit a warning so tests don't silently
172
+ * drop delivery.
173
+ */
174
+ queried: boolean;
175
+ /**
176
+ * Tx hash of the most recently completed top-level call, or `Fr.ZERO` if the call was tx-less (context setters,
177
+ * utility execution). Populated by call executor handlers after execution completes.
178
+ */
179
+ txHash: Fr;
180
+ /**
181
+ * Anchor block timestamp of the most recently completed top-level call, captured from the anchor block header that
182
+ * was active when the call started. Populated by call executor handlers after execution completes.
183
+ */
184
+ anchorBlockTimestamp: bigint;
185
+ }
186
+
187
+ function emptyLastCallState(): LastCallState {
188
+ return { offchainEffects: [], queried: false, txHash: Fr.ZERO, anchorBlockTimestamp: 0n };
116
189
  }
117
190
 
118
191
  /**
@@ -122,9 +195,14 @@ export interface TXESessionStateHandler {
122
195
  export class TXESession implements TXESessionStateHandler {
123
196
  private state: SessionState = { name: 'TOP_LEVEL' };
124
197
  private authwits: Map<string, AuthWitness> = new Map();
198
+ private lastCallInfo: LastCallState = emptyLastCallState();
199
+ private txeOracleVersion: { major: number; minor: number } | undefined;
200
+
201
+ private disposed = false;
125
202
 
126
203
  constructor(
127
204
  private logger: Logger,
205
+ private sessionStore: AztecAsyncKVStore,
128
206
  private stateMachine: TXEStateMachine,
129
207
  private oracleHandler:
130
208
  | IUtilityExecutionOracle
@@ -148,8 +226,33 @@ export class TXESession implements TXESessionStateHandler {
148
226
  private nextBlockTimestamp: bigint,
149
227
  ) {}
150
228
 
229
+ /**
230
+ * Closes the per-session `txe-session` LMDB and the `NativeWorldStateService` .
231
+ * Called via IPC when the dispatcher detects the end of a test. Idempotent.
232
+ */
233
+ async dispose(): Promise<void> {
234
+ if (this.disposed) {
235
+ return;
236
+ }
237
+ this.disposed = true;
238
+ try {
239
+ await this.stateMachine.synchronizer.nativeWorldStateService.close();
240
+ } catch (err) {
241
+ this.logger.warn(`Error closing native world state during session dispose`, err);
242
+ }
243
+ try {
244
+ await this.sessionStore.close();
245
+ } catch (err) {
246
+ this.logger.warn(`Error closing session LMDB during dispose`, err);
247
+ }
248
+ }
249
+
151
250
  static async init(contractStore: ContractStore) {
152
- const store = await openTmpStore('txe-session');
251
+ // Size LMDB's reader slots to the libuv pool (capped to 2 in bin/index.ts via
252
+ // HARDWARE_CONCURRENCY): each native LMDB read needs a libuv worker thread to run, so any
253
+ // slot beyond the pool size would sit idle while still consuming a semaphore + reader-table
254
+ // entry per session.
255
+ const store = await openEphemeralStore('txe-session', undefined, 2);
153
256
 
154
257
  const addressStore = new AddressStore(store);
155
258
  const privateEventStore = new PrivateEventStore(store);
@@ -161,7 +264,6 @@ export class TXESession implements TXESessionStateHandler {
161
264
  const keyStore = new KeyStore(store);
162
265
  const accountStore = new TXEAccountStore(store);
163
266
 
164
- // Create job coordinator and register staged stores
165
267
  const jobCoordinator = new JobCoordinator(store);
166
268
  jobCoordinator.registerStores([
167
269
  capsuleStore,
@@ -181,6 +283,8 @@ export class TXESession implements TXESessionStateHandler {
181
283
 
182
284
  const initialJobId = jobCoordinator.beginJob();
183
285
 
286
+ const logger = createLogger('txe:session');
287
+
184
288
  const topLevelOracleHandler = new TXEOracleTopLevelContext(
185
289
  stateMachine,
186
290
  contractStore,
@@ -193,16 +297,17 @@ export class TXESession implements TXESessionStateHandler {
193
297
  senderAddressBookStore,
194
298
  capsuleStore,
195
299
  privateEventStore,
196
- initialJobId,
197
300
  nextBlockTimestamp,
198
301
  version,
199
302
  chainId,
200
303
  new Map(),
201
304
  );
202
- await topLevelOracleHandler.txeAdvanceBlocksBy(1);
305
+
306
+ await topLevelOracleHandler.mineDeploymentNullifiers([STANDARD_AUTH_REGISTRY_ADDRESS]);
203
307
 
204
308
  return new TXESession(
205
- createLogger('txe:session'),
309
+ logger,
310
+ store,
206
311
  stateMachine,
207
312
  topLevelOracleHandler,
208
313
  contractStore,
@@ -241,7 +346,28 @@ export class TXESession implements TXESessionStateHandler {
241
346
  return translator[validatedFunctionName](...inputs);
242
347
  } catch (error) {
243
348
  if (error instanceof z.ZodError) {
244
- throw new Error(`${functionName} does not correspond to any oracle handler available on RPCTranslator`);
349
+ let versionHint: string;
350
+ if (!this.txeOracleVersion) {
351
+ versionHint =
352
+ ' The test appears to use an older version of Aztec.nr that does not' +
353
+ ' support test environment oracle versioning. Update Aztec.nr to a compatible version.' +
354
+ ' See https://docs.aztec.network/errors/12';
355
+ } else if (this.txeOracleVersion.minor > TXE_ORACLE_VERSION_MINOR) {
356
+ versionHint =
357
+ ` The test uses Aztec.nr test oracle version` +
358
+ ` ${this.txeOracleVersion.major}.${this.txeOracleVersion.minor}, but this test environment` +
359
+ ` only supports up to ${TXE_ORACLE_VERSION_MAJOR}.${TXE_ORACLE_VERSION_MINOR}.` +
360
+ ` Upgrade the Aztec CLI to a compatible version.` +
361
+ ` See https://docs.aztec.network/errors/12`;
362
+ } else {
363
+ versionHint =
364
+ ` The test's oracle version (${this.txeOracleVersion.major}.${this.txeOracleVersion.minor})` +
365
+ ` is compatible with this test environment` +
366
+ ` (${TXE_ORACLE_VERSION_MAJOR}.${TXE_ORACLE_VERSION_MINOR}), so this oracle should be` +
367
+ ` available. This is an unexpected error, please report it.` +
368
+ ` See https://docs.aztec.network/errors/13`;
369
+ }
370
+ throw new Error(`Unknown oracle '${functionName}'.${versionHint}`);
245
371
  } else if (error instanceof Error) {
246
372
  throw new Error(
247
373
  `Execution error while processing function ${functionName} in state ${this.state.name}: ${error.message}`,
@@ -254,6 +380,86 @@ export class TXESession implements TXESessionStateHandler {
254
380
  }
255
381
  }
256
382
 
383
+ getCurrentJob(): string {
384
+ return this.currentJobId;
385
+ }
386
+
387
+ /** Commits the current job and begins a new one. Returns the new job ID. */
388
+ async cycleJob(): Promise<string> {
389
+ await this.jobCoordinator.commitJob(this.currentJobId);
390
+ this.currentJobId = this.jobCoordinator.beginJob();
391
+ return this.currentJobId;
392
+ }
393
+
394
+ private resetLastCall(): void {
395
+ const notQueriedMessageCount = this.lastCallInfo.queried
396
+ ? 0
397
+ : this.lastCallInfo.offchainEffects.filter(payload => payload[0]?.equals(OFFCHAIN_MESSAGE_IDENTIFIER)).length;
398
+ if (notQueriedMessageCount > 0) {
399
+ this.logger.warn(
400
+ `Dropping ${notQueriedMessageCount} unqueried offchain message(s) from the previous top-level call. ` +
401
+ `To deliver them, call \`env.offchain_messages()\` and forward the result to the recipient contract's ` +
402
+ `\`offchain_receive\` utility before issuing another top-level call. To intentionally discard, assign ` +
403
+ `to \`let _ = env.offchain_messages()\` to silence this warning.`,
404
+ );
405
+ }
406
+ this.lastCallInfo = emptyLastCallState();
407
+ }
408
+
409
+ recordOffchainEffect(data: Fr[]): void {
410
+ this.lastCallInfo.offchainEffects.push(data);
411
+ }
412
+
413
+ private setLastCallContext(txHash: Fr, anchorBlockTimestamp: bigint): void {
414
+ this.lastCallInfo.txHash = txHash;
415
+ this.lastCallInfo.anchorBlockTimestamp = anchorBlockTimestamp;
416
+ }
417
+
418
+ async withTopLevelCallTracking<T>(work: () => Promise<{ result: T; txHash?: Fr }>): Promise<T> {
419
+ this.resetLastCall();
420
+ // Capture the anchor *before* `work` runs: private/public executor calls mine a new block as a
421
+ // side effect, and that block's timestamp should not be attributed to this call's anchor.
422
+ const anchorBlockTimestamp = (await this.stateMachine.node.getBlockData('latest'))!.header.globalVariables
423
+ .timestamp;
424
+ const { result, txHash } = await work();
425
+ this.setLastCallContext(txHash ?? Fr.ZERO, anchorBlockTimestamp);
426
+ return result;
427
+ }
428
+
429
+ getLastCallOffchainEffects(): { effects: Fr[][] } {
430
+ this.lastCallInfo.queried = true;
431
+ const effects = this.lastCallInfo.offchainEffects;
432
+
433
+ if (effects.length > MAX_OFFCHAIN_EFFECTS_PER_TXE_QUERY) {
434
+ throw new Error(`${effects.length} offchain effects exceed max ${MAX_OFFCHAIN_EFFECTS_PER_TXE_QUERY}`);
435
+ }
436
+ if (effects.some(e => e.length > MAX_OFFCHAIN_EFFECT_LEN)) {
437
+ throw new Error(`Some offchain effect has length larger than max ${MAX_OFFCHAIN_EFFECT_LEN}`);
438
+ }
439
+
440
+ return { effects };
441
+ }
442
+
443
+ getLastCallContext(): { txHash: Fr; anchorBlockTimestamp: bigint } {
444
+ const { txHash, anchorBlockTimestamp } = this.lastCallInfo;
445
+ return { txHash, anchorBlockTimestamp };
446
+ }
447
+
448
+ setTxeOracleVersion(major: number, minor: number): void {
449
+ if (major !== TXE_ORACLE_VERSION_MAJOR) {
450
+ const hint =
451
+ major > TXE_ORACLE_VERSION_MAJOR
452
+ ? 'The test was compiled with a newer version of Aztec.nr than your test environment supports. Upgrade your test environment to a compatible version.'
453
+ : 'The test was compiled with an older version of Aztec.nr than your test environment supports. Recompile the test with a compatible version of Aztec.nr.';
454
+ throw new Error(
455
+ `Incompatible test environment version: ${hint} See https://docs.aztec.network/errors/12 (expected test oracle major version ${TXE_ORACLE_VERSION_MAJOR}, got ${major})`,
456
+ );
457
+ }
458
+
459
+ this.txeOracleVersion = { major, minor };
460
+ this.logger.debug(`Test compiled with test oracle version ${major}.${minor}`);
461
+ }
462
+
257
463
  async enterTopLevelState() {
258
464
  switch (this.state.name) {
259
465
  case 'PRIVATE': {
@@ -277,8 +483,7 @@ export class TXESession implements TXESessionStateHandler {
277
483
  }
278
484
 
279
485
  // 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();
486
+ await this.cycleJob();
282
487
 
283
488
  this.oracleHandler = new TXEOracleTopLevelContext(
284
489
  this.stateMachine,
@@ -292,7 +497,6 @@ export class TXESession implements TXESessionStateHandler {
292
497
  this.senderAddressBookStore,
293
498
  this.capsuleStore,
294
499
  this.privateEventStore,
295
- this.currentJobId,
296
500
  this.nextBlockTimestamp,
297
501
  this.version,
298
502
  this.chainId,
@@ -305,20 +509,22 @@ export class TXESession implements TXESessionStateHandler {
305
509
 
306
510
  async enterPrivateState(
307
511
  contractAddress: AztecAddress = DEFAULT_ADDRESS,
308
- anchorBlockNumber?: BlockNumber,
512
+ anchorBlockNumber: BlockNumber | undefined,
513
+ gasSettings: GasSettings,
309
514
  ): Promise<PrivateContextInputs> {
310
515
  this.exitTopLevelState();
516
+ this.resetLastCall();
311
517
 
312
518
  // Private execution has two associated block numbers: the anchor block (i.e. the historical block that is used to
313
519
  // build the proof), and the *next* block, i.e. the one we'll create once the execution ends, and which will contain
314
520
  // a single transaction with the effects of what was done in the test.
315
- const anchorBlock = await this.stateMachine.node.getBlockHeader(anchorBlockNumber ?? 'latest');
521
+ const anchorBlock = await this.stateMachine.node.getBlock(anchorBlockNumber ?? 'latest').then(b => b?.header);
316
522
 
317
523
  await new NoteService(this.noteStore, this.stateMachine.node, anchorBlock!, this.currentJobId).syncNoteNullifiers(
318
524
  contractAddress,
319
- 'ALL_SCOPES',
525
+ await this.keyStore.getAccounts(),
320
526
  );
321
- const latestBlock = await this.stateMachine.node.getBlockHeader('latest');
527
+ const latestBlock = await this.stateMachine.node.getBlock('latest').then(b => b?.header);
322
528
 
323
529
  const nextBlockGlobalVariables = makeGlobalVariables(undefined, {
324
530
  blockNumber: BlockNumber(latestBlock!.globalVariables.blockNumber + 1),
@@ -333,9 +539,9 @@ export class TXESession implements TXESessionStateHandler {
333
539
  const taggingIndexCache = new ExecutionTaggingIndexCache();
334
540
 
335
541
  const utilityExecutor = this.utilityExecutorForContractSync(anchorBlock);
336
- this.oracleHandler = new PrivateExecutionOracle({
542
+ this.oracleHandler = new TXEPrivateExecutionOracle({
337
543
  argsHash: Fr.ZERO,
338
- txContext: new TxContext(this.chainId, this.version, GasSettings.empty()),
544
+ txContext: new TxContext(this.chainId, this.version, gasSettings),
339
545
  callContext: new CallContext(AztecAddress.ZERO, contractAddress, FunctionSelector.empty(), false),
340
546
  anchorBlockHeader: anchorBlock!,
341
547
  utilityExecutor,
@@ -352,11 +558,14 @@ export class TXESession implements TXESessionStateHandler {
352
558
  senderTaggingStore: this.senderTaggingStore,
353
559
  recipientTaggingStore: this.recipientTaggingStore,
354
560
  senderAddressBookStore: this.senderAddressBookStore,
355
- capsuleStore: this.capsuleStore,
561
+ capsuleService: new CapsuleService(this.capsuleStore, await this.keyStore.getAccounts()),
356
562
  privateEventStore: this.privateEventStore,
357
563
  contractSyncService: this.stateMachine.contractSyncService,
564
+ l2TipsStore: this.stateMachine.l2TipsProvider,
358
565
  jobId: this.currentJobId,
359
- scopes: 'ALL_SCOPES',
566
+ scopes: await this.keyStore.getAccounts(),
567
+ messageContextService: this.stateMachine.messageContextService,
568
+ simulator: new WASMSimulator(),
360
569
  });
361
570
 
362
571
  // We store the note and tagging index caches fed into the PrivateExecutionOracle (along with some other auxiliary
@@ -367,17 +576,22 @@ export class TXESession implements TXESessionStateHandler {
367
576
  this.state = { name: 'PRIVATE', nextBlockGlobalVariables, noteCache, taggingIndexCache };
368
577
  this.logger.debug(`Entered state ${this.state.name}`);
369
578
 
370
- return (this.oracleHandler as PrivateExecutionOracle).getPrivateContextInputs();
579
+ // Record the *resolved* anchor's timestamp — if the caller pinned the anchor to a past block
580
+ // via `anchorBlockNumber`, "latest" would be the wrong anchor for offchain-message semantics.
581
+ this.setLastCallContext(Fr.ZERO, anchorBlock!.globalVariables.timestamp);
582
+
583
+ return (this.oracleHandler as TXEPrivateExecutionOracle).getPrivateContextInputs();
371
584
  }
372
585
 
373
586
  async enterPublicState(contractAddress?: AztecAddress) {
374
587
  this.exitTopLevelState();
588
+ this.resetLastCall();
375
589
 
376
590
  // The PublicContext will create a block with a single transaction in it, containing the effects of what was done in
377
591
  // the test. The block therefore gets the *next* block number and timestamp.
378
- const latestBlockNumber = (await this.stateMachine.node.getBlockHeader('latest'))!.globalVariables.blockNumber;
592
+ const latestHeader = (await this.stateMachine.node.getBlockData('latest'))!.header;
379
593
  const globalVariables = makeGlobalVariables(undefined, {
380
- blockNumber: BlockNumber(latestBlockNumber + 1),
594
+ blockNumber: BlockNumber(latestHeader.globalVariables.blockNumber + 1),
381
595
  timestamp: this.nextBlockTimestamp,
382
596
  version: this.version,
383
597
  chainId: this.chainId,
@@ -392,10 +606,14 @@ export class TXESession implements TXESessionStateHandler {
392
606
 
393
607
  this.state = { name: 'PUBLIC' };
394
608
  this.logger.debug(`Entered state ${this.state.name}`);
609
+
610
+ // Public state is anchored at the latest block.
611
+ this.setLastCallContext(Fr.ZERO, latestHeader.globalVariables.timestamp);
395
612
  }
396
613
 
397
614
  async enterUtilityState(contractAddress: AztecAddress = DEFAULT_ADDRESS) {
398
615
  this.exitTopLevelState();
616
+ this.resetLastCall();
399
617
 
400
618
  const anchorBlockHeader = await this.stateMachine.anchorBlockStore.getBlockHeader();
401
619
 
@@ -409,7 +627,7 @@ export class TXESession implements TXESessionStateHandler {
409
627
  this.stateMachine.node,
410
628
  anchorBlockHeader,
411
629
  this.currentJobId,
412
- ).syncNoteNullifiers(contractAddress, 'ALL_SCOPES');
630
+ ).syncNoteNullifiers(contractAddress, await this.keyStore.getAccounts());
413
631
 
414
632
  this.oracleHandler = new UtilityExecutionOracle({
415
633
  contractAddress,
@@ -423,14 +641,22 @@ export class TXESession implements TXESessionStateHandler {
423
641
  aztecNode: this.stateMachine.node,
424
642
  recipientTaggingStore: this.recipientTaggingStore,
425
643
  senderAddressBookStore: this.senderAddressBookStore,
426
- capsuleStore: this.capsuleStore,
644
+ capsuleService: new CapsuleService(this.capsuleStore, await this.keyStore.getAccounts()),
427
645
  privateEventStore: this.privateEventStore,
646
+ messageContextService: this.stateMachine.messageContextService,
647
+ contractSyncService: this.stateMachine.contractSyncService,
648
+ l2TipsStore: this.stateMachine.l2TipsProvider,
428
649
  jobId: this.currentJobId,
429
- scopes: 'ALL_SCOPES',
650
+ scopes: await this.keyStore.getAccounts(),
651
+ simulator: new WASMSimulator(),
652
+ utilityExecutor: this.utilityExecutorForContractSync(anchorBlockHeader),
430
653
  });
431
654
 
432
655
  this.state = { name: 'UTILITY' };
433
656
  this.logger.debug(`Entered state ${this.state.name}`);
657
+
658
+ // Utility state anchors at whatever the anchor block store is pointing to (tracked as latest).
659
+ this.setLastCallContext(Fr.ZERO, anchorBlockHeader.globalVariables.timestamp);
434
660
  }
435
661
 
436
662
  private exitTopLevelState() {
@@ -440,8 +666,8 @@ export class TXESession implements TXESessionStateHandler {
440
666
 
441
667
  // Note that while all public and private contexts do is build a single block that we then process when exiting
442
668
  // 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
669
+ // others, it will create empty blocks (via `advanceBlocksBy` and `deploy`), create blocks with transactions via
670
+ // `privateCallNewFlow` and `publicCallNewFlow`, add accounts to PXE via `addAccount`, etc. This is a
445
671
  // slight inconsistency in the working model of this class, but is not too bad.
446
672
  // TODO: it's quite unfortunate that we need to capture the authwits created to later pass them again when the top
447
673
  // level context is re-created. This is because authwits create a temporary utility context that'd otherwise reset
@@ -495,13 +721,14 @@ export class TXESession implements TXESessionStateHandler {
495
721
  }
496
722
 
497
723
  private utilityExecutorForContractSync(anchorBlock: any) {
498
- return async (call: FunctionCall, scopes: AccessScopes) => {
724
+ return async (call: FunctionCall, scopes: AztecAddress[]) => {
499
725
  const entryPointArtifact = await this.contractStore.getFunctionArtifactWithDebugMetadata(call.to, call.selector);
500
726
  if (entryPointArtifact.functionType !== FunctionType.UTILITY) {
501
727
  throw new Error(`Cannot run ${entryPointArtifact.functionType} function as utility`);
502
728
  }
503
729
 
504
730
  try {
731
+ const simulator = new WASMSimulator();
505
732
  const oracle = new UtilityExecutionOracle({
506
733
  contractAddress: call.to,
507
734
  authWitnesses: [],
@@ -514,12 +741,17 @@ export class TXESession implements TXESessionStateHandler {
514
741
  aztecNode: this.stateMachine.node,
515
742
  recipientTaggingStore: this.recipientTaggingStore,
516
743
  senderAddressBookStore: this.senderAddressBookStore,
517
- capsuleStore: this.capsuleStore,
744
+ capsuleService: new CapsuleService(this.capsuleStore, scopes),
518
745
  privateEventStore: this.privateEventStore,
746
+ messageContextService: this.stateMachine.messageContextService,
747
+ contractSyncService: this.stateMachine.contractSyncService,
748
+ l2TipsStore: this.stateMachine.l2TipsProvider,
519
749
  jobId: this.currentJobId,
520
750
  scopes,
751
+ simulator,
752
+ utilityExecutor: this.utilityExecutorForContractSync(anchorBlock),
521
753
  });
522
- await new WASMSimulator()
754
+ await simulator
523
755
  .executeUserCircuit(toACVMWitness(0, call.args), entryPointArtifact, new Oracle(oracle).toACIRCallback())
524
756
  .catch((err: Error) => {
525
757
  err.message = resolveAssertionMessageFromError(err, entryPointArtifact);
@@ -3,6 +3,7 @@ import type { EthAddress } from '@aztec/foundation/eth-address';
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';
6
+ import { BlockHash } from '@aztec/stdlib/block';
6
7
  import { type ContractInstanceWithAddress, ContractInstanceWithAddressSchema } from '@aztec/stdlib/contract';
7
8
 
8
9
  import { z } from 'zod';
@@ -25,6 +26,10 @@ export function addressFromSingle(obj: ForeignCallSingle) {
25
26
  return new AztecAddress(fromSingle(obj));
26
27
  }
27
28
 
29
+ export function blockHashFromSingle(obj: ForeignCallSingle) {
30
+ return new BlockHash(fromSingle(obj));
31
+ }
32
+
28
33
  export function fromArray(obj: ForeignCallArray) {
29
34
  return obj.map(str => Fr.fromBuffer(hexToBuffer(str)));
30
35
  }
@@ -142,9 +147,10 @@ export function arrayOfArraysToBoundedVecOfArrays(
142
147
 
143
148
  const numFieldsToPad = maxLen * nestedArrayLength - flattenedStorage.length;
144
149
 
145
- const flattenedStorageWithPadding = flattenedStorage.concat(Array(numFieldsToPad).fill(new Fr(0)));
150
+ // Pad with hex-encoded zeros so the result is uniformly `ForeignCallSingle` (string); raw Fr
151
+ // instances would JSON-serialize as `{ asBigInt: "0" }` and nargo would reject the response.
152
+ const flattenedStorageWithPadding = flattenedStorage.concat(toArray(Array(numFieldsToPad).fill(new Fr(0))));
146
153
 
147
- // At last we get the actual length of the BoundedVec and return the values.
148
154
  const len = toSingle(new Fr(bVecStorage.length));
149
155
  return [flattenedStorageWithPadding, len];
150
156
  }
@@ -26,8 +26,6 @@ export class TXEPublicContractDataSource implements ContractDataSource {
26
26
  packedBytecode: contractClass.packedBytecode,
27
27
  privateFunctionsRoot: contractClass.privateFunctionsRoot,
28
28
  version: contractClass.version,
29
- privateFunctions: [],
30
- utilityFunctions: [],
31
29
  };
32
30
  }
33
31
 
package/src/worker.ts ADDED
@@ -0,0 +1,98 @@
1
+ import { BackendType, Barretenberg, BarretenbergSync } from '@aztec/bb.js';
2
+ import { type Logger, createLogger } from '@aztec/foundation/log';
3
+
4
+ import { parentPort, workerData } from 'node:worker_threads';
5
+
6
+ // Importing `./index.js` registers the msgpackr Fr extension transitively (via
7
+ // ./msgpackr_fr_extension.js); this must happen before any `sendMessage` call.
8
+ import { TXEDispatcher, type TXEDispatcherOptions, type TXEForeignCallInput, activeSessionCount } from './index.js';
9
+
10
+ // Seed both bb.js singletons with the WASM backend before any crypto call. `initSingleton`
11
+ // binds the singleton to whichever backend the first call requests, so this pre-empts the
12
+ // implicit `Barretenberg.initSingleton()` inside `poseidon2Hash` from `@aztec/foundation/crypto`.
13
+ // TXE only needs hashing (no proving, no verification), so WASM is sufficient and
14
+ // `skipSrsInit: true` skips the CRS load. `threads: 1` keeps the WASM backend on a single
15
+ // thread — additional threads would each spawn a nested worker_thread, multiplying memory cost
16
+ // per pool worker.
17
+ void Barretenberg.initSingleton({ backend: BackendType.Wasm, skipSrsInit: true, threads: 1 });
18
+ void BarretenbergSync.initSingleton({ backend: BackendType.Wasm });
19
+
20
+ if (!parentPort) {
21
+ throw new Error('worker.ts must be loaded as a worker_thread');
22
+ }
23
+
24
+ const port = parentPort;
25
+ const logger: Logger = createLogger('txe:worker');
26
+
27
+ // The pool builds a template LMDB containing the protocol contracts + the SchnorrAccount
28
+ // artifact on the main thread and passes its data dir via `workerData`. The dispatcher clones
29
+ // that LMDB into a per-worker store on first use, so this worker gets a writable copy already
30
+ // populated.
31
+ const dispatcherOpts: TXEDispatcherOptions = {
32
+ contractStoreSourceDir: workerData.contractStoreSourceDir,
33
+ schnorrClassId: workerData.schnorrClassId,
34
+ };
35
+ const dispatcher = new TXEDispatcher(logger, dispatcherOpts);
36
+
37
+ interface ForeignCallRequest {
38
+ type: 'foreign-call';
39
+ requestId: number;
40
+ callData: TXEForeignCallInput;
41
+ }
42
+
43
+ interface DisposeSessionMessage {
44
+ type: 'dispose-session';
45
+ sessionId: number;
46
+ }
47
+
48
+ type IncomingMessage = ForeignCallRequest | DisposeSessionMessage;
49
+
50
+ interface SerializedError {
51
+ message: string;
52
+ name?: string;
53
+ stack?: string;
54
+ }
55
+
56
+ function serializeError(err: unknown): SerializedError {
57
+ if (err instanceof Error) {
58
+ return { message: err.message, name: err.name, stack: err.stack };
59
+ }
60
+ return { message: String(err) };
61
+ }
62
+
63
+ // Periodic memstat for diagnostic builds — set TXE_WORKER_MEMSTAT=1 to enable. Posts JS-heap
64
+ // breakdown + active-session count back to the dispatcher so we can attribute RSS growth
65
+ // between V8 heap (would show in heapUsed) and native (LMDB / world-state / WASM).
66
+ if (process.env.TXE_WORKER_MEMSTAT === '1') {
67
+ setInterval(() => {
68
+ const m = process.memoryUsage();
69
+ port.postMessage({
70
+ type: 'memstat',
71
+ sessions: activeSessionCount(),
72
+ rss: m.rss,
73
+ heapTotal: m.heapTotal,
74
+ heapUsed: m.heapUsed,
75
+ external: m.external,
76
+ arrayBuffers: m.arrayBuffers,
77
+ });
78
+ }, 2000).unref();
79
+ }
80
+
81
+ port.on('message', (msg: IncomingMessage) => {
82
+ switch (msg.type) {
83
+ case 'foreign-call':
84
+ void (async () => {
85
+ try {
86
+ const value = await dispatcher.resolve_foreign_call(msg.callData);
87
+ port.postMessage({ type: 'result', requestId: msg.requestId, ok: true, value });
88
+ } catch (err) {
89
+ port.postMessage({ type: 'result', requestId: msg.requestId, ok: false, error: serializeError(err) });
90
+ }
91
+ })();
92
+ return;
93
+ case 'dispose-session':
94
+ // Fire-and-forget; the main thread does not wait for confirmation.
95
+ void dispatcher.disposeSession(msg.sessionId).catch(err => logger.warn(`disposeSession failed`, err));
96
+ return;
97
+ }
98
+ });