@aztec/txe 0.0.1-commit.b655e406 → 0.0.1-commit.b9865e97

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 (167) hide show
  1. package/dest/ContractClassRegistry-PII7Q556.js +3 -0
  2. package/dest/ContractClassRegistry-PII7Q556.js.map +7 -0
  3. package/dest/ContractInstanceRegistry-3MHLGFNZ.js +3 -0
  4. package/dest/ContractInstanceRegistry-3MHLGFNZ.js.map +7 -0
  5. package/dest/FeeJuice-TQV5AQK7.js +3 -0
  6. package/dest/FeeJuice-TQV5AQK7.js.map +7 -0
  7. package/dest/MultiCallEntrypoint-SBJUIJY7.js +3 -0
  8. package/dest/MultiCallEntrypoint-SBJUIJY7.js.map +7 -0
  9. package/dest/SchnorrAccount-MQXPIZ44.js +3 -0
  10. package/dest/SchnorrAccount-MQXPIZ44.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 +61 -0
  14. package/dest/bin/index.d.ts +1 -1
  15. package/dest/bin/index.js +3 -30
  16. package/dest/bin/index.js.map +7 -0
  17. package/dest/bin/oracle_test_server.d.ts +3 -0
  18. package/dest/bin/oracle_test_server.d.ts.map +1 -0
  19. package/dest/bin/oracle_test_server.js +41 -0
  20. package/dest/chunk-BJVAAXNA.js +3 -0
  21. package/dest/chunk-BJVAAXNA.js.map +7 -0
  22. package/dest/chunk-CUSVOJA4.js +304 -0
  23. package/dest/chunk-CUSVOJA4.js.map +7 -0
  24. package/dest/chunk-OYLIPWI6.js +260 -0
  25. package/dest/chunk-OYLIPWI6.js.map +7 -0
  26. package/dest/constants.d.ts +7 -0
  27. package/dest/constants.d.ts.map +1 -0
  28. package/dest/constants.js +10 -0
  29. package/dest/dispatcher_pool.d.ts +67 -0
  30. package/dest/dispatcher_pool.d.ts.map +1 -0
  31. package/dest/dispatcher_pool.js +284 -0
  32. package/dest/index.d.ts +185 -7
  33. package/dest/index.d.ts.map +1 -1
  34. package/dest/index.js +73 -158
  35. package/dest/metafile.json +36863 -0
  36. package/dest/msgpackr_fr_extension.d.ts +2 -0
  37. package/dest/msgpackr_fr_extension.d.ts.map +1 -0
  38. package/dest/msgpackr_fr_extension.js +21 -0
  39. package/dest/oracle/interfaces.d.ts +60 -31
  40. package/dest/oracle/interfaces.d.ts.map +1 -1
  41. package/dest/oracle/test-resolver/fixtures.d.ts +43 -0
  42. package/dest/oracle/test-resolver/fixtures.d.ts.map +1 -0
  43. package/dest/oracle/test-resolver/fixtures.js +39 -0
  44. package/dest/oracle/test-resolver/index.d.ts +9 -0
  45. package/dest/oracle/test-resolver/index.d.ts.map +1 -0
  46. package/dest/oracle/test-resolver/index.js +33 -0
  47. package/dest/oracle/test-resolver/resolver.d.ts +34 -0
  48. package/dest/oracle/test-resolver/resolver.d.ts.map +1 -0
  49. package/dest/oracle/test-resolver/resolver.js +114 -0
  50. package/dest/oracle/txe_oracle_public_context.d.ts +41 -17
  51. package/dest/oracle/txe_oracle_public_context.d.ts.map +1 -1
  52. package/dest/oracle/txe_oracle_public_context.js +63 -23
  53. package/dest/oracle/txe_oracle_registry.d.ts +147 -0
  54. package/dest/oracle/txe_oracle_registry.d.ts.map +1 -0
  55. package/dest/oracle/txe_oracle_registry.js +562 -0
  56. package/dest/oracle/txe_oracle_top_level_context.d.ts +57 -28
  57. package/dest/oracle/txe_oracle_top_level_context.d.ts.map +1 -1
  58. package/dest/oracle/txe_oracle_top_level_context.js +341 -130
  59. package/dest/oracle/txe_oracle_version.d.ts +17 -0
  60. package/dest/oracle/txe_oracle_version.d.ts.map +1 -0
  61. package/dest/oracle/txe_oracle_version.js +14 -0
  62. package/dest/oracle/txe_private_execution_oracle.d.ts +17 -0
  63. package/dest/oracle/txe_private_execution_oracle.d.ts.map +1 -0
  64. package/dest/oracle/txe_private_execution_oracle.js +15 -0
  65. package/dest/rpc_server.d.ts +14 -0
  66. package/dest/rpc_server.d.ts.map +1 -0
  67. package/dest/rpc_server.js +78 -0
  68. package/dest/rpc_translator.d.ts +96 -213
  69. package/dest/rpc_translator.d.ts.map +1 -1
  70. package/dest/rpc_translator.js +815 -550
  71. package/dest/server.bundle.js +3 -0
  72. package/dest/server.bundle.js.map +7 -0
  73. package/dest/state_machine/archiver.d.ts +23 -52
  74. package/dest/state_machine/archiver.d.ts.map +1 -1
  75. package/dest/state_machine/archiver.js +77 -99
  76. package/dest/state_machine/dummy_p2p_client.d.ts +28 -15
  77. package/dest/state_machine/dummy_p2p_client.d.ts.map +1 -1
  78. package/dest/state_machine/dummy_p2p_client.js +54 -22
  79. package/dest/state_machine/global_variable_builder.d.ts +11 -4
  80. package/dest/state_machine/global_variable_builder.d.ts.map +1 -1
  81. package/dest/state_machine/global_variable_builder.js +21 -3
  82. package/dest/state_machine/index.d.ts +11 -7
  83. package/dest/state_machine/index.d.ts.map +1 -1
  84. package/dest/state_machine/index.js +60 -25
  85. package/dest/state_machine/mock_epoch_cache.d.ts +29 -12
  86. package/dest/state_machine/mock_epoch_cache.d.ts.map +1 -1
  87. package/dest/state_machine/mock_epoch_cache.js +50 -15
  88. package/dest/state_machine/synchronizer.d.ts +6 -5
  89. package/dest/state_machine/synchronizer.d.ts.map +1 -1
  90. package/dest/state_machine/synchronizer.js +9 -8
  91. package/dest/txe_session.d.ts +94 -21
  92. package/dest/txe_session.d.ts.map +1 -1
  93. package/dest/txe_session.js +314 -68
  94. package/dest/utils/block_creation.d.ts +21 -6
  95. package/dest/utils/block_creation.d.ts.map +1 -1
  96. package/dest/utils/block_creation.js +38 -4
  97. package/dest/utils/encoding.d.ts +191 -0
  98. package/dest/utils/encoding.d.ts.map +1 -0
  99. package/dest/{util → utils}/encoding.js +8 -3
  100. package/dest/utils/expected_failure_error.d.ts +4 -0
  101. package/dest/utils/expected_failure_error.d.ts.map +1 -0
  102. package/dest/utils/tx_effect_creation.d.ts +3 -3
  103. package/dest/utils/tx_effect_creation.d.ts.map +1 -1
  104. package/dest/utils/tx_effect_creation.js +4 -7
  105. package/dest/utils/txe_account_store.d.ts +10 -0
  106. package/dest/utils/txe_account_store.d.ts.map +1 -0
  107. package/dest/{util/txe_account_data_provider.js → utils/txe_account_store.js} +1 -1
  108. package/dest/utils/txe_artifact_resolver.d.ts +37 -0
  109. package/dest/utils/txe_artifact_resolver.d.ts.map +1 -0
  110. package/dest/utils/txe_artifact_resolver.js +161 -0
  111. package/dest/utils/txe_public_contract_data_source.d.ts +20 -0
  112. package/dest/utils/txe_public_contract_data_source.d.ts.map +1 -0
  113. package/dest/utils/txe_public_contract_data_source.js +48 -0
  114. package/dest/worker.bundle.js +3 -0
  115. package/dest/worker.bundle.js.map +7 -0
  116. package/dest/worker.d.ts +2 -0
  117. package/dest/worker.d.ts.map +1 -0
  118. package/dest/worker.js +92 -0
  119. package/package.json +40 -22
  120. package/src/bin/check_txe_oracle_version.ts +70 -0
  121. package/src/bin/index.ts +11 -2
  122. package/src/bin/oracle_test_server.ts +51 -0
  123. package/src/constants.ts +13 -0
  124. package/src/dispatcher_pool.ts +316 -0
  125. package/src/index.ts +111 -201
  126. package/src/msgpackr_fr_extension.ts +23 -0
  127. package/src/oracle/interfaces.ts +62 -36
  128. package/src/oracle/test-resolver/fixtures.ts +84 -0
  129. package/src/oracle/test-resolver/index.ts +45 -0
  130. package/src/oracle/test-resolver/resolver.ts +165 -0
  131. package/src/oracle/txe_oracle_public_context.ts +81 -28
  132. package/src/oracle/txe_oracle_registry.ts +401 -0
  133. package/src/oracle/txe_oracle_top_level_context.ts +418 -178
  134. package/src/oracle/txe_oracle_version.ts +17 -0
  135. package/src/oracle/txe_private_execution_oracle.ts +30 -0
  136. package/src/rpc_server.ts +87 -0
  137. package/src/rpc_translator.ts +999 -909
  138. package/src/state_machine/archiver.ts +83 -115
  139. package/src/state_machine/dummy_p2p_client.ts +83 -33
  140. package/src/state_machine/global_variable_builder.ts +39 -6
  141. package/src/state_machine/index.ts +82 -24
  142. package/src/state_machine/mock_epoch_cache.ts +63 -23
  143. package/src/state_machine/synchronizer.ts +10 -9
  144. package/src/txe_session.ts +486 -119
  145. package/src/utils/block_creation.ts +49 -14
  146. package/src/{util → utils}/encoding.ts +9 -3
  147. package/src/utils/tx_effect_creation.ts +5 -12
  148. package/src/{util/txe_account_data_provider.ts → utils/txe_account_store.ts} +1 -1
  149. package/src/utils/txe_artifact_resolver.ts +217 -0
  150. package/src/utils/txe_public_contract_data_source.ts +58 -0
  151. package/src/worker.ts +98 -0
  152. package/dest/util/encoding.d.ts +0 -121
  153. package/dest/util/encoding.d.ts.map +0 -1
  154. package/dest/util/expected_failure_error.d.ts +0 -4
  155. package/dest/util/expected_failure_error.d.ts.map +0 -1
  156. package/dest/util/txe_account_data_provider.d.ts +0 -10
  157. package/dest/util/txe_account_data_provider.d.ts.map +0 -1
  158. package/dest/util/txe_contract_data_provider.d.ts +0 -12
  159. package/dest/util/txe_contract_data_provider.d.ts.map +0 -1
  160. package/dest/util/txe_contract_data_provider.js +0 -22
  161. package/dest/util/txe_public_contract_data_source.d.ts +0 -20
  162. package/dest/util/txe_public_contract_data_source.d.ts.map +0 -1
  163. package/dest/util/txe_public_contract_data_source.js +0 -67
  164. package/src/util/txe_contract_data_provider.ts +0 -36
  165. package/src/util/txe_public_contract_data_source.ts +0 -85
  166. /package/dest/{util → utils}/expected_failure_error.js +0 -0
  167. /package/src/{util → utils}/expected_failure_error.ts +0 -0
