@ocap/chain-node 1.32.0 → 1.32.2

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.cjs";
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 };
package/lib/env.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ let _ocap_util_lib_error = require("@ocap/util/lib/error");
2
3
  let _arcblock_ledger_core = require("@arcblock/ledger-core");
3
4
  let _arcblock_ledger_sqlite = require("@arcblock/ledger-sqlite");
4
- let _ocap_util_lib_error = require("@ocap/util/lib/error");
5
5
 
6
6
  //#region src/env.ts
7
7
  function parseOptionalPositiveInt(raw, label) {
@@ -0,0 +1,90 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ let _ocap_config = require("@ocap/config");
3
+ _ocap_config = require_rolldown_runtime.__toESM(_ocap_config);
4
+
5
+ //#region src/follower-config.ts
6
+ /**
7
+ * How a follower obtains the chain config it replays with (#1961). Shared by `startChainNode` and the read-only
8
+ * `scripts/ops/chain-config-diff.mjs` dry-run, so the dry-run compares exactly what the node would replay with.
9
+ */
10
+ const isPlainRecord = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
11
+ /**
12
+ * A profile config is only "complete" with its `transaction` section (#1961): a follower profile that lacks it
13
+ * would otherwise replay with whatever the code defaults are (e.g. bridge off) instead of the leader's switches.
14
+ */
15
+ function isCompleteChainConfig(candidate) {
16
+ return Boolean(candidate && typeof candidate.chainId === "string" && candidate.chainId.trim() && candidate.moderator?.address && candidate.token?.symbol && candidate.vaults?.slashedStake && isPlainRecord(candidate.transaction));
17
+ }
18
+ /** Deep merge of plain objects (arrays and scalars of `overlay` replace); inputs are not mutated. */
19
+ function mergeTransactionOverlay(base, overlay) {
20
+ if (!isPlainRecord(overlay)) return overlay === void 0 ? base : overlay;
21
+ const out = isPlainRecord(base) ? { ...base } : {};
22
+ for (const [k, v] of Object.entries(overlay)) {
23
+ if (v === void 0) continue;
24
+ out[k] = mergeTransactionOverlay(out[k], v);
25
+ }
26
+ return out;
27
+ }
28
+ /**
29
+ * Keyless follower: the stored chain row (`statedb.chain`) plus the profile's `transaction` overlay. A keyless
30
+ * follower cannot rebuild the full config (no vault keys), but its profile may carry the leader's transaction
31
+ * variables from env (e.g. CHAIN_TX_BRIDGE_ENABLED): the stored row is not rewritten on a ledger-anchored leader
32
+ * restart, so it still holds the values of the last genesis/config write.
33
+ */
34
+ function rehydrateFollowerChainConfig(storedChain, profileChainConfig, extraReservedSymbols) {
35
+ const storedChainPartial = storedChain;
36
+ const storedChainId = typeof storedChainPartial.chainId === "string" ? storedChainPartial.chainId.trim() : "";
37
+ const baseSymbol = storedChainPartial.token?.symbol || "TBA";
38
+ const reservedSymbols = Array.from(new Set([
39
+ baseSymbol,
40
+ ...storedChainPartial.reservedSymbols ?? [],
41
+ ...profileChainConfig?.reservedSymbols ?? [],
42
+ ...extraReservedSymbols ?? []
43
+ ].map((s) => String(s || "").trim().toUpperCase()).filter(Boolean)));
44
+ const transactionOverlay = isPlainRecord(profileChainConfig?.transaction) ? profileChainConfig.transaction : void 0;
45
+ const storedTransaction = isPlainRecord(storedChainPartial.transaction) ? { ...storedChainPartial.transaction } : storedChainPartial.transaction;
46
+ if (isPlainRecord(storedTransaction)) delete storedTransaction.maxTxSize;
47
+ const transaction = transactionOverlay ? mergeTransactionOverlay(storedTransaction, transactionOverlay) : storedTransaction;
48
+ return _ocap_config.create({
49
+ ...storedChain,
50
+ ...storedChainId ? { chainId: storedChainId } : {},
51
+ ...transaction !== void 0 ? { transaction } : {},
52
+ reservedSymbols
53
+ });
54
+ }
55
+ /**
56
+ * The config a resolver actually runs with (`OCAPResolver` constructor): validated, with `token.address` set to the
57
+ * genesis token address. This is what the leader's `getConfig` returns and what the follower's replayer reads.
58
+ */
59
+ function toResolverConfig(config) {
60
+ const validated = _ocap_config.validate(JSON.parse(JSON.stringify(config)));
61
+ const tokenItx = _ocap_config.genTokenItx(validated);
62
+ if (tokenItx) validated.token.address = tokenItx.address;
63
+ return validated;
64
+ }
65
+ /**
66
+ * First ledger sequence whose orphan entries (finalized, no stateCommitHash, no statedb tx row) the chain's leader
67
+ * indexed. Leaders index the orphans they produce since 1.31.1 (#1387); before that they never did, and a follower
68
+ * index must hold exactly what the leader's holds (#1875). Values read from the leaders' indexdb: the first orphan
69
+ * with an index row, every earlier one without (beta: last unindexed 437972; main: last unindexed 832519). A chain
70
+ * started on 1.31.1+ indexed all of them.
71
+ */
72
+ const ORPHAN_INDEX_FROM_SEQUENCE = Object.freeze({
73
+ beta: 437983,
74
+ "xenon-2020-01-15": 832598
75
+ });
76
+ function orphanIndexFromSequence(chainId, override) {
77
+ if (override !== void 0) {
78
+ if (!Number.isSafeInteger(override) || override < 1) throw new Error(`orphanIndexFromSequence must be a positive integer, got ${String(override)}`);
79
+ return override;
80
+ }
81
+ return Object.hasOwn(ORPHAN_INDEX_FROM_SEQUENCE, chainId) ? ORPHAN_INDEX_FROM_SEQUENCE[chainId] : 1;
82
+ }
83
+
84
+ //#endregion
85
+ exports.isCompleteChainConfig = isCompleteChainConfig;
86
+ exports.isPlainRecord = isPlainRecord;
87
+ exports.mergeTransactionOverlay = mergeTransactionOverlay;
88
+ exports.orphanIndexFromSequence = orphanIndexFromSequence;
89
+ exports.rehydrateFollowerChainConfig = rehydrateFollowerChainConfig;
90
+ exports.toResolverConfig = toResolverConfig;
@@ -0,0 +1,26 @@
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>, extraReservedSymbols?: readonly string[]): 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
+ declare function orphanIndexFromSequence(chainId: string, override?: number): number;
25
+ //#endregion
26
+ export { isCompleteChainConfig, isPlainRecord, mergeTransactionOverlay, orphanIndexFromSequence, rehydrateFollowerChainConfig, toResolverConfig };
package/lib/index.cjs CHANGED
@@ -1,13 +1,32 @@
1
+ const require_config_consistency = require('./config-consistency.cjs');
1
2
  const require_env = require('./env.cjs');
