protocol_block.rs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  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 async_std::sync::Arc;
  19. use async_trait::async_trait;
  20. use log::debug;
  21. use smol::Executor;
  22. use url::Url;
  23. use darkfi::{
  24. blockchain::BlockInfo,
  25. impl_p2p_message,
  26. net::{
  27. ChannelPtr, Message, MessageSubscription, P2pPtr, ProtocolBase, ProtocolBasePtr,
  28. ProtocolJobsManager, ProtocolJobsManagerPtr,
  29. },
  30. validator::ValidatorPtr,
  31. Result,
  32. };
  33. use darkfi_serial::{SerialDecodable, SerialEncodable};
  34. /// Auxiliary [`BlockInfo`] wrapper structure used for messaging.
  35. #[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
  36. pub struct BlockInfoMessage(BlockInfo);
  37. impl From<&BlockInfo> for BlockInfoMessage {
  38. fn from(block: &BlockInfo) -> Self {
  39. BlockInfoMessage(block.clone())
  40. }
  41. }
  42. impl_p2p_message!(BlockInfoMessage, "block");
  43. pub struct ProtocolBlock {
  44. block_sub: MessageSubscription<BlockInfoMessage>,
  45. jobsman: ProtocolJobsManagerPtr,
  46. validator: ValidatorPtr,
  47. p2p: P2pPtr,
  48. channel_address: Url,
  49. }
  50. impl ProtocolBlock {
  51. pub async fn init(
  52. channel: ChannelPtr,
  53. validator: ValidatorPtr,
  54. p2p: P2pPtr,
  55. ) -> Result<ProtocolBasePtr> {
  56. debug!(
  57. target: "validator::protocol_block::init",
  58. "Adding ProtocolBlock to the protocol registry"
  59. );
  60. let msg_subsystem = channel.message_subsystem();
  61. msg_subsystem.add_dispatch::<BlockInfoMessage>().await;
  62. let block_sub = channel.subscribe_msg::<BlockInfoMessage>().await?;
  63. Ok(Arc::new(Self {
  64. block_sub,
  65. jobsman: ProtocolJobsManager::new("BlockProtocol", channel.clone()),
  66. validator,
  67. p2p,
  68. channel_address: channel.address().clone(),
  69. }))
  70. }
  71. async fn handle_receive_block(self: Arc<Self>) -> Result<()> {
  72. debug!(target: "consensus::protocol_block::handle_receive_block", "START");
  73. let exclude_list = vec![self.channel_address.clone()];
  74. loop {
  75. let block = match self.block_sub.receive().await {
  76. Ok(v) => v,
  77. Err(e) => {
  78. debug!(
  79. target: "validator::protocol_block::handle_receive_block",
  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_block::handle_receive_block",
  90. "Node still syncing blockchain, skipping..."
  91. );
  92. continue
  93. }
  94. // Check if node started participating in consensus.
  95. // Consensus-mode enabled nodes have already performed these steps,
  96. // during proposal finalization. They still listen to this sub,
  97. // in case they go out of sync and become a none-consensus node.
  98. if self.validator.read().await.consensus.participating {
  99. debug!(
  100. target: "validator::protocol_block::handle_receive_block",
  101. "Node is participating in consensus, skipping..."
  102. );
  103. continue
  104. }
  105. let block_copy = (*block).clone();
  106. match self.validator.write().await.append_block(&block_copy.0).await {
  107. Ok(()) => self.p2p.broadcast_with_exclude(&block_copy, &exclude_list).await,
  108. Err(e) => {
  109. debug!(
  110. target: "validator::protocol_block::handle_receive_block",
  111. "append_block fail: {}",
  112. e
  113. );
  114. }
  115. };
  116. }
  117. }
  118. }
  119. #[async_trait]
  120. impl ProtocolBase for ProtocolBlock {
  121. async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
  122. debug!(target: "validator::protocol_block::start", "START");
  123. self.jobsman.clone().start(executor.clone());
  124. self.jobsman.clone().spawn(self.clone().handle_receive_block(), executor.clone()).await;
  125. debug!(target: "validator::protocol_block::start", "END");
  126. Ok(())
  127. }
  128. fn name(&self) -> &'static str {
  129. "ProtocolBlock"
  130. }
  131. }