1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

//! Protocol used to exchange supported protocol information with a remote.

use crate::protocols::wire::handshake::v1::HandshakeMsg;
use bytes::BytesMut;
use futures::io::{AsyncRead, AsyncWrite, AsyncWriteExt};
use netcore::framing::{read_u16frame, write_u16frame};
use std::io;

/// The Handshake exchange protocol.
pub async fn exchange_handshake<T>(
    own_handshake: &HandshakeMsg,
    socket: &mut T,
) -> io::Result<HandshakeMsg>
where
    T: AsyncRead + AsyncWrite + Unpin,
{
    // Send serialized handshake message to remote peer.
    let msg = bcs::to_bytes(own_handshake).map_err(|e| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            format!("Failed to serialize identity msg: {}", e),
        )
    })?;
    write_u16frame(socket, &msg).await?;
    socket.flush().await?;

    // Read handshake message from the Remote
    let mut response = BytesMut::new();
    read_u16frame(socket, &mut response).await?;
    let identity = bcs::from_bytes(&response).map_err(|e| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            format!("Failed to parse identity msg: {}", e),
        )
    })?;
    Ok(identity)
}

#[cfg(test)]
mod tests {
    use crate::{
        protocols::{
            identity::exchange_handshake,
            wire::handshake::v1::{HandshakeMsg, MessagingProtocolVersion},
        },
        ProtocolId,
    };
    use diem_config::network_id::NetworkId;
    use diem_types::chain_id::ChainId;
    use futures::{executor::block_on, future::join};
    use memsocket::MemorySocket;
    use std::collections::BTreeMap;

    fn build_test_connection() -> (MemorySocket, MemorySocket) {
        MemorySocket::new_pair()
    }

    #[test]
    fn simple_handshake() {
        let network_id = NetworkId::Validator;
        let chain_id = ChainId::test();
        let (mut outbound, mut inbound) = build_test_connection();

        // Create client and server handshake messages.
        let mut supported_protocols = BTreeMap::new();
        supported_protocols.insert(
            MessagingProtocolVersion::V1,
            [
                ProtocolId::ConsensusDirectSend,
                ProtocolId::MempoolDirectSend,
            ]
            .iter()
            .into(),
        );
        let server_handshake = HandshakeMsg {
            chain_id,
            network_id: network_id.clone(),
            supported_protocols,
        };
        let mut supported_protocols = BTreeMap::new();
        supported_protocols.insert(
            MessagingProtocolVersion::V1,
            [ProtocolId::ConsensusRpc, ProtocolId::ConsensusDirectSend]
                .iter()
                .into(),
        );
        let client_handshake = HandshakeMsg {
            supported_protocols,
            chain_id,
            network_id,
        };

        let server_handshake_clone = server_handshake.clone();
        let client_handshake_clone = client_handshake.clone();

        let server = async move {
            let handshake = exchange_handshake(&server_handshake, &mut inbound)
                .await
                .expect("Handshake fails");

            assert_eq!(
                bcs::to_bytes(&handshake).unwrap(),
                bcs::to_bytes(&client_handshake_clone).unwrap()
            );
        };

        let client = async move {
            let handshake = exchange_handshake(&client_handshake, &mut outbound)
                .await
                .expect("Handshake fails");

            assert_eq!(
                bcs::to_bytes(&handshake).unwrap(),
                bcs::to_bytes(&server_handshake_clone).unwrap()
            );
        };

        block_on(join(server, client));
    }

    #[test]
    fn handshake_chain_id_mismatch() {
        let (mut outbound, mut inbound) = MemorySocket::new_pair();

        // server state
        let server_handshake = HandshakeMsg::new_for_testing();

        // client state
        let mut client_handshake = server_handshake.clone();
        client_handshake.chain_id = ChainId::new(client_handshake.chain_id.id() + 1);

        // perform the handshake negotiation
        let server = async move {
            let remote_handshake = exchange_handshake(&server_handshake, &mut inbound)
                .await
                .unwrap();
            server_handshake
                .perform_handshake(&remote_handshake)
                .unwrap_err()
        };

        let client = async move {
            let remote_handshake = exchange_handshake(&client_handshake, &mut outbound)
                .await
                .unwrap();
            client_handshake
                .perform_handshake(&remote_handshake)
                .unwrap_err()
        };

        block_on(join(server, client));
    }

    #[test]
    fn handshake_network_id_mismatch() {
        let (mut outbound, mut inbound) = MemorySocket::new_pair();

        // server state
        let server_handshake = HandshakeMsg::new_for_testing();

        // client state
        let mut client_handshake = server_handshake.clone();
        client_handshake.network_id = NetworkId::Public;

        // perform the handshake negotiation
        let server = async move {
            let remote_handshake = exchange_handshake(&server_handshake, &mut inbound)
                .await
                .unwrap();
            server_handshake
                .perform_handshake(&remote_handshake)
                .unwrap_err()
        };

        let client = async move {
            let remote_handshake = exchange_handshake(&client_handshake, &mut outbound)
                .await
                .unwrap();
            client_handshake
                .perform_handshake(&remote_handshake)
                .unwrap_err()
        };

        block_on(join(server, client));
    }
}