Skip to main content

hashtree_config/
lib.rs

1//! Shared configuration for hashtree tools
2//!
3//! Reads from ~/.hashtree/config.toml
4
5use anyhow::{Context, Result};
6use serde::{Deserialize, Serialize};
7use std::fs;
8use std::path::PathBuf;
9
10/// Default read-only file servers
11pub const DEFAULT_READ_SERVERS: &[&str] = &["https://cdn.iris.to", "https://blossom.primal.net"];
12
13/// Default write-enabled file servers
14pub const DEFAULT_WRITE_SERVERS: &[&str] = &["https://upload.iris.to"];
15
16/// Default nostr relays
17pub const DEFAULT_RELAYS: &[&str] = &[
18    "wss://temp.iris.to",
19    "wss://nos.lol",
20    "wss://relay.snort.social",
21];
22
23/// Default social graph entrypoint followed when a new identity is initialized.
24pub const DEFAULT_SOCIALGRAPH_ENTRYPOINT_NPUB: &str =
25    "npub1xdhnr9mrv47kkrn95k6cwecearydeh8e895990n3acntwvmgk2dsdeeycm";
26
27/// Default read-only alias for the social graph entrypoint.
28pub const DEFAULT_SOCIALGRAPH_ENTRYPOINT_ALIAS: &str = "siriusbusiness";
29
30/// Top-level config structure
31#[derive(Debug, Clone, Default, Serialize, Deserialize)]
32pub struct Config {
33    #[serde(default)]
34    pub server: ServerConfig,
35    #[serde(default)]
36    pub storage: StorageConfig,
37    #[serde(default)]
38    pub nostr: NostrConfig,
39    #[serde(default)]
40    pub blossom: BlossomConfig,
41    #[serde(default)]
42    pub sync: SyncConfig,
43    #[serde(default)]
44    pub cashu: CashuConfig,
45    #[serde(default)]
46    pub updater: UpdaterConfig,
47}
48
49/// Cashu wallet configuration shared by CLI and `htree-cashu`.
50#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
51pub struct CashuConfig {
52    /// Cashu mint base URLs available to explicit wallet operations.
53    #[serde(default)]
54    pub accepted_mints: Vec<String>,
55    /// Default mint to use for wallet operations.
56    #[serde(default)]
57    pub default_mint: Option<String>,
58}
59
60/// Server configuration
61#[derive(Debug, Clone, Serialize, Deserialize)]
62pub struct ServerConfig {
63    #[serde(default = "default_bind_address")]
64    pub bind_address: String,
65    #[serde(default = "default_true")]
66    pub enable_auth: bool,
67    #[serde(default)]
68    pub public_writes: bool,
69}
70
71impl Default for ServerConfig {
72    fn default() -> Self {
73        Self {
74            bind_address: default_bind_address(),
75            enable_auth: true,
76            public_writes: false,
77        }
78    }
79}
80
81fn default_bind_address() -> String {
82    "127.0.0.1:8080".to_string()
83}
84
85fn default_true() -> bool {
86    true
87}
88
89/// Storage backend type
90#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
91#[serde(rename_all = "lowercase")]
92pub enum StorageBackend {
93    /// LMDB storage - requires lmdb feature
94    #[default]
95    Lmdb,
96    /// Filesystem storage - stores in ~/.hashtree/blobs/{prefix}/{subdir}/{hash}
97    Fs,
98}
99
100/// Storage configuration
101#[derive(Debug, Clone, Serialize, Deserialize)]
102pub struct StorageConfig {
103    /// Storage backend: "lmdb" (default) or "fs"
104    #[serde(default)]
105    pub backend: StorageBackend,
106    #[serde(default = "default_data_dir")]
107    pub data_dir: String,
108    #[serde(default = "default_max_size_gb")]
109    pub max_size_gb: u64,
110    #[serde(default = "default_storage_evict_orphans")]
111    pub evict_orphans: bool,
112    #[serde(default)]
113    pub s3: Option<S3Config>,
114}
115
116impl Default for StorageConfig {
117    fn default() -> Self {
118        Self {
119            backend: StorageBackend::default(),
120            data_dir: default_data_dir(),
121            max_size_gb: default_max_size_gb(),
122            evict_orphans: default_storage_evict_orphans(),
123            s3: None,
124        }
125    }
126}
127
128fn default_data_dir() -> String {
129    get_hashtree_dir()
130        .join("data")
131        .to_string_lossy()
132        .to_string()
133}
134
135fn default_max_size_gb() -> u64 {
136    10
137}
138
139fn default_storage_evict_orphans() -> bool {
140    true
141}
142
143/// S3-compatible storage configuration
144#[derive(Debug, Clone, Serialize, Deserialize)]
145pub struct S3Config {
146    pub endpoint: String,
147    pub bucket: String,
148    pub region: String,
149    #[serde(default)]
150    pub prefix: Option<String>,
151}
152
153/// Nostr relay configuration
154#[derive(Debug, Clone, Serialize, Deserialize)]
155pub struct NostrConfig {
156    #[serde(default = "default_relays")]
157    pub relays: Vec<String>,
158    #[serde(default)]
159    pub allowed_npubs: Vec<String>,
160    #[serde(default)]
161    pub socialgraph_root: Option<String>,
162    #[serde(default = "default_nostr_bootstrap_follows")]
163    pub bootstrap_follows: Vec<String>,
164    #[serde(default = "default_social_graph_crawl_depth", alias = "crawl_depth")]
165    pub social_graph_crawl_depth: u32,
166    /// Max follow distance to mirror into public event/profile indexes.
167    /// Defaults to social_graph_crawl_depth when unset.
168    #[serde(default)]
169    pub mirror_max_follow_distance: Option<u32>,
170    #[serde(default = "default_max_write_distance")]
171    pub max_write_distance: u32,
172    /// Max size for the trusted social graph store in GB (default: 10)
173    #[serde(default = "default_nostr_db_max_size_gb")]
174    pub db_max_size_gb: u64,
175    /// Max size for the social graph spambox store in GB (default: 1)
176    /// Set to 0 for memory-only spambox (no on-disk DB)
177    #[serde(default = "default_nostr_spambox_max_size_gb")]
178    pub spambox_max_size_gb: u64,
179    /// Require relays to support NIP-77 negentropy for mirror history sync.
180    #[serde(default)]
181    pub negentropy_only: bool,
182    /// Threshold for treating a user as overmuted in mirrored profile indexing/search.
183    #[serde(default = "default_nostr_overmute_threshold")]
184    pub overmute_threshold: f64,
185    /// Kinds mirrored from upstream relays for the trusted hashtree index.
186    #[serde(default = "default_nostr_mirror_kinds")]
187    pub mirror_kinds: Vec<u16>,
188    /// Authors per ordinary history chunk and between durable mirror-root publications.
189    #[serde(default = "default_nostr_history_sync_author_chunk_size")]
190    pub history_sync_author_chunk_size: usize,
191    /// Run a catch-up history sync after relay reconnects.
192    #[serde(default = "default_nostr_history_sync_on_reconnect")]
193    pub history_sync_on_reconnect: bool,
194}
195
196impl Default for NostrConfig {
197    fn default() -> Self {
198        Self {
199            relays: default_relays(),
200            allowed_npubs: vec![],
201            socialgraph_root: None,
202            bootstrap_follows: default_nostr_bootstrap_follows(),
203            social_graph_crawl_depth: default_social_graph_crawl_depth(),
204            mirror_max_follow_distance: None,
205            max_write_distance: default_max_write_distance(),
206            db_max_size_gb: default_nostr_db_max_size_gb(),
207            spambox_max_size_gb: default_nostr_spambox_max_size_gb(),
208            negentropy_only: false,
209            overmute_threshold: default_nostr_overmute_threshold(),
210            mirror_kinds: default_nostr_mirror_kinds(),
211            history_sync_author_chunk_size: default_nostr_history_sync_author_chunk_size(),
212            history_sync_on_reconnect: default_nostr_history_sync_on_reconnect(),
213        }
214    }
215}
216
217fn default_social_graph_crawl_depth() -> u32 {
218    2
219}
220
221fn default_nostr_bootstrap_follows() -> Vec<String> {
222    vec![DEFAULT_SOCIALGRAPH_ENTRYPOINT_NPUB.to_string()]
223}
224
225fn default_nostr_overmute_threshold() -> f64 {
226    1.0
227}
228
229fn default_max_write_distance() -> u32 {
230    3
231}
232
233fn default_nostr_db_max_size_gb() -> u64 {
234    10
235}
236
237fn default_nostr_spambox_max_size_gb() -> u64 {
238    1
239}
240
241fn default_nostr_history_sync_on_reconnect() -> bool {
242    true
243}
244
245fn default_nostr_mirror_kinds() -> Vec<u16> {
246    vec![
247        0, 1, 3, 5, 6, 7, 16, 20, 1_111, 9_735, 10_000, 30_000, 30_023,
248    ]
249}
250
251fn default_nostr_history_sync_author_chunk_size() -> usize {
252    5_000
253}
254
255fn default_relays() -> Vec<String> {
256    DEFAULT_RELAYS.iter().map(|s| s.to_string()).collect()
257}
258
259/// File server (blossom) configuration
260#[derive(Debug, Clone, Serialize, Deserialize)]
261pub struct BlossomConfig {
262    /// Legacy servers field (both read and write)
263    #[serde(default)]
264    pub servers: Vec<String>,
265    /// Read-only file servers
266    #[serde(default = "default_read_servers")]
267    pub read_servers: Vec<String>,
268    /// Write-enabled file servers
269    #[serde(default = "default_write_servers")]
270    pub write_servers: Vec<String>,
271    /// Max upload size in MB
272    #[serde(default = "default_max_upload_mb")]
273    pub max_upload_mb: u64,
274    /// Require public Blossom and peer-fetched cached blobs to look encrypted.
275    #[serde(default = "default_require_random_untrusted_ingest")]
276    pub require_random_untrusted_ingest: bool,
277    /// Max number of concurrent blob uploads during push/repair.
278    #[serde(default = "default_upload_concurrency")]
279    pub upload_concurrency: usize,
280    /// Force upload all blobs, skipping "server already has" check
281    #[serde(default)]
282    pub force_upload: bool,
283}
284
285impl Default for BlossomConfig {
286    fn default() -> Self {
287        Self {
288            servers: vec![],
289            read_servers: default_read_servers(),
290            write_servers: default_write_servers(),
291            max_upload_mb: default_max_upload_mb(),
292            require_random_untrusted_ingest: default_require_random_untrusted_ingest(),
293            upload_concurrency: default_upload_concurrency(),
294            force_upload: false,
295        }
296    }
297}
298
299fn dedup_preserve_order(servers: Vec<String>) -> Vec<String> {
300    let mut seen = std::collections::HashSet::with_capacity(servers.len());
301    let mut out = Vec::with_capacity(servers.len());
302    for server in servers {
303        if seen.insert(server.clone()) {
304            out.push(server);
305        }
306    }
307    out
308}
309
310fn default_read_servers() -> Vec<String> {
311    DEFAULT_READ_SERVERS.iter().map(|s| s.to_string()).collect()
312}
313
314fn default_write_servers() -> Vec<String> {
315    DEFAULT_WRITE_SERVERS
316        .iter()
317        .map(|s| s.to_string())
318        .collect()
319}
320
321fn default_max_upload_mb() -> u64 {
322    100
323}
324
325fn default_require_random_untrusted_ingest() -> bool {
326    true
327}
328
329fn default_upload_concurrency() -> usize {
330    4
331}
332
333impl BlossomConfig {
334    /// Get all readable servers (read_servers + legacy servers + write_servers),
335    /// preserving configured priority order while deduplicating.
336    /// Dedicated read tiers come before write servers so CDN caches are tried
337    /// before direct origin fallbacks.
338    pub fn all_read_servers(&self) -> Vec<String> {
339        let mut servers = self.read_servers.clone();
340        servers.extend(self.servers.clone());
341        servers.extend(self.write_servers.clone());
342        if servers.is_empty() {
343            servers = default_read_servers();
344            servers.extend(default_write_servers());
345        }
346        dedup_preserve_order(servers)
347    }
348
349    /// Get all write servers (legacy + write_servers), preserving priority order.
350    pub fn all_write_servers(&self) -> Vec<String> {
351        let mut servers = self.servers.clone();
352        servers.extend(self.write_servers.clone());
353        if servers.is_empty() {
354            servers = default_write_servers();
355        }
356        dedup_preserve_order(servers)
357    }
358}
359
360/// Background sync configuration
361#[derive(Debug, Clone, Serialize, Deserialize)]
362pub struct SyncConfig {
363    #[serde(default)]
364    pub enabled: bool,
365    #[serde(default = "default_true")]
366    pub sync_own: bool,
367    #[serde(default)]
368    pub sync_followed: bool,
369    #[serde(default = "default_max_concurrent")]
370    pub max_concurrent: usize,
371    #[serde(default = "default_blossom_timeout_ms")]
372    pub blossom_timeout_ms: u64,
373}
374
375impl Default for SyncConfig {
376    fn default() -> Self {
377        Self {
378            enabled: false,
379            sync_own: true,
380            sync_followed: false,
381            max_concurrent: default_max_concurrent(),
382            blossom_timeout_ms: default_blossom_timeout_ms(),
383        }
384    }
385}
386
387/// htree self-update preferences. Reads `[updater]` from
388/// `~/.hashtree/config.toml`. Auto-check is on by default — `htree` will
389/// quietly check for a newer published binary at most once per
390/// `check_interval_hours` and print a one-liner to stderr when one exists.
391/// Auto-install is off by default; flip it on to install the new binary
392/// in the background and print the result.
393#[derive(Debug, Clone, Serialize, Deserialize)]
394pub struct UpdaterConfig {
395    #[serde(default = "default_true")]
396    pub auto_check: bool,
397    #[serde(default)]
398    pub auto_install: bool,
399    #[serde(default = "default_check_interval_hours")]
400    pub check_interval_hours: u32,
401}
402
403impl Default for UpdaterConfig {
404    fn default() -> Self {
405        Self {
406            auto_check: true,
407            auto_install: false,
408            check_interval_hours: default_check_interval_hours(),
409        }
410    }
411}
412
413fn default_check_interval_hours() -> u32 {
414    24
415}
416
417fn default_max_concurrent() -> usize {
418    4
419}
420
421fn default_blossom_timeout_ms() -> u64 {
422    10000
423}
424
425impl Config {
426    /// Load config from file, or create default if doesn't exist
427    pub fn load() -> Result<Self> {
428        let config_path = get_config_path();
429
430        if config_path.exists() {
431            let content = fs::read_to_string(&config_path).context("Failed to read config file")?;
432            toml::from_str(&content).context("Failed to parse config file")
433        } else {
434            let config = Config::default();
435            config.save()?;
436            Ok(config)
437        }
438    }
439
440    /// Load config, returning default on any error (no panic)
441    pub fn load_or_default() -> Self {
442        Self::load().unwrap_or_default()
443    }
444
445    /// Save config to file
446    pub fn save(&self) -> Result<()> {
447        let config_path = get_config_path();
448
449        if let Some(parent) = config_path.parent() {
450            fs::create_dir_all(parent)?;
451        }
452
453        let content = toml::to_string_pretty(self)?;
454        fs::write(&config_path, content)?;
455
456        Ok(())
457    }
458}
459
460/// Load only the `[cashu]` section from `~/.hashtree/config.toml` without rewriting
461/// unrelated sections when the file already exists.
462pub fn load_cashu_config() -> Result<CashuConfig> {
463    load_cashu_config_from(&get_config_path())
464}
465
466/// Persist only the `[cashu]` section into `~/.hashtree/config.toml`, preserving any
467/// other sections and CLI-specific keys present in the file.
468pub fn save_cashu_config(cashu: &CashuConfig) -> Result<()> {
469    save_cashu_config_to(&get_config_path(), cashu)
470}
471
472fn load_cashu_config_from(config_path: &std::path::Path) -> Result<CashuConfig> {
473    if !config_path.exists() {
474        return Ok(CashuConfig::default());
475    }
476    let content = fs::read_to_string(config_path).context("Failed to read config file")?;
477    let table: toml::Table = toml::from_str(&content).context("Failed to parse config file")?;
478    match table.get("cashu") {
479        Some(value) => value
480            .clone()
481            .try_into()
482            .context("Failed to parse [cashu] config section"),
483        None => Ok(CashuConfig::default()),
484    }
485}
486
487fn save_cashu_config_to(config_path: &std::path::Path, cashu: &CashuConfig) -> Result<()> {
488    if let Some(parent) = config_path.parent() {
489        fs::create_dir_all(parent)?;
490    }
491
492    let mut table: toml::Table = if config_path.exists() {
493        let content = fs::read_to_string(config_path).context("Failed to read config file")?;
494        toml::from_str(&content).context("Failed to parse config file")?
495    } else {
496        toml::Value::try_from(Config::default())?
497            .try_into()
498            .context("Failed to build default config table")?
499    };
500
501    table.insert("cashu".to_string(), toml::Value::try_from(cashu)?);
502    let content = toml::to_string_pretty(&table)?;
503    fs::write(config_path, content)?;
504    Ok(())
505}
506
507/// Get the hashtree directory (~/.hashtree)
508pub fn get_hashtree_dir() -> PathBuf {
509    if let Ok(dir) = std::env::var("HTREE_CONFIG_DIR") {
510        return PathBuf::from(dir);
511    }
512    dirs::home_dir()
513        .unwrap_or_else(|| PathBuf::from("."))
514        .join(".hashtree")
515}
516
517/// Get the config file path (~/.hashtree/config.toml)
518pub fn get_config_path() -> PathBuf {
519    get_hashtree_dir().join("config.toml")
520}
521
522/// Get the keys file path (~/.hashtree/keys)
523pub fn get_keys_path() -> PathBuf {
524    get_hashtree_dir().join("keys")
525}
526
527/// Get the public alias file path (~/.hashtree/aliases)
528pub fn get_aliases_path() -> PathBuf {
529    get_hashtree_dir().join("aliases")
530}
531
532/// A stored key entry from the keys file
533#[derive(Debug, Clone)]
534pub struct KeyEntry {
535    /// The raw identity token (for example nsec, npub, or hex)
536    pub secret: String,
537    /// Optional alias/petname
538    pub alias: Option<String>,
539}
540
541/// Parse the keys file content into key entries
542/// Format: `<identity> [alias]` per line
543/// Lines starting with # are comments
544pub fn parse_keys_file(content: &str) -> Vec<KeyEntry> {
545    let mut entries = Vec::new();
546    for line in content.lines() {
547        let line = line.trim();
548        if line.is_empty() || line.starts_with('#') {
549            continue;
550        }
551        let parts: Vec<&str> = line.splitn(2, ' ').collect();
552        let secret = parts[0].to_string();
553        let alias = parts.get(1).map(|s| s.trim().to_string());
554        entries.push(KeyEntry { secret, alias });
555    }
556    entries
557}
558
559/// Read and parse keys file, returning the first key's secret
560/// Returns None if file doesn't exist or is empty
561pub fn read_first_key() -> Option<String> {
562    let keys_path = get_keys_path();
563    let content = std::fs::read_to_string(&keys_path).ok()?;
564    let entries = parse_keys_file(&content);
565    entries.into_iter().next().map(|e| e.secret)
566}
567
568/// Get the auth cookie path (~/.hashtree/auth.cookie)
569pub fn get_auth_cookie_path() -> PathBuf {
570    get_hashtree_dir().join("auth.cookie")
571}
572
573/// Get the data directory from config (defaults to ~/.hashtree/data)
574/// Can be overridden with HTREE_DATA_DIR environment variable
575pub fn get_data_dir() -> PathBuf {
576    if let Ok(dir) = std::env::var("HTREE_DATA_DIR") {
577        return PathBuf::from(dir);
578    }
579    let config = Config::load_or_default();
580    PathBuf::from(&config.storage.data_dir)
581}
582
583/// Detect a local hashtree daemon on localhost and return its Blossom base URL.
584pub fn detect_local_daemon_url(bind_address: Option<&str>) -> Option<String> {
585    use std::net::{SocketAddr, TcpStream};
586    use std::time::Duration;
587
588    if !prefer_local_daemon() {
589        return None;
590    }
591
592    let port = local_daemon_port(bind_address);
593    if port == 0 {
594        return None;
595    }
596
597    let addr = SocketAddr::from(([127, 0, 0, 1], port));
598    let timeout = Duration::from_millis(100);
599    TcpStream::connect_timeout(&addr, timeout).ok()?;
600    Some(format!("http://127.0.0.1:{}", port))
601}
602
603/// Detect local Nostr relay URLs (e.g., hashtree daemon or local relay on common ports).
604pub fn detect_local_relay_urls(bind_address: Option<&str>) -> Vec<String> {
605    let mut relays = Vec::new();
606
607    if let Some(list) =
608        parse_env_list("NOSTR_LOCAL_RELAY").or_else(|| parse_env_list("HTREE_LOCAL_RELAY"))
609    {
610        for raw in list {
611            if let Some(url) = normalize_relay_url(&raw) {
612                relays.push(url);
613            }
614        }
615    }
616
617    if let Some(base) = detect_local_daemon_url(bind_address) {
618        if let Some(ws) = normalize_relay_url(&base) {
619            let ws = ws.trim_end_matches('/');
620            let ws = if ws.contains("/ws") {
621                ws.to_string()
622            } else {
623                format!("{}/ws", ws)
624            };
625            relays.push(ws);
626        }
627    }
628
629    let mut ports = parse_env_ports("NOSTR_LOCAL_RELAY_PORTS");
630    if ports.is_empty() {
631        ports.push(4869);
632    }
633
634    let daemon_port = local_daemon_port(bind_address);
635    for port in ports {
636        if port == 0 || port == daemon_port {
637            continue;
638        }
639        if local_port_open(port) {
640            relays.push(format!("ws://127.0.0.1:{port}"));
641        }
642    }
643
644    dedupe_relays(relays)
645}
646
647/// Resolve relays using environment overrides and optional local relay discovery.
648pub fn resolve_relays(config_relays: &[String], bind_address: Option<&str>) -> Vec<String> {
649    let mut base = match parse_env_list("NOSTR_RELAYS") {
650        Some(list) => list,
651        None => config_relays.to_vec(),
652    };
653
654    base = base
655        .into_iter()
656        .filter_map(|r| normalize_relay_url(&r))
657        .collect();
658
659    if !prefer_local_relay() {
660        return dedupe_relays(base);
661    }
662
663    let mut combined = detect_local_relay_urls(bind_address);
664    combined.extend(base);
665    dedupe_relays(combined)
666}
667
668fn local_daemon_port(bind_address: Option<&str>) -> u16 {
669    let default_port = 8080;
670    let Some(addr) = bind_address else {
671        return default_port;
672    };
673    if let Ok(sock) = addr.parse::<std::net::SocketAddr>() {
674        return sock.port();
675    }
676    if let Some((_, port_str)) = addr.rsplit_once(':') {
677        if let Ok(port) = port_str.parse::<u16>() {
678            return port;
679        }
680    }
681    default_port
682}
683
684fn prefer_local_relay() -> bool {
685    for key in ["NOSTR_PREFER_LOCAL", "HTREE_PREFER_LOCAL_RELAY"] {
686        if let Ok(val) = std::env::var(key) {
687            let val = val.trim().to_lowercase();
688            return !matches!(val.as_str(), "0" | "false" | "no" | "off");
689        }
690    }
691    true
692}
693
694fn prefer_local_daemon() -> bool {
695    for key in [
696        "HTREE_LOCAL_DAEMON_ONLY",
697        "HTREE_PREFER_LOCAL_DAEMON",
698        "NOSTR_PREFER_LOCAL",
699        "HTREE_PREFER_LOCAL_RELAY",
700    ] {
701        if let Ok(val) = std::env::var(key) {
702            let val = val.trim().to_lowercase();
703            return !matches!(val.as_str(), "0" | "false" | "no" | "off");
704        }
705    }
706    false
707}
708
709fn parse_env_list(var: &str) -> Option<Vec<String>> {
710    let value = std::env::var(var).ok()?;
711    let mut items = Vec::new();
712    for part in value.split([',', ';', '\n', '\t', ' ']) {
713        let trimmed = part.trim();
714        if !trimmed.is_empty() {
715            items.push(trimmed.to_string());
716        }
717    }
718    if items.is_empty() {
719        None
720    } else {
721        Some(items)
722    }
723}
724
725fn parse_env_ports(var: &str) -> Vec<u16> {
726    let Some(list) = parse_env_list(var) else {
727        return Vec::new();
728    };
729    list.into_iter()
730        .filter_map(|item| item.parse::<u16>().ok())
731        .collect()
732}
733
734fn normalize_relay_url(raw: &str) -> Option<String> {
735    let trimmed = raw.trim();
736    if trimmed.is_empty() {
737        return None;
738    }
739    let trimmed = trimmed.trim_end_matches('/');
740    let lower = trimmed.to_lowercase();
741    if lower.starts_with("ws://") || lower.starts_with("wss://") {
742        return Some(trimmed.to_string());
743    }
744    if lower.starts_with("http://") {
745        return Some(format!("ws://{}", &trimmed[7..]));
746    }
747    if lower.starts_with("https://") {
748        return Some(format!("wss://{}", &trimmed[8..]));
749    }
750    Some(format!("ws://{}", trimmed))
751}
752
753fn local_port_open(port: u16) -> bool {
754    use std::net::{SocketAddr, TcpStream};
755    use std::time::Duration;
756
757    let addr = SocketAddr::from(([127, 0, 0, 1], port));
758    let timeout = Duration::from_millis(100);
759    TcpStream::connect_timeout(&addr, timeout).is_ok()
760}
761
762fn dedupe_relays(relays: Vec<String>) -> Vec<String> {
763    use std::collections::HashSet;
764    let mut seen = HashSet::new();
765    let mut out = Vec::new();
766    for relay in relays {
767        let key = relay.trim_end_matches('/').to_lowercase();
768        if seen.insert(key) {
769            out.push(relay);
770        }
771    }
772    out
773}
774
775#[cfg(test)]
776mod tests {
777    use super::*;
778    use std::net::TcpListener;
779    use std::sync::Mutex;
780
781    static ENV_LOCK: Mutex<()> = Mutex::new(());
782
783    struct EnvGuard {
784        key: &'static str,
785        prev: Option<String>,
786    }
787
788    impl EnvGuard {
789        fn set(key: &'static str, value: &str) -> Self {
790            let prev = std::env::var(key).ok();
791            std::env::set_var(key, value);
792            Self { key, prev }
793        }
794
795        fn clear(key: &'static str) -> Self {
796            let prev = std::env::var(key).ok();
797            std::env::remove_var(key);
798            Self { key, prev }
799        }
800    }
801
802    impl Drop for EnvGuard {
803        fn drop(&mut self) {
804            if let Some(prev) = &self.prev {
805                std::env::set_var(self.key, prev);
806            } else {
807                std::env::remove_var(self.key);
808            }
809        }
810    }
811
812    #[test]
813    fn test_default_config() {
814        let config = Config::default();
815        assert!(!config.blossom.read_servers.is_empty());
816        assert!(!config.blossom.write_servers.is_empty());
817        assert_eq!(
818            config.blossom.upload_concurrency,
819            default_upload_concurrency()
820        );
821        assert!(!config.nostr.relays.is_empty());
822        assert!(config
823            .nostr
824            .relays
825            .contains(&"wss://temp.iris.to".to_string()));
826    }
827
828    #[test]
829    fn test_parse_empty_config() {
830        let config: Config = toml::from_str("").unwrap();
831        assert!(!config.blossom.read_servers.is_empty());
832    }
833
834    #[test]
835    fn test_parse_partial_config() {
836        let toml = r#"
837[blossom]
838write_servers = ["https://custom.server"]
839upload_concurrency = 24
840"#;
841        let config: Config = toml::from_str(toml).unwrap();
842        assert_eq!(config.blossom.write_servers, vec!["https://custom.server"]);
843        assert_eq!(config.blossom.upload_concurrency, 24);
844        assert!(!config.blossom.read_servers.is_empty());
845    }
846
847    #[test]
848    fn test_all_servers() {
849        let config = BlossomConfig {
850            servers: vec!["https://legacy.server".to_string()],
851            ..BlossomConfig::default()
852        };
853
854        let read = config.all_read_servers();
855        assert!(read.contains(&"https://legacy.server".to_string()));
856        assert!(read.contains(&"https://cdn.iris.to".to_string()));
857        assert!(read.contains(&"https://blossom.primal.net".to_string()));
858        assert!(read.contains(&"https://upload.iris.to".to_string()));
859
860        let write = config.all_write_servers();
861        assert!(write.contains(&"https://legacy.server".to_string()));
862        assert!(write.contains(&"https://upload.iris.to".to_string()));
863    }
864
865    #[test]
866    fn test_all_servers_fall_back_to_defaults_when_explicitly_empty() {
867        let config = BlossomConfig {
868            servers: vec![],
869            read_servers: vec![],
870            write_servers: vec![],
871            max_upload_mb: default_max_upload_mb(),
872            require_random_untrusted_ingest: default_require_random_untrusted_ingest(),
873            upload_concurrency: default_upload_concurrency(),
874            force_upload: false,
875        };
876
877        let mut expected_read = default_read_servers();
878        expected_read.extend(default_write_servers());
879        let expected_read = dedup_preserve_order(expected_read);
880        assert_eq!(config.all_read_servers(), expected_read);
881        assert_eq!(
882            config.all_read_servers().first().map(String::as_str),
883            Some("https://cdn.iris.to")
884        );
885        assert_eq!(config.all_write_servers(), default_write_servers());
886    }
887
888    #[test]
889    fn test_storage_backend_default() {
890        let config = Config::default();
891        assert_eq!(config.storage.backend, StorageBackend::Lmdb);
892    }
893
894    #[test]
895    fn test_storage_backend_lmdb() {
896        let toml = r#"
897[storage]
898backend = "lmdb"
899"#;
900        let config: Config = toml::from_str(toml).unwrap();
901        assert_eq!(config.storage.backend, StorageBackend::Lmdb);
902    }
903
904    #[test]
905    fn test_storage_backend_fs_explicit() {
906        let toml = r#"
907[storage]
908backend = "fs"
909"#;
910        let config: Config = toml::from_str(toml).unwrap();
911        assert_eq!(config.storage.backend, StorageBackend::Fs);
912    }
913
914    #[test]
915    fn test_storage_orphan_eviction_defaults_on_and_allows_override() {
916        assert!(Config::default().storage.evict_orphans);
917
918        let toml = r#"
919[storage]
920evict_orphans = false
921"#;
922        let config: Config = toml::from_str(toml).unwrap();
923        assert!(!config.storage.evict_orphans);
924    }
925
926    #[test]
927    fn test_parse_keys_file() {
928        let content = r#"
929nsec1abc123 self
930# comment line
931nsec1def456 work
932
933nsec1ghi789
934"#;
935        let entries = parse_keys_file(content);
936        assert_eq!(entries.len(), 3);
937        assert_eq!(entries[0].secret, "nsec1abc123");
938        assert_eq!(entries[0].alias, Some("self".to_string()));
939        assert_eq!(entries[1].secret, "nsec1def456");
940        assert_eq!(entries[1].alias, Some("work".to_string()));
941        assert_eq!(entries[2].secret, "nsec1ghi789");
942        assert_eq!(entries[2].alias, None);
943    }
944
945    #[test]
946    fn test_local_daemon_port_default() {
947        assert_eq!(local_daemon_port(None), 8080);
948    }
949
950    #[test]
951    fn test_local_daemon_port_parses_ipv4() {
952        assert_eq!(local_daemon_port(Some("127.0.0.1:9090")), 9090);
953    }
954
955    #[test]
956    fn test_local_daemon_port_parses_anyhost() {
957        assert_eq!(local_daemon_port(Some("0.0.0.0:7070")), 7070);
958    }
959
960    #[test]
961    fn test_local_daemon_port_parses_ipv6() {
962        assert_eq!(local_daemon_port(Some("[::1]:6060")), 6060);
963    }
964
965    #[test]
966    fn test_local_daemon_port_parses_hostname() {
967        assert_eq!(local_daemon_port(Some("localhost:5050")), 5050);
968    }
969
970    #[test]
971    fn test_local_daemon_port_invalid() {
972        assert_eq!(local_daemon_port(Some("localhost")), 8080);
973    }
974
975    #[test]
976    fn test_detect_local_daemon_url_respects_prefer_local_flag() {
977        let _lock = ENV_LOCK.lock().unwrap();
978        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
979        let port = listener.local_addr().unwrap().port();
980        let _prefer = EnvGuard::set("NOSTR_PREFER_LOCAL", "0");
981
982        assert_eq!(
983            detect_local_daemon_url(Some(&format!("127.0.0.1:{port}"))),
984            None
985        );
986    }
987
988    #[test]
989    fn test_detect_local_daemon_url_requires_opt_in() {
990        let _lock = ENV_LOCK.lock().unwrap();
991        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
992        let port = listener.local_addr().unwrap().port();
993        let _prefer = EnvGuard::clear("HTREE_PREFER_LOCAL_DAEMON");
994        let _prefer_nostr = EnvGuard::clear("NOSTR_PREFER_LOCAL");
995        let _prefer_relay = EnvGuard::clear("HTREE_PREFER_LOCAL_RELAY");
996
997        assert_eq!(
998            detect_local_daemon_url(Some(&format!("127.0.0.1:{port}"))),
999            None
1000        );
1001    }
1002
1003    #[test]
1004    fn test_detect_local_daemon_url_uses_opt_in_flag() {
1005        let _lock = ENV_LOCK.lock().unwrap();
1006        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1007        let port = listener.local_addr().unwrap().port();
1008        let _prefer = EnvGuard::set("HTREE_PREFER_LOCAL_DAEMON", "1");
1009
1010        assert_eq!(
1011            detect_local_daemon_url(Some(&format!("127.0.0.1:{port}"))),
1012            Some(format!("http://127.0.0.1:{port}"))
1013        );
1014    }
1015
1016    #[test]
1017    fn test_strict_local_daemon_detection_uses_configured_bind_port() {
1018        let _lock = ENV_LOCK.lock().unwrap();
1019        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1020        let port = listener.local_addr().unwrap().port();
1021        let _strict = EnvGuard::set("HTREE_LOCAL_DAEMON_ONLY", "1");
1022        let _prefer = EnvGuard::clear("HTREE_PREFER_LOCAL_DAEMON");
1023
1024        assert_eq!(
1025            detect_local_daemon_url(Some(&format!("127.0.0.1:{port}"))),
1026            Some(format!("http://127.0.0.1:{port}"))
1027        );
1028    }
1029
1030    #[test]
1031    fn test_resolve_relays_prefers_local() {
1032        let _lock = ENV_LOCK.lock().unwrap();
1033        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1034        let port = listener.local_addr().unwrap().port();
1035
1036        let _prefer = EnvGuard::set("NOSTR_PREFER_LOCAL", "1");
1037        let _ports = EnvGuard::set("NOSTR_LOCAL_RELAY_PORTS", &port.to_string());
1038        let _relays = EnvGuard::clear("NOSTR_RELAYS");
1039
1040        let base = vec!["wss://relay.example".to_string()];
1041        let resolved = resolve_relays(&base, Some("127.0.0.1:0"));
1042
1043        assert!(!resolved.is_empty());
1044        assert_eq!(resolved[0], format!("ws://127.0.0.1:{port}"));
1045        assert!(resolved.contains(&"wss://relay.example".to_string()));
1046    }
1047
1048    #[test]
1049    fn test_resolve_relays_env_override() {
1050        let _lock = ENV_LOCK.lock().unwrap();
1051        let _prefer = EnvGuard::set("NOSTR_PREFER_LOCAL", "0");
1052        let _relays = EnvGuard::set("NOSTR_RELAYS", "wss://relay.one,wss://relay.two");
1053
1054        let base = vec!["wss://relay.example".to_string()];
1055        let resolved = resolve_relays(&base, Some("127.0.0.1:0"));
1056
1057        assert_eq!(
1058            resolved,
1059            vec!["wss://relay.one".to_string(), "wss://relay.two".to_string()]
1060        );
1061    }
1062
1063    #[test]
1064    fn test_nostr_config_defaults_include_mirror_settings() {
1065        let config = NostrConfig::default();
1066
1067        assert_eq!(config.social_graph_crawl_depth, 2);
1068        assert_eq!(config.mirror_max_follow_distance, None);
1069        assert_eq!(config.max_write_distance, 3);
1070        assert!(config.socialgraph_root.is_none());
1071        assert_eq!(
1072            config.bootstrap_follows,
1073            vec![DEFAULT_SOCIALGRAPH_ENTRYPOINT_NPUB.to_string()]
1074        );
1075        assert!(!config.negentropy_only);
1076        assert_eq!(config.overmute_threshold, 1.0);
1077        assert_eq!(
1078            config.mirror_kinds,
1079            vec![0, 1, 3, 5, 6, 7, 16, 20, 1_111, 9_735, 10_000, 30_000, 30_023]
1080        );
1081        assert_eq!(config.history_sync_author_chunk_size, 5_000);
1082        assert!(config.history_sync_on_reconnect);
1083    }
1084
1085    #[test]
1086    fn test_nostr_config_deserializes_mirror_settings() {
1087        let config: NostrConfig = toml::from_str(
1088            r#"
1089relays = ["wss://relay.example"]
1090socialgraph_root = "npub1test"
1091bootstrap_follows = []
1092social_graph_crawl_depth = 6
1093mirror_max_follow_distance = 2
1094max_write_distance = 7
1095negentropy_only = true
1096overmute_threshold = 1.5
1097mirror_kinds = [0, 1, 3, 6, 7, 9735]
1098history_sync_author_chunk_size = 512
1099history_sync_on_reconnect = false
1100"#,
1101        )
1102        .expect("deserialize nostr config");
1103
1104        assert_eq!(config.relays, vec!["wss://relay.example".to_string()]);
1105        assert_eq!(config.socialgraph_root.as_deref(), Some("npub1test"));
1106        assert!(config.bootstrap_follows.is_empty());
1107        assert_eq!(config.social_graph_crawl_depth, 6);
1108        assert_eq!(config.mirror_max_follow_distance, Some(2));
1109        assert_eq!(config.max_write_distance, 7);
1110        assert!(config.negentropy_only);
1111        assert_eq!(config.overmute_threshold, 1.5);
1112        assert_eq!(config.mirror_kinds, vec![0, 1, 3, 6, 7, 9_735]);
1113        assert_eq!(config.history_sync_author_chunk_size, 512);
1114        assert!(!config.history_sync_on_reconnect);
1115    }
1116
1117    #[test]
1118    fn test_nostr_config_deserializes_legacy_crawl_depth_alias() {
1119        let config: NostrConfig = toml::from_str(
1120            r#"
1121relays = ["wss://relay.example"]
1122crawl_depth = 5
1123"#,
1124        )
1125        .expect("deserialize nostr config");
1126
1127        assert_eq!(config.social_graph_crawl_depth, 5);
1128    }
1129
1130    #[test]
1131    fn test_save_cashu_config_preserves_other_sections() {
1132        let dir =
1133            std::env::temp_dir().join(format!("hashtree-config-cashu-test-{}", std::process::id()));
1134        let _ = fs::remove_dir_all(&dir);
1135        fs::create_dir_all(&dir).expect("create temp dir");
1136        let path = dir.join("config.toml");
1137        fs::write(
1138            &path,
1139            "[server]\nenable_fips = false\n[paid_retrieval]\nmax_price_sat = 7\n",
1140        )
1141        .expect("write initial config");
1142
1143        let mut cashu = load_cashu_config_from(&path).expect("load default cashu");
1144        assert!(cashu.accepted_mints.is_empty());
1145        cashu
1146            .accepted_mints
1147            .push("https://mint.example".to_string());
1148        cashu.default_mint = Some("https://mint.example".to_string());
1149        save_cashu_config_to(&path, &cashu).expect("save cashu");
1150
1151        let reloaded = load_cashu_config_from(&path).expect("reload cashu");
1152        assert_eq!(reloaded, cashu);
1153
1154        let raw: toml::Table =
1155            toml::from_str(&fs::read_to_string(&path).expect("read config")).expect("parse toml");
1156        assert_eq!(
1157            raw["server"]["enable_fips"].as_bool(),
1158            Some(false),
1159            "CLI-specific server fields must be preserved"
1160        );
1161        assert_eq!(
1162            raw["paid_retrieval"]["max_price_sat"].as_integer(),
1163            Some(7),
1164            "CLI-specific paid_retrieval section must be preserved"
1165        );
1166        let _ = fs::remove_dir_all(&dir);
1167    }
1168}