@ocap/resolver 1.31.9 → 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.
Files changed (42) hide show
  1. package/esm/_virtual/rolldown_runtime.mjs +7 -0
  2. package/esm/api.d.mts +33 -5
  3. package/esm/api.mjs +939 -53
  4. package/esm/dashboard.d.mts +199 -0
  5. package/esm/dashboard.mjs +2481 -0
  6. package/esm/explorer.d.mts +29 -0
  7. package/esm/explorer.mjs +227 -0
  8. package/esm/follower.d.mts +294 -0
  9. package/esm/follower.mjs +2452 -0
  10. package/esm/hooks.mjs +1 -1
  11. package/esm/hotstuff-runtime.d.mts +271 -0
  12. package/esm/hotstuff-runtime.mjs +2668 -0
  13. package/esm/index.d.mts +79 -4
  14. package/esm/index.mjs +911 -174
  15. package/esm/node-preferences.d.mts +203 -0
  16. package/esm/node-preferences.mjs +1021 -0
  17. package/esm/replayer.d.mts +114 -0
  18. package/esm/replayer.mjs +430 -0
  19. package/esm/token-distribution.mjs +2 -2
  20. package/esm/token-flow.mjs +1 -1
  21. package/esm/types.d.mts +25 -2
  22. package/lib/api.cjs +941 -52
  23. package/lib/api.d.cts +33 -5
  24. package/lib/dashboard.cjs +2491 -0
  25. package/lib/dashboard.d.cts +199 -0
  26. package/lib/explorer.cjs +227 -0
  27. package/lib/explorer.d.cts +29 -0
  28. package/lib/follower.cjs +2458 -0
  29. package/lib/follower.d.cts +294 -0
  30. package/lib/hooks.cjs +1 -1
  31. package/lib/hotstuff-runtime.cjs +2671 -0
  32. package/lib/hotstuff-runtime.d.cts +271 -0
  33. package/lib/index.cjs +946 -174
  34. package/lib/index.d.cts +79 -4
  35. package/lib/node-preferences.cjs +1043 -0
  36. package/lib/node-preferences.d.cts +203 -0
  37. package/lib/replayer.cjs +432 -0
  38. package/lib/replayer.d.cts +114 -0
  39. package/lib/token-distribution.cjs +2 -2
  40. package/lib/token-flow.cjs +1 -1
  41. package/lib/types.d.cts +25 -2
  42. package/package.json +20 -14
