protocol_sync.rs 4.7 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, error};
  21. use smol::Executor;
  22. use darkfi::{
  23. blockchain::BlockInfo,
  24. impl_p2p_message,
  25. net::{
  26. ChannelPtr, Message, MessageSubscription, ProtocolBase, ProtocolBasePtr,
  27. ProtocolJobsManager, ProtocolJobsManagerPtr,
  28. },
  29. validator::ValidatorPtr,
  30. Result,
  31. };
  32. use darkfi_serial::{SerialDecodable, SerialEncodable};
  33. // Constant defining how many blocks we send during syncing.
  34. const BATCH: u64 = 10;
  35. /// Auxiliary structure used for blockchain syncing.
  36. #[derive(Debug, SerialEncodable, SerialDecodable)]
  37. pub struct SyncRequest {
  38. /// Slot UID
  39. pub slot: u64,
  40. /// Block headerhash of that slot
  41. pub block: blake3::Hash,
  42. }
  43. impl_p2p_message!(SyncRequest, "syncrequest");
  44. /// Auxiliary structure used for blockchain syncing.
  45. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  46. pub struct SyncResponse {
  47. /// Response blocks
  48. pub blocks: Vec<BlockInfo>,
  49. }
  50. impl_p2p_message!(SyncResponse, "syncresponse");
  51. pub struct ProtocolSync {
  52. request_sub: MessageSubscription<SyncRequest>,
  53. jobsman: ProtocolJobsManagerPtr,
  54. validator: ValidatorPtr,
  55. channel: ChannelPtr,
  56. }
  57. impl ProtocolSync {
  58. pub async fn init(channel: ChannelPtr, validator: ValidatorPtr) -> Result<ProtocolBasePtr> {
  59. debug!(
  60. target: "validator::protocol_sync::init",
  61. "Adding ProtocolSync to the protocol registry"
  62. );
  63. let msg_subsystem = channel.message_subsystem();
  64. msg_subsystem.add_dispatch::<SyncRequest>().await;
  65. let request_sub = channel.subscribe_msg::<SyncRequest>().await?;
  66. Ok(Arc::new(Self {
  67. request_sub,
  68. jobsman: ProtocolJobsManager::new("SyncProtocol", channel.clone()),
  69. validator,
  70. channel,
  71. }))
  72. }
  73. async fn handle_receive_request(self: Arc<Self>) -> Result<()> {
  74. debug!(target: "validator::protocol_sync::handle_receive_request", "START");
  75. loop {
  76. let request = match self.request_sub.receive().await {
  77. Ok(v) => v,
  78. Err(e) => {
  79. debug!(
  80. target: "validator::protocol_sync::handle_receive_request",
  81. "recv fail: {}",
  82. e
  83. );
  84. continue
  85. }
  86. };
  87. // Check if node has finished syncing its blockchain
  88. if !self.validator.read().await.synced {
  89. debug!(
  90. target: "validator::protocol_sync::handle_receive_request",
  91. "Node still syncing blockchain, skipping..."
  92. );
  93. continue
  94. }
  95. let key = request.slot;
  96. let blocks = match self.validator.read().await.blockchain.get_blocks_after(key, BATCH) {
  97. Ok(v) => v,
  98. Err(e) => {
  99. error!(
  100. target: "validator::protocol_sync::handle_receive_request",
  101. "get_blocks_after fail: {}",
  102. e
  103. );
  104. continue
  105. }
  106. };
  107. let response = SyncResponse { blocks };
  108. if let Err(e) = self.channel.send(&response).await {
  109. error!(
  110. target: "validator::protocol_sync::handle_receive_request",
  111. "channel send fail: {}",
  112. e
  113. )
  114. };
  115. }
  116. }
  117. }
  118. #[async_trait]
  119. impl ProtocolBase for ProtocolSync {
  120. async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
  121. debug!(target: "validator::protocol_sync::start", "START");
  122. self.jobsman.clone().start(executor.clone());
  123. self.jobsman.clone().spawn(self.clone().handle_receive_request(), executor.clone()).await;
  124. debug!(target: "validator::protocol_sync::start", "END");
  125. Ok(())
  126. }
  127. fn name(&self) -> &'static str {
  128. "ProtocolSync"
  129. }
  130. }