main.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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 log::{debug, error, info, warn};
  26. use semver::Version;
  27. use smol::{
  28. lock::{Mutex, MutexGuard},
  29. stream::StreamExt,
  30. Executor,
  31. };
  32. use structopt::StructOpt;
  33. use structopt_toml::StructOptToml;
  34. use tinyjson::JsonValue;
  35. use toml::Value;
  36. use url::Url;
  37. use darkfi::{
  38. async_daemonize, cli_desc,
  39. net::{self, hosts::HostColor, settings::BanPolicy, P2p, P2pPtr},
  40. rpc::{
  41. jsonrpc::*,
  42. server::{listen_and_serve, RequestHandler},
  43. settings::{RpcSettings, RpcSettingsOpt},
  44. },
  45. system::{sleep, StoppableTask, StoppableTaskPtr},
  46. util::path::get_config_path,
  47. Error, Result,
  48. };
  49. const CONFIG_FILE: &str = "lilith_config.toml";
  50. const CONFIG_FILE_CONTENTS: &str = include_str!("../lilith_config.toml");
  51. #[derive(Clone, Debug, serde::Deserialize, StructOpt, StructOptToml)]
  52. #[serde(default)]
  53. #[structopt(name = "lilith", about = cli_desc!())]
  54. struct Args {
  55. #[structopt(flatten)]
  56. /// JSON-RPC settings
  57. rpc: RpcSettingsOpt,
  58. #[structopt(short, long)]
  59. /// Configuration file to use
  60. config: Option<String>,
  61. #[structopt(short, long)]
  62. /// Set log file to ouput into
  63. log: Option<String>,
  64. #[structopt(short, parse(from_occurrences))]
  65. /// Increase verbosity (-vvv supported)
  66. verbose: u8,
  67. #[structopt(long, default_value = "120")]
  68. /// Interval after which to check whitelist peers
  69. whitelist_refinery_interval: u64,
  70. }
  71. /// Struct representing a spawned P2P network
  72. struct Spawn {
  73. /// String identifier,
  74. pub name: String,
  75. /// P2P pointer
  76. pub p2p: P2pPtr,
  77. }
  78. impl Spawn {
  79. async fn get_whitelist(&self) -> Vec<JsonValue> {
  80. self.p2p
  81. .hosts()
  82. .container
  83. .fetch_all(HostColor::White)
  84. .iter()
  85. .map(|(addr, _url)| JsonValue::String(addr.to_string()))
  86. .collect()
  87. }
  88. async fn get_greylist(&self) -> Vec<JsonValue> {
  89. self.p2p
  90. .hosts()
  91. .container
  92. .fetch_all(HostColor::Grey)
  93. .iter()
  94. .map(|(addr, _url)| JsonValue::String(addr.to_string()))
  95. .collect()
  96. }
  97. async fn get_goldlist(&self) -> Vec<JsonValue> {
  98. self.p2p
  99. .hosts()
  100. .container
  101. .fetch_all(HostColor::Gold)
  102. .iter()
  103. .map(|(addr, _url)| JsonValue::String(addr.to_string()))
  104. .collect()
  105. }
  106. async fn info(&self) -> JsonValue {
  107. let mut addr_vec = vec![];
  108. for addr in &self.p2p.settings().read().await.inbound_addrs {
  109. addr_vec.push(JsonValue::String(addr.as_ref().to_string()));
  110. }
  111. JsonValue::Object(HashMap::from([
  112. ("name".to_string(), JsonValue::String(self.name.clone())),
  113. ("urls".to_string(), JsonValue::Array(addr_vec)),
  114. ("whitelist".to_string(), JsonValue::Array(self.get_whitelist().await)),
  115. ("greylist".to_string(), JsonValue::Array(self.get_greylist().await)),
  116. ("goldlist".to_string(), JsonValue::Array(self.get_goldlist().await)),
  117. ]))
  118. }
  119. }
  120. /// Defines the network-specific settings
  121. #[derive(Clone)]
  122. struct NetInfo {
  123. /// Accept addresses the network will use
  124. pub accept_addrs: Vec<Url>,
  125. /// Other seeds to connect to
  126. pub seeds: Vec<Url>,
  127. /// Manual peers to connect to
  128. pub peers: Vec<Url>,
  129. /// Supported network version
  130. pub version: Version,
  131. /// Enable localnet hosts
  132. pub localnet: bool,
  133. /// Path to P2P datastore
  134. pub datastore: String,
  135. /// Path to hostlist
  136. pub hostlist: String,
  137. }
  138. /// Struct representing the daemon
  139. struct Lilith {
  140. /// Spawned networks
  141. pub networks: Vec<Spawn>,
  142. /// JSON-RPC connection tracker
  143. pub rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  144. }
  145. impl Lilith {
  146. /// Since `Lilith` does not make outbound connections, if a peer is
  147. /// upgraded to whitelist it will remain on the whitelist even if the
  148. /// give peer is no longer online.
  149. ///
  150. /// To protect `Lilith` from sharing potentially offline nodes,
  151. /// `whitelist_refinery` periodically ping nodes on the whitelist. If they
  152. /// are reachable, we update their last seen field. Otherwise, we downgrade
  153. /// them to the greylist.
  154. ///
  155. /// Note: if `Lilith` loses connectivity this method will delete peers from
  156. /// the whitelist, meaning `Lilith` will need to rebuild its hostlist when
  157. /// it comes back online.
  158. async fn whitelist_refinery(
  159. network_name: String,
  160. p2p: P2pPtr,
  161. refinery_interval: u64,
  162. ) -> Result<()> {
  163. debug!(target: "net::refinery::whitelist_refinery", "Starting whitelist refinery for \"{}\"",
  164. network_name);
  165. let hosts = p2p.hosts();
  166. loop {
  167. sleep(refinery_interval).await;
  168. match hosts.container.fetch_last(HostColor::White) {
  169. Some(entry) => {
  170. let url = &entry.0;
  171. let last_seen = &entry.1;
  172. if !hosts.refinable(url.clone()) {
  173. debug!(target: "net::refinery::whitelist_refinery", "Addr={} not available!",
  174. url.clone());
  175. continue
  176. }
  177. if !p2p.session_refine().handshake_node(url.clone(), p2p.clone()).await {
  178. debug!(target: "net::refinery:::whitelist_refinery",
  179. "Host {} is not responsive. Downgrading from whitelist", url);
  180. hosts.greylist_host(url, *last_seen)?;
  181. continue
  182. }
  183. debug!(target: "net::refinery::whitelist_refinery",
  184. "Peer {} is responsive. Updating last_seen", url);
  185. // This node is active. Update the last seen field.
  186. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  187. hosts.whitelist_host(url, last_seen)?;
  188. }
  189. None => {
  190. debug!(target: "net::refinery::whitelist_refinery",
  191. "Whitelist is empty! Cannot start refinery process");
  192. continue
  193. }
  194. }
  195. }
  196. }
  197. // RPCAPI:
  198. // Returns all spawned networks names with their node addresses.
  199. // --> {"jsonrpc": "2.0", "method": "spawns", "params": [], "id": 42}
  200. // <-- {"jsonrpc": "2.0", "result": {"spawns": spawns_info}, "id": 42}
  201. async fn spawns(&self, id: u16, _params: JsonValue) -> JsonResult {
  202. let mut spawns = vec![];
  203. for spawn in &self.networks {
  204. spawns.push(spawn.info().await);
  205. }
  206. let json =
  207. JsonValue::Object(HashMap::from([("spawns".to_string(), JsonValue::Array(spawns))]));
  208. JsonResponse::new(json, id).into()
  209. }
  210. }
  211. #[async_trait]
  212. impl RequestHandler<()> for Lilith {
  213. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  214. return match req.method.as_str() {
  215. "ping" => self.pong(req.id, req.params).await,
  216. "spawns" => self.spawns(req.id, req.params).await,
  217. _ => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  218. }
  219. }
  220. async fn connections_mut(&self) -> MutexGuard<'life0, HashSet<StoppableTaskPtr>> {
  221. self.rpc_connections.lock().await
  222. }
  223. }
  224. /// Parse a TOML string for any configured network and return a map containing
  225. /// said configurations.
  226. fn parse_configured_networks(data: &str) -> Result<HashMap<String, NetInfo>> {
  227. let mut ret = HashMap::new();
  228. if let Value::Table(map) = toml::from_str(data)? {
  229. if map.contains_key("network") && map["network"].is_table() {
  230. for net in map["network"].as_table().unwrap() {
  231. info!(target: "lilith", "Found configuration for network: {}", net.0);
  232. let table = net.1.as_table().unwrap();
  233. if !table.contains_key("accept_addrs") {
  234. warn!(target: "lilith", "Network accept addrs are mandatory, skipping network.");
  235. continue
  236. }
  237. if !table.contains_key("hostlist") {
  238. error!(target: "lilith", "Hostlist path is mandatory! Configure and try again.");
  239. exit(1)
  240. }
  241. let name = net.0.to_string();
  242. let accept_addrs: Vec<Url> = table["accept_addrs"]
  243. .as_array()
  244. .unwrap()
  245. .iter()
  246. .map(|x| Url::parse(x.as_str().unwrap()).unwrap())
  247. .collect();
  248. let mut seeds = vec![];
  249. if table.contains_key("seeds") {
  250. if let Some(s) = table["seeds"].as_array() {
  251. for seed in s {
  252. if let Some(u) = seed.as_str() {
  253. if let Ok(url) = Url::parse(u) {
  254. seeds.push(url);
  255. }
  256. }
  257. }
  258. }
  259. }
  260. let mut peers = vec![];
  261. if table.contains_key("peers") {
  262. if let Some(p) = table["peers"].as_array() {
  263. for peer in p {
  264. if let Some(u) = peer.as_str() {
  265. if let Ok(url) = Url::parse(u) {
  266. peers.push(url);
  267. }
  268. }
  269. }
  270. }
  271. }
  272. let localnet = if table.contains_key("localnet") {
  273. table["localnet"].as_bool().unwrap()
  274. } else {
  275. false
  276. };
  277. let version = if table.contains_key("version") {
  278. semver::Version::parse(table["version"].as_str().unwrap())?
  279. } else {
  280. semver::Version::parse(option_env!("CARGO_PKG_VERSION").unwrap_or("0.0.0"))?
  281. };
  282. let datastore: String = table["datastore"].as_str().unwrap().to_string();
  283. let hostlist: String = table["hostlist"].as_str().unwrap().to_string();
  284. let net_info =
  285. NetInfo { accept_addrs, seeds, peers, version, localnet, datastore, hostlist };
  286. ret.insert(name, net_info);
  287. }
  288. }
  289. }
  290. Ok(ret)
  291. }
  292. async fn spawn_net(name: String, info: &NetInfo, ex: Arc<Executor<'static>>) -> Result<Spawn> {
  293. let mut listen_urls = vec![];
  294. // Configure listen addrs for this network
  295. for url in &info.accept_addrs {
  296. listen_urls.push(url.clone());
  297. }
  298. // P2P network settings
  299. let settings = net::Settings {
  300. inbound_addrs: listen_urls.clone(),
  301. seeds: info.seeds.clone(),
  302. peers: info.peers.clone(),
  303. outbound_connections: 0,
  304. outbound_connect_timeout: 30,
  305. inbound_connections: 512,
  306. app_version: info.version.clone(),
  307. localnet: info.localnet,
  308. p2p_datastore: Some(info.datastore.clone()),
  309. hostlist: Some(info.hostlist.clone()),
  310. allowed_transports: vec![
  311. "tcp".to_string(),
  312. "tcp+tls".to_string(),
  313. "tor".to_string(),
  314. "tor+tls".to_string(),
  315. "nym".to_string(),
  316. "nym+tls".to_string(),
  317. ],
  318. ban_policy: BanPolicy::Relaxed,
  319. ..Default::default()
  320. };
  321. // Create P2P instance
  322. let p2p = P2p::new(settings, ex.clone()).await?;
  323. let addrs_str: Vec<&str> = listen_urls.iter().map(|x| x.as_str()).collect();
  324. info!(target: "lilith", "Starting seed network node for \"{}\" on {:?}", name, addrs_str);
  325. p2p.clone().start().await?;
  326. let spawn = Spawn { name, p2p };
  327. Ok(spawn)
  328. }
  329. async_daemonize!(realmain);
  330. async fn realmain(args: Args, ex: Arc<Executor<'static>>) -> Result<()> {
  331. // Pick up network settings from the TOML config
  332. let cfg_path = get_config_path(args.config, CONFIG_FILE)?;
  333. let toml_contents = std::fs::read_to_string(cfg_path)?;
  334. let configured_nets = parse_configured_networks(&toml_contents)?;
  335. if configured_nets.is_empty() {
  336. error!(target: "lilith", "No networks are enabled in config");
  337. exit(1);
  338. }
  339. // Spawn configured networks
  340. let mut networks = vec![];
  341. for (name, info) in &configured_nets {
  342. match spawn_net(name.to_string(), info, ex.clone()).await {
  343. Ok(spawn) => networks.push(spawn),
  344. Err(e) => {
  345. error!(target: "lilith", "Failed to start P2P network seed for \"{}\": {}", name, e);
  346. exit(1);
  347. }
  348. }
  349. }
  350. // Set up main daemon and background refinery_tasks
  351. let lilith = Arc::new(Lilith { networks, rpc_connections: Mutex::new(HashSet::new()) });
  352. let mut refinery_tasks = HashMap::new();
  353. for network in &lilith.networks {
  354. let name = network.name.clone();
  355. let task = StoppableTask::new();
  356. task.clone().start(
  357. Lilith::whitelist_refinery(name.clone(), network.p2p.clone(), args.whitelist_refinery_interval),
  358. |res| async move {
  359. match res {
  360. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  361. Err(e) => error!(target: "lilith", "Failed starting refinery task for \"{}\": {}", name, e),
  362. }
  363. },
  364. Error::DetachedTaskStopped,
  365. ex.clone(),
  366. );
  367. refinery_tasks.insert(network.name.clone(), task);
  368. }
  369. // JSON-RPC server
  370. let rpc_settings: RpcSettings = args.rpc.into();
  371. info!(target: "lilith", "Starting JSON-RPC server on {}", rpc_settings.listen);
  372. let lilith_ = lilith.clone();
  373. let rpc_task = StoppableTask::new();
  374. rpc_task.clone().start(
  375. listen_and_serve(rpc_settings, lilith.clone(), None, ex.clone()),
  376. |res| async move {
  377. match res {
  378. Ok(()) | Err(Error::RpcServerStopped) => lilith_.stop_connections().await,
  379. Err(e) => error!(target: "lilith", "Failed starting JSON-RPC server: {}", e),
  380. }
  381. },
  382. Error::RpcServerStopped,
  383. ex.clone(),
  384. );
  385. // Signal handling for graceful termination.
  386. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  387. signals_handler.wait_termination(signals_task).await?;
  388. info!(target: "lilith", "Caught termination signal, cleaning up and exiting...");
  389. info!(target: "lilith", "Stopping JSON-RPC server...");
  390. rpc_task.stop().await;
  391. // Cleanly stop p2p networks
  392. for spawn in &lilith.networks {
  393. info!(target: "lilith", "Stopping \"{}\" task", spawn.name);
  394. refinery_tasks.get(&spawn.name).unwrap().stop().await;
  395. info!(target: "lilith", "Stopping \"{}\" P2P", spawn.name);
  396. spawn.p2p.stop().await;
  397. }
  398. info!(target: "lilith", "Bye!");
  399. Ok(())
  400. }