@aztec/txe 0.0.0-test.1 → 0.0.1-commit.017a351
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/ContractClassRegistry-PII7Q556.js +3 -0
- package/dest/ContractClassRegistry-PII7Q556.js.map +7 -0
- package/dest/ContractInstanceRegistry-3MHLGFNZ.js +3 -0
- package/dest/ContractInstanceRegistry-3MHLGFNZ.js.map +7 -0
- package/dest/FeeJuice-TQV5AQK7.js +3 -0
- package/dest/FeeJuice-TQV5AQK7.js.map +7 -0
- package/dest/MultiCallEntrypoint-SBJUIJY7.js +3 -0
- package/dest/MultiCallEntrypoint-SBJUIJY7.js.map +7 -0
- package/dest/SchnorrAccount-MQXPIZ44.js +3 -0
- package/dest/SchnorrAccount-MQXPIZ44.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.d.ts +1 -1
- package/dest/bin/index.js +3 -29
- 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-BA54BEZH.js +265 -0
- package/dest/chunk-BA54BEZH.js.map +7 -0
- package/dest/chunk-BJVAAXNA.js +3 -0
- package/dest/chunk-BJVAAXNA.js.map +7 -0
- package/dest/chunk-ZKW35DT6.js +304 -0
- package/dest/chunk-ZKW35DT6.js.map +7 -0
- package/dest/constants.d.ts +7 -0
- package/dest/constants.d.ts.map +1 -0
- package/dest/constants.js +10 -0
- package/dest/dispatcher_pool.d.ts +67 -0
- package/dest/dispatcher_pool.d.ts.map +1 -0
- package/dest/dispatcher_pool.js +284 -0
- package/dest/index.d.ts +185 -7
- package/dest/index.d.ts.map +1 -1
- package/dest/index.js +76 -132
- package/dest/metafile.json +38691 -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 +83 -0
- package/dest/oracle/interfaces.d.ts.map +1 -0
- package/dest/oracle/interfaces.js +3 -0
- package/dest/oracle/test-resolver/fixtures.d.ts +43 -0
- package/dest/oracle/test-resolver/fixtures.d.ts.map +1 -0
- package/dest/oracle/test-resolver/fixtures.js +39 -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 +33 -0
- package/dest/oracle/test-resolver/resolver.d.ts +34 -0
- package/dest/oracle/test-resolver/resolver.d.ts.map +1 -0
- package/dest/oracle/test-resolver/resolver.js +114 -0
- package/dest/oracle/txe_oracle_public_context.d.ts +58 -0
- package/dest/oracle/txe_oracle_public_context.d.ts.map +1 -0
- package/dest/oracle/txe_oracle_public_context.js +164 -0
- package/dest/oracle/txe_oracle_registry.d.ts +147 -0
- package/dest/oracle/txe_oracle_registry.d.ts.map +1 -0
- package/dest/oracle/txe_oracle_registry.js +562 -0
- package/dest/oracle/txe_oracle_top_level_context.d.ts +85 -0
- package/dest/oracle/txe_oracle_top_level_context.d.ts.map +1 -0
- package/dest/oracle/txe_oracle_top_level_context.js +634 -0
- 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 +120 -0
- package/dest/rpc_translator.d.ts.map +1 -0
- package/dest/rpc_translator.js +882 -0
- package/dest/server.bundle.js +3 -0
- package/dest/server.bundle.js.map +7 -0
- package/dest/state_machine/archiver.d.ts +32 -0
- package/dest/state_machine/archiver.d.ts.map +1 -0
- package/dest/state_machine/archiver.js +96 -0
- package/dest/state_machine/dummy_p2p_client.d.ts +65 -0
- package/dest/state_machine/dummy_p2p_client.d.ts.map +1 -0
- package/dest/state_machine/dummy_p2p_client.js +165 -0
- package/dest/state_machine/global_variable_builder.d.ts +16 -0
- package/dest/state_machine/global_variable_builder.d.ts.map +1 -0
- package/dest/state_machine/global_variable_builder.js +28 -0
- package/dest/state_machine/index.d.ts +20 -0
- package/dest/state_machine/index.d.ts.map +1 -0
- package/dest/state_machine/index.js +86 -0
- package/dest/state_machine/mock_epoch_cache.d.ts +42 -0
- package/dest/state_machine/mock_epoch_cache.d.ts.map +1 -0
- package/dest/state_machine/mock_epoch_cache.js +85 -0
- package/dest/state_machine/synchronizer.d.ts +33 -0
- package/dest/state_machine/synchronizer.d.ts.map +1 -0
- package/dest/state_machine/synchronizer.js +59 -0
- package/dest/txe_session.d.ts +140 -0
- package/dest/txe_session.d.ts.map +1 -0
- package/dest/txe_session.js +499 -0
- package/dest/utils/block_creation.d.ts +28 -0
- package/dest/utils/block_creation.d.ts.map +1 -0
- package/dest/utils/block_creation.js +58 -0
- package/dest/utils/encoding.d.ts +191 -0
- package/dest/utils/encoding.d.ts.map +1 -0
- package/dest/utils/encoding.js +136 -0
- package/dest/utils/expected_failure_error.d.ts +4 -0
- package/dest/utils/expected_failure_error.d.ts.map +1 -0
- package/dest/utils/tx_effect_creation.d.ts +5 -0
- package/dest/utils/tx_effect_creation.d.ts.map +1 -0
- package/dest/utils/tx_effect_creation.js +13 -0
- package/dest/utils/txe_account_store.d.ts +10 -0
- package/dest/utils/txe_account_store.d.ts.map +1 -0
- package/dest/{util/txe_account_data_provider.js → utils/txe_account_store.js} +1 -1
- 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 +48 -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 +52 -29
- package/src/bin/check_txe_oracle_version.ts +70 -0
- package/src/bin/index.ts +14 -4
- package/src/bin/oracle_test_server.ts +51 -0
- package/src/constants.ts +13 -0
- package/src/dispatcher_pool.ts +316 -0
- package/src/index.ts +113 -175
- package/src/msgpackr_fr_extension.ts +23 -0
- package/src/oracle/interfaces.ts +109 -0
- package/src/oracle/test-resolver/fixtures.ts +84 -0
- package/src/oracle/test-resolver/index.ts +45 -0
- package/src/oracle/test-resolver/resolver.ts +165 -0
- package/src/oracle/txe_oracle_public_context.ts +218 -0
- package/src/oracle/txe_oracle_registry.ts +401 -0
- package/src/oracle/txe_oracle_top_level_context.ts +898 -0
- 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 +1103 -0
- package/src/state_machine/archiver.ts +119 -0
- package/src/state_machine/dummy_p2p_client.ts +247 -0
- package/src/state_machine/global_variable_builder.ts +53 -0
- package/src/state_machine/index.ts +135 -0
- package/src/state_machine/mock_epoch_cache.ts +107 -0
- package/src/state_machine/synchronizer.ts +88 -0
- package/src/txe_session.ts +799 -0
- package/src/utils/block_creation.ts +97 -0
- package/src/utils/encoding.ts +172 -0
- package/src/utils/tx_effect_creation.ts +30 -0
- package/src/{util/txe_account_data_provider.ts → utils/txe_account_store.ts} +1 -1
- package/src/utils/txe_artifact_resolver.ts +217 -0
- package/src/utils/txe_public_contract_data_source.ts +58 -0
- package/src/worker.ts +98 -0
- package/dest/node/txe_node.d.ts +0 -358
- package/dest/node/txe_node.d.ts.map +0 -1
- package/dest/node/txe_node.js +0 -504
- package/dest/oracle/txe_oracle.d.ts +0 -152
- package/dest/oracle/txe_oracle.d.ts.map +0 -1
- package/dest/oracle/txe_oracle.js +0 -833
- package/dest/txe_service/txe_service.d.ts +0 -212
- package/dest/txe_service/txe_service.d.ts.map +0 -1
- package/dest/txe_service/txe_service.js +0 -572
- package/dest/util/encoding.d.ts +0 -103
- package/dest/util/encoding.d.ts.map +0 -1
- package/dest/util/encoding.js +0 -76
- package/dest/util/expected_failure_error.d.ts +0 -4
- package/dest/util/expected_failure_error.d.ts.map +0 -1
- package/dest/util/txe_account_data_provider.d.ts +0 -10
- package/dest/util/txe_account_data_provider.d.ts.map +0 -1
- package/dest/util/txe_public_contract_data_source.d.ts +0 -20
- package/dest/util/txe_public_contract_data_source.d.ts.map +0 -1
- package/dest/util/txe_public_contract_data_source.js +0 -88
- package/dest/util/txe_world_state_db.d.ts +0 -14
- package/dest/util/txe_world_state_db.d.ts.map +0 -1
- package/dest/util/txe_world_state_db.js +0 -27
- package/src/node/txe_node.ts +0 -725
- package/src/oracle/txe_oracle.ts +0 -1241
- package/src/txe_service/txe_service.ts +0 -749
- package/src/util/encoding.ts +0 -92
- package/src/util/txe_public_contract_data_source.ts +0 -101
- package/src/util/txe_world_state_db.ts +0 -38
- /package/dest/{util → utils}/expected_failure_error.js +0 -0
- /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,213 +1,151 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
AztecAddress,
|
|
4
|
-
type ContractArtifact,
|
|
5
|
-
type ContractInstanceWithAddress,
|
|
6
|
-
Fr,
|
|
7
|
-
PublicKeys,
|
|
8
|
-
deriveKeys,
|
|
9
|
-
getContractInstanceFromDeployParams,
|
|
10
|
-
loadContractArtifact,
|
|
11
|
-
} from '@aztec/aztec.js';
|
|
12
|
-
import { createSafeJsonRpcServer } from '@aztec/foundation/json-rpc/server';
|
|
1
|
+
import { Fr } from '@aztec/aztec.js/fields';
|
|
13
2
|
import type { Logger } from '@aztec/foundation/log';
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
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';
|
|
6
|
+
import type { ApiSchemaFor } from '@aztec/stdlib/schemas';
|
|
7
|
+
import { zodFor } from '@aztec/stdlib/schemas';
|
|
17
8
|
|
|
18
|
-
import { readFile, readdir } from 'fs/promises';
|
|
19
9
|
import { join } from 'path';
|
|
20
10
|
import { z } from 'zod';
|
|
21
11
|
|
|
22
|
-
import
|
|
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';
|
|
15
|
+
import { type TXEOracleFunctionName, TXESession } from './txe_session.js';
|
|
23
16
|
import {
|
|
24
17
|
type ForeignCallArgs,
|
|
25
18
|
ForeignCallArgsSchema,
|
|
26
|
-
type ForeignCallArray,
|
|
27
19
|
type ForeignCallResult,
|
|
28
20
|
ForeignCallResultSchema,
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
fromSingle,
|
|
32
|
-
toForeignCallResult,
|
|
33
|
-
toSingle,
|
|
34
|
-
} from './util/encoding.js';
|
|
35
|
-
|
|
36
|
-
const TXESessions = new Map<number, TXEService>();
|
|
21
|
+
} from './utils/encoding.js';
|
|
22
|
+
import { TXEArtifactResolver } from './utils/txe_artifact_resolver.js';
|
|
37
23
|
|
|
38
|
-
|
|
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[] = [];
|
|
39
27
|
|
|
40
|
-
|
|
41
|
-
[K in keyof T]: T[K] extends (...args: any[]) => any ? K : never;
|
|
42
|
-
}[keyof T];
|
|
28
|
+
const sessions = new Map<number, TXESession>();
|
|
43
29
|
|
|
44
|
-
type TXEForeignCallInput = {
|
|
30
|
+
export type TXEForeignCallInput = {
|
|
45
31
|
session_id: number;
|
|
46
|
-
function:
|
|
32
|
+
function: TXEOracleFunctionName;
|
|
47
33
|
root_path: string;
|
|
48
34
|
package_name: string;
|
|
49
35
|
inputs: ForeignCallArgs;
|
|
50
36
|
};
|
|
51
37
|
|
|
52
|
-
const TXEForeignCallInputSchema =
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
let artifact;
|
|
85
|
-
let instance;
|
|
86
|
-
|
|
87
|
-
if (TXEArtifactsCache.has(cacheKey)) {
|
|
88
|
-
this.logger.debug(`Using cached artifact for ${cacheKey}`);
|
|
89
|
-
({ artifact, instance } = TXEArtifactsCache.get(cacheKey)!);
|
|
90
|
-
} else {
|
|
91
|
-
let artifactPath = '';
|
|
92
|
-
// We're deploying the contract under test
|
|
93
|
-
// env.deploy_self("contractName")
|
|
94
|
-
if (!pathStr) {
|
|
95
|
-
artifactPath = join(rootPath, './target', `${packageName}-${contractName}.json`);
|
|
96
|
-
} else {
|
|
97
|
-
// We're deploying a contract that belongs in a workspace
|
|
98
|
-
// env.deploy("../path/to/workspace/root@packageName", "contractName")
|
|
99
|
-
if (pathStr.includes('@')) {
|
|
100
|
-
const [workspace, pkg] = pathStr.split('@');
|
|
101
|
-
const targetPath = join(rootPath, workspace, './target');
|
|
102
|
-
this.logger.debug(`Looking for compiled artifact in workspace ${targetPath}`);
|
|
103
|
-
artifactPath = join(targetPath, `${pkg}-${contractName}.json`);
|
|
104
|
-
} else {
|
|
105
|
-
// We're deploying a standalone contract
|
|
106
|
-
// env.deploy("../path/to/contract/root", "contractName")
|
|
107
|
-
const targetPath = join(rootPath, pathStr, './target');
|
|
108
|
-
this.logger.debug(`Looking for compiled artifact in ${targetPath}`);
|
|
109
|
-
[artifactPath] = (await readdir(targetPath)).filter(file => file.endsWith(`-${contractName}.json`));
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
this.logger.debug(`Loading compiled artifact ${artifactPath}`);
|
|
113
|
-
artifact = loadContractArtifact(JSON.parse(await readFile(artifactPath, 'utf-8')));
|
|
114
|
-
this.logger.debug(
|
|
115
|
-
`Deploy ${
|
|
116
|
-
artifact.name
|
|
117
|
-
} with initializer ${initializer}(${decodedArgs}) and public keys hash ${publicKeysHash.toString()}`,
|
|
118
|
-
);
|
|
119
|
-
instance = await getContractInstanceFromDeployParams(artifact, {
|
|
120
|
-
constructorArgs: decodedArgs,
|
|
121
|
-
skipArgsDecoding: true,
|
|
122
|
-
salt: Fr.ONE,
|
|
123
|
-
publicKeys,
|
|
124
|
-
constructorArtifact: initializer ? initializer : undefined,
|
|
125
|
-
deployer: AztecAddress.ZERO,
|
|
126
|
-
});
|
|
127
|
-
TXEArtifactsCache.set(cacheKey, { artifact, instance });
|
|
128
|
-
}
|
|
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
|
+
}
|
|
129
69
|
|
|
130
|
-
|
|
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);
|
|
131
82
|
}
|
|
132
83
|
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
if (TXEArtifactsCache.has(cacheKey)) {
|
|
142
|
-
this.logger.debug(`Using cached artifact for ${cacheKey}`);
|
|
143
|
-
({ artifact, instance } = TXEArtifactsCache.get(cacheKey)!);
|
|
144
|
-
} else {
|
|
145
|
-
const keys = await deriveKeys(secret);
|
|
146
|
-
const args = [keys.publicKeys.masterIncomingViewingPublicKey.x, keys.publicKeys.masterIncomingViewingPublicKey.y];
|
|
147
|
-
artifact = SchnorrAccountContractArtifact;
|
|
148
|
-
instance = await getContractInstanceFromDeployParams(artifact, {
|
|
149
|
-
constructorArgs: args,
|
|
150
|
-
skipArgsDecoding: true,
|
|
151
|
-
salt: Fr.ONE,
|
|
152
|
-
publicKeys: keys.publicKeys,
|
|
153
|
-
constructorArtifact: 'constructor',
|
|
154
|
-
deployer: AztecAddress.ZERO,
|
|
155
|
-
});
|
|
156
|
-
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;
|
|
157
92
|
}
|
|
158
|
-
|
|
159
|
-
|
|
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 });
|
|
160
103
|
}
|
|
161
104
|
|
|
162
105
|
// eslint-disable-next-line camelcase
|
|
163
106
|
async resolve_foreign_call(callData: TXEForeignCallInput): Promise<ForeignCallResult> {
|
|
164
|
-
const {
|
|
107
|
+
const {
|
|
108
|
+
session_id: sessionId,
|
|
109
|
+
function: functionName,
|
|
110
|
+
inputs,
|
|
111
|
+
root_path: rootPath,
|
|
112
|
+
package_name: packageName,
|
|
113
|
+
} = callData;
|
|
165
114
|
this.logger.debug(`Calling ${functionName} on session ${sessionId}`);
|
|
166
115
|
|
|
167
|
-
if (!
|
|
116
|
+
if (!sessions.has(sessionId)) {
|
|
168
117
|
this.logger.debug(`Creating new session ${sessionId}`);
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
protocolContractNames.map(name => new BundledProtocolContractsProvider().getProtocolContractArtifact(name)),
|
|
172
|
-
);
|
|
173
|
-
}
|
|
174
|
-
TXESessions.set(sessionId, await TXEService.init(this.logger, this.protocolContracts));
|
|
118
|
+
await this.warmUp();
|
|
119
|
+
sessions.set(sessionId, await TXESession.init(this.contractStore, this.artifactResolver, rootPath, packageName));
|
|
175
120
|
}
|
|
176
121
|
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
TXESessions.delete(sessionId) &&
|
|
180
|
-
this.logger.debug(`Called reset on session ${sessionId}, yeeting it out of existence`);
|
|
181
|
-
return toForeignCallResult([]);
|
|
182
|
-
}
|
|
183
|
-
case 'deploy': {
|
|
184
|
-
await this.#processDeployInputs(callData);
|
|
185
|
-
break;
|
|
186
|
-
}
|
|
187
|
-
case 'addAccount': {
|
|
188
|
-
await this.#processAddAccountInputs(callData);
|
|
189
|
-
break;
|
|
190
|
-
}
|
|
191
|
-
}
|
|
122
|
+
return await sessions.get(sessionId)!.processFunction(functionName, inputs);
|
|
123
|
+
}
|
|
192
124
|
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
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();
|
|
196
138
|
}
|
|
197
139
|
}
|
|
198
140
|
|
|
199
|
-
|
|
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> = {
|
|
200
147
|
// eslint-disable-next-line camelcase
|
|
201
|
-
resolve_foreign_call: z.function(
|
|
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() }),
|
|
202
151
|
};
|
|
203
|
-
|
|
204
|
-
/**
|
|
205
|
-
* Creates an RPC server that forwards calls to the TXE.
|
|
206
|
-
* @param logger - Logger to output to
|
|
207
|
-
* @returns A TXE RPC server.
|
|
208
|
-
*/
|
|
209
|
-
export function createTXERpcServer(logger: Logger) {
|
|
210
|
-
return createSafeJsonRpcServer(new TXEDispatcher(logger), TXEDispatcherApiSchema, {
|
|
211
|
-
http200OnError: true,
|
|
212
|
-
});
|
|
213
|
-
}
|
|
@@ -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
|
+
});
|