proposal.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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::time::Duration;
  19. use async_std::sync::Arc;
  20. use log::{debug, error, info, warn};
  21. use super::consensus_sync_task;
  22. use crate::{
  23. consensus::{constants, ValidatorStatePtr},
  24. net::P2pPtr,
  25. util::{async_util::sleep, time::Timestamp},
  26. };
  27. /// async task used for participating in the consensus protocol
  28. pub async fn proposal_task(
  29. consensus_p2p: P2pPtr,
  30. sync_p2p: P2pPtr,
  31. state: ValidatorStatePtr,
  32. ex: Arc<smol::Executor<'_>>,
  33. ) {
  34. // Check if network is configured to start in the future,
  35. // otherwise wait for current or next slot finalization period for optimal sync conditions.
  36. // NOTE: Network beign configured to start in the future should always be the case
  37. // when bootstrapping or restarting a network.
  38. let current_ts = Timestamp::current_time();
  39. let bootstrap_ts = state.read().await.consensus.bootstrap_ts;
  40. if current_ts < bootstrap_ts {
  41. let diff = bootstrap_ts.0 - current_ts.0;
  42. info!(target: "consensus::proposal", "consensus: Waiting for network bootstrap: {} seconds", diff);
  43. sleep(diff as u64).await;
  44. } else {
  45. let mut sleep_time = state.read().await.consensus.next_n_slot_start(1);
  46. let sync_offset = Duration::new(constants::FINAL_SYNC_DUR, 0);
  47. loop {
  48. if sleep_time > sync_offset {
  49. sleep_time -= sync_offset;
  50. break
  51. }
  52. info!(target: "consensus::proposal", "consensus: Waiting for next slot ({:?})", sleep_time);
  53. sleep(sleep_time.as_secs()).await;
  54. sleep_time = state.read().await.consensus.next_n_slot_start(1);
  55. }
  56. info!(target: "consensus::proposal", "consensus: Waiting for finalization sync period ({:?})", sleep_time);
  57. sleep(sleep_time.as_secs()).await;
  58. }
  59. let mut retries = 0;
  60. // Sync loop
  61. loop {
  62. // Resetting consensus state, so node can still follow the finalized blocks by
  63. // the sync p2p network/protocols
  64. state.write().await.consensus.reset();
  65. // Checking sync retries
  66. if retries > constants::SYNC_MAX_RETRIES {
  67. error!(target: "consensus::proposal", "consensus: Node reached max sync retries ({}) due to not being able to follow up with consensus processing.", constants::SYNC_MAX_RETRIES);
  68. warn!(target: "consensus::proposal", "consensus: Terminating consensus participation.");
  69. break
  70. }
  71. // Node syncs its consensus state
  72. match consensus_sync_task(consensus_p2p.clone(), state.clone()).await {
  73. Ok(p) => {
  74. // Check if node is not connected to other nodes and can
  75. // start proposing immediately.
  76. if p {
  77. info!(target: "consensus::proposal", "consensus: Node can start proposing!");
  78. state.write().await.consensus.proposing = p;
  79. }
  80. }
  81. Err(e) => {
  82. error!(target: "consensus::proposal", "consensus: Failed syncing consensus state: {}. Quitting consensus.", e);
  83. // TODO: Perhaps notify over a channel in order to
  84. // stop consensus p2p protocols.
  85. return
  86. }
  87. };
  88. // Node modifies its participating slot to next.
  89. match state.write().await.consensus.set_participating() {
  90. Ok(()) => {
  91. info!(target: "consensus::proposal", "consensus: Node will start participating in the next slot")
  92. }
  93. Err(e) => {
  94. error!(target: "consensus::proposal", "consensus: Failed to set participation slot: {}", e)
  95. }
  96. }
  97. // Record epoch we start the consensus loop
  98. let start_epoch = state.read().await.consensus.current_epoch();
  99. // Start executing consensus
  100. consensus_loop(consensus_p2p.clone(), sync_p2p.clone(), state.clone(), ex.clone()).await;
  101. // Reset retries counter if more epochs have passed than sync retries duration
  102. let break_epoch = state.read().await.consensus.current_epoch();
  103. if (break_epoch - start_epoch) > constants::SYNC_RETRIES_DURATION {
  104. retries = 0;
  105. }
  106. // Increase retries count on consensus loop break
  107. retries += 1;
  108. }
  109. }
  110. /// Consensus protocol loop
  111. async fn consensus_loop(
  112. consensus_p2p: P2pPtr,
  113. sync_p2p: P2pPtr,
  114. state: ValidatorStatePtr,
  115. ex: Arc<smol::Executor<'_>>,
  116. ) {
  117. // Note: when a node can start produce proposals is only enforced in code,
  118. // where we verify if the hardware can keep up with the consensus, by
  119. // counting how many consecutive slots node successfully listened and process
  120. // everything. Additionally, we check each proposer coin creation slot to be
  121. // greater than an epoch length. Later, this will be enforced via contract,
  122. // where it will be explicit when a node can produce proposals,
  123. // and after which slot they can be considered as valid.
  124. let mut listened_slots = 0;
  125. let mut changed_status = false;
  126. loop {
  127. // Check if node can start proposing.
  128. // This code ensures that we only change the status once
  129. // and listened_slots doesn't increment further.
  130. if listened_slots > constants::EPOCH_LENGTH {
  131. if !changed_status {
  132. info!(target: "consensus::proposal", "consensus: Node can start proposing!");
  133. state.write().await.consensus.proposing = true;
  134. changed_status = true;
  135. }
  136. } else {
  137. listened_slots += 1;
  138. }
  139. // Node waits and execute consensus protocol propose period.
  140. if propose_period(consensus_p2p.clone(), state.clone()).await {
  141. // Node needs to resync
  142. warn!(
  143. target: "consensus::proposal",
  144. "consensus: Node missed slot {} due to proposal processing, resyncing...",
  145. state.read().await.consensus.current_slot()
  146. );
  147. break
  148. }
  149. // Node waits and execute consensus protocol finalization period.
  150. if finalization_period(sync_p2p.clone(), state.clone(), ex.clone()).await {
  151. // Node needs to resync
  152. warn!(
  153. target: "consensus::proposal",
  154. "consensus: Node missed slot {} due to finalizated blocks processing, resyncing...",
  155. state.read().await.consensus.current_slot()
  156. );
  157. break
  158. }
  159. }
  160. }
  161. /// async function to wait and execute consensus protocol propose period.
  162. /// Propose period consists of 2 parts:
  163. /// - Generate slot sigmas and checkpoint
  164. /// - Check if slot leader to generate and broadcast proposal
  165. /// Returns flag in case node needs to resync.
  166. async fn propose_period(consensus_p2p: P2pPtr, state: ValidatorStatePtr) -> bool {
  167. // Node sleeps until next slot
  168. let seconds_next_slot = state.read().await.consensus.next_n_slot_start(1).as_secs();
  169. info!(target: "consensus::proposal", "consensus: Waiting for next slot ({} sec)", seconds_next_slot);
  170. sleep(seconds_next_slot).await;
  171. // Keep a record of slot to verify if next slot got skipped during processing
  172. let processing_slot = state.read().await.consensus.current_slot();
  173. // Retrieve slot sigmas
  174. let (sigma1, sigma2) = state.write().await.consensus.sigmas();
  175. // Node checks if epoch has changed and generate slot checkpoint
  176. let epoch_changed = state.write().await.consensus.epoch_changed(sigma1, sigma2).await;
  177. match epoch_changed {
  178. Ok(changed) => {
  179. if changed {
  180. info!(target: "consensus::proposal", "consensus: New epoch started: {}", state.read().await.consensus.epoch);
  181. }
  182. }
  183. Err(e) => {
  184. error!(target: "consensus::proposal", "consensus: Epoch check failed: {}", e);
  185. return false
  186. }
  187. };
  188. // Node checks if it's the slot leader to generate a new proposal
  189. // for that slot.
  190. let (won, fork_index, coin_index) =
  191. state.write().await.consensus.is_slot_leader(sigma1, sigma2);
  192. let result = if won {
  193. state.write().await.propose(processing_slot, fork_index, coin_index, sigma1, sigma2).await
  194. } else {
  195. Ok(None)
  196. };
  197. let (proposal, coin, derived_blind) = match result {
  198. Ok(pair) => {
  199. if pair.is_none() {
  200. info!(target: "consensus::proposal", "consensus: Node is not the slot lead");
  201. return false
  202. }
  203. pair.unwrap()
  204. }
  205. Err(e) => {
  206. error!(target: "consensus::proposal", "consensus: Block proposal failed: {}", e);
  207. return false
  208. }
  209. };
  210. // Node checks if it missed finalization period due to proposal creation
  211. let next_slot_start = state.read().await.consensus.next_n_slot_start(1);
  212. if next_slot_start.as_secs() <= constants::FINAL_SYNC_DUR {
  213. warn!(
  214. target: "consensus::proposal",
  215. "consensus: Node missed slot {} finalization period due to proposal creation, resyncing...",
  216. state.read().await.consensus.current_slot()
  217. );
  218. return true
  219. }
  220. // Node stores the proposal and broadcast to rest nodes
  221. info!(target: "consensus::proposal", "consensus: Node is the slot leader: Proposed block: {}", proposal);
  222. debug!(target: "consensus::proposal", "consensus: Full proposal: {:?}", proposal);
  223. match state
  224. .write()
  225. .await
  226. .receive_proposal(&proposal, Some((coin_index, coin, derived_blind)))
  227. .await
  228. {
  229. Ok(_) => {
  230. // Here we don't have to check to broadcast, because the flag
  231. // will always be true, since the node is able to produce proposals
  232. info!(target: "consensus::proposal", "consensus: Block proposal saved successfully");
  233. // Broadcast proposal to other consensus nodes
  234. match consensus_p2p.broadcast(proposal).await {
  235. Ok(()) => {
  236. info!(target: "consensus::proposal", "consensus: Proposal broadcasted successfully")
  237. }
  238. Err(e) => {
  239. error!(target: "consensus::proposal", "consensus: Failed broadcasting proposal: {}", e)
  240. }
  241. }
  242. }
  243. Err(e) => {
  244. error!(target: "consensus::proposal", "consensus: Block proposal save failed: {}", e);
  245. }
  246. }
  247. // Verify node didn't skip next slot
  248. processing_slot != state.read().await.consensus.current_slot()
  249. }
  250. /// async function to wait and execute consensus protocol finalization period.
  251. /// Returns flag in case node needs to resync.
  252. async fn finalization_period(
  253. sync_p2p: P2pPtr,
  254. state: ValidatorStatePtr,
  255. ex: Arc<smol::Executor<'_>>,
  256. ) -> bool {
  257. // Node sleeps until finalization sync period starts
  258. let next_slot_start = state.read().await.consensus.next_n_slot_start(1);
  259. if next_slot_start.as_secs() > constants::FINAL_SYNC_DUR {
  260. let seconds_sync_period =
  261. (next_slot_start - Duration::new(constants::FINAL_SYNC_DUR, 0)).as_secs();
  262. info!(target: "consensus::proposal", "consensus: Waiting for finalization sync period ({} sec)", seconds_sync_period);
  263. sleep(seconds_sync_period).await;
  264. } else {
  265. warn!(
  266. target: "consensus::proposal",
  267. "consensus: Node missed slot {} finalization period due to proposals processing, resyncing...",
  268. state.read().await.consensus.current_slot()
  269. );
  270. return true
  271. }
  272. // Keep a record of slot to verify if next slot got skipped during processing
  273. let completed_slot = state.read().await.consensus.current_slot();
  274. // Check if any forks can be finalized
  275. match state.write().await.chain_finalization().await {
  276. Ok((to_broadcast_block, to_broadcast_slot_checkpoints)) => {
  277. // Broadcasting in background
  278. if !to_broadcast_block.is_empty() || !to_broadcast_slot_checkpoints.is_empty() {
  279. ex.spawn(async move {
  280. // Broadcast finalized blocks info, if any:
  281. info!(target: "consensus::proposal", "consensus: Broadcasting finalized blocks");
  282. for info in to_broadcast_block {
  283. match sync_p2p.broadcast(info).await {
  284. Ok(()) => info!(target: "consensus::proposal", "consensus: Broadcasted block"),
  285. Err(e) => error!(target: "consensus::proposal", "consensus: Failed broadcasting block: {}", e),
  286. }
  287. }
  288. // Broadcast finalized slot checkpoints, if any:
  289. info!(target: "consensus::proposal", "consensus: Broadcasting finalized slot checkpoints");
  290. for slot_checkpoint in to_broadcast_slot_checkpoints {
  291. match sync_p2p.broadcast(slot_checkpoint).await {
  292. Ok(()) => info!(target: "consensus::proposal", "consensus: Broadcasted slot_checkpoint"),
  293. Err(e) => {
  294. error!(target: "consensus::proposal", "consensus: Failed broadcasting slot_checkpoint: {}", e)
  295. }
  296. }
  297. }
  298. })
  299. .detach();
  300. } else {
  301. info!(target: "consensus::proposal", "consensus: No finalized blocks or slot checkpoints to broadcast");
  302. }
  303. }
  304. Err(e) => {
  305. error!(target: "consensus::proposal", "consensus: Finalization check failed: {}", e);
  306. }
  307. }
  308. // Verify node didn't skip next slot
  309. completed_slot != state.read().await.consensus.current_slot()
  310. }