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
use crate::rpc_proto;
use crate::topic::Topic;
use libp2p_core::{InboundUpgrade, OutboundUpgrade, UpgradeInfo, PeerId, upgrade};
use prost::Message;
use std::{error, fmt, io, iter, pin::Pin};
use futures::{Future, io::{AsyncRead, AsyncWrite}};
#[derive(Debug, Clone, Default)]
pub struct FloodsubProtocol {}
impl FloodsubProtocol {
pub fn new() -> FloodsubProtocol {
FloodsubProtocol {}
}
}
impl UpgradeInfo for FloodsubProtocol {
type Info = &'static [u8];
type InfoIter = iter::Once<Self::Info>;
fn protocol_info(&self) -> Self::InfoIter {
iter::once(b"/floodsub/1.0.0")
}
}
impl<TSocket> InboundUpgrade<TSocket> for FloodsubProtocol
where
TSocket: AsyncRead + AsyncWrite + Send + Unpin + 'static,
{
type Output = FloodsubRpc;
type Error = FloodsubDecodeError;
type Future = Pin<Box<dyn Future<Output = Result<Self::Output, Self::Error>> + Send>>;
fn upgrade_inbound(self, mut socket: TSocket, _: Self::Info) -> Self::Future {
Box::pin(async move {
let packet = upgrade::read_one(&mut socket, 2048).await?;
let rpc = rpc_proto::Rpc::decode(&packet[..])?;
let mut messages = Vec::with_capacity(rpc.publish.len());
for publish in rpc.publish.into_iter() {
messages.push(FloodsubMessage {
source: PeerId::from_bytes(&publish.from.unwrap_or_default()).map_err(|_| {
FloodsubDecodeError::InvalidPeerId
})?,
data: publish.data.unwrap_or_default(),
sequence_number: publish.seqno.unwrap_or_default(),
topics: publish.topic_ids
.into_iter()
.map(Topic::new)
.collect(),
});
}
Ok(FloodsubRpc {
messages,
subscriptions: rpc.subscriptions
.into_iter()
.map(|sub| FloodsubSubscription {
action: if Some(true) == sub.subscribe {
FloodsubSubscriptionAction::Subscribe
} else {
FloodsubSubscriptionAction::Unsubscribe
},
topic: Topic::new(sub.topic_id.unwrap_or_default()),
})
.collect(),
})
})
}
}
#[derive(Debug)]
pub enum FloodsubDecodeError {
ReadError(upgrade::ReadOneError),
ProtobufError(prost::DecodeError),
InvalidPeerId,
}
impl From<upgrade::ReadOneError> for FloodsubDecodeError {
fn from(err: upgrade::ReadOneError) -> Self {
FloodsubDecodeError::ReadError(err)
}
}
impl From<prost::DecodeError> for FloodsubDecodeError {
fn from(err: prost::DecodeError) -> Self {
FloodsubDecodeError::ProtobufError(err)
}
}
impl fmt::Display for FloodsubDecodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
FloodsubDecodeError::ReadError(ref err) =>
write!(f, "Error while reading from socket: {}", err),
FloodsubDecodeError::ProtobufError(ref err) =>
write!(f, "Error while decoding protobuf: {}", err),
FloodsubDecodeError::InvalidPeerId =>
write!(f, "Error while decoding PeerId from message"),
}
}
}
impl error::Error for FloodsubDecodeError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match *self {
FloodsubDecodeError::ReadError(ref err) => Some(err),
FloodsubDecodeError::ProtobufError(ref err) => Some(err),
FloodsubDecodeError::InvalidPeerId => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FloodsubRpc {
pub messages: Vec<FloodsubMessage>,
pub subscriptions: Vec<FloodsubSubscription>,
}
impl UpgradeInfo for FloodsubRpc {
type Info = &'static [u8];
type InfoIter = iter::Once<Self::Info>;
fn protocol_info(&self) -> Self::InfoIter {
iter::once(b"/floodsub/1.0.0")
}
}
impl<TSocket> OutboundUpgrade<TSocket> for FloodsubRpc
where
TSocket: AsyncWrite + AsyncRead + Send + Unpin + 'static,
{
type Output = ();
type Error = io::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Output, Self::Error>> + Send>>;
fn upgrade_outbound(self, mut socket: TSocket, _: Self::Info) -> Self::Future {
Box::pin(async move {
let bytes = self.into_bytes();
upgrade::write_one(&mut socket, bytes).await?;
Ok(())
})
}
}
impl FloodsubRpc {
fn into_bytes(self) -> Vec<u8> {
let rpc = rpc_proto::Rpc {
publish: self.messages.into_iter()
.map(|msg| {
rpc_proto::Message {
from: Some(msg.source.to_bytes()),
data: Some(msg.data),
seqno: Some(msg.sequence_number),
topic_ids: msg.topics
.into_iter()
.map(|topic| topic.into())
.collect()
}
})
.collect(),
subscriptions: self.subscriptions.into_iter()
.map(|topic| {
rpc_proto::rpc::SubOpts {
subscribe: Some(topic.action == FloodsubSubscriptionAction::Subscribe),
topic_id: Some(topic.topic.into())
}
})
.collect()
};
let mut buf = Vec::with_capacity(rpc.encoded_len());
rpc.encode(&mut buf).expect("Vec<u8> provides capacity as needed");
buf
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FloodsubMessage {
pub source: PeerId,
pub data: Vec<u8>,
pub sequence_number: Vec<u8>,
pub topics: Vec<Topic>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FloodsubSubscription {
pub action: FloodsubSubscriptionAction,
pub topic: Topic,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum FloodsubSubscriptionAction {
Subscribe,
Unsubscribe,
}