main.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. process::exit,
  21. sync::Arc,
  22. };
  23. use async_trait::async_trait;
  24. use log::{error, info, warn};
  25. use semver::Version;
  26. use smol::{
  27. lock::{Mutex, MutexGuard},
  28. stream::StreamExt,
  29. Executor,
  30. };
  31. use structopt::StructOpt;
  32. use structopt_toml::StructOptToml;
  33. use tinyjson::JsonValue;
  34. use toml::Value;
  35. use url::Url;
  36. use darkfi::{
  37. async_daemonize, cli_desc,
  38. net::{self, P2p, P2pPtr},
  39. rpc::{
  40. jsonrpc::*,
  41. server::{listen_and_serve, RequestHandler},
  42. },
  43. system::{StoppableTask, StoppableTaskPtr},
  44. util::{
  45. path::{get_config_path},
  46. },
  47. Error, Result,
  48. };
  49. const CONFIG_FILE: &str = "lilith_config.toml";
  50. const CONFIG_FILE_CONTENTS: &str = include_str!("../lilith_config.toml");
  51. #[derive(Clone, Debug, serde::Deserialize, StructOpt, StructOptToml)]
  52. #[serde(default)]
  53. #[structopt(name = "lilith", about = cli_desc!())]
  54. struct Args {
  55. #[structopt(long, default_value = "tcp://127.0.0.1:18927")]
  56. /// JSON-RPC listen URL
  57. pub rpc_listen: Url,
  58. #[structopt(short, long)]
  59. /// Configuration file to use
  60. pub config: Option<String>,
  61. #[structopt(long, default_value = "~/.config/darkfi/lilith_hosts.tsv")]
  62. /// Hosts .tsv file to use
  63. pub hosts_file: String,
  64. #[structopt(short, long)]
  65. /// Set log file to ouput into
  66. log: Option<String>,
  67. #[structopt(short, parse(from_occurrences))]
  68. /// Increase verbosity (-vvv supported)
  69. pub verbose: u8,
  70. }
  71. /// Struct representing a spawned P2P network
  72. struct Spawn {
  73. /// String identifier,
  74. pub name: String,
  75. /// P2P pointer
  76. pub p2p: P2pPtr,
  77. }
  78. impl Spawn {
  79. async fn addresses(&self) -> Vec<JsonValue> {
  80. self.p2p
  81. .hosts()
  82. .whitelist_fetch_all()
  83. .await
  84. .iter()
  85. .map(|(addr, _url)| JsonValue::String(addr.to_string()))
  86. .collect()
  87. }
  88. async fn info(&self) -> JsonValue {
  89. let mut addr_vec = vec![];
  90. for addr in &self.p2p.settings().inbound_addrs {
  91. addr_vec.push(JsonValue::String(addr.as_ref().to_string()));
  92. }
  93. JsonValue::Object(HashMap::from([
  94. ("name".to_string(), JsonValue::String(self.name.clone())),
  95. ("urls".to_string(), JsonValue::Array(addr_vec)),
  96. ("hosts".to_string(), JsonValue::Array(self.addresses().await)),
  97. ]))
  98. }
  99. }
  100. /// Defines the network-specific settings
  101. #[derive(Clone)]
  102. struct NetInfo {
  103. /// Accept addresses the network will use
  104. pub accept_addrs: Vec<Url>,
  105. /// Other seeds to connect to
  106. pub seeds: Vec<Url>,
  107. /// Manual peers to connect to
  108. pub peers: Vec<Url>,
  109. /// Supported network version
  110. pub version: Version,
  111. /// Enable localnet hosts
  112. pub localnet: bool,
  113. }
  114. /// Struct representing the daemon
  115. struct Lilith {
  116. /// Spawned networks
  117. pub networks: Vec<Spawn>,
  118. /// JSON-RPC connection tracker
  119. pub rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  120. }
  121. impl Lilith {
  122. // RPCAPI:
  123. // Returns all spawned networks names with their node addresses.
  124. // --> {"jsonrpc": "2.0", "method": "spawns", "params": [], "id": 42}
  125. // <-- {"jsonrpc": "2.0", "result": {"spawns": spawns_info}, "id": 42}
  126. async fn spawns(&self, id: u16, _params: JsonValue) -> JsonResult {
  127. let mut spawns = vec![];
  128. for spawn in &self.networks {
  129. spawns.push(spawn.info().await);
  130. }
  131. let json =
  132. JsonValue::Object(HashMap::from([("spawns".to_string(), JsonValue::Array(spawns))]));
  133. JsonResponse::new(json, id).into()
  134. }
  135. }
  136. #[async_trait]
  137. impl RequestHandler for Lilith {
  138. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  139. match req.method.as_str() {
  140. "ping" => return self.pong(req.id, req.params).await,
  141. "spawns" => return self.spawns(req.id, req.params).await,
  142. _ => return JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  143. }
  144. }
  145. async fn connections_mut(&self) -> MutexGuard<'_, HashSet<StoppableTaskPtr>> {
  146. self.rpc_connections.lock().await
  147. }
  148. }
  149. /// Parse a TOML string for any configured network and return a map containing
  150. /// said configurations.
  151. fn parse_configured_networks(data: &str) -> Result<HashMap<String, NetInfo>> {
  152. let mut ret = HashMap::new();
  153. if let Value::Table(map) = toml::from_str(data)? {
  154. if map.contains_key("network") && map["network"].is_table() {
  155. for net in map["network"].as_table().unwrap() {
  156. info!(target: "lilith", "Found configuration for network: {}", net.0);
  157. let table = net.1.as_table().unwrap();
  158. if !table.contains_key("accept_addrs") {
  159. warn!(target: "lilith", "Network accept addrs are mandatory, skipping network.");
  160. continue
  161. }
  162. let name = net.0.to_string();
  163. let accept_addrs: Vec<Url> = table["accept_addrs"]
  164. .as_array()
  165. .unwrap()
  166. .iter()
  167. .map(|x| Url::parse(x.as_str().unwrap()).unwrap())
  168. .collect();
  169. let mut seeds = vec![];
  170. if table.contains_key("seeds") {
  171. if let Some(s) = table["seeds"].as_array() {
  172. for seed in s {
  173. if let Some(u) = seed.as_str() {
  174. if let Ok(url) = Url::parse(u) {
  175. seeds.push(url);
  176. }
  177. }
  178. }
  179. }
  180. }
  181. let mut peers = vec![];
  182. if table.contains_key("peers") {
  183. if let Some(p) = table["peers"].as_array() {
  184. for peer in p {
  185. if let Some(u) = peer.as_str() {
  186. if let Ok(url) = Url::parse(u) {
  187. peers.push(url);
  188. }
  189. }
  190. }
  191. }
  192. }
  193. let localnet = if table.contains_key("localnet") {
  194. table["localnet"].as_bool().unwrap()
  195. } else {
  196. false
  197. };
  198. let version = if table.contains_key("version") {
  199. semver::Version::parse(table["version"].as_str().unwrap())?
  200. } else {
  201. semver::Version::parse(option_env!("CARGO_PKG_VERSION").unwrap_or("0.0.0"))?
  202. };
  203. let net_info = NetInfo { accept_addrs, seeds, peers, version, localnet };
  204. ret.insert(name, net_info);
  205. }
  206. }
  207. }
  208. Ok(ret)
  209. }
  210. async fn spawn_net(
  211. name: String,
  212. info: &NetInfo,
  213. ex: Arc<Executor<'static>>,
  214. ) -> Result<Spawn> {
  215. let mut listen_urls = vec![];
  216. // Configure listen addrs for this network
  217. for url in &info.accept_addrs {
  218. listen_urls.push(url.clone());
  219. }
  220. // P2P network settings
  221. let settings = net::Settings {
  222. inbound_addrs: listen_urls.clone(),
  223. seeds: info.seeds.clone(),
  224. peers: info.peers.clone(),
  225. outbound_connections: 0,
  226. outbound_connect_timeout: 30,
  227. inbound_connections: 512,
  228. app_version: info.version.clone(),
  229. localnet: info.localnet,
  230. allowed_transports: vec![
  231. "tcp".to_string(),
  232. "tcp+tls".to_string(),
  233. "tor".to_string(),
  234. "tor+tls".to_string(),
  235. "nym".to_string(),
  236. "nym+tls".to_string(),
  237. ],
  238. ..Default::default()
  239. };
  240. // Create P2P instance
  241. let p2p = P2p::new(settings, ex.clone()).await;
  242. let addrs_str: Vec<&str> = listen_urls.iter().map(|x| x.as_str()).collect();
  243. info!(target: "lilith", "Starting seed network node for \"{}\" on {:?}", name, addrs_str);
  244. p2p.clone().start().await?;
  245. let spawn = Spawn { name, p2p };
  246. Ok(spawn)
  247. }
  248. async_daemonize!(realmain);
  249. async fn realmain(args: Args, ex: Arc<Executor<'static>>) -> Result<()> {
  250. // Pick up network settings from the TOML config
  251. let cfg_path = get_config_path(args.config, CONFIG_FILE)?;
  252. let toml_contents = std::fs::read_to_string(cfg_path)?;
  253. let configured_nets = parse_configured_networks(&toml_contents)?;
  254. if configured_nets.is_empty() {
  255. error!(target: "lilith", "No networks are enabled in config");
  256. exit(1);
  257. }
  258. // Spawn configured networks
  259. let mut networks = vec![];
  260. for (name, info) in &configured_nets {
  261. // TODO: Here we could actually differentiate between network versions
  262. // e.g. p2p_v3, p2p_v4, etc. Therefore we can spawn multiple networks
  263. // and they would all be version-checked, so we avoid mismatches when
  264. // seeding peers.
  265. match spawn_net(
  266. name.to_string(),
  267. info,
  268. ex.clone(),
  269. )
  270. .await
  271. {
  272. Ok(spawn) => networks.push(spawn),
  273. Err(e) => {
  274. error!(target: "lilith", "Failed to start P2P network seed for \"{}\": {}", name, e);
  275. exit(1);
  276. }
  277. }
  278. }
  279. // Set up main daemon
  280. let lilith = Arc::new(Lilith { networks, rpc_connections: Mutex::new(HashSet::new()) });
  281. // JSON-RPC server
  282. info!(target: "lilith", "Starting JSON-RPC server on {}", args.rpc_listen);
  283. let lilith_ = lilith.clone();
  284. let rpc_task = StoppableTask::new();
  285. rpc_task.clone().start(
  286. listen_and_serve(args.rpc_listen, lilith.clone(), None, ex.clone()),
  287. |res| async move {
  288. match res {
  289. Ok(()) | Err(Error::RpcServerStopped) => lilith_.stop_connections().await,
  290. Err(e) => error!(target: "lilith", "Failed starting JSON-RPC server: {}", e),
  291. }
  292. },
  293. Error::RpcServerStopped,
  294. ex.clone(),
  295. );
  296. // Signal handling for graceful termination.
  297. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  298. signals_handler.wait_termination(signals_task).await?;
  299. info!(target: "lilith", "Caught termination signal, cleaning up and exiting...");
  300. info!(target: "lilith", "Stopping JSON-RPC server...");
  301. rpc_task.stop().await;
  302. // Cleanly stop p2p networks
  303. for spawn in &lilith.networks {
  304. info!(target: "lilith", "Stopping \"{}\" P2P", spawn.name);
  305. spawn.p2p.stop().await;
  306. }
  307. info!(target: "lilith", "Bye!");
  308. Ok(())
  309. }