validation.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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 darkfi_sdk::{
  19. blockchain::{block_version, expected_reward, Slot},
  20. pasta::{group::ff::Field, pallas},
  21. };
  22. use crate::{
  23. blockchain::{BlockInfo, Blockchain},
  24. validator::{pid::slot_pid_output, pow::PoWModule},
  25. Error, Result,
  26. };
  27. /// Validate provided block, using its previous, based on its version.
  28. pub fn validate_block(
  29. block: &BlockInfo,
  30. previous: &BlockInfo,
  31. expected_reward: u64,
  32. module: &PoWModule,
  33. ) -> Result<()> {
  34. // TODO: verify block validations work as expected on versions change(cutoff)
  35. match block_version(block.header.height) {
  36. 1 => validate_pow_block(block, previous, expected_reward, module)?,
  37. 2 => validate_pos_block(block, previous, expected_reward)?,
  38. _ => return Err(Error::BlockVersionIsInvalid(block.header.version)),
  39. }
  40. Ok(())
  41. }
  42. /// A PoW block is considered valid when the following rules apply:
  43. /// 1. Block version is equal to 1
  44. /// 2. Parent hash is equal to the hash of the previous block
  45. /// 3. Block heigh increments previous block height by 1
  46. /// 4. Timestamp is valid based on PoWModule validation
  47. /// 5. Block hash is valid based on PoWModule validation
  48. /// 6. Slots vector contains a single valid slot
  49. /// 7. Block height is the same as the slots vector last slot id
  50. /// Additional validity rules can be applied.
  51. pub fn validate_pow_block(
  52. block: &BlockInfo,
  53. previous: &BlockInfo,
  54. expected_reward: u64,
  55. module: &PoWModule,
  56. ) -> Result<()> {
  57. let error = Err(Error::BlockIsInvalid(block.hash()?.to_string()));
  58. // Check block version (1)
  59. if block.header.version != 1 {
  60. return error
  61. }
  62. // Check previous hash (2)
  63. let previous_hash = previous.hash()?;
  64. if block.header.previous != previous_hash {
  65. return error
  66. }
  67. // Check heights are incremental (3)
  68. if block.header.height != previous.header.height + 1 {
  69. return error
  70. }
  71. // Check timestamp validity (4)
  72. if !module.verify_timestamp_by_median(block.header.timestamp.0) {
  73. return error
  74. }
  75. // Check block hash corresponds to next one (5)
  76. module.verify_block_hash(block)?;
  77. // Verify slots vector contains single slot (6)
  78. if block.slots.len() != 1 {
  79. return error
  80. }
  81. // Retrieve previous block last slot
  82. let previous_slot = previous.slots.last().unwrap();
  83. // Validate last slot
  84. let last_slot = block.slots.last().unwrap();
  85. validate_pow_slot(
  86. last_slot,
  87. previous_slot,
  88. &previous_hash,
  89. &previous.header.previous,
  90. &pallas::Base::from(previous.header.nonce),
  91. expected_reward,
  92. )?;
  93. // Check block height is the last slot id (7)
  94. if last_slot.id != block.header.height {
  95. return error
  96. }
  97. Ok(())
  98. }
  99. /// A PoW slot is considered valid when the following rules apply:
  100. /// 1. Id increments previous slot id by 1
  101. /// 2. Forks extend previous block hash
  102. /// 3. Forks follow previous block sequence
  103. /// 4. Slot total tokens represent the total network tokens
  104. /// up until this slot
  105. /// 5. Slot previous error value correspond to previous slot one
  106. /// 6. Slot previous has only 1 producer(the miner)
  107. /// 7. PID output for this slot is correct(zero)
  108. /// 8. Slot last nonce is the expected one
  109. /// 9. Slot reward value is the expected one
  110. /// Additional validity rules can be applied.
  111. pub fn validate_pow_slot(
  112. slot: &Slot,
  113. previous: &Slot,
  114. previous_block_hash: &blake3::Hash,
  115. previous_block_sequence: &blake3::Hash,
  116. last_nonce: &pallas::Base,
  117. expected_reward: u64,
  118. ) -> Result<()> {
  119. let error = Err(Error::SlotIsInvalid(slot.id));
  120. // Check slots are incremental (1)
  121. if slot.id != previous.id + 1 {
  122. return error
  123. }
  124. // Check previous block hash (2)
  125. if !slot.previous.last_hashes.contains(previous_block_hash) {
  126. return error
  127. }
  128. // Check previous block sequence (3)
  129. if !slot.previous.second_to_last_hashes.contains(previous_block_sequence) {
  130. return error
  131. }
  132. // Check total tokens (4)
  133. if slot.total_tokens != previous.total_tokens + previous.reward {
  134. return error
  135. }
  136. // Check previous slot error (5)
  137. if slot.previous.error != previous.pid.error {
  138. return error
  139. }
  140. // Check previous slot producers (6)
  141. if slot.previous.producers != 1 {
  142. return error
  143. }
  144. // Check PID output for this slot (7)
  145. if (slot.pid.f, slot.pid.error, slot.pid.sigma1, slot.pid.sigma2) !=
  146. (0.0, 0.0, pallas::Base::ZERO, pallas::Base::ZERO)
  147. {
  148. return error
  149. }
  150. // Check nonce is the expected one
  151. if &slot.last_nonce != last_nonce {
  152. return error
  153. }
  154. // Check reward is the expected one (9)
  155. if slot.reward != expected_reward {
  156. return error
  157. }
  158. Ok(())
  159. }
  160. /// A PoS block is considered valid when the following rules apply:
  161. /// 1. Block version is equal to 2
  162. /// 2. Parent hash is equal to the hash of the previous block
  163. /// 3. Timestamp increments previous block timestamp
  164. /// 4. Slot increments previous block slot
  165. /// 5. Slots vector is not empty and all its slots are valid
  166. /// 6. Slot is the same as the slots vector last slot id
  167. /// Additional validity rules can be applied.
  168. pub fn validate_pos_block(
  169. block: &BlockInfo,
  170. previous: &BlockInfo,
  171. expected_reward: u64,
  172. ) -> Result<()> {
  173. let error = Err(Error::BlockIsInvalid(block.hash()?.to_string()));
  174. // Check block version (1)
  175. if block.header.version != 2 {
  176. return error
  177. }
  178. // Check previous hash (2)
  179. let previous_hash = previous.hash()?;
  180. if block.header.previous != previous_hash {
  181. return error
  182. }
  183. // Check timestamps are incremental (3)
  184. if block.header.timestamp <= previous.header.timestamp {
  185. return error
  186. }
  187. // Check heights are incremental (4)
  188. if block.header.height <= previous.header.height {
  189. return error
  190. }
  191. // Verify slots (5)
  192. if block.slots.is_empty() {
  193. return error
  194. }
  195. // Retrieve previous block last slot
  196. let mut previous_slot = previous.slots.last().unwrap();
  197. // Check if empty slots existed
  198. if block.slots.len() > 1 {
  199. // All slots exluding the last one must have reward value set to 0.
  200. // Slots must already be in correct order (sorted by id).
  201. for slot in &block.slots[..block.slots.len() - 1] {
  202. validate_pos_slot(
  203. slot,
  204. previous_slot,
  205. &previous_hash,
  206. &previous.header.previous,
  207. &previous.header.nonce,
  208. 0,
  209. )?;
  210. previous_slot = slot;
  211. }
  212. }
  213. // Validate last slot
  214. let last_slot = block.slots.last().unwrap();
  215. validate_pos_slot(
  216. last_slot,
  217. previous_slot,
  218. &previous_hash,
  219. &previous.header.previous,
  220. &previous.header.nonce,
  221. expected_reward,
  222. )?;
  223. // Check block height is the last slot id (6)
  224. if last_slot.id != block.header.height {
  225. return error
  226. }
  227. Ok(())
  228. }
  229. /// A PoS slot is considered valid when the following rules apply:
  230. /// 1. Id increments previous slot id
  231. /// 2. Forks extend previous block hash
  232. /// 3. Forks follow previous block sequence
  233. /// 4. Slot total tokens represent the total network tokens
  234. /// up until this slot
  235. /// 5. Slot previous error value correspond to previous slot one
  236. /// 6. PID output for this slot is correct
  237. /// 7. Slot last nonce(eta) is the expected one
  238. /// 8. Slot reward value is the expected one
  239. /// Additional validity rules can be applied.
  240. pub fn validate_pos_slot(
  241. slot: &Slot,
  242. previous: &Slot,
  243. previous_block_hash: &blake3::Hash,
  244. previous_block_sequence: &blake3::Hash,
  245. last_nonce: &pallas::Base,
  246. expected_reward: u64,
  247. ) -> Result<()> {
  248. let error = Err(Error::SlotIsInvalid(slot.id));
  249. // Check slots are incremental (1)
  250. if slot.id <= previous.id {
  251. return error
  252. }
  253. // Check previous block hash (2)
  254. if !slot.previous.last_hashes.contains(previous_block_hash) {
  255. return error
  256. }
  257. // Check previous block sequence (3)
  258. if !slot.previous.second_to_last_hashes.contains(previous_block_sequence) {
  259. return error
  260. }
  261. // Check total tokens (4)
  262. if slot.total_tokens != previous.total_tokens + previous.reward {
  263. return error
  264. }
  265. // Check previous slot error (5)
  266. if slot.previous.error != previous.pid.error {
  267. return error
  268. }
  269. // Check PID output for this slot (6)
  270. if (slot.pid.f, slot.pid.error, slot.pid.sigma1, slot.pid.sigma2) !=
  271. slot_pid_output(previous, slot.previous.producers)
  272. {
  273. return error
  274. }
  275. // Check nonce(eta) is the expected one (7)
  276. if &slot.last_nonce != last_nonce {
  277. return error
  278. }
  279. // Check reward is the expected one (8)
  280. if slot.reward != expected_reward {
  281. return error
  282. }
  283. Ok(())
  284. }
  285. /// A blockchain is considered valid, when every block is valid,
  286. /// based on validate_block checks.
  287. /// Be careful as this will try to load everything in memory.
  288. pub fn validate_blockchain(
  289. blockchain: &Blockchain,
  290. pow_threads: usize,
  291. pow_target: usize,
  292. ) -> Result<()> {
  293. // Generate a PoW module
  294. let mut module = PoWModule::new(blockchain.clone(), pow_threads, pow_target)?;
  295. // We use block order store here so we have all blocks in order
  296. let blocks = blockchain.order.get_all()?;
  297. for (index, block) in blocks[1..].iter().enumerate() {
  298. let full_blocks = blockchain.get_blocks_by_hash(&[blocks[index].1, block.1])?;
  299. let expected_reward = expected_reward(full_blocks[1].header.height);
  300. let full_block = &full_blocks[1];
  301. validate_block(full_block, &full_blocks[0], expected_reward, &module)?;
  302. // Update PoW module
  303. if full_block.header.version == 1 {
  304. module.append(full_block.header.timestamp.0, &module.next_difficulty()?);
  305. }
  306. }
  307. Ok(())
  308. }