-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathpublisher-runner.ts
More file actions
523 lines (489 loc) · 19.4 KB
/
publisher-runner.ts
File metadata and controls
523 lines (489 loc) · 19.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
import { join } from 'node:path';
import { DKGAgentWallet } from '@origintrail-official/dkg-agent';
import { EVMChainAdapter, NoChainAdapter } from '@origintrail-official/dkg-chain';
import { TypedEventBus, type Ed25519Keypair } from '@origintrail-official/dkg-core';
import { ACKCollector, AsyncLiftRunner, DKGPublisher, FileWorkspacePublicSnapshotStore, TripleStoreAsyncLiftPublisher, type AsyncLiftPublishExecutionInput, type AsyncLiftPublisher, type AsyncLiftPublisherRecoveryResult, type LiftJobBroadcast, type LiftJobIncluded, type PublishOptions, type WorkspacePublicSnapshotStore } from '@origintrail-official/dkg-publisher';
import { createTripleStore, type TripleStore } from '@origintrail-official/dkg-storage';
import { loadNetworkConfig, resolveChainConfig, type DkgConfig } from './config.js';
import { loadPublisherWallets } from './publisher-wallets.js';
export interface PublisherRuntime {
readonly runner: AsyncLiftRunner;
readonly publisher: AsyncLiftPublisher;
readonly walletIds: string[];
readonly stop: () => Promise<void>;
}
export interface PublisherInspector {
readonly publisher: AsyncLiftPublisher;
readonly stop: () => Promise<void>;
}
interface ACKTransportFactory {
publisherPeerId: string;
gossipPublish: (topic: string, data: Uint8Array) => Promise<void>;
sendP2P: (peerId: string, protocol: string, data: Uint8Array) => Promise<Uint8Array>;
getConnectedCorePeers: () => string[];
/**
* Optional hosting filter, threaded straight through to
* `ACKCollectorDeps.getCorePeersHostingContextGraph`. Implementations
* should consult their local agent registry (e.g. via
* `resolvePeersHostingContextGraph` from `@origintrail-official/dkg-publisher`)
* intersected with currently-connected cores. Optional so existing
* embedders that don't supply a hosting registry still work.
*/
getCorePeersHostingContextGraph?: (cgIdStr: string) => string[] | Promise<string[]>;
log?: (message: string) => void;
}
export async function startPublisherRuntimeIfEnabled(args: {
dataDir: string;
config: DkgConfig;
store: TripleStore;
keypair: Ed25519Keypair;
chainBase?: {
rpcUrl: string;
hubAddress: string;
chainId?: string;
};
log: (message: string) => void;
ackTransportFactory?: () => ACKTransportFactory;
}): Promise<PublisherRuntime | null> {
if (!args.config.publisher?.enabled) {
return null;
}
try {
const runtime = await createPublisherRuntimeFromAgent({
dataDir: args.dataDir,
store: args.store,
keypair: args.keypair,
chainBase: args.chainBase,
pollIntervalMs: args.config.publisher.pollIntervalMs,
errorBackoffMs: args.config.publisher.errorBackoffMs,
maxRetries: args.config.publisher.maxRetries,
config: args.config,
ackTransportFactory: args.ackTransportFactory,
});
await runtime.runner.start();
args.log(`Async publisher runner started (${runtime.walletIds.length} wallet${runtime.walletIds.length === 1 ? '' : 's'})`);
return runtime;
} catch (err: any) {
const message = err?.message ?? String(err);
if (message.includes('No publisher wallets configured')) {
args.log(`Publisher startup skipped: ${message}`);
args.log('Add a wallet with `dkg publisher wallet add <privateKey>` and re-enable publisher startup if needed.');
return null;
}
throw err;
}
}
interface PublisherRuntimeBaseArgs {
dataDir: string;
keypair: Ed25519Keypair;
store: TripleStore;
chainBase?: {
rpcUrl: string;
hubAddress: string;
chainId?: string;
};
pollIntervalMs?: number;
errorBackoffMs?: number;
maxRetries?: number;
ackTransportFactory?: () => ACKTransportFactory;
v10ACKProviderFactory?: () => PublishOptions['v10ACKProvider'];
publicSnapshotStore?: WorkspacePublicSnapshotStore;
closeStoreOnStop: boolean;
}
export async function createPublisherRuntime(args: {
dataDir: string;
config: DkgConfig;
pollIntervalMs?: number;
errorBackoffMs?: number;
maxRetries?: number;
}): Promise<PublisherRuntime> {
const publisherWallets = await loadPublisherWallets(args.dataDir);
if (publisherWallets.wallets.length === 0) {
throw new Error('No publisher wallets configured. Use `dkg publisher wallet add <privateKey>` first.');
}
const network = await loadNetworkConfig();
const keypair = await loadOrCreateAgentWallet(args.dataDir);
const store = await createPublisherStore(args.dataDir, args.config);
const publicSnapshotStore = createPublicSnapshotStore(args.dataDir, args.config);
// Field-merge config + network/<env>.json#chain, then guard for the
// strict { rpcUrl, hubAddress, chainId? } shape the publisher runtime
// expects. If either required field is missing, pass undefined and let
// the runtime fall back to NoChainAdapter (publisher won't have on-chain
// finality but still functions).
const merged = resolveChainConfig(args.config, network);
const chainBase = merged?.rpcUrl && merged?.hubAddress
? { rpcUrl: merged.rpcUrl, hubAddress: merged.hubAddress, chainId: merged.chainId }
: undefined;
return createPublisherRuntimeFromBase({
dataDir: args.dataDir,
keypair: keypair.keypair,
store,
chainBase,
pollIntervalMs: args.pollIntervalMs,
errorBackoffMs: args.errorBackoffMs,
maxRetries: args.maxRetries ?? args.config.publisher?.maxRetries,
publicSnapshotStore,
closeStoreOnStop: true,
});
}
export async function createPublisherInspector(args: {
dataDir: string;
config: DkgConfig;
}): Promise<PublisherInspector> {
const store = await createPublisherStore(args.dataDir, args.config);
return createPublisherInspectorFromStore(store, true, createPublicSnapshotStore(args.dataDir, args.config));
}
export function createPublisherInspectorFromStore(
store: TripleStore,
closeStoreOnStop = false,
publicSnapshotStore?: WorkspacePublicSnapshotStore,
): PublisherInspector {
return {
publisher: new TripleStoreAsyncLiftPublisher(store, { publicSnapshotStore }),
stop: async () => {
if (closeStoreOnStop) {
await store.close();
}
},
};
}
export function createPublisherControlFromStore(
store: TripleStore,
publicSnapshotStore?: WorkspacePublicSnapshotStore,
): AsyncLiftPublisher {
return new TripleStoreAsyncLiftPublisher(store, { publicSnapshotStore });
}
export async function createPublisherRuntimeFromAgent(args: {
dataDir: string;
store: TripleStore;
keypair: Ed25519Keypair;
chainBase?: {
rpcUrl: string;
hubAddress: string;
chainId?: string;
};
pollIntervalMs?: number;
errorBackoffMs?: number;
maxRetries?: number;
config?: Pick<DkgConfig, 'sharedMemoryPublicSnapshotStorage'>;
ackTransportFactory?: () => ACKTransportFactory;
v10ACKProviderFactory?: () => PublishOptions['v10ACKProvider'];
}): Promise<PublisherRuntime> {
return createPublisherRuntimeFromBase({
dataDir: args.dataDir,
keypair: args.keypair,
store: args.store,
chainBase: args.chainBase,
pollIntervalMs: args.pollIntervalMs,
errorBackoffMs: args.errorBackoffMs,
maxRetries: args.maxRetries,
ackTransportFactory: args.ackTransportFactory,
v10ACKProviderFactory: args.v10ACKProviderFactory,
publicSnapshotStore: createPublicSnapshotStore(args.dataDir, args.config),
closeStoreOnStop: false,
});
}
async function createPublisherRuntimeFromBase(args: PublisherRuntimeBaseArgs): Promise<PublisherRuntime> {
const publisherWallets = await loadPublisherWallets(args.dataDir);
if (publisherWallets.wallets.length === 0) {
throw new Error('No publisher wallets configured. Use `dkg publisher wallet add <privateKey>` first.');
}
const eventBus = new TypedEventBus();
const publishers = new Map<string, DKGPublisher>();
const invalidWallets: string[] = [];
for (const wallet of publisherWallets.wallets) {
const chain = args.chainBase
? new EVMChainAdapter({
rpcUrl: args.chainBase.rpcUrl,
privateKey: wallet.privateKey,
hubAddress: args.chainBase.hubAddress,
chainId: args.chainBase.chainId,
allowNoAdminSigner: true,
})
: new NoChainAdapter();
const identityId = await chain.getIdentityId();
if (args.chainBase && identityId === 0n) {
invalidWallets.push(wallet.address);
continue;
}
publishers.set(
wallet.address,
new DKGPublisher({
store: args.store,
chain,
eventBus,
keypair: args.keypair,
publisherNodeIdentityId: identityId,
publisherPrivateKey: wallet.privateKey,
publicSnapshotStore: args.publicSnapshotStore,
}),
);
}
if (invalidWallets.length > 0) {
if (publishers.size === 0) {
const noun = invalidWallets.length === 1 ? 'wallet is' : 'wallets are';
throw new Error(
`Publisher startup blocked: the following publisher ${noun} missing an on-chain identity: ${invalidWallets.join(', ')}. ` +
'Run `dkg identity create` for each wallet or remove it from publisher-wallets.json.',
);
}
const noun = invalidWallets.length === 1 ? 'wallet' : 'wallets';
console.warn(
`[publisher] Skipping ${invalidWallets.length} ${noun} missing on-chain identity: ${invalidWallets.join(', ')}. ` +
`Continuing with ${publishers.size} valid wallet(s).`,
);
}
const hasChainRecovery = [...publishers.values()].some((p) => {
const chain = (p as unknown as { chain?: { resolvePublishByTxHash?: unknown } }).chain;
return typeof chain?.resolvePublishByTxHash === 'function';
});
const asyncPublisher = new TripleStoreAsyncLiftPublisher(args.store, {
chainRecoveryResolver: hasChainRecovery ? createChainRecoveryResolver(publishers) : undefined,
maxRetries: args.maxRetries,
publicSnapshotStore: args.publicSnapshotStore,
publishExecutor: async ({ walletId, publishOptions }: AsyncLiftPublishExecutionInput) => {
const publisher = publishers.get(walletId);
if (!publisher) {
throw new Error(`No publisher configured for wallet ${walletId}`);
}
const v10ACKProvider = publishOptions.v10ACKProvider
?? args.v10ACKProviderFactory?.()
?? createV10ACKProviderForPublisher(publisher, args.ackTransportFactory?.());
const publishOptionsWithACKs = v10ACKProvider
? { ...publishOptions, v10ACKProvider }
: publishOptions;
// Capability gate: use `isV10Ready()` (the authoritative V10 runtime
// signal) rather than probing for `createKnowledgeAssetsV10`. Since the
// interface made the method required, `NoChainAdapter` now implements
// it as a throwing stub, so a `typeof === 'function'` probe would
// mis-route no-chain mode into the V10 ACK-gated path and crash.
const chain = (publisher as unknown as { chain?: { isV10Ready?: () => boolean } }).chain;
if (chain?.isV10Ready?.() && !publishOptionsWithACKs.v10ACKProvider) {
throw new Error(
'Async publisher cannot publish to a V10 ACK-gated chain without a v10ACKProvider. ' +
'Use the synchronous agent publish path or add ACK collection support to the async runtime.',
);
}
return await publisher.publish(publishOptionsWithACKs);
},
});
const validWalletIds = [...publishers.keys()];
const runner = new AsyncLiftRunner({
publisher: asyncPublisher,
walletIds: validWalletIds,
pollIntervalMs: args.pollIntervalMs,
errorBackoffMs: args.errorBackoffMs,
hasIncludedRecoveryResolver: hasChainRecovery,
});
return {
runner,
publisher: asyncPublisher,
walletIds: validWalletIds,
stop: async () => {
await runner.stop();
if (args.closeStoreOnStop) {
await args.store.close();
}
},
};
}
function createV10ACKProviderForPublisher(
publisher: DKGPublisher,
transport?: ACKTransportFactory,
): PublishOptions['v10ACKProvider'] | undefined {
if (!transport) return undefined;
const chain = (publisher as unknown as {
chain?: {
isV10Ready?: () => boolean;
verifyACKIdentity?: (recoveredAddress: string, claimedIdentityId: bigint) => Promise<boolean>;
getMinimumRequiredSignatures?: () => Promise<number>;
getEvmChainId?: () => Promise<bigint>;
getKnowledgeAssetsV10Address?: () => Promise<string>;
};
}).chain;
// `isV10Ready()` is the authoritative capability gate — rejects
// NoChainAdapter (returns false) and unresolved EVM adapters.
if (!chain?.isV10Ready?.()) return undefined;
if (typeof chain.verifyACKIdentity !== 'function') return undefined;
// The H5 prefix requires both a numeric chain id AND the deployed KAV10
// address. Without them the collector cannot build a digest that matches
// what core-node handlers sign, so refuse to hand back a provider at all.
if (typeof chain.getEvmChainId !== 'function') return undefined;
if (typeof chain.getKnowledgeAssetsV10Address !== 'function') return undefined;
const collector = new ACKCollector({
gossipPublish: transport.gossipPublish,
sendP2P: transport.sendP2P,
getConnectedCorePeers: transport.getConnectedCorePeers,
getCorePeersHostingContextGraph: transport.getCorePeersHostingContextGraph,
verifyIdentity: async (recoveredAddress: string, claimedIdentityId: bigint) => chain.verifyACKIdentity!(recoveredAddress, claimedIdentityId),
log: transport.log,
});
return async (
merkleRoot,
contextGraphId,
kaCount,
rootEntities,
publicByteSize,
stagingQuads,
epochs,
tokenAmount,
swmGraphId,
subGraphName,
merkleLeafCount,
) => {
// Fail loud on non-numeric or non-positive CG ids. V10 publish requires
// a real on-chain context graph; `ZeroContextGraphId` at
// `KnowledgeAssetsV10.sol:379` rejects cgId 0 on chain. Reject `<= 0n`
// rather than `=== 0n` so `BigInt("-1") === -1n` is caught here instead
// of dying in ethers' uint256 encoder inside the evm-adapter.
// `contextGraphId` here is the TARGET on-chain numeric id; `swmGraphId`
// (optional) is the source SWM graph name and is NOT required to be
// numeric.
let cgIdBigInt: bigint;
try {
cgIdBigInt = BigInt(contextGraphId);
} catch {
throw new Error(
`Async V10 publish requires a numeric on-chain context graph id; ` +
`got '${contextGraphId}'. Register the CG on-chain via ContextGraphs.createContextGraph first.`,
);
}
if (cgIdBigInt <= 0n) {
throw new Error(
`Async V10 publish requires a positive on-chain context graph id; got ${cgIdBigInt}. ` +
`Register the CG on-chain via ContextGraphs.createContextGraph first.`,
);
}
if (!Number.isInteger(merkleLeafCount) || merkleLeafCount < 1) {
throw new Error(
`Async V10 publish requires a positive integer merkleLeafCount; got ${merkleLeafCount}. ` +
'Publishers must pass the V10 flat-KC leaf count computed by V10MerkleTree.',
);
}
const requiredACKs = typeof chain.getMinimumRequiredSignatures === 'function'
? await chain.getMinimumRequiredSignatures()
: undefined;
// Both values are guaranteed present here by the adapter-capability
// check at the top of this factory — re-resolving on every publish
// keeps the provider agnostic to hot adapter swaps.
const chainIdBig = await chain.getEvmChainId!();
const kav10Address = await chain.getKnowledgeAssetsV10Address!();
const result = await collector.collect({
merkleRoot,
contextGraphId: cgIdBigInt,
contextGraphIdStr: contextGraphId,
publisherPeerId: transport.publisherPeerId,
publicByteSize,
isPrivate: false,
kaCount,
rootEntities,
chainId: chainIdBig,
kav10Address,
requiredACKs,
stagingQuads,
epochs,
tokenAmount,
swmGraphId,
subGraphName,
merkleLeafCount,
});
return result.acks;
};
}
function createChainRecoveryResolver(
publishers: Map<string, DKGPublisher>,
): (job: LiftJobBroadcast | LiftJobIncluded) => Promise<AsyncLiftPublisherRecoveryResult | null> {
return async (job) => {
const publisher = publishers.get(job.broadcast.walletId);
if (!publisher) return null;
const chain = (publisher as unknown as { chain?: { resolvePublishByTxHash?: (txHash: string) => Promise<any> } }).chain;
if (!chain?.resolvePublishByTxHash) return null;
let result: any;
try {
result = await chain.resolvePublishByTxHash(job.broadcast.txHash);
} catch {
// Transient RPC/provider errors — treat as inconclusive (null) so the
// recovery timeout mechanism handles it rather than crashing the daemon.
return null;
}
if (!result) return null;
return {
inclusion: {
txHash: result.txHash as `0x${string}`,
blockNumber: result.blockNumber,
blockTimestamp: result.blockTimestamp,
},
finalization: {
mode: 'published',
txHash: result.txHash as `0x${string}`,
batchId: result.batchId.toString() as `${bigint}`,
startKAId: result.startKAId?.toString() as `${bigint}` | undefined,
endKAId: result.endKAId?.toString() as `${bigint}` | undefined,
publisherAddress: result.publisherAddress as `0x${string}`,
},
};
};
}
export function parsePositiveMsOption(value: string, optionName: '--poll-interval' | '--error-backoff'): number {
const parsed = Number.parseInt(value, 10);
if (!Number.isFinite(parsed) || parsed < 1) {
throw new Error(`${optionName} must be a positive integer in milliseconds`);
}
return parsed;
}
export function parsePositiveIntegerOption(value: string, optionName: string): number {
const parsed = Number.parseInt(value, 10);
if (!Number.isFinite(parsed) || parsed < 1) {
throw new Error(`${optionName} must be a positive integer`);
}
return parsed;
}
async function createPublisherStore(dataDir: string, config: DkgConfig): Promise<TripleStore> {
if (config.store) {
const storeConfig = config.store as any;
return await createTripleStore({
...storeConfig,
largeLiteralStorage: config.largeLiteralStorage ?? (
isLocalOxigraphStoreConfig(storeConfig)
? defaultLargeLiteralStorage(dataDir, config)
: undefined
),
});
}
return await createTripleStore({
backend: 'oxigraph-worker',
options: { path: join(dataDir, 'store.nq') },
largeLiteralStorage: defaultLargeLiteralStorage(dataDir, config),
});
}
function defaultLargeLiteralStorage(dataDir: string, config: DkgConfig) {
return {
enabled: config.largeLiteralStorage?.enabled ?? true,
thresholdBytes: config.largeLiteralStorage?.thresholdBytes,
directory: config.largeLiteralStorage?.directory ?? join(dataDir, 'literal-blobs'),
};
}
export function createPublicSnapshotStore(
dataDir: string,
config?: Pick<DkgConfig, 'sharedMemoryPublicSnapshotStorage'>,
): WorkspacePublicSnapshotStore | undefined {
const snapshotConfig = config?.sharedMemoryPublicSnapshotStorage;
if (snapshotConfig?.enabled === false) {
return undefined;
}
return new FileWorkspacePublicSnapshotStore(snapshotConfig?.directory ?? join(dataDir, 'swm-public-snapshots'));
}
function isLocalOxigraphStoreConfig(storeConfig: { backend?: unknown }): boolean {
return storeConfig.backend === 'oxigraph'
|| storeConfig.backend === 'oxigraph-worker'
|| storeConfig.backend === 'oxigraph-persistent';
}
async function loadOrCreateAgentWallet(dataDir: string): Promise<DKGAgentWallet> {
try {
return await DKGAgentWallet.load(dataDir);
} catch {
const wallet = await DKGAgentWallet.generate();
await wallet.save(dataDir);
return wallet;
}
}