consensus.rs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 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::str::FromStr;
  19. use darkfi::{
  20. blockchain::HeaderHash,
  21. rpc::{jsonrpc::JsonNotification, util::JsonValue},
  22. system::{sleep, Subscription},
  23. util::{encoding::base64, time::Timestamp},
  24. Error, Result,
  25. };
  26. use darkfi_serial::serialize_async;
  27. use smol::channel::Sender;
  28. use tracing::{error, info};
  29. use crate::{task::sync_task, DarkfiNodePtr};
  30. /// Auxiliary structure representing node consensus init task configuration.
  31. #[derive(Clone)]
  32. pub struct ConsensusInitTaskConfig {
  33. /// Skip syncing process and start node right away
  34. pub skip_sync: bool,
  35. /// Optional sync checkpoint height
  36. pub checkpoint_height: Option<u32>,
  37. /// Optional sync checkpoint hash
  38. pub checkpoint: Option<String>,
  39. }
  40. /// Sync the node consensus state and start the corresponding task, based on node type.
  41. pub async fn consensus_init_task(
  42. node: DarkfiNodePtr,
  43. config: ConsensusInitTaskConfig,
  44. sender: Sender<()>,
  45. ) -> Result<()> {
  46. // Check current canonical blockchain for curruption
  47. // TODO: create a restore method reverting each block backwards
  48. // until its healthy again
  49. let mut validator = node.validator.write().await;
  50. validator.consensus.healthcheck().await?;
  51. // Check if network genesis is in the future.
  52. let current = Timestamp::current_time().inner();
  53. let genesis = validator.consensus.module.genesis.inner();
  54. if current < genesis {
  55. let diff = genesis - current;
  56. info!(target: "darkfid::task::consensus_init_task", "Waiting for network genesis: {diff} seconds");
  57. sleep(diff).await;
  58. }
  59. // Generate a new fork to be able to extend
  60. info!(target: "darkfid::task::consensus_init_task", "Generating new empty fork...");
  61. validator.consensus.generate_empty_fork().await?;
  62. drop(validator);
  63. // Sync blockchain
  64. let comms_timeout =
  65. node.p2p_handler.p2p.settings().read_arc().await.outbound_connect_timeout_max();
  66. let checkpoint = if !config.skip_sync {
  67. // Parse configured checkpoint
  68. if config.checkpoint_height.is_some() && config.checkpoint.is_none() {
  69. return Err(Error::ParseFailed("Blockchain configured checkpoint hash missing"))
  70. }
  71. let checkpoint = if let Some(height) = config.checkpoint_height {
  72. Some((height, HeaderHash::from_str(config.checkpoint.as_ref().unwrap())?))
  73. } else {
  74. None
  75. };
  76. loop {
  77. match sync_task(&node, checkpoint).await {
  78. Ok(_) => break,
  79. Err(e) => {
  80. error!(target: "darkfid::task::consensus_task", "Sync task failed: {e}");
  81. info!(target: "darkfid::task::consensus_task", "Sleeping for {comms_timeout} before retry...");
  82. sleep(comms_timeout).await;
  83. }
  84. }
  85. }
  86. checkpoint
  87. } else {
  88. node.validator.write().await.synced = true;
  89. None
  90. };
  91. // Gracefully handle network disconnections
  92. loop {
  93. match listen_to_network(&node, &sender).await {
  94. Ok(_) => return Ok(()),
  95. Err(Error::NetworkNotConnected) => {
  96. // Sync node again
  97. node.validator.write().await.synced = false;
  98. if !config.skip_sync {
  99. loop {
  100. match sync_task(&node, checkpoint).await {
  101. Ok(_) => break,
  102. Err(e) => {
  103. error!(target: "darkfid::task::consensus_task", "Sync task failed: {e}");
  104. info!(target: "darkfid::task::consensus_task", "Sleeping for {comms_timeout} before retry...");
  105. sleep(comms_timeout).await;
  106. }
  107. }
  108. }
  109. } else {
  110. node.validator.write().await.synced = true;
  111. }
  112. }
  113. Err(e) => return Err(e),
  114. }
  115. }
  116. }
  117. /// Async task to start the consensus task, while monitoring for a network disconnections.
  118. async fn listen_to_network(node: &DarkfiNodePtr, sender: &Sender<()>) -> Result<()> {
  119. // Grab proposals subscriber and subscribe to it
  120. let proposals_sub = node.subscribers.get("proposals").unwrap();
  121. let prop_subscription = proposals_sub.publisher.clone().subscribe().await;
  122. // Subscribe to the network disconnect subscriber
  123. let net_subscription = node.p2p_handler.p2p.hosts().subscribe_disconnect().await;
  124. let result = smol::future::or(
  125. monitor_network(&net_subscription),
  126. consensus_task(node, &prop_subscription, sender),
  127. )
  128. .await;
  129. // Terminate the subscriptions
  130. prop_subscription.unsubscribe().await;
  131. net_subscription.unsubscribe().await;
  132. result
  133. }
  134. /// Async task to monitor network disconnections.
  135. async fn monitor_network(subscription: &Subscription<Error>) -> Result<()> {
  136. Err(subscription.receive().await)
  137. }
  138. /// Async task used for listening for new blocks and perform consensus.
  139. async fn consensus_task(
  140. node: &DarkfiNodePtr,
  141. subscription: &Subscription<JsonNotification>,
  142. sender: &Sender<()>,
  143. ) -> Result<()> {
  144. info!(target: "darkfid::task::consensus_task", "Starting consensus task...");
  145. // Grab blocks subscriber
  146. let block_sub = node.subscribers.get("blocks").unwrap();
  147. loop {
  148. // Wait for a new proposal
  149. subscription.receive().await;
  150. // Check if we can confirm anything and broadcast them
  151. let mut validator = node.validator.write().await;
  152. let confirmed = match validator.confirmation().await {
  153. Ok(f) => f,
  154. Err(e) => {
  155. error!(
  156. target: "darkfid::task::consensus_task",
  157. "Confirmation failed: {e}"
  158. );
  159. continue
  160. }
  161. };
  162. // Refresh mining registry
  163. if let Err(e) = node.registry.state.write().await.refresh(&validator).await {
  164. error!(target: "darkfid::task::consensus_task", "Failed refreshing mining block templates: {e}")
  165. }
  166. // Notify the garbage collection task
  167. if let Err(e) = sender.send(()).await {
  168. error!(
  169. target: "darkfid::task::consensus_task",
  170. "Garbage collection channel send fail: {e}"
  171. );
  172. };
  173. // Check if something was confirmed
  174. if confirmed.is_empty() {
  175. continue
  176. }
  177. // Broadcast confirmed blocks to subscribers
  178. let mut notif_blocks = Vec::with_capacity(confirmed.len());
  179. for block in confirmed {
  180. notif_blocks.push(JsonValue::String(base64::encode(&serialize_async(&block).await)));
  181. }
  182. block_sub.notify(JsonValue::Array(notif_blocks)).await;
  183. }
  184. }