snarkos_node_sync_communication_service/
lib.rs

1// Copyright (c) 2019-2025 Provable Inc.
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
16#![forbid(unsafe_code)]
17
18#[macro_use]
19extern crate async_trait;
20
21use std::{io, net::SocketAddr};
22use tokio::sync::oneshot;
23
24/// Abstract communication service.
25///
26/// Implemented by `Gateway` and `Client`.
27#[async_trait]
28pub trait CommunicationService: Send + Sync {
29    /// The message type used by this communication service.
30    type Message: Clone;
31
32    /// Generates the service-specific message for a block request.
33    fn prepare_block_request(start: u32, end: u32) -> Self::Message;
34
35    /// Sends the given message to specified peer.
36    ///
37    /// This function returns as soon as the message is queued to be sent,
38    /// without waiting for the actual delivery; instead, the caller is provided with a [`oneshot::Receiver`]
39    /// which can be used to determine when and whether the message has been delivered.
40    /// If no peer with the given IP exists, this function returns None.
41    async fn send(&self, peer_ip: SocketAddr, message: Self::Message) -> Option<oneshot::Receiver<io::Result<()>>>;
42
43    /// Mark a peer to be removed and (temporarily) banned.
44    fn ban_peer(&self, peer_ip: SocketAddr);
45}
46
47#[cfg(any(test, feature = "test-helpers"))]
48pub mod test_helpers {
49    use super::*;
50
51    use parking_lot::Mutex;
52
53    #[derive(Clone)]
54    pub struct DummyMessage {}
55
56    /// A communication service that does not do anything (for testing).
57    #[derive(Default)]
58    pub struct DummyCommunicationService {
59        // Any ban requests will be stored here.
60        pub peers_to_ban: Mutex<Vec<SocketAddr>>,
61    }
62
63    #[async_trait]
64    impl CommunicationService for DummyCommunicationService {
65        type Message = DummyMessage;
66
67        fn prepare_block_request(_start: u32, _end: u32) -> Self::Message {
68            Self::Message {}
69        }
70
71        async fn send(
72            &self,
73            _peer_ip: SocketAddr,
74            _message: Self::Message,
75        ) -> Option<oneshot::Receiver<io::Result<()>>> {
76            None
77        }
78
79        fn ban_peer(&self, peer_ip: SocketAddr) {
80            self.peers_to_ban.lock().push(peer_ip);
81        }
82    }
83}