Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #[derive(NetworkBehaviour)]
- pub struct MyBehaviour {
- pub gossipsub: gossipsub::Behaviour,
- pub kademlia: Kademlia<MemoryStore>,
- }
- #[derive(Debug, Deserialize)]
- struct BootstrapNodes {
- nodes: Vec<String>,
- }
- static NONCE: AtomicUsize = AtomicUsize::new(0);
- impl MyBehaviour {
- pub fn new(local_peer_id: PeerId, id_keys: identity::Keypair) -> Result<Self, Box<dyn Error>> {
- let store = MemoryStore::new(local_peer_id.clone());
- let mut kademlia_config = KademliaConfig::default();
- let protocol = StreamProtocol::new("/xxx/0.1.0");
- kademlia_config.set_protocol_names(vec![protocol]);
- let mut kademlia = Kademlia::with_config(local_peer_id.clone(), store, kademlia_config);
- #[cfg(debug_assertions)]
- let bootstrap_nodes_file = "../bootstrap_nodes.yaml";
- #[cfg(not(debug_assertions))]
- let bootstrap_nodes_file = "./bootstrap_nodes.yaml";
- if let Ok(bootstrap_addresses) = read_bootstrap_nodes(bootstrap_nodes_file) {
- for addr in bootstrap_addresses {
- let multiaddr: Multiaddr = addr.parse()?;
- let peer_id = multiaddr
- .iter()
- .find_map(|x| match x {
- libp2p::multiaddr::Protocol::P2p(peer_id) => Some(peer_id),
- _ => None,
- })
- .unwrap();
- debug!("👥 Kademlia bootstraped by peer: {peer_id} with address: {multiaddr}");
- kademlia.add_address(&peer_id, multiaddr);
- }
- } else if let Err(e) = read_bootstrap_nodes(bootstrap_nodes_file) {
- log::error!("‼️ Couldn't read bootstrap nodes from file: {bootstrap_nodes_file}: {e}.");
- }
- let message_id_fn = |message: &gossipsub::Message| {
- let mut s = DefaultHasher::new();
- message.data.hash(&mut s);
- let nonce = NONCE.fetch_add(1, Ordering::SeqCst);
- let combined = format!("{}{}", s.finish(), nonce);
- gossipsub::MessageId::from(combined)
- };
- let gossipsub_config = gossipsub::ConfigBuilder::default()
- .heartbeat_interval(Duration::from_secs(10))
- .validation_mode(gossipsub::ValidationMode::Strict)
- .message_id_fn(message_id_fn)
- .build()
- .expect("Valid config");
- let mut gossipsub = gossipsub::Behaviour::new(
- gossipsub::MessageAuthenticity::Signed(id_keys.clone()),
- gossipsub_config,
- )
- .expect("Correct configuration");
- gossipsub.subscribe(&gossipsub::IdentTopic::new("test-net"))?;
- gossipsub.subscribe(&gossipsub::IdentTopic::new("node-announce"))?;
- Ok(Self {
- gossipsub,
- kademlia,
- })
- }
- }
- fn read_bootstrap_nodes(file_path: &str) -> Result<Vec<String>, Box<dyn std::error::Error>> {
- let mut file = File::open(file_path)?;
- let mut contents = String::new();
- file.read_to_string(&mut contents)?;
- let bootstrap_nodes: BootstrapNodes = serde_yaml::from_str(&contents)?;
- Ok(bootstrap_nodes.nodes)
- }
Advertisement
Add Comment
Please, Sign In to add comment