main.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. process::exit,
  22. sync::Arc,
  23. };
  24. use async_trait::async_trait;
  25. use futures::future::join_all;
  26. use log::{debug, error, info, warn};
  27. use semver::Version;
  28. use smol::{stream::StreamExt, Executor};
  29. use structopt::StructOpt;
  30. use structopt_toml::StructOptToml;
  31. use tinyjson::JsonValue;
  32. use toml::Value;
  33. use url::Url;
  34. use darkfi::{
  35. async_daemonize, cli_desc,
  36. net::{self, connector::Connector, protocol::ProtocolVersion, session::Session, P2p, P2pPtr},
  37. rpc::{
  38. jsonrpc::*,
  39. server::{listen_and_serve, RequestHandler},
  40. },
  41. system::{sleep, StoppableTask},
  42. util::{
  43. file::{load_file, save_file},
  44. path::{expand_path, get_config_path},
  45. },
  46. Error, Result,
  47. };
  48. const CONFIG_FILE: &str = "lilith_config.toml";
  49. const CONFIG_FILE_CONTENTS: &str = include_str!("../lilith_config.toml");
  50. #[derive(Clone, Debug, serde::Deserialize, StructOpt, StructOptToml)]
  51. #[serde(default)]
  52. #[structopt(name = "lilith", about = cli_desc!())]
  53. struct Args {
  54. #[structopt(long, default_value = "tcp://127.0.0.1:18927")]
  55. /// JSON-RPC listen URL
  56. pub rpc_listen: Url,
  57. #[structopt(long)]
  58. /// Accept addresses (URL without port)
  59. pub accept_addrs: Vec<Url>,
  60. #[structopt(short, long)]
  61. /// Configuration file to use
  62. pub config: Option<String>,
  63. #[structopt(long, default_value = "~/.config/darkfi/lilith_hosts.tsv")]
  64. /// Hosts .tsv file to use
  65. pub hosts_file: String,
  66. #[structopt(short, long)]
  67. /// Set log file to ouput into
  68. log: Option<String>,
  69. #[structopt(short, parse(from_occurrences))]
  70. /// Increase verbosity (-vvv supported)
  71. pub verbose: u8,
  72. }
  73. /// Struct representing a spawned P2P network
  74. struct Spawn {
  75. /// String identifier,
  76. pub name: String,
  77. /// P2P pointer
  78. pub p2p: P2pPtr,
  79. }
  80. impl Spawn {
  81. async fn addresses(&self) -> Vec<JsonValue> {
  82. self.p2p
  83. .hosts()
  84. .fetch_all()
  85. .await
  86. .iter()
  87. .map(|addr| JsonValue::String(addr.to_string()))
  88. .collect()
  89. }
  90. async fn info(&self) -> JsonValue {
  91. let mut addr_vec = vec![];
  92. for addr in &self.p2p.settings().inbound_addrs {
  93. addr_vec.push(JsonValue::String(addr.as_ref().to_string()));
  94. }
  95. JsonValue::Object(HashMap::from([
  96. ("name".to_string(), JsonValue::String(self.name.clone())),
  97. ("urls".to_string(), JsonValue::Array(addr_vec)),
  98. ("hosts".to_string(), JsonValue::Array(self.addresses().await)),
  99. ]))
  100. }
  101. }
  102. /// Defines the network-specific settings
  103. #[derive(Clone)]
  104. struct NetInfo {
  105. /// Specific port the network will use
  106. pub port: u16,
  107. /// Other seeds to connect to
  108. pub seeds: Vec<Url>,
  109. /// Manual peers to connect to
  110. pub peers: Vec<Url>,
  111. /// Supported network version
  112. pub version: Version,
  113. /// Enable localnet hosts
  114. pub localnet: bool,
  115. }
  116. /// Struct representing the daemon
  117. struct Lilith {
  118. /// Spawned networks
  119. pub networks: Vec<Spawn>,
  120. }
  121. impl Lilith {
  122. /// Internal task to run a periodic purge of unreachable hosts
  123. /// for a specific P2P network.
  124. async fn periodic_purge(name: String, p2p: P2pPtr, ex: Arc<Executor<'_>>) -> Result<()> {
  125. info!(target: "lilith", "Starting periodic host purge task for \"{}\"", name);
  126. loop {
  127. // We'll pick up to 10 hosts every minute and try to connect to
  128. // them. If we can't reach them, we'll remove them from our set.
  129. sleep(60).await;
  130. debug!(target: "lilith", "[{}] Picking random hosts from db", name);
  131. let lottery_winners = p2p.clone().hosts().fetch_n_random(10).await;
  132. let win_str: Vec<&str> = lottery_winners.iter().map(|x| x.as_str()).collect();
  133. debug!(target: "lilith", "[{}] Got: {:?}", name, win_str);
  134. let mut tasks = vec![];
  135. for host in &lottery_winners {
  136. let p2p_ = p2p.clone();
  137. let ex_ = ex.clone();
  138. tasks.push(async move {
  139. let session_out = p2p_.session_outbound().await;
  140. let session_weak = Arc::downgrade(&p2p_.session_outbound().await);
  141. let connector = Connector::new(p2p_.settings(), session_weak);
  142. debug!(target: "lilith", "Connecting to {}", host);
  143. match connector.connect(host).await {
  144. Ok((_url, channel)) => {
  145. debug!(target: "lilith", "Connected successfully!");
  146. let proto_ver = ProtocolVersion::new(
  147. channel.clone(),
  148. p2p_.settings().clone(),
  149. p2p_.hosts().clone(),
  150. )
  151. .await;
  152. let handshake_task = session_out.perform_handshake_protocols(
  153. proto_ver,
  154. channel.clone(),
  155. ex_.clone(),
  156. );
  157. channel.clone().start(ex_.clone());
  158. match handshake_task.await {
  159. Ok(()) => {
  160. debug!(target: "lilith", "Handshake success! Stopping channel.");
  161. channel.stop().await;
  162. }
  163. Err(e) => {
  164. debug!(target: "lilith", "Handshake failure! {}", e);
  165. }
  166. }
  167. }
  168. Err(e) => {
  169. debug!(target: "lilith", "Failed to connect to {}, removing from set ({})", host, e);
  170. // Remove from hosts set
  171. p2p_.hosts().remove(host).await;
  172. }
  173. }
  174. });
  175. }
  176. join_all(tasks).await;
  177. }
  178. }
  179. // RPCAPI:
  180. // Returns all spawned networks names with their node addresses.
  181. // --> {"jsonrpc": "2.0", "method": "spawns", "params": [], "id": 42}
  182. // <-- {"jsonrpc": "2.0", "result": {"spawns": spawns_info}, "id": 42}
  183. async fn spawns(&self, id: u16, _params: JsonValue) -> JsonResult {
  184. let mut spawns = vec![];
  185. for spawn in &self.networks {
  186. spawns.push(spawn.info().await);
  187. }
  188. let json =
  189. JsonValue::Object(HashMap::from([("spawns".to_string(), JsonValue::Array(spawns))]));
  190. JsonResponse::new(json, id).into()
  191. }
  192. }
  193. #[async_trait]
  194. impl RequestHandler for Lilith {
  195. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  196. match req.method.as_str() {
  197. "ping" => return self.pong(req.id, req.params).await,
  198. "spawns" => return self.spawns(req.id, req.params).await,
  199. _ => return JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  200. }
  201. }
  202. }
  203. /// Attempt to read existing hosts tsv
  204. fn load_hosts(path: &Path, networks: &[&str]) -> HashMap<String, HashSet<Url>> {
  205. let mut saved_hosts = HashMap::new();
  206. let contents = load_file(path);
  207. if let Err(e) = contents {
  208. warn!(target: "lilith", "Failed retrieving saved hosts: {}", e);
  209. return saved_hosts
  210. }
  211. for line in contents.unwrap().lines() {
  212. let data: Vec<&str> = line.split('\t').collect();
  213. if networks.contains(&data[0]) {
  214. let mut hosts = match saved_hosts.get(data[0]) {
  215. Some(hosts) => hosts.clone(),
  216. None => HashSet::new(),
  217. };
  218. let url = match Url::parse(data[1]) {
  219. Ok(u) => u,
  220. Err(e) => {
  221. warn!(target: "lilith", "Skipping malformed url: {} ({})", data[1], e);
  222. continue
  223. }
  224. };
  225. hosts.insert(url);
  226. saved_hosts.insert(data[0].to_string(), hosts);
  227. }
  228. }
  229. saved_hosts
  230. }
  231. async fn save_hosts(path: &Path, networks: &[Spawn]) {
  232. let mut tsv = String::new();
  233. for spawn in networks {
  234. for host in spawn.p2p.hosts().fetch_all().await {
  235. tsv.push_str(&format!("{}\t{}\n", spawn.name, host.as_str()));
  236. }
  237. }
  238. if !tsv.eq("") {
  239. info!(target: "lilith", "Saving current hosts of spawned networks to: {:?}", path);
  240. if let Err(e) = save_file(path, &tsv) {
  241. error!(target: "lilith", "Failed saving hosts: {}", e);
  242. }
  243. }
  244. }
  245. /// Parse a TOML string for any configured network and return a map containing
  246. /// said configurations.
  247. fn parse_configured_networks(data: &str) -> Result<HashMap<String, NetInfo>> {
  248. let mut ret = HashMap::new();
  249. if let Value::Table(map) = toml::from_str(data)? {
  250. if map.contains_key("network") && map["network"].is_table() {
  251. for net in map["network"].as_table().unwrap() {
  252. info!(target: "lilith", "Found configuration for network: {}", net.0);
  253. let table = net.1.as_table().unwrap();
  254. if !table.contains_key("port") {
  255. warn!(target: "lilith", "Network port is mandatory, skipping network.");
  256. continue
  257. }
  258. let name = net.0.to_string();
  259. let port = table["port"].as_integer().unwrap().try_into().unwrap();
  260. let mut seeds = vec![];
  261. if table.contains_key("seeds") {
  262. if let Some(s) = table["seeds"].as_array() {
  263. for seed in s {
  264. if let Some(u) = seed.as_str() {
  265. if let Ok(url) = Url::parse(u) {
  266. seeds.push(url);
  267. }
  268. }
  269. }
  270. }
  271. }
  272. let mut peers = vec![];
  273. if table.contains_key("peers") {
  274. if let Some(p) = table["peers"].as_array() {
  275. for peer in p {
  276. if let Some(u) = peer.as_str() {
  277. if let Ok(url) = Url::parse(u) {
  278. peers.push(url);
  279. }
  280. }
  281. }
  282. }
  283. }
  284. let localnet = if table.contains_key("localnet") {
  285. table["localnet"].as_bool().unwrap()
  286. } else {
  287. false
  288. };
  289. let version = if table.contains_key("version") {
  290. semver::Version::parse(table["version"].as_str().unwrap())?
  291. } else {
  292. semver::Version::parse(option_env!("CARGO_PKG_VERSION").unwrap_or("0.0.0"))?
  293. };
  294. let net_info = NetInfo { port, seeds, peers, version, localnet };
  295. ret.insert(name, net_info);
  296. }
  297. }
  298. }
  299. Ok(ret)
  300. }
  301. async fn spawn_net(
  302. name: String,
  303. info: &NetInfo,
  304. accept_addrs: &[Url],
  305. saved_hosts: &HashSet<Url>,
  306. ex: Arc<Executor<'static>>,
  307. ) -> Result<Spawn> {
  308. let mut listen_urls = vec![];
  309. // Configure listen addrs for this network
  310. for url in accept_addrs {
  311. let mut url = url.clone();
  312. url.set_port(Some(info.port))?;
  313. listen_urls.push(url);
  314. }
  315. // P2P network settings
  316. let settings = net::Settings {
  317. inbound_addrs: listen_urls.clone(),
  318. seeds: info.seeds.clone(),
  319. peers: info.peers.clone(),
  320. outbound_connections: 0,
  321. outbound_connect_timeout: 30,
  322. app_version: info.version.clone(),
  323. localnet: info.localnet,
  324. allowed_transports: vec![
  325. "tcp".to_string(),
  326. "tcp+tls".to_string(),
  327. "tor".to_string(),
  328. "tor+tls".to_string(),
  329. "nym".to_string(),
  330. "nym+tls".to_string(),
  331. ],
  332. ..Default::default()
  333. };
  334. // Create P2P instance
  335. let p2p = P2p::new(settings, ex.clone()).await;
  336. // Fill db with cached hosts
  337. let hosts: Vec<Url> = saved_hosts.iter().cloned().collect();
  338. p2p.hosts().store(&hosts).await;
  339. let addrs_str: Vec<&str> = listen_urls.iter().map(|x| x.as_str()).collect();
  340. info!(target: "lilith", "Starting seed network node for \"{}\" on {:?}", name, addrs_str);
  341. p2p.clone().start().await?;
  342. let spawn = Spawn { name, p2p };
  343. Ok(spawn)
  344. }
  345. async_daemonize!(realmain);
  346. async fn realmain(args: Args, ex: Arc<Executor<'static>>) -> Result<()> {
  347. // Pick up network settings from the TOML config
  348. let cfg_path = get_config_path(args.config, CONFIG_FILE)?;
  349. let toml_contents = std::fs::read_to_string(cfg_path)?;
  350. let configured_nets = parse_configured_networks(&toml_contents)?;
  351. if configured_nets.is_empty() {
  352. error!(target: "lilith", "No networks are enabled in config");
  353. exit(1);
  354. }
  355. // Retrieve any saved hosts for configured networks
  356. let net_names: Vec<&str> = configured_nets.keys().map(|x| x.as_str()).collect();
  357. let saved_hosts = load_hosts(&expand_path(&args.hosts_file)?, &net_names);
  358. // Spawn configured networks
  359. let mut networks = vec![];
  360. for (name, info) in &configured_nets {
  361. // TODO: Here we could actually differentiate between network versions
  362. // e.g. p2p_v3, p2p_v4, etc. Therefore we can spawn multiple networks
  363. // and they would all be version-checked, so we avoid mismatches when
  364. // seeding peers.
  365. match spawn_net(
  366. name.to_string(),
  367. info,
  368. &args.accept_addrs,
  369. saved_hosts.get(name).unwrap_or(&HashSet::new()),
  370. ex.clone(),
  371. )
  372. .await
  373. {
  374. Ok(spawn) => networks.push(spawn),
  375. Err(e) => {
  376. error!(target: "lilith", "Failed to start P2P network seed for \"{}\": {}", name, e);
  377. exit(1);
  378. }
  379. }
  380. }
  381. // Set up main daemon and background tasks
  382. let lilith = Arc::new(Lilith { networks });
  383. let mut periodic_tasks = HashMap::new();
  384. for network in &lilith.networks {
  385. let name = network.name.clone();
  386. let task = StoppableTask::new();
  387. task.clone().start(
  388. Lilith::periodic_purge(name.clone(), network.p2p.clone(), ex.clone()),
  389. |res| async move {
  390. match res {
  391. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  392. Err(e) => error!(target: "lilith", "Failed starting periodic task for \"{}\": {}", name, e),
  393. }
  394. },
  395. Error::DetachedTaskStopped,
  396. ex.clone(),
  397. );
  398. periodic_tasks.insert(network.name.clone(), task);
  399. }
  400. // JSON-RPC server
  401. info!(target: "lilith", "Starting JSON-RPC server on {}", args.rpc_listen);
  402. let rpc_task = StoppableTask::new();
  403. rpc_task.clone().start(
  404. listen_and_serve(args.rpc_listen, lilith.clone(), ex.clone()),
  405. |res| async {
  406. match res {
  407. Ok(()) | Err(Error::RPCServerStopped) => { /* Do nothing */ }
  408. Err(e) => error!(target: "lilith", "Failed starting JSON-RPC server: {}", e),
  409. }
  410. },
  411. Error::RPCServerStopped,
  412. ex.clone(),
  413. );
  414. // Signal handling for graceful termination.
  415. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  416. signals_handler.wait_termination(signals_task).await?;
  417. info!(target: "lilith", "Caught termination signal, cleaning up and exiting...");
  418. // Save in-memory hosts to tsv file
  419. save_hosts(&expand_path(&args.hosts_file)?, &lilith.networks).await;
  420. info!(target: "lilith", "Stopping JSON-RPC server...");
  421. rpc_task.stop().await;
  422. // Cleanly stop p2p networks
  423. for spawn in &lilith.networks {
  424. info!(target: "lilith", "Stopping \"{}\" periodic task", spawn.name);
  425. periodic_tasks.get(&spawn.name).unwrap().stop().await;
  426. info!(target: "lilith", "Stopping \"{}\" P2P", spawn.name);
  427. spawn.p2p.stop().await;
  428. }
  429. info!(target: "lilith", "Bye!");
  430. Ok(())
  431. }