@aztec/txe 0.0.1-commit.d3ec352c → 0.0.1-commit.d58ff9d0

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 (175) hide show
  1. package/dest/AuthRegistry-QVGDDH5X.js +3 -0
  2. package/dest/AuthRegistry-QVGDDH5X.js.map +7 -0
  3. package/dest/ContractClassRegistry-VWR3F42P.js +3 -0
  4. package/dest/ContractClassRegistry-VWR3F42P.js.map +7 -0
  5. package/dest/ContractInstanceRegistry-FHIWE33X.js +3 -0
  6. package/dest/ContractInstanceRegistry-FHIWE33X.js.map +7 -0
  7. package/dest/FeeJuice-SAOWVGG7.js +3 -0
  8. package/dest/FeeJuice-SAOWVGG7.js.map +7 -0
  9. package/dest/HandshakeRegistry-GY5CPEPS.js +3 -0
  10. package/dest/HandshakeRegistry-GY5CPEPS.js.map +7 -0
  11. package/dest/MultiCallEntrypoint-QG5H33ZZ.js +3 -0
  12. package/dest/MultiCallEntrypoint-QG5H33ZZ.js.map +7 -0
  13. package/dest/SchnorrAccount-NME3E45O.js +3 -0
  14. package/dest/SchnorrAccount-NME3E45O.js.map +7 -0
  15. package/dest/SchnorrInitializerlessAccount-WTGXU6SW.js +3 -0
  16. package/dest/SchnorrInitializerlessAccount-WTGXU6SW.js.map +7 -0
  17. package/dest/bin/check_txe_oracle_version.d.ts +2 -0
  18. package/dest/bin/check_txe_oracle_version.d.ts.map +1 -0
  19. package/dest/bin/check_txe_oracle_version.js +53 -0
  20. package/dest/bin/index.js +3 -30
  21. package/dest/bin/index.js.map +7 -0
  22. package/dest/bin/oracle_test_server.d.ts +3 -0
  23. package/dest/bin/oracle_test_server.d.ts.map +1 -0
  24. package/dest/bin/oracle_test_server.js +41 -0
  25. package/dest/chunk-32UHX7YY.js +3 -0
  26. package/dest/chunk-32UHX7YY.js.map +7 -0
  27. package/dest/chunk-GSUKUCKV.js +260 -0
  28. package/dest/chunk-GSUKUCKV.js.map +7 -0
  29. package/dest/chunk-UP4KKUVA.js +304 -0
  30. package/dest/chunk-UP4KKUVA.js.map +7 -0
  31. package/dest/constants.d.ts +7 -0
  32. package/dest/constants.d.ts.map +1 -0
  33. package/dest/constants.js +10 -0
  34. package/dest/dispatcher_pool.d.ts +67 -0
  35. package/dest/dispatcher_pool.d.ts.map +1 -0
  36. package/dest/dispatcher_pool.js +286 -0
  37. package/dest/index.d.ts +51 -7
  38. package/dest/index.d.ts.map +1 -1
  39. package/dest/index.js +75 -158
  40. package/dest/metafile.json +38759 -0
  41. package/dest/msgpackr_fr_extension.d.ts +2 -0
  42. package/dest/msgpackr_fr_extension.d.ts.map +1 -0
  43. package/dest/msgpackr_fr_extension.js +21 -0
  44. package/dest/oracle/interfaces.d.ts +71 -30
  45. package/dest/oracle/interfaces.d.ts.map +1 -1
  46. package/dest/oracle/tagging_secret_strategy.d.ts +12 -0
  47. package/dest/oracle/tagging_secret_strategy.d.ts.map +1 -0
  48. package/dest/oracle/tagging_secret_strategy.js +12 -0
  49. package/dest/oracle/test-resolver/default_fixtures.d.ts +16 -0
  50. package/dest/oracle/test-resolver/default_fixtures.d.ts.map +1 -0
  51. package/dest/oracle/test-resolver/default_fixtures.js +200 -0
  52. package/dest/oracle/test-resolver/index.d.ts +9 -0
  53. package/dest/oracle/test-resolver/index.d.ts.map +1 -0
  54. package/dest/oracle/test-resolver/index.js +32 -0
  55. package/dest/oracle/test-resolver/resolver.d.ts +48 -0
  56. package/dest/oracle/test-resolver/resolver.d.ts.map +1 -0
  57. package/dest/oracle/test-resolver/resolver.js +181 -0
  58. package/dest/oracle/txe_oracle_public_context.d.ts +40 -16
  59. package/dest/oracle/txe_oracle_public_context.d.ts.map +1 -1
  60. package/dest/oracle/txe_oracle_public_context.js +69 -23
  61. package/dest/oracle/txe_oracle_registry.d.ts +172 -0
  62. package/dest/oracle/txe_oracle_registry.d.ts.map +1 -0
  63. package/dest/oracle/txe_oracle_registry.js +767 -0
  64. package/dest/oracle/txe_oracle_top_level_context.d.ts +79 -30
  65. package/dest/oracle/txe_oracle_top_level_context.d.ts.map +1 -1
  66. package/dest/oracle/txe_oracle_top_level_context.js +653 -285
  67. package/dest/oracle/txe_oracle_version.d.ts +17 -0
  68. package/dest/oracle/txe_oracle_version.d.ts.map +1 -0
  69. package/dest/oracle/txe_oracle_version.js +14 -0
  70. package/dest/oracle/txe_private_execution_oracle.d.ts +17 -0
  71. package/dest/oracle/txe_private_execution_oracle.d.ts.map +1 -0
  72. package/dest/oracle/txe_private_execution_oracle.js +15 -0
  73. package/dest/rpc_server.d.ts +14 -0
  74. package/dest/rpc_server.d.ts.map +1 -0
  75. package/dest/rpc_server.js +78 -0
  76. package/dest/rpc_translator.d.ts +115 -216
  77. package/dest/rpc_translator.d.ts.map +1 -1
  78. package/dest/rpc_translator.js +901 -560
  79. package/dest/server.bundle.js +3 -0
  80. package/dest/server.bundle.js.map +7 -0
  81. package/dest/state_machine/archiver.d.ts +23 -58
  82. package/dest/state_machine/archiver.d.ts.map +1 -1
  83. package/dest/state_machine/archiver.js +76 -112
  84. package/dest/state_machine/dummy_p2p_client.d.ts +31 -17
  85. package/dest/state_machine/dummy_p2p_client.d.ts.map +1 -1
  86. package/dest/state_machine/dummy_p2p_client.js +63 -25
  87. package/dest/state_machine/global_variable_builder.d.ts +10 -5
  88. package/dest/state_machine/global_variable_builder.d.ts.map +1 -1
  89. package/dest/state_machine/global_variable_builder.js +20 -5
  90. package/dest/state_machine/index.d.ts +14 -8
  91. package/dest/state_machine/index.d.ts.map +1 -1
  92. package/dest/state_machine/index.js +84 -27
  93. package/dest/state_machine/mock_epoch_cache.d.ts +24 -8
  94. package/dest/state_machine/mock_epoch_cache.d.ts.map +1 -1
  95. package/dest/state_machine/mock_epoch_cache.js +43 -9
  96. package/dest/state_machine/synchronizer.d.ts +14 -6
  97. package/dest/state_machine/synchronizer.d.ts.map +1 -1
  98. package/dest/state_machine/synchronizer.js +23 -10
  99. package/dest/txe_session.d.ts +102 -20
  100. package/dest/txe_session.d.ts.map +1 -1
  101. package/dest/txe_session.js +442 -75
  102. package/dest/utils/block_creation.d.ts +20 -6
  103. package/dest/utils/block_creation.d.ts.map +1 -1
  104. package/dest/utils/block_creation.js +40 -6
  105. package/dest/utils/encoding.d.ts +192 -0
  106. package/dest/utils/encoding.d.ts.map +1 -0
  107. package/dest/{util → utils}/encoding.js +8 -3
  108. package/dest/{util → utils}/expected_failure_error.d.ts +1 -1
  109. package/dest/utils/expected_failure_error.d.ts.map +1 -0
  110. package/dest/utils/tx_effect_creation.d.ts +2 -3
  111. package/dest/utils/tx_effect_creation.d.ts.map +1 -1
  112. package/dest/utils/tx_effect_creation.js +3 -7
  113. package/dest/utils/txe_account_store.d.ts +10 -0
  114. package/dest/utils/txe_account_store.d.ts.map +1 -0
  115. package/dest/{util/txe_account_data_provider.js → utils/txe_account_store.js} +1 -1
  116. package/dest/utils/txe_artifact_resolver.d.ts +37 -0
  117. package/dest/utils/txe_artifact_resolver.d.ts.map +1 -0
  118. package/dest/utils/txe_artifact_resolver.js +161 -0
  119. package/dest/utils/txe_public_contract_data_source.d.ts +20 -0
  120. package/dest/utils/txe_public_contract_data_source.d.ts.map +1 -0
  121. package/dest/utils/txe_public_contract_data_source.js +51 -0
  122. package/dest/worker.bundle.js +3 -0
  123. package/dest/worker.bundle.js.map +7 -0
  124. package/dest/worker.d.ts +2 -0
  125. package/dest/worker.d.ts.map +1 -0
  126. package/dest/worker.js +92 -0
  127. package/package.json +39 -22
  128. package/src/bin/check_txe_oracle_version.ts +67 -0
  129. package/src/bin/index.ts +11 -2
  130. package/src/bin/oracle_test_server.ts +51 -0
  131. package/src/constants.ts +13 -0
  132. package/src/dispatcher_pool.ts +317 -0
  133. package/src/index.ts +113 -201
  134. package/src/msgpackr_fr_extension.ts +23 -0
  135. package/src/oracle/interfaces.ts +77 -35
  136. package/src/oracle/tagging_secret_strategy.ts +25 -0
  137. package/src/oracle/test-resolver/default_fixtures.ts +271 -0
  138. package/src/oracle/test-resolver/index.ts +44 -0
  139. package/src/oracle/test-resolver/resolver.ts +245 -0
  140. package/src/oracle/txe_oracle_public_context.ts +82 -27
  141. package/src/oracle/txe_oracle_registry.ts +556 -0
  142. package/src/oracle/txe_oracle_top_level_context.ts +555 -189
  143. package/src/oracle/txe_oracle_version.ts +17 -0
  144. package/src/oracle/txe_private_execution_oracle.ts +30 -0
  145. package/src/rpc_server.ts +87 -0
  146. package/src/rpc_translator.ts +1115 -923
  147. package/src/state_machine/archiver.ts +81 -132
  148. package/src/state_machine/dummy_p2p_client.ts +96 -38
  149. package/src/state_machine/global_variable_builder.ts +28 -10
  150. package/src/state_machine/index.ts +118 -44
  151. package/src/state_machine/mock_epoch_cache.ts +53 -14
  152. package/src/state_machine/synchronizer.ts +32 -12
  153. package/src/txe_session.ts +727 -123
  154. package/src/utils/block_creation.ts +50 -16
  155. package/src/{util → utils}/encoding.ts +9 -3
  156. package/src/utils/tx_effect_creation.ts +3 -13
  157. package/src/{util/txe_account_data_provider.ts → utils/txe_account_store.ts} +1 -1
  158. package/src/utils/txe_artifact_resolver.ts +217 -0
  159. package/src/utils/txe_public_contract_data_source.ts +60 -0
  160. package/src/worker.ts +98 -0
  161. package/dest/util/encoding.d.ts +0 -121
  162. package/dest/util/encoding.d.ts.map +0 -1
  163. package/dest/util/expected_failure_error.d.ts.map +0 -1
  164. package/dest/util/txe_account_data_provider.d.ts +0 -10
  165. package/dest/util/txe_account_data_provider.d.ts.map +0 -1
  166. package/dest/util/txe_contract_data_provider.d.ts +0 -12
  167. package/dest/util/txe_contract_data_provider.d.ts.map +0 -1
  168. package/dest/util/txe_contract_data_provider.js +0 -22
  169. package/dest/util/txe_public_contract_data_source.d.ts +0 -21
  170. package/dest/util/txe_public_contract_data_source.d.ts.map +0 -1
  171. package/dest/util/txe_public_contract_data_source.js +0 -67
  172. package/src/util/txe_contract_data_provider.ts +0 -36
  173. package/src/util/txe_public_contract_data_source.ts +0 -86
  174. /package/dest/{util → utils}/expected_failure_error.js +0 -0
  175. /package/src/{util → utils}/expected_failure_error.ts +0 -0
