protocol_seed.rs 2.6 KB

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