@ocap/chain-node 1.32.0 → 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.
@@ -0,0 +1,59 @@
1
+ import { TChainConfigCheckMode } from "./standalone-env.mjs";
2
+ import { IPipelineLogger } from "@ocap/types";
3
+
4
+ //#region src/config-consistency.d.ts
5
+ declare const CONSENSUS_CONFIG_KEYS: readonly ["chainId", "mode", "moderator.address", "token.address", "token.symbol", "token.decimal", "vaults", "reservedSymbols", "transaction"];
6
+ type Plain = Record<string, unknown>;
7
+ /** The consensus-relevant projection of a chain config, with defaults applied identically on both sides. */
8
+ declare function normalizeConsensusConfig(config: unknown): Plain;
9
+ interface ConfigDifference {
10
+ path: string;
11
+ local: unknown;
12
+ upstream: unknown;
13
+ }
14
+ /** Differences between two configs' consensus projections, by dotted path (arrays compare as a whole). */
15
+ declare function diffConsensusConfig(local: unknown, upstream: unknown): ConfigDifference[];
16
+ /** POST `{ getConfig }` to `<upstreamUrl>/api/gql` and return the parsed in-memory config of the upstream. */
17
+ declare function fetchUpstreamChainConfig(upstreamUrl: string, {
18
+ fetchImpl,
19
+ timeoutMs
20
+ }?: {
21
+ fetchImpl?: typeof fetch;
22
+ timeoutMs?: number;
23
+ }): Promise<unknown>;
24
+ declare function formatConfigDifferences(diff: ConfigDifference[]): string;
25
+ interface VerifyFollowerConfigOptions {
26
+ mode: TChainConfigCheckMode;
27
+ /** The config the follower will replay with (`resolver.config`). */
28
+ localConfig: unknown;
29
+ upstreamUrl: string | null | undefined;
30
+ /** Defaults to `fetchUpstreamChainConfig`; tests pass a stub upstream. */
31
+ fetchUpstreamConfig?: (upstreamUrl: string) => Promise<unknown>;
32
+ logger: Pick<IPipelineLogger, 'info' | 'warn'>;
33
+ /**
34
+ * The data dir already held this node's chain state before this start (not a fresh snapshot bootstrap). With
35
+ * `enforce`, an upstream that stays unavailable past the deadline is then a warning, not a refusal.
36
+ */
37
+ hasLocalState?: boolean;
38
+ /** `enforce` only: keep retrying an unavailable upstream this long (default 60 s, CHAIN_CONFIG_CHECK_TIMEOUT_SEC). */
39
+ retryDeadlineMs?: number;
40
+ /** First backoff delay (default 1 s), doubled per attempt up to `retryMaxDelayMs` (default 10 s). */
41
+ retryDelayMs?: number;
42
+ retryMaxDelayMs?: number;
43
+ now?: () => number;
44
+ sleep?: (ms: number) => Promise<void>;
45
+ }
46
+ interface VerifyFollowerConfigResult {
47
+ status: 'skipped' | 'match' | 'mismatch' | 'unavailable';
48
+ diff: ConfigDifference[];
49
+ }
50
+ /**
51
+ * Compare the follower's replay config with the upstream leader's. `off`: no request. `warn`: one attempt, log
52
+ * any difference or failure and continue. `enforce`: a definite difference throws `CHAIN_CONFIG_MISMATCH` (lists
53
+ * every differing key). An unavailable upstream (down, HTTP error such as 429, bad body) is retried with backoff
54
+ * until `retryDeadlineMs`; then a node with existing local state starts with a warning, and only a fresh bootstrap
55
+ * throws `CHAIN_CONFIG_CHECK_UNAVAILABLE`.
56
+ */
57
+ declare function verifyFollowerConfigAgainstUpstream(opts: VerifyFollowerConfigOptions): Promise<VerifyFollowerConfigResult>;
58
+ //#endregion
59
+ export { CONSENSUS_CONFIG_KEYS, ConfigDifference, VerifyFollowerConfigOptions, VerifyFollowerConfigResult, diffConsensusConfig, fetchUpstreamChainConfig, formatConfigDifferences, normalizeConsensusConfig, verifyFollowerConfigAgainstUpstream };
@@ -0,0 +1,220 @@
1
+ import { defaultGasSecurityKnobs } from "@ocap/config";
2
+ import defaultConfig from "@ocap/config/lib/default";
3
+ import { CustomError } from "@ocap/util/lib/error";
4
+
5
+ //#region src/config-consistency.ts
6
+ /**
7
+ * Follower startup consistency check (#1961): before a follower replays anything it asks the upstream leader for
8
+ * its in-memory chain config (`getConfig`, core/resolver `getConfig()` returns `JSON.stringify(this.config)`) and
9
+ * compares every consensus-relevant key, both sides normalized with the same defaults. A follower that replays with
10
+ * a different config computes different state commits (e.g. `transaction.bridge.enabled` off rejects the first
11
+ * bridge reserve entry in `bridge-reserve-v2-gate.ts`) and halts; this check turns that into a clear startup error.
12
+ *
13
+ * Consensus-relevant keys (`CONSENSUS_CONFIG_KEYS`) are what the tx pipeline / replayer reads from `context.config`:
14
+ * - `chainId` every protocol (`tx.chainId` checks), replayer entry chain id
15
+ * - `mode` `Config.create` defaults (`ledger` zeroes fees and gas)
16
+ * - `moderator.address` moderator-only protocols (token / factory / rollup governance)
17
+ * - `token.address/symbol/decimal` official token, fee and stake units, reserved base symbol
18
+ * - `vaults` where fees, gas and slashed stake go (`txFee`, `txFees`, `txGas`, `slashedStake`)
19
+ * - `reservedSymbols` `create_token_factory` verification (compared as a case-insensitive set)
20
+ * - `transaction` the whole section: `txFee`, `txGas` (+ free-gas / burst knobs), `txStake`,
21
+ * `maxTxSize`, `maxAssetSize`, `maxListSize`, `maxMultisig`, `delegate`, `supportedTxs`,
22
+ * `multiSignV2Txs`, `maxWriteSetSize`, `security`, `bridge`, `rollupV1`, `exchangeV2`
23
+ * Not compared: `version` (software), `accounts` and token metadata/supply (genesis only: a follower never re-runs
24
+ * genesis, it starts from a verified snapshot), `moderator.pk` (protocols compare the address), `genesisTime`.
25
+ */
26
+ const CONSENSUS_CONFIG_KEYS = [
27
+ "chainId",
28
+ "mode",
29
+ "moderator.address",
30
+ "token.address",
31
+ "token.symbol",
32
+ "token.decimal",
33
+ "vaults",
34
+ "reservedSymbols",
35
+ "transaction"
36
+ ];
37
+ /** Protocol fallback of `transaction.exchangeV2.defaultTtlSeconds` (core/tx-protocols exchange-v2.ts). */
38
+ const DEFAULT_EXCHANGE_V2_TTL_SECONDS = 720 * 60 * 60;
39
+ const isPlainObject = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
40
+ /** JSON round trip: drops `undefined`, functions and frozen-ness, so both sides compare as the wire would. */
41
+ function toJsonValue(value) {
42
+ if (value === void 0) return void 0;
43
+ return JSON.parse(JSON.stringify(value));
44
+ }
45
+ function getPath(obj, dotted) {
46
+ let cur = obj;
47
+ for (const seg of dotted.split(".")) {
48
+ if (!isPlainObject(cur)) return void 0;
49
+ cur = cur[seg];
50
+ }
51
+ return cur;
52
+ }
53
+ function setPath(obj, dotted, value) {
54
+ const segs = dotted.split(".");
55
+ let cur = obj;
56
+ for (const seg of segs.slice(0, -1)) {
57
+ if (!isPlainObject(cur[seg])) cur[seg] = {};
58
+ cur = cur[seg];
59
+ }
60
+ cur[segs[segs.length - 1]] = value;
61
+ }
62
+ /** Fill only keys that are absent (`undefined`); present values, records and arrays are kept as they are. */
63
+ function fillAbsent(target, defaults) {
64
+ const out = { ...target };
65
+ for (const [k, v] of Object.entries(defaults)) if (out[k] === void 0) out[k] = toJsonValue(v);
66
+ return out;
67
+ }
68
+ function normalizeTransaction(raw) {
69
+ const tx = fillAbsent(isPlainObject(raw) ? toJsonValue(raw) : {}, defaultConfig.transaction);
70
+ tx.txGas = fillAbsent(isPlainObject(tx.txGas) ? tx.txGas : {}, defaultGasSecurityKnobs.txGas);
71
+ tx.security = fillAbsent(isPlainObject(tx.security) ? tx.security : {}, defaultGasSecurityKnobs.security);
72
+ tx.bridge = { enabled: isPlainObject(tx.bridge) && tx.bridge.enabled === true };
73
+ tx.rollupV1 = { enabled: !(isPlainObject(tx.rollupV1) && tx.rollupV1.enabled === false) };
74
+ const exchangeV2 = isPlainObject(tx.exchangeV2) ? tx.exchangeV2 : {};
75
+ tx.exchangeV2 = {
76
+ ...exchangeV2,
77
+ defaultTtlSeconds: typeof exchangeV2.defaultTtlSeconds === "number" ? exchangeV2.defaultTtlSeconds : DEFAULT_EXCHANGE_V2_TTL_SECONDS
78
+ };
79
+ return tx;
80
+ }
81
+ /** The consensus-relevant projection of a chain config, with defaults applied identically on both sides. */
82
+ function normalizeConsensusConfig(config) {
83
+ const out = {};
84
+ for (const key of CONSENSUS_CONFIG_KEYS) {
85
+ const value = toJsonValue(getPath(config, key));
86
+ switch (key) {
87
+ case "mode":
88
+ setPath(out, key, value === "ledger" ? "ledger" : "chain");
89
+ break;
90
+ case "token.address":
91
+ setPath(out, key, typeof value === "string" ? value : "");
92
+ break;
93
+ case "vaults":
94
+ setPath(out, key, isPlainObject(value) ? value : {});
95
+ break;
96
+ case "reservedSymbols":
97
+ setPath(out, key, Array.from(new Set((Array.isArray(value) ? value : []).map((s) => String(s ?? "").trim().toUpperCase()).filter(Boolean))).sort());
98
+ break;
99
+ case "transaction":
100
+ setPath(out, key, normalizeTransaction(value));
101
+ break;
102
+ default: setPath(out, key, value === void 0 ? null : value);
103
+ }
104
+ }
105
+ return out;
106
+ }
107
+ function collectDiff(local, upstream, prefix, out) {
108
+ if (isPlainObject(local) && isPlainObject(upstream)) {
109
+ const keys = Array.from(new Set([...Object.keys(local), ...Object.keys(upstream)])).sort();
110
+ for (const k of keys) collectDiff(local[k], upstream[k], prefix ? `${prefix}.${k}` : k, out);
111
+ return;
112
+ }
113
+ if (JSON.stringify(local) !== JSON.stringify(upstream)) out.push({
114
+ path: prefix,
115
+ local: local === void 0 ? null : local,
116
+ upstream: upstream === void 0 ? null : upstream
117
+ });
118
+ }
119
+ /** Differences between two configs' consensus projections, by dotted path (arrays compare as a whole). */
120
+ function diffConsensusConfig(local, upstream) {
121
+ const out = [];
122
+ collectDiff(normalizeConsensusConfig(local), normalizeConsensusConfig(upstream), "", out);
123
+ return out;
124
+ }
125
+ const MAX_CONFIG_RESPONSE_BYTES = 8 * 1024 * 1024;
126
+ const GET_CONFIG_QUERY = "{ getConfig { code config } }";
127
+ /** POST `{ getConfig }` to `<upstreamUrl>/api/gql` and return the parsed in-memory config of the upstream. */
128
+ async function fetchUpstreamChainConfig(upstreamUrl, { fetchImpl = fetch, timeoutMs = 1e4 } = {}) {
129
+ const url = `${String(upstreamUrl).trim().replace(/\/+$/, "")}/api/gql`;
130
+ const res = await fetchImpl(url, {
131
+ method: "POST",
132
+ headers: {
133
+ "content-type": "application/json",
134
+ accept: "application/json"
135
+ },
136
+ body: JSON.stringify({ query: GET_CONFIG_QUERY }),
137
+ redirect: "error",
138
+ signal: AbortSignal.timeout(timeoutMs)
139
+ });
140
+ const text = await res.text();
141
+ if (!res.ok) throw new Error(`getConfig from ${url} failed: HTTP ${res.status}`);
142
+ if (text.length > MAX_CONFIG_RESPONSE_BYTES) throw new Error(`getConfig from ${url} failed: response larger than ${MAX_CONFIG_RESPONSE_BYTES} bytes`);
143
+ const body = JSON.parse(text);
144
+ if (body.errors?.length) throw new Error(`getConfig from ${url} failed: ${body.errors.map((e) => e.message).join("; ")}`);
145
+ const raw = body.data?.getConfig?.config;
146
+ if (typeof raw !== "string" || !raw) throw new Error(`getConfig from ${url} failed: no config in the response (code=${body.data?.getConfig?.code})`);
147
+ return assertUpstreamConfigShape(JSON.parse(raw), url);
148
+ }
149
+ /** A response that is not a chain config is a bad body ("unavailable"), never a definite mismatch. */
150
+ function assertUpstreamConfigShape(parsed, source) {
151
+ if (!isPlainObject(parsed)) throw new Error(`getConfig from ${source} failed: config is not an object`);
152
+ if (typeof parsed.chainId !== "string" || !parsed.chainId.trim() || !isPlainObject(parsed.transaction)) throw new Error(`getConfig from ${source} failed: config has no chainId / transaction section`);
153
+ return parsed;
154
+ }
155
+ const formatValue = (v) => {
156
+ const s = JSON.stringify(v);
157
+ return s.length > 160 ? `${s.slice(0, 157)}...` : s;
158
+ };
159
+ function formatConfigDifferences(diff) {
160
+ return diff.map((d) => `${d.path} (local=${formatValue(d.local)}, upstream=${formatValue(d.upstream)})`).join("; ");
161
+ }
162
+ /**
163
+ * Compare the follower's replay config with the upstream leader's. `off`: no request. `warn`: one attempt, log
164
+ * any difference or failure and continue. `enforce`: a definite difference throws `CHAIN_CONFIG_MISMATCH` (lists
165
+ * every differing key). An unavailable upstream (down, HTTP error such as 429, bad body) is retried with backoff
166
+ * until `retryDeadlineMs`; then a node with existing local state starts with a warning, and only a fresh bootstrap
167
+ * throws `CHAIN_CONFIG_CHECK_UNAVAILABLE`.
168
+ */
169
+ async function verifyFollowerConfigAgainstUpstream(opts) {
170
+ if (opts.mode === "off") return {
171
+ status: "skipped",
172
+ diff: []
173
+ };
174
+ const enforce = opts.mode === "enforce";
175
+ const now = opts.now ?? (() => Date.now());
176
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
177
+ const unavailable = (reason) => {
178
+ const message$1 = `Follower config check (CHAIN_CONFIG_CHECK=${opts.mode}) could not read the upstream config: ${reason}`;
179
+ if (enforce && !opts.hasLocalState) throw new CustomError("CHAIN_CONFIG_CHECK_UNAVAILABLE", `${message$1}; refusing to start a fresh bootstrap before replay`);
180
+ opts.logger.warn(`[chain-node] ${message$1}; starting without the check${enforce ? " (existing local state)" : ""}`);
181
+ return {
182
+ status: "unavailable",
183
+ diff: []
184
+ };
185
+ };
186
+ const upstreamUrl = String(opts.upstreamUrl ?? "").trim();
187
+ if (!upstreamUrl) return unavailable("no upstream URL (UPSTREAM_CHAIN_URL) is configured");
188
+ const fetchConfig = opts.fetchUpstreamConfig ?? ((u) => fetchUpstreamChainConfig(u));
189
+ const deadline = now() + Math.max(0, opts.retryDeadlineMs ?? 6e4);
190
+ const maxDelay = Math.max(0, opts.retryMaxDelayMs ?? 1e4);
191
+ let delay = Math.max(0, opts.retryDelayMs ?? 1e3);
192
+ let upstreamConfig = null;
193
+ while (upstreamConfig === null) try {
194
+ upstreamConfig = assertUpstreamConfigShape(await fetchConfig(upstreamUrl), upstreamUrl);
195
+ } catch (err) {
196
+ const reason = err instanceof Error ? err.message : String(err);
197
+ if (!enforce || now() + delay > deadline) return unavailable(reason);
198
+ opts.logger.warn(`[chain-node] follower config check: upstream unavailable (${reason}); retrying in ${delay} ms`);
199
+ await sleep(delay);
200
+ delay = Math.min(maxDelay, delay * 2);
201
+ }
202
+ const diff = diffConsensusConfig(opts.localConfig, upstreamConfig);
203
+ if (diff.length === 0) {
204
+ opts.logger.info(`[chain-node] follower consensus config matches upstream ${upstreamUrl}`);
205
+ return {
206
+ status: "match",
207
+ diff
208
+ };
209
+ }
210
+ const message = `Follower consensus config differs from upstream ${upstreamUrl} in ${diff.length} key(s): ${formatConfigDifferences(diff)}`;
211
+ if (enforce) throw new CustomError("CHAIN_CONFIG_MISMATCH", `${message}; refusing to start before replay (#1961)`);
212
+ opts.logger.warn(`[chain-node] ${message}`);
213
+ return {
214
+ status: "mismatch",
215
+ diff
216
+ };
217
+ }
218
+
219
+ //#endregion
220
+ export { CONSENSUS_CONFIG_KEYS, diffConsensusConfig, fetchUpstreamChainConfig, formatConfigDifferences, normalizeConsensusConfig, verifyFollowerConfigAgainstUpstream };
package/esm/env.mjs CHANGED
@@ -1,6 +1,6 @@
1
+ import { CustomError } from "@ocap/util/lib/error";
1
2
  import { normalizeDidForCompare, resolveConsensusProposer, resolveConsensusProposerFromSigner, resolveEnvWitnessWallet, resolveNodeRoleConfig } from "@arcblock/ledger-core";
