p2p.rs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. use async_executor::Executor;
  2. use async_std::sync::Mutex;
  3. use std::collections::HashMap;
  4. use std::net::SocketAddr;
  5. use std::sync::Arc;
  6. use crate::net::error::NetResult;
  7. use crate::net::sessions::{InboundSession, SeedSession};
  8. use crate::net::{Channel, ChannelPtr, Connector, Hosts, HostsPtr, Settings, SettingsPtr};
  9. pub type Pending<T> = Mutex<HashMap<SocketAddr, Arc<T>>>;
  10. pub type P2pPtr = Arc<P2p>;
  11. pub struct P2p {
  12. pending_connects: Pending<Connector>,
  13. pending_channels: Pending<Channel>,
  14. hosts: HostsPtr,
  15. settings: SettingsPtr,
  16. }
  17. impl P2p {
  18. pub fn new(settings: Settings) -> Arc<Self> {
  19. let settings = Arc::new(settings);
  20. Arc::new(Self {
  21. pending_connects: Mutex::new(HashMap::new()),
  22. pending_channels: Mutex::new(HashMap::new()),
  23. hosts: Hosts::new(settings.clone()),
  24. settings,
  25. })
  26. }
  27. /// Invoke startup and seeding sequence. Call from constructing thread.
  28. pub async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> NetResult<()> {
  29. // Start manual connections
  30. // Start seed session
  31. let seed = SeedSession::new(Arc::downgrade(&self));
  32. seed.start(executor.clone()).await?;
  33. Ok(())
  34. }
  35. /// Synchronize the blockchain and then begin long running sessions,
  36. /// call after start() is invoked.
  37. pub async fn run(self: Arc<Self>, executor: Arc<Executor<'_>>) -> NetResult<()> {
  38. let inbound = InboundSession::new(Arc::downgrade(&self));
  39. inbound.start(executor.clone())?;
  40. Ok(())
  41. }
  42. pub async fn store(self: Arc<Self>, channel: ChannelPtr) {
  43. self.pending_channels
  44. .lock()
  45. .await
  46. .insert(channel.address(), channel);
  47. }
  48. pub async fn remove(self: Arc<Self>, channel: ChannelPtr) {
  49. self.pending_channels
  50. .lock()
  51. .await
  52. .remove(&channel.address());
  53. }
  54. pub fn settings(&self) -> SettingsPtr {
  55. self.settings.clone()
  56. }
  57. pub fn hosts(&self) -> HostsPtr {
  58. self.hosts.clone()
  59. }
  60. }