blockchain.rs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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::consensus::{next_block_reward, pid::slot_pid_output},
  21. Error, Result,
  22. };
  23. use darkfi_sdk::{
  24. blockchain::{PidOutput, PreviousSlot, Slot},
  25. pasta::{group::ff::Field, pallas},
  26. };
  27. struct Harness {
  28. pub alice: Blockchain,
  29. pub bob: Blockchain,
  30. }
  31. impl Harness {
  32. fn new() -> Result<Self> {
  33. let alice = Blockchain::new(&sled::Config::new().temporary(true).open()?)?;
  34. let bob = Blockchain::new(&sled::Config::new().temporary(true).open()?)?;
  35. Ok(Self { alice, bob })
  36. }
  37. fn is_empty(&self) {
  38. assert!(self.alice.is_empty());
  39. assert!(self.bob.is_empty());
  40. }
  41. fn validate_chains(&self) -> Result<()> {
  42. self.alice.validate()?;
  43. self.bob.validate()?;
  44. assert_eq!(self.alice.len(), self.bob.len());
  45. Ok(())
  46. }
  47. fn generate_next_block(&self, previous: &BlockInfo) -> BlockInfo {
  48. let previous_hash = previous.blockhash();
  49. // Generate slot
  50. let previous_slot = previous.slots.last().unwrap();
  51. let id = previous_slot.id + 1;
  52. let producers = 1;
  53. let previous_slot_info = PreviousSlot::new(
  54. producers,
  55. vec![previous_hash],
  56. vec![previous.header.previous.clone()],
  57. pallas::Base::ZERO,
  58. previous_slot.pid.error,
  59. );
  60. let (f, error, sigma1, sigma2) = slot_pid_output(&previous_slot, producers);
  61. let pid = PidOutput::new(f, error, sigma1, sigma2);
  62. let total_tokens = previous_slot.total_tokens + previous_slot.reward;
  63. let reward = next_block_reward();
  64. let slot = Slot::new(id, previous_slot_info, pid, total_tokens, reward);
  65. // We increment timestamp so we don't have to use sleep
  66. let mut timestamp = previous.header.timestamp;
  67. timestamp.add(1);
  68. // Generate header
  69. let header = Header::new(
  70. previous_hash,
  71. previous.header.epoch,
  72. id,
  73. timestamp,
  74. previous.header.root.clone(),
  75. );
  76. BlockInfo::new(header, vec![], previous.producer.clone(), vec![slot])
  77. }
  78. fn add_blocks(&self, blocks: &[BlockInfo]) -> Result<()> {
  79. self.add_blocks_to_chain(&self.alice, blocks)?;
  80. self.add_blocks_to_chain(&self.bob, blocks)?;
  81. Ok(())
  82. }
  83. // This is what the validator will execute when it receives a block.
  84. fn add_blocks_to_chain(&self, blockchain: &Blockchain, blocks: &[BlockInfo]) -> Result<()> {
  85. // Create overlay
  86. let blockchain_overlay = BlockchainOverlay::new(&blockchain)?;
  87. let lock = blockchain_overlay.lock().unwrap();
  88. // When we insert genesis, chain is empty
  89. let mut previous = if !lock.is_empty()? { Some(lock.last_block()?) } else { None };
  90. // Validate and insert each block
  91. for block in blocks {
  92. // Check if block already exists
  93. if lock.has_block(block)? {
  94. return Err(Error::BlockAlreadyExists(block.blockhash().to_string()))
  95. }
  96. // This will be true for every insert, apart from genesis
  97. if let Some(p) = previous {
  98. // Retrieve expected reward
  99. let expected_reward = next_block_reward();
  100. // Validate block
  101. block.validate(&p, expected_reward)?;
  102. }
  103. // Insert block
  104. lock.add_block(block)?;
  105. // Use last inserted block as next iteration previous
  106. previous = Some(block.clone());
  107. }
  108. // Write overlay
  109. lock.overlay.lock().unwrap().apply()?;
  110. Ok(())
  111. }
  112. }
  113. #[async_std::test]
  114. async fn blockchain_add_blocks() -> Result<()> {
  115. // Initialize harness
  116. let th = Harness::new()?;
  117. // Check that nothing exists
  118. th.is_empty();
  119. // We generate some blocks
  120. let mut blocks = vec![];
  121. let genesis_block = BlockInfo::default();
  122. blocks.push(genesis_block.clone());
  123. let block = th.generate_next_block(&genesis_block);
  124. blocks.push(block.clone());
  125. let block = th.generate_next_block(&block);
  126. blocks.push(block.clone());
  127. let block = th.generate_next_block(&block);
  128. blocks.push(block.clone());
  129. th.add_blocks(&blocks)?;
  130. // Validate chains
  131. th.validate_chains()?;
  132. // Thanks for reading
  133. Ok(())
  134. }