3
+ const require_follower_config = require('./follower-config.cjs');
2
4
  const require_start_chain_node = require('./start-chain-node.cjs');
3
5
  const require_standalone_env = require('./standalone-env.cjs');
4
6
 
5
7
  exports.BLOCKLET_ENV_CHAIN_FALLBACKS = require_standalone_env.BLOCKLET_ENV_CHAIN_FALLBACKS;
8
+ exports.CONSENSUS_CONFIG_KEYS = require_config_consistency.CONSENSUS_CONFIG_KEYS;
9
+ exports.DEFAULT_CONFIG_CHECK_TIMEOUT_SECONDS = require_standalone_env.DEFAULT_CONFIG_CHECK_TIMEOUT_SECONDS;
10
+ exports.DEFAULT_FUTURE_TIMESTAMP_SKEW_SECONDS = require_standalone_env.DEFAULT_FUTURE_TIMESTAMP_SKEW_SECONDS;
6
11
  exports.STANDALONE_ENV_MARKERS = require_standalone_env.STANDALONE_ENV_MARKERS;
12
+ exports.TRANSACTION_SWITCH_ENV = require_standalone_env.TRANSACTION_SWITCH_ENV;
13
+ exports.diffConsensusConfig = require_config_consistency.diffConsensusConfig;
14
+ exports.fetchUpstreamChainConfig = require_config_consistency.fetchUpstreamChainConfig;
7
15
  exports.findBlockletEnvLeftovers = require_standalone_env.findBlockletEnvLeftovers;
8
16
  exports.formatBlockletEnvLeftoversWarning = require_standalone_env.formatBlockletEnvLeftoversWarning;
17
+ exports.formatConfigDifferences = require_config_consistency.formatConfigDifferences;
9
18
  exports.installProcessSignalHandlers = require_env.installProcessSignalHandlers;
