snarkos_node_tcp/protocols/on_connect.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
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::unbounded_channel::<(SocketAddr, oneshot::Sender<()>)>();
39
40 // use a channel to know when the on_connect task is ready
41 let (tx, rx) = oneshot::channel::<()>();
42
43 // spawn a background task dedicated to executing the desired post-handshake actions
44 let self_clone = self.clone();
45 let on_connect_task = tokio::spawn(async move {
46 trace!(parent: self_clone.tcp().span(), "spawned the OnConnect handler task");
47 if tx.send(()).is_err() {
48 error!(parent: self_clone.tcp().span(), "OnConnect handler creation interrupted! shutting down the node");
49 self_clone.tcp().shut_down().await;
50 return;
51 }
52
53 while let Some((addr, notifier)) = from_node_receiver.recv().await {
54 let self_clone2 = self_clone.clone();
55 tokio::spawn(async move {
56 // perform the specified initial actions
57 self_clone2.on_connect(addr).await;
58 // notify the node that the initial actions have concluded
59 let _ = notifier.send(()); // can't really fail
60 });
61 }
62 });
63 let _ = rx.await;
64 self.tcp().tasks.lock().push(on_connect_task);
65
66 // register the OnConnect handler with the Node
67 let hdl = Box::new(ProtocolHandler(from_node_sender));
68 assert!(self.tcp().protocols.on_connect.set(hdl).is_ok(), "the OnConnect protocol was enabled more than once!");
69 }
70
71 /// Any initial actions to be executed after the handshake is concluded; in order to be able to
72 /// communicate with the peer in the usual manner (i.e. via [`Writing`]), only its [`SocketAddr`]
73 /// (as opposed to the related [`Connection`] object) is provided as an argument.
74 async fn on_connect(&self, addr: SocketAddr);
75}