main.rs 9.5 KB

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