blockchain.rs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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::{
  19. blockchain::{BlockInfo, Blockchain, BlockchainOverlay, Header},
  20. validator::{
  21. pid::slot_pid_output,
  22. pow::PoWModule,
  23. validation::{validate_block, validate_blockchain},
  24. },
  25. Error, Result,
  26. };
  27. use darkfi_sdk::{
  28. blockchain::{expected_reward, PidOutput, PreviousSlot, Slot, POS_START},
  29. pasta::{group::ff::Field, pallas},
  30. };
  31. const POW_THREADS: usize = 1;
  32. const POW_TARGET: usize = 10;
  33. struct Node {
  34. blockchain: Blockchain,
  35. module: PoWModule,
  36. }
  37. impl Node {
  38. fn new() -> Result<Self> {
  39. let blockchain = Blockchain::new(&sled::Config::new().temporary(true).open()?)?;
  40. let module = PoWModule::new(blockchain.clone(), POW_THREADS, POW_TARGET, None)?;
  41. Ok(Self { blockchain, module })
  42. }
  43. }
  44. struct Harness {
  45. pub alice: Node,
  46. pub bob: Node,
  47. }
  48. impl Harness {
  49. fn new() -> Result<Self> {
  50. let alice = Node::new()?;
  51. let bob = Node::new()?;
  52. Ok(Self { alice, bob })
  53. }
  54. fn is_empty(&self) {
  55. assert!(self.alice.blockchain.is_empty());
  56. assert!(self.bob.blockchain.is_empty());
  57. }
  58. fn validate_chains(&self) -> Result<()> {
  59. validate_blockchain(&self.alice.blockchain, POW_THREADS, POW_TARGET, None)?;
  60. validate_blockchain(&self.bob.blockchain, POW_THREADS, POW_TARGET, None)?;
  61. assert_eq!(self.alice.blockchain.len(), self.bob.blockchain.len());
  62. Ok(())
  63. }
  64. fn generate_next_pos_block(&self, previous: &BlockInfo) -> Result<BlockInfo> {
  65. let previous_hash = previous.hash()?;
  66. // Generate slot
  67. let previous_slot = previous.slots.last().unwrap();
  68. let id = if previous_slot.id < POS_START { POS_START } else { previous_slot.id + 1 };
  69. let producers = 1;
  70. let previous_slot_info = PreviousSlot::new(
  71. producers,
  72. vec![previous_hash],
  73. vec![previous.header.previous],
  74. previous_slot.pid.error,
  75. );
  76. let (f, error, sigma1, sigma2) = slot_pid_output(previous_slot, producers);
  77. let pid = PidOutput::new(f, error, sigma1, sigma2);
  78. let total_tokens = previous_slot.total_tokens + previous_slot.reward;
  79. let reward = expected_reward(id);
  80. let slot = Slot::new(id, previous_slot_info, pid, pallas::Base::ZERO, total_tokens, reward);
  81. // We increment timestamp so we don't have to use sleep
  82. let mut timestamp = previous.header.timestamp;
  83. timestamp.add(1);
  84. // Generate header
  85. let header =
  86. Header::new(previous_hash, previous.header.epoch, id, timestamp, previous.header.nonce);
  87. // Generate the block
  88. let mut block = BlockInfo::new_empty(header, vec![slot]);
  89. // Add transactions to the block
  90. block.append_txs(previous.txs.clone())?;
  91. // Attach signature
  92. block.signature = previous.signature;
  93. Ok(block)
  94. }
  95. fn add_pos_blocks(&mut self, blocks: &[BlockInfo]) -> Result<()> {
  96. Self::add_pos_blocks_to_chain(&mut self.alice, blocks)?;
  97. Self::add_pos_blocks_to_chain(&mut self.bob, blocks)?;
  98. Ok(())
  99. }
  100. // This is what the validator will execute when it receives a block.
  101. fn add_pos_blocks_to_chain(node: &mut Node, blocks: &[BlockInfo]) -> Result<()> {
  102. // Create overlay
  103. let blockchain_overlay = BlockchainOverlay::new(&node.blockchain)?;
  104. let lock = blockchain_overlay.lock().unwrap();
  105. // When we insert genesis, chain is empty
  106. let mut previous = if !lock.is_empty()? { Some(lock.last_block()?) } else { None };
  107. // Validate and insert each block
  108. for block in blocks {
  109. // Check if block already exists
  110. if lock.has_block(block)? {
  111. return Err(Error::BlockAlreadyExists(block.hash()?.to_string()))
  112. }
  113. // This will be true for every insert, apart from genesis
  114. if let Some(p) = previous {
  115. // Retrieve expected reward
  116. let expected_reward = expected_reward(block.header.height);
  117. // Validate block
  118. validate_block(block, &p, expected_reward, &node.module)?;
  119. // Update PoW module
  120. if block.header.version == 1 {
  121. node.module.append(block.header.timestamp.0, &node.module.next_difficulty()?);
  122. }
  123. }
  124. // Insert block
  125. lock.add_block(block)?;
  126. // Use last inserted block as next iteration previous
  127. previous = Some(block.clone());
  128. }
  129. // Write overlay
  130. lock.overlay.lock().unwrap().apply()?;
  131. Ok(())
  132. }
  133. }
  134. #[test]
  135. fn blockchain_add_pos_blocks() -> Result<()> {
  136. smol::block_on(async {
  137. // Initialize harness
  138. let mut th = Harness::new()?;
  139. // Check that nothing exists
  140. th.is_empty();
  141. // We generate some pos blocks
  142. let mut blocks = vec![];
  143. let genesis_block = BlockInfo::default();
  144. blocks.push(genesis_block.clone());
  145. let block = th.generate_next_pos_block(&genesis_block)?;
  146. blocks.push(block.clone());
  147. let block = th.generate_next_pos_block(&block)?;
  148. blocks.push(block.clone());
  149. let block = th.generate_next_pos_block(&block)?;
  150. blocks.push(block.clone());
  151. th.add_pos_blocks(&blocks)?;
  152. // Validate chains
  153. th.validate_chains()?;
  154. // Thanks for reading
  155. Ok(())
  156. })
  157. }