blockchain.rs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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 = Header::new(previous_hash, id, timestamp, previous.header.nonce);
  85. // Generate the block
  86. let mut block = BlockInfo::new_empty(header, vec![slot]);
  87. // Add transactions to the block
  88. block.append_txs(previous.txs.clone())?;
  89. // Attach signature
  90. block.signature = previous.signature;
  91. Ok(block)
  92. }
  93. fn add_pos_blocks(&mut self, blocks: &[BlockInfo]) -> Result<()> {
  94. Self::add_pos_blocks_to_chain(&mut self.alice, blocks)?;
  95. Self::add_pos_blocks_to_chain(&mut self.bob, blocks)?;
  96. Ok(())
  97. }
  98. // This is what the validator will execute when it receives a block.
  99. fn add_pos_blocks_to_chain(node: &mut Node, blocks: &[BlockInfo]) -> Result<()> {
  100. // Create overlay
  101. let blockchain_overlay = BlockchainOverlay::new(&node.blockchain)?;
  102. let lock = blockchain_overlay.lock().unwrap();
  103. // When we insert genesis, chain is empty
  104. let mut previous = if !lock.is_empty()? { Some(lock.last_block()?) } else { None };
  105. // Validate and insert each block
  106. for block in blocks {
  107. // Check if block already exists
  108. if lock.has_block(block)? {
  109. return Err(Error::BlockAlreadyExists(block.hash()?.to_string()))
  110. }
  111. // This will be true for every insert, apart from genesis
  112. if let Some(p) = previous {
  113. // Retrieve expected reward
  114. let expected_reward = expected_reward(block.header.height);
  115. // Validate block
  116. validate_block(block, &p, expected_reward, &node.module)?;
  117. // Update PoW module
  118. if block.header.version == 1 {
  119. node.module.append(block.header.timestamp.0, &node.module.next_difficulty()?);
  120. }
  121. }
  122. // Insert block
  123. lock.add_block(block)?;
  124. // Use last inserted block as next iteration previous
  125. previous = Some(block.clone());
  126. }
  127. // Write overlay
  128. lock.overlay.lock().unwrap().apply()?;
  129. Ok(())
  130. }
  131. }
  132. #[test]
  133. fn blockchain_add_pos_blocks() -> Result<()> {
  134. smol::block_on(async {
  135. // Initialize harness
  136. let mut th = Harness::new()?;
  137. // Check that nothing exists
  138. th.is_empty();
  139. // We generate some pos blocks
  140. let mut blocks = vec![];
  141. let genesis_block = BlockInfo::default();
  142. blocks.push(genesis_block.clone());
  143. let block = th.generate_next_pos_block(&genesis_block)?;
  144. blocks.push(block.clone());
  145. let block = th.generate_next_pos_block(&block)?;
  146. blocks.push(block.clone());
  147. let block = th.generate_next_pos_block(&block)?;
  148. blocks.push(block.clone());
  149. th.add_pos_blocks(&blocks)?;
  150. // Validate chains
  151. th.validate_chains()?;
  152. // Thanks for reading
  153. Ok(())
  154. })
  155. }