snarkos_node_tcp/protocols/
mod.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//! Opt-in protocols available to the node; each protocol is expected to spawn its own task that runs throughout the
17//! node's lifetime and handles a specific functionality. The communication with these tasks is done via dedicated
18//! handler objects.
19
20use std::{io, net::SocketAddr};
21
22use once_cell::race::OnceBox;
23use tokio::sync::{mpsc, oneshot};
24
25use crate::connections::Connection;
26
27mod disconnect;
28mod handshake;
29mod on_connect;
30mod reading;
31mod writing;
32
33pub use disconnect::Disconnect;
34pub use handshake::Handshake;
35pub use on_connect::OnConnect;
36pub use reading::Reading;
37pub use writing::Writing;
38
39#[derive(Default)]
40pub(crate) struct Protocols {
41    pub(crate) handshake: OnceBox<ProtocolHandler<Connection, io::Result<Connection>>>,
42    pub(crate) reading: OnceBox<ProtocolHandler<Connection, io::Result<Connection>>>,
43    pub(crate) writing: OnceBox<writing::WritingHandler>,
44    pub(crate) on_connect: OnceBox<ProtocolHandler<SocketAddr, ()>>,
45    pub(crate) disconnect: OnceBox<ProtocolHandler<SocketAddr, ()>>,
46}
47
48/// An object sent to a protocol handler task; the task assumes control of a protocol-relevant item `T`,
49/// and when it's done with it, it returns it (possibly in a wrapper object) or another relevant object
50/// to the callsite via the counterpart [`oneshot::Receiver`].
51pub(crate) type ReturnableItem<T, U> = (T, oneshot::Sender<U>);
52
53pub(crate) type ReturnableConnection = ReturnableItem<Connection, io::Result<Connection>>;
54
55pub(crate) struct ProtocolHandler<T, U>(mpsc::UnboundedSender<ReturnableItem<T, U>>);
56
57pub(crate) trait Protocol<T, U> {
58    fn trigger(&self, item: ReturnableItem<T, U>);
59}
60
61impl<T, U> Protocol<T, U> for ProtocolHandler<T, U> {
62    fn trigger(&self, item: ReturnableItem<T, U>) {
63        // ignore errors; they can only happen if a disconnect interrupts the protocol setup process
64        let _ = self.0.send(item);
65    }
66}