unknown_proposal.rs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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 log::{debug, error, info, warn};
  19. use tinyjson::JsonValue;
  20. use darkfi::{
  21. blockchain::BlockDifficulty,
  22. net::{ChannelPtr, P2pPtr},
  23. rpc::jsonrpc::JsonSubscriber,
  24. util::encoding::base64,
  25. validator::{
  26. consensus::{Fork, Proposal},
  27. pow::PoWModule,
  28. utils::{best_fork_index, header_rank},
  29. verification::verify_fork_proposal,
  30. ValidatorPtr,
  31. },
  32. Error, Result,
  33. };
  34. use darkfi_serial::serialize_async;
  35. use crate::proto::{
  36. ForkHeaderHashRequest, ForkHeaderHashResponse, ForkHeadersRequest, ForkHeadersResponse,
  37. ForkProposalsRequest, ForkProposalsResponse, ForkSyncRequest, ForkSyncResponse,
  38. ProposalMessage, BATCH,
  39. };
  40. /// Background task to handle unknown proposals.
  41. pub async fn handle_unknown_proposal(
  42. validator: ValidatorPtr,
  43. p2p: P2pPtr,
  44. proposals_sub: JsonSubscriber,
  45. blocks_sub: JsonSubscriber,
  46. channel: u32,
  47. proposal: Proposal,
  48. ) -> Result<()> {
  49. // If proposal fork chain was not found, we ask our peer for its sequence
  50. debug!(target: "darkfid::task::handle_unknown_proposal", "Asking peer for fork sequence");
  51. let Some(channel) = p2p.get_channel(channel) else {
  52. error!(target: "darkfid::task::handle_unknown_proposal", "Channel {channel} wasn't found.");
  53. return Ok(())
  54. };
  55. // Communication setup
  56. let Ok(response_sub) = channel.subscribe_msg::<ForkSyncResponse>().await else {
  57. error!(target: "darkfid::task::handle_unknown_proposal", "Failure during `ForkSyncResponse` communication setup with peer: {channel:?}");
  58. return Ok(())
  59. };
  60. // Grab last known block to create the request and execute it
  61. let last = match validator.blockchain.last() {
  62. Ok(l) => l,
  63. Err(e) => {
  64. debug!(target: "darkfid::task::handle_unknown_proposal", "Blockchain last retriaval failed: {e}");
  65. return Ok(())
  66. }
  67. };
  68. let request = ForkSyncRequest { tip: last.1, fork_tip: Some(proposal.hash) };
  69. if let Err(e) = channel.send(&request).await {
  70. debug!(target: "darkfid::task::handle_unknown_proposal", "Channel send failed: {e}");
  71. return Ok(())
  72. };
  73. // Node waits for response
  74. let response = match response_sub
  75. .receive_with_timeout(p2p.settings().read().await.outbound_connect_timeout)
  76. .await
  77. {
  78. Ok(r) => r,
  79. Err(e) => {
  80. debug!(target: "darkfid::task::handle_unknown_proposal", "Asking peer for fork sequence failed: {e}");
  81. return Ok(())
  82. }
  83. };
  84. debug!(target: "darkfid::task::handle_unknown_proposal", "Peer response: {response:?}");
  85. // Verify and store retrieved proposals
  86. debug!(target: "darkfid::task::handle_unknown_proposal", "Processing received proposals");
  87. // Response should not be empty
  88. if response.proposals.is_empty() {
  89. warn!(target: "darkfid::task::handle_unknown_proposal", "Peer responded with empty sequence, node might be out of sync!");
  90. return handle_reorg(validator, p2p, proposals_sub, blocks_sub, channel, proposal).await
  91. }
  92. // Sequence length must correspond to requested height
  93. if response.proposals.len() as u32 != proposal.block.header.height - last.0 {
  94. debug!(target: "darkfid::task::handle_unknown_proposal", "Response sequence length is erroneous");
  95. return handle_reorg(validator, p2p, proposals_sub, blocks_sub, channel, proposal).await
  96. }
  97. // First proposal must extend canonical
  98. if response.proposals[0].block.header.previous != last.1 {
  99. debug!(target: "darkfid::task::handle_unknown_proposal", "Response sequence doesn't extend canonical");
  100. return handle_reorg(validator, p2p, proposals_sub, blocks_sub, channel, proposal).await
  101. }
  102. // Last proposal must be the same as the one requested
  103. if response.proposals.last().unwrap().hash != proposal.hash {
  104. debug!(target: "darkfid::task::handle_unknown_proposal", "Response sequence doesn't correspond to requested tip");
  105. return handle_reorg(validator, p2p, proposals_sub, blocks_sub, channel, proposal).await
  106. }
  107. // Process response proposals
  108. for proposal in &response.proposals {
  109. // Append proposal
  110. match validator.append_proposal(proposal).await {
  111. Ok(()) => { /* Do nothing */ }
  112. // Skip already existing proposals
  113. Err(Error::ProposalAlreadyExists) => continue,
  114. Err(e) => {
  115. error!(
  116. target: "darkfid::task::handle_unknown_proposal",
  117. "Error while appending response proposal: {e}"
  118. );
  119. break;
  120. }
  121. };
  122. // Broadcast proposal to rest nodes
  123. let message = ProposalMessage(proposal.clone());
  124. p2p.broadcast_with_exclude(&message, &[channel.address().clone()]).await;
  125. // Notify proposals subscriber
  126. let enc_prop = JsonValue::String(base64::encode(&serialize_async(proposal).await));
  127. proposals_sub.notify(vec![enc_prop].into()).await;
  128. }
  129. Ok(())
  130. }
  131. // TODO; If a reorg trigger is erroneous, disconnect from peer.
  132. /// Auxiliary function to handle a potential reorg.
  133. /// We first find our last common block with the peer,
  134. /// then grab the header sequence from that block until
  135. /// the proposal and check if it ranks higher than our
  136. /// current best ranking fork, to perform a reorg.
  137. async fn handle_reorg(
  138. validator: ValidatorPtr,
  139. p2p: P2pPtr,
  140. proposals_sub: JsonSubscriber,
  141. blocks_sub: JsonSubscriber,
  142. channel: ChannelPtr,
  143. proposal: Proposal,
  144. ) -> Result<()> {
  145. info!(target: "darkfid::task::handle_reorg", "Checking for potential reorg from proposal {} - {} by peer: {channel:?}", proposal.hash, proposal.block.header.height);
  146. // Check if genesis proposal was provided
  147. if proposal.block.header.height == 0 {
  148. info!(target: "darkfid::task::handle_reorg", "Peer send a genesis proposal, skipping...");
  149. return Ok(())
  150. }
  151. // Communication setup
  152. let Ok(response_sub) = channel.subscribe_msg::<ForkHeaderHashResponse>().await else {
  153. error!(target: "darkfid::task::handle_reorg", "Failure during `ForkHeaderHashResponse` communication setup with peer: {channel:?}");
  154. return Ok(())
  155. };
  156. // Keep track of received header hashes sequence
  157. let mut peer_header_hashes = vec![];
  158. // Find last common header, going backwards from the proposal
  159. let mut previous_height = proposal.block.header.height;
  160. let mut previous_hash = proposal.hash;
  161. for height in (0..proposal.block.header.height).rev() {
  162. // Request peer header hash for this height
  163. let request = ForkHeaderHashRequest { height, fork_header: proposal.hash };
  164. if let Err(e) = channel.send(&request).await {
  165. debug!(target: "darkfid::task::handle_reorg", "Channel send failed: {e}");
  166. return Ok(())
  167. };
  168. // Node waits for response
  169. let response = match response_sub
  170. .receive_with_timeout(p2p.settings().read().await.outbound_connect_timeout)
  171. .await
  172. {
  173. Ok(r) => r,
  174. Err(e) => {
  175. debug!(target: "darkfid::task::handle_reorg", "Asking peer for header hash failed: {e}");
  176. return Ok(())
  177. }
  178. };
  179. debug!(target: "darkfid::task::handle_reorg", "Peer response: {response:?}");
  180. // Check if peer returned a header
  181. let Some(peer_header) = response.fork_header else {
  182. info!(target: "darkfid::task::handle_reorg", "Peer responded with an empty header");
  183. return Ok(())
  184. };
  185. // Check if we know this header
  186. match validator.blockchain.blocks.get_order(&[height], false)?[0] {
  187. Some(known_header) => {
  188. if known_header == peer_header {
  189. previous_height = height;
  190. previous_hash = known_header;
  191. break
  192. }
  193. // Since we retrieve in right -> left order we push them in reverse order
  194. peer_header_hashes.insert(0, peer_header);
  195. }
  196. None => peer_header_hashes.insert(0, peer_header),
  197. }
  198. }
  199. // Check if we have a sequence to process
  200. if peer_header_hashes.is_empty() {
  201. info!(target: "darkfid::task::handle_reorg", "No headers to process, skipping...");
  202. return Ok(())
  203. }
  204. // Communication setup
  205. let Ok(response_sub) = channel.subscribe_msg::<ForkHeadersResponse>().await else {
  206. error!(target: "darkfid::task::handle_reorg", "Failure during `ForkHeadersResponse` communication setup with peer: {channel:?}");
  207. return Ok(())
  208. };
  209. // Grab last common height ranks
  210. let last_common_height = previous_height;
  211. let last_difficulty = match previous_height {
  212. 0 => BlockDifficulty::genesis(validator.blockchain.genesis_block()?.header.timestamp),
  213. _ => validator.blockchain.blocks.get_difficulty(&[last_common_height], true)?[0]
  214. .clone()
  215. .unwrap(),
  216. };
  217. // Create a new PoW from last common height
  218. let module = PoWModule::new(
  219. validator.consensus.blockchain.clone(),
  220. validator.consensus.module.read().await.target,
  221. validator.consensus.module.read().await.fixed_difficulty.clone(),
  222. Some(last_common_height + 1),
  223. )?;
  224. // Retrieve the headers of the hashes sequence, in batches, keeping track of the sequence ranking
  225. info!(target: "darkfid::task::handle_reorg", "Retrieving {} headers from peer...", peer_header_hashes.len());
  226. let mut batch = Vec::with_capacity(BATCH);
  227. let mut total_processed = 0;
  228. let mut targets_rank = last_difficulty.ranks.targets_rank.clone();
  229. let mut hashes_rank = last_difficulty.ranks.hashes_rank.clone();
  230. let mut headers_module = module.clone();
  231. for (index, hash) in peer_header_hashes.iter().enumerate() {
  232. // Add hash in batch sequence
  233. batch.push(*hash);
  234. // Check if batch is full so we can send it
  235. if batch.len() < BATCH && index != peer_header_hashes.len() - 1 {
  236. continue
  237. }
  238. // Request peer headers
  239. let request = ForkHeadersRequest { headers: batch.clone(), fork_header: proposal.hash };
  240. if let Err(e) = channel.send(&request).await {
  241. debug!(target: "darkfid::task::handle_reorg", "Channel send failed: {e}");
  242. return Ok(())
  243. };
  244. // Node waits for response
  245. let response = match response_sub
  246. .receive_with_timeout(p2p.settings().read().await.outbound_connect_timeout)
  247. .await
  248. {
  249. Ok(r) => r,
  250. Err(e) => {
  251. debug!(target: "darkfid::task::handle_reorg", "Asking peer for headers sequence failed: {e}");
  252. return Ok(())
  253. }
  254. };
  255. debug!(target: "darkfid::task::handle_reorg", "Peer response: {response:?}");
  256. // Response sequence must be the same length as the one requested
  257. if response.headers.len() != batch.len() {
  258. error!(target: "darkfid::task::handle_reorg", "Peer responded with a different headers sequence length");
  259. return Ok(())
  260. }
  261. // Process retrieved headers
  262. for (peer_header_index, peer_header) in response.headers.iter().enumerate() {
  263. let peer_header_hash = peer_header.hash();
  264. info!(target: "darkfid::task::handle_reorg", "Processing header: {peer_header_hash} - {}", peer_header.height);
  265. // Validate its the header we requested
  266. if peer_header_hash != batch[peer_header_index] {
  267. error!(target: "darkfid::task::handle_reorg", "Peer responded with a differend header: {} - {peer_header_hash}", batch[peer_header_index]);
  268. return Ok(())
  269. }
  270. // Validate sequence is correct
  271. if peer_header.previous != previous_hash || peer_header.height != previous_height + 1 {
  272. error!(target: "darkfid::task::handle_reorg", "Invalid header sequence detected");
  273. return Ok(())
  274. }
  275. // Grab next mine target and difficulty
  276. let (next_target, next_difficulty) =
  277. headers_module.next_mine_target_and_difficulty()?;
  278. // Verify header hash and calculate its rank
  279. let (target_distance_sq, hash_distance_sq) = match header_rank(
  280. peer_header,
  281. &next_target,
  282. ) {
  283. Ok(distances) => distances,
  284. Err(e) => {
  285. error!(target: "darkfid::task::handle_reorg", "Invalid header hash detected: {e}");
  286. return Ok(())
  287. }
  288. };
  289. // Update sequence ranking
  290. targets_rank += target_distance_sq.clone();
  291. hashes_rank += hash_distance_sq.clone();
  292. // Update PoW headers module
  293. headers_module.append(peer_header.timestamp, &next_difficulty);
  294. // Set previous header
  295. previous_height = peer_header.height;
  296. previous_hash = peer_header_hash;
  297. }
  298. total_processed += response.headers.len();
  299. info!(target: "darkfid::task::handle_reorg", "Headers received and verified: {total_processed}/{}", peer_header_hashes.len());
  300. // Reset batch
  301. batch = Vec::with_capacity(BATCH);
  302. }
  303. // Check if the sequence ranks higher than our current best fork
  304. let forks = validator.consensus.forks.read().await;
  305. let best_fork = &forks[best_fork_index(&forks)?];
  306. if targets_rank < best_fork.targets_rank ||
  307. (targets_rank == best_fork.targets_rank && hashes_rank <= best_fork.hashes_rank)
  308. {
  309. info!(target: "darkfid::task::handle_reorg", "Peer sequence ranks lower than our current best fork, skipping...");
  310. drop(forks);
  311. return Ok(())
  312. }
  313. drop(forks);
  314. // Communication setup
  315. let Ok(response_sub) = channel.subscribe_msg::<ForkProposalsResponse>().await else {
  316. error!(target: "darkfid::task::handle_reorg", "Failure during `ForkProposalsResponse` communication setup with peer: {channel:?}");
  317. return Ok(())
  318. };
  319. // Create a fork from last common height
  320. let mut peer_fork = Fork::new(validator.consensus.blockchain.clone(), module).await?;
  321. peer_fork.targets_rank = last_difficulty.ranks.targets_rank.clone();
  322. peer_fork.hashes_rank = last_difficulty.ranks.hashes_rank.clone();
  323. // Grab all state diffs after last common height and add their inverse to the fork
  324. let diffs = validator.blockchain.blocks.get_state_diffs_after(last_common_height)?;
  325. for diff in diffs.iter().rev() {
  326. peer_fork.overlay.lock().unwrap().overlay.lock().unwrap().add_diff(&diff.inverse())?;
  327. }
  328. // Retrieve the proposals of the hashes sequence, in batches
  329. info!(target: "darkfid::task::handle_reorg", "Peer sequence ranks higher than our current best fork, retrieving {} proposals from peer...", peer_header_hashes.len());
  330. let mut batch = Vec::with_capacity(BATCH);
  331. let mut total_processed = 0;
  332. for (index, hash) in peer_header_hashes.iter().enumerate() {
  333. // Add hash in batch sequence
  334. batch.push(*hash);
  335. // Check if batch is full so we can send it
  336. if batch.len() < BATCH && index != peer_header_hashes.len() - 1 {
  337. continue
  338. }
  339. // Request peer proposals
  340. let request = ForkProposalsRequest { headers: batch.clone(), fork_header: proposal.hash };
  341. if let Err(e) = channel.send(&request).await {
  342. debug!(target: "darkfid::task::handle_reorg", "Channel send failed: {e}");
  343. return Ok(())
  344. };
  345. // Node waits for response
  346. let response = match response_sub
  347. .receive_with_timeout(p2p.settings().read().await.outbound_connect_timeout)
  348. .await
  349. {
  350. Ok(r) => r,
  351. Err(e) => {
  352. debug!(target: "darkfid::task::handle_reorg", "Asking peer for proposals sequence failed: {e}");
  353. return Ok(())
  354. }
  355. };
  356. debug!(target: "darkfid::task::handle_reorg", "Peer response: {response:?}");
  357. // Response sequence must be the same length as the one requested
  358. if response.proposals.len() != batch.len() {
  359. error!(target: "darkfid::task::handle_reorg", "Peer responded with a different proposals sequence length");
  360. return Ok(())
  361. }
  362. // Process retrieved proposal
  363. for (peer_proposal_index, peer_proposal) in response.proposals.iter().enumerate() {
  364. info!(target: "darkfid::task::handle_reorg", "Processing proposal: {} - {}", peer_proposal.hash, peer_proposal.block.header.height);
  365. // Validate its the proposal we requested
  366. if peer_proposal.hash != batch[peer_proposal_index] {
  367. error!(target: "darkfid::task::handle_reorg", "Peer responded with a differend proposal: {} - {}", batch[peer_proposal_index], peer_proposal.hash);
  368. return Ok(())
  369. }
  370. // Verify proposal
  371. if let Err(e) =
  372. verify_fork_proposal(&peer_fork, peer_proposal, validator.verify_fees).await
  373. {
  374. error!(target: "darkfid::task::handle_reorg", "Verify fork proposal failed: {e}");
  375. return Ok(())
  376. }
  377. // Append proposal
  378. if let Err(e) = peer_fork.append_proposal(peer_proposal).await {
  379. error!(target: "darkfid::task::handle_reorg", "Appending proposal failed: {e}");
  380. return Ok(())
  381. }
  382. }
  383. total_processed += response.proposals.len();
  384. info!(target: "darkfid::task::handle_reorg", "Proposals received and verified: {total_processed}/{}", peer_header_hashes.len());
  385. // Reset batch
  386. batch = Vec::with_capacity(BATCH);
  387. }
  388. // Verify trigger proposal
  389. if let Err(e) = verify_fork_proposal(&peer_fork, &proposal, validator.verify_fees).await {
  390. error!(target: "darkfid::task::handle_reorg", "Verify proposal failed: {e}");
  391. return Ok(())
  392. }
  393. // Append trigger proposal
  394. if let Err(e) = peer_fork.append_proposal(&proposal).await {
  395. error!(target: "darkfid::task::handle_reorg", "Appending proposal failed: {e}");
  396. return Ok(())
  397. }
  398. // Check if the peer fork ranks higher than our current best fork
  399. let mut forks = validator.consensus.forks.write().await;
  400. let best_fork = &forks[best_fork_index(&forks)?];
  401. if peer_fork.targets_rank < best_fork.targets_rank ||
  402. (peer_fork.targets_rank == best_fork.targets_rank &&
  403. peer_fork.hashes_rank <= best_fork.hashes_rank)
  404. {
  405. info!(target: "darkfid::task::handle_reorg", "Peer fork ranks lower than our current best fork, skipping...");
  406. drop(forks);
  407. return Ok(())
  408. }
  409. // Execute the reorg
  410. info!(target: "darkfid::task::handle_reorg", "Peer fork ranks higher than our current best fork, executing reorg...");
  411. *forks = vec![peer_fork];
  412. drop(forks);
  413. // Check if we can confirm anything and broadcast them
  414. let confirmed = match validator.confirmation().await {
  415. Ok(f) => f,
  416. Err(e) => {
  417. error!(target: "darkfid::task::handle_reorg", "Confirmation failed: {e}");
  418. return Ok(())
  419. }
  420. };
  421. if !confirmed.is_empty() {
  422. let mut notif_blocks = Vec::with_capacity(confirmed.len());
  423. for block in confirmed {
  424. notif_blocks.push(JsonValue::String(base64::encode(&serialize_async(&block).await)));
  425. }
  426. blocks_sub.notify(JsonValue::Array(notif_blocks)).await;
  427. }
  428. // Broadcast proposal to the network
  429. let message = ProposalMessage(proposal.clone());
  430. p2p.broadcast(&message).await;
  431. // Notify proposals subscriber
  432. let enc_prop = JsonValue::String(base64::encode(&serialize_async(&proposal).await));
  433. proposals_sub.notify(vec![enc_prop].into()).await;
  434. Ok(())
  435. }