main.rs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2022 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::path::Path;
  19. use async_std::sync::Arc;
  20. use async_trait::async_trait;
  21. use fxhash::{FxHashMap, FxHashSet};
  22. use log::{error, info, warn};
  23. use serde_json::{json, Value};
  24. use structopt_toml::StructOptToml;
  25. use url::Url;
  26. use darkfi::{
  27. async_daemonize, net,
  28. net::P2pPtr,
  29. rpc::{
  30. jsonrpc::{
  31. ErrorCode::{InvalidParams, MethodNotFound},
  32. JsonError, JsonRequest, JsonResponse, JsonResult,
  33. },
  34. server::{listen_and_serve, RequestHandler},
  35. },
  36. util::{
  37. file::{load_file, save_file},
  38. path::{expand_path, get_config_path},
  39. },
  40. Result,
  41. };
  42. mod config;
  43. use config::{parse_configured_networks, Args, NetInfo};
  44. const CONFIG_FILE: &str = "lilith_config.toml";
  45. const CONFIG_FILE_CONTENTS: &str = include_str!("../lilith_config.toml");
  46. /// Struct representing a spawned p2p network.
  47. struct Spawn {
  48. name: String,
  49. p2p: P2pPtr,
  50. }
  51. impl Spawn {
  52. async fn addresses(&self) -> Vec<String> {
  53. self.p2p.hosts().load_all().await.iter().map(|addr| addr.to_string()).collect()
  54. }
  55. pub async fn info(&self) -> serde_json::Value {
  56. // Building addr_vec string
  57. let mut addr_vec = vec![];
  58. for addr in &self.p2p.settings().inbound {
  59. addr_vec.push(addr.as_ref().to_string());
  60. }
  61. json!({
  62. "name": self.name.clone(),
  63. "urls": addr_vec,
  64. "hosts": self.addresses().await,
  65. })
  66. }
  67. }
  68. /// Struct representing the daemon.
  69. struct Lilith {
  70. /// Configured urls
  71. urls: Vec<Url>,
  72. /// Spawned networks
  73. spawns: Vec<Spawn>,
  74. }
  75. impl Lilith {
  76. async fn spawns_hosts(&self) -> FxHashMap<String, Vec<String>> {
  77. // Building urls string
  78. let mut spawns = FxHashMap::default();
  79. for spawn in &self.spawns {
  80. spawns.insert(spawn.name.clone(), spawn.addresses().await);
  81. }
  82. spawns
  83. }
  84. // RPCAPI:
  85. // Returns all spawned networks names with their node addresses.
  86. // --> {"jsonrpc": "2.0", "method": "spawns", "params": [], "id": 42}
  87. // <-- {"jsonrpc": "2.0", "result": "{spawns}", "id": 42}
  88. async fn spawns(&self, id: Value, _params: &[Value]) -> JsonResult {
  89. // Building urls string
  90. let mut urls_vec = vec![];
  91. for url in &self.urls {
  92. urls_vec.push(url.as_ref().to_string());
  93. }
  94. // Gathering spawns info
  95. let mut spawns = vec![];
  96. for spawn in &self.spawns {
  97. spawns.push(spawn.info().await);
  98. }
  99. // Generating json
  100. let json = json!({
  101. "urls": urls_vec,
  102. "spawns": spawns,
  103. });
  104. JsonResponse::new(json, id).into()
  105. }
  106. // RPCAPI:
  107. // Replies to a ping method.
  108. // --> {"jsonrpc": "2.0", "method": "ping", "params": [], "id": 42}
  109. // <-- {"jsonrpc": "2.0", "result": "pong", "id": 42}
  110. async fn pong(&self, id: Value, _params: &[Value]) -> JsonResult {
  111. JsonResponse::new(json!("pong"), id).into()
  112. }
  113. }
  114. #[async_trait]
  115. impl RequestHandler for Lilith {
  116. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  117. if !req.params.is_array() {
  118. return JsonError::new(InvalidParams, None, req.id).into()
  119. }
  120. let params = req.params.as_array().unwrap();
  121. match req.method.as_str() {
  122. Some("spawns") => return self.spawns(req.id, params).await,
  123. Some("ping") => return self.pong(req.id, params).await,
  124. Some(_) | None => return JsonError::new(MethodNotFound, None, req.id).into(),
  125. }
  126. }
  127. }
  128. async fn spawn_network(
  129. name: &str,
  130. info: NetInfo,
  131. urls: Vec<Url>,
  132. saved_hosts: Option<&FxHashSet<Url>>,
  133. ex: Arc<smol::Executor<'_>>,
  134. ) -> Result<Spawn> {
  135. let mut full_urls = Vec::new();
  136. for url in &urls {
  137. let mut url = url.clone();
  138. url.set_port(Some(info.port))?;
  139. full_urls.push(url);
  140. }
  141. let network_settings = net::Settings {
  142. inbound: full_urls.clone(),
  143. seeds: info.seeds,
  144. peers: info.peers,
  145. outbound_connections: 0,
  146. localnet: info.localnet,
  147. channel_log: info.channel_log,
  148. app_version: None,
  149. ..Default::default()
  150. };
  151. let p2p = net::P2p::new(network_settings).await;
  152. // Setting saved hosts
  153. match saved_hosts {
  154. Some(hosts) => {
  155. // Converting hashet to vec
  156. let mut vec = vec![];
  157. for url in hosts {
  158. vec.push(url.clone());
  159. }
  160. p2p.hosts().store(vec).await;
  161. }
  162. None => info!("No saved hosts found for {}", name),
  163. }
  164. // Building ext_addr_vec string
  165. let mut urls_vec = vec![];
  166. for url in &full_urls {
  167. urls_vec.push(url.as_ref().to_string());
  168. }
  169. info!("Starting seed network node for {} at: {:?}", name, urls_vec);
  170. p2p.clone().start(ex.clone()).await?;
  171. let _ex = ex.clone();
  172. let _p2p = p2p.clone();
  173. ex.spawn(async move {
  174. if let Err(e) = _p2p.run(_ex).await {
  175. error!("Failed starting P2P network seed: {}", e);
  176. }
  177. })
  178. .detach();
  179. let spawn = Spawn { name: name.to_string(), p2p };
  180. Ok(spawn)
  181. }
  182. /// Retrieve saved hosts for provided networks
  183. fn load_hosts(path: &Path, networks: &[&str]) -> FxHashMap<String, FxHashSet<Url>> {
  184. let mut saved_hosts = FxHashMap::default();
  185. info!("Retrieving saved hosts from: {:?}", path);
  186. let contents = load_file(path);
  187. if let Err(e) = contents {
  188. warn!("Failed retrieving saved hosts: {}", e);
  189. return saved_hosts
  190. }
  191. for line in contents.unwrap().lines() {
  192. let data: Vec<&str> = line.split('\t').collect();
  193. if networks.contains(&data[0]) {
  194. let mut hosts = match saved_hosts.get(data[0]) {
  195. Some(hosts) => hosts.clone(),
  196. None => FxHashSet::default(),
  197. };
  198. let url = match Url::parse(data[1]) {
  199. Ok(u) => u,
  200. Err(e) => {
  201. warn!("Skipping malformed url: {} ({})", data[1], e);
  202. continue
  203. }
  204. };
  205. hosts.insert(url);
  206. saved_hosts.insert(data[0].to_string(), hosts);
  207. }
  208. }
  209. saved_hosts
  210. }
  211. /// Save spawns current hosts
  212. fn save_hosts(path: &Path, spawns: FxHashMap<String, Vec<String>>) {
  213. let mut string = "".to_string();
  214. for (name, urls) in spawns {
  215. for url in urls {
  216. string.push_str(&name);
  217. string.push('\t');
  218. string.push_str(&url);
  219. string.push('\n');
  220. }
  221. }
  222. if !string.eq("") {
  223. info!("Saving current hosts of spawnned networks to: {:?}", path);
  224. if let Err(e) = save_file(path, &string) {
  225. error!("Failed saving hosts: {}", e);
  226. }
  227. }
  228. }
  229. async_daemonize!(realmain);
  230. async fn realmain(args: Args, ex: Arc<smol::Executor<'_>>) -> Result<()> {
  231. // We use this handler to block this function after detaching all
  232. // tasks, and to catch a shutdown signal, where we can clean up and
  233. // exit gracefully.
  234. let (signal, shutdown) = smol::channel::bounded::<()>(1);
  235. ctrlc::set_handler(move || {
  236. async_std::task::block_on(signal.send(())).unwrap();
  237. })
  238. .unwrap();
  239. // Pick up network settings from the TOML configuration
  240. let cfg_path = get_config_path(args.config, CONFIG_FILE)?;
  241. let toml_contents = std::fs::read_to_string(cfg_path)?;
  242. let configured_nets = parse_configured_networks(&toml_contents)?;
  243. // Verify any daemon network is enabled
  244. if configured_nets.is_empty() {
  245. info!("No daemon network is enabled!");
  246. return Ok(())
  247. }
  248. // Setting urls
  249. let mut urls = args.urls.clone();
  250. if urls.is_empty() {
  251. info!("Urls are not provided, will use: tcp://127.0.0.1");
  252. let url = Url::parse("tcp://127.0.0.1")?;
  253. urls.push(url);
  254. }
  255. // Retrieve saved hosts for configured networks
  256. let full_path = expand_path(&args.hosts_file)?;
  257. let nets: Vec<&str> = configured_nets.keys().map(|x| x.as_str()).collect();
  258. let saved_hosts = load_hosts(&full_path, &nets);
  259. // Spawn configured networks
  260. let mut spawns = vec![];
  261. for (name, info) in &configured_nets {
  262. match spawn_network(name, info.clone(), urls.clone(), saved_hosts.get(name), ex.clone())
  263. .await
  264. {
  265. Ok(spawn) => spawns.push(spawn),
  266. Err(e) => error!("Failed starting {} P2P network seed: {}", name, e),
  267. }
  268. }
  269. let lilith = Lilith { urls, spawns };
  270. let lilith = Arc::new(lilith);
  271. // JSON-RPC server
  272. info!("Starting JSON-RPC server");
  273. ex.spawn(listen_and_serve(args.rpc_listen, lilith.clone())).detach();
  274. // Wait for SIGINT
  275. shutdown.recv().await?;
  276. print!("\r");
  277. info!("Caught termination signal, cleaning up and exiting...");
  278. // Save spawns current hosts
  279. save_hosts(&full_path, lilith.spawns_hosts().await);
  280. Ok(())
  281. }