//! Dropdown presets + user-saved values for the Configure-pools dialog (round 15 //! #1). Each pool field (address / account / worker / password) has a "+" menu //! offering built-in presets (pool stratums, worker placeholders) plus values the //! user has saved. "Add new..." opens a manager window that edits the whole saved //! list at once (round 18 #8b). Saved lists persist one-per-line under the config dir. use std::path::PathBuf; const CONFIG_DIR: &str = ".config/alkane-toolkit"; /// Which pool field a "+" menu belongs to. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PoolField { Address, Account, Worker, Password, } impl PoolField { fn saved_file(self) -> &'static str { match self { PoolField::Address => "pool-addresses.txt", PoolField::Account => "pool-accounts.txt", PoolField::Worker => "pool-workers.txt", PoolField::Password => "pool-passwords.txt", } } /// Built-in presets offered before the user's saved values. pub fn presets(self) -> Vec<&'static str> { match self { // Top Bitcoin pools by hashrate with their primary stratum endpoints // (researched round 15; verify in-app before relying on any one). PoolField::Address => POOL_STRATUMS.iter().map(|(_, u)| *u).collect(), PoolField::Account => Vec::new(), // Per-miner worker-name placeholders (see MinerRow::expand_worker_template). PoolField::Worker => vec![ "{ip1}", "{ip2}", "{ip3}", "{ip4}", "{serial}", "{mac}", "{nameplate-hr}", "{brand}", "{model}", "{submodel}", "{cpu}", "{cb}", "{firmware}", "{hostname}", ], PoolField::Password => vec!["x"], } } } /// (pool name, primary stratum URL). Used for the address dropdown labels. pub const POOL_STRATUMS: &[(&str, &str)] = &[ ("Foundry USA", "stratum+tcp://btc.foundryusapool.com:3333"), ("AntPool", "stratum+tcp://ss.antpool.com:3333"), ("F2Pool", "stratum+tcp://btc.f2pool.com:1314"), ("ViaBTC", "stratum+tcp://btc.viabtc.io:3333"), ("SpiderPool", "stratum+tcp://btc-us.spiderpool.com:2309"), ("Binance Pool", "stratum+tcp://bs.poolbinance.com:3333"), ("Luxor", "stratum+tcp://btc.global.luxor.tech:700"), ("SBI Crypto", "stratum+tcp://us1.sbicrypto.com:3333"), ("Braiins Pool", "stratum+tcp://stratum.braiins.com:3333"), ("ULTIMUSPOOL", "stratum+tcp://bs.ultimuspool.com:8888"), ("SECPOOL", "stratum+tcp://btc.secpool.com:3333"), ]; fn config_path(file: &str) -> PathBuf { let home = std::env::var("HOME").unwrap_or_else(|_| ".".into()); PathBuf::from(home).join(CONFIG_DIR).join(file) } /// The user's saved values for `field`, in save order (most recent last). pub fn load_saved(field: PoolField) -> Vec { std::fs::read_to_string(config_path(field.saved_file())) .ok() .map(|s| s.lines().map(str::trim).filter(|l| !l.is_empty()).map(String::from).collect()) .unwrap_or_default() } /// Replace `field`'s entire saved list with `values` (round 18 #8b: the preset /// manager edits the whole list at once). Each value is trimmed; empties, exact /// duplicates, and any value that is already a built-in preset are dropped. /// Returns the number of values actually written. pub fn save_all(field: PoolField, values: &[String]) -> std::io::Result { let out = dedupe_saved(&field.presets(), values); let p = config_path(field.saved_file()); if let Some(dir) = p.parent() { let _ = std::fs::create_dir_all(dir); } // The password list can hold a pool password, so write it owner-only from the // moment it is created -- never briefly world-readable (round 18 #12). write_private(&p, out.join("\n").as_bytes())?; Ok(out.len()) } /// Write `data` to `path` with owner-only (0600) permissions from creation on /// Unix, so a secret is never momentarily world-readable between write and chmod. /// `mode()` only takes effect when the file is created, so an already-existing /// file is also re-tightened; elsewhere this is a plain write. fn write_private(path: &std::path::Path, data: &[u8]) -> std::io::Result<()> { #[cfg(unix)] { use std::io::Write; use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; let mut f = std::fs::OpenOptions::new() .write(true) .create(true) .truncate(true) .mode(0o600) .open(path)?; let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)); f.write_all(data) } #[cfg(not(unix))] { std::fs::write(path, data) } } /// Trim every value, then drop empties, values equal to a built-in preset, and /// later exact duplicates (first occurrence wins). Order is otherwise preserved. fn dedupe_saved(presets: &[&str], values: &[String]) -> Vec { let mut out: Vec = Vec::new(); for v in values { let v = v.trim(); if v.is_empty() || presets.contains(&v) || out.iter().any(|s| s == v) { continue; } out.push(v.to_string()); } out } /// The full dropdown list for a field: presets first, then the user's saved /// values. For the address field each entry is labelled with the pool name. pub fn dropdown_entries(field: PoolField) -> Vec<(String, String)> { // (label, value) let mut out: Vec<(String, String)> = Vec::new(); if field == PoolField::Address { for (name, url) in POOL_STRATUMS { out.push((format!("{name} -- {url}"), url.to_string())); } } else { for p in field.presets() { out.push((p.to_string(), p.to_string())); } } for s in load_saved(field) { out.push((s.clone(), s)); } out } #[cfg(test)] mod tests { use super::*; #[test] fn dedupe_saved_trims_drops_empties_presets_and_dupes() { let presets = ["x", "{ip1}"]; let vals: Vec = [" ", "myworker", "myworker", "x", " keep ", "{ip1}", "keep"] .iter() .map(|s| s.to_string()) .collect(); // " " (empty), the second "myworker", "x"/"{ip1}" (presets) and the second // "keep" all drop; " keep " is trimmed and kept. assert_eq!(dedupe_saved(&presets, &vals), vec!["myworker".to_string(), "keep".to_string()]); } #[test] fn dedupe_saved_empty_input_is_empty() { assert!(dedupe_saved(&[], &[]).is_empty()); } }