Skip to content

fix(audit-sweep): batch A — trivial bug-hunt fixes (process.exit, error leaks, missing try/catch)#882

Merged
tcsenpai merged 2 commits into
stabilisationfrom
bugfix/audit-sweep-2026-05-29
May 29, 2026
Merged

fix(audit-sweep): batch A — trivial bug-hunt fixes (process.exit, error leaks, missing try/catch)#882
tcsenpai merged 2 commits into
stabilisationfrom
bugfix/audit-sweep-2026-05-29

Conversation

@tcsenpai
Copy link
Copy Markdown
Contributor

@tcsenpai tcsenpai commented May 29, 2026

Summary

Batch A of the 2026-05-28 read-only audit sweep. Picks up the trivial, high-confidence findings — fixes that don't need design discussion or feature ownership. All CRITICAL/HIGH items needing real architectural work (nonce stub, vote race, GCREdit stubs, fee-sum assertion, Sync.ts / secretaryManager.ts exits) are out of scope and will land in a follow-up PR.

20 files, +125 / -72.

Fixes by theme

process.exit() outside graceful shutdown

Epic-14 fixed this pattern at index.ts:827. Audit found 9 more in-scope sites. All converted to throw or log-and-continue so main().catch → gracefulShutdown handles uniformly:

  • peerGossip.ts:29 — unconditional process.exit(0) removed (time bomb; one uncomment of the mainLoop callsite would have killed the node silently)
  • PeerManager.ts:62loadPeerList() filesystem error: log + treat as empty peer list, let peerBootstrap repopulate
  • peerBootstrap.ts (7 sites: 81, 86, 98, 113, 123, 180, 207) — bootstrap failures now throw upward instead of exiting with partial state on disk
  • ConnectionPool.ts:762getInstance() init-order error throws instead of permanent kill

Raw Error objects leaked over RPC wire

TypeORM errors include SQL fragments + parameter values; axios errors include internal URLs, auth headers, request bodies. Fixed at all 5 sites with consistent e instanceof Error ? e.message : String(e) pattern:

  • Peer.ts:385
  • blockHandlers.ts:118
  • rpcDispatch.ts:134
  • identityHandlers.ts:24
  • PeerConnection.ts:890

Missing try/catch on async RPC/handler chains

Server-side exceptions used to surface to SDK clients as 400 "Invalid request format" or silent 500s:

  • bunServer.ts:107-130 — outer handler catch + Bun.serve error callback
  • server_rpc.ts:239-247/genesis handler wrapped
  • blockHandlers.ts:75-90getLastBlock, getLastBlockHash, getLastBlockNumber, getBlockTransactions all wrapped (same pattern as the getBlockByHash HIGH fix)
  • Peer.ts:403Peer.fetch() axios errors now caught with structured failure return

Uninitialised Maps in manageP2P.ts

Lines 24, 44, 47, 68, 73 — added init guards. Was a remote crash trigger for any RPC route hitting DemosP2P before init completed.

Other targeted fixes

  • broadcastManager.ts:50,142-153 — null-guard on SecretaryManager.getInstance(block.number) + log.warn on silent-return block-loss path; Promise.all failure mode for first-bad-peer-kills-broadcast addressed
  • rateLimiter.ts:378-401loadIPs sync fs.readFileSyncfs.promises.readFile (was blocking event loop on large blocked-IP files)
  • normalizeWebBuffers.ts:18,21e["message"] on unknown catch → e instanceof Error ? e.message : String(e) (non-Error throws were returning [null, undefined], callers may have read as success)
  • PoRBFT.ts:197 — N serial per-tx mempool deletes → single batch removeTransactionsByHashes(failedTxs) call (method already accepted arrays)
  • chainBlocks.ts:5-6,15-16,30-34 — removed duplicate Transaction import + duplicate fork-migration function imports (merge-conflict residue)
  • mempool.ts:152 — removed stale REVIEW: CRITICAL FIX comment describing already-implemented behaviour
  • index.ts:269-288isPortAvailable differentiates EADDRINUSE (return false) from other socket errors like EACCES/EMFILE (reject); resource exhaustion no longer masquerades as "port busy"
  • mainLoop.ts — minor cleanup tied to peerGossip removal

