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
use std::io::{Error, ErrorKind, Result};
use crate::message::{self, Compressor, Outbound};
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub struct Message {
pub peers: Vec<Peer>,
pub bypass_throttling: bool,
}
impl Message {
pub fn create(peers: Vec<Peer>, bypass_throttling: bool) -> impl Outbound + Compressor {
Self {
peers,
bypass_throttling,
}
}
}
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub struct Peer {
pub certificate: Vec<u8>,
pub ip_addr: std::net::IpAddr,
pub ip_port: u16,
pub time: u64,
pub sig: Vec<u8>,
}
impl std::fmt::Display for Message {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "msg peerlist")
}
}
impl Outbound for Message {
fn serialize_with_header(&self) -> Result<bytes::Bytes> {
let type_id = message::TYPES
.get("peerlist")
.ok_or_else(|| Error::new(ErrorKind::InvalidInput, "unknown type name"))?;
let packer = message::default_packer_with_header();
packer.pack_byte(*type_id)?;
packer.pack_bool(false)?; packer.pack_u32(self.peers.len() as u32)?;
for p in self.peers.iter() {
packer.pack_bytes_with_header(p.certificate.as_ref())?;
packer.pack_ip(p.ip_addr, p.ip_port)?;
packer.pack_u64(p.time)?;
packer.pack_bytes_with_header(p.sig.as_ref())?;
}
Ok(packer.take_bytes())
}
}
#[test]
fn test_message() {
let msg = Message::create(
vec![
Peer {
certificate: vec![0x01, 0x02, 0x03],
ip_addr: std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
ip_port: 8080,
time: 7,
sig: vec![0x01, 0x02, 0x03, 0x04],
},
Peer {
certificate: vec![0x01, 0x02, 0x03],
ip_addr: std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
ip_port: 8081,
time: 7,
sig: vec![0x01, 0x02, 0x03, 0x04],
},
],
false,
);
let data_with_header = msg.serialize_with_header().unwrap();
let expected_data: &[u8] = &[
0x00, 0x00, 0x00, 0x58, 0x12, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x1, 0x2, 0x3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0x0, 0x0,
0x1, 0x1f, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x04, 0x01, 0x02, 0x03, 0x04, 0x00, 0x00, 0x00, 0x03, 0x1, 0x2, 0x3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0x0, 0x0,
0x1, 0x1f, 0x91, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x04, 0x01, 0x02, 0x03, 0x04, ];
assert!(cmp_manager::eq_vectors(&expected_data, &data_with_header));
}