main.rs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{
  19. collections::{HashMap, HashSet},
  20. process::exit,
  21. sync::Arc,
  22. time::UNIX_EPOCH,
  23. };
  24. use async_trait::async_trait;
  25. use semver::Version;
  26. use smol::{
  27. lock::{Mutex, MutexGuard},
  28. stream::StreamExt,
  29. Executor,
  30. };
  31. use structopt::StructOpt;
  32. use structopt_toml::StructOptToml;
  33. use tinyjson::JsonValue;
  34. use toml::Value;
  35. use tracing::{debug, error, info, warn};
  36. use url::Url;
  37. use darkfi::{
  38. async_daemonize, cli_desc,
  39. net::{
  40. self,
  41. acceptor::InboundListenerHealth,
  42. hosts::HostColor,
  43. settings::{BanPolicy, MagicBytes, NetworkProfile},
  44. P2p, P2pPtr,
  45. },
  46. rpc::{
  47. jsonrpc::*,
  48. server::{listen_and_serve, RequestHandler},
  49. settings::{RpcSettings, RpcSettingsOpt},
  50. },
  51. system::{sleep, StoppableTask, StoppableTaskPtr},
  52. util::path::get_config_path,
  53. Error, Result,
  54. };
  55. const CONFIG_FILE: &str = "lilith_config.toml";
  56. const CONFIG_FILE_CONTENTS: &str = include_str!("../lilith_config.toml");
  57. #[derive(Clone, Debug, serde::Deserialize, StructOpt, StructOptToml)]
  58. #[serde(default)]
  59. #[structopt(name = "lilith", about = cli_desc!())]
  60. struct Args {
  61. #[structopt(flatten)]
  62. /// JSON-RPC settings
  63. rpc: RpcSettingsOpt,
  64. #[structopt(short, long)]
  65. /// Configuration file to use
  66. config: Option<String>,
  67. #[structopt(short, long)]
  68. /// Set log file to ouput into
  69. log: Option<String>,
  70. #[structopt(short, parse(from_occurrences))]
  71. /// Increase verbosity (-vvv supported)
  72. verbose: u8,
  73. #[structopt(long, default_value = "120")]
  74. /// Interval after which to check whitelist peers
  75. whitelist_refinery_interval: u64,
  76. }
  77. /// Struct representing a spawned P2P network
  78. struct Spawn {
  79. /// String identifier,
  80. pub name: String,
  81. /// P2P pointer
  82. pub p2p: P2pPtr,
  83. }
  84. impl Spawn {
  85. async fn get_whitelist(&self) -> Vec<JsonValue> {
  86. self.p2p
  87. .hosts()
  88. .container
  89. .fetch_all(HostColor::White)
  90. .iter()
  91. .map(|(addr, _url)| JsonValue::String(addr.to_string()))
  92. .collect()
  93. }
  94. async fn get_greylist(&self) -> Vec<JsonValue> {
  95. self.p2p
  96. .hosts()
  97. .container
  98. .fetch_all(HostColor::Grey)
  99. .iter()
  100. .map(|(addr, _url)| JsonValue::String(addr.to_string()))
  101. .collect()
  102. }
  103. async fn get_goldlist(&self) -> Vec<JsonValue> {
  104. self.p2p
  105. .hosts()
  106. .container
  107. .fetch_all(HostColor::Gold)
  108. .iter()
  109. .map(|(addr, _url)| JsonValue::String(addr.to_string()))
  110. .collect()
  111. }
  112. async fn info(&self) -> JsonValue {
  113. let mut addr_vec = vec![];
  114. for addr in &self.p2p.settings().read().await.inbound_addrs {
  115. addr_vec.push(JsonValue::String(addr.as_ref().to_string()));
  116. }
  117. let listeners = self
  118. .p2p
  119. .session_inbound()
  120. .listener_health()
  121. .await
  122. .iter()
  123. .map(listener_health_info)
  124. .collect();
  125. JsonValue::Object(HashMap::from([
  126. ("name".to_string(), JsonValue::String(self.name.clone())),
  127. ("urls".to_string(), JsonValue::Array(addr_vec)),
  128. ("listeners".to_string(), JsonValue::Array(listeners)),
  129. ("whitelist".to_string(), JsonValue::Array(self.get_whitelist().await)),
  130. ("greylist".to_string(), JsonValue::Array(self.get_greylist().await)),
  131. ("goldlist".to_string(), JsonValue::Array(self.get_goldlist().await)),
  132. ]))
  133. }
  134. }
  135. fn listener_health_info(health: &InboundListenerHealth) -> JsonValue {
  136. JsonValue::Object(HashMap::from([
  137. ("url".to_string(), JsonValue::String(health.url.to_string())),
  138. ("running".to_string(), JsonValue::Boolean(health.running)),
  139. ("active".to_string(), JsonValue::Number(health.active as f64)),
  140. ("negotiating".to_string(), JsonValue::Number(health.negotiating as f64)),
  141. ("limit".to_string(), JsonValue::Number(health.limit as f64)),
  142. ("saturated".to_string(), JsonValue::Boolean(health.saturated())),
  143. ("accept_backoff".to_string(), JsonValue::Boolean(health.accept_backoff)),
  144. ]))
  145. }
  146. /// Defines the network-specific settings
  147. #[derive(Clone)]
  148. struct NetInfo {
  149. /// Accept addresses the network will use
  150. pub accept_addrs: Vec<Url>,
  151. /// Other seeds to connect to
  152. pub seeds: Vec<Url>,
  153. /// Manual peers to connect to
  154. pub peers: Vec<Url>,
  155. /// Supported network version
  156. pub version: Version,
  157. /// App Identifier for the app running on the network
  158. pub app_name: String,
  159. /// Enable localnet hosts
  160. pub localnet: bool,
  161. /// Path to P2P datastore
  162. pub datastore: String,
  163. /// Path to hostlist
  164. pub hostlist: String,
  165. /// Magic bytes used to distinguish the p2p network
  166. pub magic_bytes: MagicBytes,
  167. }
  168. /// Struct representing the daemon
  169. struct Lilith {
  170. /// Spawned networks
  171. pub networks: Vec<Spawn>,
  172. /// JSON-RPC connection tracker
  173. pub rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  174. }
  175. impl Lilith {
  176. /// Since `Lilith` does not make outbound connections, if a peer is
  177. /// upgraded to whitelist it will remain on the whitelist even if the
  178. /// give peer is no longer online.
  179. ///
  180. /// To protect `Lilith` from sharing potentially offline nodes,
  181. /// `whitelist_refinery` periodically ping nodes on the whitelist. If they
  182. /// are reachable, we update their last seen field. Otherwise, we downgrade
  183. /// them to the greylist.
  184. ///
  185. /// Note: if `Lilith` loses connectivity this method will delete peers from
  186. /// the whitelist, meaning `Lilith` will need to rebuild its hostlist when
  187. /// it comes back online.
  188. async fn whitelist_refinery(
  189. network_name: String,
  190. p2p: P2pPtr,
  191. refinery_interval: u64,
  192. ) -> Result<()> {
  193. debug!(target: "net::refinery::whitelist_refinery", "Starting whitelist refinery for \"{network_name}\"");
  194. let hosts = p2p.hosts();
  195. loop {
  196. sleep(refinery_interval).await;
  197. match hosts.container.fetch_last(HostColor::White) {
  198. Some(entry) => {
  199. let url = &entry.0;
  200. let last_seen = &entry.1;
  201. if !hosts.refinable(url) {
  202. debug!(target: "net::refinery::whitelist_refinery", "Addr={} not available!",
  203. url.clone());
  204. continue
  205. }
  206. if !p2p.session_refine().handshake_node(url.clone(), p2p.clone()).await {
  207. debug!(target: "net::refinery:::whitelist_refinery",
  208. "Host {url} is not responsive. Downgrading from whitelist");
  209. if let Err(e) = hosts.greylist_host(url, *last_seen).await {
  210. error!(target: "net::refinery::whitelist_refinery", "Could not send {url} to the greylist: {e}");
  211. }
  212. continue
  213. }
  214. debug!(target: "net::refinery::whitelist_refinery",
  215. "Peer {url} is responsive. Updating last_seen");
  216. // This node is active. Update the last seen field.
  217. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  218. if let Err(e) = hosts.whitelist_host(url, last_seen).await {
  219. error!(target: "net::refinery::whitelist_refinery", "Could not send {url} to the whitelist: {e}");
  220. }
  221. }
  222. None => {
  223. debug!(target: "net::refinery::whitelist_refinery",
  224. "Whitelist is empty! Cannot start refinery process");
  225. continue
  226. }
  227. }
  228. }
  229. }
  230. // RPCAPI:
  231. // Returns all spawned networks names with their node addresses.
  232. // --> {"jsonrpc": "2.0", "method": "spawns", "params": [], "id": 42}
  233. // <-- {"jsonrpc": "2.0", "result": {"spawns": spawns_info}, "id": 42}
  234. async fn spawns(&self, id: i64, _params: JsonValue) -> JsonResult {
  235. let mut spawns = vec![];
  236. for spawn in &self.networks {
  237. spawns.push(spawn.info().await);
  238. }
  239. let json =
  240. JsonValue::Object(HashMap::from([("spawns".to_string(), JsonValue::Array(spawns))]));
  241. JsonResponse::new(json, id).into()
  242. }
  243. }
  244. #[async_trait]
  245. impl RequestHandler<()> for Lilith {
  246. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  247. return match req.method.as_str() {
  248. "ping" => self.pong(req.id, req.params).await,
  249. "spawns" => self.spawns(req.id, req.params).await,
  250. _ => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  251. }
  252. }
  253. async fn connections_mut(&self) -> MutexGuard<'life0, HashSet<StoppableTaskPtr>> {
  254. self.rpc_connections.lock().await
  255. }
  256. }
  257. /// Parse a TOML string for any configured network and return a map containing
  258. /// said configurations.
  259. fn parse_configured_networks(data: &str) -> Result<HashMap<String, NetInfo>> {
  260. let mut ret = HashMap::new();
  261. if let Value::Table(map) = toml::from_str(data)? {
  262. if map.contains_key("network") && map["network"].is_table() {
  263. for net in map["network"].as_table().unwrap() {
  264. info!(target: "lilith", "Found configuration for network: {}", net.0);
  265. let table = net.1.as_table().unwrap();
  266. if !table.contains_key("accept_addrs") {
  267. warn!(target: "lilith", "Network accept addrs are mandatory, skipping network.");
  268. continue
  269. }
  270. if !table.contains_key("hostlist") {
  271. error!(target: "lilith", "Hostlist path is mandatory! Configure and try again.");
  272. exit(1)
  273. }
  274. let name = net.0.to_string();
  275. let accept_addrs: Vec<Url> = table["accept_addrs"]
  276. .as_array()
  277. .unwrap()
  278. .iter()
  279. .map(|x| Url::parse(x.as_str().unwrap()).unwrap())
  280. .collect();
  281. let mut seeds = vec![];
  282. if table.contains_key("seeds") {
  283. if let Some(s) = table["seeds"].as_array() {
  284. for seed in s {
  285. if let Some(u) = seed.as_str() {
  286. if let Ok(url) = Url::parse(u) {
  287. seeds.push(url);
  288. }
  289. }
  290. }
  291. }
  292. }
  293. let mut peers = vec![];
  294. if table.contains_key("peers") {
  295. if let Some(p) = table["peers"].as_array() {
  296. for peer in p {
  297. if let Some(u) = peer.as_str() {
  298. if let Ok(url) = Url::parse(u) {
  299. peers.push(url);
  300. }
  301. }
  302. }
  303. }
  304. }
  305. let localnet = if table.contains_key("localnet") {
  306. table["localnet"].as_bool().unwrap()
  307. } else {
  308. false
  309. };
  310. let version = if table.contains_key("version") {
  311. semver::Version::parse(table["version"].as_str().unwrap())?
  312. } else {
  313. semver::Version::parse(option_env!("CARGO_PKG_VERSION").unwrap_or("0.0.0"))?
  314. };
  315. let app_name = if table.contains_key("app_name") {
  316. table["app_name"].as_str().unwrap().to_string()
  317. } else {
  318. String::new()
  319. };
  320. let datastore: String = table["datastore"].as_str().unwrap().to_string();
  321. let hostlist: String = table["hostlist"].as_str().unwrap().to_string();
  322. let magic_bytes: [u8; 4] = table["magic_bytes"]
  323. .as_array()
  324. .unwrap()
  325. .iter()
  326. .map(|v| v.as_integer().unwrap() as u8)
  327. .collect::<Vec<u8>>()
  328. .try_into()
  329. .expect("Wrong magic bytes value");
  330. let net_info = NetInfo {
  331. accept_addrs,
  332. seeds,
  333. peers,
  334. version,
  335. app_name,
  336. localnet,
  337. datastore,
  338. hostlist,
  339. magic_bytes: MagicBytes(magic_bytes),
  340. };
  341. ret.insert(name, net_info);
  342. }
  343. }
  344. }
  345. Ok(ret)
  346. }
  347. async fn spawn_net(name: String, info: &NetInfo, ex: Arc<Executor<'static>>) -> Result<Spawn> {
  348. let mut listen_urls = vec![];
  349. // Configure listen addrs for this network
  350. for url in &info.accept_addrs {
  351. listen_urls.push(url.clone());
  352. }
  353. let (active_profiles, profiles) = supported_network_profiles();
  354. // P2P network settings
  355. let settings = net::Settings {
  356. magic_bytes: info.magic_bytes.clone(),
  357. inbound_addrs: listen_urls.clone(),
  358. seeds: info.seeds.clone(),
  359. peers: info.peers.clone(),
  360. outbound_connections: 0,
  361. inbound_connections: 512,
  362. app_version: info.version.clone(),
  363. app_name: info.app_name.clone(),
  364. localnet: info.localnet,
  365. p2p_datastore: Some(info.datastore.clone()),
  366. hostlist: Some(info.hostlist.clone()),
  367. active_profiles,
  368. ban_policy: BanPolicy::Relaxed,
  369. profiles,
  370. ..Default::default()
  371. };
  372. // Create P2P instance
  373. let p2p = P2p::new(settings, ex.clone()).await?;
  374. let addrs_str: Vec<&str> = listen_urls.iter().map(|x| x.as_str()).collect();
  375. info!(target: "lilith", "Starting seed network node for \"{name}\" on {addrs_str:?}");
  376. p2p.clone().start().await?;
  377. let spawn = Spawn { name, p2p };
  378. Ok(spawn)
  379. }
  380. fn supported_network_profiles() -> (Vec<String>, HashMap<String, NetworkProfile>) {
  381. let definitions = [
  382. ("tcp", NetworkProfile::default()),
  383. ("tcp+tls", NetworkProfile::default()),
  384. ("tor", NetworkProfile::tor_default()),
  385. ("tor+tls", NetworkProfile::tor_default()),
  386. ("i2p", NetworkProfile::tor_default()),
  387. ("i2p+tls", NetworkProfile::tor_default()),
  388. ];
  389. let active_profiles = definitions.iter().map(|(name, _)| (*name).to_string()).collect();
  390. let profiles =
  391. definitions.into_iter().map(|(name, profile)| (name.to_string(), profile)).collect();
  392. (active_profiles, profiles)
  393. }
  394. async_daemonize!(realmain);
  395. async fn realmain(args: Args, ex: Arc<Executor<'static>>) -> Result<()> {
  396. // Pick up network settings from the TOML config
  397. let cfg_path = get_config_path(args.config, CONFIG_FILE)?;
  398. let toml_contents = std::fs::read_to_string(cfg_path)?;
  399. let configured_nets = parse_configured_networks(&toml_contents)?;
  400. if configured_nets.is_empty() {
  401. error!(target: "lilith", "No networks are enabled in config");
  402. exit(1);
  403. }
  404. // Spawn configured networks
  405. let mut networks = vec![];
  406. for (name, info) in &configured_nets {
  407. match spawn_net(name.to_string(), info, ex.clone()).await {
  408. Ok(spawn) => networks.push(spawn),
  409. Err(e) => {
  410. error!(target: "lilith", "Failed to start P2P network seed for \"{name}\": {e}");
  411. exit(1);
  412. }
  413. }
  414. }
  415. // Set up main daemon and background refinery_tasks
  416. let lilith = Arc::new(Lilith { networks, rpc_connections: Mutex::new(HashSet::new()) });
  417. let mut refinery_tasks = HashMap::new();
  418. for network in &lilith.networks {
  419. let name = network.name.clone();
  420. let task = StoppableTask::new();
  421. task.clone().start(
  422. Lilith::whitelist_refinery(name.clone(), network.p2p.clone(), args.whitelist_refinery_interval),
  423. |res| async move {
  424. match res {
  425. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  426. Err(e) => error!(target: "lilith", "Failed starting refinery task for \"{name}\": {e}"),
  427. }
  428. },
  429. Error::DetachedTaskStopped,
  430. ex.clone(),
  431. );
  432. refinery_tasks.insert(network.name.clone(), task);
  433. }
  434. // JSON-RPC server
  435. let rpc_settings: RpcSettings = args.rpc.into();
  436. info!(target: "lilith", "Starting JSON-RPC server on {}", rpc_settings.listen);
  437. let lilith_ = lilith.clone();
  438. let rpc_task = StoppableTask::new();
  439. rpc_task.clone().start(
  440. listen_and_serve(rpc_settings, lilith.clone(), None, ex.clone()),
  441. |res| async move {
  442. match res {
  443. Ok(()) | Err(Error::RpcServerStopped) => lilith_.stop_connections().await,
  444. Err(e) => error!(target: "lilith", "Failed starting JSON-RPC server: {e}"),
  445. }
  446. },
  447. Error::RpcServerStopped,
  448. ex.clone(),
  449. );
  450. // Signal handling for graceful termination.
  451. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  452. signals_handler.wait_termination(signals_task).await?;
  453. info!(target: "lilith", "Caught termination signal, cleaning up and exiting...");
  454. info!(target: "lilith", "Stopping JSON-RPC server...");
  455. rpc_task.stop().await;
  456. // Cleanly stop p2p networks
  457. for spawn in &lilith.networks {
  458. info!(target: "lilith", "Stopping \"{}\" task", spawn.name);
  459. refinery_tasks.get(&spawn.name).unwrap().stop().await;
  460. info!(target: "lilith", "Stopping \"{}\" P2P", spawn.name);
  461. spawn.p2p.stop().await;
  462. }
  463. info!(target: "lilith", "Bye!");
  464. Ok(())
  465. }
  466. #[cfg(test)]
  467. mod tests {
  468. use darkfi::net::{acceptor::InboundListenerHealth, hosts::HostContainer};
  469. use tinyjson::JsonValue;
  470. use url::Url;
  471. use super::{listener_health_info, supported_network_profiles};
  472. #[test]
  473. fn test_listener_health_info_reports_saturation() {
  474. let health = InboundListenerHealth {
  475. url: Url::parse("tor+tls://example.onion:9000").unwrap(),
  476. running: true,
  477. active: 2,
  478. negotiating: 1,
  479. limit: 3,
  480. accept_backoff: false,
  481. };
  482. let info = listener_health_info(&health);
  483. assert_eq!(info["url"], JsonValue::String(health.url.to_string()));
  484. assert_eq!(info["running"], JsonValue::Boolean(true));
  485. assert_eq!(info["active"], JsonValue::Number(2.0));
  486. assert_eq!(info["negotiating"], JsonValue::Number(1.0));
  487. assert_eq!(info["limit"], JsonValue::Number(3.0));
  488. assert_eq!(info["saturated"], JsonValue::Boolean(true));
  489. assert_eq!(info["accept_backoff"], JsonValue::Boolean(false));
  490. }
  491. #[test]
  492. fn test_supported_network_profiles_are_consistent() {
  493. let (active_profiles, profiles) = supported_network_profiles();
  494. assert_eq!(active_profiles, ["tcp", "tcp+tls", "tor", "tor+tls", "i2p", "i2p+tls"]);
  495. assert_eq!(profiles.len(), active_profiles.len());
  496. assert!(active_profiles.iter().all(|profile| profiles.contains_key(profile)));
  497. assert!(!active_profiles.iter().any(|profile| profile.starts_with("nym")));
  498. let shareable = HostContainer::shareable_schemes(&active_profiles, &[], &None, &None);
  499. assert_eq!(shareable, active_profiles);
  500. }
  501. }