@@ -0,0 +1,29 @@
1
+ import { RequestHandler } from "express";
2
+ import { IChainConfig } from "@ocap/types";
3
+
4
+ //#region src/explorer.d.ts
5
+
6
+ interface CreateExplorerMiddlewareOptions {
7
+ getConfig: () => Partial<IChainConfig> | undefined;
8
+ explorerDistDir?: string | null;
9
+ chainEndpoint?: string;
10
+ }
11
+ /**
12
+ * Returns `true` when local Explorer mounting is enabled via `EXPLORER_ENABLED=1|true` or CLI `--explorer`.
13
+ */
14
+ declare function isExplorerEnabled(env?: Record<string, string | undefined>, argv?: string[]): boolean;
15
+ /**
16
+ * Create a static, read-only Express middleware serving `/__blocklet__.js`, `/static/js/networks.js`,
17
+ * and `/explorer` without intercepting `/`, `/api/*`, or `/blocked`.
18
+ *
19
+ * With `explorerDistDir` it serves a pre-built `blocklet/block-explorer` bundle (#1909). That bundle is built for the
20
+ * root (`vite build --base=/`): its page routes are `/explorer/*`, its files live at top-level paths of the dist
21
+ * (`/assets/*`, `/static/*`, `/images/*`, `/favicon.ico`, ...), it reads the chain list from
22
+ * `window.ARCBLOCK_NETWORKS` and it loads `__blocklet__.js` relative to the page. So in dist mode the middleware also
23
+ * serves exactly the top-level entries the dist contains (never `/`, `/api`, `/node`, `/dashboard` or anything else),
24
+ * answers `__blocklet__.js` at any depth with an empty script (as outside Blocklet Server) and points
25
+ * `ARCBLOCK_NETWORKS` at this node's own `/api/`.
26
+ */
27
+ declare function createExplorerMiddleware(options: CreateExplorerMiddlewareOptions): RequestHandler;
28
+ //#endregion
29
+ export { CreateExplorerMiddlewareOptions, createExplorerMiddleware, isExplorerEnabled };
@@ -0,0 +1,227 @@
1
+ import { __require } from "./_virtual/rolldown_runtime.mjs";
2
+ import { UNIFIED_CONSOLE_APP_JS, buildUnifiedConsoleHtml } from "./dashboard.mjs";
3
+
4
+ //#region src/explorer.ts
5
+ function loadNodeBuiltin(id) {
6
+ try {
7
+ const proc = globalThis?.process;
8
+ if (typeof proc?.getBuiltinModule === "function") {
9
+ const mod = proc.getBuiltinModule(id);
10
+ if (mod) return mod;
11
+ }
12
+ const req = typeof __non_webpack_require__ === "function" ? __non_webpack_require__ : typeof __require === "function" ? __require : void 0;
13
+ if (typeof req === "function") return req(id);
14
+ } catch {}
15
+ }
16
+ function safeJsonForJsLiteral(value) {
17
+ return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
18
+ }
19
+ const MAX_EXPLORER_STATIC_FILE_BYTES = 16 * 1024 * 1024;
20
+ const MIME_BY_EXT = {
21
+ ".html": "text/html; charset=utf-8",
22
+ ".js": "application/javascript; charset=utf-8",
23
+ ".mjs": "application/javascript; charset=utf-8",
24
+ ".css": "text/css; charset=utf-8",
25
+ ".json": "application/json; charset=utf-8",
26
+ ".svg": "image/svg+xml",
27
+ ".png": "image/png",
28
+ ".jpg": "image/jpeg",
29
+ ".jpeg": "image/jpeg",
30
+ ".webp": "image/webp",
31
+ ".ico": "image/x-icon",
32
+ ".woff": "font/woff",
33
+ ".woff2": "font/woff2",
34
+ ".txt": "text/plain; charset=utf-8"
35
+ };
36
+ /**
37
+ * Returns `true` when local Explorer mounting is enabled via `EXPLORER_ENABLED=1|true` or CLI `--explorer`.
38
+ */
39
+ function isExplorerEnabled(env = globalThis?.process?.env ?? {}, argv = globalThis?.process?.argv ?? []) {
40
+ const raw = (env.EXPLORER_ENABLED ?? "").trim().toLowerCase();
41
+ if (raw === "1" || raw === "true") return true;
42
+ if (raw === "0" || raw === "false") return false;
43
+ return Array.isArray(argv) && argv.includes("--explorer");
44
+ }
45
+ function applyExplorerSecurityHeaders(res, isBuiltinStrictCsp) {
46
+ res.setHeader("X-Content-Type-Options", "nosniff");
47
+ res.setHeader("X-Frame-Options", "DENY");
48
+ res.setHeader("Referrer-Policy", "no-referrer");
49
+ res.setHeader("Content-Security-Policy", isBuiltinStrictCsp ? "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'" : "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: https:; font-src 'self' data: https://fonts.gstatic.com; connect-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'");
50
+ }
51
+ /**
52
+ * Create a static, read-only Express middleware serving `/__blocklet__.js`, `/static/js/networks.js`,
53
+ * and `/explorer` without intercepting `/`, `/api/*`, or `/blocked`.
54
+ *
55
+ * With `explorerDistDir` it serves a pre-built `blocklet/block-explorer` bundle (#1909). That bundle is built for the
56
+ * root (`vite build --base=/`): its page routes are `/explorer/*`, its files live at top-level paths of the dist
57
+ * (`/assets/*`, `/static/*`, `/images/*`, `/favicon.ico`, ...), it reads the chain list from
58
+ * `window.ARCBLOCK_NETWORKS` and it loads `__blocklet__.js` relative to the page. So in dist mode the middleware also
59
+ * serves exactly the top-level entries the dist contains (never `/`, `/api`, `/node`, `/dashboard` or anything else),
60
+ * answers `__blocklet__.js` at any depth with an empty script (as outside Blocklet Server) and points
61
+ * `ARCBLOCK_NETWORKS` at this node's own `/api/`.
62
+ */
63
+ function createExplorerMiddleware(options) {
64
+ const chainEndpoint = (options.chainEndpoint || "/api").trim() || "/api";
65
+ const fs = loadNodeBuiltin("node:fs");
66
+ const path = loadNodeBuiltin("node:path");
67
+ let verifiedDistRealPath = null;
68
+ const rawDist = (options.explorerDistDir ?? "").trim();
69
+ if (rawDist && fs && path) {
70
+ const resolved = path.resolve(rawDist);
71
+ if (!fs.existsSync(resolved)) throw new Error(`Configured EXPLORER_DIST_DIR does not exist: ${resolved}`);
72
+ if (!fs.statSync(resolved).isDirectory()) throw new Error(`Configured EXPLORER_DIST_DIR is not a directory: ${resolved}`);
73
+ verifiedDistRealPath = fs.realpathSync(resolved);
74
+ }
75
+ const RESERVED_ROOT_NAMES = new Set([
76
+ "index.html",
77
+ "explorer",
78
+ "api",
79
+ "node",
80
+ "dashboard",
81
+ "blocked",
82
+ "consensus"
83
+ ]);
84
+ const distRootEntries = /* @__PURE__ */ new Set();
85
+ if (verifiedDistRealPath && fs) for (const name of fs.readdirSync(verifiedDistRealPath)) {
86
+ if (name.startsWith(".") || name.startsWith("_") || RESERVED_ROOT_NAMES.has(name)) continue;
87
+ distRootEntries.add(name);
88
+ }
89
+ return (req, res, next) => {
90
+ const reqPath = req.path || "/";
91
+ if (reqPath === "/consensus" || reqPath.startsWith("/consensus/")) return res.status(404).json({ error: "Not found" });
92
+ if (req.method !== "GET" && req.method !== "HEAD") return next();
93
+ if (verifiedDistRealPath && (reqPath === "/__blocklet__.js" || reqPath.endsWith("/__blocklet__.js"))) {
94
+ applyExplorerSecurityHeaders(res, false);
95
+ res.setHeader("Content-Type", "application/javascript; charset=utf-8");
96
+ res.setHeader("Cache-Control", "no-cache");
97
+ return res.status(200).send("");
98
+ }
99
+ if (reqPath === "/__blocklet__.js") {
100
+ const cfg = options.getConfig() ?? {};
101
+ const chainId = String(cfg.chainId || "local-chain");
102
+ const payload = {
103
+ appId: chainId,
104
+ appName: chainId,
105
+ prefix: "/explorer",
106
+ mountPoints: [{
107
+ name: "chain-api",
108
+ mountPoint: chainEndpoint
109
+ }, {
110
+ name: "block-explorer",
111
+ mountPoint: "/explorer"
112
+ }],
113
+ env: { EXPLORER_CHAIN_ENDPOINT: chainEndpoint }
114
+ };
115
+ applyExplorerSecurityHeaders(res, true);
116
+ res.setHeader("Content-Type", "application/javascript; charset=utf-8");
117
+ res.setHeader("Cache-Control", "no-cache");
118
+ return res.status(200).send(`window.blocklet = ${safeJsonForJsLiteral(payload)};\n`);
119
+ }
120
+ if (verifiedDistRealPath && reqPath === "/static/js/networks.js") {
121
+ const cfg = options.getConfig() ?? {};
122
+ const chainId = String(cfg.chainId || "local-chain");
123
+ const host = req.get?.("host") || req.headers?.host || "";
124
+ const endpoint = /^https?:\/\//.test(chainEndpoint) ? chainEndpoint : `${req.protocol || "http"}://${host}${chainEndpoint.startsWith("/") ? "" : "/"}${chainEndpoint.replace(/\/+$/, "")}/`;
125
+ const networks = [{
126
+ name: chainId,
127
+ abbr: cfg.token?.symbol || "ARC",
128
+ group: "public",
129
+ endpoint,
130
+ description: "this OCAP node"
131
+ }];
132
+ applyExplorerSecurityHeaders(res, false);
133
+ res.setHeader("Content-Type", "application/javascript; charset=utf-8");
134
+ res.setHeader("Cache-Control", "no-cache");
135
+ return res.status(200).send(`window.ARCBLOCK_NETWORKS = ${safeJsonForJsLiteral(networks)};\n`);
136
+ }
137
+ if (reqPath === "/static/js/networks.js") {
138
+ const cfg = options.getConfig() ?? {};
139
+ const chainId = String(cfg.chainId || "local-chain");
140
+ const networks = [{
141
+ id: chainId,
142
+ name: chainId,
143
+ abbr: cfg.token?.symbol || "ARC",
144
+ endpoint: chainEndpoint,
145
+ localFollower: true
146
+ }];
147
+ applyExplorerSecurityHeaders(res, true);
148
+ res.setHeader("Content-Type", "application/javascript; charset=utf-8");
149
+ res.setHeader("Cache-Control", "no-cache");
150
+ return res.status(200).send(`window.networks = ${safeJsonForJsLiteral(networks)};\n`);
151
+ }
152
+ const firstSegment = reqPath.split("/")[1] ?? "";
153
+ const isDistRootAsset = Boolean(verifiedDistRealPath) && distRootEntries.has(firstSegment);
154
+ if (!isDistRootAsset && reqPath !== "/explorer" && !reqPath.startsWith("/explorer/")) return next();
155
+ const subPathRaw = isDistRootAsset ? reqPath : reqPath.slice(9) || "/";
156
+ let decodedSubPath;
157
+ try {
158
+ decodedSubPath = decodeURIComponent(subPathRaw);
159
+ } catch {
160
+ applyExplorerSecurityHeaders(res, true);
161
+ return res.status(400).type("text/plain").send("Invalid URI path");
162
+ }
163
+ if (decodedSubPath.includes("\0") || decodedSubPath.includes("\\") || decodedSubPath.split("/").includes("..")) {
164
+ applyExplorerSecurityHeaders(res, true);
165
+ return res.status(400).type("text/plain").send("Forbidden path segment");
166
+ }
167
+ if (verifiedDistRealPath && fs && path) {
168
+ const relativeTarget = decodedSubPath.replace(/^\/+/g, "") || "index.html";
169
+ const candidatePath = path.resolve(verifiedDistRealPath, relativeTarget);
170
+ const isContained = (realTarget) => realTarget === verifiedDistRealPath || realTarget.startsWith(`${verifiedDistRealPath}${path.sep}`);
171
+ let targetToServe = null;
172
+ if (fs.existsSync(candidatePath)) {
173
+ const lstat = fs.lstatSync(candidatePath);
174
+ if (lstat.isSymbolicLink()) {
175
+ applyExplorerSecurityHeaders(res, false);
176
+ return res.status(403).type("text/plain").send("Symlinks are forbidden in EXPLORER_DIST_DIR");
177
+ }
178
+ const realCandidate = fs.realpathSync(candidatePath);
179
+ if (!isContained(realCandidate)) {
180
+ applyExplorerSecurityHeaders(res, false);
181
+ return res.status(403).type("text/plain").send("Path escapes EXPLORER_DIST_DIR");
182
+ }
183
+ if (lstat.isFile()) targetToServe = realCandidate;
184
+ }
185
+ if (!targetToServe && isDistRootAsset) {
186
+ applyExplorerSecurityHeaders(res, false);
187
+ return res.status(404).type("text/plain").send("Explorer asset not found");
188
+ }
189
+ if (!targetToServe) {
190
+ const fallbackIndex = path.join(verifiedDistRealPath, "index.html");
191
+ if (fs.existsSync(fallbackIndex) && !fs.lstatSync(fallbackIndex).isSymbolicLink()) {
192
+ const realIndex = fs.realpathSync(fallbackIndex);
193
+ if (isContained(realIndex)) targetToServe = realIndex;
194
+ }
195
+ }
196
+ if (!targetToServe) {
197
+ applyExplorerSecurityHeaders(res, false);
198
+ return res.status(404).type("text/plain").send("Explorer asset not found");
199
+ }
200
+ if (fs.statSync(targetToServe).size > MAX_EXPLORER_STATIC_FILE_BYTES) {
201
+ applyExplorerSecurityHeaders(res, false);
202
+ return res.status(413).type("text/plain").send("Explorer static asset exceeds maximum allowed size");
203
+ }
204
+ const ext = path.extname(targetToServe).toLowerCase();
205
+ applyExplorerSecurityHeaders(res, false);
206
+ res.setHeader("Content-Type", MIME_BY_EXT[ext] || "application/octet-stream");
207
+ res.setHeader("Cache-Control", ext === ".html" ? "no-cache" : "public, max-age=3600");
208
+ return res.status(200).send(fs.readFileSync(targetToServe));
209
+ }
210
+ if (decodedSubPath === "/app.js") {
211
+ applyExplorerSecurityHeaders(res, true);
212
+ res.setHeader("Content-Type", "application/javascript; charset=utf-8");
213
+ res.setHeader("Cache-Control", "no-cache");
214
+ return res.status(200).send(UNIFIED_CONSOLE_APP_JS);
215
+ }
216
+ applyExplorerSecurityHeaders(res, true);
217
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
218
+ res.setHeader("Cache-Control", "no-cache");
219
+ return res.status(200).send(buildUnifiedConsoleHtml({
220
+ appBasePath: "/explorer",
221
+ defaultTab: "explorer"
222
+ }));
223
+ };
224
+ }
225
+
226
+ //#endregion
227
+ export { createExplorerMiddleware, isExplorerEnabled };
@@ -0,0 +1,294 @@
1
+ import { DnsLookupAllFn } from "./node-preferences.mjs";
2
+ import { IFutureTimestampRejection, IReplayerResolverTarget, LedgerEntryReplayer } from "./replayer.mjs";
3
+ import { ICheckpointSignerWallet } from "@arcblock/ledger-core";
4
+ import { IFollowerStatusResponse, IHotStuffClusterConfig, ILedgerArchiveHead, ILedgerSegment, INodeRuntimeAdapter, IResolverContext, TFollowerSyncMode, TNodeRetentionMode, TNodeRole, TNodeWritePolicy } from "@ocap/types";
5
+
6
+ //#region src/follower.d.ts
7
+
8
+ declare const DEFAULT_FOLLOWER_POLL_INTERVAL_MS = 500;
9
+ declare const DEFAULT_FOLLOWER_MAX_SYNC_LAG = 20;
10
+ declare const DEFAULT_FOLLOWER_MAX_UPSTREAM_STALE_MS = 15000;
11
+ declare const DEFAULT_FOLLOWER_HTTP_TIMEOUT_MS = 10000;
12
+ interface IColdSegmentReader {
13
+ getSegment(chainId: string, height: number, verifyOptions?: unknown): Promise<ILedgerSegment | null>;
14
+ getLatestHead?(chainId: string): Promise<ILedgerArchiveHead | null>;
15
+ getArchiveHead?(chainId: string): Promise<ILedgerArchiveHead | null>;
16
+ }
17
+ interface ILeaderRouterLike {
18
+ getActiveLeaderUrl(): string | null;
19
+ getCandidateUrls?(): string[];
20
+ updateCandidatePeerUrls?(peerUrls: string[]): void;
21
+ getDiagnosticsSnapshot?(): {
22
+ activeLeaderUrl: string | null;
23
+ candidateCount: number;
24
+ candidateUrls: string[];
25
+ minVerifiedCheckpointHeight: number;
26
+ inFlightForwards: number;
27
+ maxConcurrentForwards: number;
28
+ requireSignedForwardReceipt: boolean;
29
+ candidates: Array<{
30
+ url: string;
31
+ reachable: boolean;
32
+ writable: boolean;
33
+ checkpointHeight: number;
34
+ latestSequence: number;
35
+ qcView: number;
36
+ rttMs: number | null;
37
+ lastProbedAtMs: number;
38
+ }>;
39
+ };
40
+ forwardSendTx(args: {
41
+ tx: string;
42
+ extra?: Record<string, unknown> | string;
43
+ }, ctx?: IResolverContext): Promise<{
44
+ hash: string;
45
+ warning?: unknown;
46
+ }>;
47
+ probeAndPromoteLeader?(excludeBaseUrl?: string | Iterable<string>): Promise<string | null>;
48
+ updateTrustAnchor?(params: {
49
+ proposer?: string | null;
50
+ proposerPublicKey?: string | null;
51
+ }): void;
52
+ advanceMinVerifiedCheckpointHeight?(height: number): void;
53
+ setFetchImplIfDefault?(fetchFn: typeof fetch): void;
54
+ }
55
+ type TFollowerUpstreamFetchKind = 'status' | 'entries' | 'checkpoints' | 'snapshot-manifest' | 'snapshot-archive';
56
+ type TFollowerUpstreamFetchInterceptor = (ctx: {
57
+ kind: TFollowerUpstreamFetchKind;
58
+ url: string;
59
+ init?: RequestInit;
60
+ }, defaultFetch: typeof fetch) => Promise<Response>;
61
+ interface FollowerSyncServiceOptions {
62
+ resolver: IReplayerResolverTarget;
63
+ role: TNodeRole;
64
+ writePolicy: TNodeWritePolicy;
65
+ syncMode: TFollowerSyncMode;
66
+ upstreamUrl?: string | null;
67
+ peerUrls?: string[];
68
+ snapshotBaseUrl?: string | null;
69
+ coldArchiveStore?: IColdSegmentReader;
70
+ leaderRouter?: ILeaderRouterLike;
71
+ hotstuffClusterConfig?: IHotStuffClusterConfig;
72
+ trustedProposer?: string | null;
73
+ trustedProposerPublicKey?: string | null;
74
+ verifier?: (data: Uint8Array, signature: string, proposer: string) => Promise<boolean> | boolean;
75
+ allowUnauthenticated?: boolean;
76
+ disallowKeylessCascadedUpstream?: boolean;
77
+ pollIntervalMs?: number;
78
+ maxSyncLag?: number;
79
+ maxUpstreamStaleMs?: number;
80
+ httpTimeoutMs?: number;
81
+ retentionMode?: TNodeRetentionMode;
82
+ hotWindowEntries?: number;
83
+ hotWindowCheckpoints?: number;
84
+ witnessWallet?: ICheckpointSignerWallet;
85
+ witnessAddress?: string;
86
+ witnessSubmitUrls?: string[];
87
+ startPaused?: boolean;
88
+ artificialPollDelayMs?: number;
89
+ interceptUpstreamFetch?: TFollowerUpstreamFetchInterceptor;
90
+ fetchImpl?: typeof fetch;
91
+ dnsLookup?: DnsLookupAllFn;
92
+ env?: Record<string, string | undefined>;
93
+ /**
94
+ * #1961: refuse (retryably) peer entries with `sequence >= activationSequence` whose timestamp is more than
95
+ * `maxSkewMs` ahead of `now()`. Unset (default): no guard, today's behavior.
96
+ */
97
+ futureTimestampGuard?: {
98
+ activationSequence: number;
99
+ maxSkewMs: number;
100
+ now?: () => number;
101
+ };
102
+ }
103
+ declare function isTransientSqliteLockError(err: unknown): boolean;
104
+ declare class FollowerSyncService implements INodeRuntimeAdapter {
105
+ readonly role: TNodeRole;
106
+ writePolicy: TNodeWritePolicy;
107
+ readonly syncMode: TFollowerSyncMode;
108
+ readonly replayer: LedgerEntryReplayer;
109
+ private readonly resolver;
110
+ private readonly chainId;
111
+ private readonly upstreamUrl;
112
+ private readonly allowedBaseUrls;
113
+ private readonly coldArchiveStore?;
114
+ private readonly leaderRouter?;
115
+ private readonly hotstuffClusterConfig?;
116
+ private readonly hotstuffValidatorDids;
117
+ private trustedProposer;
118
+ private trustedProposerPublicKey;
119
+ private readonly verifier?;
120
+ private readonly allowUnauthenticated;
121
+ private readonly disallowKeylessCascadedUpstream;
122
+ private pollIntervalMs;
123
+ private maxSyncLag;
124
+ private readonly maxUpstreamStaleMs;
125
+ private readonly httpTimeoutMs;
126
+ private readonly retentionMode;
127
+ private readonly pruneController;
128
+ private readonly witnessWallet?;
129
+ private readonly witnessAddress;
130
+ private readonly witnessSubmitUrls;
131
+ private readonly attestedHeights;
132
+ private readonly pendingWitnessTasks;
133
+ private readonly fetchImpl;
134
+ private readonly artificialPollDelayMs;
135
+ private timer;
136
+ private syncInFlight;
137
+ private paused;
138
+ private stopped;
139
+ private halted;
140
+ private haltReason;
141
+ private futureTimestampRejections;
142
+ private lastFutureTimestampRejection;
143
+ private pendingCrashWindowReconcile;
144
+ private initialCrashReconcileCompleted;
145
+ private upstreamSequence;
146
+ private upstreamNodeId;
147
+ private upstreamNodeRole;
148
+ private lastUpstreamSuccessAtMs;
149
+ private stagnantSyncCycles;
150
+ private lastPeerProbeAtMs;
151
+ private seenSignedUpstream;
152
+ private seenSignedStatus;
153
+ private stagedTofuAnchor;
154
+ constructor(options: FollowerSyncServiceOptions);
155
+ isHalted(): boolean;
156
+ isReconciling(): boolean;
157
+ getHaltReason(): string | null;
158
+ getConsensusMode(): 'single' | 'hotstuff';
159
+ getUpstreamNodeId(): string | null;
160
+ getUpstreamNodeRole(): TNodeRole | null;
161
+ pause(): void;
162
+ resume(): void;
163
+ isPaused(): boolean;
164
+ updateRuntimeConfig(patch: {
165
+ writePolicy?: TNodeWritePolicy;
166
+ pollIntervalMs?: number;
167
+ maxSyncLag?: number;
168
+ peerUrls?: string[];
169
+ }): void;
170
+ getRuntimeDiagnostics(options?: {
171
+ includePrivateTopology?: boolean;
172
+ }): Record<string, unknown>;
173
+ triggerSyncOrProbe(): Promise<Record<string, unknown>>;
174
+ private haltFailClosed;
175
+ private resolveActiveUpstreamUrl;
176
+ isFollowerAuthenticated(): boolean;
177
+ getTrustedProposer(): string | null;
178
+ getTrustedProposerPublicKey(): string | null;
179
+ isSynced(): Promise<boolean>;
180
+ forwardSendTx(args: {
181
+ tx: string;
182
+ extra?: Record<string, unknown> | string;
183
+ }, ctx?: IResolverContext): Promise<{
184
+ hash: string;
185
+ warning?: unknown;
186
+ }>;
187
+ private readLocalStateCommitHash;
188
+ /**
189
+ * Resolve the locally verified `stateRoot` (`string` or `null` when zero state-committing entries
190
+ * have ever run up to this checkpoint) AFTER `LedgerEntryReplayer.replayEntry` has verified every
191
+ * non-orphan entry via `statedb.runAsLambda` (#1711).
192
+ */
193
+ private resolveVerifiedWitnessStateRoot;
194
+ /**
195
+ * Resolve the local StateDB commit hash to report in an `ok: false` fraud alert without ever
196
+ * reading untrusted upstream `segmentEntries` (#1711).
197
+ */
198
+ private resolveLocalFraudAlertStateRoot;
199
+ private recordFutureTimestampRejection;
200
+ /** #1961: how many peer entries were refused for a future timestamp, and the last one (for alerting/tests). */
201
+ getFutureTimestampRejections(): {
202
+ count: number;
203
+ last: IFutureTimestampRejection | null;
204
+ };
205
+ getFollowerStatus(): Promise<IFollowerStatusResponse>;
206
+ private isAllowedHotStuffValidator;
207
+ private hasCommittedTrustAnchor;
208
+ private getEffectiveTrustedProposer;
209
+ private getEffectiveTrustedProposerPublicKey;
210
+ private getEffectiveSeenSignedUpstream;
211
+ private getEffectiveSeenSignedStatus;
212
+ private markSeenSignedUpstream;
213
+ private markSeenSignedStatus;
214
+ private commitStagedTofuAnchor;
215
+ private rethrowIfLocalStorageOrLockError;
216
+ private persistTrustAnchorSafe;
217
+ private isCheckpointAuthenticatedByProposer;
218
+ /**
219
+ * Verify that BOTH `segment.checkpoint.signature` AND `segment.checkpoint.segmentCommitmentSignature`
220
+ * (covering `{ chainId: this.chainId, checkpoint, entries }`) were cryptographically signed by the
221
+ * trusted proposer (#1711). Prevents a corrupt/MITM cold mirror or cross-chain replay from tricking
222
+ * an honest Witness Follower into emitting a false-positive `ok: false` fraud alert.
223
+ */
224
+ private isColdSegmentAuthenticatedByProposer;
225
+ private dispatchWitnessAttestation;
226
+ private enqueueWitnessAttestation;
227
+ private checkCheckpointEquivocationAgainstLocal;
228
+ private buildSegmentImportOptions;
229
+ private verifyAndPinTrustAnchorFromStatus;
230
+ private verifyDidOrAccountMatchesPublicKey;
231
+ /**
232
+ * Re-hydrate `seenSignedUpstream` and any TOFU-pinned proposer trust anchor from durable `ledger`
233
+ * storage on process restart so `allowUnauthenticated` cannot regress after sealing signed checkpoints
234
+ * or pinning a verified proposer key (#1856).
235
+ */
236
+ private hydrateDurableTrustRatchet;
237
+ private tagColdTransportError;
238
+ private fetchColdSegment;
239
+ private fetchColdArchiveHead;
240
+ private fetchAllowlistedJson;
241
+ /**
242
+ * Stage 1B: Catch up sealed `.zst` checkpoint segments from `coldArchiveStore` when available.
243
+ */
244
+ private catchUpFromColdSegments;
245
+ private sealCaughtUpCheckpoints;
246
+ private tryEmitHotTailReplayFraudAlert;
247
+ private parseStrictEntryHashV2From;
248
+ private verifyHotTailEntriesBatchBeforeReplay;
249
+ /**
250
+ * In multi-peer unauthenticated / TOFU buffering mode (`bufferTailBeforeCommit`), pre-verify all
251
+ * upstream checkpoints up to `bufferedTipSeq` against `(local entries <= localSeq) + allBufferedEntries`
252
+ * BEFORE mutating `statedb` or `ledger` so a rogue peer serving valid entries with a forged checkpoint
253
+ * `stateRoot`/`txRoot` triggers clean peer failover instead of poisoning local DB (#1856).
254
+ */
255
+ private preVerifyBufferedCheckpointsBeforeCommit;
256
+ /**
257
+ * HotStuff BFT Follower Sync (#1712):
258
+ * Never replays un-QC'd hot-tail entries (`latestSequence > latestCheckpoint.sequence` or 1-of-N `batchSignature`).
259
+ * Instead, fetches each checkpoint height `h` with a verified `2f+1` `QuorumCertificate`, collects its
260
+ * finalized entries, runs `verifySegmentForImport` + `dryRunVerifyEntries` BEFORE mutating any local DB,
261
+ * and commits `statedb` + `ledger` atomically per QC-certified checkpoint.
262
+ */
263
+ private catchUpHotStuffQcSegmentsFromHttp;
264
+ private getHotLedgerEntryBySequence;
265
+ private findLocalCheckpointAtSequence;
266
+ private resolveEffectiveCheckpointStateRoot;
267
+ private replayCrashWindowEntry;
268
+ private reconcileTrailingOrphanRange;
269
+ /**
270
+ * Reconcile any crash window where finalized `ledger.sqlite` entries were durable ahead of `statedb.sqlite`
271
+ * (e.g., power loss between `ledger.importSegment` and `replayer.replayEntry`) before polling upstream (#1712).
272
+ */
273
+ private reconcileFollowerCrashWindowIfNeeded;
274
+ /**
275
+ * Run one deterministic synchronization pass (cold segments + hot-tail entries + checkpoint sealing).
276
+ */
277
+ syncOnce(): Promise<void>;
278
+ /**
279
+ * Execute one deterministic synchronization pass even while background polling is paused (`ChainNodeTestHooks`).
280
+ */
281
+ triggerSyncOnce(): Promise<void>;
282
+ private executeSyncPass;
283
+ /**
284
+ * Start background hot-tail synchronization loop (performs an initial sync pass before returning).
285
+ */
286
+ start(): Promise<void>;
287
+ flushWitnessTasks(): Promise<void>;
288
+ /**
289
+ * Stop background polling and wait for any in-flight replay transaction to finish cleanly.
290
+ */
291
+ close(): Promise<void>;
292
+ }
293
+ //#endregion
294
+ export { DEFAULT_FOLLOWER_HTTP_TIMEOUT_MS, DEFAULT_FOLLOWER_MAX_SYNC_LAG, DEFAULT_FOLLOWER_MAX_UPSTREAM_STALE_MS, DEFAULT_FOLLOWER_POLL_INTERVAL_MS, FollowerSyncService, FollowerSyncServiceOptions, IColdSegmentReader, ILeaderRouterLike, TFollowerUpstreamFetchInterceptor, TFollowerUpstreamFetchKind, isTransientSqliteLockError };