refinery.rs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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. use std::{sync::Arc, time::UNIX_EPOCH};
  19. use log::{debug, warn};
  20. use url::Url;
  21. use super::super::p2p::{P2p, P2pPtr};
  22. use crate::{
  23. net::{connector::Connector, protocol::ProtocolVersion, session::Session},
  24. system::{sleep, LazyWeak, StoppableTask, StoppableTaskPtr},
  25. Error,
  26. };
  27. pub type GreylistRefineryPtr = Arc<GreylistRefinery>;
  28. /// Probe random peers on the greylist. If a peer is responsive, update the last_seen field and
  29. /// add it to the whitelist. If a node does not respond, remove it from the greylist.
  30. /// Called periodically.
  31. pub struct GreylistRefinery {
  32. /// Weak pointer to parent p2p object
  33. pub(in crate::net) p2p: LazyWeak<P2p>,
  34. process: StoppableTaskPtr,
  35. }
  36. impl GreylistRefinery {
  37. pub fn new() -> Arc<Self> {
  38. Arc::new(Self { p2p: LazyWeak::new(), process: StoppableTask::new() })
  39. }
  40. pub async fn start(self: Arc<Self>) {
  41. match self.p2p().hosts().load_hosts().await {
  42. Ok(()) => {
  43. debug!(target: "net::refinery::start()", "Load hosts successful!");
  44. }
  45. Err(e) => {
  46. warn!(target: "net::refinery::start()", "Error loading hosts {}", e);
  47. }
  48. }
  49. let ex = self.p2p().executor();
  50. self.process.clone().start(
  51. async move {
  52. self.run().await;
  53. unreachable!();
  54. },
  55. // Ignore stop handler
  56. |_| async {},
  57. Error::NetworkServiceStopped,
  58. ex,
  59. );
  60. }
  61. pub async fn stop(self: Arc<Self>) {
  62. self.process.stop().await;
  63. match self.p2p().hosts().save_hosts().await {
  64. Ok(()) => {
  65. debug!(target: "net::refinery::stop()", "Save hosts successful!");
  66. }
  67. Err(e) => {
  68. warn!(target: "net::refinery::stop()", "Error saving hosts {}", e);
  69. }
  70. }
  71. }
  72. // Randomly select a peer on the greylist and probe it.
  73. async fn run(self: Arc<Self>) {
  74. loop {
  75. sleep(self.p2p().settings().greylist_refinery_interval).await;
  76. let hosts = self.p2p().hosts();
  77. if hosts.is_empty_greylist().await {
  78. warn!(target: "net::refinery::run()",
  79. "Greylist is empty! Cannot start refinery process");
  80. continue
  81. }
  82. let (entry, position) = hosts.greylist_fetch_random().await;
  83. let url = &entry.0;
  84. if !ping_node(url, self.p2p().clone()).await {
  85. let mut greylist = hosts.greylist.write().await;
  86. greylist.remove(position);
  87. debug!(target: "net::refinery::run()", "Peer {} is non-responsive. Removed from greylist", url);
  88. continue
  89. }
  90. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  91. // Append to the whitelist.
  92. hosts.whitelist_store_or_update(&[(url.clone(), last_seen)]).await;
  93. // Remove whitelisted peer from the greylist.
  94. hosts.greylist_remove(url, position).await;
  95. }
  96. }
  97. fn p2p(&self) -> P2pPtr {
  98. self.p2p.upgrade()
  99. }
  100. }
  101. // Ping a node to check it's online.
  102. pub async fn ping_node(addr: &Url, p2p: P2pPtr) -> bool {
  103. let session_outbound = p2p.session_outbound();
  104. let parent = Arc::downgrade(&session_outbound);
  105. let connector = Connector::new(p2p.settings(), parent);
  106. debug!(target: "net::refinery::ping_node()", "Attempting to connect to {}", addr);
  107. match connector.connect(addr).await {
  108. Ok((_url, channel)) => {
  109. debug!(target: "net::refinery::ping_node()", "Connected successfully!");
  110. let proto_ver = ProtocolVersion::new(channel.clone(), p2p.settings()).await;
  111. let handshake_task = session_outbound.perform_handshake_protocols(
  112. proto_ver,
  113. channel.clone(),
  114. p2p.executor(),
  115. );
  116. channel.clone().start(p2p.executor());
  117. match handshake_task.await {
  118. Ok(()) => {
  119. debug!(target: "net::refinery::ping_node()", "Handshake success! Stopping channel.");
  120. channel.stop().await;
  121. true
  122. }
  123. Err(e) => {
  124. debug!(target: "net::refinery::ping_node()", "Handshake failure! {}", e);
  125. channel.stop().await;
  126. false
  127. }
  128. }
  129. }
  130. Err(e) => {
  131. debug!(target: "net::refinery::ping_node()", "Failed to connect to {}, ({})", addr, e);
  132. false
  133. }
  134. }
  135. }