main.rs 14 KB

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