main.rs 15 KB

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