sync.rs 3.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 darkfi::{system::sleep, util::encoding::base64, Result};
  19. use darkfi_serial::serialize_async;
  20. use log::{debug, info, warn};
  21. use tinyjson::JsonValue;
  22. use crate::{
  23. proto::{SyncRequest, SyncResponse},
  24. Darkfid,
  25. };
  26. /// async task used for block syncing
  27. pub async fn sync_task(node: &Darkfid) -> Result<()> {
  28. info!(target: "darkfid::task::sync_task", "Starting blockchain sync...");
  29. // Block until at least node is connected to at least one peer
  30. loop {
  31. if !node.sync_p2p.channels().await.is_empty() {
  32. break
  33. }
  34. warn!(target: "darkfid::task::sync_task", "Node is not connected to other nodes, waiting to retry...");
  35. sleep(10).await;
  36. }
  37. // Getting a random connected channel to ask from peers
  38. let channel = node.sync_p2p.random_channel().await.unwrap();
  39. // Communication setup
  40. let msg_subsystem = channel.message_subsystem();
  41. msg_subsystem.add_dispatch::<SyncResponse>().await;
  42. let block_response_sub = channel.subscribe_msg::<SyncResponse>().await?;
  43. let notif_sub = node.subscribers.get("blocks").unwrap();
  44. // TODO: make this parallel and use a head selection method,
  45. // for example use a manual known head and only connect to nodes
  46. // that follow that. Also use a random peer on every block range
  47. // we sync.
  48. // Node sends the last known block hash of the canonical blockchain
  49. // and loops until the response is the same block (used to utilize
  50. // batch requests).
  51. let mut last = node.validator.blockchain.last()?;
  52. info!(target: "darkfid::task::sync_task", "Last known block: {:?} - {:?}", last.0, last.1);
  53. loop {
  54. // Node creates a `SyncRequest` and sends it
  55. let request = SyncRequest { height: last.0 };
  56. channel.send(&request).await?;
  57. // TODO: add a timeout here to retry
  58. // Node waits for response
  59. let response = block_response_sub.receive().await?;
  60. // Verify and store retrieved blocks
  61. debug!(target: "darkfid::task::sync_task", "Processing received blocks");
  62. node.validator.add_blocks(&response.blocks).await?;
  63. // Notify subscriber
  64. for block in &response.blocks {
  65. let encoded_block = JsonValue::String(base64::encode(&serialize_async(block).await));
  66. notif_sub.notify(vec![encoded_block].into()).await;
  67. }
  68. let last_received = node.validator.blockchain.last()?;
  69. info!(target: "darkfid::task::sync_task", "Last received block: {:?} - {:?}", last_received.0, last_received.1);
  70. if last == last_received {
  71. break
  72. }
  73. last = last_received;
  74. }
  75. *node.validator.synced.write().await = true;
  76. info!(target: "darkfid::task::sync_task", "Blockchain synced!");
  77. Ok(())
  78. }