Skip to content

fix: address CodeRabbit comments for pr #46#54

Open
SIDDHANTCOOKIE wants to merge 3 commits intoStabilityNexus:mainfrom
SIDDHANTCOOKIE:fix-code-rabbits-comments
Open

fix: address CodeRabbit comments for pr #46#54
SIDDHANTCOOKIE wants to merge 3 commits intoStabilityNexus:mainfrom
SIDDHANTCOOKIE:fix-code-rabbits-comments

Conversation

@SIDDHANTCOOKIE
Copy link
Contributor

@SIDDHANTCOOKIE SIDDHANTCOOKIE commented Mar 6, 2026

Addressed Issues:

This PR applies the CodeRabbit-requested fixes in main.py and minichain/p2p.py with minimal, targeted changes.

Screenshots/Recordings:

Additional Notes:

  • Added sync trust gating before merging remote accounts:
    • accept sync only from localhost/trusted peers, or when local accounts are empty
    • log accepted syncs and rejected attempts
  • Restored mempool transactions when mined block is rejected.
  • Updated CLI connect command to display success/failure message based on connect_to_peer(...) return value.
  • Replaced private callback assignment with public API:
    • added P2PNetwork.set_on_peer_connected(callback)
    • switched call site from network._on_peer_connected = ... to setter
  • Hardened server bind defaults:
    • P2PNetwork.start(..., host="127.0.0.1")
    • wired --host CLI arg through main.py to allow explicit external binding
  • Improved shutdown cleanup:
    • cancel + await _listen_tasks before clearing
  • Made outbound connections symmetric with inbound:
    • invoke peer-connected callback on successful outbound connect
  • Fixed broadcast failure cleanup:
    • close failed StreamWriters, await wait_closed(), then remove peer tuples
  • Passed peer address metadata to handler for trust checks.
  • Restored and aligned the original Unicode CLI help box formatting

Checklist

  • My PR addresses a single issue, fixes a single bug or makes a single improvement.
  • My code follows the project's code style and conventions
  • If applicable, I have made corresponding changes or additions to the documentation
  • If applicable, I have made corresponding changes or additions to tests
  • My changes generate no new warnings or errors
  • I have joined the Discord server and I will share a link to this PR with the project maintainers there
  • I have read the Contribution Guidelines
  • Once I submit my PR, CodeRabbit AI will automatically review it and I will address CodeRabbit's comments.

AI Usage Disclosure

Check one of the checkboxes below:

  • This PR does not contain AI-generated code at all.
  • This PR contains AI-generated code. I have read the AI Usage Policy and this PR complies with this policy. I have tested the code locally and I am responsible for it.

I have used the following AI models and tools: N/A

⚠️ AI Notice - Important!

We encourage contributors to use AI tools responsibly when creating Pull Requests. While AI can be a valuable aid, it is essential to ensure that your contributions meet the task requirements, build successfully, include relevant tests, and pass all linters. Submissions that do not meet these standards may be closed without warning to maintain the quality and integrity of the project. Please take the time to understand the changes you are proposing and their impact. AI slop is strongly discouraged and may lead to banning and blocking. Do not spam our repos with AI slop.

Summary by CodeRabbit

  • New Features

    • Added node bind address option (--host) with startup binding feedback.
    • Connection notifications now trigger when peers connect.
    • Funding now credits mining rewards at startup.
  • Bug Fixes

    • Requeue pending transactions when a block is rejected.
    • More robust network shutdown, connection handling and broadcast cleanup.
    • Nodes validate and accept syncs only from trusted or localhost peers; improved sync logging.
  • Chores

    • Minor CLI/help text formatting refinements.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 6, 2026

🚥 Pre-merge checks | ✅ 1 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The PR title references addressing CodeRabbit comments but is vague about the specific changes—it uses a generic reference ('CodeRabbit comments') rather than describing the actual main objective. Consider a more specific title that highlights the primary change, such as 'fix: add peer trust validation and improve P2P network robustness' or 'fix: implement sync trust gating and hardened network callbacks'.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