@@ -1,84 +1,171 @@
1
1
  import { BlockNumber } from '@aztec/foundation/branded-types';
2
- import { Fr } from '@aztec/foundation/fields';
2
+ import { Fr } from '@aztec/foundation/curves/bn254';
3
3
  import { createLogger } from '@aztec/foundation/log';
4
4
  import { KeyStore } from '@aztec/key-store';
5
- import { openTmpStore } from '@aztec/kv-store/lmdb-v2';
6
- import { AddressDataProvider, CapsuleDataProvider, NoteDataProvider, PXEOracleInterface, PrivateEventDataProvider, TaggingDataProvider } from '@aztec/pxe/server';
7
- import { ExecutionNoteCache, ExecutionTaggingIndexCache, HashedValuesCache, PrivateExecutionOracle, UtilityExecutionOracle } from '@aztec/pxe/simulator';
8
- import { FunctionSelector } from '@aztec/stdlib/abi';
5
+ import { openEphemeralStore } from '@aztec/kv-store/lmdb-v2';
6
+ import { AddressStore, AnchorBlockStore, AnchoredContractData, CapsuleService, CapsuleStore, FactService, FactStore, JobCoordinator, NoteService, NoteStore, PrivateEventStore, RecipientTaggingStore, SenderTaggingStore, TaggingSecretSourcesStore, composeHooks } from '@aztec/pxe/server';
7
+ import { ExecutionNoteCache, ExecutionTaggingIndexCache, HashedValuesCache, LEGACY_ORACLE_REGISTRY, TransientArrayService, UtilityExecutionOracle, buildACIRCallback } from '@aztec/pxe/simulator';
8
+ import { ExecutionError, WASMSimulator, createSimulationError, extractCallStack, resolveAssertionMessageFromError, toACVMWitness } from '@aztec/simulator/client';
9
+ import { STANDARD_AUTH_REGISTRY_ADDRESS } from '@aztec/standard-contracts/auth-registry/constants';
10
+ import { FunctionSelector, FunctionType } from '@aztec/stdlib/abi';
9
11
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
10
- import { Body, L2Block } from '@aztec/stdlib/block';
11
- import { GasSettings } from '@aztec/stdlib/gas';
12
12
  import { computeProtocolNullifier } from '@aztec/stdlib/hash';
