@ocap/chain-node
v1.33.8
Published
Unified OCAP chain node runtime assembly (Validator, Standby, Keyless Follower)
Readme
@ocap/chain-node
@ocap/chain-node is the single canonical runtime assembly layer for OCAP blockchain nodes (validator, standby, keyless follower, and hotstuff). It owns deterministic storage boot, snapshot trust-anchor bootstrap, role runtime wiring, Express HTTP + WebSocket mounting, fail-closed NODE_HALTED enforcement, and ordered graceful shutdown.
For full architectural rationale and design history, see docs/chain-node-design.md.
Responsibilities & Boundaries
Owned by @ocap/chain-node
- Storage & single-writer lease lifecycle:
SqliteLedgerStorage(SqliteSingleWriterLease),SqliteTrustedStorage(trusted.sqlite),SqliteStateDB(statedb.sqlite),SqliteIndexDB(indexdb.sqlite),NodePreferencesManager,INodeMaintenanceController, andBlacklist(filter.json). - Role-specific consensus & replication runtimes:
- Single-validator
Ledgercheckpointing (periodicTimer+ witness quorum policy). - Follower snapshot bootstrap (
prepareFollowerDataDirectory),FollowerSyncService, single-hopLeaderRouter(writePolicy: 'forward'), and monotonic follower high-water mark persistence. - Multi-validator
HotStuffNodeRuntime+SqliteHotStuffStateStorewith split consensus listener isolation (/consensusreturns404on the public HTTP port).
- Single-validator
OCAPResolverorchestration: Deferred initialization (deferInitialize: true), keyless followerstatedbchain-config rehydration without mutatingprocess.env, and Promise-based startup validation (never callingprocess.exit()from library code).- HTTP + WebSocket server assembly: CORS, shutdown fence (
503+Connection: close), active HTTP response tracking, Socket.IO (createSocketHandler), REST/api(createAPIHandler),/node(createNodeDashboardRouter), optional/dashboardand/node/explorer, and/GraphQL (createHttpHandler, serving/,/api, and/api/gql). - Fail-closed
NODE_HALTEDgate: Blocks all non-diagnostic GraphQL operations (CustomError('NODE_HALTED', 'Chain node is halted fail-closed')) and returns HTTP503({ code: 'NODE_HALTED', halted: true },Cache-Control: no-store) on/api/ledger/status,/api/follower/status, and non-diagnostic/api/*data endpoints whenever the underlying runtime halts. - LIFO partial-boot rollback & 9-step reverse graceful shutdown.
Explicitly Kept Out of @ocap/chain-node
.envfile loading & implicitprocess.envreads:startChainNodenever readsprocess.envfor configuration (the sole environment check is rejectingtestHookswhenprocess.env.NODE_ENV === 'production'). Callers parse env vars explicitly or pass an env dictionary into pure helpers (roleConfigFromEnv(env),leaseConfigFromEnv(env)).- Secret-key / mnemonic derivation: Callers construct
ChainNodeSignerConfig(ed25519,secp256k1, oreth) before callingstartChainNode. - Pre-Resolver immutable chain-config merging: Application-specific
applyImmutable/checkChainImmutableslogic (for examplebridge/ocap-node/src/immutable.ts) runs before passingchainConfigintostartChainNode. - Application-specific HTTP/admin routes: Mounted by the caller via
profile.configureApp(app, ctx). - Telemetry SDKs & optional index pruning packages:
@sentry/*stays in application entrypoints;@ocap/indexdb-pruneis injected viaprofile.maintenance.pruneIndexDbFnrather than hard-depended on by@ocap/chain-node. - Global process signal handlers:
startChainNodedoes not bindprocess.on('SIGINT' | 'SIGTERM')automatically; CLI entrypoints opt in viainstallProcessSignalHandlers(node, options?).
Exports & Configuration Surface
Main Entrypoint (@ocap/chain-node)
import {
installProcessSignalHandlers,
leaseConfigFromEnv,
roleConfigFromEnv,
startChainNode,
type ChainNodeRoleConfig,
type ChainProfile,
type RunningChainNode,
} from '@ocap/chain-node';startChainNode(profile)/startChainNode({ profile, testHooks }): Boots a chain node and resolves to aRunningChainNodehandle (endpoint,rpcUrl,wsUrl,port,host,chainId,role,nodeId,dataDir,proposerDid,proposerPublicKey,signatureKeyType,app,server,ledger,ledgerStorage,statedb,trustedStorage,indexdb,resolver,followerSync,hotstuffRuntime,preferencesManager,maintenanceController,ledgerHealth(),advanceClock?(seconds),restart(nextProfile?),stop()).roleConfigFromEnv(env, { signer? }): Pure parser mapping explicitenvkeys (CHAIN_ROLE/CHAIN_MODE,CONSENSUS_MODE,CHAIN_CONSENSUS_SK+CHAIN_CONSENSUS_PROPOSER+CHAIN_CONSENSUS_KEY_TYPE,CHAIN_WRITE_POLICY,ALLOW_PRIVATE_PEER_URLS,DISALLOW_KEYLESS_CASCADED_UPSTREAM,FOLLOWER_POLL_INTERVAL_MS,FOLLOWER_MAX_SYNC_LAG,FOLLOWER_MAX_UPSTREAM_STALE_MS,CONSENSUS_BIND_HOST,CONSENSUS_PORT,HOTSTUFF_VALIDATORS,HOTSTUFF_QUORUM_THRESHOLD, witness variables) into a typedChainNodeRoleConfig.leaseConfigFromEnv(env): Pure parser mapping explicitenvkeys (LEDGER_WRITER_LEASE,LEDGER_WRITER_LEASE_TTL_MS,LEDGER_WRITER_LEASE_STARTUP_WAIT_MS,CHAIN_LEASE_HOLDER_ID) intoILedgerLeaseOptions | false.loadChainEnvFiles(env, { uid? }),applyChainConfigToEnv(target, loaded),chainRuntimeEnv(base, loaded),readChainEnvFile(path, { kind })(also@ocap/chain-node/lib/env-files.js, dependency-free): strictCHAIN_SECRETS_FILE/CHAIN_CONFIG_FILEloader (#2076; regular 0600 file of the process uid, listed names only, no name also set in the env). Config values go toprocess.env; secrets only into the runtime env copy. See docs/ops/chain-env-mapping.md#secrets-and-config-files.installProcessSignalHandlers(node, options?): Attaches idempotentSIGTERM/SIGINThandlers that invokenode.stop()and returns anuninstall()disposer.
ChainProfile & Node Roles
interface ChainProfileBase {
nodeId?: string; // defaults to persisted <dataDir>/.node-id
dataDir: string;
http: {
host?: string; // defaults to '127.0.0.1'
port: number; // 0 binds an OS-assigned ephemeral port (preserved across node.restart())
corsOrigins?: string | string[] | boolean;
drainTimeoutMs?: number; // HTTP active-response drain timeout on stop() (default: 5000ms)
enableDashboard?: boolean;
enableExplorer?: boolean;
explorerDistDir?: string;
enableAccessLog?: boolean;
adminEnv?: Record<string, string | undefined>;
onGraphqlError?: (err: Error & { originalError?: Error }) => void;
};
storage?: ChainProfileBase['storage'];
checkpoint?: {
batchSize?: number;
timeoutMs?: number;
auto?: boolean;
periodicTimer?: boolean;
timerIntervalMs?: number;
};
da?: ChainProfileBase['da'];
blacklist?: ChainProfileBase['blacklist'];
txQueue?: ChainProfileBase['txQueue'];
maintenance?: ChainProfileBase['maintenance'];
validateTokenConfig?: boolean;
logger?: IPipelineLogger;
configureApp?: (app: Express, ctx: ChainAppHookContext) => void | Promise<void>;
}| Role (role.kind) | Signer | chainConfig | Write Behavior & Runtime Semantics |
| --- | --- | --- | --- |
| 'validator' | Required (ed25519 | secp256k1 | eth) | Required | Single-validator leader. Executes transactions, seals signed checkpoints (batchSize / timeoutMs + optional periodicTimer), and enforces witnessQuorum / trustedWitnesses when configured. |
| 'follower' (keyless, default runtimeRole: 'follower') | Omitted | Optional (rehydrated from statedb.sqlite) | Read-scaling / Sentinel verification node. Bootstraps from a signed snapshot, runs FollowerSyncService against upstreamChainUrl, and enforces writePolicy: 'reject' (FOLLOWER_READ_ONLY) or 'forward' (single-hop LeaderRouter proxy to upstreamChainUrl). Auto-generates <dataDir>/.follower-trusted.key (0600) for local trusted.sqlite MAC verification. |
| 'follower' (runtimeRole: 'standby') | Required | Optional / Partial | Consensus standby follower. Runs FollowerSyncService with validator identity keys loaded; merges .follower-trusted.key into legacyTrustedSecretKeys so promoting a former keyless follower data directory preserves trusted.sqlite readability. |
| 'hotstuff' | Required | Required | Multi-validator HotStuff BFT consensus node (HotStuffNodeRuntime + SqliteHotStuffStateStore + dedicated consensusBindHost:consensusPort listener). |
Trust-Anchor & Snapshot Bootstrap Contract
Keyless followers and standby nodes never trust an unverified upstream stream:
- Lease-first safety: If
<dataDir>/ledger.sqlitealready exists on disk,startChainNodeacquires theSqliteSingleWriterLeasebeforeprepareFollowerDataDirectoryinspects or mutates any files, ensuring a duplicate concurrent boot fails immediately withLEDGER_LEASE_HELD. - Signed snapshot verification (
prepareFollowerDataDirectory):- Downloads
latest-snapshot.json, signedmanifest.json,SHA256SUMS,statedb.sqlite.zst, andledger.sqlite.zstfromsnapshotBaseUrl(protected by SSRF private-IP filtering unlessallowPrivatePeers: trueis explicitly set in local harnesses). - Verifies the snapshot
manifest.jsonsignature against the pinnedtrustedProposer/trustedProposerPublicKey(and optionalhotstuffValidators) before decompressing archives. - Verifies
.zstSHA-256 checksums againstSHA256SUMS, decompressesstatedb.sqliteandledger.sqlite, verifies checkpoint signatures insideledger.sqlite, and writes<dataDir>/.follower-bootstrap.json(0600) recordingchainId,snapshotSequence,checkpointHeight,checkpointHash,stateCommitHash,proposer,proposerPublicKey,bootstrappedAt,lastKnownSequence, andlastKnownCheckpointHeight. - Cold follower boot without an existing bootstrapped DB and without
snapshotBaseUrlfails closed; tampered manifests,.zstarchives, or mismatchedtrustedProposerPublicKeyabort startup beforeOCAPResolveropens.
- Downloads
- Anti-cascading upstream guard (
disallowKeylessCascadedUpstream):- When enabled (
trueon Sentinel verification followers),FollowerSyncServiceverifies/api/ledger/statusupstream signatures and refuses to sync from another keyless/unauthenticated follower, requiring a cryptographic'validator'upstream.
- When enabled (
- Fail-closed
NODE_HALTED:- If
FollowerSyncServiceorLedgerEntryReplayerdetects an offlinestatedb.sqlitetamper,stateRootmismatch against a verified checkpoint, or unrecoverable upstream divergence, it transitions tohalted = true. - Once halted, all non-diagnostic GraphQL queries/mutations throw
CustomError('NODE_HALTED', 'Chain node is halted fail-closed')and/api/ledger/status,/api/follower/status, and non-diagnostic/api/*data endpoints return HTTP503with{ code: 'NODE_HALTED', halted: true }(Cache-Control: no-store).
- If
Deterministic Boot & Shutdown Order
12-Step Boot Sequence (with LIFO Rollback)
Every resource opened during startChainNode pushes a cleanup closure onto a LIFO rollback stack. If any step throws, all previously opened resources are closed in reverse order and SqliteSingleWriterLease is released before the Promise rejects:
- Validate
testHookstoken (FORBIDDEN_IN_PRODUCTIONinNODE_ENV=production), verifydataDiris not a symlink (assertSafeNonSymlinkDirectory), and validateChainNodeRoleConfig. - Load or atomically persist
<dataDir>/.node-id(0600). - Resolve consensus proposer identity (
ed25519,secp256k1, oreth) purely in memory without mutatingprocess.env. - For
role.kind === 'follower', acquire pre-existing ledger writer lease if present, runprepareFollowerDataDirectory, and provision.follower-trusted.keywhen keyless. - Initialize writable
SqliteLedgerStorage(ledger.sqlite) and acquireSqliteSingleWriterLease. - On a SigningBox validator started with
storage.trustedKeyMigration(TRUSTED_KEY_MIGRATION*, #2140), re-signtrusted.sqliteonce between the local trusted sub-key and the lease key (backup first; seedocs/ops/chain-env-mapping.md#trusted-storage-key-migration-2140). Then openSqliteTrustedStorage(trusted.sqlite), openSqliteStateDB(statedb.sqlite), rehydrateIChainConfigfromstatedbfor keyless followers, and initializeLedger(wiring logical clock + periodic checkpoint timer). - Initialize
SqliteIndexDB(indexdb.sqlite),NodePreferencesManager, andBlacklist(filter.json). - Initialize
OCAPResolver(deferInitialize: true,skipInitializeStateDB: trueon followers). - Wire role runtime (
FollowerSyncService+ optionalLeaderRouter+ initialrebuildIndex()/ orphan replay for followers;HotStuffNodeRuntime+SqliteHotStuffStateStorefor HotStuff). - Start background sync/consensus loops (
followerSync.start()orhotstuffRuntime.start()). - Assemble Express + Socket.IO HTTP server and bind
http.host:http.port(no globalexpress.json()is mounted so route-specific body limits like the 256 KB/api/ledger/witness/attestationsendpoint remain intact). - Run optional
testHooks.onAfterBootand returnRunningChainNode.
Access log and client IP (#1922)
http.enableAccessLog (CHAIN_ACCESS_LOG=1 in the apps) writes one line per finished response through the
profile logger, in a fixed positional format:
[access] <method> <path> <status> <ms>ms <bytes> <clientIp> <host> <cfRay> "<userAgent>"
[access] POST /api 200 12ms 1834 203.0.113.7 main.abtnetwork.io 8f1c2d3e4a5b6c7d-SJC "ArcWallet/5.10.9 (iOS 18.1)"bytes is the response body size. Missing values are -. All fields except the user agent are free of whitespace
(whitespace, ", \ and control characters are %-encoded); the user agent is last and quoted with ", \ and
control characters escaped, so a client cannot end the line or forge a field. The app's logger may put a prefix before
[access] (qldb-chain-api prints [chain] [access] …), so count fields from the [access] token, not from the
start of the line: sed -n 's/.*\[access\] //p' | awk '{print $6}' is the client IP ($3 status, $4 duration).
The client IP is resolved by @ocap/util/lib/client-ip and is the same value the GraphQL context
(ctx.request.ip), the slow-request log and the admin auth failure limiter use:
- the trusted proxy headers in
CHAIN_CLIENT_IP_HEADERSorder — only when the TCP peer is a loopback address, and only when the value is a bare IP literal; - otherwise
req.ip(equal to the socket address unless the app setstrust proxy), then the socket address. A socket whose address is gone (the client reset the connection) counts as an unknown peer: headers are ignored.
CHAIN_CLIENT_IP_HEADERS (comma-separated, ordered; none or empty trusts no header):
| Deployment | Value | Why |
|---|---|---|
| Blocklet Server nginx (default) | unset = x-real-ip | nginx sets X-Real-IP $remote_addr but passes a client-supplied CF-Connecting-IP through, so trusting cf-connecting-ip there would let a client pick its own IP |
| Cloudflare Tunnel (cloudflared on the same host) | cf-connecting-ip | see below; must be set explicitly |
Why cf-connecting-ip can be trusted under the tunnel: the chain process listens on 127.0.0.1 only and is reached
through the cloudflared daemon on the same host (#1875 decision E4). Cloudflare's edge sets cf-connecting-ip to the
real client address, and a request that already carries its own cf-connecting-ip is rejected at the edge (403,
error 1000); a client's x-real-ip did not reach the origin either (both checked with a local quick tunnel on
2026-11-19). If the tunnel opt-in is forgotten, the default x-real-ip is absent and every request resolves to
127.0.0.1: one shared bucket and a useless log column, but nothing a client can spoof. cloudflared forwards the
original Host header unchanged (unless an ingress rule sets originRequest.httpHostHeader), so the same-origin
check of mutating admin session requests keeps working.
Limits of the loopback rule: any process on the same host can connect over loopback and set any client IP (a
builder host runs ~30 other blocklets); that is accepted by #1875 E4. A non-loopback peer talks to the process
directly (e.g. a node bound to 0.0.0.0), so its headers are its own claim and are ignored.
The admin auth failure limiter (createAdminAuthGuard, 10 failures per minute) buckets by this client IP. A correct
token is compared before the limiter is consulted, so the limiter never locks out a correct token, not even from a
rate-limited address. What a shared bucket breaks is fairness: when every request appears as 127.0.0.1 (the tunnel
without the opt-in, or any proxy without a trusted header), one client's wrong guesses rate-limit everyone else's
mistyped attempts. Resolving the real client restores per-client buckets.
WebSocket per-IP connection limits (@arcblock/ws, 64 per IP) use their own setting: set WS_TRUST_PROXY=1 with
WS_TRUSTED_PROXIES=127.0.0.1/32,::1/128, or every subscriber behind the tunnel counts against one address.
9-Step Reverse Graceful Shutdown (node.stop())
- Stop
followerSync/hotstuffRuntimebackground loops and clear maintenance/HWM timers. - Flip
isShuttingDown = true(new HTTP requests receive503+Connection: close), close idle keep-alive sockets, and wait up tohttp.drainTimeoutMs(5000msdefault) foractiveResponses === 0before callingserver.close()(preventing Socket.IO/WsServer.attachcloseAllConnections()from resetting in-flight responses). - Close the HTTP + WebSocket listener (
server.close()). - Call
resolver.shutdown()(drains in-flight pre-flights, transaction queue, andflushIndexWrites()). - Demote ledger role (
ledger.setNodeRole('readonly')) to fence new writes and periodic checkpoint timers. - Dispose
Blacklistfile watchers (filter.dispose()). - Close
statedbandtrustedStorage. - Close
indexdband flush final follower high-water mark. - In
finally, callledger.close()to drain any in-flight checkpoint and releaseSqliteSingleWriterLeaselast.
Extension & Test Injection Hooks
Application Hook (profile.configureApp)
configureApp(app, ctx) runs after CORS and the shutdown fence, and before /api, /node, and / GraphQL. Handlers receive ChainAppHookContext (nodeId, dataDir, role, config, statedb, indexdb, ledger, resolver, preferencesManager, maintenanceController).
Because @ocap/chain-node intentionally avoids mounting a global express.json(), any custom POST/PUT route registered inside configureApp should attach route-scoped body parsing (for example app.post('/admin/foo', express.json({ limit: '64kb' }), handler)).
Non-Production Test Hooks (@ocap/chain-node/testing)
Deterministic fault-injection and clock hooks live behind a dedicated subpath export:
import { startChainNode } from '@ocap/chain-node';
import { createChainNodeTestHooks } from '@ocap/chain-node/testing';
const testHooks = createChainNodeTestHooks({
initialClockOffsetSeconds: 0,
followerSync: { startPaused: true },
});
const node = await startChainNode({ profile, testHooks });
node.advanceClock?.(120);- Unforgeable capability:
createChainNodeTestHooksstamps objects with a private module-scopedSymbol('@ocap/chain-node/test-hooks-token')(notSymbol.for), so test hooks cannot be injected via JSON configs, CLI flags, or environment variables. - Production hard block: Passing
testHooksor callingcreateChainNodeTestHookswhenprocess.env.NODE_ENV === 'production'immediately throwsCustomError('FORBIDDEN_IN_PRODUCTION', ...).
Relationship to OCAP Packages & Applications
bridge/ocap-node(@arcblock/bridge-ocap-node): Migrated onto@ocap/chain-node(#1812). WrapsstartChainNodewith bridge rollup immutable state (bridge/ocap-node/src/immutable.ts) and exposes a CLI supporting both--role validatorand keyless--role follower(--write-policy reject|forward,--upstream,--snapshot-base-url,--trusted-proposer,--trusted-proposer-pk).apps/qldb-chain-api&apps/asset-chain-api: Production OCAP chain applications.@ocap/chain-nodeextracts their shared storage, role runtime, HTTP/WS, and graceful shutdown stack (roleConfigFromEnv,leaseConfigFromEnv,configureApp,maintenance.pruneIndexDbFn), with full app entrypoint cutover tracked in#1820and#1821(production apps never import@ocap/chain-node/testing).- Retired legacy apps:
apps/fs-chain-apiandapps/fs-chain-managerwere removed in#1809.
