proposal.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2022 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};
  21. use super::consensus_sync_task;
  22. use crate::{
  23. consensus::{constants, ValidatorStatePtr},
  24. net::P2pPtr,
  25. util::async_util::sleep,
  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. // Node waits just before the current or next epoch last finalization syncing period, so it can
  35. // start syncing latest state.
  36. let mut seconds_until_next_epoch = state.read().await.consensus.next_n_epoch_start(1);
  37. let sync_offset = Duration::new(constants::FINAL_SYNC_DUR + 1, 0);
  38. loop {
  39. if seconds_until_next_epoch > sync_offset {
  40. seconds_until_next_epoch -= sync_offset;
  41. break
  42. }
  43. info!("consensus: Waiting for next epoch ({:?} sec)", seconds_until_next_epoch);
  44. sleep(seconds_until_next_epoch.as_secs()).await;
  45. seconds_until_next_epoch = state.read().await.consensus.next_n_epoch_start(1);
  46. }
  47. info!("consensus: Waiting for next epoch ({:?} sec)", seconds_until_next_epoch);
  48. sleep(seconds_until_next_epoch.as_secs()).await;
  49. // Node syncs its consensus state
  50. if let Err(e) = consensus_sync_task(consensus_p2p.clone(), state.clone()).await {
  51. error!("consensus: Failed syncing consensus state: {}. Quitting consensus.", e);
  52. // TODO: Perhaps notify over a channel in order to
  53. // stop consensus p2p protocols.
  54. return
  55. };
  56. // Node modifies its participating slot to next.
  57. match state.write().await.consensus.set_participating() {
  58. Ok(()) => info!("consensus: Node will start participating in the next slot"),
  59. Err(e) => error!("consensus: Failed to set participation slot: {}", e),
  60. }
  61. loop {
  62. // Node sleeps until finalization sync period start (2 seconds before next slot)
  63. let seconds_sync_period = (state.read().await.consensus.next_n_slot_start(1) -
  64. Duration::new(constants::FINAL_SYNC_DUR, 0))
  65. .as_secs();
  66. info!("consensus: Waiting for finalization sync period ({} sec)", seconds_sync_period);
  67. sleep(seconds_sync_period).await;
  68. // Check if any forks can be finalized
  69. match state.write().await.chain_finalization().await {
  70. Ok((to_broadcast_block, to_broadcast_slot_checkpoints)) => {
  71. // Broadcasting in background
  72. if !to_broadcast_block.is_empty() || !to_broadcast_slot_checkpoints.is_empty() {
  73. let _sync_p2p = sync_p2p.clone();
  74. ex.spawn(async move {
  75. // Broadcast finalized blocks info, if any:
  76. info!("consensus: Broadcasting finalized blocks");
  77. for info in to_broadcast_block {
  78. match _sync_p2p.broadcast(info).await {
  79. Ok(()) => info!("consensus: Broadcasted block"),
  80. Err(e) => error!("consensus: Failed broadcasting block: {}", e),
  81. }
  82. }
  83. // Broadcast finalized slot checkpoints, if any:
  84. info!("consensus: Broadcasting finalized slot checkpoints");
  85. for slot_checkpoint in to_broadcast_slot_checkpoints {
  86. match _sync_p2p.broadcast(slot_checkpoint).await {
  87. Ok(()) => info!("consensus: Broadcasted slot_checkpoint"),
  88. Err(e) => {
  89. error!("consensus: Failed broadcasting slot_checkpoint: {}", e)
  90. }
  91. }
  92. }
  93. })
  94. .detach();
  95. } else {
  96. info!("consensus: No finalized blocks or slot checkpoints to broadcast");
  97. }
  98. }
  99. Err(e) => {
  100. error!("consensus: Finalization check failed: {}", e);
  101. }
  102. }
  103. // Node sleeps until next slot
  104. let seconds_next_slot = state.read().await.consensus.next_n_slot_start(1).as_secs();
  105. info!("consensus: Waiting for next slot ({} sec)", seconds_next_slot);
  106. sleep(seconds_next_slot).await;
  107. // Retrieve slot sigmas
  108. let (sigma1, sigma2) = state.write().await.consensus.sigmas();
  109. // Node checks if epoch has changed, to generate new epoch coins
  110. let epoch_changed = state.write().await.consensus.epoch_changed(sigma1, sigma2).await;
  111. match epoch_changed {
  112. Ok(changed) => {
  113. if changed {
  114. info!("consensus: New epoch started: {}", state.read().await.consensus.epoch);
  115. }
  116. }
  117. Err(e) => {
  118. error!("consensus: Epoch check failed: {}", e);
  119. continue
  120. }
  121. };
  122. // Node checks if it's the slot leader to generate a new proposal
  123. // for that slot.
  124. let (won, idx) = state.write().await.consensus.is_slot_leader(sigma1, sigma2);
  125. let result = if won { state.write().await.propose(idx, sigma1, sigma2) } else { Ok(None) };
  126. let (proposal, coin) = match result {
  127. Ok(pair) => {
  128. if pair.is_none() {
  129. info!("consensus: Node is not the slot lead");
  130. continue
  131. }
  132. pair.unwrap()
  133. }
  134. Err(e) => {
  135. error!("consensus: Block proposal failed: {}", e);
  136. continue
  137. }
  138. };
  139. // Node stores the proposal and broadcast to rest nodes
  140. info!("consensus: Node is the slot leader: Proposed block: {}", proposal);
  141. debug!("consensus: Full proposal: {:?}", proposal);
  142. match state.write().await.receive_proposal(&proposal, Some((idx, coin))).await {
  143. Ok(()) => {
  144. info!("consensus: Block proposal saved successfully");
  145. // Broadcast proposal to other consensus nodes
  146. match consensus_p2p.broadcast(proposal).await {
  147. Ok(()) => info!("consensus: Proposal broadcasted successfully"),
  148. Err(e) => error!("consensus: Failed broadcasting proposal: {}", e),
  149. }
  150. }
  151. Err(e) => {
  152. error!("consensus: Block proposal save failed: {}", e);
  153. }
  154. }
  155. }
  156. }
  157. /// async task used for participating in the consensus protocol
  158. pub async fn proposal_task2(
  159. consensus_p2p: P2pPtr,
  160. sync_p2p: P2pPtr,
  161. state: ValidatorStatePtr,
  162. ex: Arc<smol::Executor<'_>>,
  163. ) {
  164. let mut retries = 0;
  165. // Sync loop
  166. loop {
  167. // Setting up participating to None, so node can still follow the finalized blocks by
  168. // the sync p2p network/protocols
  169. state.write().await.consensus.participating = None;
  170. // Checking sync retries
  171. if retries > constants::SYNC_MAX_RETRIES {
  172. error!("consensus: Node reached max sync retries ({}) due to not being able to follow up with consensus processing.", constants::SYNC_MAX_RETRIES);
  173. warn!("consensus: Terminating consensus participation.");
  174. break
  175. }
  176. // Node waits just before the current or next epoch last finalization syncing period, so it can
  177. // start syncing latest state.
  178. let mut seconds_until_next_epoch = state.read().await.consensus.next_n_epoch_start(1);
  179. let sync_offset = Duration::new(constants::FINAL_SYNC_DUR + 1, 0);
  180. loop {
  181. if seconds_until_next_epoch > sync_offset {
  182. seconds_until_next_epoch -= sync_offset;
  183. break
  184. }
  185. info!("consensus: Waiting for next epoch ({:?} sec)", seconds_until_next_epoch);
  186. sleep(seconds_until_next_epoch.as_secs()).await;
  187. seconds_until_next_epoch = state.read().await.consensus.next_n_epoch_start(1);
  188. }
  189. info!("consensus: Waiting for next epoch ({:?} sec)", seconds_until_next_epoch);
  190. sleep(seconds_until_next_epoch.as_secs()).await;
  191. // Node syncs its consensus state
  192. if let Err(e) = consensus_sync_task(consensus_p2p.clone(), state.clone()).await {
  193. error!("consensus: Failed syncing consensus state: {}. Quitting consensus.", e);
  194. // TODO: Perhaps notify over a channel in order to
  195. // stop consensus p2p protocols.
  196. return
  197. };
  198. // Node modifies its participating slot to next.
  199. match state.write().await.consensus.set_participating() {
  200. Ok(()) => info!("consensus: Node will start participating in the next slot"),
  201. Err(e) => error!("consensus: Failed to set participation slot: {}", e),
  202. }
  203. // Start executing consensus
  204. consensus_loop(consensus_p2p.clone(), sync_p2p.clone(), state.clone(), ex.clone()).await;
  205. // Increase retries count on consensus loop break
  206. retries += 1;
  207. }
  208. }
  209. /// Consensus protocol loop
  210. async fn consensus_loop(
  211. consensus_p2p: P2pPtr,
  212. sync_p2p: P2pPtr,
  213. state: ValidatorStatePtr,
  214. ex: Arc<smol::Executor<'_>>,
  215. ) {
  216. loop {
  217. // Node sleeps until finalization sync period starts
  218. let next_slot_start = state.read().await.consensus.next_n_slot_start(1);
  219. let seconds_sync_period = if next_slot_start.as_secs() > constants::FINAL_SYNC_DUR {
  220. (next_slot_start - Duration::new(constants::FINAL_SYNC_DUR, 0)).as_secs()
  221. } else {
  222. next_slot_start.as_secs()
  223. };
  224. info!("consensus: Waiting for finalization sync period ({} sec)", seconds_sync_period);
  225. sleep(seconds_sync_period).await;
  226. // Keep a record of slot to verify if next slot got skipped during processing
  227. let completed_slot = state.read().await.consensus.current_slot();
  228. // Check if any forks can be finalized
  229. match state.write().await.chain_finalization().await {
  230. Ok((to_broadcast_block, to_broadcast_slot_checkpoints)) => {
  231. // Broadcasting in background
  232. if !to_broadcast_block.is_empty() || !to_broadcast_slot_checkpoints.is_empty() {
  233. let _sync_p2p = sync_p2p.clone();
  234. ex.spawn(async move {
  235. // Broadcast finalized blocks info, if any:
  236. info!("consensus: Broadcasting finalized blocks");
  237. for info in to_broadcast_block {
  238. match _sync_p2p.broadcast(info).await {
  239. Ok(()) => info!("consensus: Broadcasted block"),
  240. Err(e) => error!("consensus: Failed broadcasting block: {}", e),
  241. }
  242. }
  243. // Broadcast finalized slot checkpoints, if any:
  244. info!("consensus: Broadcasting finalized slot checkpoints");
  245. for slot_checkpoint in to_broadcast_slot_checkpoints {
  246. match _sync_p2p.broadcast(slot_checkpoint).await {
  247. Ok(()) => info!("consensus: Broadcasted slot_checkpoint"),
  248. Err(e) => {
  249. error!("consensus: Failed broadcasting slot_checkpoint: {}", e)
  250. }
  251. }
  252. }
  253. })
  254. .detach();
  255. } else {
  256. info!("consensus: No finalized blocks or slot checkpoints to broadcast");
  257. }
  258. }
  259. Err(e) => {
  260. error!("consensus: Finalization check failed: {}", e);
  261. }
  262. }
  263. // Verify node didn't skip next slot
  264. let current_slot = state.read().await.consensus.current_slot();
  265. if completed_slot == current_slot {
  266. warn!(
  267. "consensus: Node missed slot {} due to finalizated blocks processing, resyncing...",
  268. current_slot
  269. );
  270. break
  271. }
  272. // Node sleeps until next slot
  273. let seconds_next_slot = state.read().await.consensus.next_n_slot_start(1).as_secs();
  274. info!("consensus: Waiting for next slot ({} sec)", seconds_next_slot);
  275. sleep(seconds_next_slot).await;
  276. // Keep a record of slot to verify if next slot got skipped during processing
  277. let processing_slot = state.read().await.consensus.current_slot();
  278. // Retrieve slot sigmas
  279. let (sigma1, sigma2) = state.write().await.consensus.sigmas();
  280. // Node checks if epoch has changed and generate slot checkpoint
  281. let epoch_changed = state.write().await.consensus.epoch_changed(sigma1, sigma2).await;
  282. match epoch_changed {
  283. Ok(changed) => {
  284. if changed {
  285. info!("consensus: New epoch started: {}", state.read().await.consensus.epoch);
  286. }
  287. }
  288. Err(e) => {
  289. error!("consensus: Epoch check failed: {}", e);
  290. continue
  291. }
  292. };
  293. // Node checks if it's the slot leader to generate a new proposal
  294. // for that slot.
  295. let (won, idx) = state.write().await.consensus.is_slot_leader(sigma1, sigma2);
  296. let result = if won { state.write().await.propose(idx, sigma1, sigma2) } else { Ok(None) };
  297. let (proposal, coin) = match result {
  298. Ok(pair) => {
  299. if pair.is_none() {
  300. info!("consensus: Node is not the slot lead");
  301. continue
  302. }
  303. pair.unwrap()
  304. }
  305. Err(e) => {
  306. error!("consensus: Block proposal failed: {}", e);
  307. continue
  308. }
  309. };
  310. // Node stores the proposal and broadcast to rest nodes
  311. info!("consensus: Node is the slot leader: Proposed block: {}", proposal);
  312. debug!("consensus: Full proposal: {:?}", proposal);
  313. match state.write().await.receive_proposal(&proposal, Some((idx, coin))).await {
  314. Ok(()) => {
  315. info!("consensus: Block proposal saved successfully");
  316. // Broadcast proposal to other consensus nodes
  317. match consensus_p2p.broadcast(proposal).await {
  318. Ok(()) => info!("consensus: Proposal broadcasted successfully"),
  319. Err(e) => error!("consensus: Failed broadcasting proposal: {}", e),
  320. }
  321. }
  322. Err(e) => {
  323. error!("consensus: Block proposal save failed: {}", e);
  324. }
  325. }
  326. // Verify node didn't skip next slot
  327. let current_slot = state.read().await.consensus.current_slot();
  328. if processing_slot != current_slot {
  329. warn!(
  330. "consensus: Node missed slot {} due to proposal processing, resyncing...",
  331. current_slot
  332. );
  333. break
  334. }
  335. }
  336. }