Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 112 additions & 0 deletions pkgs/id/src/chat_presence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,13 @@ pub const TYPING_TTL_SECS: u64 = 12;
/// single received heartbeat can make the table do.
pub const MAX_HEARTBEAT_CHANNELS: usize = 64;

/// Maximum number of distinct nodes the presence table will store.
///
/// Bounding the node count prevents unbounded memory growth from a flood
/// of self-signed heartbeats with minted keys on the public gossip topic (Fixes #4004).
/// Matches discovery's maximum peer table bounds (1_000).
pub const MAX_PRESENCE_NODES: usize = 1_000;

/// Frame prefix distinguishing presence frames from peer-discovery announcements on
/// the shared gossip topic. A frame without this prefix is not a presence frame, and
/// [`decode_frame`] returns `None` for it; legacy announcement bytes never decode as
Expand Down Expand Up @@ -309,6 +316,12 @@ impl PresenceTable {
/// [`PresenceHeartbeat::new`], so the constructor's dedupe/bound on
/// channels and typing is enforced here too.
///
/// - **Node count bound.** The table stores at most [`MAX_PRESENCE_NODES`] nodes.
/// Updates to an existing key update in place and consume no new capacity.
/// At capacity, a new node is admitted only by evicting an entry already past
/// its TTL (oldest such expired entry, ties broken by node key bytes). If every
/// entry is fresh, the new node is refused (Fixes #4004).
///
/// Returns whether the heartbeat was accepted (inserted or replacing).
pub fn update_at(
&self,
Expand Down Expand Up @@ -361,6 +374,26 @@ impl PresenceTable {
{
effective_ts = effective_ts.min(existing.effective_ts);
}
// Node count bound (#4004): a brand-new node key is admitted at
// capacity only by evicting the oldest expired entry (expiry runs
// from the effective stamp, #8865); if every entry is still fresh,
// the new node is refused. Existing keys refresh in place and
// consume no new capacity.
if !entries.contains_key(&node) && entries.len() >= MAX_PRESENCE_NODES {
let oldest_expired = entries
.iter()
.filter(|(_, entry)| now.saturating_sub(entry.effective_ts) > PRESENCE_TTL_SECS)
.min_by(|(k1, e1), (k2, e2)| {
e1.effective_ts.cmp(&e2.effective_ts).then_with(|| k1.cmp(k2))
})
.map(|(k, _)| *k);
match oldest_expired {
Some(k) => {
entries.remove(&k);
}
None => return false,
}
}
entries.insert(
node,
Entry {
Expand Down Expand Up @@ -1144,4 +1177,83 @@ mod tests {
assert_eq!(table.liveness_at(&alice, &chan, 4_200), Liveness::Live);
}
}

#[test]
fn node_count_bound_caps_storage_and_refuses_when_all_fresh() {
let table = PresenceTable::new();
let chan = channel("general");
let now = 10_000;

// Fill table up to MAX_PRESENCE_NODES with distinct keys
for i in 0..MAX_PRESENCE_NODES {
let mut node = [0u8; 32];
node[0..2].copy_from_slice(&(i as u16).to_le_bytes());
assert!(table.update_at(heartbeat(node, vec![chan], now), now, &|_, _| true));
}
assert_eq!(table.count(), MAX_PRESENCE_NODES);

// A new node arrives while all entries are fresh: must be refused.
let mut new_node = [0xffu8; 32];
new_node[0] = 1;
assert!(!table.update_at(heartbeat(new_node, vec![chan], now), now, &|_, _| true));
assert_eq!(table.count(), MAX_PRESENCE_NODES);
assert_eq!(table.liveness_at(&new_node, &chan, now), Liveness::Offline);
}

#[test]
fn node_count_bound_evicts_oldest_expired_entry_at_capacity() {
let table = PresenceTable::new();
let chan = channel("general");
let now = 20_000;

// Fill table with MAX_PRESENCE_NODES distinct keys
for i in 0..MAX_PRESENCE_NODES {
let mut node = [0u8; 32];
node[0..2].copy_from_slice(&(i as u16).to_le_bytes());
// node 0 has timestamp `now - 50`, others have timestamp `now`
let ts = if i == 0 { now - 50 } else { now };
assert!(table.update_at(heartbeat(node, vec![chan], ts), now, &|_, _| true));
}
assert_eq!(table.count(), MAX_PRESENCE_NODES);

// At `later = now + 30`, node 0's age is 80 > 75 (expired).
// Other entries have age 30 <= 75 (still fresh).
let later = now + 30;
let mut new_node = [0xffu8; 32];
new_node[0] = 1;
assert!(table.update_at(heartbeat(new_node, vec![chan], later), later, &|_, _| true));

// Count stays capped at MAX_PRESENCE_NODES
assert_eq!(table.count(), MAX_PRESENCE_NODES);

// Node 0 was the expired entry and was evicted
let mut node0 = [0u8; 32];
node0[0..2].copy_from_slice(&0u16.to_le_bytes());
assert_eq!(table.liveness_at(&node0, &chan, later), Liveness::Offline);
// New node was accepted and is live
assert_eq!(table.liveness_at(&new_node, &chan, later), Liveness::Live);
}

#[test]
fn existing_node_update_at_capacity_succeeds_in_place_without_eviction() {
let table = PresenceTable::new();
let chan = channel("general");
let now = 30_000;

// Fill table with MAX_PRESENCE_NODES distinct keys
for i in 0..MAX_PRESENCE_NODES {
let mut node = [0u8; 32];
node[0..2].copy_from_slice(&(i as u16).to_le_bytes());
assert!(table.update_at(heartbeat(node, vec![chan], now), now, &|_, _| true));
}
assert_eq!(table.count(), MAX_PRESENCE_NODES);

// Updating an existing node key (node 42) at capacity
let mut node42 = [0u8; 32];
node42[0..2].copy_from_slice(&42u16.to_le_bytes());
assert!(table.update_at(heartbeat(node42, vec![chan], now + 1), now + 1, &|_, _| true));

assert_eq!(table.count(), MAX_PRESENCE_NODES);
assert_eq!(table.liveness_at(&node42, &chan, now + 1), Liveness::Live);
}
}
Loading