19
+ exports.isCompleteChainConfig = require_follower_config.isCompleteChainConfig;
10
20
  exports.leaseConfigFromEnv = require_env.leaseConfigFromEnv;
21
+ exports.normalizeConsensusConfig = require_config_consistency.normalizeConsensusConfig;
22
+ exports.parseNonNegativeNumberEnv = require_standalone_env.parseNonNegativeNumberEnv;
23
+ exports.rehydrateFollowerChainConfig = require_follower_config.rehydrateFollowerChainConfig;
24
+ exports.resolveConfigCheckModeFromEnv = require_standalone_env.resolveConfigCheckModeFromEnv;
25
+ exports.resolveConfigCheckTimeoutMsFromEnv = require_standalone_env.resolveConfigCheckTimeoutMsFromEnv;
26
+ exports.resolveFutureTimestampGuardFromEnv = require_standalone_env.resolveFutureTimestampGuardFromEnv;
27
+ exports.resolveTransactionSwitchesFromEnv = require_standalone_env.resolveTransactionSwitchesFromEnv;
11
28
  exports.resolveTrustedSubject = require_standalone_env.resolveTrustedSubject;
12
29
  exports.roleConfigFromEnv = require_env.roleConfigFromEnv;
13
- exports.startChainNode = require_start_chain_node.startChainNode;
30
+ exports.startChainNode = require_start_chain_node.startChainNode;
31
+ exports.toResolverConfig = require_follower_config.toResolverConfig;
32
+ exports.verifyFollowerConfigAgainstUpstream = require_config_consistency.verifyFollowerConfigAgainstUpstream;
package/lib/index.d.cts 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.cjs";
2
+ import { CONSENSUS_CONFIG_KEYS, ConfigDifference, VerifyFollowerConfigOptions, VerifyFollowerConfigResult, diffConsensusConfig, fetchUpstreamChainConfig, formatConfigDifferences, normalizeConsensusConfig, verifyFollowerConfigAgainstUpstream } from "./config-consistency.cjs";
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.cjs";
2
4
  import { InstallProcessSignalHandlersOptions, installProcessSignalHandlers, leaseConfigFromEnv, roleConfigFromEnv } from "./env.cjs";
5
+ import { isCompleteChainConfig, rehydrateFollowerChainConfig, toResolverConfig } from "./follower-config.cjs";
3
6
  import { startChainNode } from "./start-chain-node.cjs";
