secret_rotation/
secret_rotation.rs1use anyhow::Result;
2use iroh::{Endpoint, SecretKey};
3use iroh_gossip::{api::Event, net::Gossip};
4use sha2::Digest;
5
6use distributed_topic_tracker::{
8 AutoDiscoveryGossip, RecordPublisher, RotationHandle, SecretRotation, TopicId
9};
10
11
12struct MySecretRotation;
13impl SecretRotation for MySecretRotation {
14 fn derive(
15 &self,
16 topic_hash: [u8; 32],
17 unix_minute: u64,
18 initial_secret_hash: [u8; 32],
19 ) -> [u8; 32] {
20 let mut hash = sha2::Sha512::new();
21 hash.update(topic_hash);
22 hash.update(unix_minute.to_be_bytes());
23 hash.update(initial_secret_hash);
24 hash.update(b"as long as you return 32 bytes this is a valid secret rotation function");
25 hash.finalize()[..32].try_into().expect("hashing failed")
26 }
27}
28
29#[tokio::main]
30async fn main() -> Result<()> {
31 let secret_key = SecretKey::generate(rand::rngs::OsRng);
33
34 let endpoint = Endpoint::builder()
36 .secret_key(secret_key.clone())
37 .discovery_n0()
38 .bind()
39 .await?;
40
41 let gossip = Gossip::builder()
43 .spawn(endpoint.clone());
44
45 let _router = iroh::protocol::Router::builder(endpoint.clone())
47 .accept(iroh_gossip::ALPN, gossip.clone())
48 .spawn();
49
50 let topic_id = TopicId::new("my-iroh-gossip-topic".to_string());
51 let initial_secret = b"my-initial-secret".to_vec();
52
53 let record_publisher = RecordPublisher::new(
56 topic_id.clone(),
57 endpoint.node_id().public(),
58 secret_key.secret().clone(),
59 Some(RotationHandle::new(MySecretRotation)),
60 initial_secret,
61 );
62 let (gossip_sender, gossip_receiver) = gossip
63 .subscribe_and_join_with_auto_discovery(record_publisher)
64 .await?
65 .split().await?;
66
67 println!("Joined topic");
68
69 tokio::spawn(async move {
71 while let Some(Ok(event)) = gossip_receiver.next().await {
72 if let Event::Received(msg) = event {
73 println!(
74 "\nMessage from {}: {}",
75 &msg.delivered_from.to_string()[0..8],
76 String::from_utf8(msg.content.to_vec()).unwrap()
77 );
78 } else if let Event::NeighborUp(peer) = event {
79 println!("\nJoined by {}", &peer.to_string()[0..8]);
80 }
81 }
82 });
83
84 let mut buffer = String::new();
86 let stdin = std::io::stdin();
87 loop {
88 print!("\n> ");
89 stdin.read_line(&mut buffer).unwrap();
90 gossip_sender.broadcast(buffer.clone().replace("\n", "").into())
91 .await
92 .unwrap();
93 println!(" - (sent)");
94 buffer.clear();
95 }
96}