blockchain.rs 5.4 KB

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