Skip to content
This repository was archived by the owner on Nov 6, 2020. It is now read-only.

Commit b7c97f9

Browse files
authored
[devp2p discovery]: cleanup (#11547)
* [devp2p discovery]: cleanup * [devp2p]: remove lifetime from Discovery This commit it removes the lifetime on type `Discovery` by making `request_backoff: &'static [Duration]` instead. * [devp2p discovery]: pass SockAddr by value * [devp2p discovery]: remove needless clones * [devp2p discovery]: take payload by value
1 parent 9e77e7e commit b7c97f9

File tree

2 files changed

+43
-50
lines changed

2 files changed

+43
-50
lines changed

util/network-devp2p/src/discovery.rs

Lines changed: 42 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ enum NodeValidity {
121121
#[derive(Debug)]
122122
enum BucketError {
123123
Ourselves,
124-
NotInTheBucket{node_entry: NodeEntry, bucket_distance: usize},
124+
NotInTheBucket { node_entry: NodeEntry, bucket_distance: usize },
125125
}
126126

127127
struct PingRequest {
@@ -137,22 +137,14 @@ struct PingRequest {
137137
reason: PingReason
138138
}
139139

140-
#[derive(Debug)]
140+
#[derive(Debug, Default)]
141141
pub struct NodeBucket {
142142
nodes: VecDeque<BucketEntry>, //sorted by last active
143143
}
144144

145-
impl Default for NodeBucket {
146-
fn default() -> Self {
147-
NodeBucket::new()
148-
}
149-
}
150-
151145
impl NodeBucket {
152146
fn new() -> Self {
153-
NodeBucket {
154-
nodes: VecDeque::new()
155-
}
147+
Self::default()
156148
}
157149
}
158150

@@ -161,7 +153,7 @@ pub struct Datagram {
161153
pub address: SocketAddr,
162154
}
163155

164-
pub struct Discovery<'a> {
156+
pub struct Discovery {
165157
id: NodeId,
166158
id_hash: H256,
167159
secret: Secret,
@@ -182,16 +174,16 @@ pub struct Discovery<'a> {
182174
check_timestamps: bool,
183175
adding_nodes: Vec<NodeEntry>,
184176
ip_filter: IpFilter,
185-
request_backoff: &'a [Duration],
177+
request_backoff: &'static [Duration],
186178
}
187179

188180
pub struct TableUpdates {
189181
pub added: HashMap<NodeId, NodeEntry>,
190182
pub removed: HashSet<NodeId>,
191183
}
192184

193-
impl<'a> Discovery<'a> {
194-
pub fn new(key: &KeyPair, public: NodeEndpoint, ip_filter: IpFilter) -> Discovery<'static> {
185+
impl Discovery {
186+
pub fn new(key: &KeyPair, public: NodeEndpoint, ip_filter: IpFilter) -> Discovery {
195187
Discovery {
196188
id: *key.public(),
197189
id_hash: keccak(key.public()),
@@ -243,7 +235,8 @@ impl<'a> Discovery<'a> {
243235
};
244236
let bucket = &mut self.node_buckets[dist];
245237
bucket.nodes.iter_mut().find(|n| n.address.id == e.id)
246-
.map_or(Err(BucketError::NotInTheBucket{node_entry: e.clone(), bucket_distance: dist}.into()), |entry| {
238+
.ok_or_else(|| BucketError::NotInTheBucket { node_entry: e.clone(), bucket_distance: dist })
239+
.and_then(|entry| {
247240
entry.address = e;
248241
entry.last_seen = Instant::now();
249242
entry.backoff_until = Instant::now();
@@ -389,14 +382,14 @@ impl<'a> Discovery<'a> {
389382
node.endpoint.to_rlp_list(&mut rlp);
390383
append_expiration(&mut rlp);
391384
let old_parity_hash = keccak(rlp.as_raw());
392-
let hash = self.send_packet(PACKET_PING, &node.endpoint.udp_address(), &rlp.drain())?;
385+
let hash = self.send_packet(PACKET_PING, node.endpoint.udp_address(), rlp.drain())?;
393386

394387
self.in_flight_pings.insert(node.id, PingRequest {
395388
sent_at: Instant::now(),
396389
node: node.clone(),
397390
echo_hash: hash,
398391
deprecated_echo_hash: old_parity_hash,
399-
reason: reason
392+
reason,
400393
});
401394

402395
trace!(target: "discovery", "Sent Ping to {:?} ; node_id={:#x}", &node.endpoint, node.id);
@@ -407,7 +400,7 @@ impl<'a> Discovery<'a> {
407400
let mut rlp = RlpStream::new_list(2);
408401
rlp.append(target);
409402
append_expiration(&mut rlp);
410-
self.send_packet(PACKET_FIND_NODE, &node.endpoint.udp_address(), &rlp.drain())?;
403+
self.send_packet(PACKET_FIND_NODE, node.endpoint.udp_address(), rlp.drain())?;
411404

412405
self.in_flight_find_nodes.insert(node.id, FindNodeRequest {
413406
sent_at: Instant::now(),
@@ -419,10 +412,10 @@ impl<'a> Discovery<'a> {
419412
Ok(())
420413
}
421414

422-
fn send_packet(&mut self, packet_id: u8, address: &SocketAddr, payload: &[u8]) -> Result<H256, Error> {
415+
fn send_packet(&mut self, packet_id: u8, address: SocketAddr, payload: Bytes) -> Result<H256, Error> {
423416
let packet = assemble_packet(packet_id, payload, &self.secret)?;
424417
let hash = H256::from_slice(&packet[0..32]);
425-
self.send_to(packet, address.clone());
418+
self.send_to(packet, address);
426419
Ok(hash)
427420
}
428421

@@ -498,10 +491,10 @@ impl<'a> Discovery<'a> {
498491
let packet_id = signed[0];
499492
let rlp = Rlp::new(&signed[1..]);
500493
match packet_id {
501-
PACKET_PING => self.on_ping(&rlp, &node_id, &from, hash_signed.as_bytes()),
502-
PACKET_PONG => self.on_pong(&rlp, &node_id, &from),
503-
PACKET_FIND_NODE => self.on_find_node(&rlp, &node_id, &from),
504-
PACKET_NEIGHBOURS => self.on_neighbours(&rlp, &node_id, &from),
494+
PACKET_PING => self.on_ping(&rlp, node_id, from, hash_signed.as_bytes()),
495+
PACKET_PONG => self.on_pong(&rlp, node_id, from),
496+
PACKET_FIND_NODE => self.on_find_node(&rlp, node_id, from),
497+
PACKET_NEIGHBOURS => self.on_neighbours(&rlp, node_id, from),
505498
_ => {
506499
debug!(target: "discovery", "Unknown UDP packet: {}", packet_id);
507500
Ok(None)
@@ -523,12 +516,12 @@ impl<'a> Discovery<'a> {
523516
entry.endpoint.is_allowed(&self.ip_filter) && entry.id != self.id
524517
}
525518

526-
fn on_ping(&mut self, rlp: &Rlp, node_id: &NodeId, from: &SocketAddr, echo_hash: &[u8]) -> Result<Option<TableUpdates>, Error> {
519+
fn on_ping(&mut self, rlp: &Rlp, node_id: NodeId, from: SocketAddr, echo_hash: &[u8]) -> Result<Option<TableUpdates>, Error> {
527520
trace!(target: "discovery", "Got Ping from {:?}", &from);
528521
let ping_from = if let Ok(node_endpoint) = NodeEndpoint::from_rlp(&rlp.at(1)?) {
529522
node_endpoint
530523
} else {
531-
let mut address = from.clone();
524+
let mut address = from;
532525
// address here is the node's tcp port. If we are unable to get the `NodeEndpoint` from the `ping_from`
533526
// rlp field then this is most likely a BootNode, set the tcp port to 0 because it can not be used for syncing.
534527
address.set_port(0);
@@ -542,7 +535,7 @@ impl<'a> Discovery<'a> {
542535
self.check_timestamp(timestamp)?;
543536
let mut response = RlpStream::new_list(3);
544537
let pong_to = NodeEndpoint {
545-
address: from.clone(),
538+
address: from,
546539
udp_port: ping_from.udp_port
547540
};
548541
// Here the PONG's `To` field should be the node we are
@@ -555,27 +548,27 @@ impl<'a> Discovery<'a> {
555548

556549
response.append(&echo_hash);
557550
append_expiration(&mut response);
558-
self.send_packet(PACKET_PONG, from, &response.drain())?;
551+
self.send_packet(PACKET_PONG, from, response.drain())?;
559552

560-
let entry = NodeEntry { id: *node_id, endpoint: pong_to.clone() };
553+
let entry = NodeEntry { id: node_id, endpoint: pong_to };
561554
if !entry.endpoint.is_valid_discovery_node() {
562555
debug!(target: "discovery", "Got bad address: {:?}", entry);
563556
} else if !self.is_allowed(&entry) {
564557
debug!(target: "discovery", "Address not allowed: {:?}", entry);
565558
} else {
566-
self.add_node(entry.clone());
559+
self.add_node(entry);
567560
}
568561
Ok(None)
569562
}
570563

571-
fn on_pong(&mut self, rlp: &Rlp, node_id: &NodeId, from: &SocketAddr) -> Result<Option<TableUpdates>, Error> {
564+
fn on_pong(&mut self, rlp: &Rlp, node_id: NodeId, from: SocketAddr) -> Result<Option<TableUpdates>, Error> {
572565
trace!(target: "discovery", "Got Pong from {:?} ; node_id={:#x}", &from, node_id);
573566
let _pong_to = NodeEndpoint::from_rlp(&rlp.at(0)?)?;
574567
let echo_hash: H256 = rlp.val_at(1)?;
575568
let timestamp: u64 = rlp.val_at(2)?;
576569
self.check_timestamp(timestamp)?;
577570

578-
let expected_node = match self.in_flight_pings.entry(*node_id) {
571+
let expected_node = match self.in_flight_pings.entry(node_id) {
579572
Entry::Occupied(entry) => {
580573
let expected_node = {
581574
let request = entry.get();
@@ -586,7 +579,7 @@ impl<'a> Discovery<'a> {
586579
if request.deprecated_echo_hash == echo_hash {
587580
trace!(target: "discovery", "Got Pong from an old open-ethereum version.");
588581
}
589-
Some((request.node.clone(), request.reason.clone()))
582+
Some((request.node.clone(), request.reason))
590583
}
591584
};
592585

@@ -629,16 +622,16 @@ impl<'a> Discovery<'a> {
629622
}
630623
}
631624

632-
fn on_find_node(&mut self, rlp: &Rlp, node_id: &NodeId, from: &SocketAddr) -> Result<Option<TableUpdates>, Error> {
625+
fn on_find_node(&mut self, rlp: &Rlp, node_id: NodeId, from: SocketAddr) -> Result<Option<TableUpdates>, Error> {
633626
trace!(target: "discovery", "Got FindNode from {:?}", &from);
634627
let target: NodeId = rlp.val_at(0)?;
635628
let timestamp: u64 = rlp.val_at(1)?;
636629
self.check_timestamp(timestamp)?;
637630

638631
let node = NodeEntry {
639-
id: node_id.clone(),
632+
id: node_id,
640633
endpoint: NodeEndpoint {
641-
address: *from,
634+
address: from,
642635
udp_port: from.port()
643636
}
644637
};
@@ -688,7 +681,7 @@ impl<'a> Discovery<'a> {
688681
}
689682
let mut packets = Discovery::prepare_neighbours_packets(&nearest);
690683
for p in packets.drain(..) {
691-
self.send_packet(PACKET_NEIGHBOURS, &node.endpoint.address, &p)?;
684+
self.send_packet(PACKET_NEIGHBOURS, node.endpoint.address, p)?;
692685
}
693686
trace!(target: "discovery", "Sent {} Neighbours to {:?}", nearest.len(), &node.endpoint);
694687
Ok(())
@@ -711,10 +704,10 @@ impl<'a> Discovery<'a> {
711704
packets.collect()
712705
}
713706

714-
fn on_neighbours(&mut self, rlp: &Rlp, node_id: &NodeId, from: &SocketAddr) -> Result<Option<TableUpdates>, Error> {
707+
fn on_neighbours(&mut self, rlp: &Rlp, node_id: NodeId, from: SocketAddr) -> Result<Option<TableUpdates>, Error> {
715708
let results_count = rlp.at(0)?.item_count()?;
716709

717-
let is_expected = match self.in_flight_find_nodes.entry(*node_id) {
710+
let is_expected = match self.in_flight_find_nodes.entry(node_id) {
718711
Entry::Occupied(mut entry) => {
719712
let expected = {
720713
let request = entry.get_mut();
@@ -862,11 +855,11 @@ fn append_expiration(rlp: &mut RlpStream) {
862855
rlp.append(&timestamp);
863856
}
864857

865-
fn assemble_packet(packet_id: u8, bytes: &[u8], secret: &Secret) -> Result<Bytes, Error> {
866-
let mut packet = Bytes::with_capacity(bytes.len() + 32 + 65 + 1);
858+
fn assemble_packet(packet_id: u8, payload: Bytes, secret: &Secret) -> Result<Bytes, Error> {
859+
let mut packet = Bytes::with_capacity(payload.len() + 32 + 65 + 1);
867860
packet.resize(32 + 65, 0); // Filled in below
868861
packet.push(packet_id);
869-
packet.extend_from_slice(bytes);
862+
packet.extend(payload);
870863

871864
let hash = keccak(&packet[(32 + 65)..]);
872865
let signature = match sign(secret, &hash) {
@@ -1043,7 +1036,7 @@ mod tests {
10431036
let key = Random.generate();
10441037
discovery.send_find_node(&node_entries[100], key.public()).unwrap();
10451038
for payload in Discovery::prepare_neighbours_packets(&node_entries[101..116]) {
1046-
let packet = assemble_packet(PACKET_NEIGHBOURS, &payload, &key.secret()).unwrap();
1039+
let packet = assemble_packet(PACKET_NEIGHBOURS, payload, &key.secret()).unwrap();
10471040
discovery.on_packet(&packet, from.clone()).unwrap();
10481041
}
10491042

@@ -1055,7 +1048,7 @@ mod tests {
10551048
// FIND_NODE does not time out because it receives k results.
10561049
discovery.send_find_node(&node_entries[100], key.public()).unwrap();
10571050
for payload in Discovery::prepare_neighbours_packets(&node_entries[101..117]) {
1058-
let packet = assemble_packet(PACKET_NEIGHBOURS, &payload, &key.secret()).unwrap();
1051+
let packet = assemble_packet(PACKET_NEIGHBOURS, payload, &key.secret()).unwrap();
10591052
discovery.on_packet(&packet, from.clone()).unwrap();
10601053
}
10611054

@@ -1065,8 +1058,8 @@ mod tests {
10651058
assert_eq!(removed, 0);
10661059

10671060
// Test bucket evictions with retries.
1068-
let request_backoff = [Duration::new(0, 0); 2];
1069-
let mut discovery = Discovery { request_backoff: &request_backoff, ..discovery };
1061+
const TEST_REQUEST_BACKOFF: [Duration; 2] = [Duration::from_secs(0); 2];
1062+
let mut discovery = Discovery { request_backoff: &TEST_REQUEST_BACKOFF, ..discovery };
10701063

10711064
for _ in 0..2 {
10721065
discovery.ping(&node_entries[101], PingReason::Default).unwrap();
@@ -1289,7 +1282,7 @@ mod tests {
12891282
incorrect_pong_rlp.append(&H256::zero());
12901283
append_expiration(&mut incorrect_pong_rlp);
12911284
let incorrect_pong_data = assemble_packet(
1292-
PACKET_PONG, &incorrect_pong_rlp.drain(), &discovery2.secret
1285+
PACKET_PONG, incorrect_pong_rlp.drain(), &discovery2.secret
12931286
).unwrap();
12941287
if let Some(_) = discovery1.on_packet(&incorrect_pong_data, ep2.address.clone()).unwrap() {
12951288
panic!("Expected no changes to discovery1's table because pong hash is incorrect");
@@ -1318,7 +1311,7 @@ mod tests {
13181311
unexpected_pong_rlp.append(&H256::zero());
13191312
append_expiration(&mut unexpected_pong_rlp);
13201313
let unexpected_pong = assemble_packet(
1321-
PACKET_PONG, &unexpected_pong_rlp.drain(), key3.secret()
1314+
PACKET_PONG, unexpected_pong_rlp.drain(), key3.secret()
13221315
).unwrap();
13231316
if let Some(_) = discovery1.on_packet(&unexpected_pong, ep3.address.clone()).unwrap() {
13241317
panic!("Expected no changes to discovery1's table for unexpected pong");

util/network-devp2p/src/host.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,7 @@ pub struct Host {
267267
udp_socket: Mutex<Option<UdpSocket>>,
268268
tcp_listener: Mutex<TcpListener>,
269269
sessions: Arc<RwLock<Slab<SharedSession>>>,
270-
discovery: Mutex<Option<Discovery<'static>>>,
270+
discovery: Mutex<Option<Discovery>>,
271271
nodes: RwLock<NodeTable>,
272272
handlers: RwLock<HashMap<ProtocolId, Arc<dyn NetworkProtocolHandler + Sync>>>,
273273
timers: RwLock<HashMap<TimerToken, ProtocolTimer>>,

0 commit comments

Comments
 (0)