Guest User

Untitled

a guest
Oct 13th, 2023
523
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 3.14 KB | Source Code | 0 0
  1. #[derive(NetworkBehaviour)]
  2. pub struct MyBehaviour {
  3.     pub gossipsub: gossipsub::Behaviour,
  4.     pub kademlia: Kademlia<MemoryStore>,
  5. }
  6.  
  7. #[derive(Debug, Deserialize)]
  8. struct BootstrapNodes {
  9.     nodes: Vec<String>,
  10. }
  11.  
  12. static NONCE: AtomicUsize = AtomicUsize::new(0);
  13.  
  14. impl MyBehaviour {
  15.     pub fn new(local_peer_id: PeerId, id_keys: identity::Keypair) -> Result<Self, Box<dyn Error>> {
  16.         let store = MemoryStore::new(local_peer_id.clone());
  17.         let mut kademlia_config = KademliaConfig::default();
  18.         let protocol = StreamProtocol::new("/xxx/0.1.0");
  19.         kademlia_config.set_protocol_names(vec![protocol]);
  20.         let mut kademlia = Kademlia::with_config(local_peer_id.clone(), store, kademlia_config);
  21.  
  22.         #[cfg(debug_assertions)]
  23.         let bootstrap_nodes_file = "../bootstrap_nodes.yaml";
  24.         #[cfg(not(debug_assertions))]
  25.         let bootstrap_nodes_file = "./bootstrap_nodes.yaml";
  26.         if let Ok(bootstrap_addresses) = read_bootstrap_nodes(bootstrap_nodes_file) {
  27.             for addr in bootstrap_addresses {
  28.                 let multiaddr: Multiaddr = addr.parse()?;
  29.                 let peer_id = multiaddr
  30.                     .iter()
  31.                     .find_map(|x| match x {
  32.                         libp2p::multiaddr::Protocol::P2p(peer_id) => Some(peer_id),
  33.                         _ => None,
  34.                     })
  35.                     .unwrap();
  36.                 debug!("👥 Kademlia bootstraped by peer: {peer_id} with address: {multiaddr}");
  37.                 kademlia.add_address(&peer_id, multiaddr);
  38.             }
  39.         } else if let Err(e) = read_bootstrap_nodes(bootstrap_nodes_file) {
  40.             log::error!("‼️ Couldn't read bootstrap nodes from file: {bootstrap_nodes_file}: {e}.");
  41.         }
  42.  
  43.         let message_id_fn = |message: &gossipsub::Message| {
  44.             let mut s = DefaultHasher::new();
  45.             message.data.hash(&mut s);
  46.             let nonce = NONCE.fetch_add(1, Ordering::SeqCst);
  47.             let combined = format!("{}{}", s.finish(), nonce);
  48.             gossipsub::MessageId::from(combined)
  49.         };
  50.         let gossipsub_config = gossipsub::ConfigBuilder::default()
  51.             .heartbeat_interval(Duration::from_secs(10))
  52.             .validation_mode(gossipsub::ValidationMode::Strict)
  53.             .message_id_fn(message_id_fn)
  54.             .build()
  55.             .expect("Valid config");
  56.  
  57.  
  58.         let mut gossipsub = gossipsub::Behaviour::new(
  59.             gossipsub::MessageAuthenticity::Signed(id_keys.clone()),
  60.             gossipsub_config,
  61.         )
  62.         .expect("Correct configuration");
  63.  
  64.         gossipsub.subscribe(&gossipsub::IdentTopic::new("test-net"))?;
  65.         gossipsub.subscribe(&gossipsub::IdentTopic::new("node-announce"))?;
  66.  
  67.         Ok(Self {
  68.             gossipsub,
  69.             kademlia,
  70.         })
  71.     }
  72. }
  73.  
  74. fn read_bootstrap_nodes(file_path: &str) -> Result<Vec<String>, Box<dyn std::error::Error>> {
  75.     let mut file = File::open(file_path)?;
  76.     let mut contents = String::new();
  77.     file.read_to_string(&mut contents)?;
  78.     let bootstrap_nodes: BootstrapNodes = serde_yaml::from_str(&contents)?;
  79.     Ok(bootstrap_nodes.nodes)
  80. }
Advertisement
Add Comment
Please, Sign In to add comment