unknown_proposal.rs 20 KB

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