protocol_seed.rs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  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::{lock::RwLock as AsyncRwLock, 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::Settings,
  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: Arc<AsyncRwLock<Settings>>,
  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. // Create a subscription to address message
  46. let addr_sub =
  47. channel.subscribe_msg::<AddrsMessage>().await.expect("Missing addr dispatcher!");
  48. Arc::new(Self { channel, hosts: p2p.hosts(), settings: p2p.settings(), addr_sub })
  49. }
  50. /// Send our own external addresses over a channel. Set the
  51. /// last_seen field to now.
  52. pub async fn send_my_addrs(&self) -> Result<()> {
  53. debug!(
  54. target: "net::protocol_seed::send_my_addrs",
  55. "[START] channel address={}", self.channel.address(),
  56. );
  57. let external_addrs = self.settings.read().await.external_addrs.clone();
  58. if external_addrs.is_empty() {
  59. debug!(
  60. target: "net::protocol_seed::send_my_addrs",
  61. "External address is not configured. Stopping",
  62. );
  63. return Ok(())
  64. }
  65. let mut addrs = vec![];
  66. for addr in external_addrs {
  67. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  68. addrs.push((addr, last_seen));
  69. }
  70. debug!(
  71. target: "net::protocol_seed::send_my_addrs",
  72. "Broadcasting {} addresses", addrs.len(),
  73. );
  74. let ext_addr_msg = AddrsMessage { addrs };
  75. self.channel.send(&ext_addr_msg).await?;
  76. debug!(
  77. target: "net::protocol_seed::send_my_addrs",
  78. "[END] channel address={}", self.channel.address(),
  79. );
  80. Ok(())
  81. }
  82. }
  83. #[async_trait]
  84. impl ProtocolBase for ProtocolSeed {
  85. /// Starts the seed protocol. Creates a subscription to the address
  86. /// message. If our external address is enabled, then send our address
  87. /// to the seed server. Sends a get-address message and receives an
  88. /// address messsage.
  89. async fn start(self: Arc<Self>, _ex: Arc<Executor<'_>>) -> Result<()> {
  90. debug!(target: "net::protocol_seed::start()", "START => address={}", self.channel.address());
  91. // Send own address to the seed server
  92. self.send_my_addrs().await?;
  93. let settings = self.settings.read().await;
  94. let outbound_connections = settings.outbound_connections;
  95. let allowed_transports = settings.allowed_transports.clone();
  96. drop(settings);
  97. // Send get address message
  98. let get_addr =
  99. GetAddrsMessage { max: outbound_connections as u32, transports: allowed_transports };
  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. if !addrs_msg.addrs.is_empty() {
  108. debug!(
  109. target: "net::protocol_seed::start()",
  110. "Appending to greylist...",
  111. );
  112. self.hosts.insert(HostColor::Grey, &addrs_msg.addrs).await;
  113. }
  114. debug!(target: "net::protocol_seed::start()", "END => address={}", self.channel.address());
  115. Ok(())
  116. }
  117. fn name(&self) -> &'static str {
  118. PROTO_NAME
  119. }
  120. }