2
3
  import { resolveLedgerLeaseConfig } from "@arcblock/ledger-sqlite";
3
- import { CustomError } from "@ocap/util/lib/error";
4
4
 
5
5
  //#region src/env.ts
6
6
  function parseOptionalPositiveInt(raw, label) {
@@ -0,0 +1,25 @@
1
+ import { IChainConfig } from "@ocap/types";
2
+
3
+ //#region src/follower-config.d.ts
4
+ declare const isPlainRecord: (v: unknown) => v is Record<string, unknown>;
5
+ /**
6
+ * A profile config is only "complete" with its `transaction` section (#1961): a follower profile that lacks it
7
+ * would otherwise replay with whatever the code defaults are (e.g. bridge off) instead of the leader's switches.
8
+ */
9
+ declare function isCompleteChainConfig(candidate: Partial<IChainConfig> | undefined): candidate is IChainConfig;
10
+ /** Deep merge of plain objects (arrays and scalars of `overlay` replace); inputs are not mutated. */
11
+ declare function mergeTransactionOverlay(base: unknown, overlay: unknown): unknown;
12
+ /**
13
+ * Keyless follower: the stored chain row (`statedb.chain`) plus the profile's `transaction` overlay. A keyless
14
+ * follower cannot rebuild the full config (no vault keys), but its profile may carry the leader's transaction
15
+ * variables from env (e.g. CHAIN_TX_BRIDGE_ENABLED): the stored row is not rewritten on a ledger-anchored leader
16
+ * restart, so it still holds the values of the last genesis/config write.
17
+ */
18
+ declare function rehydrateFollowerChainConfig(storedChain: unknown, profileChainConfig?: Partial<IChainConfig>): IChainConfig;
19
+ /**
20
+ * The config a resolver actually runs with (`OCAPResolver` constructor): validated, with `token.address` set to the
21
+ * genesis token address. This is what the leader's `getConfig` returns and what the follower's replayer reads.
22
+ */
23
+ declare function toResolverConfig(config: IChainConfig): IChainConfig;
24
+ //#endregion
25
+ export { isCompleteChainConfig, isPlainRecord, mergeTransactionOverlay, rehydrateFollowerChainConfig, toResolverConfig };
@@ -0,0 +1,57 @@
1
+ import * as Config from "@ocap/config";
2
+
3
+ //#region src/follower-config.ts
4
+ /**
5
+ * How a follower obtains the chain config it replays with (#1961). Shared by `startChainNode` and the read-only
6
+ * `scripts/ops/chain-config-diff.mjs` dry-run, so the dry-run compares exactly what the node would replay with.
7
+ */
8
+ const isPlainRecord = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
9
+ /**
10
+ * A profile config is only "complete" with its `transaction` section (#1961): a follower profile that lacks it
11
+ * would otherwise replay with whatever the code defaults are (e.g. bridge off) instead of the leader's switches.
12
+ */
13
+ function isCompleteChainConfig(candidate) {
14
+ return Boolean(candidate && typeof candidate.chainId === "string" && candidate.chainId.trim() && candidate.moderator?.address && candidate.token?.symbol && candidate.vaults?.slashedStake && isPlainRecord(candidate.transaction));
15
+ }
16
+ /** Deep merge of plain objects (arrays and scalars of `overlay` replace); inputs are not mutated. */
17
+ function mergeTransactionOverlay(base, overlay) {
18
+ if (!isPlainRecord(overlay)) return overlay === void 0 ? base : overlay;
19
+ const out = isPlainRecord(base) ? { ...base } : {};
20
+ for (const [k, v] of Object.entries(overlay)) {
21
+ if (v === void 0) continue;
22
+ out[k] = mergeTransactionOverlay(out[k], v);
23
+ }
24
+ return out;
25
+ }
26
+ /**
27
+ * Keyless follower: the stored chain row (`statedb.chain`) plus the profile's `transaction` overlay. A keyless
28
+ * follower cannot rebuild the full config (no vault keys), but its profile may carry the leader's transaction
29
+ * variables from env (e.g. CHAIN_TX_BRIDGE_ENABLED): the stored row is not rewritten on a ledger-anchored leader
30
+ * restart, so it still holds the values of the last genesis/config write.
31
+ */
32
+ function rehydrateFollowerChainConfig(storedChain, profileChainConfig) {
33
+ const storedChainPartial = storedChain;
34
+ const storedChainId = typeof storedChainPartial.chainId === "string" ? storedChainPartial.chainId.trim() : "";
35
+ const baseSymbol = storedChainPartial.token?.symbol || "TBA";
36
+ const reservedSymbols = Array.from(new Set([baseSymbol, ...storedChainPartial.reservedSymbols ?? []].map((s) => String(s || "").trim().toUpperCase()).filter(Boolean)));
37
+ const transactionOverlay = isPlainRecord(profileChainConfig?.transaction) ? profileChainConfig.transaction : void 0;
38
+ return Config.create({
39
+ ...storedChain,
40
+ ...storedChainId ? { chainId: storedChainId } : {},
41
+ ...transactionOverlay ? { transaction: mergeTransactionOverlay(storedChainPartial.transaction, transactionOverlay) } : {},
42
+ reservedSymbols
43
+ });
44
+ }
45
+ /**
46
+ * The config a resolver actually runs with (`OCAPResolver` constructor): validated, with `token.address` set to the
47
+ * genesis token address. This is what the leader's `getConfig` returns and what the follower's replayer reads.
48
+ */
49
+ function toResolverConfig(config) {
50
+ const validated = Config.validate(JSON.parse(JSON.stringify(config)));
51
+ const tokenItx = Config.genTokenItx(validated);
52
+ if (tokenItx) validated.token.address = tokenItx.address;
53
+ return validated;
54
+ }
55
+
56
+ //#endregion
57
+ export { isCompleteChainConfig, isPlainRecord, mergeTransactionOverlay, rehydrateFollowerChainConfig, toResolverConfig };
package/esm/index.d.mts CHANGED
@@ -1,5 +1,7 @@
1
+ import { BLOCKLET_ENV_CHAIN_FALLBACKS, BlockletEnvLeftovers, DEFAULT_CONFIG_CHECK_TIMEOUT_SECONDS, DEFAULT_FUTURE_TIMESTAMP_SKEW_SECONDS, FutureTimestampGuardConfig, STANDALONE_ENV_MARKERS, TChainConfigCheckMode, TRANSACTION_SWITCH_ENV, TransactionSwitches, findBlockletEnvLeftovers, formatBlockletEnvLeftoversWarning, parseNonNegativeNumberEnv, resolveConfigCheckModeFromEnv, resolveConfigCheckTimeoutMsFromEnv, resolveFutureTimestampGuardFromEnv, resolveTransactionSwitchesFromEnv, resolveTrustedSubject } from "./standalone-env.mjs";
2
+ import { CONSENSUS_CONFIG_KEYS, ConfigDifference, VerifyFollowerConfigOptions, VerifyFollowerConfigResult, diffConsensusConfig, fetchUpstreamChainConfig, formatConfigDifferences, normalizeConsensusConfig, verifyFollowerConfigAgainstUpstream } from "./config-consistency.mjs";
1
3
  import { ChainAppHookContext, ChainNodeHandle, ChainNodeProfile, ChainNodeRoleConfig, ChainNodeSegmentPublisher, ChainNodeSignerConfig, ChainNodeTestHooks, ChainNodeTestHooksInput, ChainProfile, ChainProfileBase, FollowerRoleConfig, FollowerSyncTestController, FollowerUpstreamInterceptorContext, HotStuffValidatorRoleConfig, ILedgerHealthStatus, ILedgerLeaseOptions, PublicKeyOnlyValidatorSignerConfig, RunningChainNode, StartChainNodeOptions, TNodeRetentionMode, TrustedAccountConfig, ValidatorRoleConfig, ValidatorSignerConfig } from "./types.mjs";
2
4
  import { InstallProcessSignalHandlersOptions, installProcessSignalHandlers, leaseConfigFromEnv, roleConfigFromEnv } from "./env.mjs";
5
+ import { isCompleteChainConfig, rehydrateFollowerChainConfig, toResolverConfig } from "./follower-config.mjs";
3
6
  import { startChainNode } from "./start-chain-node.mjs";
4
- import { BLOCKLET_ENV_CHAIN_FALLBACKS, BlockletEnvLeftovers, STANDALONE_ENV_MARKERS, findBlockletEnvLeftovers, formatBlockletEnvLeftoversWarning, resolveTrustedSubject } from "./standalone-env.mjs";
5
- export { BLOCKLET_ENV_CHAIN_FALLBACKS, type BlockletEnvLeftovers, type ChainAppHookContext, type ChainNodeHandle, type ChainNodeProfile, type ChainNodeRoleConfig, type ChainNodeSegmentPublisher, type ChainNodeSignerConfig, type ChainNodeTestHooks, type ChainNodeTestHooksInput, type ChainProfile, type ChainProfileBase, type FollowerRoleConfig, type FollowerSyncTestController, type FollowerUpstreamInterceptorContext, type HotStuffValidatorRoleConfig, type ILedgerHealthStatus, type ILedgerLeaseOptions, type InstallProcessSignalHandlersOptions, type PublicKeyOnlyValidatorSignerConfig, type RunningChainNode, STANDALONE_ENV_MARKERS, type StartChainNodeOptions, type TNodeRetentionMode, type TrustedAccountConfig, type ValidatorRoleConfig, type ValidatorSignerConfig, findBlockletEnvLeftovers, formatBlockletEnvLeftoversWarning, installProcessSignalHandlers, leaseConfigFromEnv, resolveTrustedSubject, roleConfigFromEnv, startChainNode };
7
+ export { BLOCKLET_ENV_CHAIN_FALLBACKS, type BlockletEnvLeftovers, CONSENSUS_CONFIG_KEYS, type ChainAppHookContext, type ChainNodeHandle, type ChainNodeProfile, type ChainNodeRoleConfig, type ChainNodeSegmentPublisher, type ChainNodeSignerConfig, type ChainNodeTestHooks, type ChainNodeTestHooksInput, type ChainProfile, type ChainProfileBase, type ConfigDifference, DEFAULT_CONFIG_CHECK_TIMEOUT_SECONDS, DEFAULT_FUTURE_TIMESTAMP_SKEW_SECONDS, type FollowerRoleConfig, type FollowerSyncTestController, type FollowerUpstreamInterceptorContext, type FutureTimestampGuardConfig, type HotStuffValidatorRoleConfig, type ILedgerHealthStatus, type ILedgerLeaseOptions, type InstallProcessSignalHandlersOptions, type PublicKeyOnlyValidatorSignerConfig, type RunningChainNode, STANDALONE_ENV_MARKERS, type StartChainNodeOptions, type TChainConfigCheckMode, type TNodeRetentionMode, TRANSACTION_SWITCH_ENV, type TransactionSwitches, type TrustedAccountConfig, type ValidatorRoleConfig, type ValidatorSignerConfig, type VerifyFollowerConfigOptions, type VerifyFollowerConfigResult, diffConsensusConfig, fetchUpstreamChainConfig, findBlockletEnvLeftovers, formatBlockletEnvLeftoversWarning, formatConfigDifferences, installProcessSignalHandlers, isCompleteChainConfig, leaseConfigFromEnv, normalizeConsensusConfig, parseNonNegativeNumberEnv, rehydrateFollowerChainConfig, resolveConfigCheckModeFromEnv, resolveConfigCheckTimeoutMsFromEnv, resolveFutureTimestampGuardFromEnv, resolveTransactionSwitchesFromEnv, resolveTrustedSubject, roleConfigFromEnv, startChainNode, toResolverConfig, verifyFollowerConfigAgainstUpstream };
package/esm/index.mjs CHANGED
@@ -1,5 +1,7 @@
1
+ import { CONSENSUS_CONFIG_KEYS, diffConsensusConfig, fetchUpstreamChainConfig, formatConfigDifferences, normalizeConsensusConfig, verifyFollowerConfigAgainstUpstream } from "./config-consistency.mjs";
1
2
  import { installProcessSignalHandlers, leaseConfigFromEnv, roleConfigFromEnv } from "./env.mjs";
3
+ import { isCompleteChainConfig, rehydrateFollowerChainConfig, toResolverConfig } from "./follower-config.mjs";
2
4
  import { startChainNode } from "./start-chain-node.mjs";
3
- import { BLOCKLET_ENV_CHAIN_FALLBACKS, STANDALONE_ENV_MARKERS, findBlockletEnvLeftovers, formatBlockletEnvLeftoversWarning, resolveTrustedSubject } from "./standalone-env.mjs";
5
+ import { BLOCKLET_ENV_CHAIN_FALLBACKS, DEFAULT_CONFIG_CHECK_TIMEOUT_SECONDS, DEFAULT_FUTURE_TIMESTAMP_SKEW_SECONDS, STANDALONE_ENV_MARKERS, TRANSACTION_SWITCH_ENV, findBlockletEnvLeftovers, formatBlockletEnvLeftoversWarning, parseNonNegativeNumberEnv, resolveConfigCheckModeFromEnv, resolveConfigCheckTimeoutMsFromEnv, resolveFutureTimestampGuardFromEnv, resolveTransactionSwitchesFromEnv, resolveTrustedSubject } from "./standalone-env.mjs";
4
6
 
5
- export { BLOCKLET_ENV_CHAIN_FALLBACKS, STANDALONE_ENV_MARKERS, findBlockletEnvLeftovers, formatBlockletEnvLeftoversWarning, installProcessSignalHandlers, leaseConfigFromEnv, resolveTrustedSubject, roleConfigFromEnv, startChainNode };
7
+ export { BLOCKLET_ENV_CHAIN_FALLBACKS, CONSENSUS_CONFIG_KEYS, DEFAULT_CONFIG_CHECK_TIMEOUT_SECONDS, DEFAULT_FUTURE_TIMESTAMP_SKEW_SECONDS, STANDALONE_ENV_MARKERS, TRANSACTION_SWITCH_ENV, diffConsensusConfig, fetchUpstreamChainConfig, findBlockletEnvLeftovers, formatBlockletEnvLeftoversWarning, formatConfigDifferences, installProcessSignalHandlers, isCompleteChainConfig, leaseConfigFromEnv, normalizeConsensusConfig, parseNonNegativeNumberEnv, rehydrateFollowerChainConfig, resolveConfigCheckModeFromEnv, resolveConfigCheckTimeoutMsFromEnv, resolveFutureTimestampGuardFromEnv, resolveTransactionSwitchesFromEnv, resolveTrustedSubject, roleConfigFromEnv, startChainNode, toResolverConfig, verifyFollowerConfigAgainstUpstream };
@@ -35,5 +35,58 @@ declare function formatBlockletEnvLeftoversWarning({
35
35
  leftovers,
36
36
  readByChain
37
37
  }: BlockletEnvLeftovers): string;
38
+ /** Env names of the `transaction.*` master switches a chain app maps into its chain config. */
39
+ declare const TRANSACTION_SWITCH_ENV: {
40
+ readonly bridge: "CHAIN_TX_BRIDGE_ENABLED";
41
+ readonly rollupV1: "CHAIN_TX_ROLLUP_V1_ENABLED";
42
+ };
43
+ interface TransactionSwitches {
44
+ bridge?: {
45
+ enabled: boolean;
46
+ };
47
+ rollupV1?: {
48
+ enabled: boolean;
49
+ };
50
+ }
51
+ /**
52
+ * `transaction.bridge` / `transaction.rollupV1` from env. Only explicitly set switches are returned, so an env
53
+ * without them leaves the chain config exactly as before (bridge absent = disabled, rollupV1 absent = enabled).
54
+ */
55
+ declare function resolveTransactionSwitchesFromEnv(env?: Env): TransactionSwitches;
56
+ type TChainConfigCheckMode = 'off' | 'warn' | 'enforce';
57
+ /**
58
+ * `CHAIN_CONFIG_CHECK`: what a follower does with the startup comparison of its consensus config against the
59
+ * upstream leader's `getConfig` (`off` default: no request at all; `warn`: log differences and start; `enforce`:
60
+ * refuse to start on any difference or when the upstream cannot be asked).
61
+ */
62
+ declare function resolveConfigCheckModeFromEnv(env?: Env): TChainConfigCheckMode;
63
+ declare const DEFAULT_CONFIG_CHECK_TIMEOUT_SECONDS = 60;
64
+ /**
65
+ * `CHAIN_CONFIG_CHECK_TIMEOUT_SEC` (non-negative integer seconds, default 60): how long `enforce` keeps retrying an
66
+ * unreachable / bad upstream before it decides (start with a warning on existing local state, refuse when fresh).
67
+ */
68
+ declare function resolveConfigCheckTimeoutMsFromEnv(env?: Env): number;
69
+ /**
70
+ * A fee / gas env value (`CHAIN_GAS_PRICE`, `CREATE_*_TX_FEE`), parsed identically on leader and follower:
71
+ * unset or empty -> undefined (the caller's default / no overlay); otherwise a plain non-negative decimal
72
+ * (`integer`: digits only). Whitespace, NaN, negatives, exponents and hex fail startup instead of becoming `0`.
73
+ */
74
+ declare function parseNonNegativeNumberEnv(env: Env, name: string, {
75
+ integer
76
+ }?: {
77
+ integer?: boolean;
78
+ }): number | undefined;
79
+ /** Default clock skew a replayed entry's timestamp may be ahead of the local clock (#1961; #1965 owns the value). */
80
+ declare const DEFAULT_FUTURE_TIMESTAMP_SKEW_SECONDS = 300;
81
+ interface FutureTimestampGuardConfig {
82
+ /** Entries with `sequence >= activationSequence` are checked; earlier history is always accepted. */
83
+ activationSequence: number;
84
+ maxSkewMs: number;
85
+ }
86
+ /**
87
+ * `LEDGER_FUTURE_TIMESTAMP_FROM_SEQ` (positive integer; unset = guard disabled, today's behavior) and
88
+ * `LEDGER_FUTURE_TIMESTAMP_SKEW_SEC` (non-negative integer seconds, default 300; ignored while the guard is off).
89
+ */
90
+ declare function resolveFutureTimestampGuardFromEnv(env?: Env): FutureTimestampGuardConfig | undefined;
38
91
  //#endregion
39
- export { BLOCKLET_ENV_CHAIN_FALLBACKS, BlockletEnvLeftovers, STANDALONE_ENV_MARKERS, findBlockletEnvLeftovers, formatBlockletEnvLeftoversWarning, resolveTrustedSubject };
92
+ export { BLOCKLET_ENV_CHAIN_FALLBACKS, BlockletEnvLeftovers, DEFAULT_CONFIG_CHECK_TIMEOUT_SECONDS, DEFAULT_FUTURE_TIMESTAMP_SKEW_SECONDS, FutureTimestampGuardConfig, STANDALONE_ENV_MARKERS, TChainConfigCheckMode, TRANSACTION_SWITCH_ENV, TransactionSwitches, findBlockletEnvLeftovers, formatBlockletEnvLeftoversWarning, parseNonNegativeNumberEnv, resolveConfigCheckModeFromEnv, resolveConfigCheckTimeoutMsFromEnv, resolveFutureTimestampGuardFromEnv, resolveTransactionSwitchesFromEnv, resolveTrustedSubject };
@@ -66,6 +66,87 @@ function formatBlockletEnvLeftoversWarning({ standaloneMarkers, leftovers, readB
66
66
  const read = readByChain.length ? ` ${readByChain.join(", ")} still feed key/path fallbacks when the CHAIN_* equivalent is unset.` : "";
67
67
  return `[chain] standalone env (${standaloneMarkers.join(", ")}) also carries Blocklet Server variables: ${leftovers.join(", ")}.${read} Remove them so CHAIN_* is the only source (docs/ops/chain-env-mapping.md, #1923)`;
68
68
  }
69
+ /** Env names of the `transaction.*` master switches a chain app maps into its chain config. */
70
+ const TRANSACTION_SWITCH_ENV = {
71
+ bridge: "CHAIN_TX_BRIDGE_ENABLED",
72
+ rollupV1: "CHAIN_TX_ROLLUP_V1_ENABLED"
73
+ };
74
+ /** `1`/`true` -> true, `0`/`false` -> false, unset/blank -> undefined; anything else fails startup. */
75
+ function parseStrictBoolEnv(env, name) {
76
+ const raw = String(env[name] ?? "").trim().toLowerCase();
77
+ if (!raw) return void 0;
78
+ if (raw === "1" || raw === "true") return true;
79
+ if (raw === "0" || raw === "false") return false;
80
+ throw new Error(`Invalid ${name}="${env[name]}": expected 1/true or 0/false (or leave it empty for the default)`);
81
+ }
82
+ /**
83
+ * `transaction.bridge` / `transaction.rollupV1` from env. Only explicitly set switches are returned, so an env
84
+ * without them leaves the chain config exactly as before (bridge absent = disabled, rollupV1 absent = enabled).
85
+ */
86
+ function resolveTransactionSwitchesFromEnv(env = process.env) {
87
+ const out = {};
88
+ const bridge = parseStrictBoolEnv(env, TRANSACTION_SWITCH_ENV.bridge);
89
+ if (bridge !== void 0) out.bridge = { enabled: bridge };
90
+ const rollupV1 = parseStrictBoolEnv(env, TRANSACTION_SWITCH_ENV.rollupV1);
91
+ if (rollupV1 !== void 0) out.rollupV1 = { enabled: rollupV1 };
92
+ return out;
93
+ }
94
+ /**
95
+ * `CHAIN_CONFIG_CHECK`: what a follower does with the startup comparison of its consensus config against the
96
+ * upstream leader's `getConfig` (`off` default: no request at all; `warn`: log differences and start; `enforce`:
97
+ * refuse to start on any difference or when the upstream cannot be asked).
98
+ */
99
+ function resolveConfigCheckModeFromEnv(env = process.env) {
100
+ const raw = String(env.CHAIN_CONFIG_CHECK ?? "").trim().toLowerCase();
101
+ if (!raw) return "off";
102
+ if (raw === "off" || raw === "warn" || raw === "enforce") return raw;
103
+ throw new Error(`Invalid CHAIN_CONFIG_CHECK="${env.CHAIN_CONFIG_CHECK}": expected off, warn or enforce`);
104
+ }
105
+ const DEFAULT_CONFIG_CHECK_TIMEOUT_SECONDS = 60;
106
+ /**
107
+ * `CHAIN_CONFIG_CHECK_TIMEOUT_SEC` (non-negative integer seconds, default 60): how long `enforce` keeps retrying an
108
+ * unreachable / bad upstream before it decides (start with a warning on existing local state, refuse when fresh).
109
+ */
110
+ function resolveConfigCheckTimeoutMsFromEnv(env = process.env) {
111
+ const raw = env.CHAIN_CONFIG_CHECK_TIMEOUT_SEC;
112
+ if (raw === void 0 || raw === "") return DEFAULT_CONFIG_CHECK_TIMEOUT_SECONDS * 1e3;
113
+ if (!/^(?:0|[1-9]\d*)$/.test(raw) || !Number.isSafeInteger(Number(raw) * 1e3)) throw new Error(`Invalid CHAIN_CONFIG_CHECK_TIMEOUT_SEC="${raw}": expected a non-negative integer (seconds)`);
114
+ return Number(raw) * 1e3;
115
+ }
116
+ /**
117
+ * A fee / gas env value (`CHAIN_GAS_PRICE`, `CREATE_*_TX_FEE`), parsed identically on leader and follower:
118
+ * unset or empty -> undefined (the caller's default / no overlay); otherwise a plain non-negative decimal
119
+ * (`integer`: digits only). Whitespace, NaN, negatives, exponents and hex fail startup instead of becoming `0`.
120
+ */
121
+ function parseNonNegativeNumberEnv(env, name, { integer = false } = {}) {
122
+ const raw = env[name];
123
+ if (raw === void 0 || raw === "") return void 0;
124
+ const re = integer ? /^(?:0|[1-9]\d*)$/ : /^(?:0|[1-9]\d*)(?:\.\d+)?$/;
125
+ const value = Number(raw);
126
+ if (!re.test(raw) || !Number.isFinite(value) || integer && !Number.isSafeInteger(value)) throw new Error(`Invalid ${name}="${raw}": expected a non-negative ${integer ? "integer" : "number"} (or leave it empty)`);
127
+ return value;
128
+ }
129
+ /** Default clock skew a replayed entry's timestamp may be ahead of the local clock (#1961; #1965 owns the value). */
130
+ const DEFAULT_FUTURE_TIMESTAMP_SKEW_SECONDS = 300;
131
+ /**
132
+ * `LEDGER_FUTURE_TIMESTAMP_FROM_SEQ` (positive integer; unset = guard disabled, today's behavior) and
133
+ * `LEDGER_FUTURE_TIMESTAMP_SKEW_SEC` (non-negative integer seconds, default 300; ignored while the guard is off).
134
+ */
135
+ function resolveFutureTimestampGuardFromEnv(env = process.env) {
136
+ const rawSeq = String(env.LEDGER_FUTURE_TIMESTAMP_FROM_SEQ ?? "").trim();
137
+ if (!rawSeq) return void 0;
138
+ if (!/^[1-9]\d*$/.test(rawSeq) || !Number.isSafeInteger(Number(rawSeq))) throw new Error(`Invalid LEDGER_FUTURE_TIMESTAMP_FROM_SEQ="${env.LEDGER_FUTURE_TIMESTAMP_FROM_SEQ}": expected a positive integer`);
139
+ const rawSkew = String(env.LEDGER_FUTURE_TIMESTAMP_SKEW_SEC ?? "").trim();
140
+ let skewSeconds = DEFAULT_FUTURE_TIMESTAMP_SKEW_SECONDS;
141
+ if (rawSkew) {
142
+ if (!/^(?:0|[1-9]\d*)$/.test(rawSkew) || !Number.isSafeInteger(Number(rawSkew) * 1e3)) throw new Error(`Invalid LEDGER_FUTURE_TIMESTAMP_SKEW_SEC="${env.LEDGER_FUTURE_TIMESTAMP_SKEW_SEC}": expected a non-negative integer`);
143
+ skewSeconds = Number(rawSkew);
144
+ }
145
+ return {
146
+ activationSequence: Number(rawSeq),
147
+ maxSkewMs: skewSeconds * 1e3
148
+ };
149
+ }
69
150
 
70
151
  //#endregion
71
- export { BLOCKLET_ENV_CHAIN_FALLBACKS, STANDALONE_ENV_MARKERS, findBlockletEnvLeftovers, formatBlockletEnvLeftoversWarning, resolveTrustedSubject };
152
+ export { BLOCKLET_ENV_CHAIN_FALLBACKS, DEFAULT_CONFIG_CHECK_TIMEOUT_SECONDS, DEFAULT_FUTURE_TIMESTAMP_SKEW_SECONDS, STANDALONE_ENV_MARKERS, TRANSACTION_SWITCH_ENV, findBlockletEnvLeftovers, formatBlockletEnvLeftoversWarning, parseNonNegativeNumberEnv, resolveConfigCheckModeFromEnv, resolveConfigCheckTimeoutMsFromEnv, resolveFutureTimestampGuardFromEnv, resolveTransactionSwitchesFromEnv, resolveTrustedSubject };
@@ -1,13 +1,14 @@
1
1
  import { createAccessLogMiddleware } from "./access-log.mjs";
2
+ import { verifyFollowerConfigAgainstUpstream } from "./config-consistency.mjs";
3
+ import { isCompleteChainConfig, rehydrateFollowerChainConfig } from "./follower-config.mjs";
2
4
  import { assertValidChainNodeTestHooks } from "./test-hooks-token.mjs";
5
+ import { CustomError } from "@ocap/util/lib/error";
3
6
  import { LeaderRouter, Ledger, bytesToHex, canonicalizeMultiCurvePublicKey, createCheckpointSigner, createEnvAnchorPublisher, createEnvColdArchiveReader, createEnvSegmentPublisher, createEnvWitnessRegistry, decodeMultiCurvePublicKey, normalizeDidForCompare, resolveConsensusProposerFromSigner, toHotStuffClusterConfig, verifyDidMatchesMultiCurvePublicKey } from "@arcblock/ledger-core";
4
7
  import { SqliteHotStuffStateStore, SqliteLedgerStorage, formatLocalProcessHolderId, hasExistingFollowerDatabases, persistFollowerHighWaterMark, prepareFollowerDataDirectory, readFollowerTrustedSecretKeyIfPresent, unlinkFollowerTrustedSecretKeyIfPresent } from "@arcblock/ledger-sqlite";
5
- import { CustomError } from "@ocap/util/lib/error";
6
8
  import crypto from "node:crypto";
7
9
  import fs from "node:fs";
8
10
  import path from "node:path";
9
11
  import { isValid } from "@arcblock/did";
10
- import * as Config from "@ocap/config";
11
12
  import { createHttpHandler, createSocketHandler } from "@ocap/gql";
12
13
  import SqliteIndexDB from "@ocap/indexdb-sqlite";
13
14
  import OCAPResolver, { FollowerSyncService, HotStuffNodeRuntime, NodePreferencesManager, applyBootRuntimePreferences, createAdminAuthGuard, createExplorerMiddleware, createFollowerPeerFetchGuard, createNodeDashboardRouter, createNodeMaintenanceController, createUnifiedConsoleMiddleware, isDashboardEnabled, isExplorerEnabled } from "@ocap/resolver";
@@ -148,9 +149,6 @@ function adaptColdReaderToArchiveStore(reader) {
148
149
  ...typeof reader.getLatestHead === "function" ? { getLatestHead: reader.getLatestHead.bind(reader) } : {}
149
150
  };
150
151
  }
151
- function isCompleteChainConfig(candidate) {
152
- return Boolean(candidate && typeof candidate.chainId === "string" && candidate.chainId.trim() && candidate.moderator?.address && candidate.token?.symbol && candidate.vaults?.slashedStake);
153
- }
154
152
  function formatHttpHostForUrl(bindHost) {
155
153
  const trimmed = bindHost.trim();
156
154
  if (!trimmed || trimmed === "0.0.0.0" || trimmed === "::" || trimmed === "[::]") return "127.0.0.1";
@@ -343,13 +341,7 @@ async function bootChainNodeOnce(params) {
343
341
  const storedChainId = typeof storedChainPartial.chainId === "string" ? storedChainPartial.chainId.trim() : "";
344
342
  const overrideChainId = typeof profile.chainConfig?.chainId === "string" ? profile.chainConfig.chainId.trim() : "";
345
343
  if (storedChainId && overrideChainId && overrideChainId !== storedChainId) throw new CustomError("SNAPSHOT_CHAIN_ID_MISMATCH", `Follower profile.chainConfig.chainId (${overrideChainId}) !== statedb chain.chainId (${storedChainId})`);
346
- const baseSymbol = storedChainPartial.token?.symbol || "TBA";
347
- const reservedSymbols = Array.from(new Set([baseSymbol, ...storedChainPartial.reservedSymbols ?? []].map((s) => String(s || "").trim().toUpperCase()).filter(Boolean)));
348
- chainConfig = Config.create({
349
- ...storedChain,
350
- ...storedChainId ? { chainId: storedChainId } : {},
351
- reservedSymbols
352
- });
344
+ chainConfig = rehydrateFollowerChainConfig(storedChain, profile.chainConfig);
353
345
  } else {
354
346
  const baseConfig = profile.chainConfig;
355
347
  if (role.kind === "follower") {
@@ -594,6 +586,15 @@ async function bootChainNodeOnce(params) {
594
586
  const initialPrefs = preferencesManager.getSnapshot();
595
587
  if (initialPrefs.runtime.txMaxRequest !== void 0) resolver.setMaxTxRequest(initialPrefs.runtime.txMaxRequest);
596
588
  await resolver.initialize();
589
+ if (role.kind === "follower") await verifyFollowerConfigAgainstUpstream({
590
+ mode: profile.configCheck?.mode ?? "off",
591
+ localConfig: resolver.config,
592
+ upstreamUrl: role.upstreamChainUrl ?? role.clusterPeerUrls?.[0] ?? null,
593
+ fetchUpstreamConfig: profile.configCheck?.fetchUpstreamConfig,
594
+ hasLocalState: !followerPrep?.bootstrapped && await ledger.getLatestSequence() > 0,
595
+ ...profile.configCheck?.retryDeadlineMs !== void 0 ? { retryDeadlineMs: profile.configCheck.retryDeadlineMs } : {},
596
+ logger
597
+ });
597
598
  let followerSync;
598
599
  let hotstuffRuntime;
599
600
  if (role.kind === "follower") {
@@ -635,6 +636,10 @@ async function bootChainNodeOnce(params) {
635
636
  startPaused: testHooks?.followerSync?.startPaused,
636
637
  artificialPollDelayMs: testHooks?.followerSync?.artificialPollDelayMs,
637
638
  interceptUpstreamFetch: testHooks?.followerSync?.interceptUpstreamFetch,
639
+ ...profile.replayGuards?.futureTimestamp ? { futureTimestampGuard: {
640
+ ...profile.replayGuards.futureTimestamp,
641
+ now: clockNow
642
+ } } : {},
638
643
  env: { ALLOW_PRIVATE_PEER_URLS: role.allowPrivatePeers ? "1" : "0" }
639
644
  });
640
645
  resolver.setNodeRuntime(followerSync);