sync.rs 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  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 darkfi::{system::sleep, util::encoding::base64};
  19. use darkfi_serial::serialize;
  20. use log::{debug, info, warn, error};
  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) {
  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 = match channel.subscribe_msg::<SyncResponse>().await {
  43. Err(why) => {
  44. // if there is Error::NetworkOperationFailed returns at dispatcher subscription attempt
  45. panic!("darkiid2::task::sync_task channel subscribe_msg failed at dispatcher subscription: {:?}", why);
  46. },
  47. Ok(value) => value
  48. };
  49. let notif_sub = node.subscribers.get("blocks").unwrap();
  50. // TODO: make this parallel and use a head selection method,
  51. // for example use a manual known head and only connect to nodes
  52. // that follow that. Also use a random peer on every block range
  53. // we sync.
  54. // Node sends the last known block hash of the canonical blockchain
  55. // and loops until the response is the same block (used to utilize
  56. // batch requests).
  57. let mut last = match node.validator.read().await.blockchain.last() {
  58. Err(why) => {
  59. panic!("darkfid::task::sync_task attempting to retrive last block at empty BlockOrderStore sledTree: {:?}", why)
  60. },
  61. Ok(value) => value
  62. };
  63. info!(target: "darkfid::task::sync_task", "Last known block: {:?} - {:?}", last.0, last.1);
  64. loop {
  65. // Node creates a `SyncRequest` and sends it
  66. let request = SyncRequest { slot: last.0, block: last.1 };
  67. if let Err(why) = channel.send(&request).await {
  68. error!(target: "darkfid::task::sync_task", "request send failure: {:}", why);
  69. sleep(10).await;
  70. continue;
  71. }
  72. // TODO: add a timeout here to retry
  73. // Node waits for response
  74. let response = match block_response_sub.receive().await {
  75. Err(why) => {
  76. panic!("darkfid::task::sync_task block_response_sub receive error at recv_queue recv: {:?}", why)
  77. },
  78. Ok(value) => value
  79. };
  80. // Verify and store retrieved blocks
  81. debug!(target: "darkfid::task::sync_task", "Processing received blocks");
  82. if let Err(why) = node.validator.write().await.add_blocks(&response.blocks).await {
  83. panic!("darkfid::task::sync_task block validation failed: {:?}", why)
  84. };
  85. // Notify subscriber
  86. for block in &response.blocks {
  87. let encoded_block = JsonValue::String(base64::encode(&serialize(block)));
  88. notif_sub.notify(vec![encoded_block].into()).await;
  89. }
  90. let last_received = match node.validator.read().await.blockchain.last() {
  91. Err(why) => {
  92. panic!("darkfid::task::sync_task attempting to retrive last block at empty BlockOrderStore sledTree: {:?}", why)
  93. },
  94. Ok(value) => value
  95. };
  96. info!(target: "darkfid::task::sync_task", "Last received block: {:?} - {:?}", last_received.0, last_received.1);
  97. if last == last_received {
  98. break
  99. }
  100. last = last_received;
  101. }
  102. node.validator.write().await.synced = true;
  103. info!(target: "darkfid::task::sync_task", "Blockchain synced!");
  104. }