Skip to main content

karyon_p2p/
handshake.rs

1use std::{collections::HashMap, time::Duration};
2
3use bincode::{Decode, Encode};
4use log::trace;
5use semver::VersionReq;
6
7use karyon_core::async_util::timeout;
8
9use karyon_net::{FramedReader, FramedWriter};
10
11use crate::{
12    Error, PeerID, Result, Version,
13    codec::PeerNetMsgCodec,
14    message::{PeerNetCmd, PeerNetMsg},
15    protocol::{ProtocolFlags, ProtocolID, ProtocolMeta},
16    util::decode,
17    version::{VersionInt, version_match},
18};
19
20/// Negotiated protocol set from a successful handshake.
21pub type NegotiatedProtocols = Vec<ProtocolID>;
22
23/// Writer type for the handshake.
24pub type HandshakeWriter = FramedWriter<PeerNetMsgCodec>;
25
26/// A version and the versions it accepts, as sent on the wire.
27#[derive(Decode, Encode, Debug, Clone)]
28pub struct WireVersion {
29    pub v: VersionInt,
30    pub req: String,
31}
32
33impl From<&Version> for WireVersion {
34    fn from(version: &Version) -> Self {
35        Self {
36            v: version.v.clone(),
37            req: version.req.to_string(),
38        }
39    }
40}
41
42/// Version-exchange message. Both sides send one.
43#[derive(Decode, Encode, Debug, Clone)]
44pub struct VerMsg {
45    pub peer_id: PeerID,
46    pub version: WireVersion,
47    pub protocols: HashMap<ProtocolID, WireVersion>,
48}
49
50/// Answers a Version message; `ack=false` means the sender rejected
51/// the remote version/protocol mix.
52#[derive(Decode, Encode, Debug, Clone)]
53pub struct VerAckMsg {
54    pub peer_id: PeerID,
55    pub ack: bool,
56}
57
58/// Non-IO inputs to the handshake.
59pub struct HandshakeParams<'a> {
60    pub own_id: &'a PeerID,
61    pub config_version: &'a Version,
62    /// Local protocols with metadata (version + kind). Drives both
63    /// version negotiation and the mandatory-subset check.
64    pub protocols: &'a HashMap<ProtocolID, ProtocolMeta>,
65    pub timeout_secs: u64,
66    /// PeerID derived from the secure transport (TLS cert), if any.
67    /// When `Some`, the handshake asserts the peer's claimed `vermsg.peer_id`
68    /// matches it - so a peer can't claim an identity it can't prove.
69    pub verified_peer_id: Option<&'a PeerID>,
70}
71
72/// Run the handshake on split reader/writer. Returns the remote peer ID
73/// and the set of protocols both sides support.
74///
75/// Both sides send a VerMsg, check the remote one with the same rules,
76/// then send a VerAck. So both sides end up with the same protocol set.
77pub async fn handshake(
78    reader: &mut FramedReader<PeerNetMsgCodec>,
79    writer: &mut HandshakeWriter,
80    p: &HandshakeParams<'_>,
81) -> Result<(PeerID, NegotiatedProtocols)> {
82    trace!("Init Handshake");
83
84    send_vermsg(writer, p).await?;
85
86    let t = Duration::from_secs(p.timeout_secs);
87    let msg: PeerNetMsg = timeout(t, reader.recv_msg()).await??;
88    let result = match msg.header.command {
89        PeerNetCmd::Version => validate_version_msg(&msg, p),
90        cmd => Err(Error::InvalidMsg(format!("unexpected msg found {cmd:?}"))),
91    };
92
93    match &result {
94        Ok(_) => send_verack(writer, p.own_id, true).await?,
95        Err(Error::IncompatibleVersion(_)) | Err(Error::IncompatiblePeer) => {
96            send_verack(writer, p.own_id, false).await?;
97        }
98        _ => {}
99    };
100    let (pid, shared) = result?;
101
102    let msg: PeerNetMsg = timeout(t, reader.recv_msg()).await??;
103    match msg.header.command {
104        PeerNetCmd::Verack => validate_verack_msg(&msg, &pid)?,
105        cmd => return Err(Error::InvalidMsg(format!("unexpected msg found {cmd:?}"))),
106    }
107
108    Ok((pid, shared))
109}
110
111async fn send_vermsg(writer: &mut HandshakeWriter, p: &HandshakeParams<'_>) -> Result<()> {
112    let protocols = p
113        .protocols
114        .iter()
115        .map(|(k, m)| (k.clone(), WireVersion::from(&m.version)))
116        .collect();
117
118    let vermsg = VerMsg {
119        peer_id: p.own_id.clone(),
120        version: WireVersion::from(p.config_version),
121        protocols,
122    };
123
124    trace!("Send VerMsg");
125    writer
126        .send_msg(PeerNetMsg::new(PeerNetCmd::Version, &vermsg)?)
127        .await?;
128    Ok(())
129}
130
131/// Sends a Verack message.
132async fn send_verack(writer: &mut HandshakeWriter, own_id: &PeerID, ack: bool) -> Result<()> {
133    let verack = VerAckMsg {
134        peer_id: own_id.clone(),
135        ack,
136    };
137
138    trace!("Send VerAckMsg {verack:?}");
139    writer
140        .send_msg(PeerNetMsg::new(PeerNetCmd::Verack, &verack)?)
141        .await?;
142    Ok(())
143}
144
145/// Validates the given version msg. Returns the remote peer ID and
146/// the negotiated protocol set.
147fn validate_version_msg(
148    msg: &PeerNetMsg,
149    p: &HandshakeParams<'_>,
150) -> Result<(PeerID, NegotiatedProtocols)> {
151    let (vermsg, _) = decode::<VerMsg>(&msg.payload)?;
152
153    if !mutual_match(p.config_version, &vermsg.version) {
154        return Err(Error::IncompatibleVersion("system version".into()));
155    }
156
157    // Bind the claimed PeerID to the secure transport's identity. A peer
158    // with a valid TLS cert for keypair X cannot claim PeerID Y.
159    if let Some(vpid) = p.verified_peer_id
160        && vpid != &vermsg.peer_id
161    {
162        return Err(Error::IncompatiblePeer);
163    }
164
165    let shared = protocols_intersection(p.protocols, &vermsg.protocols);
166
167    if shared.is_empty() {
168        return Err(Error::IncompatiblePeer);
169    }
170
171    // Every protocol the local node marked `REQUIRED` must be in the
172    // negotiated intersection. Otherwise reject the handshake.
173    for (id, meta) in p.protocols.iter() {
174        if meta.flags.contains(ProtocolFlags::REQUIRED) && !shared.iter().any(|p| p == id) {
175            return Err(Error::IncompatiblePeer);
176        }
177    }
178
179    trace!("Received VerMsg from: {}", vermsg.peer_id);
180    Ok((vermsg.peer_id, shared))
181}
182
183/// Validates the given verack msg from the peer that sent `pid`'s VerMsg.
184fn validate_verack_msg(msg: &PeerNetMsg, pid: &PeerID) -> Result<()> {
185    let (verack, _) = decode::<VerAckMsg>(&msg.payload)?;
186
187    if !verack.ack || &verack.peer_id != pid {
188        return Err(Error::IncompatiblePeer);
189    }
190
191    trace!("Received VerAckMsg from: {}", verack.peer_id);
192    Ok(())
193}
194
195/// Compute the intersection of protocols both sides support with
196/// compatible versions. Returns the list of shared protocol IDs.
197fn protocols_intersection(
198    our_protocols: &HashMap<ProtocolID, ProtocolMeta>,
199    their_protocols: &HashMap<ProtocolID, WireVersion>,
200) -> NegotiatedProtocols {
201    let mut shared = Vec::new();
202    for (name, theirs) in their_protocols.iter() {
203        if let Some(our_meta) = our_protocols.get(name)
204            && mutual_match(&our_meta.version, theirs)
205        {
206            shared.push(name.clone());
207        }
208    }
209    shared
210}
211
212/// True when each side accepts the other side's version. Both sides
213/// run the same check, so they agree on the result.
214fn mutual_match(ours: &Version, theirs: &WireVersion) -> bool {
215    let Ok(their_req) = theirs.req.parse::<VersionReq>() else {
216        return false;
217    };
218    version_match(&ours.req, &theirs.v) && version_match(&their_req, &ours.v)
219}