protocol_participant.rs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. use async_executor::Executor;
  2. use async_trait::async_trait;
  3. use darkfi::{
  4. consensus::{participant::Participant, state::StatePtr},
  5. net::{
  6. ChannelPtr, MessageSubscription, P2pPtr, ProtocolBase, ProtocolBasePtr,
  7. ProtocolJobsManager, ProtocolJobsManagerPtr,
  8. },
  9. Result,
  10. };
  11. use log::debug;
  12. use std::sync::Arc;
  13. pub struct ProtocolParticipant {
  14. participant_sub: MessageSubscription<Participant>,
  15. jobsman: ProtocolJobsManagerPtr,
  16. state: StatePtr,
  17. p2p: P2pPtr,
  18. }
  19. impl ProtocolParticipant {
  20. pub async fn init(channel: ChannelPtr, state: StatePtr, p2p: P2pPtr) -> ProtocolBasePtr {
  21. let message_subsytem = channel.get_message_subsystem();
  22. message_subsytem.add_dispatch::<Participant>().await;
  23. let participant_sub =
  24. channel.subscribe_msg::<Participant>().await.expect("Missing Participant dispatcher!");
  25. Arc::new(Self {
  26. participant_sub,
  27. jobsman: ProtocolJobsManager::new("ParticipantProtocol", channel),
  28. state,
  29. p2p,
  30. })
  31. }
  32. async fn handle_receive_participant(self: Arc<Self>) -> Result<()> {
  33. debug!(target: "ircd", "ProtocolParticipant::handle_receive_participant() [START]");
  34. loop {
  35. let participant = self.participant_sub.receive().await?;
  36. debug!(
  37. target: "ircd",
  38. "ProtocolParticipant::handle_receive_participant() received {:?}",
  39. participant
  40. );
  41. if self.state.write().unwrap().append_participant((*participant).clone()) {
  42. let pending_participants = self.state.read().unwrap().pending_participants.clone();
  43. for pending_participant in pending_participants {
  44. self.p2p.broadcast(pending_participant.clone()).await?;
  45. }
  46. }
  47. }
  48. }
  49. }
  50. #[async_trait]
  51. impl ProtocolBase for ProtocolParticipant {
  52. async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
  53. debug!(target: "ircd", "ProtocolParticipant::start() [START]");
  54. self.jobsman.clone().start(executor.clone());
  55. self.jobsman
  56. .clone()
  57. .spawn(self.clone().handle_receive_participant(), executor.clone())
  58. .await;
  59. debug!(target: "ircd", "ProtocolParticipant::start() [END]");
  60. Ok(())
  61. }
  62. fn name(&self) -> &'static str {
  63. "ProtocolParticipant"
  64. }
  65. }