4
- import { BLOCKLET_ENV_CHAIN_FALLBACKS, BlockletEnvLeftovers, STANDALONE_ENV_MARKERS, findBlockletEnvLeftovers, formatBlockletEnvLeftoversWarning, resolveTrustedSubject } from "./standalone-env.cjs";
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 };
@@ -67,10 +67,99 @@ function formatBlockletEnvLeftoversWarning({ standaloneMarkers, leftovers, readB
67
67
  const read = readByChain.length ? ` ${readByChain.join(", ")} still feed key/path fallbacks when the CHAIN_* equivalent is unset.` : "";
68
68
  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)`;
69
69
  }
70
+ /** Env names of the `transaction.*` master switches a chain app maps into its chain config. */
71
+ const TRANSACTION_SWITCH_ENV = {
72
+ bridge: "CHAIN_TX_BRIDGE_ENABLED",
73
+ rollupV1: "CHAIN_TX_ROLLUP_V1_ENABLED"
74
+ };
75
+ /** `1`/`true` -> true, `0`/`false` -> false, unset/blank -> undefined; anything else fails startup. */
76
+ function parseStrictBoolEnv(env, name) {
77
+ const raw = String(env[name] ?? "").trim().toLowerCase();
78
+ if (!raw) return void 0;
79
+ if (raw === "1" || raw === "true") return true;
80
+ if (raw === "0" || raw === "false") return false;
81
+ throw new Error(`Invalid ${name}="${env[name]}": expected 1/true or 0/false (or leave it empty for the default)`);
82
+ }
83
+ /**
84
+ * `transaction.bridge` / `transaction.rollupV1` from env. Only explicitly set switches are returned, so an env
85
+ * without them leaves the chain config exactly as before (bridge absent = disabled, rollupV1 absent = enabled).
86
+ */
87
+ function resolveTransactionSwitchesFromEnv(env = process.env) {
88
+ const out = {};
89
+ const bridge = parseStrictBoolEnv(env, TRANSACTION_SWITCH_ENV.bridge);
90
+ if (bridge !== void 0) out.bridge = { enabled: bridge };
91
+ const rollupV1 = parseStrictBoolEnv(env, TRANSACTION_SWITCH_ENV.rollupV1);
92
+ if (rollupV1 !== void 0) out.rollupV1 = { enabled: rollupV1 };
93
+ return out;
94
+ }
95
+ /**
96
+ * `CHAIN_CONFIG_CHECK`: what a follower does with the startup comparison of its consensus config against the
97
+ * upstream leader's `getConfig` (`off` default: no request at all; `warn`: log differences and start; `enforce`:
98
+ * refuse to start on any difference or when the upstream cannot be asked).
99
+ */
100
+ function resolveConfigCheckModeFromEnv(env = process.env) {
101
+ const raw = String(env.CHAIN_CONFIG_CHECK ?? "").trim().toLowerCase();
102
+ if (!raw) return "off";
103
+ if (raw === "off" || raw === "warn" || raw === "enforce") return raw;
104
+ throw new Error(`Invalid CHAIN_CONFIG_CHECK="${env.CHAIN_CONFIG_CHECK}": expected off, warn or enforce`);
105
+ }
106
+ const DEFAULT_CONFIG_CHECK_TIMEOUT_SECONDS = 60;
107
+ /**
108
+ * `CHAIN_CONFIG_CHECK_TIMEOUT_SEC` (non-negative integer seconds, default 60): how long `enforce` keeps retrying an
109
+ * unreachable / bad upstream before it decides (start with a warning on existing local state, refuse when fresh).
110
+ */
111
+ function resolveConfigCheckTimeoutMsFromEnv(env = process.env) {
112
+ const raw = env.CHAIN_CONFIG_CHECK_TIMEOUT_SEC;
113
+ if (raw === void 0 || raw === "") return DEFAULT_CONFIG_CHECK_TIMEOUT_SECONDS * 1e3;
114
+ 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)`);
115
+ return Number(raw) * 1e3;
116
+ }
117
+ /**
118
+ * A fee / gas env value (`CHAIN_GAS_PRICE`, `CREATE_*_TX_FEE`), parsed identically on leader and follower:
119
+ * unset or empty -> undefined (the caller's default / no overlay); otherwise a plain non-negative decimal
120
+ * (`integer`: digits only). Whitespace, NaN, negatives, exponents and hex fail startup instead of becoming `0`.
121
+ */
122
+ function parseNonNegativeNumberEnv(env, name, { integer = false } = {}) {
123
+ const raw = env[name];
124
+ if (raw === void 0 || raw === "") return void 0;
125
+ const re = integer ? /^(?:0|[1-9]\d*)$/ : /^(?:0|[1-9]\d*)(?:\.\d+)?$/;
126
+ const value = Number(raw);
127
+ 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)`);
128
+ return value;
129
+ }
130
+ /** Default clock skew a replayed entry's timestamp may be ahead of the local clock (#1961; #1965 owns the value). */
131
+ const DEFAULT_FUTURE_TIMESTAMP_SKEW_SECONDS = 300;
132
+ /**
133
+ * `LEDGER_FUTURE_TIMESTAMP_FROM_SEQ` (positive integer; unset = guard disabled, today's behavior) and
134
+ * `LEDGER_FUTURE_TIMESTAMP_SKEW_SEC` (non-negative integer seconds, default 300; ignored while the guard is off).
135
+ */
136
+ function resolveFutureTimestampGuardFromEnv(env = process.env) {
137
+ const rawSeq = String(env.LEDGER_FUTURE_TIMESTAMP_FROM_SEQ ?? "").trim();
138
+ if (!rawSeq) return void 0;
139
+ 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`);
140
+ const rawSkew = String(env.LEDGER_FUTURE_TIMESTAMP_SKEW_SEC ?? "").trim();
141
+ let skewSeconds = DEFAULT_FUTURE_TIMESTAMP_SKEW_SECONDS;
142
+ if (rawSkew) {
143
+ 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`);
144
+ skewSeconds = Number(rawSkew);
145
+ }
146
+ return {
147
+ activationSequence: Number(rawSeq),
148
+ maxSkewMs: skewSeconds * 1e3
149
+ };
150
+ }
70
151
 
71
152
  //#endregion
72
153
  exports.BLOCKLET_ENV_CHAIN_FALLBACKS = BLOCKLET_ENV_CHAIN_FALLBACKS;
154
+ exports.DEFAULT_CONFIG_CHECK_TIMEOUT_SECONDS = DEFAULT_CONFIG_CHECK_TIMEOUT_SECONDS;
155
+ exports.DEFAULT_FUTURE_TIMESTAMP_SKEW_SECONDS = DEFAULT_FUTURE_TIMESTAMP_SKEW_SECONDS;
73
156
  exports.STANDALONE_ENV_MARKERS = STANDALONE_ENV_MARKERS;
157
+ exports.TRANSACTION_SWITCH_ENV = TRANSACTION_SWITCH_ENV;
74
158
  exports.findBlockletEnvLeftovers = findBlockletEnvLeftovers;
75
159
  exports.formatBlockletEnvLeftoversWarning = formatBlockletEnvLeftoversWarning;
160
+ exports.parseNonNegativeNumberEnv = parseNonNegativeNumberEnv;
161
+ exports.resolveConfigCheckModeFromEnv = resolveConfigCheckModeFromEnv;
162
+ exports.resolveConfigCheckTimeoutMsFromEnv = resolveConfigCheckTimeoutMsFromEnv;
163
+ exports.resolveFutureTimestampGuardFromEnv = resolveFutureTimestampGuardFromEnv;
164
+ exports.resolveTransactionSwitchesFromEnv = resolveTransactionSwitchesFromEnv;
76
165
  exports.resolveTrustedSubject = resolveTrustedSubject;
@@ -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 };
@@ -1,9 +1,11 @@
1
1
  const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
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');
3
5
  const require_test_hooks_token = require('./test-hooks-token.cjs');
6
+ let _ocap_util_lib_error = require("@ocap/util/lib/error");
4
7
  let _arcblock_ledger_core = require("@arcblock/ledger-core");
5
8
  let _arcblock_ledger_sqlite = require("@arcblock/ledger-sqlite");
6
- let _ocap_util_lib_error = require("@ocap/util/lib/error");
7
9
  let node_crypto = require("node:crypto");
8
10
  node_crypto = require_rolldown_runtime.__toESM(node_crypto);
9
11
  let node_fs = require("node:fs");
@@ -11,8 +13,6 @@ node_fs = require_rolldown_runtime.__toESM(node_fs);
11
13
  let node_path = require("node:path");
12
14
  node_path = require_rolldown_runtime.__toESM(node_path);
13
15
  let _arcblock_did = require("@arcblock/did");
14
- let _ocap_config = require("@ocap/config");
15
- _ocap_config = require_rolldown_runtime.__toESM(_ocap_config);
16
16
  let _ocap_gql = require("@ocap/gql");
17
17
  let _ocap_indexdb_sqlite = require("@ocap/indexdb-sqlite");
18
18
  _ocap_indexdb_sqlite = require_rolldown_runtime.__toESM(_ocap_indexdb_sqlite);
@@ -69,6 +69,22 @@ function assertSafeNonSymlinkDirectory(rawDataDir) {
69
69
  if (node_fs.default.lstatSync(dataDir).isSymbolicLink()) throw new _ocap_util_lib_error.CustomError("SECURITY_VIOLATION", `Refusing symlinked chain node dataDir: ${dataDir}`);
70
70
  return dataDir;
71
71
  }
72
+ /** Write a small file and fsync it and its directory, so it survives a crash or power loss right after. */
73
+ function writeFileDurably(filePath, content) {
74
+ const fd = node_fs.default.openSync(filePath, "w", 384);
75
+ try {
76
+ node_fs.default.writeFileSync(fd, content);
77
+ node_fs.default.fsyncSync(fd);
78
+ } finally {
79
+ node_fs.default.closeSync(fd);
80
+ }
81
+ const dirFd = node_fs.default.openSync(node_path.default.dirname(filePath), "r");
82
+ try {
83
+ node_fs.default.fsyncSync(dirFd);
84
+ } finally {
85
+ node_fs.default.closeSync(dirFd);
86
+ }
87
+ }
72
88
  function loadOrCreateNodeId(dataDir, explicitNodeId) {
73
89
  const nodeIdPath = node_path.default.join(dataDir, NODE_ID_FILENAME);
74
90
  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}`);
