在 CometBFT 节点上运行的每个协议都会实现一个 reactor,并将该实现注册到 p2p 层。
p2p 层会向已注册的 reactor 提供网络事件,其中最主要的两类是与 peer 建立新连接,以及接收到消息。
reactor 则会向 p2p 层提供要发送给 peer 的消息,以及用于控制 p2p 层运行的命令。
需要注意的是,下图中展示的各个组件都会运行多个 routine,且图示中的动作是并行发生的。
例如,连接建立相关的 routine 会并行运行,并发调用图中的 AddPeer 方法。
当连接完全建立后,每个 Peer 实例都会运行一个发送 routine 和一个接收 routine。
发送 routine 会收集来自多个 reactor、发往某个 peer 的消息,将其封装为原始消息后传输给该 peer。
接收 routine 会处理传入消息,并将其转发给目标 reactor,同时调用图中的 Receive 方法。
此外,reactor 还会运行多个 routine,用于与 peer 交互(例如向其发送消息)或与 Switch 交互。
其余文档的组织如下:
-
Reactor API:说明
p2p.Reactor接口,并规定 p2p 层在与 reactor 交互时的行为。 换句话说,这描述的是 p2p 层与协议层之间自底向上的交互。 -
P2P API:说明 p2p
层通过
Switch和Peer抽象向 reactor 提供的接口。 换句话说,这描述的是协议层与 p2p 层之间自顶向下的交互。
Reactor is the generic name for a component that employs the p2p communication layer. This section documents the interaction of the p2p communication layer with the reactors. The diagram below summarizes this interaction, namely the northbound interface of the p2p communication layer, representing some relevant event flows:
Each of the protocols running a CometBFT node implements a reactor and registers
the implementation with the p2p layer.
The p2p layer provides network events to the registered reactors, the main
two being new connections with peers and received messages.
The reactors provide to the p2p layer messages to be sent to
peers and commands to control the operation of the p2p layer.
It is worth noting that the components depicted in the diagram below run
multiple routines and that the illustrated actions happen in parallel.
For instance, the connection establishment routines run in parallel, invoking
the depicted AddPeer method concurrently.
Once a connection is fully established, each Peer instance runs a send and a
receive routines.
The send routine collects messages from multiple reactors to a peer, packaging
then into raw messages which are transmitted to the peer.
The receive routine processes incoming messages and forwards them to the
destination reactors, invoking the depicted Receive methods.
In addition, the reactors run multiple routines for interacting
with the peers (for example, to send messages to them) or with the Switch.
The remaining of the documentation is organized as follows:
-
Reactor API: documents the
p2p.Reactorinterface and specifies the behaviour of the p2p layer when interacting with a reactor. In other words, the interaction of the p2p layer with the protocol layer (bottom-up). -
P2P API: documents the interface provided by the p2p
layer to the reactors, through the
SwitchandPeerabstractions. In other words, the interaction of the protocol layer with the p2p layer (top-down).