P2P

P2P

Overview

The P2P layer implemented in Go-Ethereum allows Ethereum nodes to discover each other, establish connections, and exchange data, such as blocks, transactions, and other network messages. This implementation is built on several key components and protocols that ensure secure, reliable, and efficient communication between nodes.

Architecture

notion image
 
In Geth’s P2P network, each node has its own ENR (Ethereum Node Record) which records essential information about this node, like node id which is the unique identifier for the node, usually derived from the node's public key, IP address, TCP/UDP port and sequence number which represents the ENR’s version, etc.
When a node starts, it will start node discovery routine, this routine is responsible to find enough diverse nodes in the network and know their ENR.
After nodes have been discovered, local node tries to dial them.
After node has receives dial from remote node, it will try to perform handshakes with them, those handshakes are essentially message exchanges with purpose to establish shared secret and know matched protocols with remote nodes.
After handshake has succeeded, peers use shared secret to encrypt and decrypt message sent between them to perform matched protocols.

Node Discovery

Node discovery module is responsible for finding nodes in Network.
Geth uses Kademlia DHT(Distributed Hash Table) to help find nodes in network. Basically, when a local node starts, it first asks bootstrap node about the nodes near it (distance is measured using XOR of nodes IDs). After it has got other nodes, it will send messages to those nodes to ask other nodes near it. This process keeps going to refresh local node’s view of network nodes. Node discovery mechanism makes the nodes in network connected and distributed, also make the whole network resilient.
notion image
 

Dial Scheduler

Dial scheduler manages dialing nodes discovered by node discovery module. Dial is essentially a TCP connection action, after the remote node has received dial and established the TCP connection,it starts performing handshakes to establish peer connecton with the dialer. (peer connection means two nodes have exchanged necessary information, thus are able to perform sub protocols)
notion image

Listening

Listening module listens dial from remote nodes and try to perform handshake with them to establish peer connection.
There are two handshakes:
  1. RLPx handshake:
    1. performs ECDH processes to establish shared secret with the other node, which can be used to safely encrypt and decrypt messages between nodes.
  1. Protocol handshake:
    1. nodes exchange information about sub protocols they support. With this information, two nodes can correctly performs sub protocols between them.
       
notion image
 

Code Analysis

Start Server
Server Config and Creation
Setup Local Node
Setup Port Mapping
Setup Listening
Setup Discovery
Setup Dial Scheduler
Main Loop
Appendix

Reference