share-nodesP2P Protocol

Build a custom P2P protocol

Introduction

Direct P2P communication that opens a stream between two peers can be achieved by building a custom P2P protocol.

To call a specific peer, its multiaddress is required. While all peers are connected through algorithms using a Kademlia DHT (distributed hash table), not all peers are directly connected. In a P2P network, “connected” does not mean “directly connected.” It means reachable through other peers. Unlike using a GossipSub, where you don't need a peer's multiaddress for them to receive a message, it's required while using direct P2P communication.

Acquiring A Multiaddress

A peer's multiaddress can be stored on-chain and fetched there (a node adding a multiaddress on-chain is optional, but can be required by subnets to allow them into the subnets P2P network); the subnet can set up a heartbeat system using a GossipSub that shares each peer's multiaddress, or a peer can ask a directly connected peer for another peer's multiaddress from itself or its neighbors.

Once a multiaddress is acquired, then a peer can reach out to the desired peer.

Building Custom Protocol

Building a custom P2P protocol for the subnets use case or use cases is achieved by inheriting the ProtocolBase template class.

Define the protobuf messages

syntax = "proto3";

package task_protocol.pb;

message TaskRequest {
  string task_id = 1;
  bytes payload = 2;
}

message TaskResponse {
  bool accepted = 1;
  bytes result = 2;
  string error = 3;
}

Generate the Python protobuf module from the repository root:

This creates subnet/protocols/pb/task_protocol_pb2.py and, when mypy-protobuf is installed, subnet/protocols/pb/task_protocol_pb2.pyi. If you are not generating type stubs, omit --mypy_out=.. To regenerate it through the Makefile, add the proto path to the PB variable.

Create a protocol class

This is achieved by subclassing ProtobufRequestResponseProtocolTemplate:

Instantiate the protocol

The base class registers the stream handler automatically.

Last updated