main.rs 15 KB

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