protocol_proposal.rs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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::{collections::HashSet, sync::Arc};
  19. use async_trait::async_trait;
  20. use log::{debug, error};
  21. use smol::lock::RwLock;
  22. use tinyjson::JsonValue;
  23. use darkfi::{
  24. impl_p2p_message,
  25. net::{
  26. protocol::protocol_generic::{
  27. ProtocolGenericAction, ProtocolGenericHandler, ProtocolGenericHandlerPtr,
  28. },
  29. session::SESSION_DEFAULT,
  30. Message, P2pPtr,
  31. },
  32. rpc::jsonrpc::JsonSubscriber,
  33. system::{ExecutorPtr, StoppableTask, StoppableTaskPtr},
  34. util::encoding::base64,
  35. validator::{consensus::Proposal, ValidatorPtr},
  36. Error, Result,
  37. };
  38. use darkfi_serial::{serialize_async, SerialDecodable, SerialEncodable};
  39. use crate::task::handle_unknown_proposal;
  40. /// Auxiliary [`Proposal`] wrapper structure used for messaging.
  41. #[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
  42. pub struct ProposalMessage(pub Proposal);
  43. impl_p2p_message!(ProposalMessage, "proposal");
  44. /// Atomic pointer to the `ProtocolProposal` handler.
  45. pub type ProtocolProposalHandlerPtr = Arc<ProtocolProposalHandler>;
  46. /// Handler managing [`Proposal`] messages, over a generic P2P protocol.
  47. pub struct ProtocolProposalHandler {
  48. /// The generic handler for [`Proposal`] messages.
  49. handler: ProtocolGenericHandlerPtr<ProposalMessage, ProposalMessage>,
  50. /// Background tasks invoked by the handler.
  51. tasks: Arc<RwLock<HashSet<StoppableTaskPtr>>>,
  52. }
  53. impl ProtocolProposalHandler {
  54. /// Initialize a generic prototocol handler for [`Proposal`] messages
  55. /// and registers it to the provided P2P network, using the default session flag.
  56. pub async fn init(p2p: &P2pPtr) -> ProtocolProposalHandlerPtr {
  57. debug!(
  58. target: "darkfid::proto::protocol_proposal::init",
  59. "Adding ProtocolProposal to the protocol registry"
  60. );
  61. let handler = ProtocolGenericHandler::new(p2p, "ProtocolProposal", SESSION_DEFAULT).await;
  62. let tasks = Arc::new(RwLock::new(HashSet::new()));
  63. Arc::new(Self { handler, tasks })
  64. }
  65. /// Start the `ProtocolProposal` background task.
  66. pub async fn start(
  67. &self,
  68. executor: &ExecutorPtr,
  69. validator: &ValidatorPtr,
  70. p2p: &P2pPtr,
  71. proposals_sub: JsonSubscriber,
  72. blocks_sub: JsonSubscriber,
  73. ) -> Result<()> {
  74. debug!(
  75. target: "darkfid::proto::protocol_proposal::start",
  76. "Starting ProtocolProposal handler task..."
  77. );
  78. self.handler.task.clone().start(
  79. handle_receive_proposal(self.handler.clone(), self.tasks.clone(), validator.clone(), p2p.clone(), proposals_sub, blocks_sub, executor.clone()),
  80. |res| async move {
  81. match res {
  82. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  83. Err(e) => error!(target: "darkfid::proto::protocol_proposal::start", "Failed starting ProtocolProposal handler task: {e}"),
  84. }
  85. },
  86. Error::DetachedTaskStopped,
  87. executor.clone(),
  88. );
  89. debug!(
  90. target: "darkfid::proto::protocol_proposal::start",
  91. "ProtocolProposal handler task started!"
  92. );
  93. Ok(())
  94. }
  95. /// Stop the `ProtocolProposal` background tasks.
  96. pub async fn stop(&self) {
  97. debug!(target: "darkfid::proto::protocol_proposal::stop", "Terminating ProtocolProposal handler task...");
  98. self.handler.task.stop().await;
  99. let mut tasks = self.tasks.write().await;
  100. for task in tasks.iter() {
  101. task.stop().await;
  102. }
  103. *tasks = HashSet::new();
  104. drop(tasks);
  105. debug!(target: "darkfid::proto::protocol_proposal::stop", "ProtocolProposal handler task terminated!");
  106. }
  107. }
  108. /// Background handler function for ProtocolProposal.
  109. async fn handle_receive_proposal(
  110. handler: ProtocolGenericHandlerPtr<ProposalMessage, ProposalMessage>,
  111. tasks: Arc<RwLock<HashSet<StoppableTaskPtr>>>,
  112. validator: ValidatorPtr,
  113. p2p: P2pPtr,
  114. proposals_sub: JsonSubscriber,
  115. blocks_sub: JsonSubscriber,
  116. executor: ExecutorPtr,
  117. ) -> Result<()> {
  118. debug!(target: "darkfid::proto::protocol_proposal::handle_receive_proposal", "START");
  119. loop {
  120. // Wait for a new proposal message
  121. let (channel, proposal) = match handler.receiver.recv().await {
  122. Ok(r) => r,
  123. Err(e) => {
  124. debug!(
  125. target: "darkfid::proto::protocol_proposal::handle_receive_proposal",
  126. "recv fail: {e}"
  127. );
  128. continue
  129. }
  130. };
  131. // Check if node has finished syncing its blockchain
  132. if !*validator.synced.read().await {
  133. debug!(
  134. target: "darkfid::proto::protocol_proposal::handle_receive_proposal",
  135. "Node still syncing blockchain, skipping..."
  136. );
  137. handler.send_action(channel, ProtocolGenericAction::Skip).await;
  138. continue
  139. }
  140. // Append proposal
  141. match validator.append_proposal(&proposal.0).await {
  142. Ok(()) => {
  143. // Signal handler to broadcast the valid proposal to rest nodes
  144. handler.send_action(channel, ProtocolGenericAction::Broadcast).await;
  145. // Notify proposals subscriber
  146. let enc_prop = JsonValue::String(base64::encode(&serialize_async(&proposal).await));
  147. proposals_sub.notify(vec![enc_prop].into()).await;
  148. continue
  149. }
  150. Err(e) => {
  151. debug!(
  152. target: "darkfid::proto::protocol_proposal::handle_receive_proposal",
  153. "append_proposal fail: {e}",
  154. );
  155. handler.send_action(channel, ProtocolGenericAction::Skip).await;
  156. match e {
  157. Error::ExtendedChainIndexNotFound => { /* Do nothing */ }
  158. _ => continue,
  159. }
  160. }
  161. };
  162. // Handle unknown proposal in the background
  163. let task = StoppableTask::new();
  164. let _tasks = tasks.clone();
  165. let _task = task.clone();
  166. task.clone().start(
  167. handle_unknown_proposal(validator.clone(), p2p.clone(), proposals_sub.clone(), blocks_sub.clone(), channel, proposal.0),
  168. |res| async move {
  169. match res {
  170. Ok(()) | Err(Error::DetachedTaskStopped) => { _tasks.write().await.remove(&_task); }
  171. Err(e) => error!(target: "darkfid::proto::protocol_proposal::start", "Failed starting ProtocolProposal handler task: {e}"),
  172. }
  173. },
  174. Error::DetachedTaskStopped,
  175. executor.clone(),
  176. );
  177. tasks.write().await.insert(task);
  178. }
  179. }