@ocap/chain-node 0.0.0-stage → 1.32.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +234 -2
  2. package/esm/access-log.d.mts +34 -0
  3. package/esm/access-log.mjs +71 -0
  4. package/esm/config-consistency.d.mts +59 -0
  5. package/esm/config-consistency.mjs +220 -0
  6. package/esm/env.d.mts +32 -0
  7. package/esm/env.mjs +218 -0
  8. package/esm/follower-config.d.mts +25 -0
  9. package/esm/follower-config.mjs +57 -0
  10. package/esm/index.d.mts +7 -0
  11. package/esm/index.mjs +7 -0
  12. package/esm/standalone-env.d.mts +92 -0
  13. package/esm/standalone-env.mjs +152 -0
  14. package/esm/start-chain-node.d.mts +14 -0
  15. package/esm/start-chain-node.mjs +1107 -0
  16. package/esm/test-hooks-token.d.mts +12 -0
  17. package/esm/test-hooks-token.mjs +21 -0
  18. package/esm/testing.d.mts +13 -0
  19. package/esm/testing.mjs +23 -0
  20. package/esm/types.d.mts +310 -0
  21. package/esm/types.mjs +1 -0
  22. package/lib/_virtual/rolldown_runtime.cjs +29 -0
  23. package/lib/access-log.cjs +73 -0
  24. package/lib/access-log.d.cts +34 -0
  25. package/lib/config-consistency.cjs +227 -0
  26. package/lib/config-consistency.d.cts +59 -0
  27. package/lib/env.cjs +221 -0
  28. package/lib/env.d.cts +32 -0
  29. package/lib/follower-config.cjs +63 -0
  30. package/lib/follower-config.d.cts +25 -0
  31. package/lib/index.cjs +32 -0
  32. package/lib/index.d.cts +7 -0
  33. package/lib/standalone-env.cjs +165 -0
  34. package/lib/standalone-env.d.cts +92 -0
  35. package/lib/start-chain-node.cjs +1116 -0
  36. package/lib/start-chain-node.d.cts +14 -0
  37. package/lib/test-hooks-token.cjs +24 -0
  38. package/lib/test-hooks-token.d.cts +12 -0
  39. package/lib/testing.cjs +23 -0
  40. package/lib/testing.d.cts +13 -0
  41. package/lib/types.cjs +0 -0
  42. package/lib/types.d.cts +310 -0
  43. package/package.json +78 -4
