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