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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
use std::{
    fmt::{Display, Error as FmtError, Formatter},
    mem::size_of,
};

use log::warn;
use parity_scale_codec::{Decode, Encode, Error as CodecError, Input as CodecInput};

use crate::{
    network::{session::Authentication, AddressingInformation},
    SessionId, Version,
};

type ByteCount = u16;

// We allow sending authentications of size up to 16KiB, that should be enough.
const MAX_AUTHENTICATION_SIZE: u16 = 16 * 1024;

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum VersionedAuthentication<A: AddressingInformation> {
    // Most likely from the future.
    Other(Version, Vec<u8>),
    V2(Authentication<A>),
}

impl<A: AddressingInformation> From<Authentication<A>> for Vec<VersionedAuthentication<A>> {
    fn from(authentication: Authentication<A>) -> Self {
        vec![VersionedAuthentication::V2(authentication)]
    }
}

pub type DiscoveryMessage<A> = Authentication<A>;

impl<A: AddressingInformation> DiscoveryMessage<A> {
    /// Session ID associated with this message.
    pub fn session_id(&self) -> SessionId {
        self.0.session()
    }
}

impl<A: AddressingInformation> TryInto<DiscoveryMessage<A>> for VersionedAuthentication<A> {
    type Error = Error;

    fn try_into(self) -> Result<DiscoveryMessage<A>, Self::Error> {
        use VersionedAuthentication::*;
        match self {
            V2(authentication) => Ok(authentication),
            Other(v, _) => Err(Error::UnknownVersion(v)),
        }
    }
}

fn encode_with_version(version: Version, payload: &[u8]) -> Vec<u8> {
    // If size is bigger then u16 we set it to MAX_AUTHENTICATION_SIZE.
    // This should never happen but in case it does we will not panic.
    // Also for other users if they have this version of protocol, authentication
    // will be decoded. If they do not know the protocol, authentication will result
    // in decoding error.
    // We do not have a guarantee that size_hint is implemented for DiscoveryMessage, so we need
    // to compute actual size to place it in the encoded data.
    let size = payload
        .len()
        .try_into()
        .unwrap_or(MAX_AUTHENTICATION_SIZE + 1);
    if size > MAX_AUTHENTICATION_SIZE {
        warn!(
            "Versioned Authentication v{:?} too big during Encode. Size is {:?}. Should be {:?} at max.",
            version,
            payload.len(),
            MAX_AUTHENTICATION_SIZE
        );
    }

    let mut result = Vec::with_capacity(version.size_hint() + size.size_hint() + payload.len());

    version.encode_to(&mut result);
    size.encode_to(&mut result);
    result.extend_from_slice(payload);

    result
}

impl<A: AddressingInformation> Encode for VersionedAuthentication<A> {
    fn size_hint(&self) -> usize {
        use VersionedAuthentication::*;
        let version_size = size_of::<Version>();
        let byte_count_size = size_of::<ByteCount>();
        version_size
            + byte_count_size
            + match self {
                Other(_, payload) => payload.len(),
                V2(data) => data.size_hint(),
            }
    }

    fn encode(&self) -> Vec<u8> {
        use VersionedAuthentication::*;
        match self {
            Other(version, payload) => encode_with_version(*version, payload),
            V2(data) => encode_with_version(Version(2), &data.encode()),
        }
    }
}