@@ -0,0 +1,227 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ let _ocap_config = require("@ocap/config");
3
+ let _ocap_config_lib_default = require("@ocap/config/lib/default");
4
+ _ocap_config_lib_default = require_rolldown_runtime.__toESM(_ocap_config_lib_default);
5
+ let _ocap_util_lib_error = require("@ocap/util/lib/error");
6
+
7
+ //#region src/config-consistency.ts
8
+ /**
9
+ * Follower startup consistency check (#1961): before a follower replays anything it asks the upstream leader for
10
+ * its in-memory chain config (`getConfig`, core/resolver `getConfig()` returns `JSON.stringify(this.config)`) and
11
+ * compares every consensus-relevant key, both sides normalized with the same defaults. A follower that replays with
12
+ * a different config computes different state commits (e.g. `transaction.bridge.enabled` off rejects the first
13
+ * bridge reserve entry in `bridge-reserve-v2-gate.ts`) and halts; this check turns that into a clear startup error.
14
+ *
15
+ * Consensus-relevant keys (`CONSENSUS_CONFIG_KEYS`) are what the tx pipeline / replayer reads from `context.config`:
16
+ * - `chainId` every protocol (`tx.chainId` checks), replayer entry chain id
17
+ * - `mode` `Config.create` defaults (`ledger` zeroes fees and gas)
18
+ * - `moderator.address` moderator-only protocols (token / factory / rollup governance)
19
+ * - `token.address/symbol/decimal` official token, fee and stake units, reserved base symbol
20
+ * - `vaults` where fees, gas and slashed stake go (`txFee`, `txFees`, `txGas`, `slashedStake`)
21
+ * - `reservedSymbols` `create_token_factory` verification (compared as a case-insensitive set)
22
+ * - `transaction` the whole section: `txFee`, `txGas` (+ free-gas / burst knobs), `txStake`,
23
+ * `maxTxSize`, `maxAssetSize`, `maxListSize`, `maxMultisig`, `delegate`, `supportedTxs`,
24
+ * `multiSignV2Txs`, `maxWriteSetSize`, `security`, `bridge`, `rollupV1`, `exchangeV2`
25
+ * Not compared: `version` (software), `accounts` and token metadata/supply (genesis only: a follower never re-runs
26
+ * genesis, it starts from a verified snapshot), `moderator.pk` (protocols compare the address), `genesisTime`.
27
+ */
28
+ const CONSENSUS_CONFIG_KEYS = [
29
+ "chainId",
30
+ "mode",
31
+ "moderator.address",
32
+ "token.address",
33
+ "token.symbol",
34
+ "token.decimal",
35
+ "vaults",
36
+ "reservedSymbols",
37
+ "transaction"
38
+ ];
39
+ /** Protocol fallback of `transaction.exchangeV2.defaultTtlSeconds` (core/tx-protocols exchange-v2.ts). */
40
+ const DEFAULT_EXCHANGE_V2_TTL_SECONDS = 720 * 60 * 60;
41
+ const isPlainObject = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
42
+ /** JSON round trip: drops `undefined`, functions and frozen-ness, so both sides compare as the wire would. */
43
+ function toJsonValue(value) {
44
+ if (value === void 0) return void 0;
45
+ return JSON.parse(JSON.stringify(value));
46
+ }
47
+ function getPath(obj, dotted) {
48
+ let cur = obj;
49
+ for (const seg of dotted.split(".")) {
50
+ if (!isPlainObject(cur)) return void 0;
51
+ cur = cur[seg];
52
+ }
53
+ return cur;
54
+ }
55
+ function setPath(obj, dotted, value) {
56
+ const segs = dotted.split(".");
57
+ let cur = obj;
58
+ for (const seg of segs.slice(0, -1)) {
59
+ if (!isPlainObject(cur[seg])) cur[seg] = {};
60
+ cur = cur[seg];
61
+ }
62
+ cur[segs[segs.length - 1]] = value;
63
+ }
64
+ /** Fill only keys that are absent (`undefined`); present values, records and arrays are kept as they are. */
65
+ function fillAbsent(target, defaults) {
66
+ const out = { ...target };
67
+ for (const [k, v] of Object.entries(defaults)) if (out[k] === void 0) out[k] = toJsonValue(v);
68
+ return out;
69
+ }
70
+ function normalizeTransaction(raw) {
71
+ const tx = fillAbsent(isPlainObject(raw) ? toJsonValue(raw) : {}, _ocap_config_lib_default.default.transaction);
72
+ tx.txGas = fillAbsent(isPlainObject(tx.txGas) ? tx.txGas : {}, _ocap_config.defaultGasSecurityKnobs.txGas);
73
+ tx.security = fillAbsent(isPlainObject(tx.security) ? tx.security : {}, _ocap_config.defaultGasSecurityKnobs.security);
74
+ tx.bridge = { enabled: isPlainObject(tx.bridge) && tx.bridge.enabled === true };
75
+ tx.rollupV1 = { enabled: !(isPlainObject(tx.rollupV1) && tx.rollupV1.enabled === false) };
76
+ const exchangeV2 = isPlainObject(tx.exchangeV2) ? tx.exchangeV2 : {};
77
+ tx.exchangeV2 = {
78
+ ...exchangeV2,
79
+ defaultTtlSeconds: typeof exchangeV2.defaultTtlSeconds === "number" ? exchangeV2.defaultTtlSeconds : DEFAULT_EXCHANGE_V2_TTL_SECONDS
80
+ };
81
+ return tx;
82
+ }
83
+ /** The consensus-relevant projection of a chain config, with defaults applied identically on both sides. */
84
+ function normalizeConsensusConfig(config) {
85
+ const out = {};
86
+ for (const key of CONSENSUS_CONFIG_KEYS) {
87
+ const value = toJsonValue(getPath(config, key));
88
+ switch (key) {
89
+ case "mode":
90
+ setPath(out, key, value === "ledger" ? "ledger" : "chain");
91
+ break;
92
+ case "token.address":
93
+ setPath(out, key, typeof value === "string" ? value : "");
94
+ break;
95
+ case "vaults":
96
+ setPath(out, key, isPlainObject(value) ? value : {});
97
+ break;
98
+ case "reservedSymbols":
99
+ setPath(out, key, Array.from(new Set((Array.isArray(value) ? value : []).map((s) => String(s ?? "").trim().toUpperCase()).filter(Boolean))).sort());
100
+ break;
101
+ case "transaction":
102
+ setPath(out, key, normalizeTransaction(value));
103
+ break;
104
+ default: setPath(out, key, value === void 0 ? null : value);
105
+ }
106
+ }
107
+ return out;
108
+ }
109
+ function collectDiff(local, upstream, prefix, out) {
110
+ if (isPlainObject(local) && isPlainObject(upstream)) {
111
+ const keys = Array.from(new Set([...Object.keys(local), ...Object.keys(upstream)])).sort();
112
+ for (const k of keys) collectDiff(local[k], upstream[k], prefix ? `${prefix}.${k}` : k, out);
113
+ return;
114
+ }
115
+ if (JSON.stringify(local) !== JSON.stringify(upstream)) out.push({
116
+ path: prefix,
117
+ local: local === void 0 ? null : local,
118
+ upstream: upstream === void 0 ? null : upstream
119
+ });
120
+ }
121
+ /** Differences between two configs' consensus projections, by dotted path (arrays compare as a whole). */
122
+ function diffConsensusConfig(local, upstream) {
123
+ const out = [];
124
+ collectDiff(normalizeConsensusConfig(local), normalizeConsensusConfig(upstream), "", out);
125
+ return out;
126
+ }
127
+ const MAX_CONFIG_RESPONSE_BYTES = 8 * 1024 * 1024;
128
+ const GET_CONFIG_QUERY = "{ getConfig { code config } }";
129
+ /** POST `{ getConfig }` to `<upstreamUrl>/api/gql` and return the parsed in-memory config of the upstream. */
130
+ async function fetchUpstreamChainConfig(upstreamUrl, { fetchImpl = fetch, timeoutMs = 1e4 } = {}) {
131
+ const url = `${String(upstreamUrl).trim().replace(/\/+$/, "")}/api/gql`;
132
+ const res = await fetchImpl(url, {
133
+ method: "POST",
134
+ headers: {
135
+ "content-type": "application/json",
136
+ accept: "application/json"
137
+ },
138
+ body: JSON.stringify({ query: GET_CONFIG_QUERY }),
139
+ redirect: "error",
140
+ signal: AbortSignal.timeout(timeoutMs)
141
+ });
142
+ const text = await res.text();
143
+ if (!res.ok) throw new Error(`getConfig from ${url} failed: HTTP ${res.status}`);
144
+ if (text.length > MAX_CONFIG_RESPONSE_BYTES) throw new Error(`getConfig from ${url} failed: response larger than ${MAX_CONFIG_RESPONSE_BYTES} bytes`);
145
+ const body = JSON.parse(text);
146
+ if (body.errors?.length) throw new Error(`getConfig from ${url} failed: ${body.errors.map((e) => e.message).join("; ")}`);
147
+ const raw = body.data?.getConfig?.config;
148
+ if (typeof raw !== "string" || !raw) throw new Error(`getConfig from ${url} failed: no config in the response (code=${body.data?.getConfig?.code})`);
149
+ return assertUpstreamConfigShape(JSON.parse(raw), url);
150
+ }
151
+ /** A response that is not a chain config is a bad body ("unavailable"), never a definite mismatch. */
152
+ function assertUpstreamConfigShape(parsed, source) {
153
+ if (!isPlainObject(parsed)) throw new Error(`getConfig from ${source} failed: config is not an object`);
154
+ if (typeof parsed.chainId !== "string" || !parsed.chainId.trim() || !isPlainObject(parsed.transaction)) throw new Error(`getConfig from ${source} failed: config has no chainId / transaction section`);
155
+ return parsed;
156
+ }
157
+ const formatValue = (v) => {
158
+ const s = JSON.stringify(v);
159
+ return s.length > 160 ? `${s.slice(0, 157)}...` : s;
160
+ };
161
+ function formatConfigDifferences(diff) {
162
+ return diff.map((d) => `${d.path} (local=${formatValue(d.local)}, upstream=${formatValue(d.upstream)})`).join("; ");
163
+ }
164
+ /**
165
+ * Compare the follower's replay config with the upstream leader's. `off`: no request. `warn`: one attempt, log
166
+ * any difference or failure and continue. `enforce`: a definite difference throws `CHAIN_CONFIG_MISMATCH` (lists
167
+ * every differing key). An unavailable upstream (down, HTTP error such as 429, bad body) is retried with backoff
168
+ * until `retryDeadlineMs`; then a node with existing local state starts with a warning, and only a fresh bootstrap
169
+ * throws `CHAIN_CONFIG_CHECK_UNAVAILABLE`.
170
+ */
171
+ async function verifyFollowerConfigAgainstUpstream(opts) {
172
+ if (opts.mode === "off") return {
173
+ status: "skipped",
174
+ diff: []
175
+ };
176
+ const enforce = opts.mode === "enforce";
177
+ const now = opts.now ?? (() => Date.now());
178
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
179
+ const unavailable = (reason) => {
180
+ const message$1 = `Follower config check (CHAIN_CONFIG_CHECK=${opts.mode}) could not read the upstream config: ${reason}`;
181
+ if (enforce && !opts.hasLocalState) throw new _ocap_util_lib_error.CustomError("CHAIN_CONFIG_CHECK_UNAVAILABLE", `${message$1}; refusing to start a fresh bootstrap before replay`);
182
+ opts.logger.warn(`[chain-node] ${message$1}; starting without the check${enforce ? " (existing local state)" : ""}`);
183
+ return {
184
+ status: "unavailable",
185
+ diff: []
186
+ };
187
+ };
188
+ const upstreamUrl = String(opts.upstreamUrl ?? "").trim();
189
+ if (!upstreamUrl) return unavailable("no upstream URL (UPSTREAM_CHAIN_URL) is configured");
190
+ const fetchConfig = opts.fetchUpstreamConfig ?? ((u) => fetchUpstreamChainConfig(u));
191
+ const deadline = now() + Math.max(0, opts.retryDeadlineMs ?? 6e4);
192
+ const maxDelay = Math.max(0, opts.retryMaxDelayMs ?? 1e4);
193
+ let delay = Math.max(0, opts.retryDelayMs ?? 1e3);
194
+ let upstreamConfig = null;
195
+ while (upstreamConfig === null) try {
196
+ upstreamConfig = assertUpstreamConfigShape(await fetchConfig(upstreamUrl), upstreamUrl);
197
+ } catch (err) {
198
+ const reason = err instanceof Error ? err.message : String(err);
199
+ if (!enforce || now() + delay > deadline) return unavailable(reason);
200
+ opts.logger.warn(`[chain-node] follower config check: upstream unavailable (${reason}); retrying in ${delay} ms`);
201
+ await sleep(delay);
202
+ delay = Math.min(maxDelay, delay * 2);
203
+ }
204
+ const diff = diffConsensusConfig(opts.localConfig, upstreamConfig);
205
+ if (diff.length === 0) {
206
+ opts.logger.info(`[chain-node] follower consensus config matches upstream ${upstreamUrl}`);
207
+ return {
208
+ status: "match",
209
+ diff
210
+ };
211
+ }
212
+ const message = `Follower consensus config differs from upstream ${upstreamUrl} in ${diff.length} key(s): ${formatConfigDifferences(diff)}`;
213
+ if (enforce) throw new _ocap_util_lib_error.CustomError("CHAIN_CONFIG_MISMATCH", `${message}; refusing to start before replay (#1961)`);
214
+ opts.logger.warn(`[chain-node] ${message}`);
215
+ return {
216
+ status: "mismatch",
217
+ diff
218
+ };
219
+ }
220
+
221
+ //#endregion
222
+ exports.CONSENSUS_CONFIG_KEYS = CONSENSUS_CONFIG_KEYS;
223
+ exports.diffConsensusConfig = diffConsensusConfig;
224
+ exports.fetchUpstreamChainConfig = fetchUpstreamChainConfig;
225
+ exports.formatConfigDifferences = formatConfigDifferences;
226
+ exports.normalizeConsensusConfig = normalizeConsensusConfig;
227
+ exports.verifyFollowerConfigAgainstUpstream = verifyFollowerConfigAgainstUpstream;
@@ -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 ADDED
@@ -0,0 +1,221 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ let _ocap_util_lib_error = require("@ocap/util/lib/error");
3
+ let _arcblock_ledger_core = require("@arcblock/ledger-core");
4
+ let _arcblock_ledger_sqlite = require("@arcblock/ledger-sqlite");
5
+
6
+ //#region src/env.ts
7
+ function parseOptionalPositiveInt(raw, label) {
8
+ const trimmed = (raw ?? "").trim();
9
+ if (!trimmed) return void 0;
10
+ if (!/^[1-9]\d*$/.test(trimmed)) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `Invalid ${label}="${raw}": expected a positive integer >= 1`);
11
+ const parsed = Number(trimmed);
12
+ if (!Number.isSafeInteger(parsed) || parsed < 1) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `Invalid ${label}="${raw}": expected a positive safe integer >= 1`);
13
+ return parsed;
14
+ }
15
+ function parseOptionalNonNegativeInt(raw, label) {
16
+ const trimmed = (raw ?? "").trim();
17
+ if (!trimmed) return void 0;
18
+ if (!/^(?:0|[1-9]\d*)$/.test(trimmed)) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `Invalid ${label}="${raw}": expected a non-negative integer >= 0`);
19
+ const parsed = Number(trimmed);
20
+ if (!Number.isSafeInteger(parsed) || parsed < 0) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `Invalid ${label}="${raw}": expected a non-negative safe integer >= 0`);
21
+ return parsed;
22
+ }
23
+ function parseBoolEnv(raw) {
24
+ const norm = (raw ?? "").trim().toLowerCase();
25
+ return norm === "1" || norm === "true";
26
+ }
27
+ function hasSigningSecretKey(signer) {
28
+ return Boolean(signer && typeof signer.secretKey === "string" && signer.secretKey.trim().length > 0);
29
+ }
30
+ function normalizeConsensusKeyType(rawValue) {
31
+ const trimmed = (rawValue ?? "").trim().toLowerCase();
32
+ if (!trimmed) return void 0;
33
+ if (trimmed === "ethereum") return "eth";
34
+ if (trimmed === "ed25519" || trimmed === "secp256k1" || trimmed === "eth") return trimmed;
35
+ throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `Unsupported CHAIN_CONSENSUS_KEY_TYPE="${rawValue}": expected ed25519, secp256k1, or eth`);
36
+ }
37
+ function resolveSignerFromEnvRecord(env, explicitSigner) {
38
+ const keyType = normalizeConsensusKeyType(env.CHAIN_CONSENSUS_KEY_TYPE);
39
+ const secretKey = (env.CHAIN_CONSENSUS_SK ?? "").trim();
40
+ const address = (env.CHAIN_CONSENSUS_PROPOSER ?? "").trim();
41
+ if (!secretKey) {
42
+ if (keyType) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `CHAIN_CONSENSUS_KEY_TYPE (${env.CHAIN_CONSENSUS_KEY_TYPE}) requires CHAIN_CONSENSUS_SK to be set`);
43
+ if (address) {
44
+ if (!hasSigningSecretKey(explicitSigner) || (0, _arcblock_ledger_core.normalizeDidForCompare)(explicitSigner.address) !== (0, _arcblock_ledger_core.normalizeDidForCompare)(address)) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `CHAIN_CONSENSUS_PROPOSER (${env.CHAIN_CONSENSUS_PROPOSER}) requires a matching CHAIN_CONSENSUS_SK`);
45
+ }
46
+ return explicitSigner;
47
+ }
48
+ if (hasSigningSecretKey(explicitSigner)) return explicitSigner;
49
+ if (address) {
50
+ const resolved = (0, _arcblock_ledger_core.resolveConsensusProposerFromSigner)({
51
+ address,
52
+ secretKey,
53
+ ...keyType ? { keyType } : {}
54
+ });
55
+ return {
56
+ address: resolved.address,
57
+ secretKey: resolved.secretKey,
58
+ publicKey: resolved.publicKey,
59
+ ...keyType ? { keyType } : {}
60
+ };
61
+ }
62
+ const derived = (0, _arcblock_ledger_core.resolveConsensusProposer)({
63
+ moderator: { address: explicitSigner?.address || "" },
64
+ env: {
65
+ ...env,
66
+ ...keyType ? { CHAIN_CONSENSUS_KEY_TYPE: keyType } : {}
67
+ }
68
+ });
69
+ if (derived.secretKey) return {
70
+ address: derived.address,
71
+ secretKey: derived.secretKey,
72
+ publicKey: derived.publicKey,
73
+ ...keyType ? { keyType } : {}
74
+ };
75
+ return explicitSigner;
76
+ }
77
+ /**
78
+ * Pure environment-to-role parser (`@ocap/chain-node`).
79
+ *
80
+ * Reads ONLY the explicitly supplied `env` dictionary — zero implicit `process.env` reads.
81
+ */
82
+ function roleConfigFromEnv(env, options) {
83
+ if (!env || typeof env !== "object") throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", "roleConfigFromEnv requires an explicit env record");
84
+ const resolved = (0, _arcblock_ledger_core.resolveNodeRoleConfig)(env);
85
+ const allowPrivatePeers = parseBoolEnv(env.ALLOW_PRIVATE_PEER_URLS);
86
+ const explicitOrEnvSigner = resolveSignerFromEnvRecord(env, options?.signer);
87
+ if (resolved.role === "validator") {
88
+ if (!explicitOrEnvSigner) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", "Validator role requires options.signer or explicit CHAIN_CONSENSUS_SK + CHAIN_CONSENSUS_PROPOSER in env");
89
+ if (resolved.consensusMode === "hotstuff") {
90
+ if (!hasSigningSecretKey(explicitOrEnvSigner)) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", "HotStuff validator role requires a signing secretKey in options.signer or CHAIN_CONSENSUS_SK");
91
+ if (!resolved.consensusBindHost || resolved.consensusPort === null) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", "HotStuff validator role requires CONSENSUS_BIND_HOST and CONSENSUS_PORT");
92
+ return {
93
+ kind: "hotstuff",
94
+ signer: explicitOrEnvSigner,
95
+ validators: resolved.hotstuffValidators,
96
+ ...resolved.hotstuffQuorumThreshold !== void 0 ? { quorumThreshold: resolved.hotstuffQuorumThreshold } : {},
97
+ consensusBindHost: resolved.consensusBindHost,
98
+ consensusPort: resolved.consensusPort,
99
+ allowPublicConsensusBind: resolved.allowPublicConsensusBind,
100
+ writePolicy: resolved.writePolicy,
101
+ allowPrivatePeers,
102
+ retentionMode: resolved.retentionMode,
103
+ hotWindowEntries: resolved.hotWindowEntries,
104
+ hotWindowCheckpoints: resolved.hotWindowCheckpoints,
105
+ snapshotBaseUrl: resolved.snapshotBaseUrl,
106
+ witnessQuorum: resolved.witnessQuorum,
107
+ ...resolved.trustedWitnesses !== void 0 ? { trustedWitnesses: resolved.trustedWitnesses } : {},
108
+ witnessSubmitUrls: resolved.witnessSubmitUrls
109
+ };
110
+ }
111
+ return {
112
+ kind: "validator",
113
+ signer: explicitOrEnvSigner,
114
+ retentionMode: resolved.retentionMode,
115
+ hotWindowEntries: resolved.hotWindowEntries,
116
+ hotWindowCheckpoints: resolved.hotWindowCheckpoints,
117
+ snapshotBaseUrl: resolved.snapshotBaseUrl,
118
+ witnessQuorum: resolved.witnessQuorum,
119
+ ...resolved.trustedWitnesses !== void 0 ? { trustedWitnesses: resolved.trustedWitnesses } : {},
120
+ witnessSubmitUrls: resolved.witnessSubmitUrls,
121
+ anchorWebhookUrl: resolved.anchorWebhookUrl
122
+ };
123
+ }
124
+ const pollIntervalMs = parseOptionalPositiveInt(env.FOLLOWER_POLL_INTERVAL_MS, "FOLLOWER_POLL_INTERVAL_MS");
125
+ const maxSyncLag = parseOptionalNonNegativeInt(env.FOLLOWER_MAX_SYNC_LAG, "FOLLOWER_MAX_SYNC_LAG");
126
+ const maxUpstreamStaleMs = parseOptionalPositiveInt(env.FOLLOWER_MAX_UPSTREAM_STALE_MS, "FOLLOWER_MAX_UPSTREAM_STALE_MS");
127
+ const witnessWallet = (0, _arcblock_ledger_core.resolveEnvWitnessWallet)(env) ?? void 0;
128
+ const snapshotPrefix = (env.SNAPSHOT_S3_PREFIX ?? "").trim() || void 0;
129
+ const disallowKeylessCascadedUpstream = parseBoolEnv(env.DISALLOW_KEYLESS_CASCADED_UPSTREAM);
130
+ return {
131
+ kind: "follower",
132
+ runtimeRole: resolved.role === "standby" ? "standby" : "follower",
133
+ writePolicy: resolved.writePolicy,
134
+ upstreamChainUrl: resolved.upstreamChainUrl,
135
+ clusterPeerUrls: resolved.clusterPeerUrls,
136
+ snapshotBaseUrl: resolved.snapshotBaseUrl,
137
+ ...snapshotPrefix ? { snapshotPrefix } : {},
138
+ trustedProposer: resolved.trustedProposer,
139
+ trustedProposerPublicKey: resolved.trustedProposerPublicKey,
140
+ ...resolved.hotstuffValidators.length > 0 ? { hotstuffValidators: resolved.hotstuffValidators } : {},
141
+ ...resolved.hotstuffQuorumThreshold !== void 0 ? { hotstuffQuorumThreshold: resolved.hotstuffQuorumThreshold } : {},
142
+ allowPrivatePeers,
143
+ disallowKeylessCascadedUpstream,
144
+ allowUnauthenticatedBootstrap: resolved.allowUnauthenticatedBootstrap,
145
+ syncMode: resolved.syncMode,
146
+ ...pollIntervalMs !== void 0 ? { pollIntervalMs } : {},
147
+ ...maxSyncLag !== void 0 ? { maxSyncLag } : {},
148
+ ...maxUpstreamStaleMs !== void 0 ? { maxUpstreamStaleMs } : {},
149
+ retentionMode: resolved.retentionMode,
150
+ hotWindowEntries: resolved.hotWindowEntries,
151
+ hotWindowCheckpoints: resolved.hotWindowCheckpoints,
152
+ ...witnessWallet ? { witnessWallet } : {},
153
+ witnessSubmitUrls: resolved.witnessSubmitUrls,
154
+ ...hasSigningSecretKey(explicitOrEnvSigner) ? { signer: explicitOrEnvSigner } : {}
155
+ };
156
+ }
157
+ /**
158
+ * Pure environment-to-SQLite-writer-lease parser (`@ocap/chain-node`).
159
+ *
160
+ * Reads ONLY the explicitly supplied `env` dictionary — zero implicit `process.env` reads.
161
+ */
162
+ function leaseConfigFromEnv(env) {
163
+ if (!env || typeof env !== "object") throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", "leaseConfigFromEnv requires an explicit env record");
164
+ const parsed = (0, _arcblock_ledger_sqlite.resolveLedgerLeaseConfig)(env);
165
+ if (!parsed.enabled) return false;
166
+ return {
167
+ enabled: true,
168
+ autoAcquire: true,
169
+ holderId: parsed.holderId,
170
+ ttlMs: parsed.ttlMs,
171
+ startupWaitMs: parsed.startupWaitMs
172
+ };
173
+ }
174
+ /**
175
+ * Install idempotent `SIGTERM` / `SIGINT` graceful shutdown handlers for a running chain node.
176
+ * Returns a cleanup callback that removes the signal listeners.
177
+ */
178
+ function installProcessSignalHandlers(node, options) {
179
+ const timeoutMs = typeof options?.timeoutMs === "number" && Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : 15e3;
180
+ const signals = options?.signals ?? ["SIGTERM", "SIGINT"];
181
+ const exitProcess = options?.exitProcess !== false;
182
+ const log = options?.logger ?? console;
183
+ let shuttingDown = false;
184
+ const handleSignal = (signal) => {
185
+ if (shuttingDown) return;
186
+ shuttingDown = true;
187
+ log.info(`\n${signal} received, shutting down chain node gracefully...`);
188
+ const forceTimer = setTimeout(() => {
189
+ log.error("Chain node graceful shutdown timed out, forcing exit");
190
+ options?.onExit?.(1);
191
+ if (exitProcess) process.exit(1);
192
+ }, timeoutMs);
193
+ if (typeof forceTimer.unref === "function") forceTimer.unref();
194
+ node.stop().then(() => {
195
+ clearTimeout(forceTimer);
196
+ log.info("Chain node graceful shutdown complete");
197
+ options?.onExit?.(0);
198
+ if (exitProcess) process.exit(0);
199
+ }).catch((err) => {
200
+ clearTimeout(forceTimer);
201
+ log.error("Error during chain node graceful shutdown:", err);
202
+ options?.onExit?.(1);
203
+ if (exitProcess) process.exit(1);
204
+ });
205
+ };
206
+ const listeners = /* @__PURE__ */ new Map();
207
+ for (const sig of signals) {
208
+ const listener = () => handleSignal(sig);
209
+ listeners.set(sig, listener);
210
+ process.on(sig, listener);
211
+ }
212
+ return () => {
213
+ for (const [sig, listener] of listeners) process.off(sig, listener);
214
+ listeners.clear();
215
+ };
216
+ }
217
+
218
+ //#endregion
219
+ exports.installProcessSignalHandlers = installProcessSignalHandlers;
220
+ exports.leaseConfigFromEnv = leaseConfigFromEnv;
221
+ exports.roleConfigFromEnv = roleConfigFromEnv;
package/lib/env.d.cts ADDED
@@ -0,0 +1,32 @@
1
+ import { ChainNodeRoleConfig, ILedgerLeaseOptions, RunningChainNode, ValidatorSignerConfig } from "./types.cjs";
2
+
3
+ //#region src/env.d.ts
4
+
5
+ /**
6
+ * Pure environment-to-role parser (`@ocap/chain-node`).
7
+ *
8
+ * Reads ONLY the explicitly supplied `env` dictionary — zero implicit `process.env` reads.
9
+ */
10
+ declare function roleConfigFromEnv(env: Record<string, string | undefined>, options?: {
11
+ signer?: ValidatorSignerConfig;
12
+ }): ChainNodeRoleConfig;
13
+ /**
14
+ * Pure environment-to-SQLite-writer-lease parser (`@ocap/chain-node`).
15
+ *
16
+ * Reads ONLY the explicitly supplied `env` dictionary — zero implicit `process.env` reads.
17
+ */
18
+ declare function leaseConfigFromEnv(env: Record<string, string | undefined>): ILedgerLeaseOptions | false;
19
+ interface InstallProcessSignalHandlersOptions {
20
+ timeoutMs?: number;
21
+ signals?: NodeJS.Signals[];
22
+ exitProcess?: boolean;
23
+ onExit?: (exitCode: number) => void;
24
+ logger?: Pick<Console, 'info' | 'error'>;
25
+ }
26
+ /**
27
+ * Install idempotent `SIGTERM` / `SIGINT` graceful shutdown handlers for a running chain node.
28
+ * Returns a cleanup callback that removes the signal listeners.
29
+ */
30
+ declare function installProcessSignalHandlers(node: Pick<RunningChainNode, 'stop'>, options?: InstallProcessSignalHandlersOptions): () => void;
31
+ //#endregion
32
+ export { InstallProcessSignalHandlersOptions, installProcessSignalHandlers, leaseConfigFromEnv, roleConfigFromEnv };
@@ -0,0 +1,63 @@
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) {
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([baseSymbol, ...storedChainPartial.reservedSymbols ?? []].map((s) => String(s || "").trim().toUpperCase()).filter(Boolean)));
39
+ const transactionOverlay = isPlainRecord(profileChainConfig?.transaction) ? profileChainConfig.transaction : void 0;
40
+ return _ocap_config.create({
41
+ ...storedChain,
42
+ ...storedChainId ? { chainId: storedChainId } : {},
43
+ ...transactionOverlay ? { transaction: mergeTransactionOverlay(storedChainPartial.transaction, transactionOverlay) } : {},
44
+ reservedSymbols
45
+ });
46
+ }
47
+ /**
48
+ * The config a resolver actually runs with (`OCAPResolver` constructor): validated, with `token.address` set to the
49
+ * genesis token address. This is what the leader's `getConfig` returns and what the follower's replayer reads.
50
+ */
51
+ function toResolverConfig(config) {
52
+ const validated = _ocap_config.validate(JSON.parse(JSON.stringify(config)));
53
+ const tokenItx = _ocap_config.genTokenItx(validated);
54
+ if (tokenItx) validated.token.address = tokenItx.address;
55
+ return validated;
56
+ }
57
+
58
+ //#endregion
59
+ exports.isCompleteChainConfig = isCompleteChainConfig;
60
+ exports.isPlainRecord = isPlainRecord;
61
+ exports.mergeTransactionOverlay = mergeTransactionOverlay;
62
+ exports.rehydrateFollowerChainConfig = rehydrateFollowerChainConfig;
63
+ exports.toResolverConfig = toResolverConfig;
@@ -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 };
package/lib/index.cjs ADDED
@@ -0,0 +1,32 @@
1
+ const require_config_consistency = require('./config-consistency.cjs');
2
+ const require_env = require('./env.cjs');
3
+ const require_follower_config = require('./follower-config.cjs');
4
+ const require_start_chain_node = require('./start-chain-node.cjs');
5
+ const require_standalone_env = require('./standalone-env.cjs');
6
+
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;
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;
15
+ exports.findBlockletEnvLeftovers = require_standalone_env.findBlockletEnvLeftovers;
16
+ exports.formatBlockletEnvLeftoversWarning = require_standalone_env.formatBlockletEnvLeftoversWarning;
17
+ exports.formatConfigDifferences = require_config_consistency.formatConfigDifferences;
18
+ exports.installProcessSignalHandlers = require_env.installProcessSignalHandlers;
19
+ exports.isCompleteChainConfig = require_follower_config.isCompleteChainConfig;
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;
28
+ exports.resolveTrustedSubject = require_standalone_env.resolveTrustedSubject;
29
+ exports.roleConfigFromEnv = require_env.roleConfigFromEnv;
30
+ exports.startChainNode = require_start_chain_node.startChainNode;
31
+ exports.toResolverConfig = require_follower_config.toResolverConfig;
32
+ exports.verifyFollowerConfigAgainstUpstream = require_config_consistency.verifyFollowerConfigAgainstUpstream;