Skip to main content

snarkos_node_tcp/protocols/
on_connect.rs

1// Copyright (c) 2019-2026 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
16use std::net::SocketAddr;
17
18use tokio::sync::{mpsc, oneshot};
19use tracing::*;
20
21#[cfg(doc)]
22use crate::{
23    Connection,
24    protocols::{Reading, Writing},
25};
26use crate::{P2P, protocols::ProtocolHandler};
27
28/// Can be used to automatically perform some initial actions once the connection with a peer is
29/// fully established.
30#[async_trait::async_trait]
31pub trait OnConnect: P2P
32where
33    Self: Clone + Send + Sync + 'static,
34{
35    /// Attaches the behavior specified in [`OnConnect::on_connect`] right after every successful
36    /// handshake.
37    async fn enable_on_connect(&self) {
38        let (from_node_sender, mut from_node_receiver) = mpsc::channel::<(
39            SocketAddr,
40            oneshot::Sender<tokio::task::JoinHandle<()>>,
41        )>(self.tcp().config().max_connections as usize);
42
43        // use a channel to know when the on_connect task is ready
44        let (tx, rx) = oneshot::channel::<()>();
45
46        // spawn a background task dedicated to executing the desired post-handshake actions
47        let self_clone = self.clone();
48        let on_connect_task = tokio::spawn(async move {
49            trace!(parent: self_clone.tcp().span(), "spawned the OnConnect handler task");
50            if tx.send(()).is_err() {
51                error!(parent: self_clone.tcp().span(), "OnConnect handler creation interrupted! shutting down the node");
52                self_clone.tcp().shut_down().await;
53                return;
54            }
55
56            while let Some((addr, notifier)) = from_node_receiver.recv().await {
57                let self_clone2 = self_clone.clone();
58                let handle = tokio::spawn(async move {
59                    // perform the specified initial actions
60                    self_clone2.on_connect(addr).await;
61                });
62                // notify the node that the initial actions have concluded
63                let _ = notifier.send(handle); // can't really fail
64            }
65        });
66        let _ = rx.await;
67        self.tcp().tasks.lock().push(on_connect_task);
68
69        // register the OnConnect handler with the Node
70        let hdl = Box::new(ProtocolHandler(from_node_sender));
71        assert!(self.tcp().protocols.on_connect.set(hdl).is_ok(), "the OnConnect protocol was enabled more than once!");
72    }
73
74    /// Any initial actions to be executed after the handshake is concluded; in order to be able to
75    /// communicate with the peer in the usual manner (i.e. via [`Writing`]), only its [`SocketAddr`]
76    /// (as opposed to the related [`Connection`] object) is provided as an argument.
77    async fn on_connect(&self, addr: SocketAddr);
78}