protocol_tx.rs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. use async_executor::Executor;
  2. use async_std::sync::Arc;
  3. use async_trait::async_trait;
  4. use log::debug;
  5. use darkfi::{
  6. consensus2::{state::ValidatorStatePtr, Tx},
  7. net::{
  8. ChannelPtr, MessageSubscription, P2pPtr, ProtocolBase, ProtocolBasePtr,
  9. ProtocolJobsManager, ProtocolJobsManagerPtr,
  10. },
  11. Result,
  12. };
  13. pub struct ProtocolTx {
  14. tx_sub: MessageSubscription<Tx>,
  15. jobsman: ProtocolJobsManagerPtr,
  16. state: ValidatorStatePtr,
  17. p2p: P2pPtr,
  18. }
  19. impl ProtocolTx {
  20. pub async fn init(
  21. channel: ChannelPtr,
  22. state: ValidatorStatePtr,
  23. p2p: P2pPtr,
  24. ) -> Result<ProtocolBasePtr> {
  25. let msg_subsystem = channel.get_message_subsystem();
  26. msg_subsystem.add_dispatch::<Tx>().await;
  27. let tx_sub = channel.subscribe_msg::<Tx>().await?;
  28. Ok(Arc::new(Self {
  29. tx_sub,
  30. jobsman: ProtocolJobsManager::new("TxProtocol", channel),
  31. state,
  32. p2p,
  33. }))
  34. }
  35. async fn handle_receive_tx(self: Arc<Self>) -> Result<()> {
  36. debug!("ProtocolTx::handle_receive_tx() [START]");
  37. loop {
  38. let tx = self.tx_sub.receive().await?;
  39. debug!("ProtocolTx::handle_receive_tx() recv: {:?}", tx);
  40. let tx_copy = (*tx).clone();
  41. if self.state.write().await.append_tx(tx_copy.clone()) {
  42. self.p2p.broadcast(tx_copy).await?;
  43. }
  44. }
  45. }
  46. }
  47. #[async_trait]
  48. impl ProtocolBase for ProtocolTx {
  49. async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
  50. debug!("ProtocolTx::start() [START]");
  51. self.jobsman.clone().start(executor.clone());
  52. self.jobsman.clone().spawn(self.clone().handle_receive_tx(), executor.clone()).await;
  53. debug!("ProtocolTx::start() [END]");
  54. Ok(())
  55. }
  56. fn name(&self) -> &'static str {
  57. "ProtocolTx"
  58. }
  59. }