Skip to content

Fix/p2p discovery - #144

Open
SIDDHANTCOOKIE wants to merge 2 commits into
mainfrom
fix/p2p-discovery
Open

Fix/p2p discovery#144
SIDDHANTCOOKIE wants to merge 2 commits into
mainfrom
fix/p2p-discovery

Conversation

@SIDDHANTCOOKIE

Copy link
Copy Markdown
Member

Addressed Issues:

Adds mDNS, UPnP, and circuit relay (via --relay/--relay-addr) so a node is reachable without a tunnel, plus --bootstrap for startup discovery. On top of that: a persisted node identity (minichain/identity.py) so peer ID survives restarts, a peer book so a node redials who it knew before, and getaddr/addr peer exchange so the network outlives whoever introduced you to it. --announce fixes the advertised address under NAT; --fund now defaults to 0 since a nonzero value silently broke consensus between nodes.

Test plan: 89/89 pytest passing (new identity + peer-book tests). Live: relay-only connection with no direct route, identity + redial surviving a restart, zero-flag node rejoining from its peer book, peer discovered via addr gossip alone, --announce override confirmed.
Fixes #(TODO:issue number)

Screenshots/Recordings:

TODO: If applicable, add screenshots or recordings that demonstrate the interface before and after the changes.

Additional Notes:

AI Usage Disclosure:

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.

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: TODO

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.
  • I have filled this PR template completely and carefully, and I understand that my PR may be closed without review otherwise.

Swarm.listen() waits on a nursery that only exists while the swarm runs as
a background service, so a node calling host.get_network().listen() directly
never finished starting up: no multiaddr printed, no inbound connections
possible. Listening now goes through host.run(). The dialing side had the
same problem in reverse — it borrowed a nursery attribute the swarm doesn't
expose, so a peer that dialed out never registered the connection or read
from it. Both now use the nursery this module already opens for itself.

Two mining bugs made a fresh chain effectively unusable: mining refused to
produce a block when the mempool was empty, but the mining reward is the
only source of new coins, so a chain that had never received one could never
mine its first coin either. And two blocks minted within the same
millisecond were rejected, since consensus requires strictly increasing
timestamps. Both are fixed at the source: an empty block still carries the
reward and proof-of-work, and the timestamp is clamped to be newer than the
parent's instead of just read off the clock.

A node that accepted a transaction or block only kept it — it never told any
other peer, so a network more than one hop wide couldn't stay in sync.
Accepted content is now relayed onward, excluding whoever sent it, with the
existing dedup set stopping the echo from circulating. That set was
unbounded, and now that it's load-bearing for stopping gossip loops rather
than just avoiding duplicate work, its size is capped with an LRU eviction.

Smaller fixes bundled in because they're cheap and adjacent: `peers` now
lists the peer IDs it's connected to, not just a count; the JSON-RPC server's
bind address is a flag instead of hardcoded to loopack; two unused constants
(TRUSTED_PEERS, LOCALHOST_PEERS) are removed; and the README's --connect
example, which predates the multiaddr-based CLI, is corrected.
Stacked on fix/p2p-core. That branch makes P2P work at all; this makes it
work across networks and survive a restart.

A node was only dialable if someone had arranged for its address to be
reachable, which in practice meant running bore or ngrok alongside it. Three
mechanisms replace that, in increasing order of last resort: mDNS finds
peers on the same LAN with nothing typed at all; --upnp asks the router for
a port mapping; --relay/--relay-addr route through another MiniChain node
when neither works, via libp2p's circuit relay v2. --bootstrap dials a list
of peers on startup — discovery rather than reachability, but the same path.

That solved reaching a peer once. It did not solve staying reachable: the
node's own identity was regenerated every restart, which invalidated any
address a peer had saved for it, and it forgot every peer it had ever
connected to the moment it stopped. Three more pieces close that:

  identity.py     persists the libp2p keypair to <datadir>/nodekey, so the
                  peer ID a node presents is the same across restarts.

  known_peers     a table beside the existing banned_peers one
  (persistence.py) (remember_peer / get_known_peers). A node dials it on
                  startup alongside --bootstrap, and redials with backoff
                  when a stream it dialed itself drops.

  getaddr/addr    after a handshake, a node asks its peer for more peers and
  (main.py)       remembers what it's told, so the network stays reachable
                  after whoever it was originally introduced to goes away.
                  Addresses are stored, never relayed onward, so this can't
                  become an amplification vector. Only the dialing side of a
                  connection ever has a real address for the peer to share —
                  an inbound connection reveals nothing but an ephemeral
                  remote port — which is the same asymmetry Bitcoin has via
                  service flags.

--announce lets a node advertise a different address than the one it binds
to, for when the bind address (0.0.0.0 under --upnp, a NAT'd LAN IP) isn't
itself dialable. --fund now defaults to 0: it credits a wallet outside of
block validation, so a nonzero value diverges a node's state from every
peer's the moment it mines, and the previous default of 100 broke multi-node
operation out of the box.

Verified live: two nodes reach each other only through a relay, with no
direct route ever used; a node's peer ID and its ability to redial its last
peer both survive a restart, even for a node that was only ever reachable
through that relay; a third node dialing only one existing peer discovers
and connects to the other via addr gossip alone.
@coderabbitai

coderabbitai Bot commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

Next included review available in 58 minutes.

View limit details

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 05bbbc43-f017-427d-bd75-97e67fea4963

📥 Commits

Reviewing files that changed from the base of the PR and between c29182d and 14956eb.

📒 Files selected for processing (10)
  • README.md
  • main.py
  • minichain/identity.py
  • minichain/network_config.py
  • minichain/node_config.py
  • minichain/p2p.py
  • minichain/persistence.py
  • tests/test_identity_and_peerbook.py
  • tests/test_persistence_runtime.py
  • tests/test_protocol_hardening.py

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.

@github-actions

Copy link
Copy Markdown
Tests Skipped Failures Errors Time
11 0 💤 0 ❌ 11 🔥 1.829s ⏱️

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.

2 participants