Explicitly out of scope (deferred to batch B)

These need design decisions, feature ownership, or sit outside the original audit scope. Filed as the next PR:

  • validateTransaction.ts:358assignNonce() hardcoded true (replay attack vector — needs per-account nonce design)
  • validateTransaction.ts:304 — PROD flag bypassing gas balance check (needs PROD policy call)
  • broadcastBlockHash.ts:40-155 — pro/con vote race at block-accept time
  • handleGCR.ts:920,926 — GCREdit assign/smartContract/escrow/subnetsTx stubs returning { success: true, message: "Not implemented" }
  • applyGasFeeSeparation.ts:107-118 — fee breakdown component sum not asserted against total
  • Sync.ts:282,305,867 + secretaryManager.ts:394,410,682,887 — 7 more process.exit calls flagged out-of-scope by reviewer; particularly dangerous inside active consensus rounds
  • createBlock.ts:72-77hashNativeTables() proxy unfinished
  • subOperations.ts:297-305addAsset/removeAsset silent stubs

Verification

  • Static audit pass (read-only) used to identify findings; full report in .ccb/bug-hunt-2026-05-28/FINAL_REPORT.md (not committed — local CCB workspace).
  • No behavioural regression intended: every change preserves the original success-path contract; only failure paths are altered to be observable / non-fatal.
  • E2E transfer test scaffolding (testing/devnet/scripts/test-transfer-e2e.sh, fixture compose, funded-genesis JSON) prepared locally but not run in CI — the CCB session was killed before execution. Recommend running it manually against this branch before merge.

Test plan

  • bun install and verify compilation succeeds
  • Run existing unit tests (bun test)
  • Manual smoke: boot devnet via testing/devnet, confirm node-1 reaches block production
  • Force a loadPeerList() permission error in a sandbox and confirm node does not exit (should log and continue)
  • Confirm RPC error responses no longer leak axios config / SQL fragments by hitting /blocks/lastBlockHash with a forced DB error

Summary by CodeRabbit

  • Bug Fixes

    • Improved error resilience across network operations; failures no longer cause complete broadcast/operation failures.
    • Enhanced error propagation and handling to prevent unexpected runtime crashes.
  • Refactor

    • Optimized mempool cleanup during consensus operations.
    • Standardized error message formatting for consistency.
    • Made rate limiting non-blocking for improved performance.

Review Change Stack

@qodo-code-review
Copy link
Copy Markdown
Contributor

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 29, 2026

Warning

Review limit reached

@tcsenpai, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 48 minutes and 37 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2fe8ba38-a680-4121-ab2f-32f902e0229d

📥 Commits

Reviewing files that changed from the base of the PR and between 48a321c and 2406cfc.

📒 Files selected for processing (2)
  • src/libs/network/manageP2P.ts
  • src/libs/peer/routines/peerBootstrap.ts

Walkthrough

This PR systematically improves error resilience across the entire network and peer management layers by replacing uncaught process.exit() calls with thrown errors, adding comprehensive try/catch error handling, normalizing error message serialization, adopting Promise.allSettled for graceful degradation, and converting blocking operations to async.

Changes

Comprehensive Error Handling & Resilience Refactor

