main.rs 17 KB

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