impl<A: AddressingInformation> Decode for VersionedAuthentication<A> {
    fn decode<I: CodecInput>(input: &mut I) -> Result<Self, CodecError> {
        use VersionedAuthentication::*;
        let version = Version::decode(input)?;
        let num_bytes = ByteCount::decode(input)?;
        match version {
            Version(2) => Ok(V2(Authentication::decode(input)?)),
            _ => {
                if num_bytes > MAX_AUTHENTICATION_SIZE {
                    Err("Authentication has unknown version and is encoded as more than 16KiB.")?;
                };
                let mut payload = vec![0; num_bytes.into()];
                input.read(payload.as_mut_slice())?;
                Ok(Other(version, payload))
            }
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Error {
    UnknownVersion(Version),
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
        use Error::*;
        match self {
            UnknownVersion(version) => {
                write!(f, "Authentication has unknown version {}", version.0)
            }
        }
    }
}

#[cfg(test)]
mod test {
    use std::sync::Arc;

    use network_clique::mock::MockAddressingInformation;
    use parity_scale_codec::{Decode, Encode};
    use sp_keystore::testing::MemoryKeystore as Keystore;

    use super::VersionedAuthentication;
    use crate::{
        crypto::AuthorityVerifier,
        network::{
            session::{compatibility::MAX_AUTHENTICATION_SIZE, SessionHandler},
            tcp::{testing::new_identity, SignedTcpAddressingInformation},
            NetworkIdentity,
        },
        nodes::new_pen,
        NodeIndex, SessionId, Version,
    };

    /// Session Handler used for generating versioned authentication in `raw_authentication_v1`
    fn handler() -> SessionHandler<SignedTcpAddressingInformation> {
        let mnemonic = "ring cool spatial rookie need wing opinion pond fork garbage more april";
        let external_addresses = vec![
            String::from("addr1"),
            String::from("addr2"),
            String::from("addr3"),
        ];

        let keystore = Arc::new(Keystore::new());
        let pen = new_pen(mnemonic, keystore);
        let identity = new_identity(external_addresses, &pen);

        SessionHandler::new(
            Some((NodeIndex(21), pen)),
            AuthorityVerifier::new(vec![]),
            SessionId(37),
            identity.identity(),
        )
    }

    fn authentication_v2(
        handler: SessionHandler<SignedTcpAddressingInformation>,
    ) -> VersionedAuthentication<SignedTcpAddressingInformation> {
        VersionedAuthentication::V2(
            handler
                .authentication()
                .expect("should have authentication"),
        )
    }

    /// Versioned authentication for authority with:
    /// external_addresses: [String::from("addr1"), String::from("addr2"), String::from("addr3")]
    /// derived from mnemonic "ring cool spatial rookie need wing opinion pond fork garbage more april"
    /// for node index 21 and session id 37
    /// encoded at version of Phron Node after 8.0
    fn raw_authentication_v2() -> Vec<u8> {
        vec![
            2, 0, 191, 0, 50, 40, 192, 239, 72, 72, 119, 156, 76, 37, 212, 220, 76, 165, 39, 73,
            20, 89, 77, 66, 171, 174, 61, 31, 254, 137, 186, 1, 7, 141, 187, 219, 20, 97, 100, 100,
            114, 49, 8, 20, 97, 100, 100, 114, 50, 20, 97, 100, 100, 114, 51, 193, 134, 174, 215,
            223, 67, 113, 105, 253, 217, 120, 59, 47, 176, 146, 72, 205, 114, 242, 242, 115, 214,
            97, 112, 69, 56, 119, 168, 164, 170, 74, 7, 97, 149, 53, 122, 42, 209, 198, 146, 6,
            169, 37, 242, 131, 152, 209, 10, 52, 78, 218, 52, 69, 81, 235, 254, 58, 44, 134, 201,
            119, 132, 5, 8, 21, 0, 0, 0, 0, 0, 0, 0, 37, 0, 0, 0, 230, 134, 124, 175, 213, 131, 76,
            99, 89, 247, 169, 129, 87, 134, 249, 172, 99, 77, 203, 254, 12, 171, 178, 163, 47, 145,
            104, 166, 75, 174, 164, 119, 197, 78, 101, 221, 52, 51, 116, 221, 67, 45, 196, 65, 61,
            5, 246, 111, 56, 215, 145, 48, 170, 241, 60, 68, 231, 187, 72, 201, 18, 82, 249, 11,
        ]
    }

    #[test]
    fn correcly_encodes_v2_to_bytes() {
        let handler = handler();
        let raw = raw_authentication_v2();
        let authentication_v2 = authentication_v2(handler);

        assert_eq!(authentication_v2.encode(), raw);
    }

    #[test]
    fn correcly_decodes_v2_from_bytes() {
        let handler = handler();
        let raw = raw_authentication_v2();
        let authentication_v2 = authentication_v2(handler);

        let decoded = VersionedAuthentication::decode(&mut raw.as_slice());

        assert_eq!(decoded, Ok(authentication_v2));
    }

    #[test]
    fn correctly_decodes_v2_roundtrip() {
        let handler = handler();
        let authentication_v2 = authentication_v2(handler);

        let encoded = authentication_v2.encode();
        let decoded = VersionedAuthentication::decode(&mut encoded.as_slice());

        assert_eq!(decoded, Ok(authentication_v2))
    }

    #[test]
    fn correctly_decodes_other() {
        let other =
            VersionedAuthentication::<MockAddressingInformation>::Other(Version(42), vec![21, 37]);
        let encoded = other.encode();
        let decoded = VersionedAuthentication::decode(&mut encoded.as_slice());
        assert_eq!(decoded, Ok(other));

        let mut other_big = 42u16.encode();
        other_big.append(&mut (MAX_AUTHENTICATION_SIZE).encode());
        other_big.append(&mut vec![0u8; (MAX_AUTHENTICATION_SIZE).into()]);
        let decoded =
            VersionedAuthentication::<MockAddressingInformation>::decode(&mut other_big.as_slice());
        assert_eq!(
            decoded,
            Ok(VersionedAuthentication::<MockAddressingInformation>::Other(
                Version(42),
                other_big[4..].to_vec()
            ))
        );
    }

    #[test]
    fn returns_error_other_too_big() {
        let mut other = 42u16.encode();
        let size = MAX_AUTHENTICATION_SIZE + 1;
        other.append(&mut size.encode());
        other.append(&mut vec![0u8; size.into()]);
        let decoded =
            VersionedAuthentication::<MockAddressingInformation>::decode(&mut other.as_slice());
        assert!(decoded.is_err());

        let other = VersionedAuthentication::<MockAddressingInformation>::Other(
            Version(42),
            vec![0u8; size.into()],
        );
        let encoded = other.encode();
        let decoded =
            VersionedAuthentication::<MockAddressingInformation>::decode(&mut encoded.as_slice());
        assert!(decoded.is_err());
    }

    #[test]
    fn returns_error_other_wrong_size() {
        let mut other = 42u16.encode();
        other.append(&mut MAX_AUTHENTICATION_SIZE.encode());
        other.append(&mut vec![21, 37]);
        let decoded =
            VersionedAuthentication::<MockAddressingInformation>::decode(&mut other.as_slice());
        assert!(decoded.is_err());
    }
}