Layer / File(s) Summary
Startup & Port Availability Validation
src/index.ts
Port availability check now throws on unexpected socket errors (non-EADDRINUSE) instead of silently resolving false, enabling proper diagnosis of infrastructure issues during startup.
Peer Bootstrap & Genesis Synchronization
src/libs/peer/routines/peerBootstrap.ts, src/libs/peer/routines/peerGossip.ts
Bootstrap failures (conflicting genesis hashes, download failures, corrupt genesis file, anchor peer pairing) now throw Error instead of calling process.exit(), and genesis.json parsing is wrapped in try/catch for controlled error propagation. Early-exit path removes process.exit(0) call.
P2P Network & Message Relay Initialization
src/libs/network/manageP2P.ts
DemosP2P multiton storage (static instances Map) and instance fields (this.messages) are now explicitly initialized; relayMessage ensures per-publicKey message list exists before pushing, preventing missing-entry failures.
Peer Connection & OmniProtocol Error Reporting
src/libs/omniprotocol/transport/PeerConnection.ts, src/libs/omniprotocol/transport/ConnectionPool.ts
PeerConnection.handleIncomingRequest now calls handleError() and normalizes error payload using error.message for Error instances. ConnectionPool.getInstance() throws Error instead of calling process.exit(1).
Peer HTTP Calls & Fetch Error Handling
src/libs/peer/Peer.ts
Peer.httpCall error responses serialize error messages as strings instead of raw objects. Peer.fetch wraps HTTP GET in try/catch, returning sentinel object with stringified error message on failure.
Peer List Loading & Connection String Validation
src/libs/peer/PeerManager.ts
PeerManager.loadPeerList() handles read/parse failures without crashing (non-ENOENT errors return early, corrupt JSON logs warning). addPeer() validates peer.connection.string via new URL() in try/catch, rejecting invalid URLs with logged warning.
Bun Server Middleware & Request Error Handling
src/libs/network/bunServer.ts
Request handling wraps full middleware/route execution in try/catch, reporting via handleError() and returning standardized 500 JSON response. Bun.serve config adds error() handler for unhandled exceptions with explicit JSON content-type.
RPC Handlers & Blockchain Query Error Handling
src/libs/network/handlers/blockHandlers.ts, src/libs/network/handlers/identityHandlers.ts, src/libs/network/rpcDispatch.ts, src/libs/network/server_rpc.ts
Block/identity handlers wrap Chain.* calls in try/catch, normalizing errors to 503 STATE_NOT_READY responses with normalized messages. RPC dispatch and server_rpc endpoints add error handling for mempool and genesis queries with consistent error serialization.
Broadcast Message Resilience & Promise.allSettled
src/libs/communications/broadcastManager.ts
broadcastNewBlock and broadcastOurSyncData replace Promise.all with Promise.allSettled, filtering for fulfilled outcomes only and skipping non-200 RPC results, preventing individual peer failures from cascading.
Consensus & Blockchain Operation Optimizations
src/libs/consensus/v2/PoRBFT.ts, src/libs/blockchain/mempool.ts, src/libs/blockchain/chainBlocks.ts
PoRBFT batches failed transaction removal into single Mempool.removeTransactionsByHashes() call. Mempool comment clarifies transactional EntityManager usage. ChainBlocks removes duplicate import and reorders governance/migration imports.
Utility Functions & Rate Limiter Async Conversion
src/libs/network/middleware/rateLimiter.ts, src/libs/network/routines/normalizeWebBuffers.ts, src/utilities/mainLoop.ts
RateLimiter.loadIPs converts to async using fs.promises.readFile. normalizeWebBuffers checks e instanceof Error before accessing .message. mainLoop adds .catch() handler for checkOfflinePeers background operation with centralized error reporting.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related issues

Possibly related PRs

  • kynesyslabs/node#691: Both PRs modify PeerConnection.handleIncomingRequest error handling in src/libs/omniprotocol/transport/PeerConnection.ts, with shared concern for request error path behavior.
  • kynesyslabs/node#663: Both PRs modify src/libs/peer/routines/peerBootstrap.ts genesis validation/sync flow, with the main PR changing error propagation from process.exit to thrown errors.
  • kynesyslabs/node#659: Both PRs modify peer HTTP-call/error handling in src/libs/peer/Peer.ts, refactoring error payload serialization behavior.

Suggested labels

ReviewedByDojoReviews, Review effort 4/5

Poem

🐰 Errors once hidden now ring bright,
Process exits yield to thrown light,
Promises settled, no cascade fail,
Messages normalized tell their tale.
Bootstrap blooms through proper throws,
Resilience flowers as error-flow grows! 🌸

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main objective: a batch of trivial bug-hunt fixes addressing process.exit calls, error leaks, and missing try/catch blocks across multiple files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch bugfix/audit-sweep-2026-05-29

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@greptile-apps
Copy link
Copy Markdown

