npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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, and Blacklist (filter.json).
  • Role-specific consensus & replication runtimes:
    • Single-validator Ledger checkpointing (periodicTimer + witness quorum policy).
    • Follower snapshot bootstrap (prepareFollowerDataDirectory), FollowerSyncService, single-hop LeaderRouter (writePolicy: 'forward'), and monotonic follower high-water mark persistence.
    • Multi-validator HotStuffNodeRuntime + SqliteHotStuffStateStore with split consensus listener isolation (/consensus returns 404 on the public HTTP port).
  • OCAPResolver orchestration: Deferred initialization (deferInitialize: true), keyless follower statedb chain-config rehydration without mutating process.env, and Promise-based startup validation (never calling process.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 /dashboard and /node/explorer, and / GraphQL (createHttpHandler, serving /, /api, and /api/gql).
  • Fail-closed NODE_HALTED gate: Blocks all non-diagnostic GraphQL operations (CustomError('NODE_HALTED', 'Chain node is halted fail-closed')) and returns HTTP 503 ({ 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

  • .env file loading & implicit process.env reads: startChainNode never reads process.env for configuration (the sole environment check is rejecting testHooks when process.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, or eth) before calling startChainNode.
  • Pre-Resolver immutable chain-config merging: Application-specific applyImmutable / checkChainImmutables logic (for example bridge/ocap-node/src/immutable.ts) runs before passing chainConfig into startChainNode.
  • 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-prune is injected via profile.maintenance.pruneIndexDbFn rather than hard-depended on by @ocap/chain-node.
  • Global process signal handlers: startChainNode does not bind process.on('SIGINT' | 'SIGTERM') automatically; CLI entrypoints opt in via installProcessSignalHandlers(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 a RunningChainNode handle (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 explicit env keys (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 typed ChainNodeRoleConfig.
  • leaseConfigFromEnv(env): Pure parser mapping explicit env keys (LEDGER_WRITER_LEASE, LEDGER_WRITER_LEASE_TTL_MS, LEDGER_WRITER_LEASE_STARTUP_WAIT_MS, CHAIN_LEASE_HOLDER_ID) into ILedgerLeaseOptions | false.
  • loadChainEnvFiles(env, { uid? }), applyChainConfigToEnv(target, loaded), chainRuntimeEnv(base, loaded), readChainEnvFile(path, { kind }) (also @ocap/chain-node/lib/env-files.js, dependency-free): strict CHAIN_SECRETS_FILE / CHAIN_CONFIG_FILE loader (#2076; regular 0600 file of the process uid, listed names only, no name also set in the env). Config values go to process.env; secrets only into the runtime env copy. See docs/ops/chain-env-mapping.md#secrets-and-config-files.
  • installProcessSignalHandlers(node, options?): Attaches idempotent SIGTERM/SIGINT handlers that invoke node.stop() and returns an uninstall() 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:

  1. Lease-first safety: If <dataDir>/ledger.sqlite already exists on disk, startChainNode acquires the SqliteSingleWriterLease before prepareFollowerDataDirectory inspects or mutates any files, ensuring a duplicate concurrent boot fails immediately with LEDGER_LEASE_HELD.
  2. Signed snapshot verification (prepareFollowerDataDirectory):
    • Downloads latest-snapshot.json, signed manifest.json, SHA256SUMS, statedb.sqlite.zst, and ledger.sqlite.zst from snapshotBaseUrl (protected by SSRF private-IP filtering unless allowPrivatePeers: true is explicitly set in local harnesses).
    • Verifies the snapshot manifest.json signature against the pinned trustedProposer / trustedProposerPublicKey (and optional hotstuffValidators) before decompressing archives.
    • Verifies .zst SHA-256 checksums against SHA256SUMS, decompresses statedb.sqlite and ledger.sqlite, verifies checkpoint signatures inside ledger.sqlite, and writes <dataDir>/.follower-bootstrap.json (0600) recording chainId, snapshotSequence, checkpointHeight, checkpointHash, stateCommitHash, proposer, proposerPublicKey, bootstrappedAt, lastKnownSequence, and lastKnownCheckpointHeight.
    • Cold follower boot without an existing bootstrapped DB and without snapshotBaseUrl fails closed; tampered manifests, .zst archives, or mismatched trustedProposerPublicKey abort startup before OCAPResolver opens.
  3. Anti-cascading upstream guard (disallowKeylessCascadedUpstream):
    • When enabled (true on Sentinel verification followers), FollowerSyncService verifies /api/ledger/status upstream signatures and refuses to sync from another keyless/unauthenticated follower, requiring a cryptographic 'validator' upstream.
  4. Fail-closed NODE_HALTED:
    • If FollowerSyncService or LedgerEntryReplayer detects an offline statedb.sqlite tamper, stateRoot mismatch against a verified checkpoint, or unrecoverable upstream divergence, it transitions to halted = 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 HTTP 503 with { code: 'NODE_HALTED', halted: true } (Cache-Control: no-store).

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:

  1. Validate testHooks token (FORBIDDEN_IN_PRODUCTION in NODE_ENV=production), verify dataDir is not a symlink (assertSafeNonSymlinkDirectory), and validate ChainNodeRoleConfig.
  2. Load or atomically persist <dataDir>/.node-id (0600).
  3. Resolve consensus proposer identity (ed25519, secp256k1, or eth) purely in memory without mutating process.env.
  4. For role.kind === 'follower', acquire pre-existing ledger writer lease if present, run prepareFollowerDataDirectory, and provision .follower-trusted.key when keyless.
  5. Initialize writable SqliteLedgerStorage (ledger.sqlite) and acquire SqliteSingleWriterLease.
  6. On a SigningBox validator started with storage.trustedKeyMigration (TRUSTED_KEY_MIGRATION*, #2140), re-sign trusted.sqlite once between the local trusted sub-key and the lease key (backup first; see docs/ops/chain-env-mapping.md#trusted-storage-key-migration-2140). Then open SqliteTrustedStorage (trusted.sqlite), open SqliteStateDB (statedb.sqlite), rehydrate IChainConfig from statedb for keyless followers, and initialize Ledger (wiring logical clock + periodic checkpoint timer).
  7. Initialize SqliteIndexDB (indexdb.sqlite), NodePreferencesManager, and Blacklist (filter.json).
  8. Initialize OCAPResolver (deferInitialize: true, skipInitializeStateDB: true on followers).
  9. Wire role runtime (FollowerSyncService + optional LeaderRouter + initial rebuildIndex() / orphan replay for followers; HotStuffNodeRuntime + SqliteHotStuffStateStore for HotStuff).
  10. Start background sync/consensus loops (followerSync.start() or hotstuffRuntime.start()).
  11. Assemble Express + Socket.IO HTTP server and bind http.host:http.port (no global express.json() is mounted so route-specific body limits like the 256 KB /api/ledger/witness/attestations endpoint remain intact).
  12. Run optional testHooks.onAfterBoot and return RunningChainNode.

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:

  1. the trusted proxy headers in CHAIN_CLIENT_IP_HEADERS order — only when the TCP peer is a loopback address, and only when the value is a bare IP literal;
  2. otherwise req.ip (equal to the socket address unless the app sets trust 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())

  1. Stop followerSync / hotstuffRuntime background loops and clear maintenance/HWM timers.
  2. Flip isShuttingDown = true (new HTTP requests receive 503 + Connection: close), close idle keep-alive sockets, and wait up to http.drainTimeoutMs (5000ms default) for activeResponses === 0 before calling server.close() (preventing Socket.IO/WsServer.attach closeAllConnections() from resetting in-flight responses).
  3. Close the HTTP + WebSocket listener (server.close()).
  4. Call resolver.shutdown() (drains in-flight pre-flights, transaction queue, and flushIndexWrites()).
  5. Demote ledger role (ledger.setNodeRole('readonly')) to fence new writes and periodic checkpoint timers.
  6. Dispose Blacklist file watchers (filter.dispose()).
  7. Close statedb and trustedStorage.
  8. Close indexdb and flush final follower high-water mark.
  9. In finally, call ledger.close() to drain any in-flight checkpoint and release SqliteSingleWriterLease last.

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: createChainNodeTestHooks stamps objects with a private module-scoped Symbol('@ocap/chain-node/test-hooks-token') (not Symbol.for), so test hooks cannot be injected via JSON configs, CLI flags, or environment variables.
  • Production hard block: Passing testHooks or calling createChainNodeTestHooks when process.env.NODE_ENV === 'production' immediately throws CustomError('FORBIDDEN_IN_PRODUCTION', ...).

Relationship to OCAP Packages & Applications

  • bridge/ocap-node (@arcblock/bridge-ocap-node): Migrated onto @ocap/chain-node (#1812). Wraps startChainNode with bridge rollup immutable state (bridge/ocap-node/src/immutable.ts) and exposes a CLI supporting both --role validator and 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-node extracts their shared storage, role runtime, HTTP/WS, and graceful shutdown stack (roleConfigFromEnv, leaseConfigFromEnv, configureApp, maintenance.pruneIndexDbFn), with full app entrypoint cutover tracked in #1820 and #1821 (production apps never import @ocap/chain-node/testing).
  • Retired legacy apps: apps/fs-chain-api and apps/fs-chain-manager were removed in #1809.