main.rs 11 KB

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