@ocap/chain-node 0.0.0-stage → 1.32.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +234 -2
- package/esm/access-log.d.mts +34 -0
- package/esm/access-log.mjs +71 -0
- package/esm/config-consistency.d.mts +59 -0
- package/esm/config-consistency.mjs +220 -0
- package/esm/env.d.mts +32 -0
- package/esm/env.mjs +218 -0
- package/esm/follower-config.d.mts +25 -0
- package/esm/follower-config.mjs +57 -0
- package/esm/index.d.mts +7 -0
- package/esm/index.mjs +7 -0
- package/esm/standalone-env.d.mts +92 -0
- package/esm/standalone-env.mjs +152 -0
- package/esm/start-chain-node.d.mts +14 -0
- package/esm/start-chain-node.mjs +1107 -0
- package/esm/test-hooks-token.d.mts +12 -0
- package/esm/test-hooks-token.mjs +21 -0
- package/esm/testing.d.mts +13 -0
- package/esm/testing.mjs +23 -0
- package/esm/types.d.mts +310 -0
- package/esm/types.mjs +1 -0
- package/lib/_virtual/rolldown_runtime.cjs +29 -0
- package/lib/access-log.cjs +73 -0
- package/lib/access-log.d.cts +34 -0
- package/lib/config-consistency.cjs +227 -0
- package/lib/config-consistency.d.cts +59 -0
- package/lib/env.cjs +221 -0
- package/lib/env.d.cts +32 -0
- package/lib/follower-config.cjs +63 -0
- package/lib/follower-config.d.cts +25 -0
- package/lib/index.cjs +32 -0
- package/lib/index.d.cts +7 -0
- package/lib/standalone-env.cjs +165 -0
- package/lib/standalone-env.d.cts +92 -0
- package/lib/start-chain-node.cjs +1116 -0
- package/lib/start-chain-node.d.cts +14 -0
- package/lib/test-hooks-token.cjs +24 -0
- package/lib/test-hooks-token.d.cts +12 -0
- package/lib/testing.cjs +23 -0
- package/lib/testing.d.cts +13 -0
- package/lib/types.cjs +0 -0
- package/lib/types.d.cts +310 -0
- package/package.json +78 -4
package/esm/env.d.mts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { ChainNodeRoleConfig, ILedgerLeaseOptions, RunningChainNode, ValidatorSignerConfig } from "./types.mjs";
|
|
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 };
|
package/esm/env.mjs
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import { CustomError } from "@ocap/util/lib/error";
|
|
2
|
+
import { normalizeDidForCompare, resolveConsensusProposer, resolveConsensusProposerFromSigner, resolveEnvWitnessWallet, resolveNodeRoleConfig } from "@arcblock/ledger-core";
|
|
3
|
+
import { resolveLedgerLeaseConfig } from "@arcblock/ledger-sqlite";
|
|
4
|
+
|
|
5
|
+
//#region src/env.ts
|
|
6
|
+
function parseOptionalPositiveInt(raw, label) {
|
|
7
|
+
const trimmed = (raw ?? "").trim();
|
|
8
|
+
if (!trimmed) return void 0;
|
|
9
|
+
if (!/^[1-9]\d*$/.test(trimmed)) throw new CustomError("INVALID_CONFIG", `Invalid ${label}="${raw}": expected a positive integer >= 1`);
|
|
10
|
+
const parsed = Number(trimmed);
|
|
11
|
+
if (!Number.isSafeInteger(parsed) || parsed < 1) throw new CustomError("INVALID_CONFIG", `Invalid ${label}="${raw}": expected a positive safe integer >= 1`);
|
|
12
|
+
return parsed;
|
|
13
|
+
}
|
|
14
|
+
function parseOptionalNonNegativeInt(raw, label) {
|
|
15
|
+
const trimmed = (raw ?? "").trim();
|
|
16
|
+
if (!trimmed) return void 0;
|
|
17
|
+
if (!/^(?:0|[1-9]\d*)$/.test(trimmed)) throw new CustomError("INVALID_CONFIG", `Invalid ${label}="${raw}": expected a non-negative integer >= 0`);
|
|
18
|
+
const parsed = Number(trimmed);
|
|
19
|
+
if (!Number.isSafeInteger(parsed) || parsed < 0) throw new CustomError("INVALID_CONFIG", `Invalid ${label}="${raw}": expected a non-negative safe integer >= 0`);
|
|
20
|
+
return parsed;
|
|
21
|
+
}
|
|
22
|
+
function parseBoolEnv(raw) {
|
|
23
|
+
const norm = (raw ?? "").trim().toLowerCase();
|
|
24
|
+
return norm === "1" || norm === "true";
|
|
25
|
+
}
|
|
26
|
+
function hasSigningSecretKey(signer) {
|
|
27
|
+
return Boolean(signer && typeof signer.secretKey === "string" && signer.secretKey.trim().length > 0);
|
|
28
|
+
}
|
|
29
|
+
function normalizeConsensusKeyType(rawValue) {
|
|
30
|
+
const trimmed = (rawValue ?? "").trim().toLowerCase();
|
|
31
|
+
if (!trimmed) return void 0;
|
|
32
|
+
if (trimmed === "ethereum") return "eth";
|
|
33
|
+
if (trimmed === "ed25519" || trimmed === "secp256k1" || trimmed === "eth") return trimmed;
|
|
34
|
+
throw new CustomError("INVALID_CONFIG", `Unsupported CHAIN_CONSENSUS_KEY_TYPE="${rawValue}": expected ed25519, secp256k1, or eth`);
|
|
35
|
+
}
|
|
36
|
+
function resolveSignerFromEnvRecord(env, explicitSigner) {
|
|
37
|
+
const keyType = normalizeConsensusKeyType(env.CHAIN_CONSENSUS_KEY_TYPE);
|
|
38
|
+
const secretKey = (env.CHAIN_CONSENSUS_SK ?? "").trim();
|
|
39
|
+
const address = (env.CHAIN_CONSENSUS_PROPOSER ?? "").trim();
|
|
40
|
+
if (!secretKey) {
|
|
41
|
+
if (keyType) throw new CustomError("INVALID_CONFIG", `CHAIN_CONSENSUS_KEY_TYPE (${env.CHAIN_CONSENSUS_KEY_TYPE}) requires CHAIN_CONSENSUS_SK to be set`);
|
|
42
|
+
if (address) {
|
|
43
|
+
if (!hasSigningSecretKey(explicitSigner) || normalizeDidForCompare(explicitSigner.address) !== normalizeDidForCompare(address)) throw new CustomError("INVALID_CONFIG", `CHAIN_CONSENSUS_PROPOSER (${env.CHAIN_CONSENSUS_PROPOSER}) requires a matching CHAIN_CONSENSUS_SK`);
|
|
44
|
+
}
|
|
45
|
+
return explicitSigner;
|
|
46
|
+
}
|
|
47
|
+
if (hasSigningSecretKey(explicitSigner)) return explicitSigner;
|
|
48
|
+
if (address) {
|
|
49
|
+
const resolved = resolveConsensusProposerFromSigner({
|
|
50
|
+
address,
|
|
51
|
+
secretKey,
|
|
52
|
+
...keyType ? { keyType } : {}
|
|
53
|
+
});
|
|
54
|
+
return {
|
|
55
|
+
address: resolved.address,
|
|
56
|
+
secretKey: resolved.secretKey,
|
|
57
|
+
publicKey: resolved.publicKey,
|
|
58
|
+
...keyType ? { keyType } : {}
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
const derived = resolveConsensusProposer({
|
|
62
|
+
moderator: { address: explicitSigner?.address || "" },
|
|
63
|
+
env: {
|
|
64
|
+
...env,
|
|
65
|
+
...keyType ? { CHAIN_CONSENSUS_KEY_TYPE: keyType } : {}
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
if (derived.secretKey) return {
|
|
69
|
+
address: derived.address,
|
|
70
|
+
secretKey: derived.secretKey,
|
|
71
|
+
publicKey: derived.publicKey,
|
|
72
|
+
...keyType ? { keyType } : {}
|
|
73
|
+
};
|
|
74
|
+
return explicitSigner;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Pure environment-to-role parser (`@ocap/chain-node`).
|
|
78
|
+
*
|
|
79
|
+
* Reads ONLY the explicitly supplied `env` dictionary — zero implicit `process.env` reads.
|
|
80
|
+
*/
|
|
81
|
+
function roleConfigFromEnv(env, options) {
|
|
82
|
+
if (!env || typeof env !== "object") throw new CustomError("INVALID_CONFIG", "roleConfigFromEnv requires an explicit env record");
|
|
83
|
+
const resolved = resolveNodeRoleConfig(env);
|
|
84
|
+
const allowPrivatePeers = parseBoolEnv(env.ALLOW_PRIVATE_PEER_URLS);
|
|
85
|
+
const explicitOrEnvSigner = resolveSignerFromEnvRecord(env, options?.signer);
|
|
86
|
+
if (resolved.role === "validator") {
|
|
87
|
+
if (!explicitOrEnvSigner) throw new CustomError("INVALID_CONFIG", "Validator role requires options.signer or explicit CHAIN_CONSENSUS_SK + CHAIN_CONSENSUS_PROPOSER in env");
|
|
88
|
+
if (resolved.consensusMode === "hotstuff") {
|
|
89
|
+
if (!hasSigningSecretKey(explicitOrEnvSigner)) throw new CustomError("INVALID_CONFIG", "HotStuff validator role requires a signing secretKey in options.signer or CHAIN_CONSENSUS_SK");
|
|
90
|
+
if (!resolved.consensusBindHost || resolved.consensusPort === null) throw new CustomError("INVALID_CONFIG", "HotStuff validator role requires CONSENSUS_BIND_HOST and CONSENSUS_PORT");
|
|
91
|
+
return {
|
|
92
|
+
kind: "hotstuff",
|
|
93
|
+
signer: explicitOrEnvSigner,
|
|
94
|
+
validators: resolved.hotstuffValidators,
|
|
95
|
+
...resolved.hotstuffQuorumThreshold !== void 0 ? { quorumThreshold: resolved.hotstuffQuorumThreshold } : {},
|
|
96
|
+
consensusBindHost: resolved.consensusBindHost,
|
|
97
|
+
consensusPort: resolved.consensusPort,
|
|
98
|
+
allowPublicConsensusBind: resolved.allowPublicConsensusBind,
|
|
99
|
+
writePolicy: resolved.writePolicy,
|
|
100
|
+
allowPrivatePeers,
|
|
101
|
+
retentionMode: resolved.retentionMode,
|
|
102
|
+
hotWindowEntries: resolved.hotWindowEntries,
|
|
103
|
+
hotWindowCheckpoints: resolved.hotWindowCheckpoints,
|
|
104
|
+
snapshotBaseUrl: resolved.snapshotBaseUrl,
|
|
105
|
+
witnessQuorum: resolved.witnessQuorum,
|
|
106
|
+
...resolved.trustedWitnesses !== void 0 ? { trustedWitnesses: resolved.trustedWitnesses } : {},
|
|
107
|
+
witnessSubmitUrls: resolved.witnessSubmitUrls
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
kind: "validator",
|
|
112
|
+
signer: explicitOrEnvSigner,
|
|
113
|
+
retentionMode: resolved.retentionMode,
|
|
114
|
+
hotWindowEntries: resolved.hotWindowEntries,
|
|
115
|
+
hotWindowCheckpoints: resolved.hotWindowCheckpoints,
|
|
116
|
+
snapshotBaseUrl: resolved.snapshotBaseUrl,
|
|
117
|
+
witnessQuorum: resolved.witnessQuorum,
|
|
118
|
+
...resolved.trustedWitnesses !== void 0 ? { trustedWitnesses: resolved.trustedWitnesses } : {},
|
|
119
|
+
witnessSubmitUrls: resolved.witnessSubmitUrls,
|
|
120
|
+
anchorWebhookUrl: resolved.anchorWebhookUrl
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
const pollIntervalMs = parseOptionalPositiveInt(env.FOLLOWER_POLL_INTERVAL_MS, "FOLLOWER_POLL_INTERVAL_MS");
|
|
124
|
+
const maxSyncLag = parseOptionalNonNegativeInt(env.FOLLOWER_MAX_SYNC_LAG, "FOLLOWER_MAX_SYNC_LAG");
|
|
125
|
+
const maxUpstreamStaleMs = parseOptionalPositiveInt(env.FOLLOWER_MAX_UPSTREAM_STALE_MS, "FOLLOWER_MAX_UPSTREAM_STALE_MS");
|
|
126
|
+
const witnessWallet = resolveEnvWitnessWallet(env) ?? void 0;
|
|
127
|
+
const snapshotPrefix = (env.SNAPSHOT_S3_PREFIX ?? "").trim() || void 0;
|
|
128
|
+
const disallowKeylessCascadedUpstream = parseBoolEnv(env.DISALLOW_KEYLESS_CASCADED_UPSTREAM);
|
|
129
|
+
return {
|
|
130
|
+
kind: "follower",
|
|
131
|
+
runtimeRole: resolved.role === "standby" ? "standby" : "follower",
|
|
132
|
+
writePolicy: resolved.writePolicy,
|
|
133
|
+
upstreamChainUrl: resolved.upstreamChainUrl,
|
|
134
|
+
clusterPeerUrls: resolved.clusterPeerUrls,
|
|
135
|
+
snapshotBaseUrl: resolved.snapshotBaseUrl,
|
|
136
|
+
...snapshotPrefix ? { snapshotPrefix } : {},
|
|
137
|
+
trustedProposer: resolved.trustedProposer,
|
|
138
|
+
trustedProposerPublicKey: resolved.trustedProposerPublicKey,
|
|
139
|
+
...resolved.hotstuffValidators.length > 0 ? { hotstuffValidators: resolved.hotstuffValidators } : {},
|
|
140
|
+
...resolved.hotstuffQuorumThreshold !== void 0 ? { hotstuffQuorumThreshold: resolved.hotstuffQuorumThreshold } : {},
|
|
141
|
+
allowPrivatePeers,
|
|
142
|
+
disallowKeylessCascadedUpstream,
|
|
143
|
+
allowUnauthenticatedBootstrap: resolved.allowUnauthenticatedBootstrap,
|
|
144
|
+
syncMode: resolved.syncMode,
|
|
145
|
+
...pollIntervalMs !== void 0 ? { pollIntervalMs } : {},
|
|
146
|
+
...maxSyncLag !== void 0 ? { maxSyncLag } : {},
|
|
147
|
+
...maxUpstreamStaleMs !== void 0 ? { maxUpstreamStaleMs } : {},
|
|
148
|
+
retentionMode: resolved.retentionMode,
|
|
149
|
+
hotWindowEntries: resolved.hotWindowEntries,
|
|
150
|
+
hotWindowCheckpoints: resolved.hotWindowCheckpoints,
|
|
151
|
+
...witnessWallet ? { witnessWallet } : {},
|
|
152
|
+
witnessSubmitUrls: resolved.witnessSubmitUrls,
|
|
153
|
+
...hasSigningSecretKey(explicitOrEnvSigner) ? { signer: explicitOrEnvSigner } : {}
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Pure environment-to-SQLite-writer-lease parser (`@ocap/chain-node`).
|
|
158
|
+
*
|
|
159
|
+
* Reads ONLY the explicitly supplied `env` dictionary — zero implicit `process.env` reads.
|
|
160
|
+
*/
|
|
161
|
+
function leaseConfigFromEnv(env) {
|
|
162
|
+
if (!env || typeof env !== "object") throw new CustomError("INVALID_CONFIG", "leaseConfigFromEnv requires an explicit env record");
|
|
163
|
+
const parsed = resolveLedgerLeaseConfig(env);
|
|
164
|
+
if (!parsed.enabled) return false;
|
|
165
|
+
return {
|
|
166
|
+
enabled: true,
|
|
167
|
+
autoAcquire: true,
|
|
168
|
+
holderId: parsed.holderId,
|
|
169
|
+
ttlMs: parsed.ttlMs,
|
|
170
|
+
startupWaitMs: parsed.startupWaitMs
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Install idempotent `SIGTERM` / `SIGINT` graceful shutdown handlers for a running chain node.
|
|
175
|
+
* Returns a cleanup callback that removes the signal listeners.
|
|
176
|
+
*/
|
|
177
|
+
function installProcessSignalHandlers(node, options) {
|
|
178
|
+
const timeoutMs = typeof options?.timeoutMs === "number" && Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : 15e3;
|
|
179
|
+
const signals = options?.signals ?? ["SIGTERM", "SIGINT"];
|
|
180
|
+
const exitProcess = options?.exitProcess !== false;
|
|
181
|
+
const log = options?.logger ?? console;
|
|
182
|
+
let shuttingDown = false;
|
|
183
|
+
const handleSignal = (signal) => {
|
|
184
|
+
if (shuttingDown) return;
|
|
185
|
+
shuttingDown = true;
|
|
186
|
+
log.info(`\n${signal} received, shutting down chain node gracefully...`);
|
|
187
|
+
const forceTimer = setTimeout(() => {
|
|
188
|
+
log.error("Chain node graceful shutdown timed out, forcing exit");
|
|
189
|
+
options?.onExit?.(1);
|
|
190
|
+
if (exitProcess) process.exit(1);
|
|
191
|
+
}, timeoutMs);
|
|
192
|
+
if (typeof forceTimer.unref === "function") forceTimer.unref();
|
|
193
|
+
node.stop().then(() => {
|
|
194
|
+
clearTimeout(forceTimer);
|
|
195
|
+
log.info("Chain node graceful shutdown complete");
|
|
196
|
+
options?.onExit?.(0);
|
|
197
|
+
if (exitProcess) process.exit(0);
|
|
198
|
+
}).catch((err) => {
|
|
199
|
+
clearTimeout(forceTimer);
|
|
200
|
+
log.error("Error during chain node graceful shutdown:", err);
|
|
201
|
+
options?.onExit?.(1);
|
|
202
|
+
if (exitProcess) process.exit(1);
|
|
203
|
+
});
|
|
204
|
+
};
|
|
205
|
+
const listeners = /* @__PURE__ */ new Map();
|
|
206
|
+
for (const sig of signals) {
|
|
207
|
+
const listener = () => handleSignal(sig);
|
|
208
|
+
listeners.set(sig, listener);
|
|
209
|
+
process.on(sig, listener);
|
|
210
|
+
}
|
|
211
|
+
return () => {
|
|
212
|
+
for (const [sig, listener] of listeners) process.off(sig, listener);
|
|
213
|
+
listeners.clear();
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
//#endregion
|
|
218
|
+
export { installProcessSignalHandlers, leaseConfigFromEnv, roleConfigFromEnv };
|
|
@@ -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
ADDED
|
@@ -0,0 +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";
|
|
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";
|
|
4
|
+
import { InstallProcessSignalHandlersOptions, installProcessSignalHandlers, leaseConfigFromEnv, roleConfigFromEnv } from "./env.mjs";
|
|
5
|
+
import { isCompleteChainConfig, rehydrateFollowerChainConfig, toResolverConfig } from "./follower-config.mjs";
|
|
6
|
+
import { startChainNode } from "./start-chain-node.mjs";
|
|
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
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { CONSENSUS_CONFIG_KEYS, diffConsensusConfig, fetchUpstreamChainConfig, formatConfigDifferences, normalizeConsensusConfig, verifyFollowerConfigAgainstUpstream } from "./config-consistency.mjs";
|
|
2
|
+
import { installProcessSignalHandlers, leaseConfigFromEnv, roleConfigFromEnv } from "./env.mjs";
|
|
3
|
+
import { isCompleteChainConfig, rehydrateFollowerChainConfig, toResolverConfig } from "./follower-config.mjs";
|
|
4
|
+
import { startChainNode } from "./start-chain-node.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";
|
|
6
|
+
|
|
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 };
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
//#region src/standalone-env.d.ts
|
|
2
|
+
type Env = Record<string, string | undefined>;
|
|
3
|
+
/**
|
|
4
|
+
* Standalone replacement for the Blocklet Server app DID that seeds the trusted-storage wallet.
|
|
5
|
+
* Returns '' when unset/blank so callers fall back to BLOCKLET_APP_PID / BLOCKLET_APP_ID / moderator exactly as
|
|
6
|
+
* before. The subject is hashed as a raw string by `fromAppDid`, so a `did:abt:` prefix or a typo would silently
|
|
7
|
+
* yield a different trusted key: only a bare, valid DID address is accepted.
|
|
8
|
+
*/
|
|
9
|
+
declare function resolveTrustedSubject(env?: Env): string;
|
|
10
|
+
/**
|
|
11
|
+
* Standalone-only replacements for Blocklet Server variables. Blocklet Server sets none of them on beta or main
|
|
12
|
+
* (checked against both live process envs), so seeing one means the operator runs (or migrates to) a standalone
|
|
13
|
+
* env file. `CHAIN_VAULT_PSK` is deliberately not a marker: main's blocklet.yml declares it, so it is present there.
|
|
14
|
+
*/
|
|
15
|
+
declare const STANDALONE_ENV_MARKERS: readonly string[];
|
|
16
|
+
/** Blocklet Server variables both chain apps still read as fallbacks behind a CHAIN_* variable. */
|
|
17
|
+
declare const BLOCKLET_ENV_CHAIN_FALLBACKS: ReadonlySet<string>;
|
|
18
|
+
interface BlockletEnvLeftovers {
|
|
19
|
+
standaloneMarkers: string[];
|
|
20
|
+
leftovers: string[];
|
|
21
|
+
readByChain: string[];
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Detect a standalone env that still carries Blocklet Server variables, so two key sources are never mixed
|
|
25
|
+
* silently. Returns null under Blocklet Server (no standalone marker) and for a clean standalone env.
|
|
26
|
+
* Only variable names are returned, never values.
|
|
27
|
+
*/
|
|
28
|
+
declare function findBlockletEnvLeftovers(env?: Env, {
|
|
29
|
+
readByChain
|
|
30
|
+
}?: {
|
|
31
|
+
readByChain?: Iterable<string>;
|
|
32
|
+
}): BlockletEnvLeftovers | null;
|
|
33
|
+
declare function formatBlockletEnvLeftoversWarning({
|
|
34
|
+
standaloneMarkers,
|
|
35
|
+
leftovers,
|
|
36
|
+
readByChain
|
|
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;
|
|
91
|
+
//#endregion
|
|
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 };
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { isValid } from "@arcblock/did";
|
|
2
|
+
|
|
3
|
+
//#region src/standalone-env.ts
|
|
4
|
+
/**
|
|
5
|
+
* Standalone (non-Blocklet-Server) env helpers shared by the chain apps (#1923, docs/ops/chain-env-mapping.md).
|
|
6
|
+
*
|
|
7
|
+
* Kept free of runtime imports beyond `@arcblock/did` so app key-derivation code can require this module
|
|
8
|
+
* (`@ocap/chain-node/lib/standalone-env.js`) without loading the node runtime.
|
|
9
|
+
*/
|
|
10
|
+
/**
|
|
11
|
+
* Standalone replacement for the Blocklet Server app DID that seeds the trusted-storage wallet.
|
|
12
|
+
* Returns '' when unset/blank so callers fall back to BLOCKLET_APP_PID / BLOCKLET_APP_ID / moderator exactly as
|
|
13
|
+
* before. The subject is hashed as a raw string by `fromAppDid`, so a `did:abt:` prefix or a typo would silently
|
|
14
|
+
* yield a different trusted key: only a bare, valid DID address is accepted.
|
|
15
|
+
*/
|
|
16
|
+
function resolveTrustedSubject(env = process.env) {
|
|
17
|
+
const subject = String(env.CHAIN_TRUSTED_SUBJECT || "").trim();
|
|
18
|
+
if (!subject) return "";
|
|
19
|
+
if (/^did:/i.test(subject) || !isValid(subject)) throw new Error("Invalid CHAIN_TRUSTED_SUBJECT: must be a bare DID address (no \"did:abt:\" prefix)");
|
|
20
|
+
return subject;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Standalone-only replacements for Blocklet Server variables. Blocklet Server sets none of them on beta or main
|
|
24
|
+
* (checked against both live process envs), so seeing one means the operator runs (or migrates to) a standalone
|
|
25
|
+
* env file. `CHAIN_VAULT_PSK` is deliberately not a marker: main's blocklet.yml declares it, so it is present there.
|
|
26
|
+
*/
|
|
27
|
+
const STANDALONE_ENV_MARKERS = [
|
|
28
|
+
"CHAIN_DATA_DIR",
|
|
29
|
+
"CHAIN_PORT",
|
|
30
|
+
"CHAIN_SK",
|
|
31
|
+
"CHAIN_MODERATOR_PK",
|
|
32
|
+
"CHAIN_TRUSTED_SUBJECT"
|
|
33
|
+
];
|
|
34
|
+
/** Blocklet Server variables both chain apps still read as fallbacks behind a CHAIN_* variable. */
|
|
35
|
+
const BLOCKLET_ENV_CHAIN_FALLBACKS = new Set([
|
|
36
|
+
"BLOCKLET_APP_ASK",
|
|
37
|
+
"BLOCKLET_APP_DIR",
|
|
38
|
+
"BLOCKLET_APP_ID",
|
|
39
|
+
"BLOCKLET_APP_PID",
|
|
40
|
+
"BLOCKLET_APP_PK",
|
|
41
|
+
"BLOCKLET_APP_PPK",
|
|
42
|
+
"BLOCKLET_APP_PSK",
|
|
43
|
+
"BLOCKLET_APP_SK",
|
|
44
|
+
"BLOCKLET_DATA_DIR",
|
|
45
|
+
"BLOCKLET_PORT"
|
|
46
|
+
]);
|
|
47
|
+
/**
|
|
48
|
+
* Detect a standalone env that still carries Blocklet Server variables, so two key sources are never mixed
|
|
49
|
+
* silently. Returns null under Blocklet Server (no standalone marker) and for a clean standalone env.
|
|
50
|
+
* Only variable names are returned, never values.
|
|
51
|
+
*/
|
|
52
|
+
function findBlockletEnvLeftovers(env = process.env, { readByChain = BLOCKLET_ENV_CHAIN_FALLBACKS } = {}) {
|
|
53
|
+
const isSet = (k) => String(env[k] ?? "").trim() !== "";
|
|
54
|
+
const standaloneMarkers = STANDALONE_ENV_MARKERS.filter(isSet);
|
|
55
|
+
if (!standaloneMarkers.length) return null;
|
|
56
|
+
const leftovers = Object.keys(env).filter((k) => /^(BLOCKLET_|ABT_NODE_)/.test(k) && isSet(k)).sort();
|
|
57
|
+
if (!leftovers.length) return null;
|
|
58
|
+
const read = new Set(readByChain);
|
|
59
|
+
return {
|
|
60
|
+
standaloneMarkers,
|
|
61
|
+
leftovers,
|
|
62
|
+
readByChain: leftovers.filter((k) => read.has(k))
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
function formatBlockletEnvLeftoversWarning({ standaloneMarkers, leftovers, readByChain }) {
|
|
66
|
+
const read = readByChain.length ? ` ${readByChain.join(", ")} still feed key/path fallbacks when the CHAIN_* equivalent is unset.` : "";
|
|
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
|
+
}
|
|
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
|
+
}
|
|
150
|
+
|
|
151
|
+
//#endregion
|
|
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 };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { ChainNodeTestHooks, ChainProfile, RunningChainNode, StartChainNodeOptions } from "./types.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/start-chain-node.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Boot a unified OCAP chain node (`validator`, `follower`, or `hotstuff`) with a 12-step LIFO rollback guard
|
|
7
|
+
* and 9-step reverse graceful shutdown (`docs/chain-node-design.md` §2.3–§2.4).
|
|
8
|
+
*/
|
|
9
|
+
declare function startChainNode(options: StartChainNodeOptions): Promise<RunningChainNode>;
|
|
10
|
+
declare function startChainNode(profile: ChainProfile & {
|
|
11
|
+
testHooks?: ChainNodeTestHooks;
|
|
12
|
+
}): Promise<RunningChainNode>;
|
|
13
|
+
//#endregion
|
|
14
|
+
export { startChainNode };
|