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
// Copyright 2020-2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
use super::{
event::{IotaGossipEvent, IotaGossipHandlerEvent},
handler::{GossipProtocolHandler, IotaGossipHandlerInEvent},
id::IotaGossipIdentifier,
};
use crate::{alias, init::global::network_id, network::origin::Origin};
use libp2p::{
core::{connection::ConnectionId, ConnectedPoint},
swarm::{NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters},
Multiaddr, PeerId,
};
use log::debug;
use std::{
collections::{HashMap, VecDeque},
task::{Context, Poll},
};
const IOTA_GOSSIP_NAME: &str = "iota-gossip";
const IOTA_GOSSIP_VERSION: &str = "1.0.0";
struct ConnectionInfo {
addr: Multiaddr,
origin: Origin,
}
#[derive(Debug)]
struct SwarmEvent {
peer_id: PeerId,
peer_addr: Multiaddr,
conn_id: ConnectionId,
origin: Origin,
}
#[derive(Debug)]
struct HandlerEvent {
peer_id: PeerId,
conn_id: ConnectionId,
event: IotaGossipHandlerEvent,
}
/// Substream upgrade protocol for `/iota-gossip/1.0.0`.
pub struct IotaGossipProtocol {
/// The gossip protocol identifier.
id: IotaGossipIdentifier,
/// Counts the number of handlers created.
num_handlers: usize,
/// Counts the number of inbound connections.
num_inbounds: usize,
/// Counts the number of outbound connections.
num_outbounds: usize,
/// Events produced for the behavior and handlers.
events: VecDeque<NetworkBehaviourAction<IotaGossipHandlerInEvent, IotaGossipEvent>>,
/// Maps peers to their connection infos. Peers can only have 1 gossip connection, hence the mapping is 1:1.
peers: HashMap<PeerId, ConnectionInfo>,
}
impl IotaGossipProtocol {
pub fn new() -> Self {
Self::default()
}
}
impl Default for IotaGossipProtocol {
fn default() -> Self {
Self {
id: IotaGossipIdentifier::new(IOTA_GOSSIP_NAME, network_id(), IOTA_GOSSIP_VERSION),
num_handlers: 0,
num_inbounds: 0,
num_outbounds: 0,
events: VecDeque::with_capacity(16),
peers: HashMap::with_capacity(8),
}
}
}
impl NetworkBehaviour for IotaGossipProtocol {
type ProtocolsHandler = GossipProtocolHandler;
type OutEvent = IotaGossipEvent;
/// **libp2p docs**:
///
/// Creates a new `ProtocolsHandler` for a connection with a peer.
///
/// Every time an incoming connection is opened, and every time we start dialing a node, this
/// method is called.
///
/// The returned object is a handler for that specific connection, and will be moved to a
/// background task dedicated to that connection.
///
/// The network behaviour (ie. the implementation of this trait) and the handlers it has
/// spawned (ie. the objects returned by `new_handler`) can communicate by passing messages.
/// Messages sent from the handler to the behaviour are injected with `inject_event`, and
/// the behaviour can send a message to the handler by making `poll` return `SendEvent`.
fn new_handler(&mut self) -> Self::ProtocolsHandler {
self.num_handlers += 1;
debug!("gossip protocol: new handler ({}).", self.num_handlers);
GossipProtocolHandler::new(self.id.clone())
}
/// **libp2p docs**:
///
/// Addresses that this behaviour is aware of for this specific peer, and that may allow
/// reaching the peer.
///
/// The addresses will be tried in the order returned by this function, which means that they
/// should be ordered by decreasing likelihood of reachability. In other words, the first
/// address should be the most likely to be reachable.
fn addresses_of_peer(&mut self, peer_id: &PeerId) -> Vec<Multiaddr> {
let addrs = self
.peers
.get(peer_id)
.map_or(Vec::new(), |conn_info| vec![conn_info.addr.clone()]);
debug!("gossip protocol: addresses of peer {}: {:?}.", alias!(peer_id), addrs);
addrs
}
/// **libp2p docs**:
///
/// Informs the behaviour about a newly established connection to a peer.
fn inject_connection_established(&mut self, peer_id: &PeerId, conn_id: &ConnectionId, endpoint: &ConnectedPoint) {
let (peer_addr, origin) = match endpoint {
ConnectedPoint::Dialer { address } => (address.clone(), Origin::Outbound),
ConnectedPoint::Listener { send_back_addr, .. } => (send_back_addr.clone(), Origin::Inbound),
};
match origin {
Origin::Inbound => self.num_inbounds += 1,
Origin::Outbound => self.num_outbounds += 1,
}
debug!(
"gossip protocol: connection established: inbound/outbound: {}/{}",
self.num_inbounds, self.num_outbounds
);
self.peers.insert(*peer_id, {
ConnectionInfo {
addr: peer_addr,
origin,
}
});
let handler_event = IotaGossipHandlerInEvent { origin };
let notify_handler = NetworkBehaviourAction::NotifyHandler {
peer_id: *peer_id,
handler: NotifyHandler::One(*conn_id), // TODO: maybe better use ::Any ??
event: handler_event,
};
self.events.push_back(notify_handler);
}
/// **libp2p docs**:
///
/// Indicate to the behaviour that we connected to the node with the given peer id.
///
/// This node now has a handler (as spawned by `new_handler`) running in the background.
///
/// This method is only called when the first connection to the peer is established, preceded by
/// [`inject_connection_established`](NetworkBehaviour::inject_connection_established).
fn inject_connected(&mut self, peer_id: &PeerId) {
debug!("gossip protocol: {} connected.", alias!(peer_id));
}
/// **libp2p docs**:
///
/// Informs the behaviour about an event generated by the handler dedicated to the peer identified by `peer_id`.
/// for the behaviour.
///
/// The `peer_id` is guaranteed to be in a connected state. In other words, `inject_connected`
/// has previously been called with this `PeerId`.
fn inject_event(&mut self, peer_id: PeerId, _: ConnectionId, event: IotaGossipHandlerEvent) {
debug!("gossip protocol: handler event: {:?}", event);
// Propagate events to the behavior.
let ev = match event {
IotaGossipHandlerEvent::SentUpgradeRequest { to } => {
NetworkBehaviourAction::GenerateEvent(IotaGossipEvent::SentUpgradeRequest { to })
}
IotaGossipHandlerEvent::UpgradeCompleted { substream } => {
if let Some(conn_info) = self.peers.remove(&peer_id) {
NetworkBehaviourAction::GenerateEvent(IotaGossipEvent::UpgradeCompleted {
peer_id,
peer_addr: conn_info.addr,
origin: conn_info.origin,
substream,
})
} else {
return;
}
}
IotaGossipHandlerEvent::UpgradeError { peer_id, error } => {
NetworkBehaviourAction::GenerateEvent(IotaGossipEvent::UpgradeError { peer_id, error })
}
_ => return,
};
self.events.push_back(ev);
}
/// **libp2p docs**:
///
/// Informs the behaviour about a closed connection to a peer.
///
/// A call to this method is always paired with an earlier call to
/// `inject_connection_established` with the same peer ID, connection ID and
/// endpoint.
fn inject_connection_closed(&mut self, peer_id: &PeerId, _: &ConnectionId, _: &ConnectedPoint) {
debug!("gossip behavior: connection with {} closed.", alias!(peer_id));
}
/// **libp2p docs**:
///
/// Indicates to the behaviour that we disconnected from the node with the given peer id.
///
/// There is no handler running anymore for this node. Any event that has been sent to it may
/// or may not have been processed by the handler.
///
/// This method is only called when the last established connection to the peer is closed,
/// preceded by [`inject_connection_closed`](NetworkBehaviour::inject_connection_closed).
fn inject_disconnected(&mut self, peer_id: &PeerId) {
debug!("gossip behavior: {} disconnected.", alias!(peer_id));
}
/// **libp2p docs**:
///
/// Informs the behaviour that the [`ConnectedPoint`] of an existing connection has changed.
fn inject_address_change(
&mut self,
peer_id: &PeerId,
_: &ConnectionId,
_old: &ConnectedPoint,
_new: &ConnectedPoint,
) {
debug!("gossip behavior: address of {} changed.", alias!(peer_id));
}
fn poll(
&mut self,
_: &mut Context<'_>,
_: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<IotaGossipHandlerInEvent, Self::OutEvent>> {
if let Some(event) = self.events.pop_front() {
Poll::Ready(event)
} else {
Poll::Pending
}
}
}