greptile-apps Bot commented May 29, 2026

Greptile Summary

This PR is a targeted audit sweep fixing trivial-but-real bugs across 20 files: removing process.exit() calls from 9 non-shutdown sites, sanitizing raw Error objects leaked over RPC, adding missing try/catch on async handler chains, and fixing uninitialized Maps in manageP2P.ts. The intent is clear — preserve success-path contracts while making failure paths observable and recoverable through the existing main().catch → gracefulShutdown pipeline.

  • process.exit removal: All 9 in-scope sites now throw or log-and-return; peerBootstrap, ConnectionPool, PeerManager, and peerGossip no longer kill the process on recoverable or init-order errors.
  • RPC error sanitization: Five sites now use e instanceof Error ? e.message : String(e) consistently, preventing TypeORM SQL fragments and axios internals from reaching SDK clients.
  • Handler hardening: bunServer.handleRequest, /genesis, and four block handlers are all wrapped; manageP2P Map init guards close the crash window for pre-init RPC calls; rateLimiter.loadIPs is made non-blocking via fs.promises.

Confidence Score: 5/5

Safe to merge — all changes are failure-path only; success paths are untouched and the fixes are mechanical in nature.

Every changed code path is a failure handler, a missing guard, or a duplicate import removal. No success-path logic is altered. The two observations noted are observability gaps (no logging on dropped broadcast rejections) and a contract change in Peer.fetch() that affects unknown callers, both of which are low-risk in context.

broadcastManager.ts and Peer.ts warrant a second look — the former silently drops rejected peer promises with no logging, the latter changes fetch() from throw-on-error to return-error-object.

Important Files Changed

Filename Overview
src/libs/communications/broadcastManager.ts Promise.all replaced with Promise.allSettled to prevent first-failing-peer from killing the whole broadcast; rejected promises (real network failures) are silently discarded with no log
src/libs/peer/Peer.ts fetch() now catches axios errors and returns { status:0, error } instead of throwing; changes the error contract for all callers
src/libs/peer/PeerManager.ts loadPeerList now logs + treats corrupt/unreadable peer file as empty instead of process.exit; URL parsing wrapped in try-catch to reject invalid peer strings
src/libs/peer/routines/peerBootstrap.ts All 7 process.exit calls replaced with throws; genesis file read wrapped with ENOENT/corrupt distinction; behavior is equivalent fail-fast but now routes through gracefulShutdown
src/libs/network/bunServer.ts Added outer try/catch in handleRequest and a Bun.serve error callback so unhandled handler exceptions return 500 instead of crashing the server
src/libs/network/handlers/blockHandlers.ts getLastBlock, getLastBlockHash, getLastBlockNumber, getBlockTransactions wrapped in try/catch returning 503 STATE_NOT_READY; raw error objects replaced with sanitized messages
src/libs/network/manageP2P.ts instances Map and messages Map now initialised inline/in constructor; relayMessage gets a null-guard before push; getMessagesForPartecipant returns [] for unknown public keys
src/libs/network/middleware/rateLimiter.ts loadIPs converted from sync fs.readFileSync to async fs.promises.readFile; called with void to avoid blocking the event loop on startup
src/libs/consensus/v2/PoRBFT.ts N serial removeTransactionsByHashes calls collapsed into a single batch call; correct since the method already accepts arrays
src/libs/blockchain/chainBlocks.ts Removed duplicate Transaction import and duplicate fork-migration imports that were merge-conflict residue

Reviews (2): Last reviewed commit: "fix(audit-sweep): address Greptile revie..." | Re-trigger Greptile

Comment thread src/libs/peer/routines/peerBootstrap.ts
Two findings from Greptile (4/5 confidence):

