1use std::collections::HashMap;
2use std::net::SocketAddr;
3use std::sync::Arc;
4use std::time::{Duration, SystemTime, UNIX_EPOCH};
5
6use foca::{AccumulatingRuntime, Config as FocaConfig, Foca, PostcardCodec, Timer};
7use rand::SeedableRng;
8use rand::rngs::SmallRng;
9use serde::{Deserialize, Serialize};
10use tokio::net::UdpSocket;
11use tokio::sync::{Mutex, RwLock};
12use tracing::{debug, info, warn};
13
14use crate::broadcast::{GossipMessage, HoikeBroadcastHandler};
15use crate::config::GossipConfig;
16use crate::crypto::{self, GossipSigner};
17
18fn now_unix() -> u64 {
20 SystemTime::now()
21 .duration_since(UNIX_EPOCH)
22 .map(|d| d.as_secs())
23 .unwrap_or(0)
24}
25
26#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(rename_all = "lowercase")]
30pub enum MemberState {
31 Alive,
32 Suspect,
33 Down,
34}
35
36impl From<foca::State> for MemberState {
37 fn from(s: foca::State) -> Self {
38 match s {
39 foca::State::Alive => MemberState::Alive,
40 foca::State::Suspect => MemberState::Suspect,
41 foca::State::Down => MemberState::Down,
42 }
43 }
44}
45
46#[derive(Clone, Debug, Serialize)]
48pub struct MemberInfo {
49 pub name: String,
50 pub addr: SocketAddr,
51 pub incarnation: u64,
54 pub state: MemberState,
55 pub is_self: bool,
57}
58
59#[derive(Clone, Debug, Serialize)]
62pub struct GenRecord {
63 pub origin_node: String,
65 pub producer_id: String,
66 pub issuer_key_hash: String,
68 pub epoch: u64,
69 pub manifest_digest: String,
70 pub last_seen_unix: u64,
72}
73
74type GenKey = (String, String, String);
76type GenerationTable = Arc<RwLock<HashMap<GenKey, GenRecord>>>;
77
78#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
81pub struct NodeId {
82 pub addr: SocketAddr,
83 pub name: String,
84 pub incarnation: u64,
85}
86
87impl foca::Identity for NodeId {
88 type Addr = SocketAddr;
89
90 fn addr(&self) -> SocketAddr {
91 self.addr
92 }
93
94 fn renew(&self) -> Option<Self> {
95 Some(NodeId {
96 addr: self.addr,
97 name: self.name.clone(),
98 incarnation: self.incarnation + 1,
99 })
100 }
101
102 fn win_addr_conflict(&self, adversary: &Self) -> bool {
103 self.incarnation > adversary.incarnation
104 }
105}
106
107type HoikeFoca = Foca<NodeId, PostcardCodec, SmallRng, HoikeBroadcastHandler>;
108type TimerQueue = Arc<Mutex<Vec<(Duration, Timer<NodeId>)>>>;
109
110pub struct GossipNode {
111 foca: Arc<Mutex<HoikeFoca>>,
112 #[allow(dead_code)]
113 socket: Arc<UdpSocket>,
114 config: GossipConfig,
115 identity: NodeId,
118 generations: GenerationTable,
120 signer: Option<GossipSigner>,
123}
124
125impl GossipNode {
126 pub async fn start(
129 config: GossipConfig,
130 msg_tx: tokio::sync::mpsc::Sender<GossipMessage>,
131 ) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
132 let (signer, verifier) = crypto::load_authentication(&config)?;
139 info!(
140 auth_mode = ?config.auth_mode,
141 peers = config.peer_identities.len(),
142 signing = signer.is_some(),
143 "gossip message authentication loaded"
144 );
145
146 let bind_addr: SocketAddr = config
147 .bind
148 .parse()
149 .map_err(|e| format!("invalid gossip bind address '{}': {}", config.bind, e))?;
150
151 let socket = UdpSocket::bind(bind_addr)
152 .await
153 .map_err(|e| format!("failed to bind gossip socket on {}: {}", bind_addr, e))?;
154
155 let local_addr = socket.local_addr()?;
156 info!(addr = %local_addr, name = %config.node_name, "gossip node starting");
157
158 let identity = NodeId {
159 addr: local_addr,
160 name: config.node_name.clone(),
161 incarnation: 0,
162 };
163
164 let foca_config = FocaConfig::simple();
165 let rng = SmallRng::seed_from_u64(
166 std::time::SystemTime::now()
167 .duration_since(std::time::UNIX_EPOCH)
168 .unwrap_or_default()
169 .as_nanos() as u64,
170 );
171
172 let broadcast_handler = HoikeBroadcastHandler::new(msg_tx, verifier);
173
174 let self_identity = identity.clone();
178
179 let foca = Foca::with_custom_broadcast(
180 identity,
181 foca_config,
182 rng,
183 PostcardCodec,
184 broadcast_handler,
185 );
186
187 let socket = Arc::new(socket);
188 let foca = Arc::new(Mutex::new(foca));
189 let timer_queue: TimerQueue = Arc::new(Mutex::new(Vec::new()));
190
191 let node = GossipNode {
192 foca: Arc::clone(&foca),
193 socket: Arc::clone(&socket),
194 config: config.clone(),
195 identity: self_identity,
196 generations: Arc::new(RwLock::new(HashMap::new())),
197 signer,
198 };
199
200 {
202 let foca = Arc::clone(&foca);
203 let socket = Arc::clone(&socket);
204 let tq = Arc::clone(&timer_queue);
205 tokio::spawn(async move {
206 receive_loop(foca, socket, tq).await;
207 });
208 }
209
210 {
212 let foca = Arc::clone(&foca);
213 let socket_clone = Arc::clone(&socket);
214 let tq = Arc::clone(&timer_queue);
215 tokio::spawn(async move {
216 timer_loop(foca, socket_clone, tq).await;
217 });
218 }
219
220 for seed in &config.seeds {
222 match seed.parse::<SocketAddr>() {
223 Ok(addr) => {
224 let seed_id = NodeId {
225 addr,
226 name: String::new(),
227 incarnation: 0,
228 };
229 let mut foca_guard = foca.lock().await;
230 let mut runtime = AccumulatingRuntime::new();
231 if let Err(e) = foca_guard.announce(seed_id, &mut runtime) {
232 warn!(seed = %addr, error = %e, "failed to announce to seed");
233 }
234 drain_runtime(&mut runtime, &socket, &timer_queue).await;
235 info!(seed = %addr, "announced to seed");
236 }
237 Err(e) => {
238 warn!(seed = %seed, error = %e, "invalid seed address, skipping");
239 }
240 }
241 }
242
243 Ok(node)
244 }
245
246 fn frame_broadcast(&self, payload: Vec<u8>) -> Vec<u8> {
250 match &self.signer {
251 Some(signer) => signer.frame(&payload),
252 None => payload,
253 }
254 }
255
256 pub async fn announce_generation(
258 &self,
259 producer_id: String,
260 issuer_key_hash: Vec<u8>,
261 epoch: u64,
262 manifest_digest: [u8; 32],
263 bundle_url: Option<String>,
264 ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
265 let msg = GossipMessage::GenerationAnnouncement {
266 producer_id,
267 issuer_key_hash,
268 epoch,
269 manifest_digest,
270 bundle_url,
271 origin_node: self.identity.name.clone(),
272 };
273
274 let data = self.frame_broadcast(serde_json::to_vec(&msg)?);
275 let mut foca = self.foca.lock().await;
276 foca.add_broadcast(&data)?;
277
278 info!(msg = %msg, "broadcasting generation announcement");
279 Ok(())
280 }
281
282 pub async fn announce_urgent_revocation(
284 &self,
285 producer_id: String,
286 issuer_key_hash: Vec<u8>,
287 epoch: u64,
288 ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
289 let msg = GossipMessage::UrgentRevocation {
290 producer_id,
291 issuer_key_hash,
292 epoch,
293 origin_node: self.identity.name.clone(),
294 };
295
296 let data = self.frame_broadcast(serde_json::to_vec(&msg)?);
297 let mut foca = self.foca.lock().await;
298 foca.add_broadcast(&data)?;
299
300 info!(msg = %msg, "broadcasting urgent revocation");
301 Ok(())
302 }
303
304 pub fn config(&self) -> &GossipConfig {
305 &self.config
306 }
307
308 pub fn identity(&self) -> &NodeId {
310 &self.identity
311 }
312
313 pub async fn members(&self) -> Vec<MemberInfo> {
319 let foca = self.foca.lock().await;
320 let mut out: Vec<MemberInfo> = foca
321 .iter_membership_state()
322 .map(|m| {
323 let id = m.id();
324 MemberInfo {
325 name: id.name.clone(),
326 addr: id.addr,
327 incarnation: id.incarnation,
328 state: m.state().into(),
329 is_self: false,
330 }
331 })
332 .collect();
333 drop(foca);
334
335 out.push(MemberInfo {
336 name: self.identity.name.clone(),
337 addr: self.identity.addr,
338 incarnation: self.identity.incarnation,
339 state: MemberState::Alive,
340 is_self: true,
341 });
342 out
343 }
344
345 pub async fn record_generation(&self, msg: &GossipMessage) {
353 let GossipMessage::GenerationAnnouncement {
354 producer_id,
355 issuer_key_hash,
356 epoch,
357 manifest_digest,
358 origin_node,
359 ..
360 } = msg
361 else {
362 return;
363 };
364
365 if !msg.valid_bounds() {
366 return;
367 }
368 let ikh_hex = hex::encode(issuer_key_hash);
369 let key: GenKey = (origin_node.clone(), producer_id.clone(), ikh_hex.clone());
370 let now = now_unix();
371
372 let mut table = self.generations.write().await;
373 table.retain(|_, row| now.saturating_sub(row.last_seen_unix) < 3600);
374 if !table.contains_key(&key) && table.len() >= 4096 {
375 return;
376 }
377 let entry = table.entry(key).or_insert_with(|| GenRecord {
378 origin_node: origin_node.clone(),
379 producer_id: producer_id.clone(),
380 issuer_key_hash: ikh_hex,
381 epoch: *epoch,
382 manifest_digest: hex::encode(manifest_digest),
383 last_seen_unix: now,
384 });
385 if *epoch >= entry.epoch {
386 entry.epoch = *epoch;
387 entry.manifest_digest = hex::encode(manifest_digest);
388 }
389 entry.last_seen_unix = now;
390 }
391
392 pub async fn generations(&self) -> Vec<GenRecord> {
394 let mut table = self.generations.write().await;
395 let now = now_unix();
396 table.retain(|_, row| now.saturating_sub(row.last_seen_unix) < 3600);
397 table.values().cloned().collect()
398 }
399}
400
401async fn receive_loop(
403 foca: Arc<Mutex<HoikeFoca>>,
404 socket: Arc<UdpSocket>,
405 timer_queue: TimerQueue,
406) {
407 let mut buf = vec![0u8; 2048];
408 loop {
409 match socket.recv_from(&mut buf).await {
410 Ok((len, from)) => {
411 debug!(from = %from, len, "gossip packet received");
412 let mut foca_guard = foca.lock().await;
413 let mut runtime = AccumulatingRuntime::new();
414 if let Err(e) = foca_guard.handle_data(&buf[..len], &mut runtime) {
415 debug!(from = %from, error = %e, "foca handle_data error (expected for arbitrary UDP)");
416 }
417 drop(foca_guard);
418 drain_runtime(&mut runtime, &socket, &timer_queue).await;
419 }
420 Err(e) => {
421 warn!(error = %e, "UDP recv error");
422 tokio::time::sleep(Duration::from_millis(100)).await;
423 }
424 }
425 }
426}
427
428async fn timer_loop(
430 foca: Arc<Mutex<HoikeFoca>>,
431 socket: Arc<UdpSocket>,
432 new_timers_rx: TimerQueue,
433) {
434 let mut pending_timers: Vec<(tokio::time::Instant, Timer<NodeId>)> = Vec::new();
435
436 let tick = Duration::from_millis(200);
437 let mut interval = tokio::time::interval(tick);
438
439 loop {
440 interval.tick().await;
441
442 {
444 let mut incoming = new_timers_rx.lock().await;
445 for (duration, timer) in incoming.drain(..) {
446 pending_timers.push((tokio::time::Instant::now() + duration, timer));
447 }
448 }
449
450 let now = tokio::time::Instant::now();
451
452 let mut due = Vec::new();
453 pending_timers.retain(|(deadline, timer)| {
454 if *deadline <= now {
455 due.push(timer.clone());
456 false
457 } else {
458 true
459 }
460 });
461
462 if due.is_empty() {
463 continue;
464 }
465
466 let mut foca_guard = foca.lock().await;
467 let mut runtime = AccumulatingRuntime::new();
468
469 for timer in due {
470 if let Err(e) = foca_guard.handle_timer(timer, &mut runtime) {
471 debug!(error = %e, "foca timer error");
472 }
473 }
474
475 while let Some(notification) = runtime.to_notify() {
476 handle_notification(¬ification);
477 }
478
479 while let Some((duration, timer)) = runtime.to_schedule() {
480 pending_timers.push((tokio::time::Instant::now() + duration, timer));
481 }
482
483 drop(foca_guard);
484
485 while let Some((to, data)) = runtime.to_send() {
487 if let Err(e) = socket.send_to(&data, to.addr).await {
488 debug!(to = %to.addr, error = %e, "failed to send gossip packet");
489 }
490 }
491 }
492}
493
494fn handle_notification(notification: &foca::OwnedNotification<NodeId>) {
495 match notification {
496 foca::OwnedNotification::MemberUp(id) => {
497 info!(name = %id.name, addr = %id.addr, "member joined");
498 }
499 foca::OwnedNotification::MemberDown(id) => {
500 info!(name = %id.name, addr = %id.addr, "member left");
501 }
502 foca::OwnedNotification::Rename(before, after) => {
503 info!(
504 before_name = %before.name, before_addr = %before.addr,
505 after_name = %after.name, after_addr = %after.addr,
506 "member renamed (rejoin)"
507 );
508 }
509 foca::OwnedNotification::Active => {
510 info!("gossip node is active (known by cluster)");
511 }
512 foca::OwnedNotification::Idle => {
513 info!("gossip node is idle (no known peers)");
514 }
515 foca::OwnedNotification::Defunct => {
516 warn!("gossip node declared defunct — needs manual intervention");
517 }
518 foca::OwnedNotification::Rejoin(id) => {
519 info!(name = %id.name, incarnation = id.incarnation, "auto-rejoined cluster");
520 }
521 }
522}
523
524async fn drain_runtime(
526 runtime: &mut AccumulatingRuntime<NodeId>,
527 socket: &UdpSocket,
528 timer_queue: &TimerQueue,
529) {
530 while let Some(notification) = runtime.to_notify() {
531 handle_notification(¬ification);
532 }
533
534 while let Some((to, data)) = runtime.to_send() {
535 let addr = to.addr;
536 if let Err(e) = socket.send_to(&data, addr).await {
537 debug!(to = %addr, error = %e, "failed to send gossip packet");
538 }
539 }
540
541 let mut timers = timer_queue.lock().await;
543 while let Some((duration, timer)) = runtime.to_schedule() {
544 timers.push((duration, timer));
545 }
546}
547
548#[cfg(test)]
549mod tests {
550 use super::*;
551
552 #[tokio::test]
553 async fn generation_storage_is_bounded_and_expires() {
554 let node = test_node("edge").await;
555 for n in 0..4100 {
556 node.record_generation(&GossipMessage::GenerationAnnouncement {
557 producer_id: format!("producer-{n}"),
558 issuer_key_hash: vec![1; 32],
559 epoch: 1,
560 manifest_digest: [0; 32],
561 bundle_url: None,
562 origin_node: "peer".into(),
563 })
564 .await;
565 }
566 assert_eq!(node.generations().await.len(), 4096);
567 for row in node.generations.write().await.values_mut() {
568 row.last_seen_unix = 0;
569 }
570 assert!(node.generations().await.is_empty());
571 }
572
573 #[test]
574 fn node_id_identity_trait() {
575 let id = NodeId {
576 addr: "127.0.0.1:7946".parse().unwrap(),
577 name: "test-node".into(),
578 incarnation: 0,
579 };
580
581 use foca::Identity;
583 assert_eq!(id.addr(), "127.0.0.1:7946".parse::<SocketAddr>().unwrap());
584
585 let renewed = id.renew().unwrap();
587 assert_eq!(renewed.incarnation, 1);
588 assert_eq!(renewed.addr, id.addr);
589 assert_eq!(renewed.name, id.name);
590
591 assert!(renewed.win_addr_conflict(&id));
593 assert!(!id.win_addr_conflict(&renewed));
594 }
595
596 #[test]
597 fn node_id_serde_round_trip() {
598 let id = NodeId {
599 addr: "192.168.1.1:7946".parse().unwrap(),
600 name: "edge-node-01".into(),
601 incarnation: 5,
602 };
603
604 let json = serde_json::to_string(&id).unwrap();
605 let decoded: NodeId = serde_json::from_str(&json).unwrap();
606 assert_eq!(id, decoded);
607 }
608
609 async fn test_node(name: &str) -> GossipNode {
613 let (tx, _rx) = tokio::sync::mpsc::channel(16);
614 let config = GossipConfig {
615 enabled: true,
616 bind: "127.0.0.1:0".into(),
617 seeds: vec![],
618 node_name: name.into(),
619 auth_mode: crate::config::AuthMode::Permissive,
620 identity_key: None,
621 peer_keys: vec![],
622 peer_identities: Default::default(),
623 };
624 GossipNode::start(config, tx).await.expect("node starts")
625 }
626
627 #[tokio::test]
630 async fn members_always_includes_self() {
631 let node = test_node("solo").await;
632 let members = node.members().await;
633 assert_eq!(members.len(), 1, "no peers, only self");
634 assert!(members[0].is_self);
635 assert_eq!(members[0].name, "solo");
636 assert_eq!(members[0].state, MemberState::Alive);
637 }
638
639 #[tokio::test]
640 async fn record_generation_tracks_latest_epoch_per_scope() {
641 let node = test_node("signer").await;
642 let ikh = vec![0xAB; 32];
643
644 let announce = |epoch: u64| GossipMessage::GenerationAnnouncement {
645 producer_id: "prod-1".into(),
646 issuer_key_hash: ikh.clone(),
647 epoch,
648 manifest_digest: [epoch as u8; 32],
649 bundle_url: None,
650 origin_node: "peer-a".into(),
651 };
652
653 node.record_generation(&announce(5)).await;
654 node.record_generation(&announce(7)).await;
655 node.record_generation(&announce(6)).await;
657
658 let gens = node.generations().await;
659 assert_eq!(gens.len(), 1, "one (node, scope) row");
660 assert_eq!(gens[0].epoch, 7);
661 assert_eq!(gens[0].origin_node, "peer-a");
662 assert_eq!(gens[0].producer_id, "prod-1");
663 assert_eq!(gens[0].issuer_key_hash, hex::encode(&ikh));
664 }
665
666 #[tokio::test]
669 async fn record_generation_separates_scopes_and_nodes() {
670 let node = test_node("edge").await;
671 node.record_generation(&GossipMessage::GenerationAnnouncement {
672 producer_id: "prod-1".into(),
673 issuer_key_hash: vec![0x01; 32],
674 epoch: 3,
675 manifest_digest: [0; 32],
676 bundle_url: None,
677 origin_node: "node-a".into(),
678 })
679 .await;
680 node.record_generation(&GossipMessage::GenerationAnnouncement {
681 producer_id: "prod-1".into(),
682 issuer_key_hash: vec![0x01; 32],
683 epoch: 3,
684 manifest_digest: [0; 32],
685 bundle_url: None,
686 origin_node: "node-b".into(),
687 })
688 .await;
689 assert_eq!(node.generations().await.len(), 2, "two distinct nodes");
690 }
691
692 async fn wait_for_member(node: &GossipNode, name: &str, limit: Duration) {
697 let deadline = tokio::time::Instant::now() + limit;
698 loop {
699 if node.members().await.iter().any(|m| m.name == name) {
700 return;
701 }
702 assert!(
703 tokio::time::Instant::now() < deadline,
704 "peer '{name}' never became visible in the fleet view"
705 );
706 tokio::time::sleep(Duration::from_millis(100)).await;
707 }
708 }
709
710 async fn recv_scope(
713 rx: &mut tokio::sync::mpsc::Receiver<GossipMessage>,
714 issuer_key_hash: &[u8],
715 limit: Duration,
716 ) -> GossipMessage {
717 let deadline = tokio::time::Instant::now() + limit;
718 loop {
719 let msg = tokio::time::timeout_at(deadline, rx.recv())
720 .await
721 .expect("announcement delivered within deadline")
722 .expect("gossip channel stays open");
723 if msg.scope_key().1 == issuer_key_hash {
724 return msg;
725 }
726 }
727 }
728
729 fn identity_files(
730 dir: &std::path::Path,
731 name: &str,
732 seed: u8,
733 ) -> (std::path::PathBuf, std::path::PathBuf) {
734 let (_, priv_path, pub_path) = crate::crypto::write_test_identity(dir, name, seed);
735 (priv_path, pub_path)
736 }
737
738 #[tokio::test]
744 async fn loopback_transition_permissive_signing_to_required() {
745 let dir = tempfile::tempdir().unwrap();
746 let (alpha_priv, alpha_pub) = identity_files(dir.path(), "alpha", 21);
747 let (bravo_priv, bravo_pub) = identity_files(dir.path(), "bravo", 22);
748
749 let node_config = |name: &str,
750 mode: crate::config::AuthMode,
751 identity: Option<std::path::PathBuf>,
752 peers: Vec<(&str, std::path::PathBuf)>,
753 seeds: Vec<String>| {
754 let mut peer_identities = std::collections::BTreeMap::new();
755 for (peer, path) in peers {
756 peer_identities.insert(peer.to_string(), path);
757 }
758 GossipConfig {
759 enabled: true,
760 bind: "127.0.0.1:0".into(),
761 seeds,
762 node_name: name.into(),
763 auth_mode: mode,
764 identity_key: identity,
765 peer_keys: vec![],
766 peer_identities,
767 }
768 };
769 let start = |config: GossipConfig| async move {
770 let (tx, rx) = tokio::sync::mpsc::channel(16);
771 let node = GossipNode::start(config, tx)
772 .await
773 .expect("gossip node starts");
774 (node, rx)
775 };
776
777 let (bravo, mut bravo_rx) = start(node_config(
780 "bravo",
781 crate::config::AuthMode::Permissive,
782 None,
783 vec![("alpha", alpha_pub.clone())],
784 vec![],
785 ))
786 .await;
787 let (alpha, mut alpha_rx) = start(node_config(
788 "alpha",
789 crate::config::AuthMode::Permissive,
790 Some(alpha_priv.clone()),
791 vec![("alpha", alpha_pub.clone())],
792 vec![bravo.identity().addr.to_string()],
793 ))
794 .await;
795
796 wait_for_member(&bravo, "alpha", Duration::from_secs(15)).await;
798
799 alpha
801 .announce_generation("producer".into(), vec![0x01; 32], 7, [7; 32], None)
802 .await
803 .unwrap();
804 let signed = recv_scope(&mut bravo_rx, &[0x01; 32], Duration::from_secs(10)).await;
805 assert_eq!(signed.epoch(), 7);
806
807 bravo
809 .announce_generation("producer".into(), vec![0x02; 32], 3, [3; 32], None)
810 .await
811 .unwrap();
812 let unsigned = recv_scope(&mut alpha_rx, &[0x02; 32], Duration::from_secs(10)).await;
813 assert_eq!(unsigned.epoch(), 3);
814
815 let (bravo_required, mut bravo_required_rx) = start(node_config(
820 "bravo",
821 crate::config::AuthMode::Required,
822 Some(bravo_priv.clone()),
823 vec![("alpha", alpha_pub.clone()), ("bravo", bravo_pub.clone())],
824 vec![
825 alpha.identity().addr.to_string(),
826 bravo.identity().addr.to_string(),
827 ],
828 ))
829 .await;
830 wait_for_member(&bravo_required, "alpha", Duration::from_secs(15)).await;
831 wait_for_member(&bravo_required, "bravo", Duration::from_secs(15)).await;
832
833 alpha
835 .announce_generation("producer".into(), vec![0x03; 32], 9, [9; 32], None)
836 .await
837 .unwrap();
838 let signed = recv_scope(&mut bravo_required_rx, &[0x03; 32], Duration::from_secs(10)).await;
839 assert_eq!(signed.epoch(), 9);
840
841 bravo
845 .announce_generation("producer".into(), vec![0x04; 32], 4, [4; 32], None)
846 .await
847 .unwrap();
848 let deadline = tokio::time::Instant::now() + Duration::from_secs(4);
849 let mut leaked = None;
850 while tokio::time::Instant::now() < deadline {
851 match tokio::time::timeout_at(deadline, bravo_required_rx.recv()).await {
852 Ok(Some(msg)) if msg.scope_key().1 == [0x04; 32] => {
853 leaked = Some(msg);
854 break;
855 }
856 Ok(Some(_)) => continue,
858 Ok(None) => panic!("required receiver's channel closed"),
859 Err(_) => break, }
861 }
862 assert!(
863 leaked.is_none(),
864 "unsigned broadcast must be rejected in required mode: {leaked:?}"
865 );
866 }
867}