main.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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, JsonNotification, JsonRequest, JsonResponse, JsonResult, JsonSubscriber,
  33. },
  34. server::{listen_and_serve, RequestHandler},
  35. },
  36. system::{Subscriber, SubscriberPtr},
  37. util::{
  38. async_util::sleep,
  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. // TODO: Subscriber should come from ValidatorState or something
  77. subscriber: SubscriberPtr<JsonNotification>,
  78. }
  79. impl Lilith {
  80. async fn spawns_hosts(&self) -> FxHashMap<String, Vec<String>> {
  81. // Building urls string
  82. let mut spawns = FxHashMap::default();
  83. for spawn in &self.spawns {
  84. spawns.insert(spawn.name.clone(), spawn.addresses().await);
  85. }
  86. spawns
  87. }
  88. // RPCAPI:
  89. // Returns all spawned networks names with their node addresses.
  90. // --> {"jsonrpc": "2.0", "method": "spawns", "params": [], "id": 42}
  91. // <-- {"jsonrpc": "2.0", "result": "{spawns}", "id": 42}
  92. async fn spawns(&self, id: Value, _params: &[Value]) -> JsonResult {
  93. // Building urls string
  94. let mut urls_vec = vec![];
  95. for url in &self.urls {
  96. urls_vec.push(url.as_ref().to_string());
  97. }
  98. // Gathering spawns info
  99. let mut spawns = vec![];
  100. for spawn in &self.spawns {
  101. spawns.push(spawn.info().await);
  102. }
  103. // Generating json
  104. let json = json!({
  105. "urls": urls_vec,
  106. "spawns": spawns,
  107. });
  108. JsonResponse::new(json, id).into()
  109. }
  110. // RPCAPI:
  111. // Replies to a ping method.
  112. // --> {"jsonrpc": "2.0", "method": "ping", "params": [], "id": 42}
  113. // <-- {"jsonrpc": "2.0", "result": "pong", "id": 42}
  114. async fn pong(&self, id: Value, _params: &[Value]) -> JsonResult {
  115. JsonResponse::new(json!("pong"), id).into()
  116. }
  117. // RPCAPI:
  118. // Create a new subscriber for new blocks to notify connected peer.
  119. //
  120. // --> {"jsonrpc": "2.0", "method": "blockchain.notify_blocks", "params": [], "id": 1}
  121. // <-- {"jsonrpc": "2.0", "result": {...}, "id": 1}
  122. pub async fn blockchain_notify_blocks(&self, id: Value, params: &[Value]) -> JsonResult {
  123. if !params.is_empty() {
  124. return JsonError::new(InvalidParams, None, id).into()
  125. }
  126. JsonSubscriber::new(self.subscriber.clone()).into()
  127. }
  128. }
  129. // TODO: remove this
  130. async fn simulate_blocks(subscriber: SubscriberPtr<JsonNotification>) {
  131. // Notifications simulation
  132. let message =
  133. JsonNotification::new("blockchain.notify_blocks", Value::from("New Block created!"));
  134. loop {
  135. subscriber.notify(message.clone()).await;
  136. sleep(10).await;
  137. }
  138. }
  139. #[async_trait]
  140. impl RequestHandler for Lilith {
  141. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  142. if !req.params.is_array() {
  143. return JsonError::new(InvalidParams, None, req.id).into()
  144. }
  145. let params = req.params.as_array().unwrap();
  146. match req.method.as_str() {
  147. Some("spawns") => return self.spawns(req.id, params).await,
  148. Some("ping") => return self.pong(req.id, params).await,
  149. Some("blockchain.notify_blocks") => {
  150. return self.blockchain_notify_blocks(req.id, params).await
  151. }
  152. Some(_) | None => return JsonError::new(MethodNotFound, None, req.id).into(),
  153. }
  154. }
  155. }
  156. async fn spawn_network(
  157. name: &str,
  158. info: NetInfo,
  159. urls: Vec<Url>,
  160. saved_hosts: Option<&FxHashSet<Url>>,
  161. ex: Arc<smol::Executor<'_>>,
  162. ) -> Result<Spawn> {
  163. let mut full_urls = Vec::new();
  164. for url in &urls {
  165. let mut url = url.clone();
  166. url.set_port(Some(info.port))?;
  167. full_urls.push(url);
  168. }
  169. let network_settings = net::Settings {
  170. inbound: full_urls.clone(),
  171. seeds: info.seeds,
  172. peers: info.peers,
  173. outbound_connections: 0,
  174. localnet: info.localnet,
  175. channel_log: info.channel_log,
  176. app_version: None,
  177. ..Default::default()
  178. };
  179. let p2p = net::P2p::new(network_settings).await;
  180. // Setting saved hosts
  181. match saved_hosts {
  182. Some(hosts) => {
  183. // Converting hashet to vec
  184. let mut vec = vec![];
  185. for url in hosts {
  186. vec.push(url.clone());
  187. }
  188. p2p.hosts().store(vec).await;
  189. }
  190. None => info!("No saved hosts found for {}", name),
  191. }
  192. // Building ext_addr_vec string
  193. let mut urls_vec = vec![];
  194. for url in &full_urls {
  195. urls_vec.push(url.as_ref().to_string());
  196. }
  197. info!("Starting seed network node for {} at: {:?}", name, urls_vec);
  198. p2p.clone().start(ex.clone()).await?;
  199. let _ex = ex.clone();
  200. let _p2p = p2p.clone();
  201. ex.spawn(async move {
  202. if let Err(e) = _p2p.run(_ex).await {
  203. error!("Failed starting P2P network seed: {}", e);
  204. }
  205. })
  206. .detach();
  207. let spawn = Spawn { name: name.to_string(), p2p };
  208. Ok(spawn)
  209. }
  210. /// Retrieve saved hosts for provided networks
  211. fn load_hosts(path: &Path, networks: &[&str]) -> FxHashMap<String, FxHashSet<Url>> {
  212. let mut saved_hosts = FxHashMap::default();
  213. info!("Retrieving saved hosts from: {:?}", path);
  214. let contents = load_file(path);
  215. if let Err(e) = contents {
  216. warn!("Failed retrieving saved hosts: {}", e);
  217. return saved_hosts
  218. }
  219. for line in contents.unwrap().lines() {
  220. let data: Vec<&str> = line.split('\t').collect();
  221. if networks.contains(&data[0]) {
  222. let mut hosts = match saved_hosts.get(data[0]) {
  223. Some(hosts) => hosts.clone(),
  224. None => FxHashSet::default(),
  225. };
  226. let url = match Url::parse(data[1]) {
  227. Ok(u) => u,
  228. Err(e) => {
  229. warn!("Skipping malformed url: {} ({})", data[1], e);
  230. continue
  231. }
  232. };
  233. hosts.insert(url);
  234. saved_hosts.insert(data[0].to_string(), hosts);
  235. }
  236. }
  237. saved_hosts
  238. }
  239. /// Save spawns current hosts
  240. fn save_hosts(path: &Path, spawns: FxHashMap<String, Vec<String>>) {
  241. let mut string = "".to_string();
  242. for (name, urls) in spawns {
  243. for url in urls {
  244. string.push_str(&name);
  245. string.push('\t');
  246. string.push_str(&url);
  247. string.push('\n');
  248. }
  249. }
  250. if !string.eq("") {
  251. info!("Saving current hosts of spawnned networks to: {:?}", path);
  252. if let Err(e) = save_file(path, &string) {
  253. error!("Failed saving hosts: {}", e);
  254. }
  255. }
  256. }
  257. async_daemonize!(realmain);
  258. async fn realmain(args: Args, ex: Arc<smol::Executor<'_>>) -> Result<()> {
  259. // We use this handler to block this function after detaching all
  260. // tasks, and to catch a shutdown signal, where we can clean up and
  261. // exit gracefully.
  262. let (signal, shutdown) = smol::channel::bounded::<()>(1);
  263. ctrlc::set_handler(move || {
  264. async_std::task::block_on(signal.send(())).unwrap();
  265. })
  266. .unwrap();
  267. // Pick up network settings from the TOML configuration
  268. let cfg_path = get_config_path(args.config, CONFIG_FILE)?;
  269. let toml_contents = std::fs::read_to_string(cfg_path)?;
  270. let configured_nets = parse_configured_networks(&toml_contents)?;
  271. // Verify any daemon network is enabled
  272. if configured_nets.is_empty() {
  273. info!("No daemon network is enabled!");
  274. return Ok(())
  275. }
  276. // Setting urls
  277. let mut urls = args.urls.clone();
  278. if urls.is_empty() {
  279. info!("Urls are not provided, will use: tcp://127.0.0.1");
  280. let url = Url::parse("tcp://127.0.0.1")?;
  281. urls.push(url);
  282. }
  283. // Retrieve saved hosts for configured networks
  284. let full_path = expand_path(&args.hosts_file)?;
  285. let nets: Vec<&str> = configured_nets.keys().map(|x| x.as_str()).collect();
  286. let saved_hosts = load_hosts(&full_path, &nets);
  287. // Spawn configured networks
  288. let mut spawns = vec![];
  289. for (name, info) in &configured_nets {
  290. match spawn_network(name, info.clone(), urls.clone(), saved_hosts.get(name), ex.clone())
  291. .await
  292. {
  293. Ok(spawn) => spawns.push(spawn),
  294. Err(e) => error!("Failed starting {} P2P network seed: {}", name, e),
  295. }
  296. }
  297. // TODO: Subscriber should come from ValidatorState or something
  298. let subscriber: SubscriberPtr<JsonNotification> = Subscriber::new();
  299. let lilith = Lilith { urls, spawns, subscriber: subscriber.clone() };
  300. let lilith = Arc::new(lilith);
  301. // JSON-RPC server
  302. info!("Starting JSON-RPC server");
  303. let _ex = ex.clone();
  304. ex.spawn(listen_and_serve(args.rpc_listen, lilith.clone(), _ex)).detach();
  305. // JSON-RPC notifications simulation
  306. ex.spawn(simulate_blocks(subscriber)).detach();
  307. // Wait for SIGINT
  308. shutdown.recv().await?;
  309. print!("\r");
  310. info!("Caught termination signal, cleaning up and exiting...");
  311. // Save spawns current hosts
  312. save_hosts(&full_path, lilith.spawns_hosts().await);
  313. Ok(())
  314. }