13
- import { makeAppendOnlyTreeSnapshot, makeGlobalVariables } from '@aztec/stdlib/testing';
14
- import { CallContext, TxContext } from '@aztec/stdlib/tx';
13
+ import { makeGlobalVariables } from '@aztec/stdlib/testing';
14
+ import { CallContext, OFFCHAIN_MESSAGE_IDENTIFIER, TxContext } from '@aztec/stdlib/tx';
15
15
  import { z } from 'zod';
16
+ import { DEFAULT_ADDRESS, MAX_OFFCHAIN_EFFECTS_PER_TXE_QUERY, MAX_OFFCHAIN_EFFECT_LEN } from './constants.js';
17
+ import { makeResolveTaggingSecretStrategyHook } from './oracle/tagging_secret_strategy.js';
16
18
  import { TXEOraclePublicContext } from './oracle/txe_oracle_public_context.js';
17
- import { TXEOracleTopLevelContext } from './oracle/txe_oracle_top_level_context.js';
18
- import { RPCTranslator } from './rpc_translator.js';
19
+ import { callTxeLegacyHandler } from './oracle/txe_oracle_registry.js';
20
+ import { TXEOracleTopLevelContext, authorizeAllUtilityCallsHook } from './oracle/txe_oracle_top_level_context.js';
21
+ import { TXE_ORACLE_VERSION_MAJOR, TXE_ORACLE_VERSION_MINOR } from './oracle/txe_oracle_version.js';
22
+ import { TXEPrivateExecutionOracle } from './oracle/txe_private_execution_oracle.js';
23
+ import { RPCTranslator, UnavailableOracleError } from './rpc_translator.js';
24
+ import { TXEArchiver } from './state_machine/archiver.js';
19
25
  import { TXEStateMachine } from './state_machine/index.js';
20
- import { TXEAccountDataProvider } from './util/txe_account_data_provider.js';
21
- import { TXEContractDataProvider } from './util/txe_contract_data_provider.js';
22
- import { getSingleTxBlockRequestHash, insertTxEffectIntoWorldTrees, makeTXEBlockHeader } from './utils/block_creation.js';
26
+ import { getSingleTxBlockRequestHash, insertTxEffectIntoWorldTrees, makeTXEBlock } from './utils/block_creation.js';
23
27
  import { makeTxEffect } from './utils/tx_effect_creation.js';
