@ocap/chain-node 0.0.0-stage → 1.32.0
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/README.md +234 -2
- package/esm/access-log.d.mts +34 -0
- package/esm/access-log.mjs +71 -0
- package/esm/env.d.mts +32 -0
- package/esm/env.mjs +218 -0
- package/esm/index.d.mts +5 -0
- package/esm/index.mjs +5 -0
- package/esm/standalone-env.d.mts +39 -0
- package/esm/standalone-env.mjs +71 -0
- package/esm/start-chain-node.d.mts +14 -0
- package/esm/start-chain-node.mjs +1102 -0
- package/esm/test-hooks-token.d.mts +12 -0
- package/esm/test-hooks-token.mjs +21 -0
- package/esm/testing.d.mts +13 -0
- package/esm/testing.mjs +23 -0
- package/esm/types.d.mts +293 -0
- package/esm/types.mjs +1 -0
- package/lib/_virtual/rolldown_runtime.cjs +29 -0
- package/lib/access-log.cjs +73 -0
- package/lib/access-log.d.cts +34 -0
- package/lib/env.cjs +221 -0
- package/lib/env.d.cts +32 -0
- package/lib/index.cjs +13 -0
- package/lib/index.d.cts +5 -0
- package/lib/standalone-env.cjs +76 -0
- package/lib/standalone-env.d.cts +39 -0
- package/lib/start-chain-node.cjs +1112 -0
- package/lib/start-chain-node.d.cts +14 -0
- package/lib/test-hooks-token.cjs +24 -0
- package/lib/test-hooks-token.d.cts +12 -0
- package/lib/testing.cjs +23 -0
- package/lib/testing.d.cts +13 -0
- package/lib/types.cjs +0 -0
- package/lib/types.d.cts +293 -0
- package/package.json +78 -4
|
@@ -0,0 +1,1102 @@
|
|
|
1
|
+
import { createAccessLogMiddleware } from "./access-log.mjs";
|
|
2
|
+
import { assertValidChainNodeTestHooks } from "./test-hooks-token.mjs";
|
|
3
|
+
import { LeaderRouter, Ledger, bytesToHex, canonicalizeMultiCurvePublicKey, createCheckpointSigner, createEnvAnchorPublisher, createEnvColdArchiveReader, createEnvSegmentPublisher, createEnvWitnessRegistry, decodeMultiCurvePublicKey, normalizeDidForCompare, resolveConsensusProposerFromSigner, toHotStuffClusterConfig, verifyDidMatchesMultiCurvePublicKey } from "@arcblock/ledger-core";
|
|
4
|
+
import { SqliteHotStuffStateStore, SqliteLedgerStorage, formatLocalProcessHolderId, hasExistingFollowerDatabases, persistFollowerHighWaterMark, prepareFollowerDataDirectory, readFollowerTrustedSecretKeyIfPresent, unlinkFollowerTrustedSecretKeyIfPresent } from "@arcblock/ledger-sqlite";
|
|
5
|
+
import { CustomError } from "@ocap/util/lib/error";
|
|
6
|
+
import crypto from "node:crypto";
|
|
7
|
+
import fs from "node:fs";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import { isValid } from "@arcblock/did";
|
|
10
|
+
import * as Config from "@ocap/config";
|
|
11
|
+
import { createHttpHandler, createSocketHandler } from "@ocap/gql";
|
|
12
|
+
import SqliteIndexDB from "@ocap/indexdb-sqlite";
|
|
13
|
+
import OCAPResolver, { FollowerSyncService, HotStuffNodeRuntime, NodePreferencesManager, applyBootRuntimePreferences, createAdminAuthGuard, createExplorerMiddleware, createFollowerPeerFetchGuard, createNodeDashboardRouter, createNodeMaintenanceController, createUnifiedConsoleMiddleware, isDashboardEnabled, isExplorerEnabled } from "@ocap/resolver";
|
|
14
|
+
import { createAPIHandler } from "@ocap/resolver/api";
|
|
15
|
+
import { Blacklist } from "@ocap/state";
|
|
16
|
+
import SqliteStateDB from "@ocap/statedb-sqlite";
|
|
17
|
+
import { SqliteTrustedStorage } from "@ocap/trusted-storage";
|
|
18
|
+
import cors from "cors";
|
|
19
|
+
import express from "express";
|
|
20
|
+
|
|
21
|
+
//#region src/start-chain-node.ts
|
|
22
|
+
const CHAIN_STATE_ADDR = crypto.createHash("md5").update("OCAP_CHAIN_ADDR").digest("hex");
|
|
23
|
+
const NODE_ID_FILENAME = ".node-id";
|
|
24
|
+
const DEFAULT_DRAIN_TIMEOUT_MS = 5e3;
|
|
25
|
+
const FORMATTED_HOLDER_ID_RE = /:\d+:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
26
|
+
function createDefaultLogger(prefix = "chain-node") {
|
|
27
|
+
return {
|
|
28
|
+
info: (...args) => console.info(`[${prefix}]`, ...args),
|
|
29
|
+
warn: (...args) => console.warn(`[${prefix}]`, ...args),
|
|
30
|
+
error: (...args) => console.error(`[${prefix}]`, ...args),
|
|
31
|
+
debug: (...args) => console.debug(`[${prefix}]`, ...args)
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
function toVariadicLogger(logger) {
|
|
35
|
+
return {
|
|
36
|
+
info: (...args) => logger.info(String(args[0] ?? ""), ...args.slice(1)),
|
|
37
|
+
warn: (...args) => logger.warn(String(args[0] ?? ""), ...args.slice(1)),
|
|
38
|
+
error: (...args) => logger.error(String(args[0] ?? ""), ...args.slice(1)),
|
|
39
|
+
debug: (...args) => logger.debug(String(args[0] ?? ""), ...args.slice(1))
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function classifyFetchKind(rawUrl) {
|
|
43
|
+
try {
|
|
44
|
+
const pathname = new URL(rawUrl).pathname.toLowerCase();
|
|
45
|
+
if (pathname.endsWith("/api/ledger/entries") || pathname.includes("/ledger/entries")) return "entries";
|
|
46
|
+
if (pathname.endsWith("/api/ledger/checkpoint") || pathname.includes("/ledger/checkpoint")) return "checkpoints";
|
|
47
|
+
if (pathname.endsWith(".zst")) return "snapshot-archive";
|
|
48
|
+
if (pathname.endsWith("manifest.json") || pathname.endsWith("latest-snapshot.json")) return "snapshot-manifest";
|
|
49
|
+
return "status";
|
|
50
|
+
} catch {
|
|
51
|
+
return "status";
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function assertSafeNonSymlinkDirectory(rawDataDir) {
|
|
55
|
+
const dataDir = path.resolve(rawDataDir);
|
|
56
|
+
if (fs.existsSync(dataDir)) {
|
|
57
|
+
if (fs.lstatSync(dataDir).isSymbolicLink()) throw new CustomError("SECURITY_VIOLATION", `Refusing symlinked chain node dataDir: ${dataDir}`);
|
|
58
|
+
} else fs.mkdirSync(dataDir, { recursive: true });
|
|
59
|
+
if (fs.lstatSync(dataDir).isSymbolicLink()) throw new CustomError("SECURITY_VIOLATION", `Refusing symlinked chain node dataDir: ${dataDir}`);
|
|
60
|
+
return dataDir;
|
|
61
|
+
}
|
|
62
|
+
function loadOrCreateNodeId(dataDir, explicitNodeId) {
|
|
63
|
+
const nodeIdPath = path.join(dataDir, NODE_ID_FILENAME);
|
|
64
|
+
if (fs.existsSync(nodeIdPath) && fs.lstatSync(nodeIdPath).isSymbolicLink()) throw new CustomError("SECURITY_VIOLATION", `Refusing symlinked .node-id file: ${nodeIdPath}`);
|
|
65
|
+
const trimmedExplicit = explicitNodeId?.trim();
|
|
66
|
+
if (trimmedExplicit) {
|
|
67
|
+
if (!fs.existsSync(nodeIdPath)) {
|
|
68
|
+
const tmpPath$1 = `${nodeIdPath}.tmp.${process.pid}.${crypto.randomBytes(4).toString("hex")}`;
|
|
69
|
+
fs.writeFileSync(tmpPath$1, `${trimmedExplicit}\n`, { mode: 384 });
|
|
70
|
+
fs.renameSync(tmpPath$1, nodeIdPath);
|
|
71
|
+
}
|
|
72
|
+
return trimmedExplicit;
|
|
73
|
+
}
|
|
74
|
+
if (fs.existsSync(nodeIdPath)) {
|
|
75
|
+
const existing = fs.readFileSync(nodeIdPath, "utf8").trim();
|
|
76
|
+
if (existing) return existing;
|
|
77
|
+
}
|
|
78
|
+
const generated = crypto.randomUUID();
|
|
79
|
+
const tmpPath = `${nodeIdPath}.tmp.${process.pid}.${crypto.randomBytes(4).toString("hex")}`;
|
|
80
|
+
fs.writeFileSync(tmpPath, `${generated}\n`, { mode: 384 });
|
|
81
|
+
fs.renameSync(tmpPath, nodeIdPath);
|
|
82
|
+
return generated;
|
|
83
|
+
}
|
|
84
|
+
function resolveStorageLeaseOptions(leaseOption) {
|
|
85
|
+
if (leaseOption === false || leaseOption?.enabled === false) return {
|
|
86
|
+
enabled: false,
|
|
87
|
+
autoAcquire: false
|
|
88
|
+
};
|
|
89
|
+
const ttlMs = typeof leaseOption?.ttlMs === "number" && Number.isFinite(leaseOption.ttlMs) && leaseOption.ttlMs > 0 ? leaseOption.ttlMs : 3e4;
|
|
90
|
+
const startupWaitMs = typeof leaseOption?.startupWaitMs === "number" && Number.isFinite(leaseOption.startupWaitMs) && leaseOption.startupWaitMs >= 0 ? leaseOption.startupWaitMs : Math.ceil(ttlMs * 1.5);
|
|
91
|
+
const rawHolderId = leaseOption?.holderId?.trim();
|
|
92
|
+
const holderId = rawHolderId && FORMATTED_HOLDER_ID_RE.test(rawHolderId) ? rawHolderId : formatLocalProcessHolderId(rawHolderId);
|
|
93
|
+
return {
|
|
94
|
+
enabled: true,
|
|
95
|
+
autoAcquire: leaseOption?.autoAcquire !== false,
|
|
96
|
+
holderId,
|
|
97
|
+
ttlMs,
|
|
98
|
+
startupWaitMs,
|
|
99
|
+
...leaseOption?.renewIntervalMs !== void 0 ? { renewIntervalMs: leaseOption.renewIntervalMs } : {}
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
function buildFollowerNodeRoleConfig(role, resolvedSigner) {
|
|
103
|
+
const hotstuffValidators = Array.isArray(role.hotstuffValidators) ? role.hotstuffValidators : [];
|
|
104
|
+
const isHotStuffCluster = hotstuffValidators.length > 0;
|
|
105
|
+
const hasExplicitTrustedAnchor = role.trustedProposer != null || role.trustedProposerPublicKey != null;
|
|
106
|
+
return {
|
|
107
|
+
role: role.runtimeRole ?? "follower",
|
|
108
|
+
consensusMode: isHotStuffCluster ? "hotstuff" : "single",
|
|
109
|
+
rpcBindHost: null,
|
|
110
|
+
consensusBindHost: null,
|
|
111
|
+
consensusPort: null,
|
|
112
|
+
allowPublicConsensusBind: false,
|
|
113
|
+
hotstuffValidators,
|
|
114
|
+
hotstuffQuorumThreshold: role.hotstuffQuorumThreshold,
|
|
115
|
+
writePolicy: role.writePolicy,
|
|
116
|
+
retentionMode: role.retentionMode ?? "archive",
|
|
117
|
+
hotWindowEntries: role.hotWindowEntries ?? 1e4,
|
|
118
|
+
hotWindowCheckpoints: role.hotWindowCheckpoints ?? 2,
|
|
119
|
+
syncMode: role.syncMode ?? "active-follower",
|
|
120
|
+
upstreamChainUrl: role.upstreamChainUrl ?? null,
|
|
121
|
+
clusterPeerUrls: role.clusterPeerUrls ?? [],
|
|
122
|
+
snapshotBaseUrl: role.snapshotBaseUrl ?? null,
|
|
123
|
+
trustedProposer: isHotStuffCluster ? null : hasExplicitTrustedAnchor ? role.trustedProposer ?? null : resolvedSigner?.address ?? null,
|
|
124
|
+
trustedProposerPublicKey: isHotStuffCluster ? null : hasExplicitTrustedAnchor ? role.trustedProposerPublicKey ?? null : resolvedSigner?.publicKey ?? null,
|
|
125
|
+
allowUnauthenticatedBootstrap: Boolean(role.allowUnauthenticatedBootstrap),
|
|
126
|
+
witnessQuorum: 0,
|
|
127
|
+
witnessSubmitUrls: role.witnessSubmitUrls ?? [],
|
|
128
|
+
anchorWebhookUrl: null
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
function adaptColdReaderToArchiveStore(reader) {
|
|
132
|
+
const maybeFull = reader;
|
|
133
|
+
if (typeof maybeFull.putSegment === "function" && typeof maybeFull.hasSegment === "function") return reader;
|
|
134
|
+
return {
|
|
135
|
+
name: maybeFull.name || "chain-node-cold-reader",
|
|
136
|
+
async putSegment() {
|
|
137
|
+
throw new Error("Cold archive reader is read-only");
|
|
138
|
+
},
|
|
139
|
+
async getSegment(chainId, height, options) {
|
|
140
|
+
const seg = await reader.getSegment(chainId, height, options);
|
|
141
|
+
if (!seg) return null;
|
|
142
|
+
return seg;
|
|
143
|
+
},
|
|
144
|
+
async hasSegment(chainId, height) {
|
|
145
|
+
const seg = await reader.getSegment(chainId, height);
|
|
146
|
+
return Boolean(seg);
|
|
147
|
+
},
|
|
148
|
+
...typeof reader.getLatestHead === "function" ? { getLatestHead: reader.getLatestHead.bind(reader) } : {}
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
function isCompleteChainConfig(candidate) {
|
|
152
|
+
return Boolean(candidate && typeof candidate.chainId === "string" && candidate.chainId.trim() && candidate.moderator?.address && candidate.token?.symbol && candidate.vaults?.slashedStake);
|
|
153
|
+
}
|
|
154
|
+
function formatHttpHostForUrl(bindHost) {
|
|
155
|
+
const trimmed = bindHost.trim();
|
|
156
|
+
if (!trimmed || trimmed === "0.0.0.0" || trimmed === "::" || trimmed === "[::]") return "127.0.0.1";
|
|
157
|
+
if (trimmed.includes(":") && !trimmed.startsWith("[")) return `[${trimmed}]`;
|
|
158
|
+
return trimmed;
|
|
159
|
+
}
|
|
160
|
+
async function waitEventEmitterReady(target) {
|
|
161
|
+
if (typeof target.onReady !== "function") return;
|
|
162
|
+
await new Promise((resolve) => {
|
|
163
|
+
target.onReady(() => resolve());
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
async function bootChainNodeOnce(params) {
|
|
167
|
+
const { profile, testHooks, clockNow } = params;
|
|
168
|
+
const cleanupStack = [];
|
|
169
|
+
const pushCleanup = (fn) => cleanupStack.push(fn) - 1;
|
|
170
|
+
const unwindCleanupStack = async () => {
|
|
171
|
+
for (let i = cleanupStack.length - 1; i >= 0; i--) try {
|
|
172
|
+
await cleanupStack[i]();
|
|
173
|
+
} catch {}
|
|
174
|
+
};
|
|
175
|
+
try {
|
|
176
|
+
assertValidChainNodeTestHooks(testHooks);
|
|
177
|
+
if (!profile || typeof profile !== "object" || typeof profile.dataDir !== "string" || !profile.dataDir.trim()) throw new CustomError("INVALID_CONFIG", "ChainProfile.dataDir must be a non-empty directory path");
|
|
178
|
+
const dataDir = assertSafeNonSymlinkDirectory(profile.dataDir);
|
|
179
|
+
const { role } = profile;
|
|
180
|
+
if (!role || role.kind !== "validator" && role.kind !== "follower" && role.kind !== "hotstuff") throw new CustomError("INVALID_CONFIG", "ChainProfile.role.kind must be \"validator\", \"follower\", or \"hotstuff\"");
|
|
181
|
+
if ((role.kind === "validator" || role.kind === "hotstuff") && !isCompleteChainConfig(profile.chainConfig)) throw new CustomError("INVALID_CONFIG", `${role.kind} role requires a complete chainConfig`);
|
|
182
|
+
if ((role.kind === "validator" || role.kind === "hotstuff") && !role.signer) throw new CustomError("INVALID_CONFIG", `${role.kind} role requires role.signer`);
|
|
183
|
+
if (role.kind === "hotstuff" && (!Array.isArray(role.validators) || role.validators.length === 0)) throw new CustomError("INVALID_CONFIG", "HotStuff role requires a non-empty validators list");
|
|
184
|
+
const logger = testHooks?.logger ?? profile.logger ?? createDefaultLogger("chain-node");
|
|
185
|
+
const variadicLogger = toVariadicLogger(logger);
|
|
186
|
+
const followerExpectedChainId = "expectedChainId" in profile ? profile.expectedChainId : void 0;
|
|
187
|
+
const statedbPath = profile.storage?.statedbPath ? path.resolve(profile.storage.statedbPath) : path.join(dataDir, "statedb.sqlite");
|
|
188
|
+
const ledgerPath = profile.storage?.ledgerPath ? path.resolve(profile.storage.ledgerPath) : path.join(dataDir, "ledger.sqlite");
|
|
189
|
+
const indexdbPath = profile.storage?.indexdbPath ? path.resolve(profile.storage.indexdbPath) : path.join(dataDir, "indexdb.sqlite");
|
|
190
|
+
const trustedPath = profile.storage?.trustedPath ? path.resolve(profile.storage.trustedPath) : path.join(dataDir, "trusted.sqlite");
|
|
191
|
+
const nodeId = loadOrCreateNodeId(dataDir, profile.nodeId);
|
|
192
|
+
let resolvedProposer = null;
|
|
193
|
+
let pkOnlyValidatorAddress = null;
|
|
194
|
+
let pkOnlyValidatorPublicKey;
|
|
195
|
+
if (role.kind === "hotstuff") {
|
|
196
|
+
if (!role.signer.secretKey?.trim()) throw new CustomError("INVALID_CONFIG", "HotStuff validator role requires role.signer.secretKey");
|
|
197
|
+
resolvedProposer = resolveConsensusProposerFromSigner(role.signer);
|
|
198
|
+
} else if (role.kind === "validator") if (role.signer.secretKey?.trim()) resolvedProposer = resolveConsensusProposerFromSigner({
|
|
199
|
+
address: role.signer.address,
|
|
200
|
+
secretKey: role.signer.secretKey,
|
|
201
|
+
...role.signer.publicKey ? { publicKey: role.signer.publicKey } : {},
|
|
202
|
+
...role.signer.keyType ? { keyType: role.signer.keyType } : {}
|
|
203
|
+
});
|
|
204
|
+
else {
|
|
205
|
+
if (!profile.storage?.trustedStorageSecretKey?.trim()) throw new CustomError("INVALID_CONFIG", "Validator without signer.secretKey requires explicit storage.trustedStorageSecretKey");
|
|
206
|
+
const rawAddr = String(role.signer.address ?? "").trim();
|
|
207
|
+
const normalizedAddr = normalizeDidForCompare(rawAddr);
|
|
208
|
+
const isEthAddr = /^0x[0-9a-fA-F]{40}$/.test(normalizedAddr);
|
|
209
|
+
if (!normalizedAddr || !isEthAddr && !isValid(normalizedAddr)) throw new CustomError("INVALID_CONFIG", `Invalid validator signer address DID: ${rawAddr}`);
|
|
210
|
+
pkOnlyValidatorAddress = normalizedAddr;
|
|
211
|
+
const rawPk = role.signer.publicKey !== void 0 ? String(role.signer.publicKey).trim() : "";
|
|
212
|
+
if (rawPk) {
|
|
213
|
+
const canonicalPk = canonicalizeMultiCurvePublicKey(rawPk);
|
|
214
|
+
if (!canonicalPk || !verifyDidMatchesMultiCurvePublicKey(normalizedAddr, canonicalPk.bytes)) throw new CustomError("INVALID_CONFIG", `Validator signer publicKey does not match address ${normalizedAddr}`);
|
|
215
|
+
pkOnlyValidatorPublicKey = `0x${bytesToHex(canonicalPk.bytes)}`;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
else if (role.signer) resolvedProposer = resolveConsensusProposerFromSigner(role.signer);
|
|
219
|
+
const resolvedLeaseOptions = resolveStorageLeaseOptions(profile.storage?.lease);
|
|
220
|
+
const createLedgerStorage = () => new SqliteLedgerStorage({
|
|
221
|
+
filename: ledgerPath,
|
|
222
|
+
tablePrefix: "ledger",
|
|
223
|
+
entryHashV2: profile.storage?.entryHashV2 ?? "auto",
|
|
224
|
+
lease: resolvedLeaseOptions,
|
|
225
|
+
...profile.storage?.walAutoCheckpoint !== void 0 ? { walAutoCheckpoint: profile.storage.walAutoCheckpoint } : {}
|
|
226
|
+
});
|
|
227
|
+
let ledgerStorage = null;
|
|
228
|
+
let ledgerCleanupIndex = -1;
|
|
229
|
+
let followerPrep = null;
|
|
230
|
+
const isKeylessFollower = role.kind === "follower" && !profile.storage?.trustedStorageSecretKey?.trim();
|
|
231
|
+
if (role.kind === "follower") {
|
|
232
|
+
if (fs.existsSync(ledgerPath) && fs.statSync(ledgerPath).size > 0) {
|
|
233
|
+
const precheckLedgerStorage = createLedgerStorage();
|
|
234
|
+
ledgerStorage = precheckLedgerStorage;
|
|
235
|
+
ledgerCleanupIndex = pushCleanup(async () => {
|
|
236
|
+
await precheckLedgerStorage.close();
|
|
237
|
+
});
|
|
238
|
+
await precheckLedgerStorage.init();
|
|
239
|
+
if (!hasExistingFollowerDatabases(dataDir, {
|
|
240
|
+
statedbPath,
|
|
241
|
+
ledgerPath
|
|
242
|
+
})) {
|
|
243
|
+
await precheckLedgerStorage.close();
|
|
244
|
+
cleanupStack[ledgerCleanupIndex] = async () => {};
|
|
245
|
+
ledgerStorage = null;
|
|
246
|
+
ledgerCleanupIndex = -1;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
const guardedBootstrapFetch = createFollowerPeerFetchGuard({
|
|
250
|
+
env: { ALLOW_PRIVATE_PEER_URLS: role.allowPrivatePeers ? "1" : "0" },
|
|
251
|
+
trustedStaticUrls: [
|
|
252
|
+
role.upstreamChainUrl,
|
|
253
|
+
role.snapshotBaseUrl,
|
|
254
|
+
...role.clusterPeerUrls ?? []
|
|
255
|
+
].filter((u) => Boolean(u && String(u).trim())),
|
|
256
|
+
baseFetch: globalThis.fetch
|
|
257
|
+
});
|
|
258
|
+
const interceptFetch = testHooks?.followerSync?.interceptUpstreamFetch;
|
|
259
|
+
const bootstrapFetchImpl = interceptFetch ? (async (input, init) => {
|
|
260
|
+
const urlStr = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
|
261
|
+
return interceptFetch({
|
|
262
|
+
kind: classifyFetchKind(urlStr),
|
|
263
|
+
url: urlStr,
|
|
264
|
+
init
|
|
265
|
+
}, guardedBootstrapFetch);
|
|
266
|
+
}) : guardedBootstrapFetch;
|
|
267
|
+
const explicitExpectedChainId = followerExpectedChainId?.trim() || "";
|
|
268
|
+
const profileChainId = profile.chainConfig?.chainId?.trim() || "";
|
|
269
|
+
if (explicitExpectedChainId && profileChainId && explicitExpectedChainId !== profileChainId) throw new CustomError("SNAPSHOT_CHAIN_ID_MISMATCH", `Follower expectedChainId (${explicitExpectedChainId}) !== profile.chainConfig.chainId (${profileChainId})`);
|
|
270
|
+
followerPrep = await prepareFollowerDataDirectory({
|
|
271
|
+
dataDir,
|
|
272
|
+
roleConfig: buildFollowerNodeRoleConfig(role, resolvedProposer),
|
|
273
|
+
expectedChainId: explicitExpectedChainId || profileChainId || void 0,
|
|
274
|
+
snapshotPrefix: role.snapshotPrefix,
|
|
275
|
+
statedbPath,
|
|
276
|
+
ledgerPath,
|
|
277
|
+
trustedPath,
|
|
278
|
+
keyless: isKeylessFollower,
|
|
279
|
+
fetchImpl: bootstrapFetchImpl
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
if (!ledgerStorage) {
|
|
283
|
+
const freshLedgerStorage = createLedgerStorage();
|
|
284
|
+
ledgerStorage = freshLedgerStorage;
|
|
285
|
+
ledgerCleanupIndex = pushCleanup(async () => {
|
|
286
|
+
await freshLedgerStorage.close();
|
|
287
|
+
});
|
|
288
|
+
await freshLedgerStorage.init();
|
|
289
|
+
}
|
|
290
|
+
const trustedSecretKey = role.kind === "follower" && isKeylessFollower ? followerPrep.trustedSecretKey : profile.storage?.trustedStorageSecretKey?.trim() || resolvedProposer?.secretKey || "";
|
|
291
|
+
if (!trustedSecretKey) throw new CustomError("INVALID_CONFIG", "Missing trustedStorageSecretKey for SQLite trusted storage");
|
|
292
|
+
const followerLegacyKey = readFollowerTrustedSecretKeyIfPresent(dataDir);
|
|
293
|
+
const proposerLegacyKey = profile.storage?.trustedStorageSecretKey?.trim() ? resolvedProposer?.secretKey : void 0;
|
|
294
|
+
const trustedStorage = new SqliteTrustedStorage({
|
|
295
|
+
filename: trustedPath,
|
|
296
|
+
secretKey: trustedSecretKey,
|
|
297
|
+
legacySecretKeys: Array.from(new Set([
|
|
298
|
+
...profile.storage?.legacyTrustedSecretKeys ?? [],
|
|
299
|
+
followerLegacyKey,
|
|
300
|
+
proposerLegacyKey
|
|
301
|
+
].map((k) => typeof k === "string" ? k.trim() : "").filter((k) => Boolean(k) && k !== trustedSecretKey))),
|
|
302
|
+
retryLimit: profile.storage?.trustedRetryLimit ?? 60,
|
|
303
|
+
allowLegacySignatures: Boolean(followerLegacyKey) || profile.storage?.trustedAllowLegacySignatures !== false
|
|
304
|
+
});
|
|
305
|
+
pushCleanup(async () => {
|
|
306
|
+
await trustedStorage.close();
|
|
307
|
+
});
|
|
308
|
+
const statedb = new SqliteStateDB({
|
|
309
|
+
filename: statedbPath,
|
|
310
|
+
trustedStorage,
|
|
311
|
+
allowTrustedBootstrap: role.kind === "follower" && (Boolean(followerPrep?.bootstrapped) || Boolean(followerPrep?.reanchoredTrusted)),
|
|
312
|
+
...profile.storage?.walAutoCheckpoint !== void 0 ? { walAutoCheckpoint: profile.storage.walAutoCheckpoint } : {}
|
|
313
|
+
});
|
|
314
|
+
pushCleanup(async () => {
|
|
315
|
+
await statedb.close();
|
|
316
|
+
});
|
|
317
|
+
await statedb.initialize();
|
|
318
|
+
await waitEventEmitterReady(statedb);
|
|
319
|
+
if (!isKeylessFollower) unlinkFollowerTrustedSecretKeyIfPresent(dataDir);
|
|
320
|
+
if (testHooks?.resolver?.beforeStateDbCommit) {
|
|
321
|
+
const hookFn = testHooks.resolver.beforeStateDbCommit;
|
|
322
|
+
const origRunAsLambda = statedb.runAsLambda.bind(statedb);
|
|
323
|
+
statedb.runAsLambda = ((fn, options) => {
|
|
324
|
+
const prevBeforeCommit = options?.beforeCommit;
|
|
325
|
+
return origRunAsLambda(fn, {
|
|
326
|
+
...options,
|
|
327
|
+
beforeCommit: async (info) => {
|
|
328
|
+
if (prevBeforeCommit) await prevBeforeCommit(info);
|
|
329
|
+
if (!options?.dryRun) await hookFn({
|
|
330
|
+
commitHash: info.commitHash,
|
|
331
|
+
prevHash: info.prevHash,
|
|
332
|
+
seq: info.seq
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
});
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
let chainConfig;
|
|
339
|
+
if (role.kind === "follower" && !isCompleteChainConfig(profile.chainConfig)) {
|
|
340
|
+
const storedChain = await statedb.chain.get(CHAIN_STATE_ADDR);
|
|
341
|
+
if (!storedChain) throw new CustomError("INVALID_STATE", `Missing chain state (${CHAIN_STATE_ADDR}) in Follower statedb.sqlite (${statedbPath})`);
|
|
342
|
+
const storedChainPartial = storedChain;
|
|
343
|
+
const storedChainId = typeof storedChainPartial.chainId === "string" ? storedChainPartial.chainId.trim() : "";
|
|
344
|
+
const overrideChainId = typeof profile.chainConfig?.chainId === "string" ? profile.chainConfig.chainId.trim() : "";
|
|
345
|
+
if (storedChainId && overrideChainId && overrideChainId !== storedChainId) throw new CustomError("SNAPSHOT_CHAIN_ID_MISMATCH", `Follower profile.chainConfig.chainId (${overrideChainId}) !== statedb chain.chainId (${storedChainId})`);
|
|
346
|
+
const baseSymbol = storedChainPartial.token?.symbol || "TBA";
|
|
347
|
+
const reservedSymbols = Array.from(new Set([baseSymbol, ...storedChainPartial.reservedSymbols ?? []].map((s) => String(s || "").trim().toUpperCase()).filter(Boolean)));
|
|
348
|
+
chainConfig = Config.create({
|
|
349
|
+
...storedChain,
|
|
350
|
+
...storedChainId ? { chainId: storedChainId } : {},
|
|
351
|
+
reservedSymbols
|
|
352
|
+
});
|
|
353
|
+
} else {
|
|
354
|
+
const baseConfig = profile.chainConfig;
|
|
355
|
+
if (role.kind === "follower") {
|
|
356
|
+
const storedChain = await statedb.chain.get(CHAIN_STATE_ADDR);
|
|
357
|
+
const storedChainId = storedChain && typeof storedChain.chainId === "string" ? (storedChain.chainId || "").trim() : "";
|
|
358
|
+
if (storedChainId && baseConfig.chainId !== storedChainId) throw new CustomError("SNAPSHOT_CHAIN_ID_MISMATCH", `Follower profile.chainConfig.chainId (${baseConfig.chainId}) !== statedb chain.chainId (${storedChainId})`);
|
|
359
|
+
}
|
|
360
|
+
chainConfig = baseConfig;
|
|
361
|
+
}
|
|
362
|
+
if (role.kind === "follower" && followerExpectedChainId && chainConfig.chainId !== followerExpectedChainId) throw new CustomError("SNAPSHOT_CHAIN_ID_MISMATCH", `Rehydrated Follower chainId (${chainConfig.chainId}) !== expectedChainId (${followerExpectedChainId})`);
|
|
363
|
+
const hotstuffValidators = role.kind === "hotstuff" ? role.validators : role.kind === "follower" ? role.hotstuffValidators ?? [] : [];
|
|
364
|
+
const hotstuffQuorumThreshold = role.kind === "hotstuff" ? role.quorumThreshold : role.kind === "follower" ? role.hotstuffQuorumThreshold : void 0;
|
|
365
|
+
const hotstuffClusterConfig = role.kind === "hotstuff" || hotstuffValidators.length > 0 ? toHotStuffClusterConfig(chainConfig.chainId, hotstuffValidators, hotstuffQuorumThreshold) : void 0;
|
|
366
|
+
const segmentPublisher = profile.da?.segmentPublisher !== void 0 ? profile.da.segmentPublisher : role.kind !== "follower" && profile.da?.env ? createEnvSegmentPublisher({
|
|
367
|
+
env: profile.da.env,
|
|
368
|
+
logger: variadicLogger
|
|
369
|
+
}) : null;
|
|
370
|
+
const explicitColdReader = profile.da?.coldArchiveReader ?? null;
|
|
371
|
+
const envColdReader = !explicitColdReader && profile.da?.env ? createEnvColdArchiveReader({ env: profile.da.env }) : null;
|
|
372
|
+
const coldSegmentStore = explicitColdReader ? adaptColdReaderToArchiveStore(explicitColdReader) : segmentPublisher?.getArchiveStore?.() || (envColdReader ? adaptColdReaderToArchiveStore(envColdReader) : void 0);
|
|
373
|
+
const hasExplicitTrustedAnchor = role.kind === "follower" && (role.trustedProposer != null || role.trustedProposerPublicKey != null);
|
|
374
|
+
const followerExplicitPk = role.kind === "follower" ? followerPrep?.trustedProposerPublicKey || role.trustedProposerPublicKey || null : null;
|
|
375
|
+
const followerFallbackDidCandidate = role.kind === "follower" ? (hasExplicitTrustedAnchor ? null : resolvedProposer?.address || null) || chainConfig.moderator.address : null;
|
|
376
|
+
const activeProposerDid = role.kind === "validator" || role.kind === "hotstuff" ? resolvedProposer?.address ?? pkOnlyValidatorAddress : hotstuffClusterConfig ? chainConfig.moderator.address : followerPrep?.trustedProposer || role.trustedProposer || (followerFallbackDidCandidate && (!followerExplicitPk || verifyDidMatchesMultiCurvePublicKey(followerFallbackDidCandidate, followerExplicitPk)) ? followerFallbackDidCandidate : "");
|
|
377
|
+
const followerFallbackPkCandidate = role.kind === "follower" ? (hasExplicitTrustedAnchor ? null : resolvedProposer?.publicKey || null) || chainConfig.moderator.pk || null : null;
|
|
378
|
+
const activeProposerPk = role.kind === "validator" || role.kind === "hotstuff" ? resolvedProposer?.publicKey ?? pkOnlyValidatorPublicKey : hotstuffClusterConfig ? void 0 : followerExplicitPk || (followerFallbackPkCandidate && (!activeProposerDid || verifyDidMatchesMultiCurvePublicKey(activeProposerDid, followerFallbackPkCandidate)) ? followerFallbackPkCandidate : void 0);
|
|
379
|
+
const witnessQuorum = "witnessQuorum" in role ? role.witnessQuorum : void 0;
|
|
380
|
+
const trustedWitnesses = "trustedWitnesses" in role ? role.trustedWitnesses : void 0;
|
|
381
|
+
const witnessRegistry = createEnvWitnessRegistry({
|
|
382
|
+
chainId: chainConfig.chainId,
|
|
383
|
+
witnessQuorum,
|
|
384
|
+
trustedWitnesses,
|
|
385
|
+
hotstuffClusterConfig,
|
|
386
|
+
expectedProposer: hotstuffClusterConfig ? void 0 : activeProposerDid,
|
|
387
|
+
proposerPublicKey: hotstuffClusterConfig ? void 0 : activeProposerPk,
|
|
388
|
+
logger
|
|
389
|
+
}) || void 0;
|
|
390
|
+
const anchorPublisher = profile.da?.anchorPublisher !== void 0 ? profile.da.anchorPublisher || void 0 : role.kind === "validator" && resolvedProposer && (role.anchorWebhookUrl || profile.da?.env) ? createEnvAnchorPublisher({
|
|
391
|
+
chainId: chainConfig.chainId,
|
|
392
|
+
signer: createCheckpointSigner(resolvedProposer.proposerWallet, resolvedProposer.address),
|
|
393
|
+
anchorSigner: resolvedProposer.address,
|
|
394
|
+
anchorPublicKey: resolvedProposer.publicKey,
|
|
395
|
+
env: {
|
|
396
|
+
...profile.da?.env ?? {},
|
|
397
|
+
...role.anchorWebhookUrl ? { ANCHOR_WEBHOOK_URL: role.anchorWebhookUrl } : {}
|
|
398
|
+
},
|
|
399
|
+
logger
|
|
400
|
+
}) || void 0 : void 0;
|
|
401
|
+
const cpBatchSize = testHooks?.checkpoint?.batchSize ?? profile.checkpoint?.batchSize ?? (role.kind === "validator" ? 100 : 1e3);
|
|
402
|
+
const cpTimeoutMs = role.kind === "validator" ? testHooks?.checkpoint?.timeoutMs ?? profile.checkpoint?.timeoutMs ?? 6e4 : 0;
|
|
403
|
+
const cpAuto = role.kind === "validator" ? profile.checkpoint?.auto !== false : false;
|
|
404
|
+
const cpPeriodicTimer = role.kind === "validator" ? profile.checkpoint?.periodicTimer ?? (cpAuto !== false && cpTimeoutMs > 0) : false;
|
|
405
|
+
const ledger = new Ledger(ledgerStorage, {
|
|
406
|
+
chainId: chainConfig.chainId,
|
|
407
|
+
proposer: activeProposerDid,
|
|
408
|
+
proposerWallet: role.kind !== "follower" ? resolvedProposer?.proposerWallet : void 0,
|
|
409
|
+
proposerPublicKey: activeProposerPk || void 0,
|
|
410
|
+
nodeRole: role.kind === "follower" ? role.runtimeRole ?? "follower" : "validator",
|
|
411
|
+
consensusMode: role.kind === "hotstuff" ? "hotstuff" : "single",
|
|
412
|
+
hotstuffClusterConfig,
|
|
413
|
+
segmentPublisher: segmentPublisher || void 0,
|
|
414
|
+
coldSegmentStore,
|
|
415
|
+
witnessRegistry,
|
|
416
|
+
anchorPublisher,
|
|
417
|
+
now: clockNow,
|
|
418
|
+
checkpoint: {
|
|
419
|
+
batchSize: cpBatchSize,
|
|
420
|
+
timeoutMs: cpTimeoutMs,
|
|
421
|
+
auto: cpAuto,
|
|
422
|
+
periodicTimer: cpPeriodicTimer,
|
|
423
|
+
...profile.checkpoint?.timerIntervalMs !== void 0 ? { timerIntervalMs: profile.checkpoint.timerIntervalMs } : {}
|
|
424
|
+
}
|
|
425
|
+
});
|
|
426
|
+
cleanupStack[ledgerCleanupIndex] = async () => {
|
|
427
|
+
await ledger.close();
|
|
428
|
+
};
|
|
429
|
+
await ledger.initialize();
|
|
430
|
+
const isFileBackedFollower = role.kind === "follower" && ledgerPath !== ":memory:" && statedbPath !== ":memory:";
|
|
431
|
+
const followerHwmProposer = hotstuffClusterConfig ? null : followerPrep?.trustedProposer ?? (role.kind === "follower" ? role.trustedProposer : null) ?? null;
|
|
432
|
+
const followerHwmProposerPk = hotstuffClusterConfig ? null : followerPrep?.trustedProposerPublicKey ?? (role.kind === "follower" ? role.trustedProposerPublicKey : null) ?? null;
|
|
433
|
+
let followerHwmClosed = false;
|
|
434
|
+
let followerHwmTimer = null;
|
|
435
|
+
const cancelFollowerHwmTimer = () => {
|
|
436
|
+
followerHwmClosed = true;
|
|
437
|
+
if (followerHwmTimer) {
|
|
438
|
+
clearTimeout(followerHwmTimer);
|
|
439
|
+
followerHwmTimer = null;
|
|
440
|
+
}
|
|
441
|
+
};
|
|
442
|
+
if (isFileBackedFollower) {
|
|
443
|
+
pushCleanup(async () => {
|
|
444
|
+
cancelFollowerHwmTimer();
|
|
445
|
+
});
|
|
446
|
+
const [initialSeq, initialCp] = await Promise.all([ledger.getLatestSequence(), ledger.getCheckpoint()]);
|
|
447
|
+
let persistedSeq = Math.max(followerPrep?.record?.snapshotSequence ?? 0, followerPrep?.record?.lastKnownSequence ?? 0, initialSeq);
|
|
448
|
+
let persistedCpHeight = Math.max(followerPrep?.record?.checkpointHeight ?? 0, followerPrep?.record?.lastKnownCheckpointHeight ?? 0, initialCp?.height ?? 0);
|
|
449
|
+
let pendingSeq = persistedSeq;
|
|
450
|
+
let pendingCpHeight = persistedCpHeight;
|
|
451
|
+
let lastHotTailPersistAt = 0;
|
|
452
|
+
try {
|
|
453
|
+
persistFollowerHighWaterMark({
|
|
454
|
+
dataDir,
|
|
455
|
+
sequence: pendingSeq,
|
|
456
|
+
checkpointHeight: pendingCpHeight,
|
|
457
|
+
chainId: chainConfig.chainId,
|
|
458
|
+
proposer: followerHwmProposer,
|
|
459
|
+
proposerPublicKey: followerHwmProposerPk
|
|
460
|
+
});
|
|
461
|
+
} catch (err) {
|
|
462
|
+
logger.warn(`[chain-node] initial follower high-water mark persist failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
463
|
+
}
|
|
464
|
+
const flushFollowerHighWaterMark = () => {
|
|
465
|
+
if (followerHwmTimer) {
|
|
466
|
+
clearTimeout(followerHwmTimer);
|
|
467
|
+
followerHwmTimer = null;
|
|
468
|
+
}
|
|
469
|
+
if (followerHwmClosed || pendingSeq <= persistedSeq && pendingCpHeight <= persistedCpHeight) return;
|
|
470
|
+
try {
|
|
471
|
+
persistFollowerHighWaterMark({
|
|
472
|
+
dataDir,
|
|
473
|
+
sequence: pendingSeq,
|
|
474
|
+
checkpointHeight: pendingCpHeight,
|
|
475
|
+
chainId: chainConfig.chainId,
|
|
476
|
+
proposer: followerHwmProposer,
|
|
477
|
+
proposerPublicKey: followerHwmProposerPk
|
|
478
|
+
});
|
|
479
|
+
persistedSeq = Math.max(persistedSeq, pendingSeq);
|
|
480
|
+
persistedCpHeight = Math.max(persistedCpHeight, pendingCpHeight);
|
|
481
|
+
lastHotTailPersistAt = Date.now();
|
|
482
|
+
} catch (err) {
|
|
483
|
+
logger.warn(`[chain-node] live follower high-water mark update failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
484
|
+
}
|
|
485
|
+
};
|
|
486
|
+
const scheduleFollowerHighWaterMark = (immediate) => {
|
|
487
|
+
if (followerHwmClosed || pendingSeq <= persistedSeq && pendingCpHeight <= persistedCpHeight) return;
|
|
488
|
+
if (immediate || Date.now() - lastHotTailPersistAt >= 20) {
|
|
489
|
+
flushFollowerHighWaterMark();
|
|
490
|
+
return;
|
|
491
|
+
}
|
|
492
|
+
if (!followerHwmTimer) {
|
|
493
|
+
followerHwmTimer = setTimeout(() => {
|
|
494
|
+
followerHwmTimer = null;
|
|
495
|
+
flushFollowerHighWaterMark();
|
|
496
|
+
}, 20);
|
|
497
|
+
if (typeof followerHwmTimer.unref === "function") followerHwmTimer.unref();
|
|
498
|
+
}
|
|
499
|
+
};
|
|
500
|
+
const origImportSegment = ledger.importSegment.bind(ledger);
|
|
501
|
+
ledger.importSegment = (async (...args) => {
|
|
502
|
+
await origImportSegment(...args);
|
|
503
|
+
const cp = args[0]?.checkpoint;
|
|
504
|
+
if (cp) {
|
|
505
|
+
if (Number.isFinite(cp.sequence)) pendingSeq = Math.max(pendingSeq, Math.trunc(cp.sequence));
|
|
506
|
+
if (Number.isFinite(cp.height)) pendingCpHeight = Math.max(pendingCpHeight, Math.trunc(cp.height));
|
|
507
|
+
scheduleFollowerHighWaterMark(true);
|
|
508
|
+
}
|
|
509
|
+
});
|
|
510
|
+
const origAppendVerifiedEntries = ledger.appendVerifiedEntries.bind(ledger);
|
|
511
|
+
ledger.appendVerifiedEntries = (async (...args) => {
|
|
512
|
+
await origAppendVerifiedEntries(...args);
|
|
513
|
+
const entries = args[0];
|
|
514
|
+
if (Array.isArray(entries) && entries.length > 0) {
|
|
515
|
+
for (const e of entries) if (e && Number.isFinite(e.sequence)) pendingSeq = Math.max(pendingSeq, Math.trunc(e.sequence));
|
|
516
|
+
scheduleFollowerHighWaterMark(false);
|
|
517
|
+
}
|
|
518
|
+
});
|
|
519
|
+
const origSaveCheckpoint = ledgerStorage.saveCheckpoint.bind(ledgerStorage);
|
|
520
|
+
ledgerStorage.saveCheckpoint = (async (...args) => {
|
|
521
|
+
await origSaveCheckpoint(...args);
|
|
522
|
+
const cp = args[0];
|
|
523
|
+
if (cp) {
|
|
524
|
+
if (Number.isFinite(cp.sequence)) pendingSeq = Math.max(pendingSeq, Math.trunc(cp.sequence));
|
|
525
|
+
if (Number.isFinite(cp.height)) pendingCpHeight = Math.max(pendingCpHeight, Math.trunc(cp.height));
|
|
526
|
+
scheduleFollowerHighWaterMark(true);
|
|
527
|
+
}
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
const indexDbExisted = fs.existsSync(indexdbPath);
|
|
531
|
+
const indexdb = new SqliteIndexDB({
|
|
532
|
+
filename: indexdbPath,
|
|
533
|
+
...profile.storage?.indexWalAutoCheckpoint !== void 0 ? { walAutoCheckpoint: profile.storage.indexWalAutoCheckpoint } : {}
|
|
534
|
+
});
|
|
535
|
+
pushCleanup(async () => {
|
|
536
|
+
await indexdb.close();
|
|
537
|
+
});
|
|
538
|
+
await indexdb.initialize();
|
|
539
|
+
await waitEventEmitterReady(indexdb);
|
|
540
|
+
let resolverRef = null;
|
|
541
|
+
const adminEnv = profile.http.adminEnv ?? {};
|
|
542
|
+
const preferencesManager = new NodePreferencesManager({
|
|
543
|
+
dataDir,
|
|
544
|
+
env: adminEnv,
|
|
545
|
+
staticBlockedAddresses: profile.blacklist?.staticBlockedAddresses,
|
|
546
|
+
baseReservedSymbols: Array.from(new Set([
|
|
547
|
+
chainConfig.token?.symbol || "TBA",
|
|
548
|
+
...chainConfig.reservedSymbols ?? [],
|
|
549
|
+
...profile.reservedSymbols ?? []
|
|
550
|
+
].filter(Boolean))),
|
|
551
|
+
getNodeRole: () => resolverRef?.getNodeRuntime?.()?.role || (role.kind === "follower" ? role.runtimeRole ?? "follower" : "validator"),
|
|
552
|
+
getConsensusMode: () => role.kind === "hotstuff" || Boolean(hotstuffClusterConfig) ? "hotstuff" : "single",
|
|
553
|
+
onApply: async (snap) => {
|
|
554
|
+
if (snap.runtime.txMaxRequest !== void 0 && resolverRef?.setMaxTxRequest) resolverRef.setMaxTxRequest(snap.runtime.txMaxRequest);
|
|
555
|
+
const activeRuntime = resolverRef?.getNodeRuntime?.();
|
|
556
|
+
if (activeRuntime && typeof activeRuntime.updateRuntimeConfig === "function") await Promise.resolve(activeRuntime.updateRuntimeConfig(snap.runtime));
|
|
557
|
+
}
|
|
558
|
+
});
|
|
559
|
+
const resolveTrustedAccounts = profile.blacklist?.getTrustedAccounts;
|
|
560
|
+
const filter = new Blacklist({
|
|
561
|
+
dumpPath: profile.blacklist?.dumpPath ?? path.join(dataDir, "filter.json"),
|
|
562
|
+
dumpInterval: profile.blacklist?.dumpIntervalMs ?? 1e3,
|
|
563
|
+
getBlockedAccounts: async () => [],
|
|
564
|
+
getTrustedAccounts: resolveTrustedAccounts ? async () => await resolveTrustedAccounts() : async () => preferencesManager.getTrustedAccounts()
|
|
565
|
+
});
|
|
566
|
+
pushCleanup(async () => {
|
|
567
|
+
filter.dispose();
|
|
568
|
+
});
|
|
569
|
+
const resolverChainConfig = profile.genesisTime && !chainConfig.genesisTime ? {
|
|
570
|
+
...chainConfig,
|
|
571
|
+
genesisTime: profile.genesisTime
|
|
572
|
+
} : chainConfig;
|
|
573
|
+
const resolver = new OCAPResolver({
|
|
574
|
+
statedb,
|
|
575
|
+
indexdb,
|
|
576
|
+
ledger,
|
|
577
|
+
filter,
|
|
578
|
+
admissionBlockedCheck: profile.blacklist?.admissionBlockedCheck ?? ((addr) => preferencesManager.isBlocked(addr)),
|
|
579
|
+
admissionReservedSymbolCheck: profile.blacklist?.admissionReservedSymbolCheck ?? ((sym) => preferencesManager.isReservedSymbol(sym)),
|
|
580
|
+
config: resolverChainConfig,
|
|
581
|
+
validateTokenConfig: role.kind === "follower" ? false : profile.validateTokenConfig ?? true,
|
|
582
|
+
skipInitializeStateDB: role.kind === "follower",
|
|
583
|
+
deferInitialize: true,
|
|
584
|
+
consensusMode: role.kind === "hotstuff" || Boolean(hotstuffClusterConfig) ? "hotstuff" : "single",
|
|
585
|
+
txQueueConfig: profile.txQueue,
|
|
586
|
+
now: clockNow,
|
|
587
|
+
logger
|
|
588
|
+
});
|
|
589
|
+
resolverRef = resolver;
|
|
590
|
+
pushCleanup(async () => {
|
|
591
|
+
await resolver.shutdown();
|
|
592
|
+
ledger.setNodeRole("readonly");
|
|
593
|
+
});
|
|
594
|
+
const initialPrefs = preferencesManager.getSnapshot();
|
|
595
|
+
if (initialPrefs.runtime.txMaxRequest !== void 0) resolver.setMaxTxRequest(initialPrefs.runtime.txMaxRequest);
|
|
596
|
+
await resolver.initialize();
|
|
597
|
+
let followerSync;
|
|
598
|
+
let hotstuffRuntime;
|
|
599
|
+
if (role.kind === "follower") {
|
|
600
|
+
const hotstuffPeerUrls = (role.hotstuffValidators ?? []).map((v) => v.rpcUrl);
|
|
601
|
+
const mergedPeerUrls = Array.from(new Set([...role.clusterPeerUrls ?? [], ...hotstuffPeerUrls]));
|
|
602
|
+
const leaderRouter = Boolean(role.upstreamChainUrl) || mergedPeerUrls.length > 0 ? new LeaderRouter({
|
|
603
|
+
chainId: chainConfig.chainId,
|
|
604
|
+
upstreamUrl: role.upstreamChainUrl ?? null,
|
|
605
|
+
peerUrls: mergedPeerUrls,
|
|
606
|
+
hotstuffClusterConfig,
|
|
607
|
+
trustedProposer: followerPrep?.trustedProposer || role.trustedProposer || void 0,
|
|
608
|
+
trustedProposerPublicKey: followerPrep?.trustedProposerPublicKey || role.trustedProposerPublicKey || void 0,
|
|
609
|
+
allowUnauthenticatedLeaderFailover: Boolean(role.allowUnauthenticatedBootstrap)
|
|
610
|
+
}) : void 0;
|
|
611
|
+
const coldReaderForFollower = explicitColdReader ?? envColdReader ?? void 0;
|
|
612
|
+
followerSync = new FollowerSyncService({
|
|
613
|
+
resolver,
|
|
614
|
+
role: role.runtimeRole ?? "follower",
|
|
615
|
+
writePolicy: role.writePolicy,
|
|
616
|
+
syncMode: role.syncMode ?? "active-follower",
|
|
617
|
+
retentionMode: role.retentionMode ?? "archive",
|
|
618
|
+
hotWindowEntries: role.hotWindowEntries,
|
|
619
|
+
hotWindowCheckpoints: role.hotWindowCheckpoints,
|
|
620
|
+
upstreamUrl: role.upstreamChainUrl ?? null,
|
|
621
|
+
peerUrls: mergedPeerUrls,
|
|
622
|
+
snapshotBaseUrl: role.snapshotBaseUrl ?? null,
|
|
623
|
+
coldArchiveStore: coldReaderForFollower,
|
|
624
|
+
leaderRouter,
|
|
625
|
+
hotstuffClusterConfig,
|
|
626
|
+
trustedProposer: followerPrep?.trustedProposer ?? role.trustedProposer ?? null,
|
|
627
|
+
trustedProposerPublicKey: followerPrep?.trustedProposerPublicKey ?? role.trustedProposerPublicKey ?? null,
|
|
628
|
+
allowUnauthenticated: Boolean(role.allowUnauthenticatedBootstrap),
|
|
629
|
+
disallowKeylessCascadedUpstream: Boolean(role.disallowKeylessCascadedUpstream),
|
|
630
|
+
witnessWallet: role.witnessWallet,
|
|
631
|
+
witnessSubmitUrls: role.witnessSubmitUrls,
|
|
632
|
+
pollIntervalMs: role.pollIntervalMs,
|
|
633
|
+
maxSyncLag: role.maxSyncLag,
|
|
634
|
+
maxUpstreamStaleMs: role.maxUpstreamStaleMs,
|
|
635
|
+
startPaused: testHooks?.followerSync?.startPaused,
|
|
636
|
+
artificialPollDelayMs: testHooks?.followerSync?.artificialPollDelayMs,
|
|
637
|
+
interceptUpstreamFetch: testHooks?.followerSync?.interceptUpstreamFetch,
|
|
638
|
+
env: { ALLOW_PRIVATE_PEER_URLS: role.allowPrivatePeers ? "1" : "0" }
|
|
639
|
+
});
|
|
640
|
+
resolver.setNodeRuntime(followerSync);
|
|
641
|
+
if (testHooks?.followerSync?.onControllerReady) {
|
|
642
|
+
const syncRef = followerSync;
|
|
643
|
+
testHooks.followerSync.onControllerReady({
|
|
644
|
+
pause: () => syncRef.pause(),
|
|
645
|
+
resume: () => syncRef.resume(),
|
|
646
|
+
isPaused: () => syncRef.isPaused(),
|
|
647
|
+
triggerSyncOnce: () => syncRef.triggerSyncOnce()
|
|
648
|
+
});
|
|
649
|
+
}
|
|
650
|
+
if (Boolean(followerPrep?.bootstrapped) || !indexDbExisted) {
|
|
651
|
+
await resolver.rebuildIndex();
|
|
652
|
+
await followerSync.replayer.indexExistingOrphanEntries();
|
|
653
|
+
}
|
|
654
|
+
} else if (role.kind === "hotstuff") {
|
|
655
|
+
const hotstuffStateStore = new SqliteHotStuffStateStore(ledgerStorage);
|
|
656
|
+
hotstuffRuntime = new HotStuffNodeRuntime({
|
|
657
|
+
resolver,
|
|
658
|
+
validatorDid: resolvedProposer.address,
|
|
659
|
+
validatorWallet: resolvedProposer.proposerWallet,
|
|
660
|
+
validatorPublicKey: resolvedProposer.publicKey,
|
|
661
|
+
validators: role.validators,
|
|
662
|
+
quorumThreshold: role.quorumThreshold,
|
|
663
|
+
consensusBindHost: role.consensusBindHost,
|
|
664
|
+
consensusPort: role.consensusPort,
|
|
665
|
+
allowPublicBind: Boolean(role.allowPublicConsensusBind),
|
|
666
|
+
allowPrivateHttpPeers: Boolean(role.allowPrivatePeers),
|
|
667
|
+
writePolicy: role.writePolicy ?? "forward",
|
|
668
|
+
stateStore: hotstuffStateStore,
|
|
669
|
+
onOutboundConsensusRequest: testHooks?.hotstuff?.onOutboundConsensusRequest ?? testHooks?.hotstuff?.interceptOutboundRpc
|
|
670
|
+
});
|
|
671
|
+
resolver.setNodeRuntime(hotstuffRuntime);
|
|
672
|
+
}
|
|
673
|
+
await applyBootRuntimePreferences({
|
|
674
|
+
runtime: resolver.getNodeRuntime?.(),
|
|
675
|
+
preferencesManager,
|
|
676
|
+
env: adminEnv,
|
|
677
|
+
logger: variadicLogger
|
|
678
|
+
});
|
|
679
|
+
if (followerSync) {
|
|
680
|
+
const syncRef = followerSync;
|
|
681
|
+
pushCleanup(async () => {
|
|
682
|
+
await syncRef.close();
|
|
683
|
+
});
|
|
684
|
+
await followerSync.start();
|
|
685
|
+
} else if (hotstuffRuntime) {
|
|
686
|
+
const hsRef = hotstuffRuntime;
|
|
687
|
+
pushCleanup(async () => {
|
|
688
|
+
await hsRef.close();
|
|
689
|
+
});
|
|
690
|
+
await hotstuffRuntime.start();
|
|
691
|
+
}
|
|
692
|
+
const app = express();
|
|
693
|
+
let isShuttingDown = false;
|
|
694
|
+
let activeResponses = 0;
|
|
695
|
+
const drainWaiters = /* @__PURE__ */ new Set();
|
|
696
|
+
if (profile.http.corsOrigins !== false) app.use(profile.http.corsOrigins !== void 0 && profile.http.corsOrigins !== true ? cors({ origin: profile.http.corsOrigins }) : cors());
|
|
697
|
+
app.use((_req, res, next) => {
|
|
698
|
+
if (isShuttingDown) {
|
|
699
|
+
res.setHeader("Connection", "close");
|
|
700
|
+
res.setHeader("Cache-Control", "no-store");
|
|
701
|
+
res.status(503).json({
|
|
702
|
+
code: "SERVICE_UNAVAILABLE",
|
|
703
|
+
error: "Chain node is shutting down"
|
|
704
|
+
});
|
|
705
|
+
return;
|
|
706
|
+
}
|
|
707
|
+
activeResponses++;
|
|
708
|
+
let settled = false;
|
|
709
|
+
const markDone = () => {
|
|
710
|
+
if (settled) return;
|
|
711
|
+
settled = true;
|
|
712
|
+
activeResponses = Math.max(0, activeResponses - 1);
|
|
713
|
+
if (activeResponses === 0 && drainWaiters.size > 0) {
|
|
714
|
+
for (const notify of Array.from(drainWaiters)) notify();
|
|
715
|
+
drainWaiters.clear();
|
|
716
|
+
}
|
|
717
|
+
};
|
|
718
|
+
res.once("finish", markDone);
|
|
719
|
+
res.once("close", markDone);
|
|
720
|
+
next();
|
|
721
|
+
});
|
|
722
|
+
if (profile.http.enableAccessLog) app.use(createAccessLogMiddleware(logger));
|
|
723
|
+
app.head("/", (_req, res) => {
|
|
724
|
+
res.status(200).send("OK");
|
|
725
|
+
});
|
|
726
|
+
const maintenanceController = createNodeMaintenanceController({
|
|
727
|
+
resolver,
|
|
728
|
+
preferencesManager,
|
|
729
|
+
replayFilter: filter,
|
|
730
|
+
pruneIndexDbFn: profile.maintenance?.pruneIndexDbFn ? ({ findOnly }) => Promise.resolve(profile.maintenance.pruneIndexDbFn({
|
|
731
|
+
findOnly,
|
|
732
|
+
indexdb,
|
|
733
|
+
statedb
|
|
734
|
+
})) : void 0,
|
|
735
|
+
requireAllowUpdateTokenDistributionEnv: profile.maintenance?.requireAllowUpdateTokenDistributionEnv ?? false,
|
|
736
|
+
env: profile.maintenance?.env ?? adminEnv
|
|
737
|
+
});
|
|
738
|
+
const effectiveRetentionMode = role.retentionMode ?? "archive";
|
|
739
|
+
const effectiveSnapshotBaseUrl = "snapshotBaseUrl" in role ? role.snapshotBaseUrl ?? null : null;
|
|
740
|
+
const adminAuthGuard = createAdminAuthGuard({ env: adminEnv });
|
|
741
|
+
const nodeDashboardRouter = createNodeDashboardRouter({
|
|
742
|
+
resolver,
|
|
743
|
+
dataDir,
|
|
744
|
+
retentionMode: effectiveRetentionMode,
|
|
745
|
+
preferencesManager,
|
|
746
|
+
maintenanceController,
|
|
747
|
+
authGuard: adminAuthGuard,
|
|
748
|
+
env: adminEnv
|
|
749
|
+
});
|
|
750
|
+
if (profile.configureApp) await profile.configureApp(app, {
|
|
751
|
+
nodeId,
|
|
752
|
+
dataDir,
|
|
753
|
+
role: role.kind,
|
|
754
|
+
config: chainConfig,
|
|
755
|
+
statedb,
|
|
756
|
+
indexdb,
|
|
757
|
+
ledger,
|
|
758
|
+
resolver,
|
|
759
|
+
preferencesManager,
|
|
760
|
+
maintenanceController
|
|
761
|
+
});
|
|
762
|
+
const server = createSocketHandler({
|
|
763
|
+
indexdb,
|
|
764
|
+
app,
|
|
765
|
+
wsOptions: { broadcastEventName: `@arcblock/ws:broadcast:${nodeId}:${crypto.randomUUID()}` }
|
|
766
|
+
});
|
|
767
|
+
pushCleanup(async () => {
|
|
768
|
+
isShuttingDown = true;
|
|
769
|
+
await new Promise((resolveClose) => {
|
|
770
|
+
server.close(() => resolveClose());
|
|
771
|
+
});
|
|
772
|
+
});
|
|
773
|
+
app.use("/api", createAPIHandler({
|
|
774
|
+
resolver,
|
|
775
|
+
retentionMode: effectiveRetentionMode,
|
|
776
|
+
snapshotBaseUrl: effectiveSnapshotBaseUrl,
|
|
777
|
+
nodeId,
|
|
778
|
+
preferencesManager,
|
|
779
|
+
authGuard: adminAuthGuard,
|
|
780
|
+
nodeDashboardRouter,
|
|
781
|
+
nodeDashboardOptions: {
|
|
782
|
+
env: adminEnv,
|
|
783
|
+
authGuard: adminAuthGuard
|
|
784
|
+
}
|
|
785
|
+
}));
|
|
786
|
+
app.use("/node", nodeDashboardRouter);
|
|
787
|
+
if (profile.http.enableExplorer ?? isExplorerEnabled(adminEnv)) app.use(createExplorerMiddleware({
|
|
788
|
+
getConfig: () => resolver.config,
|
|
789
|
+
explorerDistDir: profile.http.explorerDistDir
|
|
790
|
+
}));
|
|
791
|
+
if (profile.http.enableDashboard ?? isDashboardEnabled(adminEnv)) app.use(createUnifiedConsoleMiddleware({
|
|
792
|
+
mountPath: "/dashboard",
|
|
793
|
+
getConfig: () => resolver.config
|
|
794
|
+
}));
|
|
795
|
+
app.use("/consensus", (_req, res) => {
|
|
796
|
+
res.status(404).json({ error: "Not found" });
|
|
797
|
+
});
|
|
798
|
+
app.use("/", createHttpHandler({
|
|
799
|
+
resolver,
|
|
800
|
+
onError: profile.http.onGraphqlError ? (err) => {
|
|
801
|
+
profile.http.onGraphqlError(err);
|
|
802
|
+
} : () => {}
|
|
803
|
+
}));
|
|
804
|
+
const bindHost = profile.http.host?.trim() || "127.0.0.1";
|
|
805
|
+
const requestedPort = profile.http.port;
|
|
806
|
+
if (!Number.isSafeInteger(requestedPort) || requestedPort < 0 || requestedPort > 65535) throw new CustomError("INVALID_CONFIG", `Invalid http.port="${String(requestedPort)}": expected 0..65535`);
|
|
807
|
+
await new Promise((resolveListen, rejectListen) => {
|
|
808
|
+
const onError = (err) => {
|
|
809
|
+
server.off("listening", onListening);
|
|
810
|
+
rejectListen(err);
|
|
811
|
+
};
|
|
812
|
+
const onListening = () => {
|
|
813
|
+
server.off("error", onError);
|
|
814
|
+
resolveListen();
|
|
815
|
+
};
|
|
816
|
+
server.once("error", onError);
|
|
817
|
+
server.once("listening", onListening);
|
|
818
|
+
server.listen(requestedPort, bindHost);
|
|
819
|
+
});
|
|
820
|
+
const addressInfo = server.address();
|
|
821
|
+
const boundPort = addressInfo && typeof addressInfo === "object" && typeof addressInfo.port === "number" ? addressInfo.port : requestedPort;
|
|
822
|
+
const urlHost = formatHttpHostForUrl(bindHost);
|
|
823
|
+
const endpoint = `http://${urlHost}:${boundPort}`;
|
|
824
|
+
const wsUrl = `ws://${urlHost}:${boundPort}`;
|
|
825
|
+
if (testHooks?.onAfterBoot) await testHooks.onAfterBoot({
|
|
826
|
+
dataDir,
|
|
827
|
+
statedb,
|
|
828
|
+
ledger,
|
|
829
|
+
trustedStorage
|
|
830
|
+
});
|
|
831
|
+
const drainTimeoutMs = typeof profile.http.drainTimeoutMs === "number" && Number.isFinite(profile.http.drainTimeoutMs) && profile.http.drainTimeoutMs >= 0 ? profile.http.drainTimeoutMs : DEFAULT_DRAIN_TIMEOUT_MS;
|
|
832
|
+
const waitForActiveHttpDrain = async () => {
|
|
833
|
+
if (activeResponses <= 0 || drainTimeoutMs <= 0) return;
|
|
834
|
+
await new Promise((resolveDrain) => {
|
|
835
|
+
let timer = null;
|
|
836
|
+
const finish = () => {
|
|
837
|
+
if (timer) {
|
|
838
|
+
clearTimeout(timer);
|
|
839
|
+
timer = null;
|
|
840
|
+
}
|
|
841
|
+
drainWaiters.delete(finish);
|
|
842
|
+
resolveDrain();
|
|
843
|
+
};
|
|
844
|
+
drainWaiters.add(finish);
|
|
845
|
+
timer = setTimeout(finish, drainTimeoutMs);
|
|
846
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
847
|
+
if (activeResponses <= 0) finish();
|
|
848
|
+
});
|
|
849
|
+
};
|
|
850
|
+
let stopPromise = null;
|
|
851
|
+
const stop = () => {
|
|
852
|
+
if (stopPromise) return stopPromise;
|
|
853
|
+
stopPromise = (async () => {
|
|
854
|
+
let firstError = null;
|
|
855
|
+
const captureErr = (err) => {
|
|
856
|
+
if (firstError === null) firstError = err;
|
|
857
|
+
};
|
|
858
|
+
try {
|
|
859
|
+
if (followerSync) await followerSync.close().catch(captureErr);
|
|
860
|
+
cancelFollowerHwmTimer();
|
|
861
|
+
if (hotstuffRuntime) await hotstuffRuntime.close().catch(captureErr);
|
|
862
|
+
isShuttingDown = true;
|
|
863
|
+
server.closeIdleConnections?.();
|
|
864
|
+
await waitForActiveHttpDrain();
|
|
865
|
+
await new Promise((resolveClose) => {
|
|
866
|
+
server.close(() => resolveClose());
|
|
867
|
+
});
|
|
868
|
+
await resolver.shutdown().catch(captureErr);
|
|
869
|
+
ledger.setNodeRole("readonly");
|
|
870
|
+
try {
|
|
871
|
+
filter.dispose();
|
|
872
|
+
} catch (err) {
|
|
873
|
+
captureErr(err);
|
|
874
|
+
}
|
|
875
|
+
await statedb.close().catch(captureErr);
|
|
876
|
+
await trustedStorage.close().catch(captureErr);
|
|
877
|
+
await indexdb.close().catch(captureErr);
|
|
878
|
+
if (isFileBackedFollower) try {
|
|
879
|
+
const [latestSeq, latestCp] = await Promise.all([ledger.getLatestSequence(), ledger.getCheckpoint()]);
|
|
880
|
+
persistFollowerHighWaterMark({
|
|
881
|
+
dataDir,
|
|
882
|
+
sequence: latestSeq,
|
|
883
|
+
checkpointHeight: latestCp?.height ?? 0,
|
|
884
|
+
chainId: chainConfig.chainId,
|
|
885
|
+
proposer: followerHwmProposer,
|
|
886
|
+
proposerPublicKey: followerHwmProposerPk
|
|
887
|
+
});
|
|
888
|
+
} catch (err) {
|
|
889
|
+
captureErr(err);
|
|
890
|
+
}
|
|
891
|
+
} finally {
|
|
892
|
+
await ledger.close().catch(captureErr);
|
|
893
|
+
}
|
|
894
|
+
if (firstError !== null) throw firstError;
|
|
895
|
+
})();
|
|
896
|
+
return stopPromise;
|
|
897
|
+
};
|
|
898
|
+
const finalProposerDid = (role.kind === "follower" ? followerSync?.getTrustedProposer() : null) || ledger.getProposer?.() || null;
|
|
899
|
+
const finalProposerPk = (role.kind === "follower" ? followerSync?.getTrustedProposerPublicKey() : null) || ledger.getProposerPublicKey?.() || null;
|
|
900
|
+
const signatureKeyType = finalProposerPk ? decodeMultiCurvePublicKey(finalProposerPk)?.curve ?? null : null;
|
|
901
|
+
return {
|
|
902
|
+
endpoint,
|
|
903
|
+
rpcUrl: endpoint,
|
|
904
|
+
wsUrl,
|
|
905
|
+
port: boundPort,
|
|
906
|
+
host: bindHost,
|
|
907
|
+
chainId: chainConfig.chainId,
|
|
908
|
+
role: role.kind,
|
|
909
|
+
nodeId,
|
|
910
|
+
dataDir,
|
|
911
|
+
get proposerDid() {
|
|
912
|
+
return (role.kind === "follower" ? followerSync?.getTrustedProposer() : null) || ledger.getProposer?.() || finalProposerDid;
|
|
913
|
+
},
|
|
914
|
+
get proposerPublicKey() {
|
|
915
|
+
return (role.kind === "follower" ? followerSync?.getTrustedProposerPublicKey() : null) || ledger.getProposerPublicKey?.() || finalProposerPk;
|
|
916
|
+
},
|
|
917
|
+
get signatureKeyType() {
|
|
918
|
+
const pk = (role.kind === "follower" ? followerSync?.getTrustedProposerPublicKey() : null) || ledger.getProposerPublicKey?.() || finalProposerPk;
|
|
919
|
+
return pk ? decodeMultiCurvePublicKey(pk)?.curve ?? null : signatureKeyType;
|
|
920
|
+
},
|
|
921
|
+
app,
|
|
922
|
+
resolver,
|
|
923
|
+
ledger,
|
|
924
|
+
ledgerStorage,
|
|
925
|
+
statedb,
|
|
926
|
+
indexdb,
|
|
927
|
+
trustedStorage,
|
|
928
|
+
server,
|
|
929
|
+
...followerSync ? { followerSync } : {},
|
|
930
|
+
...hotstuffRuntime ? { hotstuffRuntime } : {},
|
|
931
|
+
preferencesManager,
|
|
932
|
+
maintenanceController,
|
|
933
|
+
stop
|
|
934
|
+
};
|
|
935
|
+
} catch (err) {
|
|
936
|
+
await unwindCleanupStack();
|
|
937
|
+
throw err;
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
function isStartChainNodeOptions(input) {
|
|
941
|
+
return Boolean(input && typeof input === "object" && "profile" in input && input.profile);
|
|
942
|
+
}
|
|
943
|
+
async function startChainNode(optionsOrProfile) {
|
|
944
|
+
const initialProfile = isStartChainNodeOptions(optionsOrProfile) ? optionsOrProfile.profile : optionsOrProfile;
|
|
945
|
+
const testHooks = optionsOrProfile.testHooks;
|
|
946
|
+
assertValidChainNodeTestHooks(testHooks);
|
|
947
|
+
const baseNow = testHooks?.now ?? (() => Date.now());
|
|
948
|
+
let clockOffsetMs = Math.trunc((testHooks?.initialClockOffsetMs ?? 0) + (testHooks?.initialClockOffsetSeconds ?? 0) * 1e3);
|
|
949
|
+
const clockNow = () => baseNow() + clockOffsetMs;
|
|
950
|
+
let currentProfile = initialProfile;
|
|
951
|
+
let currentBooted = await bootChainNodeOnce({
|
|
952
|
+
profile: currentProfile,
|
|
953
|
+
testHooks,
|
|
954
|
+
clockNow
|
|
955
|
+
});
|
|
956
|
+
const advanceClockFn = testHooks !== void 0 ? (seconds) => {
|
|
957
|
+
assertValidChainNodeTestHooks(testHooks);
|
|
958
|
+
if (typeof seconds !== "number" || !Number.isFinite(seconds)) throw new CustomError("INVALID_PARAMS", `advanceClock requires a finite number of seconds, got ${String(seconds)}`);
|
|
959
|
+
clockOffsetMs += Math.trunc(seconds * 1e3);
|
|
960
|
+
return clockNow();
|
|
961
|
+
} : void 0;
|
|
962
|
+
let lifecycleChain = Promise.resolve();
|
|
963
|
+
const withLifecycleLock = (fn) => {
|
|
964
|
+
const next = lifecycleChain.then(fn, fn);
|
|
965
|
+
lifecycleChain = next.then(() => void 0, () => void 0);
|
|
966
|
+
return next;
|
|
967
|
+
};
|
|
968
|
+
const handle = {
|
|
969
|
+
get endpoint() {
|
|
970
|
+
return currentBooted.endpoint;
|
|
971
|
+
},
|
|
972
|
+
get rpcUrl() {
|
|
973
|
+
return currentBooted.rpcUrl;
|
|
974
|
+
},
|
|
975
|
+
get wsUrl() {
|
|
976
|
+
return currentBooted.wsUrl;
|
|
977
|
+
},
|
|
978
|
+
get port() {
|
|
979
|
+
return currentBooted.port;
|
|
980
|
+
},
|
|
981
|
+
get host() {
|
|
982
|
+
return currentBooted.host;
|
|
983
|
+
},
|
|
984
|
+
get chainId() {
|
|
985
|
+
return currentBooted.chainId;
|
|
986
|
+
},
|
|
987
|
+
get role() {
|
|
988
|
+
return currentBooted.role;
|
|
989
|
+
},
|
|
990
|
+
get nodeId() {
|
|
991
|
+
return currentBooted.nodeId;
|
|
992
|
+
},
|
|
993
|
+
get dataDir() {
|
|
994
|
+
return currentBooted.dataDir;
|
|
995
|
+
},
|
|
996
|
+
get proposerDid() {
|
|
997
|
+
return currentBooted.proposerDid;
|
|
998
|
+
},
|
|
999
|
+
get proposerPublicKey() {
|
|
1000
|
+
return currentBooted.proposerPublicKey;
|
|
1001
|
+
},
|
|
1002
|
+
get signatureKeyType() {
|
|
1003
|
+
return currentBooted.signatureKeyType;
|
|
1004
|
+
},
|
|
1005
|
+
get app() {
|
|
1006
|
+
return currentBooted.app;
|
|
1007
|
+
},
|
|
1008
|
+
get resolver() {
|
|
1009
|
+
return currentBooted.resolver;
|
|
1010
|
+
},
|
|
1011
|
+
get ledger() {
|
|
1012
|
+
return currentBooted.ledger;
|
|
1013
|
+
},
|
|
1014
|
+
get ledgerStorage() {
|
|
1015
|
+
return currentBooted.ledgerStorage;
|
|
1016
|
+
},
|
|
1017
|
+
get statedb() {
|
|
1018
|
+
return currentBooted.statedb;
|
|
1019
|
+
},
|
|
1020
|
+
get indexdb() {
|
|
1021
|
+
return currentBooted.indexdb;
|
|
1022
|
+
},
|
|
1023
|
+
get trustedStorage() {
|
|
1024
|
+
return currentBooted.trustedStorage;
|
|
1025
|
+
},
|
|
1026
|
+
get server() {
|
|
1027
|
+
return currentBooted.server;
|
|
1028
|
+
},
|
|
1029
|
+
get followerSync() {
|
|
1030
|
+
return currentBooted.followerSync;
|
|
1031
|
+
},
|
|
1032
|
+
get hotstuffRuntime() {
|
|
1033
|
+
return currentBooted.hotstuffRuntime;
|
|
1034
|
+
},
|
|
1035
|
+
get preferencesManager() {
|
|
1036
|
+
return currentBooted.preferencesManager;
|
|
1037
|
+
},
|
|
1038
|
+
get maintenanceController() {
|
|
1039
|
+
return currentBooted.maintenanceController;
|
|
1040
|
+
},
|
|
1041
|
+
async ledgerHealth() {
|
|
1042
|
+
return currentBooted.ledger.getHealth();
|
|
1043
|
+
},
|
|
1044
|
+
...advanceClockFn ? { advanceClock: advanceClockFn } : {},
|
|
1045
|
+
async restart(nextProfile) {
|
|
1046
|
+
return withLifecycleLock(async () => {
|
|
1047
|
+
const previousPort = currentBooted.port;
|
|
1048
|
+
await currentBooted.stop();
|
|
1049
|
+
const mergedHttp = {
|
|
1050
|
+
...currentProfile.http,
|
|
1051
|
+
...nextProfile?.http ?? {},
|
|
1052
|
+
port: nextProfile?.http?.port !== void 0 ? nextProfile.http.port : previousPort
|
|
1053
|
+
};
|
|
1054
|
+
const mergedProfile = {
|
|
1055
|
+
...currentProfile,
|
|
1056
|
+
...nextProfile ?? {},
|
|
1057
|
+
http: mergedHttp,
|
|
1058
|
+
...currentProfile.storage || nextProfile?.storage ? { storage: {
|
|
1059
|
+
...currentProfile.storage ?? {},
|
|
1060
|
+
...nextProfile?.storage ?? {}
|
|
1061
|
+
} } : {},
|
|
1062
|
+
...currentProfile.checkpoint || nextProfile?.checkpoint ? { checkpoint: {
|
|
1063
|
+
...currentProfile.checkpoint ?? {},
|
|
1064
|
+
...nextProfile?.checkpoint ?? {}
|
|
1065
|
+
} } : {},
|
|
1066
|
+
...currentProfile.da || nextProfile?.da ? { da: {
|
|
1067
|
+
...currentProfile.da ?? {},
|
|
1068
|
+
...nextProfile?.da ?? {}
|
|
1069
|
+
} } : {},
|
|
1070
|
+
...currentProfile.blacklist || nextProfile?.blacklist ? { blacklist: {
|
|
1071
|
+
...currentProfile.blacklist ?? {},
|
|
1072
|
+
...nextProfile?.blacklist ?? {}
|
|
1073
|
+
} } : {},
|
|
1074
|
+
...currentProfile.txQueue || nextProfile?.txQueue ? { txQueue: {
|
|
1075
|
+
...currentProfile.txQueue ?? {},
|
|
1076
|
+
...nextProfile?.txQueue ?? {}
|
|
1077
|
+
} } : {},
|
|
1078
|
+
...currentProfile.maintenance || nextProfile?.maintenance ? { maintenance: {
|
|
1079
|
+
...currentProfile.maintenance ?? {},
|
|
1080
|
+
...nextProfile?.maintenance ?? {}
|
|
1081
|
+
} } : {}
|
|
1082
|
+
};
|
|
1083
|
+
currentBooted = await bootChainNodeOnce({
|
|
1084
|
+
profile: mergedProfile,
|
|
1085
|
+
testHooks,
|
|
1086
|
+
clockNow
|
|
1087
|
+
});
|
|
1088
|
+
currentProfile = mergedProfile;
|
|
1089
|
+
return handle;
|
|
1090
|
+
});
|
|
1091
|
+
},
|
|
1092
|
+
async stop() {
|
|
1093
|
+
return withLifecycleLock(async () => {
|
|
1094
|
+
await currentBooted.stop();
|
|
1095
|
+
});
|
|
1096
|
+
}
|
|
1097
|
+
};
|
|
1098
|
+
return handle;
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
//#endregion
|
|
1102
|
+
export { startChainNode };
|