Skip to main content

hashtree_cli/
p2p_common.rs

1use std::path::PathBuf;
2use std::sync::Arc;
3
4use crate::socialgraph;
5use crate::webrtc::{PeerClassifier, PeerPool, WebRTCConfig};
6
7/// Build default WebRTC config with explicit relay set.
8pub fn default_webrtc_config(relays: &[String]) -> WebRTCConfig {
9    WebRTCConfig {
10        relays: relays.to_vec(),
11        ..Default::default()
12    }
13}
14
15/// Build peer classifier used by daemon/runtime startup paths.
16pub fn build_peer_classifier(
17    data_dir: PathBuf,
18    store: Arc<dyn socialgraph::SocialGraphBackend>,
19) -> PeerClassifier {
20    let contacts_file = data_dir.join("contacts.json");
21    Arc::new(move |pubkey_hex: &str| {
22        if contacts_file.exists() {
23            if let Ok(data) = std::fs::read_to_string(&contacts_file) {
24                if let Ok(contacts) = serde_json::from_str::<Vec<String>>(&data) {
25                    if contacts.contains(&pubkey_hex.to_string()) {
26                        return PeerPool::Follows;
27                    }
28                }
29            }
30        }
31        if let Ok(pk_bytes) = hex::decode(pubkey_hex) {
32            if pk_bytes.len() == 32 {
33                let pk: [u8; 32] = pk_bytes.try_into().unwrap();
34                if let Some(dist) = socialgraph::get_follow_distance(store.as_ref(), &pk) {
35                    if dist <= 2 {
36                        return PeerPool::Follows;
37                    }
38                }
39            }
40        }
41        PeerPool::Other
42    })
43}