refinery.rs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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::{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. // NOTE: in monero this is called "greylist housekeeping" but that's a bit verbose.
  32. pub struct GreylistRefinery {
  33. /// Weak pointer to parent p2p object
  34. pub(in crate::net) p2p: LazyWeak<P2p>,
  35. process: StoppableTaskPtr,
  36. }
  37. impl GreylistRefinery {
  38. pub fn new() -> Arc<Self> {
  39. Arc::new(Self { p2p: LazyWeak::new(), process: StoppableTask::new() })
  40. }
  41. pub async fn start(self: Arc<Self>) {
  42. let ex = self.p2p().executor();
  43. self.process.clone().start(
  44. async move {
  45. self.run().await;
  46. unreachable!();
  47. },
  48. // Ignore stop handler
  49. |_| async {},
  50. Error::NetworkServiceStopped,
  51. ex,
  52. );
  53. }
  54. pub async fn stop(self: Arc<Self>) {
  55. self.process.stop().await
  56. }
  57. //// Randomly select a peer on the greylist and probe it.
  58. //// TODO: This frequency of this call can be set in net::Settings.
  59. async fn run(self: Arc<Self>) {
  60. debug!(target: "net::refinery::run()", "START");
  61. loop {
  62. let hosts = self.p2p().hosts();
  63. if hosts.is_empty_greylist().await {
  64. warn!(target: "net::refinery::run()",
  65. "Greylist is empty! Cannot start refinery process");
  66. } else {
  67. debug!(target: "net::refinery::run()", "Starting refinery process");
  68. // Randomly select an entry from the greylist.
  69. let (entry, position) = hosts.greylist_fetch_random().await;
  70. let url = &entry.0;
  71. if ping_node(url, self.p2p().clone()).await {
  72. // Peer is responsive. Update last_seen and add it to the whitelist.
  73. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  74. // Append to the whitelist.
  75. hosts.whitelist_store_or_update(&[(url.clone(), last_seen)]).await.unwrap();
  76. // Remove whitelisted peer from the greylist.
  77. hosts.greylist_remove(url, position).await;
  78. } else {
  79. let mut greylist = hosts.greylist.write().await;
  80. greylist.remove(position);
  81. debug!(target: "net::refinery::run()", "Peer {} is not response. Removed from greylist", url);
  82. }
  83. }
  84. // TODO: create a custom net setting for this timer
  85. debug!(target: "net::greylist_refinery::run()", "Sleeping...");
  86. sleep(10).await;
  87. }
  88. }
  89. fn p2p(&self) -> P2pPtr {
  90. self.p2p.upgrade()
  91. }
  92. }
  93. // Ping a node to check it's online.
  94. // TODO: make this an actual ping-pong method, rather than a version exchange.
  95. pub async fn ping_node(addr: &Url, p2p: P2pPtr) -> bool {
  96. let session_outbound = p2p.session_outbound();
  97. let parent = Arc::downgrade(&session_outbound);
  98. let connector = Connector::new(p2p.settings(), parent);
  99. debug!(target: "net::refinery::ping_node()", "Attempting to connect to {}", addr);
  100. match connector.connect(addr).await {
  101. Ok((_url, channel)) => {
  102. debug!(target: "net::refinery::ping_node()", "Connected successfully!");
  103. let proto_ver = ProtocolVersion::new(channel.clone(), p2p.settings()).await;
  104. let handshake_task = session_outbound.perform_handshake_protocols(
  105. proto_ver,
  106. channel.clone(),
  107. p2p.executor(),
  108. );
  109. channel.clone().start(p2p.executor());
  110. match handshake_task.await {
  111. Ok(()) => {
  112. debug!(target: "net::refinery::ping_node()", "Handshake success! Stopping channel.");
  113. channel.stop().await;
  114. true
  115. }
  116. Err(e) => {
  117. debug!(target: "net::refinery::ping_node()", "Handshake failure! {}", e);
  118. false
  119. }
  120. }
  121. }
  122. Err(e) => {
  123. debug!(target: "net::refinery::ping_node()", "Failed to connect to {}, ({})", addr, e);
  124. false
  125. }
  126. }
  127. }