unknown_proposal.rs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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::{collections::HashSet, sync::Arc};
  19. use smol::{channel::Receiver, lock::RwLock};
  20. use tinyjson::JsonValue;
  21. use tracing::{debug, error, info};
  22. use darkfi::{
  23. blockchain::BlockDifficulty,
  24. net::{ChannelPtr, P2pPtr},
  25. rpc::jsonrpc::JsonSubscriber,
  26. util::encoding::base64,
  27. validator::{
  28. consensus::{Fork, Proposal},
  29. pow::PoWModule,
  30. utils::{best_fork_index, header_rank},
  31. verification::verify_fork_proposal,
  32. ValidatorPtr,
  33. },
  34. Error, Result,
  35. };
  36. use darkfi_serial::serialize_async;
  37. use crate::proto::{
  38. ForkHeaderHashRequest, ForkHeaderHashResponse, ForkHeadersRequest, ForkHeadersResponse,
  39. ForkProposalsRequest, ForkProposalsResponse, ForkSyncRequest, ForkSyncResponse,
  40. ProposalMessage, BATCH,
  41. };
  42. /// Background task to handle unknown proposals.
  43. pub async fn handle_unknown_proposals(
  44. receiver: Receiver<(Proposal, u32)>,
  45. unknown_proposals: Arc<RwLock<HashSet<[u8; 32]>>>,
  46. validator: ValidatorPtr,
  47. p2p: P2pPtr,
  48. proposals_sub: JsonSubscriber,
  49. blocks_sub: JsonSubscriber,
  50. ) -> Result<()> {
  51. debug!(target: "darkfid::task::handle_unknown_proposal", "START");
  52. loop {
  53. // Wait for a new unknown proposal trigger
  54. let (proposal, channel) = match receiver.recv().await {
  55. Ok(m) => m,
  56. Err(e) => {
  57. debug!(
  58. target: "darkfid::task::handle_unknown_proposal",
  59. "recv fail: {e}"
  60. );
  61. continue
  62. }
  63. };
  64. // Check if proposal exists in our queue
  65. let lock = unknown_proposals.read().await;
  66. let contains_proposal = lock.contains(proposal.hash.inner());
  67. drop(lock);
  68. if !contains_proposal {
  69. debug!(
  70. target: "darkfid::task::handle_unknown_proposal",
  71. "Proposal {} is not in our unknown proposals queue.",
  72. proposal.hash,
  73. );
  74. continue
  75. };
  76. // Handle the unknown proposal
  77. if handle_unknown_proposal(
  78. &validator,
  79. &p2p,
  80. &proposals_sub,
  81. &blocks_sub,
  82. channel,
  83. &proposal,
  84. )
  85. .await
  86. {
  87. // Ban channel if it exists
  88. if let Some(channel) = p2p.get_channel(channel) {
  89. channel.ban().await;
  90. }
  91. };
  92. // Remove proposal from the queue
  93. let mut lock = unknown_proposals.write().await;
  94. lock.remove(proposal.hash.inner());
  95. drop(lock);
  96. }
  97. }
  98. /// Background task to handle an unknown proposal.
  99. /// Returns a boolean flag indicate if we should ban the channel.
  100. async fn handle_unknown_proposal(
  101. validator: &ValidatorPtr,
  102. p2p: &P2pPtr,
  103. proposals_sub: &JsonSubscriber,
  104. blocks_sub: &JsonSubscriber,
  105. channel: u32,
  106. proposal: &Proposal,
  107. ) -> bool {
  108. // If proposal fork chain was not found, we ask our peer for its sequence
  109. debug!(target: "darkfid::task::handle_unknown_proposal", "Asking peer for fork sequence");
  110. let Some(channel) = p2p.get_channel(channel) else {
  111. debug!(target: "darkfid::task::handle_unknown_proposal", "Channel {channel} wasn't found.");
  112. return false
  113. };
  114. // Communication setup
  115. let Ok(response_sub) = channel.subscribe_msg::<ForkSyncResponse>().await else {
  116. debug!(target: "darkfid::task::handle_unknown_proposal", "Failure during `ForkSyncResponse` communication setup with peer: {channel:?}");
  117. return true
  118. };
  119. // Grab last known block to create the request and execute it
  120. let last = match validator.blockchain.last() {
  121. Ok(l) => l,
  122. Err(e) => {
  123. error!(target: "darkfid::task::handle_unknown_proposal", "Blockchain last retriaval failed: {e}");
  124. return false
  125. }
  126. };
  127. let request = ForkSyncRequest { tip: last.1, fork_tip: Some(proposal.hash) };
  128. if let Err(e) = channel.send(&request).await {
  129. debug!(target: "darkfid::task::handle_unknown_proposal", "Channel send failed: {e}");
  130. return true
  131. };
  132. // Node waits for response
  133. let response = match response_sub
  134. .receive_with_timeout(p2p.settings().read().await.outbound_connect_timeout)
  135. .await
  136. {
  137. Ok(r) => r,
  138. Err(e) => {
  139. debug!(target: "darkfid::task::handle_unknown_proposal", "Asking peer for fork sequence failed: {e}");
  140. return true
  141. }
  142. };
  143. debug!(target: "darkfid::task::handle_unknown_proposal", "Peer response: {response:?}");
  144. // Verify and store retrieved proposals
  145. debug!(target: "darkfid::task::handle_unknown_proposal", "Processing received proposals");
  146. // Response should not be empty
  147. if response.proposals.is_empty() {
  148. debug!(target: "darkfid::task::handle_unknown_proposal", "Peer responded with empty sequence, node might be out of sync!");
  149. return handle_reorg(validator, p2p, proposals_sub, blocks_sub, channel, proposal).await
  150. }
  151. // Sequence length must correspond to requested height
  152. if response.proposals.len() as u32 != proposal.block.header.height - last.0 {
  153. debug!(target: "darkfid::task::handle_unknown_proposal", "Response sequence length is erroneous");
  154. return handle_reorg(validator, p2p, proposals_sub, blocks_sub, channel, proposal).await
  155. }
  156. // First proposal must extend canonical
  157. if response.proposals[0].block.header.previous != last.1 {
  158. debug!(target: "darkfid::task::handle_unknown_proposal", "Response sequence doesn't extend canonical");
  159. return handle_reorg(validator, p2p, proposals_sub, blocks_sub, channel, proposal).await
  160. }
  161. // Last proposal must be the same as the one requested
  162. if response.proposals.last().unwrap().hash != proposal.hash {
  163. debug!(target: "darkfid::task::handle_unknown_proposal", "Response sequence doesn't correspond to requested tip");
  164. return handle_reorg(validator, p2p, proposals_sub, blocks_sub, channel, proposal).await
  165. }
  166. // Process response proposals
  167. for proposal in &response.proposals {
  168. // Append proposal
  169. match validator.append_proposal(proposal).await {
  170. Ok(()) => { /* Do nothing */ }
  171. // Skip already existing proposals
  172. Err(Error::ProposalAlreadyExists) => continue,
  173. Err(e) => {
  174. debug!(
  175. target: "darkfid::task::handle_unknown_proposal",
  176. "Error while appending response proposal: {e}"
  177. );
  178. break;
  179. }
  180. };
  181. // Broadcast proposal to rest nodes
  182. let message = ProposalMessage(proposal.clone());
  183. p2p.broadcast_with_exclude(&message, &[channel.address().clone()]).await;
  184. // Notify proposals subscriber
  185. let enc_prop = JsonValue::String(base64::encode(&serialize_async(proposal).await));
  186. proposals_sub.notify(vec![enc_prop].into()).await;
  187. }
  188. false
  189. }
  190. /// Auxiliary function to handle a potential reorg.
  191. /// We first find our last common block with the peer,
  192. /// then grab the header sequence from that block until
  193. /// the proposal and check if it ranks higher than our
  194. /// current best ranking fork, to perform a reorg.
  195. /// Returns a boolean flag indicate if we should ban the
  196. /// channel.
  197. async fn handle_reorg(
  198. validator: &ValidatorPtr,
  199. p2p: &P2pPtr,
  200. proposals_sub: &JsonSubscriber,
  201. blocks_sub: &JsonSubscriber,
  202. channel: ChannelPtr,
  203. proposal: &Proposal,
  204. ) -> bool {
  205. info!(target: "darkfid::task::handle_reorg", "Checking for potential reorg from proposal {} - {} by peer: {channel:?}", proposal.hash, proposal.block.header.height);
  206. // Check if genesis proposal was provided
  207. if proposal.block.header.height == 0 {
  208. debug!(target: "darkfid::task::handle_reorg", "Peer send a genesis proposal, skipping...");
  209. return true
  210. }
  211. // Communication setup
  212. let Ok(response_sub) = channel.subscribe_msg::<ForkHeaderHashResponse>().await else {
  213. debug!(target: "darkfid::task::handle_reorg", "Failure during `ForkHeaderHashResponse` communication setup with peer: {channel:?}");
  214. return true
  215. };
  216. // Keep track of received header hashes sequence
  217. let mut peer_header_hashes = vec![];
  218. // Find last common header, going backwards from the proposal
  219. let mut previous_height = proposal.block.header.height;
  220. let mut previous_hash = proposal.hash;
  221. for height in (0..proposal.block.header.height).rev() {
  222. // Request peer header hash for this height
  223. let request = ForkHeaderHashRequest { height, fork_header: proposal.hash };
  224. if let Err(e) = channel.send(&request).await {
  225. debug!(target: "darkfid::task::handle_reorg", "Channel send failed: {e}");
  226. return true
  227. };
  228. // Node waits for response
  229. let response = match response_sub
  230. .receive_with_timeout(p2p.settings().read().await.outbound_connect_timeout)
  231. .await
  232. {
  233. Ok(r) => r,
  234. Err(e) => {
  235. debug!(target: "darkfid::task::handle_reorg", "Asking peer for header hash failed: {e}");
  236. return true
  237. }
  238. };
  239. debug!(target: "darkfid::task::handle_reorg", "Peer response: {response:?}");
  240. // Check if peer returned a header
  241. let Some(peer_header) = response.fork_header else {
  242. debug!(target: "darkfid::task::handle_reorg", "Peer responded with an empty header");
  243. return true
  244. };
  245. // Check if we know this header
  246. let headers = match validator.blockchain.blocks.get_order(&[height], false) {
  247. Ok(r) => r,
  248. Err(e) => {
  249. error!(target: "darkfid::task::handle_reorg", "Retrieving headers failed: {e}");
  250. return false
  251. }
  252. };
  253. match headers[0] {
  254. Some(known_header) => {
  255. if known_header == peer_header {
  256. previous_height = height;
  257. previous_hash = known_header;
  258. break
  259. }
  260. // Since we retrieve in right -> left order we push them in reverse order
  261. peer_header_hashes.insert(0, peer_header);
  262. }
  263. None => peer_header_hashes.insert(0, peer_header),
  264. }
  265. }
  266. // Check if we have a sequence to process
  267. if peer_header_hashes.is_empty() {
  268. debug!(target: "darkfid::task::handle_reorg", "No headers to process, skipping...");
  269. return true
  270. }
  271. // Communication setup
  272. let Ok(response_sub) = channel.subscribe_msg::<ForkHeadersResponse>().await else {
  273. debug!(target: "darkfid::task::handle_reorg", "Failure during `ForkHeadersResponse` communication setup with peer: {channel:?}");
  274. return true
  275. };
  276. // Grab last common height ranks
  277. let last_common_height = previous_height;
  278. let last_difficulty = match previous_height {
  279. 0 => {
  280. let genesis_timestamp = match validator.blockchain.genesis_block() {
  281. Ok(b) => b.header.timestamp,
  282. Err(e) => {
  283. error!(target: "darkfid::task::handle_reorg", "Retrieving genesis block failed: {e}");
  284. return false
  285. }
  286. };
  287. BlockDifficulty::genesis(genesis_timestamp)
  288. }
  289. _ => match validator.blockchain.blocks.get_difficulty(&[last_common_height], true) {
  290. Ok(d) => d[0].clone().unwrap(),
  291. Err(e) => {
  292. error!(target: "darkfid::task::handle_reorg", "Retrieving block difficulty failed: {e}");
  293. return false
  294. }
  295. },
  296. };
  297. // Create a new PoW from last common height
  298. let module = match PoWModule::new(
  299. validator.consensus.blockchain.clone(),
  300. validator.consensus.module.read().await.target,
  301. validator.consensus.module.read().await.fixed_difficulty.clone(),
  302. Some(last_common_height + 1),
  303. ) {
  304. Ok(m) => m,
  305. Err(e) => {
  306. error!(target: "darkfid::task::handle_reorg", "PoWModule generation failed: {e}");
  307. return false
  308. }
  309. };
  310. // Retrieve the headers of the hashes sequence, in batches, keeping track of the sequence ranking
  311. info!(target: "darkfid::task::handle_reorg", "Retrieving {} headers from peer...", peer_header_hashes.len());
  312. let mut batch = Vec::with_capacity(BATCH);
  313. let mut total_processed = 0;
  314. let mut targets_rank = last_difficulty.ranks.targets_rank.clone();
  315. let mut hashes_rank = last_difficulty.ranks.hashes_rank.clone();
  316. let mut headers_module = module.clone();
  317. for (index, hash) in peer_header_hashes.iter().enumerate() {
  318. // Add hash in batch sequence
  319. batch.push(*hash);
  320. // Check if batch is full so we can send it
  321. if batch.len() < BATCH && index != peer_header_hashes.len() - 1 {
  322. continue
  323. }
  324. // Request peer headers
  325. let request = ForkHeadersRequest { headers: batch.clone(), fork_header: proposal.hash };
  326. if let Err(e) = channel.send(&request).await {
  327. debug!(target: "darkfid::task::handle_reorg", "Channel send failed: {e}");
  328. return true
  329. };
  330. // Node waits for response
  331. let response = match response_sub
  332. .receive_with_timeout(p2p.settings().read().await.outbound_connect_timeout)
  333. .await
  334. {
  335. Ok(r) => r,
  336. Err(e) => {
  337. debug!(target: "darkfid::task::handle_reorg", "Asking peer for headers sequence failed: {e}");
  338. return true
  339. }
  340. };
  341. debug!(target: "darkfid::task::handle_reorg", "Peer response: {response:?}");
  342. // Response sequence must be the same length as the one requested
  343. if response.headers.len() != batch.len() {
  344. debug!(target: "darkfid::task::handle_reorg", "Peer responded with a different headers sequence length");
  345. return true
  346. }
  347. // Process retrieved headers
  348. for (peer_header_index, peer_header) in response.headers.iter().enumerate() {
  349. let peer_header_hash = peer_header.hash();
  350. debug!(target: "darkfid::task::handle_reorg", "Processing header: {peer_header_hash} - {}", peer_header.height);
  351. // Validate its the header we requested
  352. if peer_header_hash != batch[peer_header_index] {
  353. debug!(target: "darkfid::task::handle_reorg", "Peer responded with a differend header: {} - {peer_header_hash}", batch[peer_header_index]);
  354. return true
  355. }
  356. // Validate sequence is correct
  357. if peer_header.previous != previous_hash || peer_header.height != previous_height + 1 {
  358. debug!(target: "darkfid::task::handle_reorg", "Invalid header sequence detected");
  359. return true
  360. }
  361. // Grab next mine target and difficulty
  362. let (next_target, next_difficulty) = match headers_module
  363. .next_mine_target_and_difficulty()
  364. {
  365. Ok(p) => p,
  366. Err(e) => {
  367. debug!(target: "darkfid::task::handle_reorg", "Retrieving next mine target and difficulty failed: {e}");
  368. return false
  369. }
  370. };
  371. // Verify header hash and calculate its rank
  372. let (target_distance_sq, hash_distance_sq) = match header_rank(
  373. peer_header,
  374. &next_target,
  375. ) {
  376. Ok(distances) => distances,
  377. Err(e) => {
  378. debug!(target: "darkfid::task::handle_reorg", "Invalid header hash detected: {e}");
  379. return true
  380. }
  381. };
  382. // Update sequence ranking
  383. targets_rank += target_distance_sq.clone();
  384. hashes_rank += hash_distance_sq.clone();
  385. // Update PoW headers module
  386. headers_module.append(peer_header.timestamp, &next_difficulty);
  387. // Set previous header
  388. previous_height = peer_header.height;
  389. previous_hash = peer_header_hash;
  390. }
  391. total_processed += response.headers.len();
  392. info!(target: "darkfid::task::handle_reorg", "Headers received and verified: {total_processed}/{}", peer_header_hashes.len());
  393. // Reset batch
  394. batch = Vec::with_capacity(BATCH);
  395. }
  396. // Check if the sequence ranks higher than our current best fork
  397. let forks = validator.consensus.forks.read().await;
  398. let index = match best_fork_index(&forks) {
  399. Ok(i) => i,
  400. Err(e) => {
  401. debug!(target: "darkfid::task::handle_reorg", "Retrieving best fork index failed: {e}");
  402. return false
  403. }
  404. };
  405. let best_fork = &forks[index];
  406. if targets_rank < best_fork.targets_rank ||
  407. (targets_rank == best_fork.targets_rank && hashes_rank <= best_fork.hashes_rank)
  408. {
  409. info!(target: "darkfid::task::handle_reorg", "Peer sequence ranks lower than our current best fork, skipping...");
  410. drop(forks);
  411. return true
  412. }
  413. drop(forks);
  414. // Communication setup
  415. let Ok(response_sub) = channel.subscribe_msg::<ForkProposalsResponse>().await else {
  416. debug!(target: "darkfid::task::handle_reorg", "Failure during `ForkProposalsResponse` communication setup with peer: {channel:?}");
  417. return true
  418. };
  419. // Create a fork from last common height
  420. let mut peer_fork =
  421. match Fork::new(validator.consensus.blockchain.clone(), module.clone()).await {
  422. Ok(f) => f,
  423. Err(e) => {
  424. error!(target: "darkfid::task::handle_reorg", "Generating peer fork failed: {e}");
  425. return false
  426. }
  427. };
  428. peer_fork.targets_rank = last_difficulty.ranks.targets_rank.clone();
  429. peer_fork.hashes_rank = last_difficulty.ranks.hashes_rank.clone();
  430. // Grab all state inverse diffs after last common height, and add them to the fork
  431. let inverse_diffs = match validator
  432. .blockchain
  433. .blocks
  434. .get_state_inverse_diffs_after(last_common_height)
  435. {
  436. Ok(i) => i,
  437. Err(e) => {
  438. error!(target: "darkfid::task::handle_reorg", "Retrieving state inverse diffs failed: {e}");
  439. return false
  440. }
  441. };
  442. for inverse_diff in inverse_diffs.iter().rev() {
  443. if let Err(e) =
  444. peer_fork.overlay.lock().unwrap().overlay.lock().unwrap().add_diff(inverse_diff)
  445. {
  446. error!(target: "darkfid::task::handle_reorg", "Applying inverse diff failed: {e}");
  447. return false
  448. }
  449. }
  450. // Rebuild fork contracts states monotree
  451. if let Err(e) = peer_fork.compute_monotree() {
  452. error!(target: "darkfid::task::handle_reorg", "Rebuilding peer fork monotree failed: {e}");
  453. return false
  454. }
  455. // Retrieve the proposals of the hashes sequence, in batches
  456. info!(target: "darkfid::task::handle_reorg", "Peer sequence ranks higher than our current best fork, retrieving {} proposals from peer...", peer_header_hashes.len());
  457. let mut batch = Vec::with_capacity(BATCH);
  458. let mut total_processed = 0;
  459. for (index, hash) in peer_header_hashes.iter().enumerate() {
  460. // Add hash in batch sequence
  461. batch.push(*hash);
  462. // Check if batch is full so we can send it
  463. if batch.len() < BATCH && index != peer_header_hashes.len() - 1 {
  464. continue
  465. }
  466. // Request peer proposals
  467. let request = ForkProposalsRequest { headers: batch.clone(), fork_header: proposal.hash };
  468. if let Err(e) = channel.send(&request).await {
  469. debug!(target: "darkfid::task::handle_reorg", "Channel send failed: {e}");
  470. return true
  471. };
  472. // Node waits for response
  473. let response = match response_sub
  474. .receive_with_timeout(p2p.settings().read().await.outbound_connect_timeout)
  475. .await
  476. {
  477. Ok(r) => r,
  478. Err(e) => {
  479. debug!(target: "darkfid::task::handle_reorg", "Asking peer for proposals sequence failed: {e}");
  480. return true
  481. }
  482. };
  483. debug!(target: "darkfid::task::handle_reorg", "Peer response: {response:?}");
  484. // Response sequence must be the same length as the one requested
  485. if response.proposals.len() != batch.len() {
  486. debug!(target: "darkfid::task::handle_reorg", "Peer responded with a different proposals sequence length");
  487. return true
  488. }
  489. // Process retrieved proposal
  490. for (peer_proposal_index, peer_proposal) in response.proposals.iter().enumerate() {
  491. info!(target: "darkfid::task::handle_reorg", "Processing proposal: {} - {}", peer_proposal.hash, peer_proposal.block.header.height);
  492. // Validate its the proposal we requested
  493. if peer_proposal.hash != batch[peer_proposal_index] {
  494. error!(target: "darkfid::task::handle_reorg", "Peer responded with a differend proposal: {} - {}", batch[peer_proposal_index], peer_proposal.hash);
  495. return true
  496. }
  497. // Verify proposal
  498. if let Err(e) =
  499. verify_fork_proposal(&mut peer_fork, peer_proposal, validator.verify_fees).await
  500. {
  501. error!(target: "darkfid::task::handle_reorg", "Verify fork proposal failed: {e}");
  502. return true
  503. }
  504. // Append proposal
  505. if let Err(e) = peer_fork.append_proposal(peer_proposal).await {
  506. error!(target: "darkfid::task::handle_reorg", "Appending proposal failed: {e}");
  507. return true
  508. }
  509. }
  510. total_processed += response.proposals.len();
  511. info!(target: "darkfid::task::handle_reorg", "Proposals received and verified: {total_processed}/{}", peer_header_hashes.len());
  512. // Reset batch
  513. batch = Vec::with_capacity(BATCH);
  514. }
  515. // Verify trigger proposal
  516. if let Err(e) = verify_fork_proposal(&mut peer_fork, proposal, validator.verify_fees).await {
  517. error!(target: "darkfid::task::handle_reorg", "Verify proposal failed: {e}");
  518. return true
  519. }
  520. // Append trigger proposal
  521. if let Err(e) = peer_fork.append_proposal(proposal).await {
  522. error!(target: "darkfid::task::handle_reorg", "Appending proposal failed: {e}");
  523. return true
  524. }
  525. // Check if the peer fork ranks higher than our current best fork
  526. let mut forks = validator.consensus.forks.write().await;
  527. let index = match best_fork_index(&forks) {
  528. Ok(i) => i,
  529. Err(e) => {
  530. debug!(target: "darkfid::task::handle_reorg", "Retrieving best fork index failed: {e}");
  531. return false
  532. }
  533. };
  534. let best_fork = &forks[index];
  535. if peer_fork.targets_rank < best_fork.targets_rank ||
  536. (peer_fork.targets_rank == best_fork.targets_rank &&
  537. peer_fork.hashes_rank <= best_fork.hashes_rank)
  538. {
  539. info!(target: "darkfid::task::handle_reorg", "Peer fork ranks lower than our current best fork, skipping...");
  540. drop(forks);
  541. return true
  542. }
  543. // Execute the reorg
  544. info!(target: "darkfid::task::handle_reorg", "Peer fork ranks higher than our current best fork, executing reorg...");
  545. *validator.consensus.module.write().await = module;
  546. *forks = vec![peer_fork];
  547. drop(forks);
  548. // Check if we can confirm anything and broadcast them
  549. let confirmed = match validator.confirmation().await {
  550. Ok(f) => f,
  551. Err(e) => {
  552. error!(target: "darkfid::task::handle_reorg", "Confirmation failed: {e}");
  553. return false
  554. }
  555. };
  556. if !confirmed.is_empty() {
  557. let mut notif_blocks = Vec::with_capacity(confirmed.len());
  558. for block in confirmed {
  559. notif_blocks.push(JsonValue::String(base64::encode(&serialize_async(&block).await)));
  560. }
  561. blocks_sub.notify(JsonValue::Array(notif_blocks)).await;
  562. }
  563. // Broadcast proposal to the network
  564. let message = ProposalMessage(proposal.clone());
  565. p2p.broadcast(&message).await;
  566. // Notify proposals subscriber
  567. let enc_prop = JsonValue::String(base64::encode(&serialize_async(proposal).await));
  568. proposals_sub.notify(vec![enc_prop].into()).await;
  569. false
  570. }