protocol_seed.rs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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 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. // Do nothing if advertise is set to false
  65. if !self.settings.advertise {
  66. debug!(target: "net::protocol_seed::send_my_addrs()",
  67. "Advertise is set to false. Stopping");
  68. return Ok(())
  69. }
  70. let mut addrs = vec![];
  71. for addr in self.settings.external_addrs.clone() {
  72. debug!(target: "net::protocol_seed::send_my_addrs()", "Attempting to ping self");
  73. // See if we can do a version exchange with ourself.
  74. if ping_node(&addr, self.p2p.clone()).await {
  75. // We're online. Update last_seen and broadcast our address.
  76. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  77. addrs.push((addr, last_seen));
  78. } else {
  79. debug!(target: "net::protocol_seed::send_my_addrs()", "Ping self failed");
  80. return Ok(())
  81. }
  82. }
  83. debug!(target: "net::protocol_seed::send_my_addrs()", "Broadcasting address");
  84. let ext_addr_msg = AddrsMessage { addrs };
  85. self.channel.send(&ext_addr_msg).await?;
  86. debug!(target: "net::protocol_seed::send_my_addrs()", "[END]");
  87. Ok(())
  88. }
  89. }
  90. #[async_trait]
  91. impl ProtocolBase for ProtocolSeed {
  92. /// Starts the seed protocol. Creates a subscription to the address message,
  93. /// then sends our address to the seed server. Sends a get-address message
  94. /// and receives an address messsage.
  95. async fn start(self: Arc<Self>, _ex: Arc<Executor<'_>>) -> Result<()> {
  96. debug!(target: "net::protocol_seed::start()", "START => address={}", self.channel.address());
  97. // Send own address to the seed server
  98. self.send_my_addrs().await?;
  99. // Send get address message
  100. let get_addr = GetAddrsMessage {
  101. max: self.settings.outbound_connections as u32,
  102. transports: self.settings.allowed_transports.clone(),
  103. };
  104. self.channel.send(&get_addr).await?;
  105. // Receive addresses
  106. let addrs_msg = self.addr_sub.receive().await?;
  107. debug!(
  108. target: "net::protocol_seed::start()",
  109. "Received {} addrs from {}", addrs_msg.addrs.len(), self.channel.address(),
  110. );
  111. debug!(
  112. target: "net::protocol_seed::start()",
  113. "Appending to greylist...",
  114. );
  115. self.hosts.greylist_store_or_update(&addrs_msg.addrs).await?;
  116. debug!(target: "net::protocol_seed::start()", "END => address={}", self.channel.address());
  117. Ok(())
  118. }
  119. fn name(&self) -> &'static str {
  120. PROTO_NAME
  121. }
  122. }