main.rs 17 KB

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