protocol_proposal.rs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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 async_trait::async_trait;
  20. use log::debug;
  21. use smol::Executor;
  22. use tinyjson::JsonValue;
  23. use url::Url;
  24. use darkfi::{
  25. impl_p2p_message,
  26. net::{
  27. ChannelPtr, Message, MessageSubscription, P2pPtr, ProtocolBase, ProtocolBasePtr,
  28. ProtocolJobsManager, ProtocolJobsManagerPtr,
  29. },
  30. rpc::jsonrpc::JsonSubscriber,
  31. util::encoding::base64,
  32. validator::{consensus::Proposal, ValidatorPtr},
  33. Result,
  34. };
  35. use darkfi_serial::{serialize, SerialDecodable, SerialEncodable};
  36. /// Auxiliary [`Proposal`] wrapper structure used for messaging.
  37. #[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
  38. struct ProposalMessage(Proposal);
  39. impl_p2p_message!(ProposalMessage, "proposal");
  40. pub struct ProtocolProposal {
  41. proposal_sub: MessageSubscription<ProposalMessage>,
  42. jobsman: ProtocolJobsManagerPtr,
  43. validator: ValidatorPtr,
  44. p2p: P2pPtr,
  45. channel_address: Url,
  46. subscriber: JsonSubscriber,
  47. }
  48. impl ProtocolProposal {
  49. pub async fn init(
  50. channel: ChannelPtr,
  51. validator: ValidatorPtr,
  52. p2p: P2pPtr,
  53. subscriber: JsonSubscriber,
  54. ) -> Result<ProtocolBasePtr> {
  55. debug!(
  56. target: "validator::protocol_proposal::init",
  57. "Adding ProtocolProposal to the protocol registry"
  58. );
  59. let msg_subsystem = channel.message_subsystem();
  60. msg_subsystem.add_dispatch::<ProposalMessage>().await;
  61. let proposal_sub = channel.subscribe_msg::<ProposalMessage>().await?;
  62. Ok(Arc::new(Self {
  63. proposal_sub,
  64. jobsman: ProtocolJobsManager::new("ProposalProtocol", channel.clone()),
  65. validator,
  66. p2p,
  67. channel_address: channel.address().clone(),
  68. subscriber,
  69. }))
  70. }
  71. async fn handle_receive_proposal(self: Arc<Self>) -> Result<()> {
  72. debug!(target: "consensus::protocol_proposal::handle_receive_proposal", "START");
  73. let exclude_list = vec![self.channel_address.clone()];
  74. loop {
  75. let proposal = match self.proposal_sub.receive().await {
  76. Ok(v) => v,
  77. Err(e) => {
  78. debug!(
  79. target: "validator::protocol_proposal::handle_receive_proposal",
  80. "recv fail: {}",
  81. e
  82. );
  83. continue
  84. }
  85. };
  86. // Check if node has finished syncing its blockchain
  87. if !self.validator.read().await.synced {
  88. debug!(
  89. target: "validator::protocol_proposal::handle_receive_proposal",
  90. "Node still syncing blockchain, skipping..."
  91. );
  92. continue
  93. }
  94. // Check if node started participating in consensus.
  95. if !self.validator.read().await.consensus.participating {
  96. debug!(
  97. target: "validator::protocol_proposal::handle_receive_proposal",
  98. "Node is not participating in consensus, skipping..."
  99. );
  100. continue
  101. }
  102. let proposal_copy = (*proposal).clone();
  103. match self.validator.write().await.consensus.append_proposal(&proposal_copy.0).await {
  104. Ok(()) => {
  105. self.p2p.broadcast_with_exclude(&proposal_copy, &exclude_list).await;
  106. let enc_prop = JsonValue::String(base64::encode(&serialize(&proposal_copy)));
  107. self.subscriber.notify(vec![enc_prop]).await;
  108. }
  109. Err(e) => {
  110. debug!(
  111. target: "validator::protocol_proposal::handle_receive_proposal",
  112. "append_proposal fail: {}",
  113. e
  114. );
  115. }
  116. };
  117. }
  118. }
  119. }
  120. #[async_trait]
  121. impl ProtocolBase for ProtocolProposal {
  122. async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
  123. debug!(target: "validator::protocol_proposal::start", "START");
  124. self.jobsman.clone().start(executor.clone());
  125. self.jobsman.clone().spawn(self.clone().handle_receive_proposal(), executor.clone()).await;
  126. debug!(target: "validator::protocol_proposal::start", "END");
  127. Ok(())
  128. }
  129. fn name(&self) -> &'static str {
  130. "ProtocolProposal"
  131. }
  132. }