@@ -158,9 +174,6 @@ function adaptColdReaderToArchiveStore(reader) {
158
174
  ...typeof reader.getLatestHead === "function" ? { getLatestHead: reader.getLatestHead.bind(reader) } : {}
159
175
  };
160
176
  }
161
- function isCompleteChainConfig(candidate) {
162
- return Boolean(candidate && typeof candidate.chainId === "string" && candidate.chainId.trim() && candidate.moderator?.address && candidate.token?.symbol && candidate.vaults?.slashedStake);
163
- }
164
177
  function formatHttpHostForUrl(bindHost) {
165
178
  const trimmed = bindHost.trim();
166
179
  if (!trimmed || trimmed === "0.0.0.0" || trimmed === "::" || trimmed === "[::]") return "127.0.0.1";
@@ -188,9 +201,10 @@ async function bootChainNodeOnce(params) {
188
201
  const dataDir = assertSafeNonSymlinkDirectory(profile.dataDir);
189
202
  const { role } = profile;
190
203
  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\"");
191
- if ((role.kind === "validator" || role.kind === "hotstuff") && !isCompleteChainConfig(profile.chainConfig)) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `${role.kind} role requires a complete chainConfig`);
204
+ 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`);
192
205
  if ((role.kind === "validator" || role.kind === "hotstuff") && !role.signer) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `${role.kind} role requires role.signer`);
193
206
  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");
207
+ if (role.kind === "follower" && role.orphanIndexFromSequence !== void 0 && (!Number.isSafeInteger(role.orphanIndexFromSequence) || role.orphanIndexFromSequence < 1)) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `role.orphanIndexFromSequence must be a positive integer, got ${String(role.orphanIndexFromSequence)}`);
194
208
  const logger = testHooks?.logger ?? profile.logger ?? createDefaultLogger("chain-node");
195
209
  const variadicLogger = toVariadicLogger(logger);
196
210
  const followerExpectedChainId = "expectedChainId" in profile ? profile.expectedChainId : void 0;
@@ -238,6 +252,7 @@ async function bootChainNodeOnce(params) {
238
252
  let ledgerCleanupIndex = -1;
239
253
  let followerPrep = null;
240
254
  const isKeylessFollower = role.kind === "follower" && !profile.storage?.trustedStorageSecretKey?.trim();
255
+ let followerFetchGuard;
241
256
  if (role.kind === "follower") {
242
257
  if (node_fs.default.existsSync(ledgerPath) && node_fs.default.statSync(ledgerPath).size > 0) {
243
258
  const precheckLedgerStorage = createLedgerStorage();
@@ -274,6 +289,7 @@ async function bootChainNodeOnce(params) {
274
289
  init
275
290
  }, guardedBootstrapFetch);
276
291
  }) : guardedBootstrapFetch;
292
+ followerFetchGuard = bootstrapFetchImpl;
277
293
  const explicitExpectedChainId = followerExpectedChainId?.trim() || "";
278
294
  const profileChainId = profile.chainConfig?.chainId?.trim() || "";
279
295
  if (explicitExpectedChainId && profileChainId && explicitExpectedChainId !== profileChainId) throw new _ocap_util_lib_error.CustomError("SNAPSHOT_CHAIN_ID_MISMATCH", `Follower expectedChainId (${explicitExpectedChainId}) !== profile.chainConfig.chainId (${profileChainId})`);
@@ -346,20 +362,14 @@ async function bootChainNodeOnce(params) {
346
362
  });
347
363
  }
348
364
  let chainConfig;
349
- if (role.kind === "follower" && !isCompleteChainConfig(profile.chainConfig)) {
365
+ if (role.kind === "follower" && !require_follower_config.isCompleteChainConfig(profile.chainConfig)) {
350
366
  const storedChain = await statedb.chain.get(CHAIN_STATE_ADDR);
351
367
  if (!storedChain) throw new _ocap_util_lib_error.CustomError("INVALID_STATE", `Missing chain state (${CHAIN_STATE_ADDR}) in Follower statedb.sqlite (${statedbPath})`);
352
368
  const storedChainPartial = storedChain;
353
369
  const storedChainId = typeof storedChainPartial.chainId === "string" ? storedChainPartial.chainId.trim() : "";
354
370
  const overrideChainId = typeof profile.chainConfig?.chainId === "string" ? profile.chainConfig.chainId.trim() : "";
355
371
  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})`);
