protocol_tx.rs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::sync::Arc;
  19. use tinyjson::JsonValue;
  20. use tracing::{debug, error};
  21. use darkfi::{
  22. net::{
  23. protocol::protocol_generic::{
  24. ProtocolGenericAction, ProtocolGenericHandler, ProtocolGenericHandlerPtr,
  25. },
  26. session::SESSION_DEFAULT,
  27. P2pPtr,
  28. },
  29. rpc::jsonrpc::JsonSubscriber,
  30. system::ExecutorPtr,
  31. tx::Transaction,
  32. util::encoding::base64,
  33. validator::ValidatorPtr,
  34. Error, Result,
  35. };
  36. use darkfi_serial::serialize_async;
  37. /// Atomic pointer to the `ProtocolTx` handler.
  38. pub type ProtocolTxHandlerPtr = Arc<ProtocolTxHandler>;
  39. /// Handler managing [`Transaction`] messages, over a generic P2P protocol.
  40. pub struct ProtocolTxHandler {
  41. /// The generic handler for [`Transaction`] messages.
  42. handler: ProtocolGenericHandlerPtr<Transaction, Transaction>,
  43. }
  44. impl ProtocolTxHandler {
  45. /// Initialize a generic prototocol handler for [`Transaction`] messages
  46. /// and registers it to the provided P2P network, using the default session flag.
  47. pub async fn init(p2p: &P2pPtr) -> ProtocolTxHandlerPtr {
  48. debug!(
  49. target: "darkfid::proto::protocol_tx::init",
  50. "Adding ProtocolTx to the protocol registry"
  51. );
  52. let handler = ProtocolGenericHandler::new(p2p, "ProtocolTx", SESSION_DEFAULT).await;
  53. Arc::new(Self { handler })
  54. }
  55. /// Start the `ProtocolTx` background task.
  56. pub async fn start(
  57. &self,
  58. executor: &ExecutorPtr,
  59. validator: &ValidatorPtr,
  60. subscriber: JsonSubscriber,
  61. ) -> Result<()> {
  62. debug!(
  63. target: "darkfid::proto::protocol_tx::start",
  64. "Starting ProtocolTx handler task..."
  65. );
  66. self.handler.task.clone().start(
  67. handle_receive_tx(self.handler.clone(), validator.clone(), subscriber),
  68. |res| async move {
  69. match res {
  70. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  71. Err(e) => error!(target: "darkfid::proto::protocol_tx::start", "Failed starting ProtocolTx handler task: {e}"),
  72. }
  73. },
  74. Error::DetachedTaskStopped,
  75. executor.clone(),
  76. );
  77. debug!(
  78. target: "darkfid::proto::protocol_tx::start",
  79. "ProtocolTx handler task started!"
  80. );
  81. Ok(())
  82. }
  83. /// Stop the `ProtocolTx` background task.
  84. pub async fn stop(&self) {
  85. debug!(target: "darkfid::proto::protocol_tx::stop", "Terminating ProtocolTx handler task...");
  86. self.handler.task.stop().await;
  87. debug!(target: "darkfid::proto::protocol_tx::stop", "ProtocolTx handler task terminated!");
  88. }
  89. }
  90. /// Background handler function for ProtocolTx.
  91. async fn handle_receive_tx(
  92. handler: ProtocolGenericHandlerPtr<Transaction, Transaction>,
  93. validator: ValidatorPtr,
  94. subscriber: JsonSubscriber,
  95. ) -> Result<()> {
  96. debug!(target: "darkfid::proto::protocol_tx::handle_receive_tx", "START");
  97. loop {
  98. // Wait for a new transaction message
  99. let (channel, tx) = match handler.receiver.recv().await {
  100. Ok(r) => r,
  101. Err(e) => {
  102. debug!(
  103. target: "darkfid::proto::protocol_tx::handle_receive_tx",
  104. "recv fail: {e}"
  105. );
  106. continue
  107. }
  108. };
  109. // Check if node has finished syncing its blockchain
  110. if !*validator.synced.read().await {
  111. debug!(
  112. target: "darkfid::proto::protocol_tx::handle_receive_tx",
  113. "Node still syncing blockchain, skipping..."
  114. );
  115. handler.send_action(channel, ProtocolGenericAction::Skip).await;
  116. continue
  117. }
  118. // Append transaction
  119. if let Err(e) = validator.append_tx(&tx, true).await {
  120. debug!(
  121. target: "darkfid::proto::protocol_tx::handle_receive_tx",
  122. "append_tx fail: {e}"
  123. );
  124. handler.send_action(channel, ProtocolGenericAction::Skip).await;
  125. continue
  126. }
  127. // Signal handler to broadcast the valid transaction to rest nodes
  128. handler.send_action(channel, ProtocolGenericAction::Broadcast).await;
  129. // Notify subscriber
  130. let encoded_tx = JsonValue::String(base64::encode(&serialize_async(&tx).await));
  131. subscriber.notify(vec![encoded_tx].into()).await;
  132. }
  133. }