protocol_tx.rs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. use async_executor::Executor;
  2. use async_trait::async_trait;
  3. use darkfi::{
  4. consensus::{state::ValidatorStatePtr, tx::Tx},
  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 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. ) -> ProtocolBasePtr {
  25. let message_subsytem = channel.get_message_subsystem();
  26. message_subsytem.add_dispatch::<Tx>().await;
  27. let tx_sub = channel.subscribe_msg::<Tx>().await.expect("Missing Tx dispatcher!");
  28. 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!(target: "ircd", "ProtocolTx::handle_receive_tx() [START]");
  37. loop {
  38. let tx = self.tx_sub.receive().await?;
  39. debug!(
  40. target: "ircd",
  41. "ProtocolTx::handle_receive_tx() received {:?}",
  42. tx
  43. );
  44. let tx_copy = (*tx).clone();
  45. // Nodes use unconfirmed_txs vector as seen_txs pool.
  46. if self.state.write().unwrap().append_tx(tx_copy.clone()) {
  47. self.p2p.broadcast(tx_copy).await?;
  48. }
  49. }
  50. }
  51. }
  52. #[async_trait]
  53. impl ProtocolBase for ProtocolTx {
  54. async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
  55. debug!(target: "ircd", "ProtocolTx::start() [START]");
  56. self.jobsman.clone().start(executor.clone());
  57. self.jobsman.clone().spawn(self.clone().handle_receive_tx(), executor.clone()).await;
  58. debug!(target: "ircd", "ProtocolTx::start() [END]");
  59. Ok(())
  60. }
  61. fn name(&self) -> &'static str {
  62. "ProtocolTx"
  63. }
  64. }