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 anyhow::anyhow;
use diem_config::network_id::NetworkId;
use diem_types::chain_id::ChainId;
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, convert::TryInto, fmt, iter::Iterator};
use thiserror::Error;
#[cfg(any(test, feature = "fuzzing"))]
use proptest_derive::Arbitrary;
#[cfg(test)]
mod test;
#[repr(u8)]
#[derive(Clone, Copy, Hash, Eq, PartialEq, Deserialize, Serialize)]
#[cfg_attr(any(test, feature = "fuzzing"), derive(Arbitrary))]
pub enum ProtocolId {
ConsensusRpc = 0,
ConsensusDirectSend = 1,
MempoolDirectSend = 2,
StateSyncDirectSend = 3,
DiscoveryDirectSend = 4,
HealthCheckerRpc = 5,
ConsensusDirectSendJSON = 6,
}
impl ProtocolId {
pub fn as_str(self) -> &'static str {
use ProtocolId::*;
match self {
ConsensusRpc => "ConsensusRpc",
ConsensusDirectSend => "ConsensusDirectSend",
MempoolDirectSend => "MempoolDirectSend",
StateSyncDirectSend => "StateSyncDirectSend",
DiscoveryDirectSend => "DiscoveryDirectSend",
HealthCheckerRpc => "HealthCheckerRpc",
ConsensusDirectSendJSON => "ConsensusDirectSendJson",
}
}
pub fn all() -> &'static [ProtocolId] {
&[
ProtocolId::ConsensusRpc,
ProtocolId::ConsensusDirectSend,
ProtocolId::MempoolDirectSend,
ProtocolId::StateSyncDirectSend,
ProtocolId::DiscoveryDirectSend,
ProtocolId::HealthCheckerRpc,
ProtocolId::ConsensusDirectSendJSON,
]
}
pub fn to_bytes<T: Serialize>(&self, value: &T) -> anyhow::Result<Vec<u8>> {
match self {
ProtocolId::ConsensusDirectSendJSON => {
serde_json::to_vec(value).map_err(|e| anyhow!("{:?}", e))
}
_ => bcs::to_bytes(value).map_err(|e| anyhow! {"{:?}", e}),
}
}
pub fn from_bytes<'a, T: Deserialize<'a>>(&self, bytes: &'a [u8]) -> anyhow::Result<T> {
match self {
ProtocolId::ConsensusDirectSendJSON => {
serde_json::from_slice(bytes).map_err(|e| anyhow!("{:?}", e))
}
_ => bcs::from_bytes(bytes).map_err(|e| anyhow! {"{:?}", e}),
}
}
}
impl fmt::Debug for ProtocolId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl fmt::Display for ProtocolId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
#[cfg_attr(any(test, feature = "fuzzing"), derive(Arbitrary))]
pub struct SupportedProtocols(bitvec::BitVec);
impl TryInto<Vec<ProtocolId>> for SupportedProtocols {
type Error = bcs::Error;
fn try_into(self) -> bcs::Result<Vec<ProtocolId>> {
let mut protocols = Vec::with_capacity(self.0.count_ones() as usize);
if let Some(last_bit) = self.0.last_set_bit() {
for i in 0..=last_bit {
if self.0.is_set(i) {
let protocol: ProtocolId = bcs::from_bytes(&[i])?;
protocols.push(protocol);
}
}
}
Ok(protocols)
}
}
impl<'a, T: Iterator<Item = &'a ProtocolId>> From<T> for SupportedProtocols {
fn from(protocols: T) -> Self {
let mut bv = bitvec::BitVec::default();
protocols.for_each(|p| bv.set(*p as u8));
Self(bv)
}
}
impl SupportedProtocols {
fn intersection(self, other: SupportedProtocols) -> SupportedProtocols {
SupportedProtocols(self.0 & other.0)
}
pub fn contains(&self, protocol: ProtocolId) -> bool {
self.0.is_set(protocol as u8)
}
}
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Hash, Deserialize, Serialize)]
#[cfg_attr(any(test, feature = "fuzzing"), derive(Arbitrary))]
pub enum MessagingProtocolVersion {
V1 = 0,
}
impl MessagingProtocolVersion {
fn as_str(&self) -> &str {
match self {
Self::V1 => "V1",
}
}
}
impl fmt::Debug for MessagingProtocolVersion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self)
}
}
impl fmt::Display for MessagingProtocolVersion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_str(),)
}
}
#[derive(Debug, Error)]
pub enum HandshakeError {
#[error("diem-handshake: the received message has a different chain id: {0}, expected: {1}")]
InvalidChainId(ChainId, ChainId),
#[error(
"diem-handshake: the received message has an different network id: {0}, expected: {1}"
)]
InvalidNetworkId(NetworkId, NetworkId),
#[error("diem-handshake: could not find an intersection of supported protocol with the peer")]
NoCommonProtocols,
}
#[derive(Clone, Deserialize, Serialize, Default)]
pub struct HandshakeMsg {
pub supported_protocols: BTreeMap<MessagingProtocolVersion, SupportedProtocols>,
pub chain_id: ChainId,
pub network_id: NetworkId,
}
impl HandshakeMsg {
#[cfg(test)]
pub fn new_for_testing() -> Self {
let mut supported_protocols = BTreeMap::new();
supported_protocols.insert(
MessagingProtocolVersion::V1,
[ProtocolId::StateSyncDirectSend].iter().into(),
);
Self {
chain_id: ChainId::test(),
network_id: NetworkId::Validator,
supported_protocols,
}
}
pub fn perform_handshake(
&self,
other: &HandshakeMsg,
) -> Result<(MessagingProtocolVersion, SupportedProtocols), HandshakeError> {
if self.chain_id != other.chain_id {
return Err(HandshakeError::InvalidChainId(
other.chain_id,
self.chain_id,
));
}
if self.network_id != other.network_id {
return Err(HandshakeError::InvalidNetworkId(
other.network_id.clone(),
self.network_id.clone(),
));
}
let mut inner = other.supported_protocols.iter().rev().peekable();
for (k_outer, _) in self.supported_protocols.iter().rev() {
match inner.by_ref().find(|(k_inner, _)| *k_inner <= k_outer) {
None => {
break;
}
Some((k_inner, _)) if k_inner == k_outer => {
let protocols_self = self.supported_protocols.get(k_inner).unwrap();
let protocols_other = other.supported_protocols.get(k_inner).unwrap();
return Ok((
*k_inner,
protocols_self.clone().intersection(protocols_other.clone()),
));
}
_ => {}
}
}
Err(HandshakeError::NoCommonProtocols)
}
}
impl fmt::Debug for HandshakeMsg {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self)
}
}
impl fmt::Display for HandshakeMsg {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"[{},{},{:?}]",
self.chain_id, self.network_id, self.supported_protocols
)
}
}