protocol_proposal.rs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. subscriber: JsonSubscriber,
  72. ) -> Result<()> {
  73. debug!(
  74. target: "darkfid::proto::protocol_proposal::start",
  75. "Starting ProtocolProposal handler task..."
  76. );
  77. self.handler.task.clone().start(
  78. handle_receive_proposal(self.handler.clone(), self.tasks.clone(), validator.clone(), p2p.clone(), subscriber, executor.clone()),
  79. |res| async move {
  80. match res {
  81. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  82. Err(e) => error!(target: "darkfid::proto::protocol_proposal::start", "Failed starting ProtocolProposal handler task: {e}"),
  83. }
  84. },
  85. Error::DetachedTaskStopped,
  86. executor.clone(),
  87. );
  88. debug!(
  89. target: "darkfid::proto::protocol_proposal::start",
  90. "ProtocolProposal handler task started!"
  91. );
  92. Ok(())
  93. }
  94. /// Stop the `ProtocolProposal` background tasks.
  95. pub async fn stop(&self) {
  96. debug!(target: "darkfid::proto::protocol_proposal::stop", "Terminating ProtocolProposal handler task...");
  97. self.handler.task.stop().await;
  98. let mut tasks = self.tasks.write().await;
  99. for task in tasks.iter() {
  100. task.stop().await;
  101. }
  102. *tasks = HashSet::new();
  103. drop(tasks);
  104. debug!(target: "darkfid::proto::protocol_proposal::stop", "ProtocolProposal handler task terminated!");
  105. }
  106. }
  107. /// Background handler function for ProtocolProposal.
  108. async fn handle_receive_proposal(
  109. handler: ProtocolGenericHandlerPtr<ProposalMessage, ProposalMessage>,
  110. tasks: Arc<RwLock<HashSet<StoppableTaskPtr>>>,
  111. validator: ValidatorPtr,
  112. p2p: P2pPtr,
  113. subscriber: JsonSubscriber,
  114. executor: ExecutorPtr,
  115. ) -> Result<()> {
  116. debug!(target: "darkfid::proto::protocol_proposal::handle_receive_proposal", "START");
  117. loop {
  118. // Wait for a new proposal message
  119. let (channel, proposal) = match handler.receiver.recv().await {
  120. Ok(r) => r,
  121. Err(e) => {
  122. debug!(
  123. target: "darkfid::proto::protocol_proposal::handle_receive_proposal",
  124. "recv fail: {e}"
  125. );
  126. continue
  127. }
  128. };
  129. // Check if node has finished syncing its blockchain
  130. if !*validator.synced.read().await {
  131. debug!(
  132. target: "darkfid::proto::protocol_proposal::handle_receive_proposal",
  133. "Node still syncing blockchain, skipping..."
  134. );
  135. handler.send_action(channel, ProtocolGenericAction::Skip).await;
  136. continue
  137. }
  138. // Append proposal
  139. match validator.append_proposal(&proposal.0).await {
  140. Ok(()) => {
  141. // Signal handler to broadcast the valid proposal to rest nodes
  142. handler.send_action(channel, ProtocolGenericAction::Broadcast).await;
  143. // Notify subscriber
  144. let enc_prop = JsonValue::String(base64::encode(&serialize_async(&proposal).await));
  145. subscriber.notify(vec![enc_prop].into()).await;
  146. continue
  147. }
  148. Err(e) => {
  149. debug!(
  150. target: "darkfid::proto::protocol_proposal::handle_receive_proposal",
  151. "append_proposal fail: {e}",
  152. );
  153. handler.send_action(channel, ProtocolGenericAction::Skip).await;
  154. match e {
  155. Error::ExtendedChainIndexNotFound => { /* Do nothing */ }
  156. _ => continue,
  157. }
  158. }
  159. };
  160. // Handle unknown proposal in the background
  161. let task = StoppableTask::new();
  162. let _tasks = tasks.clone();
  163. let _task = task.clone();
  164. task.clone().start(
  165. handle_unknown_proposal(validator.clone(), p2p.clone(), subscriber.clone(), channel, proposal.0),
  166. |res| async move {
  167. match res {
  168. Ok(()) | Err(Error::DetachedTaskStopped) => { _tasks.write().await.remove(&_task); }
  169. Err(e) => error!(target: "darkfid::proto::protocol_proposal::start", "Failed starting ProtocolProposal handler task: {e}"),
  170. }
  171. },
  172. Error::DetachedTaskStopped,
  173. executor.clone(),
  174. );
  175. tasks.write().await.insert(task);
  176. }
  177. }