From d4657f86208a13d8fcc7933018d4558c3a96f634 Mon Sep 17 00:00:00 2001
From: Alexandru Vasile <60601340+lexnv@users.noreply.github.com>
Date: Mon, 8 Jul 2024 18:40:07 +0300
Subject: [PATCH] litep2p/peerstore: Fix bump last updated time (#4971)

This PR bumps the last time of a reputation update of a peer.
Doing so ensures the peer remains in the peerstore for longer than 1
hour.

Libp2p updates the `last_updated` field as well.

Small summary for the peerstore:
- A: when peers are reported the `last_updated` time is set to current
time (not done before this PR)
- B: peers that were not updated for 1 hour are removed from the
peerstore
- the reputation of the peers is decaying to zero over time
- peers are reported with a reputation change (positive or negative
depending on the behavior)

Because, (A) was not updating the `last_updated` time, we might lose the
reputation of peers that are constantly updated after 1hour because of
(B).

cc @paritytech/networking

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>
---
 substrate/client/network/src/litep2p/peerstore.rs | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)

diff --git a/substrate/client/network/src/litep2p/peerstore.rs b/substrate/client/network/src/litep2p/peerstore.rs
index 3f7155edbc9..347aa0b90ee 100644
--- a/substrate/client/network/src/litep2p/peerstore.rs
+++ b/substrate/client/network/src/litep2p/peerstore.rs
@@ -85,6 +85,11 @@ impl PeerInfo {
 		self.reputation < BANNED_THRESHOLD
 	}
 
+	fn add_reputation(&mut self, increment: i32) {
+		self.reputation = self.reputation.saturating_add(increment);
+		self.bump_last_updated();
+	}
+
 	fn decay_reputation(&mut self, seconds_passed: u64) {
 		// Note that decaying the reputation value happens "on its own",
 		// so we don't do `bump_last_updated()`.
@@ -103,6 +108,10 @@ impl PeerInfo {
 			}
 		}
 	}
+
+	fn bump_last_updated(&mut self) {
+		self.last_updated = Instant::now();
+	}
 }
 
 #[derive(Debug, Default)]
@@ -169,7 +178,7 @@ impl PeerStoreProvider for PeerstoreHandle {
 
 		match lock.peers.get_mut(&peer) {
 			Some(info) => {
-				info.reputation = info.reputation.saturating_add(reputation_change.value);
+				info.add_reputation(reputation_change.value);
 			},
 			None => {
 				lock.peers.insert(
-- 
GitLab