diff --git a/coordinator/src/p2p.rs b/coordinator/src/p2p.rs index 627af966..cce96d86 100644 --- a/coordinator/src/p2p.rs +++ b/coordinator/src/p2p.rs @@ -558,6 +558,17 @@ impl TributaryP2p for LibP2p { } } +fn heartbeat_time_unit() -> u64 { + // Also include the timestamp so LibP2p doesn't flag this as an old message re-circulating + let timestamp = SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .expect("system clock is wrong") + .as_secs(); + // Divide by the block time so if multiple parties send a Heartbeat, they're more likely to + // overlap + timestamp / u64::from(Tributary::::block_time()) +} + pub async fn heartbeat_tributaries_task( p2p: P, mut tributary_event: broadcast::Receiver>, @@ -592,14 +603,7 @@ pub async fn heartbeat_tributaries_task( if SystemTime::now() > (block_time + Duration::from_secs(60)) { log::warn!("last known tributary block was over a minute ago"); let mut msg = tip.to_vec(); - // Also include the timestamp so LibP2p doesn't flag this as an old message re-circulating - let timestamp = SystemTime::now() - .duration_since(SystemTime::UNIX_EPOCH) - .expect("system clock is wrong") - .as_secs(); - // Divide by the block time so if multiple parties send a Heartbeat, they're more likely to - // overlap - let time_unit = timestamp / u64::from(Tributary::::block_time()); + let time_unit = heartbeat_time_unit::(); msg.extend(time_unit.to_le_bytes()); P2p::broadcast(&p2p, P2pMessageKind::Heartbeat(tributary.genesis()), msg).await; } @@ -666,6 +670,13 @@ pub async fn handle_p2p_task( log::error!("validator sent invalid heartbeat"); continue; } + // Only respond to recent heartbeats + let msg_time_unit = u64::from_le_bytes(msg.msg[32 .. 40].try_into().expect( + "length-checked heartbeat message didn't have 8 bytes for the u64", + )); + if heartbeat_time_unit::().saturating_sub(msg_time_unit) > 1 { + continue; + } let p2p = p2p.clone(); let spec = tributary.spec.clone(); @@ -715,7 +726,7 @@ pub async fn handle_p2p_task( to_send.push(next); latest = next; } - if to_send.len() > 1 { + if to_send.len() > 3 { for next in to_send { let mut res = reader.block(&next).unwrap().serialize(); res.extend(reader.commit(&next).unwrap());