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
use {
bincode::{Options, Result},
bitflags::bitflags,
serde::Serialize,
std::{
fmt, io,
net::{IpAddr, Ipv4Addr, SocketAddr},
slice::SliceIndex,
},
};
#[cfg(test)]
static_assertions::const_assert_eq!(PACKET_DATA_SIZE, 1232);
pub const PACKET_DATA_SIZE: usize = 1280 - 40 - 8;
bitflags! {
#[repr(C)]
pub struct PacketFlags: u8 {
const DISCARD = 0b0000_0001;
const FORWARDED = 0b0000_0010;
const REPAIR = 0b0000_0100;
const SIMPLE_VOTE_TX = 0b0000_1000;
const TRACER_PACKET = 0b0001_0000;
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[repr(C)]
pub struct Meta {
pub size: usize,
pub addr: IpAddr,
pub port: u16,
pub flags: PacketFlags,
pub sender_stake: u64,
}
#[derive(Clone, Eq)]
#[repr(C)]
pub struct Packet {
buffer: [u8; PACKET_DATA_SIZE],
pub meta: Meta,
}
impl Packet {
pub fn new(buffer: [u8; PACKET_DATA_SIZE], meta: Meta) -> Self {
Self { buffer, meta }
}
#[inline]
pub fn data<I>(&self, index: I) -> Option<&<I as SliceIndex<[u8]>>::Output>
where
I: SliceIndex<[u8]>,
{
if self.meta.discard() {
None
} else {
self.buffer.get(..self.meta.size)?.get(index)
}
}
#[inline]
pub fn buffer_mut(&mut self) -> &mut [u8] {
debug_assert!(!self.meta.discard());
&mut self.buffer[..]
}
pub fn from_data<T: Serialize>(dest: Option<&SocketAddr>, data: T) -> Result<Self> {
let mut packet = Packet::default();
Self::populate_packet(&mut packet, dest, &data)?;
Ok(packet)
}
pub fn populate_packet<T: Serialize>(
&mut self,
dest: Option<&SocketAddr>,
data: &T,
) -> Result<()> {
debug_assert!(!self.meta.discard());
let mut wr = io::Cursor::new(self.buffer_mut());
bincode::serialize_into(&mut wr, data)?;
self.meta.size = wr.position() as usize;
if let Some(dest) = dest {
self.meta.set_socket_addr(dest);
}
Ok(())
}
pub fn deserialize_slice<T, I>(&self, index: I) -> Result<T>
where
T: serde::de::DeserializeOwned,
I: SliceIndex<[u8], Output = [u8]>,
{
let bytes = self.data(index).ok_or(bincode::ErrorKind::SizeLimit)?;
bincode::options()
.with_limit(PACKET_DATA_SIZE as u64)
.with_fixint_encoding()
.reject_trailing_bytes()
.deserialize(bytes)
}
}
impl fmt::Debug for Packet {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"Packet {{ size: {:?}, addr: {:?} }}",
self.meta.size,
self.meta.socket_addr()
)
}
}
#[allow(clippy::uninit_assumed_init)]
impl Default for Packet {
fn default() -> Packet {
let buffer = std::mem::MaybeUninit::<[u8; PACKET_DATA_SIZE]>::uninit();
Packet {
buffer: unsafe { buffer.assume_init() },
meta: Meta::default(),
}
}
}
impl PartialEq for Packet {
fn eq(&self, other: &Packet) -> bool {
self.meta == other.meta && self.data(..) == other.data(..)
}
}
impl Meta {
pub fn socket_addr(&self) -> SocketAddr {
SocketAddr::new(self.addr, self.port)
}
pub fn set_socket_addr(&mut self, socket_addr: &SocketAddr) {
self.addr = socket_addr.ip();
self.port = socket_addr.port();
}
#[inline]
pub fn discard(&self) -> bool {
self.flags.contains(PacketFlags::DISCARD)
}
#[inline]
pub fn set_discard(&mut self, discard: bool) {
self.flags.set(PacketFlags::DISCARD, discard);
}
#[inline]
pub fn set_tracer(&mut self, is_tracer: bool) {
self.flags.set(PacketFlags::TRACER_PACKET, is_tracer);
}
#[inline]
pub fn forwarded(&self) -> bool {
self.flags.contains(PacketFlags::FORWARDED)
}
#[inline]
pub fn repair(&self) -> bool {
self.flags.contains(PacketFlags::REPAIR)
}
#[inline]
pub fn is_simple_vote_tx(&self) -> bool {
self.flags.contains(PacketFlags::SIMPLE_VOTE_TX)
}
#[inline]
pub fn is_tracer_packet(&self) -> bool {
self.flags.contains(PacketFlags::TRACER_PACKET)
}
}
impl Default for Meta {
fn default() -> Self {
Self {
size: 0,
addr: IpAddr::V4(Ipv4Addr::UNSPECIFIED),
port: 0,
flags: PacketFlags::empty(),
sender_stake: 0,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_deserialize_slice() {
let p = Packet::from_data(None, u32::MAX).unwrap();
assert_eq!(p.deserialize_slice(..).ok(), Some(u32::MAX));
assert_eq!(p.deserialize_slice(0..4).ok(), Some(u32::MAX));
assert_eq!(
p.deserialize_slice::<u16, _>(0..4)
.map_err(|e| e.to_string()),
Err("Slice had bytes remaining after deserialization".to_string()),
);
assert_eq!(
p.deserialize_slice::<u32, _>(0..0)
.map_err(|e| e.to_string()),
Err("io error: unexpected end of file".to_string()),
);
assert_eq!(
p.deserialize_slice::<u32, _>(0..1)
.map_err(|e| e.to_string()),
Err("io error: unexpected end of file".to_string()),
);
assert_eq!(
p.deserialize_slice::<u32, _>(0..5)
.map_err(|e| e.to_string()),
Err("the size limit has been reached".to_string()),
);
#[allow(clippy::reversed_empty_ranges)]
let reversed_empty_range = 4..0;
assert_eq!(
p.deserialize_slice::<u32, _>(reversed_empty_range)
.map_err(|e| e.to_string()),
Err("the size limit has been reached".to_string()),
);
assert_eq!(
p.deserialize_slice::<u32, _>(4..5)
.map_err(|e| e.to_string()),
Err("the size limit has been reached".to_string()),
);
}
}