main.rs 16 KB

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