Copy link
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.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@main.py`:
- Around line 34-35: TRUSTED_PEERS is defined as an empty set so the trust check
using peer_addr in TRUSTED_PEERS will always fail; either populate it from
configuration or document intent. Fix by adding configuration parsing to
populate TRUSTED_PEERS (e.g., read a comma-separated env var like TRUSTED_PEERS
or add an argparse option --trusted-peer/--trusted-peers and split into a set)
and ensure LOCALHOST_PEERS remains separate; update the trust check logic that
references peer_addr to consult the populated TRUSTED_PEERS set. If emptiness is
intentional for a demo, instead add a clear comment above the TRUSTED_PEERS
declaration stating that behavior.
- Around line 94-99: The code's peer_host extracted from peer_addr (used in
is_trusted/is_localhost checks) can include IPv6 brackets (e.g., "[::1]") so
comparisons against TRUSTED_PEERS/LOCALHOST_PEERS fail; update the logic around
peer_addr/peer_host (used where peer_host is derived and in the
is_trusted/is_localhost checks inside the block guarded by chain.state.accounts)
to strip surrounding "[" and "]" if present (e.g., if peer_host.startswith("[")
and peer_host.endswith("]") then peer_host = peer_host[1:-1]) before membership
tests and before logging the rejected peer via logger.warning so bracketed IPv6
peers are recognized as localhost/trusted.

In `@minichain/p2p.py`:
- Around line 162-170: The except block that swallows exceptions during writer
cleanup should log the exception at DEBUG to aid troubleshooting; update the
except Exception: handler around writer.close() / await writer.wait_closed() to
call the module or instance logger (e.g., self.logger.debug(...) or
logging.getLogger(__name__).debug(...)) and include the exception information
and context (reader, writer, or peer identifier) without changing the existing
removal behavior of pair from self._peers.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: b02a162c-3021-492c-8796-749e3df5518a

📥 Commits

Reviewing files that changed from the base of the PR and between ff5e83a and 9717a95.

📒 Files selected for processing (2)
  • main.py
  • minichain/p2p.py

Copy link
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.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@main.py`:
- Around line 98-100: The check rejecting syncs when chain.state.accounts is
truthy blocks bootstrap for nodes pre-funded by run_node(); either defer the
initial funding in run_node() until after peer bootstrap completes, or relax the
sync guard in the peer handling code to allow bootstrapping when the only
existing account is the node's self-funded local wallet; locate the funding call
in run_node() and move it to run after the bootstrap routine, or update the
conditional around logger.warning("🔒 Rejected sync from untrusted peer %s",
peer_addr) to treat the case where chain.state.accounts contains only the local
wallet (or when a --fund flag is present) as bootstrappable so remote seeds
aren’t rejected.
- Line 157: Help text uses the incorrect placeholder "connect <host:port>" —
update the help string to match the CLI format used elsewhere by changing the
placeholder to "connect <host>:<port>" (locate the help/menu string in main.py
where the line contains "connect <host:port>" and replace it so the documented
syntax matches the actual command format).
- Around line 103-108: The payload["accounts"] handling is unsafe: validate that
payload is a dict and that payload.get("accounts") returns a mapping before
iterating; ensure each account value (acc) is a dict before mutating
chain.state.accounts or calling acc.get. In the block using remote_accounts,
first coerce or reject non-dict accounts (skip entries where not isinstance(acc,
dict) or addr not a str), accumulate only valid entries, then update
chain.state.accounts with those valid entries and use logger.info to report
synced accounts and optionally warn about skipped/malformed entries; reference
the variables and methods remote_accounts, payload, chain.state.accounts, addr,
acc, and logger.info when making the changes.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: d5b04406-47d4-42e7-a892-5e583b0002be

📥 Commits

Reviewing files that changed from the base of the PR and between 9717a95 and feb1026.

📒 Files selected for processing (1)
  • main.py

Copy link
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)
main.py (1)

306-311: 🧹 Nitpick | 🔵 Trivial

Consider renaming to avoid shadowing the host parameter.

Line 308 shadows the host parameter with a local variable. While not a bug (the original value was used at line 303), this reduces readability.

♻️ Suggested refactor for clarity
     if connect_to:
         try:
-            host, peer_port = connect_to.rsplit(":", 1)
-            await network.connect_to_peer(host, int(peer_port))
+            peer_host, peer_port = connect_to.rsplit(":", 1)
+            await network.connect_to_peer(peer_host, int(peer_port))
         except ValueError:
             logger.error("Invalid --connect format. Use host:port")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@main.py` around lines 306 - 311, The local variable created from
connect_to.rsplit(":", 1) shadows the outer parameter named host; rename that
local variable (e.g., to peer_host or remote_host) and update its use in the
network.connect_to_peer call so you don't reuse the parameter name — adjust the
try block where connect_to is parsed and the await network.connect_to_peer(host,
int(peer_port)) invocation accordingly (leave the outer host parameter
unchanged).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@main.py`:
- Around line 306-311: The local variable created from connect_to.rsplit(":", 1)
shadows the outer parameter named host; rename that local variable (e.g., to
peer_host or remote_host) and update its use in the network.connect_to_peer call
so you don't reuse the parameter name — adjust the try block where connect_to is
parsed and the await network.connect_to_peer(host, int(peer_port)) invocation
accordingly (leave the outer host parameter unchanged).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 93fe7612-5bdf-4a2f-b2b3-abb0ce080261

📥 Commits

Reviewing files that changed from the base of the PR and between feb1026 and 6184794.

📒 Files selected for processing (1)
  • main.py

@SIDDHANTCOOKIE SIDDHANTCOOKIE changed the title fix: address CodeRabbit networking comments with minimal p2p/main updates fix: address CodeRabbit comments Mar 6, 2026
@SIDDHANTCOOKIE SIDDHANTCOOKIE changed the title fix: address CodeRabbit comments fix: address CodeRabbit comments for pr #46 Mar 6, 2026
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