protocol_proposal.rs 7.8 KB

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