main.rs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  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, VecDeque},
  20. path::Path,
  21. process::exit,
  22. sync::Arc,
  23. time::{Duration, Instant, SystemTime},
  24. };
  25. use async_trait::async_trait;
  26. use futures::future::join_all;
  27. use log::{debug, error, info, warn};
  28. use semver::Version;
  29. use smol::{
  30. lock::{Mutex, MutexGuard, RwLock},
  31. stream::StreamExt,
  32. Executor,
  33. };
  34. use structopt::StructOpt;
  35. use structopt_toml::StructOptToml;
  36. use tinyjson::JsonValue;
  37. use toml::Value;
  38. use url::Url;
  39. use darkfi::{
  40. async_daemonize, cli_desc,
  41. net::{self, connector::Connector, protocol::ProtocolVersion, session::Session, P2p, P2pPtr},
  42. rpc::{
  43. jsonrpc::*,
  44. server::{listen_and_serve, RequestHandler},
  45. },
  46. system::{sleep, StoppableTask, StoppableTaskPtr},
  47. util::{
  48. file::{load_file, save_file},
  49. path::{expand_path, get_config_path},
  50. },
  51. Error, Result,
  52. };
  53. const CONFIG_FILE: &str = "lilith_config.toml";
  54. const CONFIG_FILE_CONTENTS: &str = include_str!("../lilith_config.toml");
  55. /// Period in which the peer purge happens (in seconds)
  56. const CLEANSE_PERIOD: u64 = 60;
  57. /// Amount of hosts to try each purge iteration
  58. const PROBE_HOSTS_N: u32 = 10;
  59. #[derive(Clone, Debug, serde::Deserialize, StructOpt, StructOptToml)]
  60. #[serde(default)]
  61. #[structopt(name = "lilith", about = cli_desc!())]
  62. struct Args {
  63. #[structopt(long, default_value = "tcp://127.0.0.1:18927")]
  64. /// JSON-RPC listen URL
  65. pub rpc_listen: Url,
  66. #[structopt(short, long)]
  67. /// Configuration file to use
  68. pub config: Option<String>,
  69. #[structopt(long, default_value = "~/.config/darkfi/lilith_hosts.tsv")]
  70. /// Hosts .tsv file to use
  71. pub hosts_file: String,
  72. #[structopt(short, long)]
  73. /// Set log file to ouput into
  74. log: Option<String>,
  75. #[structopt(short, parse(from_occurrences))]
  76. /// Increase verbosity (-vvv supported)
  77. pub verbose: u8,
  78. }
  79. /// Struct representing a spawned P2P network
  80. struct Spawn {
  81. /// String identifier,
  82. pub name: String,
  83. /// P2P pointer
  84. pub p2p: P2pPtr,
  85. }
  86. impl Spawn {
  87. async fn addresses(&self) -> Vec<JsonValue> {
  88. self.p2p
  89. .hosts()
  90. .whitelist_fetch_all()
  91. .await
  92. .iter()
  93. .map(|(addr, url)| JsonValue::String(addr.to_string()))
  94. .collect()
  95. }
  96. async fn info(&self) -> JsonValue {
  97. let mut addr_vec = vec![];
  98. for addr in &self.p2p.settings().inbound_addrs {
  99. addr_vec.push(JsonValue::String(addr.as_ref().to_string()));
  100. }
  101. JsonValue::Object(HashMap::from([
  102. ("name".to_string(), JsonValue::String(self.name.clone())),
  103. ("urls".to_string(), JsonValue::Array(addr_vec)),
  104. ("hosts".to_string(), JsonValue::Array(self.addresses().await)),
  105. ]))
  106. }
  107. }
  108. /// Defines the network-specific settings
  109. #[derive(Clone)]
  110. struct NetInfo {
  111. /// Accept addresses the network will use
  112. pub accept_addrs: Vec<Url>,
  113. /// Other seeds to connect to
  114. pub seeds: Vec<Url>,
  115. /// Manual peers to connect to
  116. pub peers: Vec<Url>,
  117. /// Supported network version
  118. pub version: Version,
  119. /// Enable localnet hosts
  120. pub localnet: bool,
  121. }
  122. /// Struct representing the daemon
  123. struct Lilith {
  124. /// Spawned networks
  125. pub networks: Vec<Spawn>,
  126. /// JSON-RPC connection tracker
  127. pub rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  128. }
  129. impl Lilith {
  130. async fn periodic_cleanse(name: String, p2p: P2pPtr, ex: Arc<Executor<'_>>) -> Result<()> {
  131. info!(target: "lilith", "Starting periodic host cleanse task for \"{}\"", name);
  132. // Initialize a growable ring buffer(VecDeque) to store known hosts
  133. let ring_buffer = Arc::new(RwLock::new(VecDeque::<Url>::new()));
  134. loop {
  135. // Wait for next purge period
  136. sleep(CLEANSE_PERIOD).await;
  137. debug!(target: "lilith", "[{}] The Cleanse has started...", name);
  138. // Check if new hosts exist and add them to the end of the ring buffer
  139. let mut lock = ring_buffer.write().await;
  140. let hosts = p2p.clone().hosts().whitelist_fetch_all().await;
  141. if hosts.len() != lock.len() {
  142. // Since hosts are stored in a HashSet we have to check all of them
  143. for (addr, _last_seen) in hosts {
  144. if !lock.contains(&addr) {
  145. lock.push_back(addr);
  146. }
  147. }
  148. }
  149. // Pick first up to PROBE_HOSTS_N hosts from the ring buffer
  150. let mut cleansers = vec![];
  151. let mut index = 0;
  152. while index <= PROBE_HOSTS_N {
  153. match lock.pop_front() {
  154. Some(host) => cleansers.push(host),
  155. None => break,
  156. };
  157. index += 1;
  158. }
  159. // Try to connect to them. If we establish a connection, update the last_seen() field.
  160. let cleansers_str: Vec<&str> = cleansers.iter().map(|x| x.as_str()).collect();
  161. debug!(target: "lilith", "[{}] Got: {:?}", name, cleansers_str);
  162. let mut tasks = vec![];
  163. for host in &cleansers {
  164. let p2p_ = p2p.clone();
  165. let ex_ = ex.clone();
  166. let ring_buffer_ = ring_buffer.clone();
  167. tasks.push(async move {
  168. p2p_.hosts().refresh_whitelist(&host, p2p_.clone(), ex_.clone()).await;
  169. });
  170. }
  171. join_all(tasks).await;
  172. }
  173. }
  174. ///// Internal task to run a periodic purge of unreachable hosts
  175. ///// for a specific P2P network.
  176. //async fn periodic_purge(name: String, p2p: P2pPtr, ex: Arc<Executor<'_>>) -> Result<()> {
  177. // info!(target: "lilith", "Starting periodic host purge task for \"{}\"", name);
  178. // // Initialize a growable ring buffer(VecDeque) to store known hosts
  179. // let ring_buffer = Arc::new(RwLock::new(VecDeque::<Url>::new()));
  180. // loop {
  181. // // Wait for next purge period
  182. // sleep(PURGE_PERIOD).await;
  183. // debug!(target: "lilith", "[{}] The Purge has started...", name);
  184. // // Check if new hosts exist and add them to the end of the ring buffer
  185. // let mut lock = ring_buffer.write().await;
  186. // let hosts = p2p.clone().hosts().whitelist_fetch_all().await;
  187. // if hosts.len() != lock.len() {
  188. // // Since hosts are stored in a HashSet we have to check all of them
  189. // for host in hosts {
  190. // if !lock.contains(&host) {
  191. // lock.push_back(host);
  192. // }
  193. // }
  194. // }
  195. // // Pick first up to PROBE_HOSTS_N hosts from the ring buffer
  196. // let mut purgers = vec![];
  197. // let mut index = 0;
  198. // while index <= PROBE_HOSTS_N {
  199. // match lock.pop_front() {
  200. // Some(host) => purgers.push(host),
  201. // None => break,
  202. // };
  203. // index += 1;
  204. // }
  205. // // Try to connect to them. If we can't reach them, remove them from our set.
  206. // let purgers_str: Vec<&str> = purgers.iter().map(|x| x.as_str()).collect();
  207. // debug!(target: "lilith", "[{}] Got: {:?}", name, purgers_str);
  208. // let mut tasks = vec![];
  209. // for host in &purgers {
  210. // let p2p_ = p2p.clone();
  211. // let ex_ = ex.clone();
  212. // let ring_buffer_ = ring_buffer.clone();
  213. // tasks.push(async move {
  214. // let session_out = p2p_.session_outbound();
  215. // let session_weak = Arc::downgrade(&session_out);
  216. // let connector = Connector::new(p2p_.settings(), session_weak);
  217. // debug!(target: "lilith", "Connecting to {}", host);
  218. // match connector.connect(host).await {
  219. // Ok((_url, channel)) => {
  220. // debug!(target: "lilith", "Connected successfully!");
  221. // let proto_ver = ProtocolVersion::new(
  222. // channel.clone(),
  223. // p2p_.settings().clone(),
  224. // //p2p_.hosts().clone(),
  225. // )
  226. // .await;
  227. // let handshake_task = session_out.perform_handshake_protocols(
  228. // proto_ver,
  229. // channel.clone(),
  230. // ex_.clone(),
  231. // );
  232. // channel.clone().start(ex_.clone());
  233. // match handshake_task.await {
  234. // Ok(()) => {
  235. // debug!(target: "lilith", "Handshake success! Stopping channel.");
  236. // channel.stop().await;
  237. // // Push host back to the ring buffer
  238. // ring_buffer_.write().await.push_back(host.clone());
  239. // }
  240. // Err(e) => {
  241. // debug!(target: "lilith", "Handshake failure! {}", e);
  242. // p2p_.hosts().remove(host).await;
  243. // }
  244. // }
  245. // }
  246. // Err(e) => {
  247. // debug!(target: "lilith", "Failed to connect to {}, removing from set ({})", host, e);
  248. // // Remove from hosts set
  249. // p2p_.hosts().remove(host).await;
  250. // }
  251. // }
  252. // });
  253. // }
  254. // join_all(tasks).await;
  255. // }
  256. //}
  257. // RPCAPI:
  258. // Returns all spawned networks names with their node addresses.
  259. // --> {"jsonrpc": "2.0", "method": "spawns", "params": [], "id": 42}
  260. // <-- {"jsonrpc": "2.0", "result": {"spawns": spawns_info}, "id": 42}
  261. async fn spawns(&self, id: u16, _params: JsonValue) -> JsonResult {
  262. let mut spawns = vec![];
  263. for spawn in &self.networks {
  264. spawns.push(spawn.info().await);
  265. }
  266. let json =
  267. JsonValue::Object(HashMap::from([("spawns".to_string(), JsonValue::Array(spawns))]));
  268. JsonResponse::new(json, id).into()
  269. }
  270. }
  271. #[async_trait]
  272. impl RequestHandler for Lilith {
  273. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  274. match req.method.as_str() {
  275. "ping" => return self.pong(req.id, req.params).await,
  276. "spawns" => return self.spawns(req.id, req.params).await,
  277. _ => return JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  278. }
  279. }
  280. async fn connections_mut(&self) -> MutexGuard<'_, HashSet<StoppableTaskPtr>> {
  281. self.rpc_connections.lock().await
  282. }
  283. }
  284. ///// Attempt to read existing hosts tsv
  285. //fn load_hosts(path: &Path, networks: &[&str]) -> HashMap<String, HashSet<Url>> {
  286. // let mut saved_hosts = HashMap::new();
  287. //
  288. // let contents = load_file(path);
  289. // if let Err(e) = contents {
  290. // warn!(target: "lilith", "Failed retrieving saved hosts: {}", e);
  291. // return saved_hosts
  292. // }
  293. //
  294. // for line in contents.unwrap().lines() {
  295. // let data: Vec<&str> = line.split('\t').collect();
  296. // if networks.contains(&data[0]) {
  297. // let mut hosts = match saved_hosts.get(data[0]) {
  298. // Some(hosts) => hosts.clone(),
  299. // None => HashSet::new(),
  300. // };
  301. //
  302. // let url = match Url::parse(data[1]) {
  303. // Ok(u) => u,
  304. // Err(e) => {
  305. // warn!(target: "lilith", "Skipping malformed url: {} ({})", data[1], e);
  306. // continue
  307. // }
  308. // };
  309. //
  310. // hosts.insert(url);
  311. // saved_hosts.insert(data[0].to_string(), hosts);
  312. // }
  313. // }
  314. //
  315. // saved_hosts
  316. //}
  317. fn load_hosts(path: &Path, networks: &[&str]) -> HashMap<String, Vec<(Url, u64)>> {
  318. let mut saved_hosts = HashMap::new();
  319. let contents = load_file(path);
  320. if let Err(e) = contents {
  321. warn!(target: "lilith", "Failed retrieving saved hosts: {}", e);
  322. return saved_hosts
  323. }
  324. for line in contents.unwrap().lines() {
  325. let data: Vec<&str> = line.split('\t').collect();
  326. debug!(target: "lilith", "::load_hosts()::data\"{:?}\"", data);
  327. if networks.contains(&data[0]) {
  328. let mut hosts = match saved_hosts.get(data[0]) {
  329. Some(hosts) => hosts.clone(),
  330. None => Vec::new(),
  331. };
  332. let url = match Url::parse(data[1]) {
  333. Ok(u) => u,
  334. Err(e) => {
  335. warn!(target: "lilith", "Skipping malformed url: {} ({})", data[1], e);
  336. continue
  337. }
  338. };
  339. let last_seen = match data[2].parse::<u64>() {
  340. Ok(u) => u,
  341. Err(e) => {
  342. warn!(target: "lilith", "Skipping malformed timestamp: {} ({})", data[2], e);
  343. continue
  344. }
  345. };
  346. hosts.push((url, last_seen));
  347. saved_hosts.insert(data[0].to_string(), hosts);
  348. }
  349. }
  350. saved_hosts
  351. }
  352. //async fn save_hosts(path: &Path, networks: &[Spawn]) {
  353. // let mut tsv = String::new();
  354. //
  355. // for spawn in networks {
  356. // for host in spawn.p2p.hosts().fetch_all().await {
  357. // tsv.push_str(&format!("{}\t{}\n", spawn.name, host.as_str()));
  358. // }
  359. // }
  360. //
  361. // if !tsv.eq("") {
  362. // info!(target: "lilith", "Saving current hosts of spawned networks to: {:?}", path);
  363. // if let Err(e) = save_file(path, &tsv) {
  364. // error!(target: "lilith", "Failed saving hosts: {}", e);
  365. // }
  366. // }
  367. //}
  368. async fn save_hosts(path: &Path, networks: &[Spawn]) {
  369. let mut tsv = String::new();
  370. for spawn in networks {
  371. for (host, last_seen) in spawn.p2p.hosts().whitelist_fetch_all().await {
  372. tsv.push_str(&format!("{}\t{}\t{}\n", spawn.name, host.as_str(), last_seen));
  373. }
  374. }
  375. if !tsv.eq("") {
  376. info!(target: "lilith", "Saving current hosts of spawned networks to: {:?}", path);
  377. if let Err(e) = save_file(path, &tsv) {
  378. error!(target: "lilith", "Failed saving hosts: {}", e);
  379. }
  380. }
  381. }
  382. /// Parse a TOML string for any configured network and return a map containing
  383. /// said configurations.
  384. fn parse_configured_networks(data: &str) -> Result<HashMap<String, NetInfo>> {
  385. let mut ret = HashMap::new();
  386. if let Value::Table(map) = toml::from_str(data)? {
  387. if map.contains_key("network") && map["network"].is_table() {
  388. for net in map["network"].as_table().unwrap() {
  389. info!(target: "lilith", "Found configuration for network: {}", net.0);
  390. let table = net.1.as_table().unwrap();
  391. if !table.contains_key("accept_addrs") {
  392. warn!(target: "lilith", "Network accept addrs are mandatory, skipping network.");
  393. continue
  394. }
  395. let name = net.0.to_string();
  396. let accept_addrs: Vec<Url> = table["accept_addrs"]
  397. .as_array()
  398. .unwrap()
  399. .iter()
  400. .map(|x| Url::parse(x.as_str().unwrap()).unwrap())
  401. .collect();
  402. let mut seeds = vec![];
  403. if table.contains_key("seeds") {
  404. if let Some(s) = table["seeds"].as_array() {
  405. for seed in s {
  406. if let Some(u) = seed.as_str() {
  407. if let Ok(url) = Url::parse(u) {
  408. seeds.push(url);
  409. }
  410. }
  411. }
  412. }
  413. }
  414. let mut peers = vec![];
  415. if table.contains_key("peers") {
  416. if let Some(p) = table["peers"].as_array() {
  417. for peer in p {
  418. if let Some(u) = peer.as_str() {
  419. if let Ok(url) = Url::parse(u) {
  420. peers.push(url);
  421. }
  422. }
  423. }
  424. }
  425. }
  426. let localnet = if table.contains_key("localnet") {
  427. table["localnet"].as_bool().unwrap()
  428. } else {
  429. false
  430. };
  431. let version = if table.contains_key("version") {
  432. semver::Version::parse(table["version"].as_str().unwrap())?
  433. } else {
  434. semver::Version::parse(option_env!("CARGO_PKG_VERSION").unwrap_or("0.0.0"))?
  435. };
  436. let net_info = NetInfo { accept_addrs, seeds, peers, version, localnet };
  437. ret.insert(name, net_info);
  438. }
  439. }
  440. }
  441. Ok(ret)
  442. }
  443. //async fn spawn_net(
  444. // name: String,
  445. // info: &NetInfo,
  446. // saved_hosts: Vec<(Url, u64)>,
  447. // ex: Arc<Executor<'static>>,
  448. //) -> Result<Spawn> {
  449. // let mut listen_urls = vec![];
  450. //
  451. // // Configure listen addrs for this network
  452. // for url in &info.accept_addrs {
  453. // listen_urls.push(url.clone());
  454. // }
  455. //
  456. // // P2P network settings
  457. // let settings = net::Settings {
  458. // inbound_addrs: listen_urls.clone(),
  459. // seeds: info.seeds.clone(),
  460. // peers: info.peers.clone(),
  461. // outbound_connections: 0,
  462. // outbound_connect_timeout: 30,
  463. // inbound_connections: 512,
  464. // app_version: info.version.clone(),
  465. // localnet: info.localnet,
  466. // allowed_transports: vec![
  467. // "tcp".to_string(),
  468. // "tcp+tls".to_string(),
  469. // "tor".to_string(),
  470. // "tor+tls".to_string(),
  471. // "nym".to_string(),
  472. // "nym+tls".to_string(),
  473. // ],
  474. // ..Default::default()
  475. // };
  476. //
  477. // // Create P2P instance
  478. // let p2p = P2p::new(settings, ex.clone()).await;
  479. //
  480. // // Fill db with cached hosts
  481. // let hosts: Vec<(Url, u64)> = saved_hosts.iter().cloned().collect();
  482. // p2p.hosts().greylist_store(&hosts).await;
  483. //
  484. // let addrs_str: Vec<&str> = listen_urls.iter().map(|x| x.as_str()).collect();
  485. // info!(target: "lilith", "Starting seed network node for \"{}\" on {:?}", name, addrs_str);
  486. // p2p.clone().start().await?;
  487. //
  488. // let spawn = Spawn { name, p2p };
  489. // Ok(spawn)
  490. //}
  491. //
  492. async fn spawn_net(
  493. name: String,
  494. info: &NetInfo,
  495. saved_hosts: &Vec<(Url, u64)>,
  496. ex: Arc<Executor<'static>>,
  497. ) -> Result<Spawn> {
  498. let mut listen_urls = vec![];
  499. // Configure listen addrs for this network
  500. for url in &info.accept_addrs {
  501. listen_urls.push(url.clone());
  502. }
  503. // P2P network settings
  504. let settings = net::Settings {
  505. inbound_addrs: listen_urls.clone(),
  506. seeds: info.seeds.clone(),
  507. peers: info.peers.clone(),
  508. outbound_connections: 0,
  509. outbound_connect_timeout: 30,
  510. inbound_connections: 512,
  511. app_version: info.version.clone(),
  512. localnet: info.localnet,
  513. allowed_transports: vec![
  514. "tcp".to_string(),
  515. "tcp+tls".to_string(),
  516. "tor".to_string(),
  517. "tor+tls".to_string(),
  518. "nym".to_string(),
  519. "nym+tls".to_string(),
  520. ],
  521. ..Default::default()
  522. };
  523. // Create P2P instance
  524. let p2p = P2p::new(settings, ex.clone()).await;
  525. // Fill db with cached hosts
  526. let hosts: Vec<(Url, u64)> = saved_hosts.iter().cloned().collect();
  527. p2p.hosts().greylist_store(&hosts).await;
  528. let addrs_str: Vec<&str> = listen_urls.iter().map(|x| x.as_str()).collect();
  529. info!(target: "lilith", "Starting seed network node for \"{}\" on {:?}", name, addrs_str);
  530. p2p.clone().start().await?;
  531. let spawn = Spawn { name, p2p };
  532. Ok(spawn)
  533. }
  534. //async_daemonize!(realmain);
  535. //async fn realmain(args: Args, ex: Arc<Executor<'static>>) -> Result<()> {
  536. // // Pick up network settings from the TOML config
  537. // let cfg_path = get_config_path(args.config, CONFIG_FILE)?;
  538. // let toml_contents = std::fs::read_to_string(cfg_path)?;
  539. // let configured_nets = parse_configured_networks(&toml_contents)?;
  540. //
  541. // if configured_nets.is_empty() {
  542. // error!(target: "lilith", "No networks are enabled in config");
  543. // exit(1);
  544. // }
  545. //
  546. // // Retrieve any saved hosts for configured networks
  547. // let net_names: Vec<&str> = configured_nets.keys().map(|x| x.as_str()).collect();
  548. // let saved_hosts = load_hosts(&expand_path(&args.hosts_file)?, &net_names);
  549. //
  550. // // Spawn configured networks
  551. // let mut networks = vec![];
  552. // for (name, info) in &configured_nets {
  553. // // TODO: Here we could actually differentiate between network versions
  554. // // e.g. p2p_v3, p2p_v4, etc. Therefore we can spawn multiple networks
  555. // // and they would all be version-checked, so we avoid mismatches when
  556. // // seeding peers.
  557. // match spawn_net(
  558. // name.to_string(),
  559. // info,
  560. // saved_hosts.get(name).unwrap_or(&HashSet::new()),
  561. // ex.clone(),
  562. // )
  563. // .await
  564. // {
  565. // Ok(spawn) => networks.push(spawn),
  566. // Err(e) => {
  567. // error!(target: "lilith", "Failed to start P2P network seed for \"{}\": {}", name, e);
  568. // exit(1);
  569. // }
  570. // }
  571. // }
  572. //
  573. // // Set up main daemon and background tasks
  574. // let lilith = Arc::new(Lilith { networks, rpc_connections: Mutex::new(HashSet::new()) });
  575. // let mut periodic_tasks = HashMap::new();
  576. // for network in &lilith.networks {
  577. // let name = network.name.clone();
  578. // let task = StoppableTask::new();
  579. // task.clone().start(
  580. // Lilith::periodic_purge(name.clone(), network.p2p.clone(), ex.clone()),
  581. // |res| async move {
  582. // match res {
  583. // Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  584. // Err(e) => error!(target: "lilith", "Failed starting periodic task for \"{}\": {}", name, e),
  585. // }
  586. // },
  587. // Error::DetachedTaskStopped,
  588. // ex.clone(),
  589. // );
  590. // periodic_tasks.insert(network.name.clone(), task);
  591. // }
  592. //
  593. // // JSON-RPC server
  594. // info!(target: "lilith", "Starting JSON-RPC server on {}", args.rpc_listen);
  595. // let lilith_ = lilith.clone();
  596. // let rpc_task = StoppableTask::new();
  597. // rpc_task.clone().start(
  598. // listen_and_serve(args.rpc_listen, lilith.clone(), None, ex.clone()),
  599. // |res| async move {
  600. // match res {
  601. // Ok(()) | Err(Error::RpcServerStopped) => lilith_.stop_connections().await,
  602. // Err(e) => error!(target: "lilith", "Failed starting JSON-RPC server: {}", e),
  603. // }
  604. // },
  605. // Error::RpcServerStopped,
  606. // ex.clone(),
  607. // );
  608. //
  609. // // Signal handling for graceful termination.
  610. // let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  611. // signals_handler.wait_termination(signals_task).await?;
  612. // info!(target: "lilith", "Caught termination signal, cleaning up and exiting...");
  613. //
  614. // // Save in-memory hosts to tsv file
  615. // save_hosts(&expand_path(&args.hosts_file)?, &lilith.networks).await;
  616. //
  617. // info!(target: "lilith", "Stopping JSON-RPC server...");
  618. // rpc_task.stop().await;
  619. //
  620. // // Cleanly stop p2p networks
  621. // for spawn in &lilith.networks {
  622. // info!(target: "lilith", "Stopping \"{}\" periodic task", spawn.name);
  623. // periodic_tasks.get(&spawn.name).unwrap().stop().await;
  624. // info!(target: "lilith", "Stopping \"{}\" P2P", spawn.name);
  625. // spawn.p2p.stop().await;
  626. // }
  627. //
  628. // info!(target: "lilith", "Bye!");
  629. // Ok(())
  630. //}
  631. async_daemonize!(realmain);
  632. async fn realmain(args: Args, ex: Arc<Executor<'static>>) -> Result<()> {
  633. // Pick up network settings from the TOML config
  634. let cfg_path = get_config_path(args.config, CONFIG_FILE)?;
  635. let toml_contents = std::fs::read_to_string(cfg_path)?;
  636. let configured_nets = parse_configured_networks(&toml_contents)?;
  637. if configured_nets.is_empty() {
  638. error!(target: "lilith", "No networks are enabled in config");
  639. exit(1);
  640. }
  641. // Retrieve any saved hosts for configured networks
  642. let net_names: Vec<&str> = configured_nets.keys().map(|x| x.as_str()).collect();
  643. let saved_hosts = load_hosts(&expand_path(&args.hosts_file)?, &net_names);
  644. // Spawn configured networks
  645. let mut networks = vec![];
  646. for (name, info) in &configured_nets {
  647. // TODO: Here we could actually differentiate between network versions
  648. // e.g. p2p_v3, p2p_v4, etc. Therefore we can spawn multiple networks
  649. // and they would all be version-checked, so we avoid mismatches when
  650. // seeding peers.
  651. match spawn_net(
  652. name.to_string(),
  653. info,
  654. saved_hosts.get(name).unwrap_or(&Vec::new()),
  655. ex.clone(),
  656. )
  657. .await
  658. {
  659. Ok(spawn) => networks.push(spawn),
  660. Err(e) => {
  661. error!(target: "lilith", "Failed to start P2P network seed for \"{}\": {}", name, e);
  662. exit(1);
  663. }
  664. }
  665. }
  666. // Set up main daemon and background tasks
  667. let lilith = Arc::new(Lilith { networks, rpc_connections: Mutex::new(HashSet::new()) });
  668. let mut periodic_tasks = HashMap::new();
  669. for network in &lilith.networks {
  670. let name = network.name.clone();
  671. let task = StoppableTask::new();
  672. task.clone().start(
  673. Lilith::periodic_cleanse(name.clone(), network.p2p.clone(), ex.clone()),
  674. |res| async move {
  675. match res {
  676. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  677. Err(e) => error!(target: "lilith", "Failed starting periodic task for \"{}\": {}", name, e),
  678. }
  679. },
  680. Error::DetachedTaskStopped,
  681. ex.clone(),
  682. );
  683. periodic_tasks.insert(network.name.clone(), task);
  684. }
  685. // JSON-RPC server
  686. info!(target: "lilith", "Starting JSON-RPC server on {}", args.rpc_listen);
  687. let lilith_ = lilith.clone();
  688. let rpc_task = StoppableTask::new();
  689. rpc_task.clone().start(
  690. listen_and_serve(args.rpc_listen, lilith.clone(), None, ex.clone()),
  691. |res| async move {
  692. match res {
  693. Ok(()) | Err(Error::RpcServerStopped) => lilith_.stop_connections().await,
  694. Err(e) => error!(target: "lilith", "Failed starting JSON-RPC server: {}", e),
  695. }
  696. },
  697. Error::RpcServerStopped,
  698. ex.clone(),
  699. );
  700. // Signal handling for graceful termination.
  701. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  702. signals_handler.wait_termination(signals_task).await?;
  703. info!(target: "lilith", "Caught termination signal, cleaning up and exiting...");
  704. // Save in-memory hosts to tsv file
  705. save_hosts(&expand_path(&args.hosts_file)?, &lilith.networks).await;
  706. info!(target: "lilith", "Stopping JSON-RPC server...");
  707. rpc_task.stop().await;
  708. // Cleanly stop p2p networks
  709. for spawn in &lilith.networks {
  710. info!(target: "lilith", "Stopping \"{}\" periodic task", spawn.name);
  711. periodic_tasks.get(&spawn.name).unwrap().stop().await;
  712. info!(target: "lilith", "Stopping \"{}\" P2P", spawn.name);
  713. spawn.p2p.stop().await;
  714. }
  715. info!(target: "lilith", "Bye!");
  716. Ok(())
  717. }