kona_node_service/actors/network/
driver.rs

1use alloy_primitives::Address;
2use futures::future::OptionFuture;
3use kona_p2p::{ConnectionGater, Discv5Driver, GossipDriver, PEER_SCORE_INSPECT_FREQUENCY};
4use kona_sources::{BlockSigner, BlockSignerStartError};
5use libp2p::TransportError;
6use tokio::sync::watch;
7
8use crate::actors::network::handler::NetworkHandler;
9
10/// A network driver. This is the driver that is used to start the network.
11#[derive(Debug)]
12pub struct NetworkDriver {
13    /// The gossip driver.
14    pub gossip: GossipDriver<ConnectionGater>,
15    /// The discovery driver.
16    pub discovery: Discv5Driver,
17    /// The unsafe block signer sender.
18    pub unsafe_block_signer_sender: watch::Sender<Address>,
19    /// A block signer. This is optional and should be set if the node is configured to sign blocks
20    pub signer: Option<BlockSigner>,
21}
22
23/// An error from the [`NetworkDriver`].
24#[derive(Debug, thiserror::Error)]
25pub enum NetworkDriverError {
26    /// An error occurred starting the libp2p Swarm.
27    #[error("error starting libp2p Swarm")]
28    GossipStartError(#[from] TransportError<std::io::Error>),
29    /// An error occurred starting the block signer client.
30    #[error("error starting block signer client: {0}")]
31    BlockSignerStartError(#[from] BlockSignerStartError),
32}
33
34impl NetworkDriver {
35    /// Starts the network.
36    pub async fn start(mut self) -> Result<NetworkHandler, NetworkDriverError> {
37        // Start the discovery service.
38        let (handler, enr_receiver) = self.discovery.start();
39
40        // Start the libp2p Swarm
41        self.gossip.start().await?;
42
43        // We are checking the peer scores every [`PEER_SCORE_INSPECT_FREQUENCY`] seconds.
44        let peer_score_inspector = tokio::time::interval(*PEER_SCORE_INSPECT_FREQUENCY);
45
46        // Start the block signer if it is configured.
47        let signer =
48            OptionFuture::from(self.signer.map(async |s| s.start().await)).await.transpose()?;
49
50        Ok(NetworkHandler {
51            gossip: self.gossip,
52            discovery: handler,
53            enr_receiver,
54            unsafe_block_signer_sender: self.unsafe_block_signer_sender,
55            peer_score_inspector,
56            signer,
57        })
58    }
59}