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
44#[cfg(any(test, feature = "test-helpers"))]
45pub mod test_helpers {
46 use super::*;
47
48 #[derive(Clone)]
49 pub struct DummyMessage {}
50
51 /// A communication service that does not do anything (for testing).
52 #[derive(Default)]
53 pub struct DummyCommunicationService;
54
55 #[async_trait]
56 impl CommunicationService for DummyCommunicationService {
57 type Message = DummyMessage;
58
59 fn prepare_block_request(_start: u32, _end: u32) -> Self::Message {
60 Self::Message {}
61 }
62
63 async fn send(
64 &self,
65 _peer_ip: SocketAddr,
66 _message: Self::Message,
67 ) -> Option<oneshot::Receiver<io::Result<()>>> {
68 None
69 }
70 }
71}