356
- const baseSymbol = storedChainPartial.token?.symbol || "TBA";
357
- const reservedSymbols = Array.from(new Set([baseSymbol, ...storedChainPartial.reservedSymbols ?? []].map((s) => String(s || "").trim().toUpperCase()).filter(Boolean)));
358
- chainConfig = _ocap_config.create({
359
- ...storedChain,
360
- ...storedChainId ? { chainId: storedChainId } : {},
361
- reservedSymbols
362
- });
372
+ chainConfig = require_follower_config.rehydrateFollowerChainConfig(storedChain, profile.chainConfig, profile.reservedSymbols);
363
373
  } else {
364
374
  const baseConfig = profile.chainConfig;
365
375
  if (role.kind === "follower") {
@@ -370,6 +380,7 @@ async function bootChainNodeOnce(params) {
370
380
  chainConfig = baseConfig;
371
381
  }
372
382
  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})`);
383
+ const orphanIndexStart = role.kind === "follower" ? require_follower_config.orphanIndexFromSequence(chainConfig.chainId, role.orphanIndexFromSequence) : 1;
373
384
  const hotstuffValidators = role.kind === "hotstuff" ? role.validators : role.kind === "follower" ? role.hotstuffValidators ?? [] : [];
374
385
  const hotstuffQuorumThreshold = role.kind === "hotstuff" ? role.quorumThreshold : role.kind === "follower" ? role.hotstuffQuorumThreshold : void 0;
375
386
  const hotstuffClusterConfig = role.kind === "hotstuff" || hotstuffValidators.length > 0 ? (0, _arcblock_ledger_core.toHotStuffClusterConfig)(chainConfig.chainId, hotstuffValidators, hotstuffQuorumThreshold) : void 0;
@@ -538,6 +549,9 @@ async function bootChainNodeOnce(params) {
538
549
  });
539
550
  }
540
551
  const indexDbExisted = node_fs.default.existsSync(indexdbPath);
552
+ const indexBuildMarkerPath = `${indexdbPath}.build-pending`;
553
+ let followerIndexBuildNeeded = role.kind === "follower" && (Boolean(followerPrep?.bootstrapped) || !indexDbExisted || node_fs.default.existsSync(indexBuildMarkerPath));
554
+ if (followerIndexBuildNeeded) writeFileDurably(indexBuildMarkerPath, `${(/* @__PURE__ */ new Date()).toISOString()}\n`);
541
555
  const indexdb = new _ocap_indexdb_sqlite.default({
542
556
  filename: indexdbPath,
543
557
  ...profile.storage?.indexWalAutoCheckpoint !== void 0 ? { walAutoCheckpoint: profile.storage.indexWalAutoCheckpoint } : {}
@@ -547,8 +561,16 @@ async function bootChainNodeOnce(params) {
547
561
  });
548
562
  await indexdb.initialize();
549
563
  await waitEventEmitterReady(indexdb);
564
+ if (role.kind === "follower" && !followerIndexBuildNeeded) {
565
+ if (await indexdb.tx.count() === 0 && await ledger.getLatestSequence() > 0) {
566
+ logger.warn?.("follower IndexDB has no transactions while the ledger has entries; rebuilding it", { indexdbPath });
567
+ followerIndexBuildNeeded = true;
568
+ writeFileDurably(indexBuildMarkerPath, `${(/* @__PURE__ */ new Date()).toISOString()}\n`);
569
+ }
570
+ }
550
571
  let resolverRef = null;
551
- const adminEnv = profile.http.adminEnv ?? {};
572
+ const explicitAdminEnv = profile.http.adminEnv;
573
+ const adminEnv = explicitAdminEnv ?? {};
552
574
  const preferencesManager = new _ocap_resolver.NodePreferencesManager({
553
575
  dataDir,
554
576
  env: adminEnv,
@@ -604,6 +626,15 @@ async function bootChainNodeOnce(params) {
604
626
  const initialPrefs = preferencesManager.getSnapshot();
605
627
  if (initialPrefs.runtime.txMaxRequest !== void 0) resolver.setMaxTxRequest(initialPrefs.runtime.txMaxRequest);
606
628
  await resolver.initialize();
629
+ if (role.kind === "follower") await require_config_consistency.verifyFollowerConfigAgainstUpstream({
630
+ mode: profile.configCheck?.mode ?? "off",
631
+ localConfig: resolver.config,
632
+ upstreamUrl: role.upstreamChainUrl ?? role.clusterPeerUrls?.[0] ?? null,
633
+ fetchUpstreamConfig: profile.configCheck?.fetchUpstreamConfig ?? ((u) => require_config_consistency.fetchUpstreamChainConfig(u, followerFetchGuard ? { fetchImpl: followerFetchGuard } : void 0)),
634
+ hasLocalState: !followerPrep?.bootstrapped && await ledger.getLatestSequence() > 0,
635
+ ...profile.configCheck?.retryDeadlineMs !== void 0 ? { retryDeadlineMs: profile.configCheck.retryDeadlineMs } : {},
636
+ logger
637
+ });
607
638
  let followerSync;
608
639
  let hotstuffRuntime;
609
640
  if (role.kind === "follower") {
@@ -645,6 +676,10 @@ async function bootChainNodeOnce(params) {
645
676
  startPaused: testHooks?.followerSync?.startPaused,
646
677
  artificialPollDelayMs: testHooks?.followerSync?.artificialPollDelayMs,
647
678
  interceptUpstreamFetch: testHooks?.followerSync?.interceptUpstreamFetch,
679
+ ...profile.replayGuards?.futureTimestamp ? { futureTimestampGuard: {
680
+ ...profile.replayGuards.futureTimestamp,
681
+ now: clockNow
682
+ } } : {},
648
683
  env: { ALLOW_PRIVATE_PEER_URLS: role.allowPrivatePeers ? "1" : "0" }
649
684
  });
650
685
  resolver.setNodeRuntime(followerSync);
@@ -657,9 +692,20 @@ async function bootChainNodeOnce(params) {
657
692
  triggerSyncOnce: () => syncRef.triggerSyncOnce()
658
693
  });
659
694
  }
660
- if (Boolean(followerPrep?.bootstrapped) || !indexDbExisted) {
661
- await resolver.rebuildIndex();
662
- await followerSync.replayer.indexExistingOrphanEntries();
695
+ if (followerIndexBuildNeeded) {
696
+ const buildStart = Date.now();
697
+ logger.info?.("follower initial index build started", {
698
+ indexdbPath,
699
+ resumed: indexDbExisted
700
+ });
701
+ const built = await resolver.rebuildIndex();
702
+ const orphans = await followerSync.replayer.indexExistingOrphanEntries(orphanIndexStart);
703
+ node_fs.default.rmSync(indexBuildMarkerPath, { force: true });
704
+ logger.info?.("follower initial index build finished", {
705
+ tables: built?.tables,
706
+ orphanEntries: orphans,
707
+ durationMs: Date.now() - buildStart
708
+ });
663
709
  }
664
710
  } else if (role.kind === "hotstuff") {
665
711
  const hotstuffStateStore = new _arcblock_ledger_sqlite.SqliteHotStuffStateStore(ledgerStorage);
@@ -729,7 +775,7 @@ async function bootChainNodeOnce(params) {
729
775
  res.once("close", markDone);
730
776
  next();
731
777
  });
732
- if (profile.http.enableAccessLog) app.use(require_access_log.createAccessLogMiddleware(logger));
778
+ if (profile.http.enableAccessLog) app.use(require_access_log.createAccessLogMiddleware(logger, explicitAdminEnv ? { env: explicitAdminEnv } : void 0));
733
779
  app.head("/", (_req, res) => {
734
780
  res.status(200).send("OK");
735
781
  });
@@ -772,7 +818,10 @@ async function bootChainNodeOnce(params) {
772
818
  const server = (0, _ocap_gql.createSocketHandler)({
773
819
  indexdb,
774
820
  app,
775
- wsOptions: { broadcastEventName: `@arcblock/ws:broadcast:${nodeId}:${node_crypto.default.randomUUID()}` }
821
+ wsOptions: {
822
+ broadcastEventName: `@arcblock/ws:broadcast:${nodeId}:${node_crypto.default.randomUUID()}`,
823
+ ...explicitAdminEnv ? { env: explicitAdminEnv } : {}
824
+ }
776
825
  });
777
826
  pushCleanup(async () => {
778
827
  isShuttingDown = true;
@@ -807,6 +856,7 @@ async function bootChainNodeOnce(params) {
807
856
  });
808
857
  app.use("/", (0, _ocap_gql.createHttpHandler)({
809
858
  resolver,
859
+ ...explicitAdminEnv ? { env: explicitAdminEnv } : {},
810
860
  onError: profile.http.onGraphqlError ? (err) => {
811
861
  profile.http.onGraphqlError(err);
812
862
  } : () => {}