blockchain.rs 4.4 KB

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