P1 — src/libs/network/manageP2P.ts:74-80 (getMessagesForPartecipant)
  Adjacent methods in this class were guarded against unset Maps in
  the original batch A, but this method was missed. `this.messages.get(
  publicKey)` returns undefined when no relayMessage has ever been
  called for that key, and the subsequent `for-of` then throws
  `TypeError: undefined is not iterable`. Same crash category the rest
  of the PR was targeting. Fix: `?? []` fallback on the Map.get result
  so callers always receive an iterable Message[].

P2 — src/libs/peer/routines/peerBootstrap.ts:218-222 (genesis I/O)
  The try/catch around `JSON.parse(fs.readFileSync(...))` wrapped both
  ENOENT (missing file) and SyntaxError (corrupt JSON) under the same
  "Corrupt genesis file" label. An operator with a missing genesis
  file would chase a non-existent corruption issue. Fix: differentiate
  on `(error as NodeJS.ErrnoException).code === "ENOENT"` and emit
  "Missing genesis file" vs "Corrupt genesis file" accordingly.
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/index.ts (1)

269-287: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Catch non-EADDRINUSE probe errors in getNextAvailablePort to avoid aborting port scanning

isPortAvailable() now reject(err) for any net.Server listen error code other than EADDRINUSE, but getNextAvailablePort() awaits it in its scan loop with no try/catch. That means errors like EACCES (permission denied) / EADDRNOTAVAIL (address not available) will escape the helper instead of being treated as “port unavailable”.

In src/index.ts, getNextAvailablePort(...) is only invoked for signaling, omni, metrics, and mcp probes (no other callers found). Ensure every call site either handles those rejections consistently or (preferably) handle them inside getNextAvailablePort (log with context and continue scanning, or rethrow with context in a way that matches the intended startup semantics).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/index.ts` around lines 269 - 287, isPortAvailable currently rejects for
non-EADDRINUSE listen errors and getNextAvailablePort awaits it without
protection, causing scans to abort on EACCES/EADDRNOTAVAIL; update
getNextAvailablePort to catch errors from isPortAvailable (or call
isPortAvailable inside a try/catch) and treat non-EADDRINUSE errors as "port
unavailable" (resolve/continue scanning) while logging the error with context
(include probe name/port and error.code) so startup continues for
signaling/omni/metrics/mcp probes; alternatively, rethrow only if the error is
unrecoverable per your startup semantics, but do not let typical probe listen
errors escape the scan loop.
🧹 Nitpick comments (2)
src/libs/peer/routines/peerBootstrap.ts (1)

217-223: ⚡ Quick win

Consider typing genesisData with the expected structure.

The variable genesisData is declared as unknown (line 217) and then passed directly to hashGenesisData() (line 223) without validation. If hashGenesisData doesn't perform structural validation, this could lead to runtime errors when the genesis file contains unexpected data.

Consider either:

  1. Typing genesisData with the expected genesis structure type
  2. Adding validation after parsing to ensure the structure matches expectations
🔧 Suggested improvement
-    let genesisData: unknown
+    let genesisData: GenesisData // or appropriate type
     try {
         genesisData = JSON.parse(fs.readFileSync(genesisFile, "utf8"))
     } catch (error) {
         throw new Error(`Corrupt genesis file at data/genesis.json: ${error instanceof Error ? error.message : String(error)}`)
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/libs/peer/routines/peerBootstrap.ts` around lines 217 - 223, genesisData
is currently typed as unknown and passed straight to hashGenesisData, risking
runtime errors; change this by defining an expected Genesis type (e.g.,
interface Genesis { ... }) and replace genesisData: unknown with genesisData:
Genesis, or after JSON.parse run a runtime validation (schema check or small
validator function) that verifies required fields/types before calling
hashGenesisData(genesisData); ensure the validator throws a clear error
mentioning genesisFile on failure so downstream code only receives a correctly
shaped Genesis object.
src/libs/peer/Peer.ts (1)

403-408: 💤 Low value

Consider typing the fetch return value.

The fetch method now returns either the successful response data or a sentinel object {status: 0, error: string} on failure. The return type is currently Promise<any>, which doesn't capture this union behavior.

Consider defining a union type or at least documenting the sentinel return value so callers know to check for status: 0.

