main.rs 16 KB

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