Don't wait 30 seconds in case of a quick restart (#1488)

Currently on startup we wait for 30 secs if we don't have at least 4 peers with more work. If a node was quickly restarted it is already fully synced so thereare no peers with more work at all. This pr assumes that if we've done some work already and we have enough peers but still 0 with more work we are fully synced and good to go.
This commit is contained in:
hashmap 2018-09-07 22:01:54 +02:00 committed by Ignotus Peverell
parent 2e6f7f72b3
commit da87f5fef4
2 changed files with 23 additions and 2 deletions

View file

@ -37,16 +37,18 @@ pub struct Peers {
store: PeerStore,
peers: RwLock<HashMap<SocketAddr, Arc<RwLock<Peer>>>>,
dandelion_relay: RwLock<HashMap<i64, Arc<RwLock<Peer>>>>,
config: P2PConfig,
}
unsafe impl Send for Peers {}
unsafe impl Sync for Peers {}
impl Peers {
pub fn new(store: PeerStore, adapter: Arc<ChainAdapter>, _config: P2PConfig) -> Peers {
pub fn new(store: PeerStore, adapter: Arc<ChainAdapter>, config: P2PConfig) -> Peers {
Peers {
adapter,
store,
config,
peers: RwLock::new(HashMap::new()),
dandelion_relay: RwLock::new(HashMap::new()),
}
@ -500,6 +502,10 @@ impl Peers {
peer.stop();
}
}
pub fn enough_peers(&self) -> bool {
self.connected_peers().len() >= self.config.peer_min_preferred_count() as usize
}
}
impl ChainAdapter for Peers {

View file

@ -80,9 +80,24 @@ pub fn run_sync(
// short period of time for tests to do the right thing.
let wait_secs = if skip_sync_wait { 3 } else { 30 };
let head = chain.head().unwrap();
awaiting_peers.store(true, Ordering::Relaxed);
let mut n = 0;
while peers.more_work_peers().len() < 4 && n < wait_secs {
const MIN_PEERS: usize = 3;
loop {
let wp = peers.more_work_peers();
// exit loop when:
// * we have more than MIN_PEERS more_work peers
// * we are synced already, e.g. grin was quickly restarted
// * timeout
if wp.len() > MIN_PEERS
|| (wp.len() == 0
&& peers.enough_peers()
&& head.total_difficulty > Difficulty::zero()) || n > wait_secs
{
break;
}
thread::sleep(time::Duration::from_secs(1));
n += 1;
}