24
- const DEFAULT_ADDRESS = AztecAddress.fromNumber(42);
28
+ import { TXEAccountStore } from './utils/txe_account_store.js';
29
+ function emptyLastCallState() {
30
+ return {
31
+ offchainEffects: [],
32
+ queried: false,
33
+ txHash: Fr.ZERO,
34
+ anchorBlockTimestamp: 0n
35
+ };
36
+ }
25
37
  /**
26
38
  * A `TXESession` corresponds to a Noir `#[test]` function, and handles all of its oracle calls, stores test-specific
27
39
  * state, etc., independent of all other tests running in parallel.
28
40
  */ export class TXESession {
29
41
  logger;
42
+ sessionStore;
30
43
  stateMachine;
31
44
  oracleHandler;
32
- contractDataProvider;
45
+ contractStore;
46
+ noteStore;
33
47
  keyStore;
34
- addressDataProvider;
35
- accountDataProvider;
48
+ addressStore;
49
+ accountStore;
50
+ senderTaggingStore;
51
+ recipientTaggingStore;
52
+ taggingSecretSourcesStore;
53
+ capsuleStore;
54
+ factStore;
55
+ privateEventStore;
56
+ jobCoordinator;
57
+ currentJobId;
36
58
  chainId;
37
59
  version;
38
60
  nextBlockTimestamp;
39
- pxeOracleInterface;
61
+ artifactResolver;
62
+ rootPath;
63
+ packageName;
40
64
  state;
41
65
  authwits;
42
- constructor(logger, stateMachine, oracleHandler, contractDataProvider, keyStore, addressDataProvider, accountDataProvider, chainId, version, nextBlockTimestamp, pxeOracleInterface){
66
+ taggingSecretStrategies;
67
+ authorizeAllUtilityCallTargets;
68
+ lastCallInfo;
69
+ txeOracleVersion;
70
+ disposed;
71
+ constructor(logger, sessionStore, stateMachine, oracleHandler, contractStore, noteStore, keyStore, addressStore, accountStore, senderTaggingStore, recipientTaggingStore, taggingSecretSourcesStore, capsuleStore, factStore, privateEventStore, jobCoordinator, currentJobId, chainId, version, nextBlockTimestamp, artifactResolver, rootPath, packageName){
43
72
  this.logger = logger;
73
+ this.sessionStore = sessionStore;
44
74
  this.stateMachine = stateMachine;
45
75
  this.oracleHandler = oracleHandler;
46
- this.contractDataProvider = contractDataProvider;
76
+ this.contractStore = contractStore;
77
+ this.noteStore = noteStore;
47
78
  this.keyStore = keyStore;
48
- this.addressDataProvider = addressDataProvider;
49
- this.accountDataProvider = accountDataProvider;
79
+ this.addressStore = addressStore;
80
+ this.accountStore = accountStore;
81
+ this.senderTaggingStore = senderTaggingStore;
82
+ this.recipientTaggingStore = recipientTaggingStore;
83
+ this.taggingSecretSourcesStore = taggingSecretSourcesStore;
84
+ this.capsuleStore = capsuleStore;
85
+ this.factStore = factStore;
86
+ this.privateEventStore = privateEventStore;
87
+ this.jobCoordinator = jobCoordinator;
88
+ this.currentJobId = currentJobId;
50
89
  this.chainId = chainId;
51
90
  this.version = version;
52
91
  this.nextBlockTimestamp = nextBlockTimestamp;
53
- this.pxeOracleInterface = pxeOracleInterface;
92
+ this.artifactResolver = artifactResolver;
93
+ this.rootPath = rootPath;
94
+ this.packageName = packageName;
54
95
  this.state = {
55
96
  name: 'TOP_LEVEL'
56
97
  };
57
98
  this.authwits = new Map();
99
+ this.taggingSecretStrategies = new Map();
100
+ this.authorizeAllUtilityCallTargets = false;
101
+ this.lastCallInfo = emptyLastCallState();
102
+ this.disposed = false;
58
103
  }
59
- static async init(protocolContracts) {
60
- const store = await openTmpStore('txe-session');
61
- const addressDataProvider = new AddressDataProvider(store);
62
- const privateEventDataProvider = new PrivateEventDataProvider(store);
63
- const contractDataProvider = new TXEContractDataProvider(store);
64
- const noteDataProvider = await NoteDataProvider.create(store);
65
- const taggingDataProvider = new TaggingDataProvider(store);
66
- const capsuleDataProvider = new CapsuleDataProvider(store);
67
- const keyStore = new KeyStore(store);
68
- const accountDataProvider = new TXEAccountDataProvider(store);
69
- // Register protocol contracts.
70
- for (const { contractClass, instance, artifact } of protocolContracts){
71
- await contractDataProvider.addContractArtifact(contractClass.id, artifact);
72
- await contractDataProvider.addContractInstance(instance);
104
+ /**
105
+ * Tears down the per-session AVM simulator (process pool + CDB server), the `NativeWorldStateService`,
106
+ * and the `txe-session` LMDB. Called via IPC when the dispatcher detects the end of a test. Idempotent.
107
+ */ async dispose() {
108
+ if (this.disposed) {
109
+ return;
110
+ }
111
+ this.disposed = true;
112
+ // Dispose the AVM pool before the world state: it kills the bb-avm-sim processes so they release their
113
+ // connection to the WSDB server, letting it shut down cleanly. Skipping this leaks a bb-avm-sim process
114
+ // (and keeps its WSDB alive) per session.
115
+ try {
116
+ await this.stateMachine.synchronizer.closeIpc();
117
+ } catch (err) {
118
+ this.logger.warn(`Error closing AVM simulator during session dispose`, err);
119
+ }
120
+ try {
121
+ await this.stateMachine.synchronizer.nativeWorldStateService.close();
122
+ } catch (err) {
123
+ this.logger.warn(`Error closing native world state during session dispose`, err);
73
124
  }
74
- const stateMachine = await TXEStateMachine.create(store);
125
+ try {
126
+ await this.sessionStore.close();
127
+ } catch (err) {
128
+ this.logger.warn(`Error closing session LMDB during dispose`, err);
129
+ }
130
+ }
131
+ static async init(contractStore, artifactResolver, rootPath, packageName) {
132
+ // Size LMDB's reader slots to the libuv pool (capped to 2 in bin/index.ts via
133
+ // HARDWARE_CONCURRENCY): each native LMDB read needs a libuv worker thread to run, so any
134
+ // slot beyond the pool size would sit idle while still consuming a semaphore + reader-table
135
+ // entry per session.
136
+ const store = await openEphemeralStore('txe-session', undefined, 2);
137
+ const addressStore = new AddressStore(store);
138
+ const privateEventStore = new PrivateEventStore(store);
139
+ const noteStore = new NoteStore(store);
140
+ const senderTaggingStore = new SenderTaggingStore(store);
141
+ const recipientTaggingStore = new RecipientTaggingStore(store);
142
+ const taggingSecretSourcesStore = new TaggingSecretSourcesStore(store);
143
+ const capsuleStore = new CapsuleStore(store);
144
+ const factStore = new FactStore(store);
145
+ const keyStore = new KeyStore(store);
146
+ const accountStore = new TXEAccountStore(store);
147
+ const jobCoordinator = new JobCoordinator(store);
148
+ jobCoordinator.registerStores([
149
+ capsuleStore,
150
+ factStore,
151
+ senderTaggingStore,
152
+ recipientTaggingStore,
153
+ privateEventStore,
154
+ noteStore
155
+ ]);
156
+ const archiver = new TXEArchiver(store);
157
+ const anchorBlockStore = new AnchorBlockStore(store);
158
+ const stateMachine = await TXEStateMachine.create(archiver, anchorBlockStore, contractStore, noteStore);
75
159
  const nextBlockTimestamp = BigInt(Math.floor(new Date().getTime() / 1000));
76
160
  const version = new Fr(await stateMachine.node.getVersion());
77
161
  const chainId = new Fr(await stateMachine.node.getChainId());
78
- const pxeOracleInterface = new PXEOracleInterface(stateMachine.node, keyStore, contractDataProvider, noteDataProvider, capsuleDataProvider, stateMachine.syncDataProvider, taggingDataProvider, addressDataProvider, privateEventDataProvider);
79
- const topLevelOracleHandler = new TXEOracleTopLevelContext(stateMachine, contractDataProvider, keyStore, addressDataProvider, accountDataProvider, pxeOracleInterface, nextBlockTimestamp, version, chainId, new Map());
80
- await topLevelOracleHandler.txeAdvanceBlocksBy(1);
81
- return new TXESession(createLogger('txe:session'), stateMachine, topLevelOracleHandler, contractDataProvider, keyStore, addressDataProvider, accountDataProvider, version, chainId, nextBlockTimestamp, pxeOracleInterface);
162
+ const initialJobId = jobCoordinator.beginJob();
163
+ const logger = createLogger('txe:session');
164
+ const topLevelOracleHandler = new TXEOracleTopLevelContext(stateMachine, contractStore, noteStore, keyStore, addressStore, accountStore, senderTaggingStore, recipientTaggingStore, taggingSecretSourcesStore, capsuleStore, factStore, privateEventStore, nextBlockTimestamp, version, chainId, new Map(), new Map(), false, artifactResolver, rootPath, packageName);
165
+ await topLevelOracleHandler.mineDeploymentNullifiers([
166
+ STANDARD_AUTH_REGISTRY_ADDRESS
167
+ ]);
168
+ return new TXESession(logger, store, stateMachine, topLevelOracleHandler, contractStore, noteStore, keyStore, addressStore, accountStore, senderTaggingStore, recipientTaggingStore, taggingSecretSourcesStore, capsuleStore, factStore, privateEventStore, jobCoordinator, initialJobId, version, chainId, nextBlockTimestamp, artifactResolver, rootPath, packageName);
82
169
  }
83
170
  /**
84
171
  * Processes an oracle function invoked by the Noir test associated to this session.
@@ -87,13 +174,28 @@ const DEFAULT_ADDRESS = AztecAddress.fromNumber(42);
87
174
  * @returns The oracle return values.
88
175
  */ processFunction(functionName, inputs) {
89
176
  try {
177
+ // Oracles retired into the PXE legacy registry have no translator method; dispatch them through the same
178
+ // buildACIRCallback legacy path that contract execution uses, keeping TXE's two oracle paths in sync.
179
+ // Use an own-property check: `in` would match inherited `Object.prototype` keys (e.g. `constructor`), routing
180
+ // them into the legacy path instead of letting them fall through to the unknown-oracle error.
181
+ if (Object.hasOwn(LEGACY_ORACLE_REGISTRY, functionName)) {
182
+ return callTxeLegacyHandler(functionName, inputs, this.oracleHandler);
183
+ }
90
184
  const translator = new RPCTranslator(this, this.oracleHandler);
91
185
  // We perform a runtime validation to check that the function name corresponds to a real oracle handler.
92
186
  const validatedFunctionName = z.string().refine((fn)=>typeof translator[fn] === 'function' && !fn.startsWith('handlerAs') && fn !== 'constructor').parse(functionName);
93
187
  return translator[validatedFunctionName](...inputs);
94
188
  } catch (error) {
95
189
  if (error instanceof z.ZodError) {
96
- throw new Error(`${functionName} does not correspond to any oracle handler available on RPCTranslator`);
190
+ let versionHint;
191
+ if (!this.txeOracleVersion) {
192
+ versionHint = ' The test appears to use an older version of Aztec.nr that does not' + ' support test environment oracle versioning. Update Aztec.nr to a compatible version.' + ' See https://docs.aztec.network/errors/12';
193
+ } else if (this.txeOracleVersion.minor > TXE_ORACLE_VERSION_MINOR) {
194
+ versionHint = ` The test uses Aztec.nr test oracle version` + ` ${this.txeOracleVersion.major}.${this.txeOracleVersion.minor}, but this test environment` + ` only supports up to ${TXE_ORACLE_VERSION_MAJOR}.${TXE_ORACLE_VERSION_MINOR}.` + ` Upgrade the Aztec CLI to a compatible version.` + ` See https://docs.aztec.network/errors/12`;
195
+ } else {
196
+ versionHint = ` The test's oracle version (${this.txeOracleVersion.major}.${this.txeOracleVersion.minor})` + ` is compatible with this test environment` + ` (${TXE_ORACLE_VERSION_MAJOR}.${TXE_ORACLE_VERSION_MINOR}), so this oracle should be` + ` available. This is an unexpected error, please report it.` + ` See https://docs.aztec.network/errors/13`;
197
+ }
198
+ throw new Error(`Unknown oracle '${functionName}'.${versionHint}`);
97
199
  } else if (error instanceof Error) {
98
200
  throw new Error(`Execution error while processing function ${functionName} in state ${this.state.name}: ${error.message}`);
99
201
  } else {
@@ -101,6 +203,132 @@ const DEFAULT_ADDRESS = AztecAddress.fromNumber(42);
101
203
  }
102
204
  }
103
205
  }
206
+ /** Commits the current job and begins a new one. Returns the new job ID. */ async cycleJob() {
207
+ await this.jobCoordinator.commitJob(this.currentJobId);
208
+ this.currentJobId = this.jobCoordinator.beginJob();
209
+ return this.currentJobId;
210
+ }
211
+ resetLastCall() {
212
+ const notQueriedMessageCount = this.lastCallInfo.queried ? 0 : this.lastCallInfo.offchainEffects.filter((payload)=>payload[0]?.equals(OFFCHAIN_MESSAGE_IDENTIFIER)).length;
213
+ if (notQueriedMessageCount > 0) {
214
+ this.logger.warn(`Dropping ${notQueriedMessageCount} unqueried offchain message(s) from the previous top-level call. ` + `To deliver them, call \`env.offchain_messages()\` and forward the result to the recipient contract's ` + `\`offchain_receive\` utility before issuing another top-level call. To intentionally discard, assign ` + `to \`let _ = env.offchain_messages()\` to silence this warning.`);
215
+ }
216
+ this.lastCallInfo = emptyLastCallState();
217
+ }
218
+ recordOffchainEffect(data) {
219
+ this.lastCallInfo.offchainEffects.push(data);
220
+ }
221
+ setLastCallContext(txHash, anchorBlockTimestamp) {
222
+ this.lastCallInfo.txHash = txHash;
223
+ this.lastCallInfo.anchorBlockTimestamp = anchorBlockTimestamp;
224
+ }
225
+ async withTopLevelCallTracking(work) {
226
+ this.resetLastCall();
227
+ // Capture the anchor *before* `work` runs: private/public executor calls mine a new block as a
228
+ // side effect, and that block's timestamp should not be attributed to this call's anchor.
229
+ const anchorBlockTimestamp = (await this.stateMachine.node.getBlockData('latest')).header.globalVariables.timestamp;
230
+ const { result, txHash } = await work();
231
+ this.setLastCallContext(txHash ?? Fr.ZERO, anchorBlockTimestamp);
232
+ return result;
233
+ }
234
+ getLastCallOffchainEffects() {
235
+ this.lastCallInfo.queried = true;
236
+ const effects = this.lastCallInfo.offchainEffects;
237
+ if (effects.length > MAX_OFFCHAIN_EFFECTS_PER_TXE_QUERY) {
238
+ throw new Error(`${effects.length} offchain effects exceed max ${MAX_OFFCHAIN_EFFECTS_PER_TXE_QUERY}`);
239
+ }
240
+ if (effects.some((e)=>e.length > MAX_OFFCHAIN_EFFECT_LEN)) {
241
+ throw new Error(`Some offchain effect has length larger than max ${MAX_OFFCHAIN_EFFECT_LEN}`);
242
+ }
243
+ return {
244
+ effects
245
+ };
246
+ }
247
+ getLastCallContext() {
248
+ const { txHash, anchorBlockTimestamp } = this.lastCallInfo;
249
+ return {
250
+ txHash,
251
+ anchorBlockTimestamp
252
+ };
253
+ }
254
+ async executePrivateCall(from, targetContractAddress, functionSelector, args, argsHash, isStaticCall, additionalScopes, authorizedUtilityCallTargets, gasSettings) {
255
+ const handler = this.handlerAsTxe();
256
+ return await this.withTopLevelCallTracking(async ()=>{
257
+ const { returnValues, offchainEffects } = await handler.privateCallNewFlow(from?.value, targetContractAddress, functionSelector, args, argsHash, isStaticCall, additionalScopes, this.currentJobId, authorizedUtilityCallTargets, gasSettings);
258
+ // Private execution collects offchain effects inside PXE's PrivateExecutionOracle rather than round-tripping
259
+ // them through `aztec_utl_emitOffchainEffect`, so the session buffer is empty at this point. Drain the effects
260
+ // from the execution tree into the session buffer so the next `env.offchain_messages()` call in the test sees
261
+ // them.
262
+ for (const data of offchainEffects){
263
+ this.recordOffchainEffect(data);
264
+ }
265
+ await this.cycleJob();
266
+ if (isStaticCall) {
267
+ // Static calls revert their checkpoint and mine no block, so there is no tx hash to tag offchain effects
268
+ // with. Querying `getLastTxEffects()` here would return an unrelated predecessor tx.
269
+ return {
270
+ result: returnValues
271
+ };
272
+ }
273
+ const { txHash } = await handler.getLastTxEffects();
274
+ return {
275
+ result: returnValues,
276
+ txHash: txHash.hash
277
+ };
278
+ });
279
+ }
280
+ async executeUtilityFunction(from, targetContractAddress, functionSelector, args, authorizedUtilityCallTargets) {
281
+ const handler = this.handlerAsTxe();
282
+ return await this.withTopLevelCallTracking(async ()=>{
283
+ const returnValues = await handler.executeUtilityFunction(from?.value, targetContractAddress, functionSelector, args, this.currentJobId, authorizedUtilityCallTargets);
284
+ await this.cycleJob();
285
+ return {
286
+ result: returnValues
287
+ };
288
+ });
289
+ }
290
+ async executePublicCall(from, targetContractAddress, calldata, isStaticCall, gasSettings) {
291
+ const handler = this.handlerAsTxe();
292
+ return await this.withTopLevelCallTracking(async ()=>{
293
+ const returnValues = await handler.publicCallNewFlow(from?.value, targetContractAddress, calldata, isStaticCall, gasSettings);
294
+ await this.cycleJob();
295
+ if (isStaticCall) {
296
+ // See the equivalent branch in `executePrivateCall`.
297
+ return {
298
+ result: returnValues
299
+ };
300
+ }
301
+ const { txHash } = await handler.getLastTxEffects();
302
+ return {
303
+ result: returnValues,
304
+ txHash: txHash.hash
305
+ };
306
+ });
307
+ }
308
+ async getPrivateEvents(selector, contractAddress, scope) {
309
+ const handler = this.handlerAsTxe();
310
+ await handler.syncContractNonOracleMethod(contractAddress, scope, this.currentJobId);
311
+ // Cycle the job to commit the stores after the contract sync.
312
+ await this.cycleJob();
313
+ return handler.getPrivateEvents(selector, contractAddress, scope);
314
+ }
315
+ handlerAsTxe() {
316
+ if (!('isTxe' in this.oracleHandler)) {
317
+ throw new UnavailableOracleError('Txe');
318
+ }
319
+ return this.oracleHandler;
320
+ }
321
+ setTxeOracleVersion(major, minor) {
322
+ if (major !== TXE_ORACLE_VERSION_MAJOR) {
323
+ const hint = major > TXE_ORACLE_VERSION_MAJOR ? 'The test was compiled with a newer version of Aztec.nr than your test environment supports. Upgrade your test environment to a compatible version.' : '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.';
324
+ throw new Error(`Incompatible test environment version: ${hint} See https://docs.aztec.network/errors/12 (expected test oracle major version ${TXE_ORACLE_VERSION_MAJOR}, got ${major})`);
325
+ }
326
+ this.txeOracleVersion = {
327
+ major,
328
+ minor
329
+ };
330
+ this.logger.debug(`Test compiled with test oracle version ${major}.${minor}`);
331
+ }
104
332
  async enterTopLevelState() {
105
333
  switch(this.state.name){
106
334
  case 'PRIVATE':
@@ -127,25 +355,25 @@ const DEFAULT_ADDRESS = AztecAddress.fromNumber(42);
127
355
  this.state;
128
356
  }
129
357
  }
130
- this.oracleHandler = new TXEOracleTopLevelContext(this.stateMachine, this.contractDataProvider, this.keyStore, this.addressDataProvider, this.accountDataProvider, this.pxeOracleInterface, this.nextBlockTimestamp, this.version, this.chainId, this.authwits);
358
+ // Commit all staged stores from the job that was just completed, then begin a new job
359
+ await this.cycleJob();
360
+ this.oracleHandler = new TXEOracleTopLevelContext(this.stateMachine, this.contractStore, this.noteStore, this.keyStore, this.addressStore, this.accountStore, this.senderTaggingStore, this.recipientTaggingStore, this.taggingSecretSourcesStore, this.capsuleStore, this.factStore, this.privateEventStore, this.nextBlockTimestamp, this.version, this.chainId, this.authwits, this.taggingSecretStrategies, this.authorizeAllUtilityCallTargets, this.artifactResolver, this.rootPath, this.packageName);
131
361
  this.state = {
132
362
  name: 'TOP_LEVEL'
133
363
  };
134
364
  this.logger.debug(`Entered state ${this.state.name}`);
135
365
  }
136
- async enterPrivateState(contractAddress = DEFAULT_ADDRESS, anchorBlockNumber) {
366
+ async enterPrivateState(contractAddressOpt, anchorBlockNumberOpt, gasSettings) {
367
+ const contractAddress = contractAddressOpt?.value ?? DEFAULT_ADDRESS;
368
+ const anchorBlockNumber = anchorBlockNumberOpt?.value;
137
369
  this.exitTopLevelState();
138
- // There is no automatic message discovery and contract-driven syncing process in inlined private or utility
139
- // contexts, which means that known nullifiers are also not searched for, since it is during the tagging sync that
140
- // we perform this. We therefore search for known nullifiers now, as otherwise notes that were nullified would not
141
- // be removed from the database.
142
- // TODO(#12553): make the synchronizer sync here instead and remove this
143
- await this.pxeOracleInterface.syncNoteNullifiers(contractAddress);
370
+ this.resetLastCall();
144
371
  // Private execution has two associated block numbers: the anchor block (i.e. the historical block that is used to
145
372
  // build the proof), and the *next* block, i.e. the one we'll create once the execution ends, and which will contain
146
373
  // a single transaction with the effects of what was done in the test.
147
- const anchorBlock = await this.stateMachine.node.getBlockHeader(anchorBlockNumber ?? 'latest');
148
- const latestBlock = await this.stateMachine.node.getBlockHeader('latest');
374
+ const anchorBlock = await this.stateMachine.node.getBlock(anchorBlockNumber ?? 'latest').then((b)=>b?.header);
375
+ await new NoteService(this.noteStore, this.stateMachine.node, anchorBlock, this.currentJobId).syncNoteNullifiers(contractAddress, await this.keyStore.getAccounts());
376
+ const latestBlock = await this.stateMachine.node.getBlock('latest').then((b)=>b?.header);
149
377
  const nextBlockGlobalVariables = makeGlobalVariables(undefined, {
150
378
  blockNumber: BlockNumber(latestBlock.globalVariables.blockNumber + 1),
151
379
  timestamp: this.nextBlockTimestamp,
@@ -156,7 +384,44 @@ const DEFAULT_ADDRESS = AztecAddress.fromNumber(42);
156
384
  const protocolNullifier = await computeProtocolNullifier(txRequestHash);
157
385
  const noteCache = new ExecutionNoteCache(protocolNullifier);
158
386
  const taggingIndexCache = new ExecutionTaggingIndexCache();
159
- this.oracleHandler = new PrivateExecutionOracle(Fr.ZERO, new TxContext(this.chainId, this.version, GasSettings.empty()), new CallContext(AztecAddress.ZERO, contractAddress, FunctionSelector.empty(), false), anchorBlock, [], [], new HashedValuesCache(), noteCache, taggingIndexCache, this.pxeOracleInterface);
387
+ const utilityExecutor = this.utilityExecutorForContractSync(anchorBlock);
388
+ const transientArrayService = new TransientArrayService();
389
+ const anchoredContractData = new AnchoredContractData(this.contractStore, this.stateMachine.contractClassService, anchorBlock);
390
+ this.oracleHandler = new TXEPrivateExecutionOracle({
391
+ argsHash: Fr.ZERO,
392
+ txContext: new TxContext(this.chainId, this.version, gasSettings),
393
+ txRequestSalt: Fr.ZERO,
394
+ callContext: new CallContext(AztecAddress.ZERO, contractAddress, FunctionSelector.empty(), false),
395
+ anchorBlockHeader: anchorBlock,
396
+ utilityExecutor,
397
+ authWitnesses: [],
398
+ capsules: [],
399
+ executionCache: new HashedValuesCache(),
400
+ noteCache,
401
+ taggingIndexCache,
402
+ anchoredContractData,
403
+ noteStore: this.noteStore,
404
+ keyStore: this.keyStore,
405
+ addressStore: this.addressStore,
406
+ aztecNode: this.stateMachine.node,
407
+ senderTaggingStore: this.senderTaggingStore,
408
+ recipientTaggingStore: this.recipientTaggingStore,
409
+ taggingSecretSourcesStore: this.taggingSecretSourcesStore,
410
+ capsuleService: new CapsuleService(this.capsuleStore, await this.keyStore.getAccounts()),
411
+ factService: new FactService(this.factStore, await this.keyStore.getAccounts()),
412
+ privateEventStore: this.privateEventStore,
413
+ contractSyncService: this.stateMachine.contractSyncService,
414
+ l2TipsStore: this.stateMachine.l2TipsProvider,
415
+ jobId: this.currentJobId,
416
+ scopes: await this.keyStore.getAccounts(),
417
+ txResolver: this.stateMachine.txResolver,
418
+ simulator: new WASMSimulator(),
419
+ hooks: composeHooks({
420
+ resolveTaggingSecretStrategy: makeResolveTaggingSecretStrategyHook(this.taggingSecretStrategies),
421
+ authorizeUtilityCall: this.authorizeAllUtilityCallTargets ? authorizeAllUtilityCallsHook : undefined
422
+ }),
423
+ transientArrayService
424
+ });
160
425
  // We store the note and tagging index caches fed into the PrivateExecutionOracle (along with some other auxiliary
161
426
  // data) in order to refer to it later, mimicking the way this object is used by the ContractFunctionSimulator. The
162
427
  // difference resides in that the simulator has all information needed in order to run the simulation, while ours
@@ -165,58 +430,104 @@ const DEFAULT_ADDRESS = AztecAddress.fromNumber(42);
165
430
  this.state = {
166
431
  name: 'PRIVATE',
167
432
  nextBlockGlobalVariables,
168
- protocolNullifier,
169
433
  noteCache,
170
434
  taggingIndexCache
171
435
  };
172
436
  this.logger.debug(`Entered state ${this.state.name}`);
437
+ // Record the *resolved* anchor's timestamp — if the caller pinned the anchor to a past block
438
+ // via `anchorBlockNumber`, "latest" would be the wrong anchor for offchain-message semantics.
439
+ this.setLastCallContext(Fr.ZERO, anchorBlock.globalVariables.timestamp);
173
440
  return this.oracleHandler.getPrivateContextInputs();
174
441
  }
175
- async enterPublicState(contractAddress) {
442
+ async enterPublicState(contractAddressOpt) {
443
+ const contractAddress = contractAddressOpt?.value ?? DEFAULT_ADDRESS;
176
444
  this.exitTopLevelState();
445
+ this.resetLastCall();
177
446
  // The PublicContext will create a block with a single transaction in it, containing the effects of what was done in
178
447
  // the test. The block therefore gets the *next* block number and timestamp.
179
- const latestBlockNumber = (await this.stateMachine.node.getBlockHeader('latest')).globalVariables.blockNumber;
448
+ const latestHeader = (await this.stateMachine.node.getBlockData('latest')).header;
180
449
  const globalVariables = makeGlobalVariables(undefined, {
181
- blockNumber: BlockNumber(latestBlockNumber + 1),
450
+ blockNumber: BlockNumber(latestHeader.globalVariables.blockNumber + 1),
182
451
  timestamp: this.nextBlockTimestamp,
183
452
  version: this.version,
184
453
  chainId: this.chainId
185
454
  });
186
- this.oracleHandler = new TXEOraclePublicContext(contractAddress ?? DEFAULT_ADDRESS, await this.stateMachine.synchronizer.nativeWorldStateService.fork(), getSingleTxBlockRequestHash(globalVariables.blockNumber), globalVariables);
455
+ this.oracleHandler = new TXEOraclePublicContext(contractAddress, await this.stateMachine.synchronizer.nativeWorldStateService.fork(), getSingleTxBlockRequestHash(globalVariables.blockNumber), globalVariables, this.contractStore);
187
456
  this.state = {
188
457
  name: 'PUBLIC'
189
458
  };
190
459
  this.logger.debug(`Entered state ${this.state.name}`);
460
+ // Public state is anchored at the latest block.
461
+ this.setLastCallContext(Fr.ZERO, latestHeader.globalVariables.timestamp);
191
462
  }
192
- async enterUtilityState(contractAddress = DEFAULT_ADDRESS) {
463
+ async enterUtilityState(contractAddressOpt) {
464
+ const contractAddress = contractAddressOpt?.value ?? DEFAULT_ADDRESS;
193
465
  this.exitTopLevelState();
466
+ this.resetLastCall();
467
+ const anchorBlockHeader = await this.stateMachine.anchorBlockStore.getBlockHeader();
194
468
  // There is no automatic message discovery and contract-driven syncing process in inlined private or utility
195
469
  // contexts, which means that known nullifiers are also not searched for, since it is during the tagging sync that
196
470
  // we perform this. We therefore search for known nullifiers now, as otherwise notes that were nullified would not
197
471
  // be removed from the database.
198
472
  // TODO(#12553): make the synchronizer sync here instead and remove this
199
- await this.pxeOracleInterface.syncNoteNullifiers(contractAddress);
200
- this.oracleHandler = new UtilityExecutionOracle(contractAddress, [], [], this.pxeOracleInterface);
473
+ await new NoteService(this.noteStore, this.stateMachine.node, anchorBlockHeader, this.currentJobId).syncNoteNullifiers(contractAddress, await this.keyStore.getAccounts());
474
+ this.oracleHandler = new UtilityExecutionOracle({
475
+ callContext: CallContext.from({
476
+ msgSender: AztecAddress.NULL_MSG_SENDER,
477
+ contractAddress,
478
+ // No specific function is being executed in this inlined utility context, hence the empty selector.
479
+ functionSelector: FunctionSelector.empty(),
480
+ isStaticCall: true
481
+ }),
482
+ authWitnesses: [],
483
+ capsules: [],
484
+ anchorBlockHeader,
485
+ anchoredContractData: new AnchoredContractData(this.contractStore, this.stateMachine.contractClassService, anchorBlockHeader),
486
+ noteStore: this.noteStore,
487
+ keyStore: this.keyStore,
488
+ addressStore: this.addressStore,
489
+ aztecNode: this.stateMachine.node,
490
+ recipientTaggingStore: this.recipientTaggingStore,
491
+ taggingSecretSourcesStore: this.taggingSecretSourcesStore,
492
+ capsuleService: new CapsuleService(this.capsuleStore, await this.keyStore.getAccounts()),
493
+ factService: new FactService(this.factStore, await this.keyStore.getAccounts()),
494
+ privateEventStore: this.privateEventStore,
495
+ txResolver: this.stateMachine.txResolver,
496
+ contractSyncService: this.stateMachine.contractSyncService,
497
+ l2TipsStore: this.stateMachine.l2TipsProvider,
498
+ jobId: this.currentJobId,
499
+ scopes: await this.keyStore.getAccounts(),
500
+ simulator: new WASMSimulator(),
501
+ utilityExecutor: this.utilityExecutorForContractSync(anchorBlockHeader),
502
+ hooks: composeHooks({
503
+ authorizeUtilityCall: this.authorizeAllUtilityCallTargets ? authorizeAllUtilityCallsHook : undefined
504
+ }),
505
+ // Execution-tree root (top-level utility run): own store; nested frames inherit it.
506
+ transientArrayService: new TransientArrayService()
507
+ });
201
508
  this.state = {
202
509
  name: 'UTILITY'
203
510
  };
204
511
  this.logger.debug(`Entered state ${this.state.name}`);
512
+ // Utility state anchors at whatever the anchor block store is pointing to (tracked as latest).
513
+ this.setLastCallContext(Fr.ZERO, anchorBlockHeader.globalVariables.timestamp);
205
514
  }
206
515
  exitTopLevelState() {
207
516
  if (this.state.name != 'TOP_LEVEL') {
208
517
  throw new Error(`Expected to be in state 'TOP_LEVEL', but got '${this.state.name}' instead`);
209
518
  }
210
519
  // Note that while all public and private contexts do is build a single block that we then process when exiting
211
- // those, the top level context performs a large number of actions not captured in the following 'close' call. Among
212
- // others, it will create empty blocks (via `txeAdvanceBlocksBy` and `deploy`), create blocks with transactions via
213
- // `txePrivateCallNewFlow` and `txePublicCallNewFlow`, add accounts to PXE via `txeAddAccount`, etc. This is a
214
- // slight inconsistency in the working model of this class, but is not too bad.
215
- // TODO: it's quite unfortunate that we need to capture the authwits created to later pass them again when the top
216
- // level context is re-created. This is because authwits create a temporary utility context that'd otherwise reset
217
- // the authwits if not persisted, so we'd not be able to pass more than one per execution.
218
- // Ideally authwits would be passed alongside a contract call instead of pre-seeded.
219
- [this.nextBlockTimestamp, this.authwits] = this.oracleHandler.close();
520
+ // them, the top level context does most of its work as it goes: it creates empty blocks (via `advanceBlocksBy`
521
+ // and `deploy`), creates blocks with transactions (via `privateCallNewFlow` and `publicCallNewFlow`), adds
522
+ // accounts to PXE (via `addAccount`), etc. This is a slight inconsistency in the working model of this class, but
523
+ // is not too bad. The `close` call below therefore only hands back the session-scoped values that a test
524
+ // sets directly at the top level, outside any contract execution (e.g. via `advanceTimestampBy`,
525
+ // `addAuthWitness`, `setTaggingSecretStrategies`). The oracle handler is discarded on every state transition,
526
+ // so the session must seed these values into the contexts it creates later.
527
+ // TODO: persisting authwits this way is quite unfortunate: they create a temporary utility context that would
528
+ // otherwise reset them, so we'd not be able to pass more than one per execution. Ideally authwits would be passed
529
+ // alongside a contract call instead of pre-seeded.
530
+ ({ nextBlockTimestamp: this.nextBlockTimestamp, authwits: this.authwits, taggingSecretStrategies: this.taggingSecretStrategies, authorizeAllUtilityCallTargets: this.authorizeAllUtilityCallTargets } = this.oracleHandler.close());
220
531
  }
221
532
  async exitPrivateState() {
222
533
  if (this.state.name != 'PRIVATE') {
@@ -227,13 +538,13 @@ const DEFAULT_ADDRESS = AztecAddress.fromNumber(42);
227
538
  });
228
539
  // We rely on the note cache to determine the effects of the transaction. This is incomplete as it doesn't private
229
540
  // logs (other effects like enqueued public calls don't need to be considered since those are not allowed).
230
- const txEffect = await makeTxEffect(this.state.noteCache, this.state.protocolNullifier, this.state.nextBlockGlobalVariables.blockNumber);
541
+ const txEffect = await makeTxEffect(this.state.noteCache, this.state.nextBlockGlobalVariables.blockNumber);
231
542
  // We build a block holding just this transaction
232
543
  const forkedWorldTrees = await this.stateMachine.synchronizer.nativeWorldStateService.fork();
233
544
  await insertTxEffectIntoWorldTrees(txEffect, forkedWorldTrees);
234
- const block = new L2Block(makeAppendOnlyTreeSnapshot(), await makeTXEBlockHeader(forkedWorldTrees, this.state.nextBlockGlobalVariables), new Body([
545
+ const block = await makeTXEBlock(forkedWorldTrees, this.state.nextBlockGlobalVariables, [
235
546
  txEffect
236
- ]));
547
+ ]);
237
548
  await this.stateMachine.handleL2Block(block);
238
549
  await forkedWorldTrees.close();
239
550
  this.logger.debug('Exited PublicContext with built block', {
@@ -253,4 +564,60 @@ const DEFAULT_ADDRESS = AztecAddress.fromNumber(42);
253
564
  throw new Error(`Expected to be in state 'UTILITY', but got '${this.state.name}' instead`);
254
565
  }
255
566
  }
567
+ utilityExecutorForContractSync(anchorBlock) {
568
+ return async (call, scopes)=>{
569
+ const anchoredContractData = new AnchoredContractData(this.contractStore, this.stateMachine.contractClassService, anchorBlock);
570
+ const entryPointArtifact = await anchoredContractData.getFunctionArtifactWithDebugMetadata(call.to, call.selector);
571
+ if (!entryPointArtifact) {
572
+ throw new Error(`Cannot run function ${call.selector} on ${call.to}: the contract is not registered.`);
573
+ }
574
+ if (entryPointArtifact.functionType !== FunctionType.UTILITY) {
575
+ throw new Error(`Cannot run ${entryPointArtifact.functionType} function as utility`);
576
+ }
577
+ try {
578
+ const simulator = new WASMSimulator();
579
+ const oracle = new UtilityExecutionOracle({
580
+ callContext: CallContext.from({
581
+ msgSender: AztecAddress.NULL_MSG_SENDER,
582
+ contractAddress: call.to,
583
+ functionSelector: call.selector,
584
+ isStaticCall: true
585
+ }),
586
+ authWitnesses: [],
587
+ capsules: [],
588
+ anchorBlockHeader: anchorBlock,
589
+ anchoredContractData,
590
+ noteStore: this.noteStore,
591
+ keyStore: this.keyStore,
592
+ addressStore: this.addressStore,
593
+ aztecNode: this.stateMachine.node,
594
+ recipientTaggingStore: this.recipientTaggingStore,
595
+ taggingSecretSourcesStore: this.taggingSecretSourcesStore,
596
+ capsuleService: new CapsuleService(this.capsuleStore, scopes),
597
+ factService: new FactService(this.factStore, scopes),
598
+ privateEventStore: this.privateEventStore,
599
+ txResolver: this.stateMachine.txResolver,
600
+ contractSyncService: this.stateMachine.contractSyncService,
601
+ l2TipsStore: this.stateMachine.l2TipsProvider,
602
+ jobId: this.currentJobId,
603
+ scopes,
604
+ simulator,
605
+ utilityExecutor: this.utilityExecutorForContractSync(anchorBlock),
606
+ // Top-level utility entrypoint: gets a fresh store. Nested frames inherit it via UtilityExecutionOracle.
607
+ transientArrayService: new TransientArrayService()
608
+ });
609
+ await simulator.executeUserCircuit(toACVMWitness(0, call.args), entryPointArtifact, buildACIRCallback(oracle)).catch((err)=>{
610
+ err.message = resolveAssertionMessageFromError(err, entryPointArtifact);
611
+ throw new ExecutionError(err.message, {
612
+ contractAddress: call.to,
613
+ functionSelector: call.selector
614
+ }, extractCallStack(err, entryPointArtifact.debug), {
615
+ cause: err
616
+ });
617
+ });
618
+ } catch (err) {
619
+ throw createSimulationError(err instanceof Error ? err : new Error('Unknown error contract data sync'));
620
+ }
621
+ };
622
+ }
256
623
  }