p2p: gossip takes the Store instead of five optional stores and setters

GossipDiscovery held Option<..> handles to the peer-node, peer-health,
document, revocation and epoch stores, filled in by five setters (one
through join_ensemble_gossip's peer_node_store parameter, which both callers
filled the same way), and every handler carried a 'no store attached'
branch. It now takes Arc<Store> at construction; the handlers take the store
they need directly, and join_ensemble_gossip loses the parameter.

The announcement watch channel holds a NodeAnnouncement rather than its
serialized bytes, so update_node_name no longer deserializes it back and
drops the wrong-variant NotJoined hack; messages are serialized at broadcast
through one broadcast() helper that the three broadcast_* fns share too.
PeerMap shrinks to the replay high-water mark it actually is, and its lock
and the neighbor set recover a poisoned lock instead of panicking.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Greg ShuflinandClaude Opus 5.5 committed 2026-09-28 07:06:17 -07:00
1 parent a09f587851
commit db1e4a9012
4 files changed
+149 -291

No files matched your search

-2
View File
@@ -286,7 +286,6 @@ impl EnsembleFfi {
.ok()
.flatten();
let store = self.core.store();
let peer_node_store = Arc::new(store.peer_node_store.clone());
// The ensemble's key for sealing this node's name in its announcements
// — see `p2p::sealed_name`. Missing it means announcing unnamed, not
// announcing in the clear, so a failure here is logged and carried on
@@ -339,7 +338,6 @@ impl EnsembleFfi {
node_name,
name_key,
bootstrap_peers,
Some(peer_node_store),
))
.map_err(|e| SyncError::Internal { msg: e.to_string() })?;
-1
View File
@@ -293,7 +293,6 @@ impl NodeRuntime {
node_name,
Some(name_key.clone()),
bootstrap_peers,
Some(Arc::clone(&peer_node_store)),
)
.await
{
+145 -267
View File
@@ -9,7 +9,7 @@
//! See `docs/BOOTSTRAPPING.md` for the full design rationale.
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, RwLock};
use std::sync::{Arc, PoisonError, RwLock};
use iroh::{
Endpoint, EndpointAddr, EndpointId, PublicKey, RelayUrl, SecretKey, Signature,
@@ -29,6 +29,7 @@ use crate::ensemble::secret::{Keypair, NodeSecret};
use crate::node::NodePubkey;
use crate::p2p::sealed_name::{NameKey, SealedName};
use crate::p2p::wire_time::wire_timestamp;
use crate::stores::Store;
use crate::stores::document::DocumentStore;
/// Errors that can occur in gossip operations.
@@ -47,7 +48,7 @@ pub enum GossipError {
}
use crate::stores::epoch::EpochStore;
use crate::stores::peer_health::PeerHealthStore;
use crate::stores::peer_nodes::{PeerNode, PeerNodeStore};
use crate::stores::peer_nodes::PeerNode;
use crate::stores::revocation::RevocationStore;
use iroh_gossip::api::GossipSender;
@@ -227,16 +228,7 @@ enum GossipMessage {
EpochBump(EpochBump),
}
/// A verified peer discovered via gossip.
#[derive(Debug, Clone)]
pub struct DiscoveredPeer {
pub node_pubkey: PublicKey,
/// `announced_at_secs` of the announcement this record came from. Used to
/// discard replays — see [`PeerMap::upsert`].
pub announced_at_secs: i64,
}
/// What [`PeerMap::upsert`] did with an incoming peer record.
/// What [`PeerMap::upsert`] did with an incoming announcement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PeerUpdate {
/// A node we had not seen before this process started.
@@ -247,17 +239,14 @@ pub enum PeerUpdate {
Stale,
}
/// Tracks peers discovered via gossip for a single ensemble topic.
/// The newest `announced_at_secs` seen per peer on one ensemble topic — the
/// high-water mark that discards replays; see [`PeerMap::upsert`].
#[derive(Debug, Clone, Default)]
pub struct PeerMap(Arc<RwLock<HashMap<PublicKey, DiscoveredPeer>>>);
pub struct PeerMap(Arc<RwLock<HashMap<PublicKey, i64>>>);
impl PeerMap {
pub fn new() -> Self {
Self::default()
}
/// Insert or update a discovered peer, ignoring an announcement older than
/// the one already held for that node.
/// Record an announcement from `node` stamped `announced_at_secs`,
/// ignoring one older than the one already held for that node.
///
/// A signature makes an announcement unforgeable but not un-*replayable*:
/// a node's own past announcements stay valid forever, so a swarm member
@@ -271,31 +260,19 @@ impl PeerMap {
/// re-announcement every [`REANNOUNCE_INTERVAL`] supersedes it — and it
/// would trade a schema column and a write per announcement for that.
/// Revisit if announcements ever carry something costlier to roll back.
pub fn upsert(&self, peer: DiscoveredPeer) -> PeerUpdate {
let mut map = self.0.write().expect("peer map poisoned");
match map.get(&peer.node_pubkey) {
Some(existing) if existing.announced_at_secs >= peer.announced_at_secs => {
PeerUpdate::Stale
}
Some(_) => {
map.insert(peer.node_pubkey, peer);
PeerUpdate::Updated
}
None => {
map.insert(peer.node_pubkey, peer);
PeerUpdate::New
}
pub fn upsert(&self, node: PublicKey, announced_at_secs: i64) -> PeerUpdate {
let mut map = self.0.write().unwrap_or_else(PoisonError::into_inner);
let held = map.get(&node).copied();
if held.is_some_and(|held| held >= announced_at_secs) {
return PeerUpdate::Stale;
}
map.insert(node, announced_at_secs);
if held.is_some() { PeerUpdate::Updated } else { PeerUpdate::New }
}
#[cfg(test)]
fn len(&self) -> usize {
self.0.read().expect("peer map poisoned").len()
}
#[cfg(test)]
fn is_empty(&self) -> bool {
self.len() == 0
self.0.read().unwrap_or_else(PoisonError::into_inner).len()
}
}
@@ -307,24 +284,13 @@ pub struct GossipDiscovery {
/// fresh `announced_at_secs`.
node_secret: SecretKey,
peer_map: PeerMap,
/// Persistent store for discovered peers, if available.
peer_node_store: Option<Arc<PeerNodeStore>>,
/// Where a peer's clock skew is recorded, if attached — see
/// [`set_peer_health_store`](Self::set_peer_health_store). A cheap clone
/// (just a db path), like the stores below it.
peer_health_store: Option<PeerHealthStore>,
/// Document store to apply incoming [`PurgeIntent`]s against, if attached.
/// A cheap clone (just a db path) — see [`DocumentStore`].
document_store: Option<DocumentStore>,
/// Deny-list to apply incoming revocations against, if attached. Also a
/// cheap clone.
revocation_store: Option<RevocationStore>,
/// Where a verified [`EpochBump`] is applied, if attached — see
/// [`set_epoch_store`](Self::set_epoch_store).
epoch_store: Option<EpochStore>,
/// Channel to push updated announcement payloads into the background task.
/// Sending a new value causes the next reannounce cycle to use it immediately.
announcement_tx: Option<tokio::sync::watch::Sender<Vec<u8>>>,
/// Where discovered peers, their clock skew, and verified purge intents,
/// revocations and epoch bumps are applied.
store: Arc<Store>,
/// This node's current announcement, shared with the background task.
/// Sending a new value makes the task broadcast it immediately, and every
/// later reannounce uses it.
announcement_tx: Option<tokio::sync::watch::Sender<NodeAnnouncement>>,
/// Sender half of the gossip topic, kept so callers can retry bootstrap via
/// [`join_peers`] after the initial subscribe.
topic_sender: Option<GossipSender>,
@@ -353,63 +319,20 @@ impl GossipDiscovery {
/// The returned [`Gossip`] protocol handler must be registered on the
/// router (via `router.accept(iroh_gossip::ALPN, gossip.clone())`) before
/// calling [`join`].
pub fn new(endpoint: &Endpoint, node_secret: SecretKey) -> (Self, Gossip) {
pub fn new(endpoint: &Endpoint, node_secret: SecretKey, store: Arc<Store>) -> (Self, Gossip) {
// raw-endpoint-ok: gossip is not connection-gated; it verifies a delegation cert per message instead
let gossip = Gossip::builder().spawn(endpoint.clone());
let discovery = GossipDiscovery {
gossip: gossip.clone(),
node_secret,
peer_map: PeerMap::new(),
peer_node_store: None,
peer_health_store: None,
document_store: None,
revocation_store: None,
epoch_store: None,
peer_map: PeerMap::default(),
store,
announcement_tx: None,
topic_sender: None,
active_neighbors: Arc::new(RwLock::new(HashSet::new())),
name_key: None,
};
(discovery, gossip.clone())
}
/// Set the persistent peer store on an already-constructed instance.
pub fn set_peer_node_store(&mut self, store: Arc<PeerNodeStore>) {
self.peer_node_store = Some(store);
}
/// Attach the per-peer diagnostics store, so that a peer whose announced
/// time disagrees with this node's clock is recorded rather than only
/// implied by what later fails to merge.
///
/// An announcement is the right measurement point and the only one
/// available before a sync: it is signed, so the time in it is
/// attributable, and it repeats every [`REANNOUNCE_INTERVAL`] — which is
/// also what lets the record clear itself once the clock is fixed, with no
/// separate resolve step for anything to forget to run.
pub fn set_peer_health_store(&mut self, store: PeerHealthStore) {
self.peer_health_store = Some(store);
}
/// Attach a document store so that verified, incoming [`PurgeIntent`]s are
/// auto-honored: applied as local tombstones as soon as they arrive.
pub fn set_document_store(&mut self, store: DocumentStore) {
self.document_store = Some(store);
}
/// Attach the deny-list so that verified, incoming revocation records are
/// applied as soon as they arrive — which is what makes a revocation take
/// effect on a running node within a gossip round rather than at its next
/// sync.
pub fn set_revocation_store(&mut self, store: RevocationStore) {
self.revocation_store = Some(store);
}
/// Attach the epoch store so that verified, incoming bumps are applied as
/// soon as they arrive — which is what makes an epoch move take effect on
/// the next connection rather than at the next sync.
pub fn set_epoch_store(&mut self, store: EpochStore) {
self.epoch_store = Some(store);
(discovery, gossip)
}
/// Attach the ensemble's key for sealing this node's name and opening its
@@ -458,25 +381,16 @@ impl GossipDiscovery {
let sealed_name = seal_name(node_name.as_deref(), self.name_key.as_ref(), &our_cert);
let announcement =
NodeAnnouncement::signed(our_cert, relay_url, sealed_name, &self.node_secret);
let payload = serde_json::to_vec(&GossipMessage::Announcement(announcement))?;
sender
.broadcast(payload.clone().into())
.await
.map_err(|e| GossipError::Broadcast(e.to_string()))?;
broadcast(&sender, &GossipMessage::Announcement(announcement.clone())).await?;
info!("Broadcast node announcement to gossip topic");
// Watch channel so callers can push an updated announcement (e.g. after
// a node name change) and have the background task broadcast it immediately.
// Always holds a serialized `GossipMessage::Announcement` — see `update_node_name`.
let (ann_tx, mut ann_rx) = tokio::sync::watch::channel(payload);
let (ann_tx, mut ann_rx) = tokio::sync::watch::channel(announcement);
// Spawn background task to process incoming events.
let peer_map = self.peer_map.clone();
let peer_node_store = self.peer_node_store.clone();
let peer_health_store = self.peer_health_store.clone();
let document_store = self.document_store.clone();
let revocation_store = self.revocation_store.clone();
let epoch_store = self.epoch_store.clone();
let store = Arc::clone(&self.store);
let expected_ensemble = *ensemble_pubkey;
let active_neighbors = Arc::clone(&self.active_neighbors);
let name_key = self.name_key.clone();
@@ -490,8 +404,8 @@ impl GossipDiscovery {
loop {
tokio::select! {
_ = reannounce.tick() => {
let current = ann_rx.borrow().clone();
if let Err(e) = sender.broadcast(current.into()).await {
let current = GossipMessage::Announcement(ann_rx.borrow().clone());
if let Err(e) = broadcast(&sender, &current).await {
warn!("Failed to rebroadcast node announcement: {e}");
} else {
info!("Rebroadcast node announcement (periodic)");
@@ -499,9 +413,9 @@ impl GossipDiscovery {
}
result = ann_rx.changed() => {
if result.is_err() { break; } // sender dropped
let updated = ann_rx.borrow().clone();
let updated = GossipMessage::Announcement(ann_rx.borrow().clone());
info!("Announcement updated — broadcasting immediately");
if let Err(e) = sender.broadcast(updated.into()).await {
if let Err(e) = broadcast(&sender, &updated).await {
warn!("Failed to broadcast updated announcement: {e}");
}
}
@@ -516,8 +430,7 @@ impl GossipDiscovery {
&expected_ensemble,
ann,
name_key.as_ref(),
peer_node_store.as_deref(),
peer_health_store.as_ref(),
&store,
&addr_cache,
);
}
@@ -525,21 +438,21 @@ impl GossipDiscovery {
handle_purge_intent(
&expected_ensemble,
intent,
document_store.as_ref(),
&store.doc_store,
);
}
Ok(GossipMessage::EpochBump(bump)) => {
handle_epoch_bump(
&expected_ensemble,
bump,
epoch_store.as_ref(),
&store.epoch_store,
);
}
Ok(GossipMessage::Revocation(record)) => {
handle_revocation(
&expected_ensemble,
record,
revocation_store.as_ref(),
&store.revocation_store,
);
}
Err(e) => {
@@ -549,17 +462,22 @@ impl GossipDiscovery {
}
Ok(Event::NeighborUp(id)) => {
let n = {
let mut neighbors =
active_neighbors.write().expect("active neighbors poisoned");
let mut neighbors = active_neighbors
.write()
.unwrap_or_else(PoisonError::into_inner);
neighbors.insert(id);
neighbors.len()
};
info!("Gossip neighbor up: {} (active: {n})", id.fmt_short());
let current = ann_rx.borrow().clone();
if let Err(e) = sender
.broadcast_neighbors(current.into())
.await
{
let current = GossipMessage::Announcement(ann_rx.borrow().clone());
let sent = match serde_json::to_vec(&current) {
Ok(bytes) => sender
.broadcast_neighbors(bytes.into())
.await
.map_err(|e| e.to_string()),
Err(e) => Err(e.to_string()),
};
if let Err(e) = sent {
warn!(
"Failed to re-announce to new neighbor {}: {e}",
id.fmt_short()
@@ -568,8 +486,9 @@ impl GossipDiscovery {
}
Ok(Event::NeighborDown(id)) => {
let n = {
let mut neighbors =
active_neighbors.write().expect("active neighbors poisoned");
let mut neighbors = active_neighbors
.write()
.unwrap_or_else(PoisonError::into_inner);
neighbors.remove(&id);
neighbors.len()
};
@@ -604,7 +523,7 @@ impl GossipDiscovery {
/// Returns the number of currently live gossip neighbors.
pub fn neighbor_count(&self) -> usize {
self.active_neighbors.read().expect("active neighbors poisoned").len()
self.active_neighbors.read().unwrap_or_else(PoisonError::into_inner).len()
}
/// Update the node name in the outgoing announcement and immediately
@@ -612,28 +531,20 @@ impl GossipDiscovery {
pub fn update_node_name(&self, new_name: Option<String>) -> Result<(), GossipError> {
let tx = self.announcement_tx.as_ref().ok_or(GossipError::NotJoined)?;
let current = tx.borrow().clone();
let mut message: GossipMessage = serde_json::from_slice(&current)?;
let GossipMessage::Announcement(announcement) = &mut message else {
// The channel only ever holds the outgoing self-announcement —
// see the invariant documented on `join`'s `ann_tx`.
return Err(GossipError::NotJoined);
};
// Re-sign rather than patching the name in place: `node_name` is
// inside the signed payload, so an edited-but-unre-signed announcement
// would be dropped by every peer as a bad signature. Re-signing also
// re-stamps `announced_at_secs`, which is what makes the new name win
// over the old one at receivers.
let sealed_name =
seal_name(new_name.as_deref(), self.name_key.as_ref(), &announcement.delegation_cert);
*announcement = NodeAnnouncement::signed(
announcement.delegation_cert.clone(),
announcement.relay_url.clone(),
seal_name(new_name.as_deref(), self.name_key.as_ref(), &current.delegation_cert);
let updated = NodeAnnouncement::signed(
current.delegation_cert,
current.relay_url,
sealed_name,
&self.node_secret,
);
let payload = serde_json::to_vec(&message)?;
tx.send(payload).map_err(|_| GossipError::Stopped)?;
Ok(())
tx.send(updated).map_err(|_| GossipError::Stopped)
}
}
@@ -670,8 +581,7 @@ fn handle_announcement(
expected_ensemble: &[u8; 32],
announcement: NodeAnnouncement,
name_key: Option<&NameKey>,
peer_node_store: Option<&PeerNodeStore>,
peer_health_store: Option<&PeerHealthStore>,
store: &Store,
addr_cache: &MemoryLookup,
) {
let cert = &announcement.delegation_cert;
@@ -705,11 +615,7 @@ fn handle_announcement(
// into it needs the same bound every other incoming timestamp gets
// ([`wire_timestamp`]) — see [`believable_recency`] for what goes wrong
// without it.
let peer = DiscoveredPeer {
node_pubkey,
announced_at_secs: believable_recency(announcement.announced_at_secs),
};
match peer_map.upsert(peer) {
match peer_map.upsert(node_pubkey, believable_recency(announcement.announced_at_secs)) {
PeerUpdate::New => {
info!("Discovered new ensemble peer via gossip: {}", node_pubkey.fmt_short());
}
@@ -735,9 +641,11 @@ fn handle_announcement(
// an old, validly-signed time, which measured against now looks exactly
// like a clock that is behind — and raising an alarm from a replay is how
// a diagnostic teaches people to ignore it.
if let Some(health) = peer_health_store {
record_announcement_skew(health, &node_pubkey, announcement.announced_at_secs);
}
record_announcement_skew(
&store.peer_health_store,
&node_pubkey,
announcement.announced_at_secs,
);
// Inject the relay URL into iroh's address cache so future connections to
// this peer bypass pkarr DNS entirely.
@@ -749,28 +657,27 @@ fn handle_announcement(
info!("Cached relay address for gossip peer {} from announcement", node_pubkey.fmt_short());
}
// Persist to the database if a store is available. The name is opened here
// and stored in the clear: the store is this node's own disk, already the
// home of the node secret and every document, and protected by
// `stores::permissions` rather than by this seal.
if let Some(store) = peer_node_store {
let display_name = open_name(&announcement.node_name, name_key, &cert.node_pubkey);
let now: Timestamp = chrono::Utc::now().into();
let seen = PeerNode {
node_pubkey: cert.node_pubkey,
ensemble_pubkey: cert.ensemble_pubkey,
display_name,
relay_url: announcement.relay_url,
// What a revocation for this peer would have to name — see
// `PeerNodeStore`'s module docs.
cert_fingerprint: Some(cert.fingerprint()),
first_seen_at: now,
last_seen_at: now,
last_synced_at: None,
};
if let Err(e) = store.batch(|tx| store.upsert_peer_node(tx, &seen)) {
warn!("Failed to persist gossip peer to database: {e}");
}
// Persist the peer. The name is opened here and stored in the clear: the
// store is this node's own disk, already the home of the node secret and
// every document, and protected by `stores::permissions` rather than by
// this seal.
let display_name = open_name(&announcement.node_name, name_key, &cert.node_pubkey);
let now: Timestamp = chrono::Utc::now().into();
let seen = PeerNode {
node_pubkey: cert.node_pubkey,
ensemble_pubkey: cert.ensemble_pubkey,
display_name,
relay_url: announcement.relay_url,
// What a revocation for this peer would have to name — see
// `PeerNodeStore`'s module docs.
cert_fingerprint: Some(cert.fingerprint()),
first_seen_at: now,
last_seen_at: now,
last_synced_at: None,
};
let peers = &store.peer_node_store;
if let Err(e) = peers.batch(|tx| peers.upsert_peer_node(tx, &seen)) {
warn!("Failed to persist gossip peer to database: {e}");
}
}
@@ -874,11 +781,7 @@ fn verify_cert(cert: &DelegationCert, expected_ensemble: &[u8; 32]) -> Result<Pu
/// tombstone locally for every id it lists. Never fatal to the event loop —
/// failures are logged and the message is dropped, same tolerance style as
/// [`handle_announcement`].
fn handle_purge_intent(
expected_ensemble: &[u8; 32],
intent: PurgeIntent,
document_store: Option<&DocumentStore>,
) {
fn handle_purge_intent(expected_ensemble: &[u8; 32], intent: PurgeIntent, store: &DocumentStore) {
let cert = &intent.delegation_cert;
let node_pubkey = match verify_cert(cert, expected_ensemble) {
@@ -895,11 +798,6 @@ fn handle_purge_intent(
return;
}
let Some(store) = document_store else {
info!("Received purge intent but no document store is attached; ignoring");
return;
};
// A document tombstone is the least reversible thing a peer can ask for:
// it can never be superseded by a later one dated earlier, it blocks the
// id from ever being recreated, and it cascades to the document's
@@ -948,16 +846,12 @@ fn handle_purge_intent(
fn handle_revocation(
expected_ensemble: &[u8; 32],
record: RevocationRecord,
revocation_store: Option<&RevocationStore>,
store: &RevocationStore,
) {
if let Err(e) = record.verify(expected_ensemble) {
warn!("Dropping revocation record: {e}");
return;
}
let Some(store) = revocation_store else {
info!("Received a revocation record but no deny-list is attached; ignoring");
return;
};
// A revocation's stamp is not what the check is made against — the
// deny-list is keyed by cert fingerprint — so a stamp this node cannot
@@ -988,19 +882,11 @@ fn handle_revocation(
/// relayed it — the same property that makes a revocation relayable, and for
/// the same reason: a node that is about to be locked out must not be able to
/// suppress the record by refusing to pass it on.
fn handle_epoch_bump(
expected_ensemble: &[u8; 32],
bump: EpochBump,
epoch_store: Option<&EpochStore>,
) {
fn handle_epoch_bump(expected_ensemble: &[u8; 32], bump: EpochBump, store: &EpochStore) {
if let Err(e) = bump.verify(expected_ensemble) {
warn!("Dropping epoch bump: {e}");
return;
}
let Some(store) = epoch_store else {
info!("Received an epoch bump but no epoch store is attached; ignoring");
return;
};
// The number orders epochs, not the clock, so an unbelievable stamp costs
// this record its date rather than its effect.
let bumped_at = wire_timestamp(bump.bumped_at_secs).unwrap_or_else(|| {
@@ -1018,6 +904,12 @@ fn handle_epoch_bump(
}
}
/// Serialize `message` and broadcast it to the ensemble's gossip topic.
async fn broadcast(sender: &GossipSender, message: &GossipMessage) -> Result<(), GossipError> {
let bytes = serde_json::to_vec(message)?;
sender.broadcast(bytes.into()).await.map_err(|e| GossipError::Broadcast(e.to_string()))
}
/// Broadcast an epoch bump to the ensemble's gossip topic.
///
/// Best-effort and unacknowledged, exactly like [`broadcast_revocation`]:
@@ -1027,8 +919,7 @@ pub async fn broadcast_epoch_bump(
sender: &GossipSender,
bump: &EpochBump,
) -> Result<(), GossipError> {
let bytes = serde_json::to_vec(&GossipMessage::EpochBump(bump.clone()))?;
sender.broadcast(bytes.into()).await.map_err(|e| GossipError::Broadcast(e.to_string()))?;
broadcast(sender, &GossipMessage::EpochBump(bump.clone())).await?;
info!("Broadcast epoch bump to {} to gossip topic", bump.epoch);
Ok(())
}
@@ -1048,8 +939,7 @@ pub async fn broadcast_revocation(
sender: &GossipSender,
record: &RevocationRecord,
) -> Result<(), GossipError> {
let bytes = serde_json::to_vec(&GossipMessage::Revocation(record.clone()))?;
sender.broadcast(bytes.into()).await.map_err(|e| GossipError::Broadcast(e.to_string()))?;
broadcast(sender, &GossipMessage::Revocation(record.clone())).await?;
info!("Broadcast revocation for node {} to gossip topic", record.node_id_hex());
Ok(())
}
@@ -1074,8 +964,7 @@ pub async fn broadcast_purge_intent(
let intent =
PurgeIntent { delegation_cert: cert.clone(), document_ids, deleted_at_secs, signature };
let bytes = serde_json::to_vec(&GossipMessage::PurgeIntent(intent))?;
sender.broadcast(bytes.into()).await.map_err(|e| GossipError::Broadcast(e.to_string()))?;
broadcast(sender, &GossipMessage::PurgeIntent(intent)).await?;
info!("Broadcast purge intent for {} document(s) to gossip topic", purged_ids.len());
Ok(())
}
@@ -1121,17 +1010,14 @@ mod tests {
#[test]
fn test_peer_map_insert_and_retrieve() {
let peer_map = PeerMap::new();
let peer_map = PeerMap::default();
let node_kp = Secret::<NodeSecret>::new_format_a().to_keypair();
let pubkey = node_kp.secret_key().public();
let peer = DiscoveredPeer { node_pubkey: pubkey, announced_at_secs: 500 };
assert_eq!(peer_map.upsert(peer.clone()), PeerUpdate::New);
assert_eq!(peer_map.upsert(pubkey, 500), PeerUpdate::New);
// Re-announcing at the same instant is not news.
assert_eq!(peer_map.upsert(peer.clone()), PeerUpdate::Stale);
let newer = DiscoveredPeer { announced_at_secs: 501, ..peer };
assert_eq!(peer_map.upsert(newer), PeerUpdate::Updated);
assert_eq!(peer_map.upsert(pubkey, 500), PeerUpdate::Stale);
assert_eq!(peer_map.upsert(pubkey, 501), PeerUpdate::Updated);
}
/// The recency guard must not be usable as a denial. An announcement this
@@ -1154,15 +1040,10 @@ mod tests {
);
// An honest announcement a moment later therefore still wins.
let peer_map = PeerMap::new();
let peer_map = PeerMap::default();
let pubkey = Secret::<NodeSecret>::new_format_a().to_keypair().secret_key().public();
let skewed = DiscoveredPeer {
node_pubkey: pubkey,
announced_at_secs: believable_recency(three_days_ahead),
};
assert_eq!(peer_map.upsert(skewed.clone()), PeerUpdate::New);
let honest = DiscoveredPeer { announced_at_secs: believable_recency(now + 1), ..skewed };
assert_eq!(peer_map.upsert(honest), PeerUpdate::Updated);
assert_eq!(peer_map.upsert(pubkey, believable_recency(three_days_ahead)), PeerUpdate::New);
assert_eq!(peer_map.upsert(pubkey, believable_recency(now + 1)), PeerUpdate::Updated);
}
/// A believable stamp is passed through untouched, so the replay guard
@@ -1178,18 +1059,15 @@ mod tests {
/// separating it from the real one, so the peer map must not take it.
#[test]
fn a_replayed_older_announcement_does_not_displace_a_newer_one() {
let peer_map = PeerMap::new();
let peer_map = PeerMap::default();
let pubkey = Secret::<NodeSecret>::new_format_a().to_keypair().secret_key().public();
let current = DiscoveredPeer { node_pubkey: pubkey, announced_at_secs: 900 };
assert_eq!(peer_map.upsert(current), PeerUpdate::New);
let replayed = DiscoveredPeer { node_pubkey: pubkey, announced_at_secs: 100 };
assert_eq!(peer_map.upsert(replayed), PeerUpdate::Stale);
assert_eq!(peer_map.upsert(pubkey, 900), PeerUpdate::New);
assert_eq!(peer_map.upsert(pubkey, 100), PeerUpdate::Stale);
}
#[test]
fn test_handle_announcement_valid() {
#[rstest]
fn test_handle_announcement_valid(store: TestStore) {
let ensemble_secret = Secret::<EnsembleSecret>::new_format_a();
let ensemble_kp = ensemble_secret.to_keypair();
let ensemble_pubkey = *ensemble_kp.public_key().as_bytes();
@@ -1206,14 +1084,14 @@ mod tests {
node_kp.secret_key(),
);
let peer_map = PeerMap::new();
let peer_map = PeerMap::default();
let cache = MemoryLookup::with_provenance("test");
handle_announcement(&peer_map, &ensemble_pubkey, ann, None, None, None, &cache);
handle_announcement(&peer_map, &ensemble_pubkey, ann, None, &store, &cache);
assert_eq!(peer_map.len(), 1);
}
#[test]
fn test_handle_announcement_wrong_ensemble() {
#[rstest]
fn test_handle_announcement_wrong_ensemble(store: TestStore) {
let ensemble_secret = Secret::<EnsembleSecret>::new_format_a();
let ensemble_kp = ensemble_secret.to_keypair();
@@ -1223,14 +1101,14 @@ mod tests {
let ann = NodeAnnouncement::signed(cert, None, None, node_kp.secret_key());
let wrong_ensemble = [0xFFu8; 32];
let peer_map = PeerMap::new();
let peer_map = PeerMap::default();
let cache = MemoryLookup::with_provenance("test");
handle_announcement(&peer_map, &wrong_ensemble, ann, None, None, None, &cache);
assert!(peer_map.is_empty(), "Should reject announcement from different ensemble");
handle_announcement(&peer_map, &wrong_ensemble, ann, None, &store, &cache);
assert!(peer_map.len() == 0, "Should reject announcement from different ensemble");
}
#[test]
fn test_handle_announcement_tampered_cert() {
#[rstest]
fn test_handle_announcement_tampered_cert(store: TestStore) {
let ensemble_secret = Secret::<EnsembleSecret>::new_format_a();
let ensemble_kp = ensemble_secret.to_keypair();
let ensemble_pubkey = *ensemble_kp.public_key().as_bytes();
@@ -1242,10 +1120,10 @@ mod tests {
let ann = NodeAnnouncement::signed(cert, None, None, node_kp.secret_key());
let peer_map = PeerMap::new();
let peer_map = PeerMap::default();
let cache = MemoryLookup::with_provenance("test");
handle_announcement(&peer_map, &ensemble_pubkey, ann, None, None, None, &cache);
assert!(peer_map.is_empty(), "Should reject announcement with tampered cert");
handle_announcement(&peer_map, &ensemble_pubkey, ann, None, &store, &cache);
assert!(peer_map.len() == 0, "Should reject announcement with tampered cert");
}
/// The attack the signature exists to stop: certs are public and ride in
@@ -1253,8 +1131,8 @@ mod tests {
/// so must not let them dictate that node's relay URL or display name —
/// the latter being what a human reads off the ensemble roster when
/// choosing a node to act on.
#[test]
fn a_harvested_cert_cannot_be_used_to_forge_someone_elses_announcement() {
#[rstest]
fn a_harvested_cert_cannot_be_used_to_forge_someone_elses_announcement(store: TestStore) {
let ensemble_kp = Secret::<EnsembleSecret>::new_format_a().to_keypair();
let ensemble_pubkey = *ensemble_kp.public_key().as_bytes();
@@ -1273,19 +1151,19 @@ mod tests {
attacker_kp.secret_key(),
);
let peer_map = PeerMap::new();
let peer_map = PeerMap::default();
let cache = MemoryLookup::with_provenance("test");
handle_announcement(&peer_map, &ensemble_pubkey, forged, None, None, None, &cache);
handle_announcement(&peer_map, &ensemble_pubkey, forged, None, &store, &cache);
assert!(
peer_map.is_empty(),
peer_map.len() == 0,
"an announcement signed by anyone but the node its cert names must be dropped"
);
}
/// Editing a signed announcement in flight must invalidate it, including
/// the display-metadata field that used to be unauthenticated.
#[test]
fn an_announcement_whose_name_was_edited_in_flight_is_dropped() {
#[rstest]
fn an_announcement_whose_name_was_edited_in_flight_is_dropped(store: TestStore) {
let ensemble_kp = Secret::<EnsembleSecret>::new_format_a().to_keypair();
let ensemble_pubkey = *ensemble_kp.public_key().as_bytes();
let node_kp = Secret::<NodeSecret>::new_format_a().to_keypair();
@@ -1300,10 +1178,10 @@ mod tests {
);
ann.node_name = Some(sealed("Greg's phone", &key, &cert));
let peer_map = PeerMap::new();
let peer_map = PeerMap::default();
let cache = MemoryLookup::with_provenance("test");
handle_announcement(&peer_map, &ensemble_pubkey, ann, None, None, None, &cache);
assert!(peer_map.is_empty(), "a rewritten node_name must break the signature");
handle_announcement(&peer_map, &ensemble_pubkey, ann, None, &store, &cache);
assert!(peer_map.len() == 0, "a rewritten node_name must break the signature");
}
/// Length-prefixing, not concatenation: `("ab", "c")` and `("a", "bc")`
@@ -1376,8 +1254,8 @@ mod tests {
/// A name that will not open is not grounds to drop the peer: the cert and
/// the signature have already said this is a member of this ensemble, and
/// an unnamed peer is still one to sync with.
#[test]
fn a_name_this_node_cannot_open_leaves_the_peer_unnamed_not_rejected() {
#[rstest]
fn a_name_this_node_cannot_open_leaves_the_peer_unnamed_not_rejected(store: TestStore) {
let ensemble_kp = Secret::<EnsembleSecret>::new_format_a().to_keypair();
let ensemble_pubkey = *ensemble_kp.public_key().as_bytes();
let node_kp = Secret::<NodeSecret>::new_format_a().to_keypair();
@@ -1394,9 +1272,9 @@ mod tests {
let stranger = name_key(&Secret::<EnsembleSecret>::new_format_a().to_keypair());
assert_eq!(open_name(&ann.node_name, Some(&stranger), &cert.node_pubkey), None);
let peer_map = PeerMap::new();
let peer_map = PeerMap::default();
let cache = MemoryLookup::with_provenance("test");
handle_announcement(&peer_map, &ensemble_pubkey, ann, Some(&stranger), None, None, &cache);
handle_announcement(&peer_map, &ensemble_pubkey, ann, Some(&stranger), &store, &cache);
assert_eq!(peer_map.len(), 1, "the peer itself is still perfectly good");
}
@@ -1432,7 +1310,7 @@ mod tests {
&node_kp,
vec![Uuid::from_bytes(doc_id.as_uuid_bytes())],
);
handle_purge_intent(&ensemble_pubkey, intent, Some(&store));
handle_purge_intent(&ensemble_pubkey, intent, &store);
assert!(is_tombstoned(&store, &doc_id).is_some());
}
@@ -1455,7 +1333,7 @@ mod tests {
vec![Uuid::from_bytes(doc_id.as_uuid_bytes())],
);
let wrong_ensemble = [0xFFu8; 32];
handle_purge_intent(&wrong_ensemble, intent, Some(&store));
handle_purge_intent(&wrong_ensemble, intent, &store);
assert!(is_tombstoned(&store, &doc_id).is_none());
}
@@ -1480,7 +1358,7 @@ mod tests {
);
// Tamper with the id list after signing, so it no longer matches the signature.
intent.document_ids.push(Uuid::new_v4());
handle_purge_intent(&ensemble_pubkey, intent, Some(&store));
handle_purge_intent(&ensemble_pubkey, intent, &store);
assert!(is_tombstoned(&store, &doc_id).is_none());
}
@@ -1516,7 +1394,7 @@ mod tests {
let (record, cert) = self_revocation(&ensemble_kp);
let revocations = &store.revocation_store;
handle_revocation(ensemble_kp.public_key().as_bytes(), record, Some(revocations));
handle_revocation(ensemble_kp.public_key().as_bytes(), record, revocations);
assert!(
revocations.batch(|tx| revocations.is_cert_revoked(tx, &cert.fingerprint())).unwrap()
@@ -1532,7 +1410,7 @@ mod tests {
let (record, cert) = self_revocation(&elsewhere);
let revocations = &store.revocation_store;
handle_revocation(ours.public_key().as_bytes(), record, Some(revocations));
handle_revocation(ours.public_key().as_bytes(), record, revocations);
assert!(
!revocations.batch(|tx| revocations.is_cert_revoked(tx, &cert.fingerprint())).unwrap()
@@ -1546,7 +1424,7 @@ mod tests {
record.revoked_cert_fingerprint[0] ^= 0xFF;
let revocations = &store.revocation_store;
handle_revocation(ensemble_kp.public_key().as_bytes(), record.clone(), Some(revocations));
handle_revocation(ensemble_kp.public_key().as_bytes(), record.clone(), revocations);
assert!(
!revocations
@@ -1570,7 +1448,7 @@ mod tests {
let record = RevocationRecord::self_signed_at(&cert, &node_kp, a_year_ahead);
let revocations = &store.revocation_store;
handle_revocation(ensemble_kp.public_key().as_bytes(), record, Some(revocations));
handle_revocation(ensemble_kp.public_key().as_bytes(), record, revocations);
assert!(
revocations.batch(|tx| revocations.is_cert_revoked(tx, &cert.fingerprint())).unwrap(),
+4 -21
View File
@@ -52,7 +52,7 @@ use crate::ensemble::RegistryMember;
use crate::ensemble::secret::{Keypair, NodeSecret};
use crate::jobs::runner::JobRunner;
use crate::node::NodePubkey;
use crate::stores::{Store, peer_nodes::PeerNodeStore};
use crate::stores::Store;
use admission::{CertifiedPeer, EnsembleEndpoint, EnsembleProtocol, Gate, Retiring};
use artifact_sync::{ARTIFACT_SYNC_ALPN, ArtifactSyncHandler};
use blob_stream::{BLOB_STREAM_ALPN, BlobStreamHandler};
@@ -262,19 +262,8 @@ impl P2PNode {
}
// Set up gossip protocol handler alongside ping.
let (mut gossip_discovery, gossip_handle) =
GossipDiscovery::new(&endpoint, keypair.secret_key().clone());
// Cheap clone (just a db path) — lets incoming purge intents be
// auto-honored as soon as they arrive, without threading the whole
// Store through the gossip module.
gossip_discovery.set_document_store(store.doc_store.clone());
gossip_discovery.set_revocation_store(store.revocation_store.clone());
gossip_discovery.set_epoch_store(store.epoch_store.clone());
// Set here rather than at `join_ensemble_gossip`, unlike the peer
// store: nothing about measuring a peer's clock depends on the join
// arguments, and a diagnostic that is only attached on some paths is a
// diagnostic that is silently absent on the others.
gossip_discovery.set_peer_health_store(store.peer_health_store.clone());
let (gossip_discovery, gossip_handle) =
GossipDiscovery::new(&endpoint, keypair.secret_key().clone(), Arc::clone(&store));
let local_node = NodePubkey(*keypair.secret_key().public().as_bytes());
let job_runner = JobRunnerCell::default();
@@ -342,8 +331,7 @@ impl P2PNode {
/// self-reported human-readable label included in the outgoing announcement,
/// sealed under `name_key` so that only ensemble members can read it (see
/// [`gossip::sealed_name`](crate::p2p::sealed_name)); pass `None` and this node
/// announces itself unnamed rather than in the clear. `peer_node_store` is the
/// persistent store for discovered peers; pass `None` to skip persistence.
/// announces itself unnamed rather than in the clear.
pub async fn join_ensemble_gossip(
&mut self,
ensemble_pubkey: &[u8; 32],
@@ -351,15 +339,10 @@ impl P2PNode {
node_name: Option<String>,
name_key: Option<sealed_name::NameKey>,
bootstrap_peers: Vec<EndpointId>,
peer_node_store: Option<Arc<PeerNodeStore>>,
) -> Result<(), GossipError> {
let relay_url = self.endpoint.addr().relay_urls().next().map(|url| url.to_string());
let discovery = &mut self.gossip_discovery;
if let Some(store) = peer_node_store {
discovery.set_peer_node_store(store);
}
if let Some(key) = name_key {
discovery.set_name_key(key);
}