From 7698b28e16cd2e6548bbddd658c3fafc6d9b44d0 Mon Sep 17 00:00:00 2001 From: Gary Yu Date: Sat, 12 Jan 2019 07:38:27 +0800 Subject: [PATCH] fix: wait_for_min_peers shouldn't wait forever when all peers are in same work (#2340) --- p2p/src/peers.rs | 16 ++++++++++++++++ servers/src/grin/sync/syncer.rs | 10 +++++----- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/p2p/src/peers.rs b/p2p/src/peers.rs index 1dcd0d90b..a67e8ffd6 100644 --- a/p2p/src/peers.rs +++ b/p2p/src/peers.rs @@ -199,6 +199,22 @@ impl Peers { max_peers } + // Return number of connected peers that currently advertise more/same work + // (total_difficulty) than/as we do. + pub fn more_or_same_work_peers(&self) -> usize { + let peers = self.connected_peers(); + if peers.len() == 0 { + return 0; + } + + let total_difficulty = self.total_difficulty(); + + peers + .iter() + .filter(|x| x.info.total_difficulty() >= total_difficulty) + .count() + } + /// Returns single random peer with more work than us. pub fn more_work_peer(&self) -> Option> { self.more_work_peers().pop() diff --git a/servers/src/grin/sync/syncer.rs b/servers/src/grin/sync/syncer.rs index 3599da380..f66856c28 100644 --- a/servers/src/grin/sync/syncer.rs +++ b/servers/src/grin/sync/syncer.rs @@ -77,18 +77,18 @@ impl SyncRunner { let mut n = 0; const MIN_PEERS: usize = 3; loop { - let wp = self.peers.more_work_peers(); + let wp = self.peers.more_or_same_work_peers(); // exit loop when: - // * we have more than MIN_PEERS more_work peers + // * we have more than MIN_PEERS more_or_same_work peers // * we are synced already, e.g. grin was quickly restarted // * timeout - if wp.len() > MIN_PEERS - || (wp.len() == 0 + if wp > MIN_PEERS + || (wp == 0 && self.peers.enough_peers() && head.total_difficulty > Difficulty::zero()) || n > wait_secs { - if wp.len() > 0 || !global::is_production_mode() { + if wp > 0 || !global::is_production_mode() { break; } }