protocol_seed.rs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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 async_trait::async_trait;
  20. use log::debug;
  21. use smol::Executor;
  22. use super::{
  23. super::{
  24. channel::ChannelPtr,
  25. hosts::store::HostsPtr,
  26. message::{AddrsMessage, GetAddrsMessage},
  27. message_subscriber::MessageSubscription,
  28. p2p::P2pPtr,
  29. settings::SettingsPtr,
  30. },
  31. protocol_base::{ProtocolBase, ProtocolBasePtr},
  32. };
  33. use crate::{net::hosts::refinery::ping_node, Result};
  34. /// Implements the seed protocol
  35. pub struct ProtocolSeed {
  36. channel: ChannelPtr,
  37. hosts: HostsPtr,
  38. settings: SettingsPtr,
  39. addr_sub: MessageSubscription<AddrsMessage>,
  40. p2p: P2pPtr,
  41. }
  42. const PROTO_NAME: &str = "ProtocolSeed";
  43. impl ProtocolSeed {
  44. /// Create a new seed protocol.
  45. pub async fn init(channel: ChannelPtr, p2p: P2pPtr) -> ProtocolBasePtr {
  46. let hosts = p2p.hosts();
  47. let settings = p2p.settings();
  48. // Create a subscription to address message
  49. let addr_sub =
  50. channel.subscribe_msg::<AddrsMessage>().await.expect("Missing addr dispatcher!");
  51. Arc::new(Self { channel, hosts, settings, addr_sub, p2p })
  52. }
  53. /// Sends own external addresses over a channel. Imports own external addresses
  54. /// from settings, then adds those addresses to an addrs message and sends it
  55. /// out over the channel.
  56. pub async fn send_my_addrs(&self) -> Result<()> {
  57. debug!(target: "net::protocol_seed::send_my_addrs()", "[START]");
  58. // Do nothing if external addresses are not configured
  59. if self.settings.external_addrs.is_empty() {
  60. debug!(target: "net::protocol_seed::send_my_addrs()",
  61. "External address is not configured. Stopping");
  62. return Ok(())
  63. }
  64. let mut addrs = vec![];
  65. for addr in self.settings.external_addrs.clone() {
  66. //addrs.push((addr, 0));
  67. debug!(target: "net::protocol_seed::send_my_addrs()", "Attempting to ping self");
  68. // See if we can do a version exchange with ourself.
  69. if ping_node(addr.clone(), self.p2p.clone()).await {
  70. // We're online. Update last_seen and broadcast our address.
  71. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  72. addrs.push((addr, last_seen));
  73. } else {
  74. // Our external addr is invalid. If every external addr in the list is invalid
  75. // we will just broadcast an empty AddrsMessage.
  76. debug!(target: "net::protocol_seed::send_my_addrs()", "Ping self failed!");
  77. }
  78. }
  79. debug!(target: "net::protocol_seed::send_my_addrs()", "Broadcasting {} addresses", addrs.len());
  80. let ext_addr_msg = AddrsMessage { addrs };
  81. self.channel.send(&ext_addr_msg).await?;
  82. debug!(target: "net::protocol_seed::send_my_addrs()", "[END]");
  83. Ok(())
  84. }
  85. }
  86. #[async_trait]
  87. impl ProtocolBase for ProtocolSeed {
  88. /// Starts the seed protocol. Creates a subscription to the address message,
  89. /// then sends our address to the seed server. Sends a get-address message
  90. /// and receives an address messsage.
  91. async fn start(self: Arc<Self>, _ex: Arc<Executor<'_>>) -> Result<()> {
  92. debug!(target: "net::protocol_seed::start()", "START => address={}", self.channel.address());
  93. // Send own address to the seed server
  94. self.send_my_addrs().await?;
  95. // Send get address message
  96. let get_addr = GetAddrsMessage {
  97. max: self.settings.outbound_connections as u32,
  98. transports: self.settings.allowed_transports.clone(),
  99. };
  100. self.channel.send(&get_addr).await?;
  101. // Receive addresses
  102. let addrs_msg = self.addr_sub.receive().await?;
  103. debug!(
  104. target: "net::protocol_seed::start()",
  105. "Received {} addrs from {}", addrs_msg.addrs.len(), self.channel.address(),
  106. );
  107. debug!(
  108. target: "net::protocol_seed::start()",
  109. "Appending to greylist...",
  110. );
  111. self.hosts.greylist_store_or_update(&addrs_msg.addrs).await;
  112. debug!(target: "net::protocol_seed::start()", "END => address={}", self.channel.address());
  113. Ok(())
  114. }
  115. fn name(&self) -> &'static str {
  116. PROTO_NAME
  117. }
  118. }