protocol_seed.rs 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  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::{HostColor, HostsPtr},
  26. message::{AddrsMessage, GetAddrsMessage},
  27. message_publisher::MessageSubscription,
  28. p2p::P2pPtr,
  29. settings::SettingsPtr,
  30. },
  31. protocol_base::{ProtocolBase, ProtocolBasePtr},
  32. };
  33. use crate::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. }
  41. const PROTO_NAME: &str = "ProtocolSeed";
  42. impl ProtocolSeed {
  43. /// Create a new seed protocol.
  44. pub async fn init(channel: ChannelPtr, p2p: P2pPtr) -> ProtocolBasePtr {
  45. let hosts = p2p.hosts();
  46. let settings = p2p.settings();
  47. // Create a subscription to address message
  48. let addr_sub =
  49. channel.subscribe_msg::<AddrsMessage>().await.expect("Missing addr dispatcher!");
  50. Arc::new(Self { channel, hosts, settings, addr_sub })
  51. }
  52. /// Send our own external addresses over a channel. Set the
  53. /// last_seen field to now.
  54. pub async fn send_my_addrs(&self) -> Result<()> {
  55. debug!(target: "net::protocol_seed::send_my_addrs()",
  56. "[START] channel address={}", self.channel.address());
  57. if self.settings.external_addrs.is_empty() {
  58. debug!(target: "net::protocol_seed::send_my_addrs()",
  59. "External address is not configured. Stopping");
  60. return Ok(())
  61. }
  62. let mut addrs = vec![];
  63. for addr in self.settings.external_addrs.clone() {
  64. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  65. addrs.push((addr, last_seen));
  66. }
  67. debug!(target: "net::protocol_seed::send_my_addrs()",
  68. "Broadcasting {} addresses", addrs.len());
  69. let ext_addr_msg = AddrsMessage { addrs };
  70. self.channel.send(&ext_addr_msg).await?;
  71. debug!(target: "net::protocol_seed::send_my_addrs()",
  72. "[END] channel address={}", self.channel.address());
  73. Ok(())
  74. }
  75. }
  76. #[async_trait]
  77. impl ProtocolBase for ProtocolSeed {
  78. /// Starts the seed protocol. Creates a subscription to the address
  79. /// message. If our external address is enabled, then send our address
  80. /// to the seed server. Sends a get-address message and receives an
  81. /// address messsage.
  82. async fn start(self: Arc<Self>, _ex: Arc<Executor<'_>>) -> Result<()> {
  83. debug!(target: "net::protocol_seed::start()", "START => address={}", self.channel.address());
  84. // Send own address to the seed server
  85. self.send_my_addrs().await?;
  86. // Send get address message
  87. let get_addr = GetAddrsMessage {
  88. max: self.settings.outbound_connections as u32,
  89. transports: self.settings.allowed_transports.clone(),
  90. };
  91. self.channel.send(&get_addr).await?;
  92. // Receive addresses
  93. let addrs_msg = self.addr_sub.receive().await?;
  94. debug!(
  95. target: "net::protocol_seed::start()",
  96. "Received {} addrs from {}", addrs_msg.addrs.len(), self.channel.address(),
  97. );
  98. if !addrs_msg.addrs.is_empty() {
  99. debug!(
  100. target: "net::protocol_seed::start()",
  101. "Appending to greylist...",
  102. );
  103. self.hosts.insert(HostColor::Grey, &addrs_msg.addrs).await;
  104. }
  105. debug!(target: "net::protocol_seed::start()", "END => address={}", self.channel.address());
  106. Ok(())
  107. }
  108. fn name(&self) -> &'static str {
  109. PROTO_NAME
  110. }
  111. }