snarkos_node_router/
routing.rs

1// Copyright 2024-2025 Aleo Network Foundation
2// This file is part of the snarkOS library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use crate::{Heartbeat, Inbound, Outbound};
17use snarkos_node_tcp::{
18    P2P,
19    protocols::{Disconnect, Handshake, OnConnect},
20};
21use snarkvm::prelude::Network;
22
23use core::time::Duration;
24
25#[async_trait]
26pub trait Routing<N: Network>:
27    P2P + Disconnect + OnConnect + Handshake + Inbound<N> + Outbound<N> + Heartbeat<N>
28{
29    /// Initialize the routing.
30    async fn initialize_routing(&self) {
31        // Enable the TCP protocols.
32        self.enable_handshake().await;
33        self.enable_reading().await;
34        self.enable_writing().await;
35        self.enable_disconnect().await;
36        self.enable_on_connect().await;
37        // Enable the TCP listener. Note: This must be called after the above protocols.
38        self.enable_listener().await;
39        // Initialize the heartbeat.
40        self.initialize_heartbeat();
41    }
42
43    // Start listening for inbound connections.
44    async fn enable_listener(&self) {
45        self.tcp().enable_listener().await.expect("Failed to enable the TCP listener");
46    }
47
48    /// Initialize a new instance of the heartbeat.
49    fn initialize_heartbeat(&self) {
50        let self_clone = self.clone();
51        self.router().spawn(async move {
52            loop {
53                // Process a heartbeat in the router.
54                self_clone.heartbeat();
55                // Sleep for `HEARTBEAT_IN_SECS` seconds.
56                tokio::time::sleep(Duration::from_secs(Self::HEARTBEAT_IN_SECS)).await;
57            }
58        });
59    }
60}