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