Skip to main content

zebra_network/peer/
connector.rs

1//! Wrapper around handshake logic that also opens a TCP connection.
2
3use std::{
4    net::SocketAddr,
5    pin::Pin,
6    task::{Context, Poll},
7};
8
9use futures::prelude::*;
10use tokio::net::TcpStream;
11use tower::{Service, ServiceExt};
12use tracing::Instrument;
13
14use zebra_chain::chain_tip::{ChainTip, NoChainTip};
15
16use crate::{
17    peer::{Client, ConnectedAddr, Handshake, HandshakeRequest},
18    peer_set::ConnectionTracker,
19    BoxError, PeerSocketAddr, Request, Response,
20};
21
22/// A wrapper around [`Handshake`] that opens a TCP connection before
23/// forwarding to the inner handshake service. Writing this as its own
24/// [`tower::Service`] lets us apply unified timeout policies, etc.
25pub struct Connector<S, C = NoChainTip>
26where
27    S: Service<Request, Response = Response, Error = BoxError> + Clone + Send + 'static,
28    S::Future: Send,
29    C: ChainTip + Clone + Send + 'static,
30{
31    handshaker: Handshake<S, C>,
32}
33
34impl<S, C> Clone for Connector<S, C>
35where
36    S: Service<Request, Response = Response, Error = BoxError> + Clone + Send + 'static,
37    S::Future: Send,
38    C: ChainTip + Clone + Send + 'static,
39{
40    fn clone(&self) -> Self {
41        Connector {
42            handshaker: self.handshaker.clone(),
43        }
44    }
45}
46
47impl<S, C> Connector<S, C>
48where
49    S: Service<Request, Response = Response, Error = BoxError> + Clone + Send + 'static,
50    S::Future: Send,
51    C: ChainTip + Clone + Send + 'static,
52{
53    pub fn new(handshaker: Handshake<S, C>) -> Self {
54        Connector { handshaker }
55    }
56}
57
58/// A connector request.
59/// Contains the information needed to make an outbound connection to the peer.
60pub struct OutboundConnectorRequest {
61    /// The Zcash listener address of the peer.
62    pub addr: PeerSocketAddr,
63
64    /// A connection tracker that reduces the open connection count when dropped.
65    ///
66    /// Used to limit the number of open connections in Zebra.
67    pub connection_tracker: ConnectionTracker,
68}
69
70impl<S, C> Service<OutboundConnectorRequest> for Connector<S, C>
71where
72    S: Service<Request, Response = Response, Error = BoxError> + Clone + Send + 'static,
73    S::Future: Send,
74    C: ChainTip + Clone + Send + 'static,
75{
76    type Response = (PeerSocketAddr, Client);
77    type Error = BoxError;
78    type Future =
79        Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
80
81    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
82        Poll::Ready(Ok(()))
83    }
84
85    fn call(&mut self, req: OutboundConnectorRequest) -> Self::Future {
86        let OutboundConnectorRequest {
87            addr,
88            connection_tracker,
89        }: OutboundConnectorRequest = req;
90
91        let hs = self.handshaker.clone();
92        let connected_addr = ConnectedAddr::new_outbound_direct(addr);
93        let connector_span = info_span!("connector", peer = ?connected_addr);
94
95        // # Security
96        //
97        // `zebra_network::init()` implements a connection timeout on this future.
98        // Any code outside this future does not have a timeout.
99        async move {
100            let tcp_stream = connect_tcp_nodelay(*addr).await?;
101            let client = hs
102                .oneshot(HandshakeRequest::<TcpStream> {
103                    data_stream: tcp_stream,
104                    connected_addr,
105                    connection_tracker,
106                })
107                .await?;
108            Ok((addr, client))
109        }
110        .instrument(connector_span)
111        .boxed()
112    }
113}
114
115/// Opens a TCP connection to the peer at `addr`, with [`set_tcp_nodelay`] applied.
116pub(crate) async fn connect_tcp_nodelay(addr: SocketAddr) -> std::io::Result<TcpStream> {
117    let tcp_stream = TcpStream::connect(addr).await?;
118    set_tcp_nodelay(&tcp_stream);
119
120    Ok(tcp_stream)
121}
122
123/// Disables Nagle's algorithm on a peer's TCP connection.
124///
125/// Zebra writes each message to the socket in one flush, so this does not split messages
126/// into extra packets. But with Nagle's algorithm, a small message sent straight after
127/// another small message waits until the peer acknowledges the first one, and peers can
128/// delay that acknowledgement for 40ms or more. For example, this happens to a response
129/// with a `tx` and a `notfound` message, or to a request sent right after an `inv`.
130///
131/// zcashd and Bitcoin Core also disable Nagle's algorithm on their peer connections.
132pub(crate) fn set_tcp_nodelay(tcp_stream: &TcpStream) {
133    if let Err(error) = tcp_stream.set_nodelay(true) {
134        debug!(
135            ?error,
136            "failed to disable Nagle's algorithm on peer connection"
137        );
138    }
139}