💡 Optional type improvement
// Add to Peer class or types file
type FetchResult<T = any> = T | { status: 0; error: string }

// Update method signature
async fetch(endpoint: string): Promise<FetchResult> {
    // ... implementation
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/libs/peer/Peer.ts` around lines 403 - 408, The fetch method in class Peer
currently returns Promise<any> but actually yields either response data or a
sentinel {status: 0, error: string}; define a proper union return type (e.g.,
add a type alias FetchResult<T = any> = T | { status: 0; error: string } in the
Peer class or a shared types file) and update the signature of Peer.fetch (and
any callers if necessary) to async fetch<T = any>(endpoint: string):
Promise<FetchResult<T>> so callers can statically check for status === 0 and
access the typed success payload.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/index.ts`:
- Around line 269-287: isPortAvailable currently rejects for non-EADDRINUSE
listen errors and getNextAvailablePort awaits it without protection, causing
scans to abort on EACCES/EADDRNOTAVAIL; update getNextAvailablePort to catch
errors from isPortAvailable (or call isPortAvailable inside a try/catch) and
treat non-EADDRINUSE errors as "port unavailable" (resolve/continue scanning)
while logging the error with context (include probe name/port and error.code) so
startup continues for signaling/omni/metrics/mcp probes; alternatively, rethrow
only if the error is unrecoverable per your startup semantics, but do not let
typical probe listen errors escape the scan loop.

---

Nitpick comments:
In `@src/libs/peer/Peer.ts`:
- Around line 403-408: The fetch method in class Peer currently returns
Promise<any> but actually yields either response data or a sentinel {status: 0,
error: string}; define a proper union return type (e.g., add a type alias
FetchResult<T = any> = T | { status: 0; error: string } in the Peer class or a
shared types file) and update the signature of Peer.fetch (and any callers if
necessary) to async fetch<T = any>(endpoint: string): Promise<FetchResult<T>> so
callers can statically check for status === 0 and access the typed success
payload.

In `@src/libs/peer/routines/peerBootstrap.ts`:
- Around line 217-223: genesisData is currently typed as unknown and passed
straight to hashGenesisData, risking runtime errors; change this by defining an
expected Genesis type (e.g., interface Genesis { ... }) and replace genesisData:
unknown with genesisData: Genesis, or after JSON.parse run a runtime validation
(schema check or small validator function) that verifies required fields/types
before calling hashGenesisData(genesisData); ensure the validator throws a clear
error mentioning genesisFile on failure so downstream code only receives a
correctly shaped Genesis object.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6970e91e-3e0d-4db5-a291-c6a929883886

📥 Commits

Reviewing files that changed from the base of the PR and between 7a75a4b and 48a321c.

📒 Files selected for processing (20)
  • src/index.ts
  • src/libs/blockchain/chainBlocks.ts
  • src/libs/blockchain/mempool.ts
  • src/libs/communications/broadcastManager.ts
  • src/libs/consensus/v2/PoRBFT.ts
  • src/libs/network/bunServer.ts
  • src/libs/network/handlers/blockHandlers.ts
  • src/libs/network/handlers/identityHandlers.ts
  • src/libs/network/manageP2P.ts
  • src/libs/network/middleware/rateLimiter.ts
  • src/libs/network/routines/normalizeWebBuffers.ts
  • src/libs/network/rpcDispatch.ts
  • src/libs/network/server_rpc.ts
  • src/libs/omniprotocol/transport/ConnectionPool.ts
  • src/libs/omniprotocol/transport/PeerConnection.ts
  • src/libs/peer/Peer.ts
  • src/libs/peer/PeerManager.ts
  • src/libs/peer/routines/peerBootstrap.ts
  • src/libs/peer/routines/peerGossip.ts
  • src/utilities/mainLoop.ts
💤 Files with no reviewable changes (2)
  • src/libs/peer/routines/peerGossip.ts
  • src/libs/blockchain/chainBlocks.ts

@tcsenpai tcsenpai merged commit eaf4481 into stabilisation May 29, 2026
4 of 5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant