| Crates.io | calimero-network |
| lib.rs | calimero-network |
| version | 0.2.5 |
| created_at | 2025-08-31 12:35:53.071349+00 |
| updated_at | 2025-09-09 14:07:19.397658+00 |
| description | Core Calimero infrastructure and tools |
| homepage | |
| repository | https://github.com/calimero-network/core |
| max_upload_size | |
| id | 1818493 |
| size | 240,734 |
The Networking crate is a robust peer-to-peer networking solution built on top of libp2p. It provides a comprehensive set of tools and abstractions for creating decentralized applications with efficient peer discovery, connection management, and custom protocol implementations.
Key features of this crate include:
The EventLoop is the central component of the networking crate, responsible
for managing the network's event-driven operations. It's implemented as a struct
containing several important fields, including the swarm, which is the main
libp2p construct for managing network connections and protocols.
graph TD
A[Node Initialization] --> B[Listen on addresses]
A --> C[EventLoop Start]
C -->|Continuous| D[Process Events]
subgraph " "
D --> N[Swarm Events]
D --> O[Incoming Streams]
D --> P[Client Commands]
D --> Q[Periodic Rendezvous Discoveries]
end
The EventLoop's main loop uses the tokio::select! macro that allows waiting on
multiple async computations and returns when a single computation completes :
Swarm Events: Network-related events from libp2p, such as new connections, disconnections, and protocol-specific events. These events are core to managing the peer-to-peer network state.
Incoming Streams: New incoming stream connections from other peers. This allows the node to handle requests and communications initiated by other nodes in the network.
Commands: Instructions received from other parts of the application through a command channel. This enables other components to interact with and control the network operations.
Periodic Rendezvous Discoveries: Regular attempts to discover new peers through the Rendezvous protocol. This helps maintain and expand the node's network of peers.
Each of the events has it's own handler function.
The Swarm is a central construct in libp2p, providing a view of the network from the perspective of a single node. It manages connections, protocols, and peer interactions. In our implementation, the Swarm is defined as:
Swarm<Behaviour>
Where Behaviour is a custom type that implements the NetworkBehaviour trait.
This allows us to define specific network behaviors tailored to our
application's needs.
The Swarm in libp2p combines a Transport (how to send/receive data) with a
NetworkBehaviour (what to do with the connections).
Identity in libp2p is crucial for unique node identification and secure communications. Each node has a Peer ID derived from its cryptographic key pair. This Peer ID is used in multiaddresses, allowing for persistent addressing:
/ip4/192.0.2.0/tcp/443/p2p/QmcEPrat8ShnCph8WjkREzt5CPXF2RwhYxYBALDcLC1iV6
The Peer ID (after /p2p/) enables connections to persist even if IP addresses
change, enhancing network resilience.
Flexible networks need flexible addressing systems. libp2p uses multiaddress
(often abbreviated multiaddr), a convention for encoding multiple layers of
addressing information into a single "future-proof" path structure. Key points
about multiaddrs:
For example:
/ip4/192.0.2.0/udp/1234 specifies an IPv4 address and UDP port./p2p/QmYyQSo1c1Ym7orWxLYvCrM2EmxFTANf8wXmmE7DWjhx5N uniquely identifies a
libp2p node.Combining location and identity information:
/ip4/198.51.100.0/tcp/4242/p2p/QmYyQSo1c1Ym7orWxLYvCrM2EmxFTANf8wXmmE7DWjhx5N
This multiaddr includes both the node's network location (IP and port) and its
identity (Peer ID). Multiaddrs can also represent complex routing scenarios,
like circuit relay:
/ip4/198.51.100.0/tcp/4242/p2p/QmRelay/p2p-circuit/p2p/QmRelayedPeer
This networking crate utilizes Tokio as its asynchronous runtime, leveraging its efficient task scheduler and I/O operations to handle concurrent network activities and event processing.
The networking crate supports multiple transport protocols to ensure wide compatibility and optimal performance:
These protocols are configured as follows:
The Behaviour struct in our implementation combines various libp2p protocols
to create a comprehensive networking solution. These protocols can be grouped
based on their primary functions:
OutboundQueryProgressed: Indicates progress in DHT operations like finding
peers or valuesCALIMERO_KAD_PROTO_NAME)BootstrapConfig, allowing for flexible
network setupThis custom Kademlia setup provides full control over the peer discovery process and network topology, tailored specifically for the Calimero network.
Discovered: New peers found on the local networkDiscovered: Peers found through the rendezvous serverRegisterFailed/DiscoverFailed: Issues with rendezvous operations/calimero/devnet/global)context_idcontext is one gossip topicMessage: New message received on a subscribed topicSubscribed: Successfully subscribed to a topicMessageJsonCodec for
serialization/deserializationMessage struct defined aspub struct Message {
pub data: Vec<u8>,
}
This flexible structure allows for sending arbitrary data between peers.
EventLoop as StreamOpened eventsThe custom stream protocol allows for tailored communication patterns specific to our application needs, complementing the standardized libp2p protocols.
Both Relay and DCUtR work together to improve connectivity in challenging network environments:
Received: Received identify information from a peerOur network employs a multi-faceted approach to peer discovery and connectivity, leveraging several protocols to ensure robust and efficient networking:
Initial Bootstrapping:
Protocol Identification:
Connection Strategies:
Discovery State Management:
Connectivity Enhancements:
Rendezvous Namespace:
Relay Setup:
Continuous Event Processing:
sequenceDiagram
Swarm->>Handle:Event [mDNS Discovered]
activate Handle
loop For non relayed addresses
Handle->>Swarm:Dial
end
deactivate Handle
Swarm->>Handle:Event [Dialing]
Swarm->>+Handle:Event [Connection Established]
Handle->>-Discovery State:Update peer addresses
Swarm->>Handle:Event [Identify Received]
activate Handle
Handle->>Discovery State:Update peer protocols
opt If relay server
opt If reservation required
Handle->>Swarm:Request reservation
Handle->>Discovery State:Update reservation status
end
end
opt If rendezvous server
opt If discovery required
Handle->>Swarm:Request rendezvous discovery
end
opt If registration required
Handle->>Swarm:Request rendezvous registration
end
end
deactivate Handle
Swarm->>Handle:Event [External Addr Confirmed]
activate Handle
Handle->>+Discovery State:Get rendezvous peers
Discovery State-->>-Handle:Peers
loop For selected peers
Handle->>Swarm:Request rendezvous registration
end
deactivate Handle
Swarm->>+Handle:Event [Listening On]
Handle->>-Network Events:Push ListeningOn
Swarm->>Handle:Event [Relay Reservation Req Accepted]
Swarm->>Handle:Event [Rendezvous Discoverd]
activate Handle
Handle->>Discovery State:Update rendezvous cookie
loop For registrations
opt If not connected
Handle->>Swarm:Dial
end
end
deactivate Handle
Swarm->>Handle:Event [Rendezvous Registered]
activate Handle
opt If discovery required
Handle->>Swarm:Request rendezvous discovery
end
deactivate Handle
NetworkClient struct)The NetworkClient serves as the primary interface for other parts of the application to interact with the networking functionality. It provides a clean, easy-to-use API for performing various network operations without directly interacting with the internals of the EventLoop or libp2p.
Key features of the NetworkClient include:
The NetworkClient extensively uses oneshot channels for most of its methods. This involves:
This approach allows for efficient, non-blocking network operations.
The networking crate defines a set of custom NetworkEvents that are emitted to the consumer of the network. These events are distinct from the internal libp2p events and provide high-level information about significant network occurrences.
Key characteristics of NetworkEvents:
The main types of NetworkEvents include:
One of the common techniques used for NAT traversal in P2P networks is Hole Punching. This technique allows two peers, each behind a NAT, to establish a direct connection with each other. Here's a brief explanation:
This technique is particularly useful in P2P networks, as it allows peers to communicate directly, reducing the load on relay servers and improving network efficiency. However, it's worth noting that hole punching may not work with all types of NATs, and success can depend on the specific NAT implementation and configuration.