protocol_seed.rs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. use std::sync::Arc;
  2. use async_trait::async_trait;
  3. use log::debug;
  4. use smol::Executor;
  5. use crate::Result;
  6. use super::{
  7. super::{
  8. message, message_subscriber::MessageSubscription, ChannelPtr, HostsPtr, P2pPtr, SettingsPtr,
  9. },
  10. ProtocolBase, ProtocolBasePtr,
  11. };
  12. /// Implements the seed protocol.
  13. pub struct ProtocolSeed {
  14. channel: ChannelPtr,
  15. hosts: HostsPtr,
  16. settings: SettingsPtr,
  17. addr_sub: MessageSubscription<message::AddrsMessage>,
  18. }
  19. impl ProtocolSeed {
  20. /// Create a new seed protocol.
  21. pub async fn init(channel: ChannelPtr, p2p: P2pPtr) -> ProtocolBasePtr {
  22. let hosts = p2p.hosts();
  23. let settings = p2p.settings();
  24. //// Create a subscription to address message.
  25. let addr_sub = channel
  26. .clone()
  27. .subscribe_msg::<message::AddrsMessage>()
  28. .await
  29. .expect("Missing addr dispatcher!");
  30. Arc::new(Self { channel, hosts, settings, addr_sub })
  31. }
  32. /// Sends own external addresses over a channel. Imports own external addresses
  33. /// from settings, then adds that addresses to an address message and
  34. /// sends it out over the channel.
  35. pub async fn send_self_address(&self) -> Result<()> {
  36. // Do nothing if external address is not configured
  37. if self.settings.external_addr.is_empty() {
  38. return Ok(())
  39. }
  40. let addrs = self.settings.external_addr.clone();
  41. debug!(target: "net", "ProtocolSeed::send_own_address() addrs={:?}", addrs);
  42. let addrs = message::AddrsMessage { addrs };
  43. Ok(self.channel.clone().send(addrs).await?)
  44. }
  45. }
  46. #[async_trait]
  47. impl ProtocolBase for ProtocolSeed {
  48. /// Starts the seed protocol. Creates a subscription to the address message,
  49. /// then sends our address to the seed server. Sends a get-address
  50. /// message and receives an address message.
  51. async fn start(self: Arc<Self>, _executor: Arc<Executor<'_>>) -> Result<()> {
  52. debug!(target: "net", "ProtocolSeed::start() [START]");
  53. // Send own address to the seed server.
  54. self.send_self_address().await?;
  55. // Send get address message.
  56. let get_addr = message::GetAddrsMessage {};
  57. self.channel.clone().send(get_addr).await?;
  58. // Receive addresses.
  59. let addrs_msg = self.addr_sub.receive().await?;
  60. debug!(target: "net", "ProtocolSeed::start() received {} addrs", addrs_msg.addrs.len());
  61. self.hosts.store(addrs_msg.addrs.clone()).await;
  62. debug!(target: "net", "ProtocolSeed::start() [END]");
  63. Ok(())
  64. }
  65. fn name(&self) -> &'static str {
  66. "ProtocolSeed"
  67. }
  68. }