@@ -0,0 +1,316 @@
1
+ import { getSchnorrAccountContractArtifact } from '@aztec/accounts/schnorr/lazy';
2
+ import { BackendType, Barretenberg, BarretenbergSync } from '@aztec/bb.js';
3
+ import type { Logger } from '@aztec/foundation/log';
4
+ import { openEphemeralStore } from '@aztec/kv-store/lmdb-v2';
5
+ import { LazyProtocolContractsProvider } from '@aztec/protocol-contracts/providers/lazy';
6
+ import { ContractStore } from '@aztec/pxe/client/lazy';
7
+ import { getStandardAuthRegistry } from '@aztec/standard-contracts/auth-registry';
8
+ import { getContractClassFromArtifact } from '@aztec/stdlib/contract';
9
+
10
+ import { existsSync } from 'node:fs';
11
+ import { cpus } from 'node:os';
12
+ import { fileURLToPath } from 'node:url';
13
+ import { Worker } from 'node:worker_threads';
14
+
15
+ import { TXE_REQUIRED_PROTOCOL_CONTRACTS } from './index.js';
16
+ import type { TXEForeignCallInput } from './index.js';
17
+ import type { ForeignCallResult } from './utils/encoding.js';
18
+
19
+ void Barretenberg.initSingleton({ backend: BackendType.Wasm, skipSrsInit: true, threads: 1 });
20
+ void BarretenbergSync.initSingleton({ backend: BackendType.Wasm });
21
+
22
+ /**
23
+ * Opens a fresh LMDB in a tmp dir and writes the protocol contracts in
24
+ * {@link TXE_REQUIRED_PROTOCOL_CONTRACTS} plus the standard AuthRegistry and the SchnorrAccount artifact,
25
+ * returning the directory path and the SchnorrAccount class id (hex). The store handle is intentionally kept
26
+ * alive: closing it would trigger the ephemeral-store cleanup hook and remove the tmp
27
+ * directory, so any worker that has not yet cloned would find it missing.
28
+ */
29
+ export async function buildSharedContractStore(): Promise<{ dataDir: string; schnorrClassId: string }> {
30
+ const kvStore = await openEphemeralStore('txe-shared-contracts', undefined, 2);
31
+ const dataDir = kvStore.dataDirectory;
32
+ const contractStore = new ContractStore(kvStore);
33
+ const provider = new LazyProtocolContractsProvider();
34
+ const [protocolContracts, standardContracts, schnorrArtifact] = await Promise.all([
35
+ Promise.all(TXE_REQUIRED_PROTOCOL_CONTRACTS.map(name => provider.getProtocolContractArtifact(name))),
36
+ Promise.all([getStandardAuthRegistry()]),
37
+ getSchnorrAccountContractArtifact(),
38
+ ]);
39
+ const schnorrClass = await getContractClassFromArtifact(schnorrArtifact);
40
+ await Promise.all([
41
+ ...[...protocolContracts, ...standardContracts].flatMap(({ instance, artifact, contractClass }) => [
42
+ contractStore.addContractArtifact(artifact, contractClass),
43
+ contractStore.addContractInstance(instance),
44
+ ]),
45
+ contractStore.addContractArtifact(schnorrArtifact, schnorrClass),
46
+ ]);
47
+ return { dataDir, schnorrClassId: schnorrClass.id.toString() };
48
+ }
49
+
50
+ /**
51
+ * Resolves `worker.bundle.js` whether this code is running unbundled (next to dispatcher_pool.js
52
+ * inside `dest/`) or bundled into `dest/bin/index.js` (one directory deeper). `import.meta.url`
53
+ * refers to whichever module the calling code actually lives in; we try both relative locations
54
+ * and use whichever exists.
55
+ */
56
+ function resolveWorkerBundlePath(): URL {
57
+ const candidates = [new URL('./worker.bundle.js', import.meta.url), new URL('../worker.bundle.js', import.meta.url)];
58
+ return candidates.find(u => existsSync(fileURLToPath(u))) ?? candidates[0];
59
+ }
60
+
61
+ interface SerializedError {
62
+ message: string;
63
+ name?: string;
64
+ stack?: string;
65
+ }
66
+
67
+ type WorkerMessage =
68
+ | { type: 'result'; requestId: number; ok: true; value: ForeignCallResult }
69
+ | { type: 'result'; requestId: number; ok: false; error: SerializedError }
70
+ | {
71
+ type: 'memstat';
72
+ sessions: number;
73
+ rss: number;
74
+ heapTotal: number;
75
+ heapUsed: number;
76
+ external: number;
77
+ arrayBuffers: number;
78
+ };
79
+
80
+ interface WorkerSlot {
81
+ worker: Worker;
82
+ sessions: Set<number>;
83
+ inFlightRequestIds: Set<number>;
84
+ }
85
+
86
+ interface PendingRequest {
87
+ resolve: (value: ForeignCallResult) => void;
88
+ reject: (err: Error) => void;
89
+ workerIdx: number;
90
+ }
91
+
92
+ function deserializeError(payload: SerializedError | undefined): Error {
93
+ if (!payload) {
94
+ return new Error('Worker returned an error with no payload');
95
+ }
96
+ const err = new Error(payload.message);
97
+ if (payload.name) {
98
+ err.name = payload.name;
99
+ }
100
+ if (payload.stack) {
101
+ err.stack = payload.stack;
102
+ }
103
+ return err;
104
+ }
105
+
106
+ export interface TXEDispatcherPoolOptions {
107
+ /** Number of worker threads */
108
+ workers?: number;
109
+ }
110
+
111
+ /**
112
+ * Main-thread router that owns a pool of TXE worker threads. Each worker runs its own
113
+ * {@link TXEDispatcher} and handles foreign-call requests for the sessions assigned to it.
114
+ *
115
+ * Routing is sticky by `session_id`: new sessions go to a freshly spawned worker (up to
116
+ * `maxWorkers`) or, once the cap is reached, to the existing worker with the fewest sessions.
117
+ * Each session's state — TXESession, native world state, KV stores — stays single-threaded
118
+ * within its worker; different sessions run in parallel across workers.
119
+ *
120
+ * The main thread builds a shared protocol-contracts LMDB once and passes its path via
121
+ * `workerData`. Workers clone the data file on demand instead of re-registering the contracts.
122
+ */
123
+ export class TXEDispatcherPool {
124
+ private readonly workers: WorkerSlot[] = [];
125
+ private readonly sessionToWorker = new Map<number, number>();
126
+ private readonly pending = new Map<number, PendingRequest>();
127
+ private nextRequestId = 0;
128
+ private readonly maxWorkers: number;
129
+ private readonly readyPromise: Promise<void>;
130
+ private contractStoreSourceDir?: string;
131
+ private schnorrClassId?: string;
132
+ private workerPath?: URL;
133
+
134
+ constructor(
135
+ private readonly logger: Logger,
136
+ opts: TXEDispatcherPoolOptions = {},
137
+ ) {
138
+ // TXE still doesn't scale well beyond 16 workers due to contention
139
+ this.maxWorkers = Math.max(1, opts.workers ?? Math.min(cpus().length, 16));
140
+ this.readyPromise = this.init();
141
+ }
142
+
143
+ /** Resolves once the shared protocol-contracts store is built. Workers spawn lazily on demand. */
144
+ public ready(): Promise<void> {
145
+ return this.readyPromise;
146
+ }
147
+
148
+ private async init(): Promise<void> {
149
+ const t0 = Date.now();
150
+ const { dataDir, schnorrClassId } = await buildSharedContractStore();
151
+ this.contractStoreSourceDir = dataDir;
152
+ this.schnorrClassId = schnorrClassId;
153
+ this.workerPath = resolveWorkerBundlePath();
154
+ this.logger.debug(`TXE dispatcher pool ready (lazy spawn, cap=${this.maxWorkers})`, {
155
+ contractStoreSourceDir: dataDir,
156
+ schnorrClassId,
157
+ ms: Date.now() - t0,
158
+ });
159
+ }
160
+
161
+ /**
162
+ * Spawns a fresh worker and returns its index in `this.workers`. Caller must have awaited
163
+ * `init()` so the shared contract store path is set. Messages posted before the worker has
164
+ * finished loading are queued by Node's worker_threads transport.
165
+ */
166
+ private spawnWorker(): number {
167
+ const workerIdx = this.workers.length;
168
+ const w = new Worker(this.workerPath!, {
169
+ workerData: { contractStoreSourceDir: this.contractStoreSourceDir, schnorrClassId: this.schnorrClassId },
170
+ });
171
+ const slot: WorkerSlot = {
172
+ worker: w,
173
+ sessions: new Set(),
174
+ inFlightRequestIds: new Set(),
175
+ };
176
+ this.workers.push(slot);
177
+ w.on('message', (msg: WorkerMessage) => this.handleMessage(workerIdx, msg));
178
+ w.on('error', err => this.handleWorkerError(workerIdx, err));
179
+ w.on('exit', code => {
180
+ if (code !== 0) {
181
+ this.handleWorkerError(workerIdx, new Error(`Worker ${workerIdx} exited with code ${code}`));
182
+ }
183
+ });
184
+ this.logger.debug(`Spawning TXE worker ${workerIdx} on demand`, {
185
+ cap: this.maxWorkers,
186
+ poolSize: this.workers.length,
187
+ });
188
+ return workerIdx;
189
+ }
190
+
191
+ /** Routes a session-dispose request to the worker that owns the session. Fire-and-forget. */
192
+ disposeSession(sessionId: number): void {
193
+ const workerIdx = this.sessionToWorker.get(sessionId);
194
+ if (workerIdx === undefined) {
195
+ throw new Error(`disposeSession: no worker mapped for session ${sessionId}`);
196
+ }
197
+ this.sessionToWorker.delete(sessionId);
198
+ const slot = this.workers[workerIdx];
199
+ if (!slot) {
200
+ throw new Error(`disposeSession: worker ${workerIdx} (session ${sessionId}) missing from pool`);
201
+ }
202
+ slot.sessions.delete(sessionId);
203
+ slot.worker.postMessage({ type: 'dispose-session', sessionId });
204
+ }
205
+
206
+ // eslint-disable-next-line camelcase
207
+ async resolve_foreign_call(callData: TXEForeignCallInput): Promise<ForeignCallResult> {
208
+ // Make sure the shared contract store + worker bundle path are in place before we spawn.
209
+ await this.readyPromise;
210
+ const sessionId = callData.session_id;
211
+ let workerIdx = this.sessionToWorker.get(sessionId);
212
+ if (workerIdx === undefined) {
213
+ workerIdx = this.pickOrSpawnWorker();
214
+ this.sessionToWorker.set(sessionId, workerIdx);
215
+ this.workers[workerIdx].sessions.add(sessionId);
216
+ this.logger.debug(`Routing new session ${sessionId} to worker ${workerIdx}`);
217
+ }
218
+
219
+ const slot = this.workers[workerIdx];
220
+ const requestId = this.nextRequestId++;
221
+ return new Promise<ForeignCallResult>((resolve, reject) => {
222
+ this.pending.set(requestId, { resolve, reject, workerIdx: workerIdx! });
223
+ slot.inFlightRequestIds.add(requestId);
224
+ slot.worker.postMessage({ type: 'foreign-call', requestId, callData });
225
+ });
226
+ }
227
+
228
+ /** Terminates all workers. Used by tests; production TXE exits the process directly. */
229
+ async shutdown(): Promise<void> {
230
+ const slots = this.workers.splice(0, this.workers.length);
231
+ await Promise.all(slots.map(s => s.worker.terminate()));
232
+ for (const [requestId, pending] of this.pending) {
233
+ pending.reject(new Error('TXE dispatcher pool was shut down'));
234
+ this.pending.delete(requestId);
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Returns the index of the worker that should handle a new session. Spawns a fresh worker if
240
+ * the pool hasn't reached its cap; otherwise picks the existing worker with the fewest
241
+ * assigned sessions. Always returns a valid index into `this.workers`.
242
+ */
243
+ private pickOrSpawnWorker(): number {
244
+ if (this.workers.length < this.maxWorkers) {
245
+ return this.spawnWorker();
246
+ }
247
+ let minIdx = 0;
248
+ let minCount = this.workers[0].sessions.size;
249
+ for (let i = 1; i < this.workers.length; i++) {
250
+ const count = this.workers[i].sessions.size;
251
+ if (count < minCount) {
252
+ minIdx = i;
253
+ minCount = count;
254
+ }
255
+ }
256
+ return minIdx;
257
+ }
258
+
259
+ private handleMessage(workerIdx: number, msg: WorkerMessage): void {
260
+ switch (msg.type) {
261
+ case 'result':
262
+ this.handleResult(workerIdx, msg);
263
+ return;
264
+ case 'memstat':
265
+ this.logger.debug(`worker ${workerIdx} memstat`, {
266
+ worker: workerIdx,
267
+ sessions: msg.sessions,
268
+ rssMiB: Math.round(msg.rss / 1024 / 1024),
269
+ heapTotalMiB: Math.round(msg.heapTotal / 1024 / 1024),
270
+ heapUsedMiB: Math.round(msg.heapUsed / 1024 / 1024),
271
+ externalMiB: Math.round(msg.external / 1024 / 1024),
272
+ arrayBuffersMiB: Math.round(msg.arrayBuffers / 1024 / 1024),
273
+ });
274
+ return;
275
+ }
276
+ }
277
+
278
+ private handleResult(workerIdx: number, msg: WorkerMessage & { type: 'result' }): void {
279
+ const pending = this.pending.get(msg.requestId);
280
+ if (!pending) {
281
+ throw new Error(`handleResult: request ${msg.requestId} (worker ${workerIdx}) not in pending map`);
282
+ }
283
+ this.pending.delete(msg.requestId);
284
+ const slot = this.workers[workerIdx];
285
+ if (!slot) {
286
+ throw new Error(`handleResult: worker ${workerIdx} (request ${msg.requestId}) missing from pool`);
287
+ }
288
+ slot.inFlightRequestIds.delete(msg.requestId);
289
+ if (msg.ok) {
290
+ pending.resolve(msg.value);
291
+ } else {
292
+ pending.reject(deserializeError(msg.error));
293
+ }
294
+ }
295
+
296
+ private handleWorkerError(workerIdx: number, err: Error): void {
297
+ this.logger.error(`TXE worker ${workerIdx} crashed; sessions assigned to it will fail`, err);
298
+ const slot = this.workers[workerIdx];
299
+ if (!slot) {
300
+ throw new Error(`handleWorkerError: worker ${workerIdx} missing from pool (orig err: ${err.message})`);
301
+ }
302
+ for (const requestId of slot.inFlightRequestIds) {
303
+ const pending = this.pending.get(requestId);
304
+ if (!pending) {
305
+ throw new Error(`handleWorkerError: in-flight request ${requestId} (worker ${workerIdx}) not in pending map`);
306
+ }
307
+ pending.reject(err);
308
+ this.pending.delete(requestId);
309
+ }
310
+ slot.inFlightRequestIds.clear();
311
+ for (const sessionId of slot.sessions) {
312
+ this.sessionToWorker.delete(sessionId);
313
+ }
314
+ slot.sessions.clear();
315
+ }
316
+ }
package/src/index.ts CHANGED
@@ -1,51 +1,33 @@
1
- import { SchnorrAccountContractArtifact } from '@aztec/accounts/schnorr';
2
- import { type NoirCompiledContract, loadContractArtifact } from '@aztec/aztec.js/abi';
3
- import { AztecAddress } from '@aztec/aztec.js/addresses';
4
- import {
5
- type ContractInstanceWithAddress,
6
- getContractInstanceFromInstantiationParams,
7
- } from '@aztec/aztec.js/contracts';
8
1
  import { Fr } from '@aztec/aztec.js/fields';
9
- import { PublicKeys, deriveKeys } from '@aztec/aztec.js/keys';
10
- import { createSafeJsonRpcServer } from '@aztec/foundation/json-rpc/server';
11
2
  import type { Logger } from '@aztec/foundation/log';
12
- import { type ProtocolContract, protocolContractNames } from '@aztec/protocol-contracts';
13
- import { BundledProtocolContractsProvider } from '@aztec/protocol-contracts/providers/bundle';
14
- import { computeArtifactHash } from '@aztec/stdlib/contract';
15
- import type { ApiSchemaFor, ZodFor } from '@aztec/stdlib/schemas';
16
-
17
- import { createHash } from 'crypto';
18
- import { createReadStream } from 'fs';
19
- import { readFile, readdir } from 'fs/promises';
20
- import { join, parse } from 'path';
3
+ import { cloneEphemeralStoreFrom } from '@aztec/kv-store/lmdb-v2';
4
+ import type { ProtocolContractName } from '@aztec/protocol-contracts';
5
+ import { ContractStore } from '@aztec/pxe/client/lazy';
6
+ import type { ApiSchemaFor } from '@aztec/stdlib/schemas';
7
+ import { zodFor } from '@aztec/stdlib/schemas';
8
+
9
+ import { join } from 'path';
21
10
  import { z } from 'zod';
22
11
 
12
+ // Side-effect import: registers the msgpackr Fr extension for the bundled `Fr` class. Must
13
+ // be loaded before any `sendMessage` call. See msgpackr_fr_extension.ts for the why.
14
+ import './msgpackr_fr_extension.js';
23
15
  import { type TXEOracleFunctionName, TXESession } from './txe_session.js';
24
16
  import {
25
17
  type ForeignCallArgs,
26
18
  ForeignCallArgsSchema,
27
- type ForeignCallArray,
28
19
  type ForeignCallResult,
29
20
  ForeignCallResultSchema,
30
- type ForeignCallSingle,
31
- fromArray,
32
- fromSingle,
33
- toSingle,
34
- } from './util/encoding.js';
35
- import type { ContractArtifactWithHash } from './util/txe_contract_data_provider.js';
21
+ } from './utils/encoding.js';
22
+ import { TXEArtifactResolver } from './utils/txe_artifact_resolver.js';
36
23
 
37
- const sessions = new Map<number, TXESession>();
24
+ // Protocol contracts TXE registers in its contract store. Only AuthRegistry is needed for the
25
+ // current test suites; add a contract here if a lookup against a `0x000…00X` address fails.
26
+ export const TXE_REQUIRED_PROTOCOL_CONTRACTS: ProtocolContractName[] = [];
38
27
 
39
- /*
40
- * TXE typically has to load the same contract artifacts over and over again for multiple tests,
41
- * so we cache them here to avoid both loading them from disk repeatedly and computing their artifact hashes
42
- */
43
- const TXEArtifactsCache = new Map<
44
- string,
45
- { artifact: ContractArtifactWithHash; instance: ContractInstanceWithAddress }
46
- >();
28
+ const sessions = new Map<number, TXESession>();
47
29
 
48
- type TXEForeignCallInput = {
30
+ export type TXEForeignCallInput = {
49
31
  session_id: number;
50
32
  function: TXEOracleFunctionName;
51
33
  root_path: string;
@@ -53,189 +35,117 @@ type TXEForeignCallInput = {
53
35
  inputs: ForeignCallArgs;
54
36
  };
55
37
 
56
- const TXEForeignCallInputSchema = z.object({
57
- // eslint-disable-next-line camelcase
58
- session_id: z.number().int().nonnegative(),
59
- function: z.string() as ZodFor<TXEOracleFunctionName>,
60
- // eslint-disable-next-line camelcase
61
- root_path: z.string(),
62
- // eslint-disable-next-line camelcase
63
- package_name: z.string(),
64
- inputs: ForeignCallArgsSchema,
65
- }) satisfies ZodFor<TXEForeignCallInput>;
66
-
67
- class TXEDispatcher {
68
- private protocolContracts!: ProtocolContract[];
69
-
70
- constructor(private logger: Logger) {}
71
-
72
- private fastHashFile(path: string) {
73
- return new Promise(resolve => {
74
- const fd = createReadStream(path);
75
- const hash = createHash('sha1');
76
- hash.setEncoding('hex');
77
-
78
- fd.on('end', function () {
79
- hash.end();
80
- resolve(hash.read());
81
- });
82
-
83
- fd.pipe(hash);
84
- });
85
- }
86
-
87
- async #processDeployInputs({ inputs, root_path: rootPath, package_name: packageName }: TXEForeignCallInput) {
88
- const [contractPath, initializer] = inputs.slice(0, 2).map(input =>
89
- fromArray(input as ForeignCallArray)
90
- .map(char => String.fromCharCode(char.toNumber()))
91
- .join(''),
92
- );
93
-
94
- const decodedArgs = fromArray(inputs[3] as ForeignCallArray);
95
- const secret = fromSingle(inputs[4] as ForeignCallSingle);
96
- const publicKeys = secret.equals(Fr.ZERO) ? PublicKeys.default() : (await deriveKeys(secret)).publicKeys;
97
- const publicKeysHash = await publicKeys.hash();
98
-
99
- let artifactPath = '';
100
- const { dir: contractDirectory, base: contractFilename } = parse(contractPath);
101
- if (contractDirectory) {
102
- if (contractDirectory.includes('@')) {
103
- // We're deploying a contract that belongs in a workspace
104
- // env.deploy("../path/to/workspace/root@packageName/contractName")
105
- const [workspace, pkg] = contractDirectory.split('@');
106
- const targetPath = join(rootPath, workspace, '/target');
107
- this.logger.debug(`Looking for compiled artifact in workspace ${targetPath}`);
108
- artifactPath = join(targetPath, `${pkg}-${contractFilename}.json`);
109
- } else {
110
- // We're deploying a standalone external contract
111
- // env.deploy("../path/to/contract/root/contractName")
112
- const targetPath = join(rootPath, contractDirectory, '/target');
113
- this.logger.debug(`Looking for compiled artifact in ${targetPath}`);
114
- [artifactPath] = (await readdir(targetPath)).filter(file => file.endsWith(`-${contractFilename}.json`));
115
- }
116
- } else {
117
- // We're deploying a local contract
118
- // env.deploy("contractName")
119
- artifactPath = join(rootPath, './target', `${packageName}-${contractFilename}.json`);
120
- }
121
-
122
- const fileHash = await this.fastHashFile(artifactPath);
123
-
124
- const cacheKey = `${contractDirectory ?? ''}-${contractFilename}-${initializer}-${decodedArgs
125
- .map(arg => arg.toString())
126
- .join('-')}-${publicKeysHash}-${fileHash}`;
127
-
128
- let instance;
129
- let artifact: ContractArtifactWithHash;
130
-
131
- if (TXEArtifactsCache.has(cacheKey)) {
132
- this.logger.debug(`Using cached artifact for ${cacheKey}`);
133
- ({ artifact, instance } = TXEArtifactsCache.get(cacheKey)!);
134
- } else {
135
- this.logger.debug(`Loading compiled artifact ${artifactPath}`);
136
- const artifactJSON = JSON.parse(await readFile(artifactPath, 'utf-8')) as NoirCompiledContract;
137
- const artifactWithoutHash = loadContractArtifact(artifactJSON);
138
- artifact = {
139
- ...artifactWithoutHash,
140
- // Artifact hash is *very* expensive to compute, so we do it here once
141
- // and the TXE contract data provider can cache it
142
- artifactHash: await computeArtifactHash(artifactWithoutHash),
143
- };
144
- this.logger.debug(
145
- `Deploy ${
146
- artifact.name
147
- } with initializer ${initializer}(${decodedArgs}) and public keys hash ${publicKeysHash.toString()}`,
148
- );
149
- instance = await getContractInstanceFromInstantiationParams(artifact, {
150
- constructorArgs: decodedArgs,
151
- skipArgsDecoding: true,
152
- salt: Fr.ONE,
153
- publicKeys,
154
- constructorArtifact: initializer ? initializer : undefined,
155
- deployer: AztecAddress.ZERO,
156
- });
157
- TXEArtifactsCache.set(cacheKey, { artifact, instance });
158
- }
38
+ export const TXEForeignCallInputSchema = zodFor<TXEForeignCallInput>()(
39
+ z.object({
40
+ // Nargo generates session_id as a u64, which may exceed Number.MAX_SAFE_INTEGER.
41
+ // Zod 4's `.int()` enforces the safe-integer bound, so we drop it here and only require
42
+ // the value to be a non-negative number (it is used solely as a Map key).
43
+ // eslint-disable-next-line camelcase
44
+ session_id: z.number().nonnegative(),
45
+ function: z.string() as z.ZodType<TXEOracleFunctionName>,
46
+ // eslint-disable-next-line camelcase
47
+ root_path: z.string(),
48
+ // eslint-disable-next-line camelcase
49
+ package_name: z.string(),
50
+ inputs: ForeignCallArgsSchema,
51
+ }),
52
+ );
53
+
54
+ export interface TXEDispatcherOptions {
55
+ /**
56
+ * Path to an LMDB directory holding the required protocol contracts (see
57
+ * {@link TXE_REQUIRED_PROTOCOL_CONTRACTS}) and the SchnorrAccount artifact. When set, the
58
+ * dispatcher clones this directory into a fresh tmpdir on first use instead of registering
59
+ * the contracts itself.
60
+ */
61
+ contractStoreSourceDir: string;
62
+ /**
63
+ * Class id (hex) of the SchnorrAccount artifact pre-registered in the shared LMDB. The
64
+ * {@link TXEArtifactResolver} looks the artifact up from the cloned store via this class id
65
+ * instead of recomputing it via `getSchnorrAccountContractArtifact()` + `computeArtifactHash()`.
66
+ */
67
+ schnorrClassId: string;
68
+ }
159
69
 
160
- inputs.splice(0, 1, artifact, instance, toSingle(secret));
70
+ export class TXEDispatcher {
71
+ private contractStore!: ContractStore;
72
+ private artifactResolver!: TXEArtifactResolver;
73
+ private readonly contractStoreSourceDir: string;
74
+ private readonly schnorrClassId: Fr;
75
+
76
+ constructor(
77
+ private logger: Logger,
78
+ opts: TXEDispatcherOptions,
79
+ ) {
80
+ this.contractStoreSourceDir = opts.contractStoreSourceDir;
81
+ this.schnorrClassId = Fr.fromString(opts.schnorrClassId);
161
82
  }
162
83
 
163
- async #processAddAccountInputs({ inputs }: TXEForeignCallInput) {
164
- const secret = fromSingle(inputs[0] as ForeignCallSingle);
165
-
166
- const cacheKey = `SchnorrAccountContract-${secret}`;
167
-
168
- let artifact: ContractArtifactWithHash;
169
- let instance;
170
-
171
- if (TXEArtifactsCache.has(cacheKey)) {
172
- this.logger.debug(`Using cached artifact for ${cacheKey}`);
173
- ({ artifact, instance } = TXEArtifactsCache.get(cacheKey)!);
174
- } else {
175
- const keys = await deriveKeys(secret);
176
- const args = [keys.publicKeys.masterIncomingViewingPublicKey.x, keys.publicKeys.masterIncomingViewingPublicKey.y];
177
- artifact = {
178
- ...SchnorrAccountContractArtifact,
179
- // Artifact hash is *very* expensive to compute, so we do it here once
180
- // and the TXE contract data provider can cache it
181
- artifactHash: await computeArtifactHash(SchnorrAccountContractArtifact),
182
- };
183
- instance = await getContractInstanceFromInstantiationParams(artifact, {
184
- constructorArgs: args,
185
- skipArgsDecoding: true,
186
- salt: Fr.ONE,
187
- publicKeys: keys.publicKeys,
188
- constructorArtifact: 'constructor',
189
- deployer: AztecAddress.ZERO,
190
- });
191
- TXEArtifactsCache.set(cacheKey, { artifact, instance });
84
+ /**
85
+ * Clones the pre-populated LMDB at `contractStoreSourceDir` into a fresh per-instance tmpdir
86
+ * on first use, so this dispatcher has a writable store already containing the required
87
+ * protocol contracts + SchnorrAccount. Idempotent — subsequent calls are no-ops.
88
+ */
89
+ private async warmUp(): Promise<void> {
90
+ if (this.contractStore) {
91
+ return;
192
92
  }
193
-
194
- inputs.splice(0, 0, artifact, instance);
93
+ const t0 = Date.now();
94
+ const kvStore = await cloneEphemeralStoreFrom(
95
+ join(this.contractStoreSourceDir, 'data.mdb'),
96
+ 'txe-contracts',
97
+ undefined,
98
+ 2,
99
+ );
100
+ this.contractStore = new ContractStore(kvStore);
101
+ this.artifactResolver = new TXEArtifactResolver(this.contractStore, this.schnorrClassId);
102
+ this.logger.debug('Cloned shared protocol-contracts store', { totalMs: Date.now() - t0 });
195
103
  }
196
104
 
197
105
  // eslint-disable-next-line camelcase
198
106
  async resolve_foreign_call(callData: TXEForeignCallInput): Promise<ForeignCallResult> {
199
- const { session_id: sessionId, function: functionName, inputs } = callData;
107
+ const {
108
+ session_id: sessionId,
109
+ function: functionName,
110
+ inputs,
111
+ root_path: rootPath,
112
+ package_name: packageName,
113
+ } = callData;
200
114
  this.logger.debug(`Calling ${functionName} on session ${sessionId}`);
201
115
 
202
116
  if (!sessions.has(sessionId)) {
203
117
  this.logger.debug(`Creating new session ${sessionId}`);
204
- if (!this.protocolContracts) {
205
- this.protocolContracts = await Promise.all(
206
- protocolContractNames.map(name => new BundledProtocolContractsProvider().getProtocolContractArtifact(name)),
207
- );
208
- }
209
- sessions.set(sessionId, await TXESession.init(this.protocolContracts));
210
- }
211
-
212
- switch (functionName) {
213
- case 'txeDeploy': {
214
- await this.#processDeployInputs(callData);
215
- break;
216
- }
217
- case 'txeAddAccount': {
218
- await this.#processAddAccountInputs(callData);
219
- break;
220
- }
118
+ await this.warmUp();
119
+ sessions.set(sessionId, await TXESession.init(this.contractStore, this.artifactResolver, rootPath, packageName));
221
120
  }
222
121
 
223
122
  return await sessions.get(sessionId)!.processFunction(functionName, inputs);
224
123
  }
124
+
125
+ /**
126
+ * Releases a session and its resources (per-session LMDB + `NativeWorldStateService`).
127
+ * Called by the dispatcher pool when nargo closes its TCP connection for a test (see
128
+ * `rpc_server.ts`'s socket tracker). No-op if the session was never created — that happens
129
+ * when nargo opens a connection but errors before sending a request.
130
+ */
131
+ async disposeSession(sessionId: number): Promise<void> {
132
+ const session = sessions.get(sessionId);
133
+ if (!session) {
134
+ return;
135
+ }
136
+ sessions.delete(sessionId);
137
+ await session.dispose();
138
+ }
225
139
  }
226
140
 
227
- const TXEDispatcherApiSchema: ApiSchemaFor<TXEDispatcher> = {
141
+ /** Diagnostic-only: number of sessions currently held by this worker. */
142
+ export function activeSessionCount(): number {
143
+ return sessions.size;
144
+ }
145
+
146
+ export const TXEDispatcherApiSchema: ApiSchemaFor<TXEDispatcher> = {
228
147
  // eslint-disable-next-line camelcase
229
- resolve_foreign_call: z.function().args(TXEForeignCallInputSchema).returns(ForeignCallResultSchema),
148
+ resolve_foreign_call: z.function({ input: z.tuple([TXEForeignCallInputSchema]), output: ForeignCallResultSchema }),
149
+ // disposeSession is invoked over IPC from the worker, not via RPC; required by ApiSchemaFor.
150
+ disposeSession: z.function({ input: z.tuple([z.number().nonnegative()]), output: z.void() }),
230
151
  };
231
-
232
- /**
233
- * Creates an RPC server that forwards calls to the TXE.
234
- * @param logger - Logger to output to
235
- * @returns A TXE RPC server.
236
- */
237
- export function createTXERpcServer(logger: Logger) {
238
- return createSafeJsonRpcServer(new TXEDispatcher(logger), TXEDispatcherApiSchema, {
239
- http200OnError: true,
240
- });
241
- }