blockchain.rs 6.1 KB

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