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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
use crate::rpc_proto;
use crate::TopicHash;
use libp2p_core::{connection::ConnectionId, PeerId};
use prometheus_client::encoding::text::Encode;
use prost::Message;
use std::fmt;
use std::fmt::Debug;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[derive(Debug)]
pub enum MessageAcceptance {
Accept,
Reject,
Ignore,
}
macro_rules! declare_message_id_type {
($name: ident, $name_string: expr) => {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct $name(pub Vec<u8>);
impl $name {
pub fn new(value: &[u8]) -> Self {
Self(value.to_vec())
}
}
impl<T: Into<Vec<u8>>> From<T> for $name {
fn from(value: T) -> Self {
Self(value.into())
}
}
impl std::fmt::Display for $name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", hex_fmt::HexFmt(&self.0))
}
}
impl std::fmt::Debug for $name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}({})", $name_string, hex_fmt::HexFmt(&self.0))
}
}
};
}
declare_message_id_type!(MessageId, "MessageId");
declare_message_id_type!(FastMessageId, "FastMessageId");
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PeerConnections {
pub kind: PeerKind,
pub connections: Vec<ConnectionId>,
}
#[derive(Debug, Clone, PartialEq, Hash, Encode, Eq)]
pub enum PeerKind {
Gossipsubv1_1,
Gossipsub,
Floodsub,
NotSupported,
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct RawGossipsubMessage {
pub source: Option<PeerId>,
pub data: Vec<u8>,
pub sequence_number: Option<u64>,
pub topic: TopicHash,
pub signature: Option<Vec<u8>>,
pub key: Option<Vec<u8>>,
pub validated: bool,
}
impl RawGossipsubMessage {
pub fn raw_protobuf_len(&self) -> usize {
let message = rpc_proto::Message {
from: self.source.map(|m| m.to_bytes()),
data: Some(self.data.clone()),
seqno: self.sequence_number.map(|s| s.to_be_bytes().to_vec()),
topic: TopicHash::into_string(self.topic.clone()),
signature: self.signature.clone(),
key: self.key.clone(),
};
message.encoded_len()
}
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct GossipsubMessage {
pub source: Option<PeerId>,
pub data: Vec<u8>,
pub sequence_number: Option<u64>,
pub topic: TopicHash,
}
impl fmt::Debug for GossipsubMessage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("GossipsubMessage")
.field(
"data",
&format_args!("{:<20}", &hex_fmt::HexFmt(&self.data)),
)
.field("source", &self.source)
.field("sequence_number", &self.sequence_number)
.field("topic", &self.topic)
.finish()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct GossipsubSubscription {
pub action: GossipsubSubscriptionAction,
pub topic_hash: TopicHash,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum GossipsubSubscriptionAction {
Subscribe,
Unsubscribe,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PeerInfo {
pub peer_id: Option<PeerId>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum GossipsubControlAction {
IHave {
topic_hash: TopicHash,
message_ids: Vec<MessageId>,
},
IWant {
message_ids: Vec<MessageId>,
},
Graft {
topic_hash: TopicHash,
},
Prune {
topic_hash: TopicHash,
peers: Vec<PeerInfo>,
backoff: Option<u64>,
},
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct GossipsubRpc {
pub messages: Vec<RawGossipsubMessage>,
pub subscriptions: Vec<GossipsubSubscription>,
pub control_msgs: Vec<GossipsubControlAction>,
}
impl GossipsubRpc {
pub fn into_protobuf(self) -> rpc_proto::Rpc {
self.into()
}
}
impl From<GossipsubRpc> for rpc_proto::Rpc {
fn from(rpc: GossipsubRpc) -> Self {
let mut publish = Vec::new();
for message in rpc.messages.into_iter() {
let message = rpc_proto::Message {
from: message.source.map(|m| m.to_bytes()),
data: Some(message.data),
seqno: message.sequence_number.map(|s| s.to_be_bytes().to_vec()),
topic: TopicHash::into_string(message.topic),
signature: message.signature,
key: message.key,
};
publish.push(message);
}
let subscriptions = rpc
.subscriptions
.into_iter()
.map(|sub| rpc_proto::rpc::SubOpts {
subscribe: Some(sub.action == GossipsubSubscriptionAction::Subscribe),
topic_id: Some(sub.topic_hash.into_string()),
})
.collect::<Vec<_>>();
let mut control = rpc_proto::ControlMessage {
ihave: Vec::new(),
iwant: Vec::new(),
graft: Vec::new(),
prune: Vec::new(),
};
let empty_control_msg = rpc.control_msgs.is_empty();
for action in rpc.control_msgs {
match action {
GossipsubControlAction::IHave {
topic_hash,
message_ids,
} => {
let rpc_ihave = rpc_proto::ControlIHave {
topic_id: Some(topic_hash.into_string()),
message_ids: message_ids.into_iter().map(|msg_id| msg_id.0).collect(),
};
control.ihave.push(rpc_ihave);
}
GossipsubControlAction::IWant { message_ids } => {
let rpc_iwant = rpc_proto::ControlIWant {
message_ids: message_ids.into_iter().map(|msg_id| msg_id.0).collect(),
};
control.iwant.push(rpc_iwant);
}
GossipsubControlAction::Graft { topic_hash } => {
let rpc_graft = rpc_proto::ControlGraft {
topic_id: Some(topic_hash.into_string()),
};
control.graft.push(rpc_graft);
}
GossipsubControlAction::Prune {
topic_hash,
peers,
backoff,
} => {
let rpc_prune = rpc_proto::ControlPrune {
topic_id: Some(topic_hash.into_string()),
peers: peers
.into_iter()
.map(|info| rpc_proto::PeerInfo {
peer_id: info.peer_id.map(|id| id.to_bytes()),
signed_peer_record: None,
})
.collect(),
backoff,
};
control.prune.push(rpc_prune);
}
}
}
rpc_proto::Rpc {
subscriptions,
publish,
control: if empty_control_msg {
None
} else {
Some(control)
},
}
}
}
impl fmt::Debug for GossipsubRpc {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut b = f.debug_struct("GossipsubRpc");
if !self.messages.is_empty() {
b.field("messages", &self.messages);
}
if !self.subscriptions.is_empty() {
b.field("subscriptions", &self.subscriptions);
}
if !self.control_msgs.is_empty() {
b.field("control_msgs", &self.control_msgs);
}
b.finish()
}
}
impl PeerKind {
pub fn as_static_ref(&self) -> &'static str {
match self {
Self::NotSupported => "Not Supported",
Self::Floodsub => "Floodsub",
Self::Gossipsub => "Gossipsub v1.0",
Self::Gossipsubv1_1 => "Gossipsub v1.1",
}
}
}
impl AsRef<str> for PeerKind {
fn as_ref(&self) -> &str {
self.as_static_ref()
}
}
impl fmt::Display for PeerKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_ref())
}
}