main.rs 19 KB

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