main.rs 20 KB

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