main.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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::HostColor, 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. #[derive(Clone, Debug, serde::Deserialize, StructOpt, StructOptToml)]
  51. #[serde(default)]
  52. #[structopt(name = "lilith", about = cli_desc!())]
  53. struct Args {
  54. #[structopt(long, default_value = "tcp://127.0.0.1:18927")]
  55. /// JSON-RPC listen URL
  56. pub rpc_listen: Url,
  57. #[structopt(short, long)]
  58. /// Configuration file to use
  59. pub config: Option<String>,
  60. #[structopt(short, long)]
  61. /// Set log file to ouput into
  62. log: Option<String>,
  63. #[structopt(short, parse(from_occurrences))]
  64. /// Increase verbosity (-vvv supported)
  65. pub verbose: u8,
  66. #[structopt(long, default_value = "120")]
  67. /// Interval after which to check whitelist peers
  68. whitelist_refinery_interval: u64,
  69. }
  70. /// Struct representing a spawned P2P network
  71. struct Spawn {
  72. /// String identifier,
  73. pub name: String,
  74. /// P2P pointer
  75. pub p2p: P2pPtr,
  76. }
  77. impl Spawn {
  78. async fn get_whitelist(&self) -> Vec<JsonValue> {
  79. self.p2p
  80. .hosts()
  81. .container
  82. .fetch_all(HostColor::White)
  83. .await
  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. .await
  94. .iter()
  95. .map(|(addr, _url)| JsonValue::String(addr.to_string()))
  96. .collect()
  97. }
  98. async fn get_anchorlist(&self) -> Vec<JsonValue> {
  99. self.p2p
  100. .hosts()
  101. .container
  102. .fetch_all(HostColor::Gold)
  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. /// 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. if hosts.container.is_empty(HostColor::White).await {
  169. debug!(target: "net::refinery::whitelist_refinery",
  170. "Whitelist is empty! Cannot start refinery process");
  171. continue
  172. }
  173. let (entry, position) = hosts.container.fetch_last(HostColor::White).await;
  174. let url = &entry.0;
  175. let last_seen = &entry.1;
  176. if !hosts.refinable(url.clone()).await {
  177. debug!(target: "net::refinery::whitelist_refinery", "Addr={} not available!",
  178. url.clone());
  179. continue
  180. }
  181. if p2p.session_refine().handshake_node(url.clone(), p2p.clone()).await {
  182. debug!(target: "net::refinery:::whitelist_refinery",
  183. "Host {} is not responsive. Downgrading from whitelist", url);
  184. hosts.greylist_host(url, *last_seen).await?;
  185. continue
  186. }
  187. debug!(target: "net::refinery::whitelist_refinery",
  188. "Peer {} is responsive. Updating last_seen", url);
  189. // This node is active. Update the last seen field.
  190. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  191. hosts
  192. .container
  193. .update_last_seen(HostColor::White as usize, url, last_seen, Some(position))
  194. .await;
  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<'_, 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 hostlist: String = table["hostlist"].as_str().unwrap().to_string();
  283. let net_info = NetInfo { accept_addrs, seeds, peers, version, localnet, hostlist };
  284. ret.insert(name, net_info);
  285. }
  286. }
  287. }
  288. Ok(ret)
  289. }
  290. async fn spawn_net(name: String, info: &NetInfo, ex: Arc<Executor<'static>>) -> Result<Spawn> {
  291. let mut listen_urls = vec![];
  292. // Configure listen addrs for this network
  293. for url in &info.accept_addrs {
  294. listen_urls.push(url.clone());
  295. }
  296. // P2P network settings
  297. let settings = net::Settings {
  298. inbound_addrs: listen_urls.clone(),
  299. seeds: info.seeds.clone(),
  300. peers: info.peers.clone(),
  301. outbound_connections: 0,
  302. outbound_connect_timeout: 30,
  303. inbound_connections: 512,
  304. app_version: info.version.clone(),
  305. localnet: info.localnet,
  306. hostlist: info.hostlist.clone(),
  307. allowed_transports: vec![
  308. "tcp".to_string(),
  309. "tcp+tls".to_string(),
  310. "tor".to_string(),
  311. "tor+tls".to_string(),
  312. "nym".to_string(),
  313. "nym+tls".to_string(),
  314. ],
  315. ..Default::default()
  316. };
  317. // Create P2P instance
  318. let p2p = P2p::new(settings, ex.clone()).await;
  319. let addrs_str: Vec<&str> = listen_urls.iter().map(|x| x.as_str()).collect();
  320. info!(target: "lilith", "Starting seed network node for \"{}\" on {:?}", name, addrs_str);
  321. p2p.clone().start().await?;
  322. let spawn = Spawn { name, p2p };
  323. Ok(spawn)
  324. }
  325. async_daemonize!(realmain);
  326. async fn realmain(args: Args, ex: Arc<Executor<'static>>) -> Result<()> {
  327. // Pick up network settings from the TOML config
  328. let cfg_path = get_config_path(args.config, CONFIG_FILE)?;
  329. let toml_contents = std::fs::read_to_string(cfg_path)?;
  330. let configured_nets = parse_configured_networks(&toml_contents)?;
  331. if configured_nets.is_empty() {
  332. error!(target: "lilith", "No networks are enabled in config");
  333. exit(1);
  334. }
  335. // Spawn configured networks
  336. let mut networks = vec![];
  337. for (name, info) in &configured_nets {
  338. match spawn_net(name.to_string(), info, ex.clone()).await {
  339. Ok(spawn) => networks.push(spawn),
  340. Err(e) => {
  341. error!(target: "lilith", "Failed to start P2P network seed for \"{}\": {}", name, e);
  342. exit(1);
  343. }
  344. }
  345. }
  346. // Set up main daemon and background refinery_tasks
  347. let lilith = Arc::new(Lilith { networks, rpc_connections: Mutex::new(HashSet::new()) });
  348. let mut refinery_tasks = HashMap::new();
  349. for network in &lilith.networks {
  350. let name = network.name.clone();
  351. let task = StoppableTask::new();
  352. task.clone().start(
  353. Lilith::whitelist_refinery(name.clone(), network.p2p.clone(), args.whitelist_refinery_interval),
  354. |res| async move {
  355. match res {
  356. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  357. Err(e) => error!(target: "lilith", "Failed starting refinery task for \"{}\": {}", name, e),
  358. }
  359. },
  360. Error::DetachedTaskStopped,
  361. ex.clone(),
  362. );
  363. refinery_tasks.insert(network.name.clone(), task);
  364. }
  365. // JSON-RPC server
  366. info!(target: "lilith", "Starting JSON-RPC server on {}", args.rpc_listen);
  367. let lilith_ = lilith.clone();
  368. let rpc_task = StoppableTask::new();
  369. rpc_task.clone().start(
  370. listen_and_serve(args.rpc_listen, lilith.clone(), None, ex.clone()),
  371. |res| async move {
  372. match res {
  373. Ok(()) | Err(Error::RpcServerStopped) => lilith_.stop_connections().await,
  374. Err(e) => error!(target: "lilith", "Failed starting JSON-RPC server: {}", e),
  375. }
  376. },
  377. Error::RpcServerStopped,
  378. ex.clone(),
  379. );
  380. // Signal handling for graceful termination.
  381. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  382. signals_handler.wait_termination(signals_task).await?;
  383. info!(target: "lilith", "Caught termination signal, cleaning up and exiting...");
  384. info!(target: "lilith", "Stopping JSON-RPC server...");
  385. rpc_task.stop().await;
  386. // Cleanly stop p2p networks
  387. for spawn in &lilith.networks {
  388. info!(target: "lilith", "Stopping \"{}\" task", spawn.name);
  389. refinery_tasks.get(&spawn.name).unwrap().stop().await;
  390. info!(target: "lilith", "Stopping \"{}\" P2P", spawn.name);
  391. spawn.p2p.stop().await;
  392. }
  393. info!(target: "lilith", "Bye!");
  394. Ok(())
  395. }