refine_session.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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. //! TODO: doc
  19. use std::{
  20. collections::HashMap,
  21. sync::Arc,
  22. time::{Duration, Instant, UNIX_EPOCH},
  23. };
  24. use async_trait::async_trait;
  25. use log::{debug, warn};
  26. use smol::lock::Mutex;
  27. use url::Url;
  28. use super::super::p2p::{P2p, P2pPtr};
  29. use crate::{
  30. net::{
  31. connector::Connector,
  32. hosts::{HostColor, HostState},
  33. protocol::ProtocolVersion,
  34. session::{Session, SessionBitFlag, SESSION_REFINE},
  35. },
  36. system::{sleep, timeout::timeout, LazyWeak, StoppableTask, StoppableTaskPtr},
  37. Error,
  38. };
  39. pub type RefineSessionPtr = Arc<RefineSession>;
  40. pub struct RefineSession {
  41. /// Weak pointer to parent p2p object
  42. pub(in crate::net) p2p: LazyWeak<P2p>,
  43. /// Task that periodically checks entries in the greylist.
  44. pub(in crate::net) refinery: Arc<GreylistRefinery>,
  45. /// Task that periodically checks our external addresses.
  46. pub(in crate::net) self_handshake: Arc<SelfHandshake>,
  47. }
  48. impl RefineSession {
  49. pub fn new() -> RefineSessionPtr {
  50. let self_ = Arc::new(Self {
  51. p2p: LazyWeak::new(),
  52. refinery: GreylistRefinery::new(),
  53. self_handshake: SelfHandshake::new(),
  54. });
  55. self_.self_handshake.session.init(self_.clone());
  56. self_.refinery.session.init(self_.clone());
  57. self_
  58. }
  59. pub(crate) async fn start(self: Arc<Self>) {
  60. debug!(target: "net::refine_session", "Starting greylist refinery process");
  61. self.refinery.clone().start().await;
  62. debug!(target: "net::refine_session", "Starting self handshake process");
  63. self.self_handshake.clone().start().await;
  64. }
  65. pub(crate) async fn stop(&self) {
  66. debug!(target: "net::refine_session", "Stopping refinery process");
  67. self.refinery.clone().stop().await;
  68. debug!(target: "net::refine_session", "Stopping self handshake process");
  69. self.self_handshake.clone().stop().await;
  70. }
  71. // TODO: doc and explain why it's public
  72. pub async fn handshake_node(self: Arc<Self>, addr: Url, p2p: P2pPtr) -> bool {
  73. let self_ = Arc::downgrade(&self);
  74. let connector = Connector::new(self.p2p().settings(), self_);
  75. debug!(target: "net::refinery::handshake_node()", "Attempting to connect to {}", addr);
  76. match connector.connect(&addr).await {
  77. Ok((url, channel)) => {
  78. debug!(target: "net::refinery::handshake_node()", "Successfully created a channel with {}", url);
  79. // First initialize the version protocol and its Version, Verack subscribers.
  80. let proto_ver = ProtocolVersion::new(channel.clone(), p2p.settings()).await;
  81. debug!(target: "net::refinery::handshake_node()", "Performing handshake protocols with {}", url);
  82. // Then run the version exchange, store the channel and subscribe to a stop signal.
  83. let handshake_task =
  84. self.perform_handshake_protocols(proto_ver, channel.clone(), p2p.executor());
  85. debug!(target: "net::refinery::handshake_node()", "Starting channel {}", url);
  86. channel.clone().start(p2p.executor());
  87. // Ensure the channel gets stopped by adding a timeout to the handshake. Otherwise if
  88. // the handshake does not finish channel.stop() will never get called, resulting in
  89. // zombie processes.
  90. let result = timeout(Duration::from_secs(5), handshake_task).await;
  91. debug!(target: "net::refinery::handshake_node()", "Stopping channel {}", url);
  92. channel.stop().await;
  93. match result {
  94. Ok(_) => {
  95. debug!(target: "net::refinery::handshake_node()", "Handshake success!");
  96. true
  97. }
  98. Err(e) => {
  99. debug!(target: "net::refinery::handshake_node()", "Handshake err: {}", e);
  100. false
  101. }
  102. }
  103. }
  104. Err(e) => {
  105. debug!(target: "net::refinery::handshake_node()", "Failed to connect to {}, ({})", addr, e);
  106. false
  107. }
  108. }
  109. }
  110. }
  111. #[async_trait]
  112. impl Session for RefineSession {
  113. fn p2p(&self) -> P2pPtr {
  114. self.p2p.upgrade()
  115. }
  116. fn type_id(&self) -> SessionBitFlag {
  117. SESSION_REFINE
  118. }
  119. }
  120. /// Periodically probes entries in the greylist.
  121. ///
  122. /// Randomly selects a greylist entry and tries to establish a local
  123. /// connection to it using the method handshake_node(), which creates a
  124. /// channel and does a version exchange using `perform_handshake_protocols()`.
  125. ///
  126. /// If successful, the entry is removed from the greylist and added to the
  127. /// whitelist with an updated last_seen timestamp. If non-successful, the
  128. /// entry is removed from the greylist.
  129. pub struct GreylistRefinery {
  130. /// Weak pointer to parent object
  131. session: LazyWeak<RefineSession>,
  132. process: StoppableTaskPtr,
  133. }
  134. impl GreylistRefinery {
  135. pub fn new() -> Arc<Self> {
  136. Arc::new(Self { session: LazyWeak::new(), process: StoppableTask::new() })
  137. }
  138. pub async fn start(self: Arc<Self>) {
  139. match self.p2p().hosts().container.load_all(&self.p2p().settings().hostlist).await {
  140. Ok(()) => {
  141. debug!(target: "net::refinery::start()", "Load hosts successful!");
  142. }
  143. Err(e) => {
  144. warn!(target: "net::refinery::start()", "Error loading hosts {}", e);
  145. }
  146. }
  147. let ex = self.p2p().executor();
  148. self.process.clone().start(
  149. async move {
  150. self.run().await;
  151. unreachable!();
  152. },
  153. // Ignore stop handler
  154. |_| async {},
  155. Error::NetworkServiceStopped,
  156. ex,
  157. );
  158. }
  159. pub async fn stop(self: Arc<Self>) {
  160. debug!(target: "net::refinery", "Stopping refinery");
  161. self.process.stop().await;
  162. match self.p2p().hosts().container.save_all(&self.p2p().settings().hostlist).await {
  163. Ok(()) => {
  164. debug!(target: "net::refinery::stop()", "Save hosts successful!");
  165. }
  166. Err(e) => {
  167. warn!(target: "net::refinery::stop()", "Error saving hosts {}", e);
  168. }
  169. }
  170. }
  171. // Randomly select a peer on the greylist and probe it. This method will remove from the
  172. // greylist and store on the whitelist providing the peer is responsive.
  173. async fn run(self: Arc<Self>) {
  174. let settings = self.p2p().settings();
  175. let hosts = self.p2p().hosts();
  176. loop {
  177. sleep(settings.greylist_refinery_interval).await;
  178. if hosts.container.is_empty(HostColor::Grey).await {
  179. debug!(target: "net::refinery",
  180. "Greylist is empty! Cannot start refinery process");
  181. continue
  182. }
  183. // Pause the refinery if we've had zero connections for longer than the configured
  184. // limit.
  185. let offline_limit = Duration::from_secs(settings.time_with_no_connections);
  186. let offline_timer = Instant::now().duration_since(*hosts.last_connection.read().await);
  187. if hosts.channels().await.is_empty() && offline_timer >= offline_limit {
  188. warn!(target: "net::refinery", "No connections for {}s. GreylistRefinery paused.",
  189. offline_timer.as_secs());
  190. // It is neccessary to clear suspended hosts at this point, otherwise these
  191. // hosts cannot be connected to in Outbound Session. Failure to do this could
  192. // result in the refinery being paused forver (since connections could never be
  193. // made).
  194. let suspended_hosts = hosts.suspended().await;
  195. for host in suspended_hosts {
  196. hosts.unregister(&host).await;
  197. }
  198. continue
  199. }
  200. // Only attempt to refine peers that match our transports.
  201. match hosts
  202. .container
  203. .fetch_random_with_schemes(HostColor::Grey, &settings.allowed_transports)
  204. .await
  205. {
  206. Some((entry, position)) => {
  207. let url = &entry.0;
  208. if let Err(e) = hosts.try_register(url.clone(), HostState::Refine).await {
  209. debug!(target: "net::refinery", "Unable to refine addr={}, err={}",
  210. url.clone(), e);
  211. continue
  212. }
  213. if !self.session().handshake_node(url.clone(), self.p2p().clone()).await {
  214. hosts.container.remove(HostColor::Grey, url, position).await;
  215. debug!(
  216. target: "net::refinery",
  217. "Peer {} is non-responsive. Removed from greylist", url,
  218. );
  219. // Remove this entry from HostRegistry to avoid this host getting
  220. // stuck in the Refining state.
  221. //
  222. // It is not necessary to call this when the refinery passes, since the
  223. // state will be changed to Connected.
  224. hosts.unregister(url).await;
  225. continue
  226. }
  227. debug!(
  228. target: "net::refinery",
  229. "Peer {} is responsive. Adding to whitelist", url,
  230. );
  231. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  232. // Add to the whitelist and remove from the greylist.
  233. hosts.move_host(url, last_seen, HostColor::White).await.unwrap();
  234. hosts.unregister(url).await;
  235. debug!(target: "net::refinery", "GreylistRefinery complete!");
  236. continue
  237. }
  238. None => {
  239. debug!(target: "net::refinery", "No matching greylist entries found. Cannot proceed with refinery");
  240. continue
  241. }
  242. }
  243. }
  244. }
  245. fn session(&self) -> RefineSessionPtr {
  246. self.session.upgrade()
  247. }
  248. fn p2p(&self) -> P2pPtr {
  249. self.session().p2p()
  250. }
  251. }
  252. /// Periodically try to do a version exchange with our own external
  253. /// addresses. If the version exchange is successful, take a timestamp and
  254. /// save it along with the external addresses. Each address along with its
  255. /// timestamp (the `last_seen` data field) is sent in to other nodes in
  256. /// ProtocolAddr and ProtocolSeed.
  257. ///
  258. /// On first run, SelfHandshake will immediately conduct a version exchange
  259. /// with our external addresses, and if successful update the last_seen
  260. /// field. The process will wait [TODO: self_handshake_interval) before retrying.
  261. ///
  262. /// There are two situations in which this can fail:
  263. ///
  264. /// 1. If our external address is misconfigured
  265. /// 2. If we have reached our inbound connection limit.
  266. ///
  267. /// If our external address is misconfigured, doing a version exchange
  268. /// with ourselves will not work and so the external addresses will not
  269. /// be shared with other nodes.
  270. ///
  271. /// If we have reached our inbound connection limit, the external address
  272. /// will continue to be broadcast with an older `last_seen` (from before
  273. /// our inbound connection was reached).
  274. pub struct SelfHandshake {
  275. process: StoppableTaskPtr,
  276. session: LazyWeak<RefineSession>,
  277. pub(in crate::net) addrs: Mutex<HashMap<Url, u64>>,
  278. }
  279. impl SelfHandshake {
  280. fn new() -> Arc<Self> {
  281. Arc::new(Self {
  282. process: StoppableTask::new(),
  283. session: LazyWeak::new(),
  284. addrs: Mutex::new(HashMap::new()),
  285. })
  286. }
  287. async fn start(self: Arc<Self>) {
  288. let ex = self.session().p2p().executor();
  289. self.process.clone().start(
  290. async move {
  291. self.run().await;
  292. unreachable!();
  293. },
  294. // Ignore stop handler
  295. |_| async {},
  296. Error::NetworkServiceStopped,
  297. ex,
  298. );
  299. }
  300. async fn stop(self: Arc<Self>) {
  301. self.process.stop().await
  302. }
  303. async fn run(self: Arc<Self>) {
  304. let external_addrs = self.session().p2p().settings().external_addrs.clone();
  305. let mut current_attempt = 0;
  306. loop {
  307. if current_attempt >= 1 {
  308. // TODO: make this a configurable interval
  309. sleep(600).await;
  310. }
  311. // Only proceed if the external address is configured.
  312. if external_addrs.is_empty() {
  313. current_attempt += 1;
  314. continue
  315. }
  316. for addr in external_addrs.iter() {
  317. debug!(target: "net::refine_session::self_handshake",
  318. "Attempting a version exchange addr={}", addr);
  319. if self.session().handshake_node(addr.clone(), self.session().p2p()).await {
  320. debug!(target: "net::refine_session::self_handshake",
  321. "Version exchange successful! Updating last seen addr={}", addr);
  322. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  323. let mut addrs = self.addrs.lock().await;
  324. if addrs.contains_key(addr) {
  325. let val = addrs.get_mut(addr).unwrap();
  326. *val = last_seen;
  327. }
  328. addrs.insert(addr.clone(), last_seen);
  329. } else {
  330. // Either our external addr is invalid or our max inbound
  331. // connection count has been reached.
  332. warn!(target: "net::refine_session::self_handshake",
  333. "Version exchange failed! addr={}", addr);
  334. }
  335. }
  336. current_attempt += 1;
  337. }
  338. }
  339. fn session(&self) -> RefineSessionPtr {
  340. self.session.upgrade()
  341. }
  342. }