From 7fd6c2772e2caf913dd4e98c7aa5dd8093251e0a Mon Sep 17 00:00:00 2001 From: YeahNotSewerSide Date: Thu, 16 May 2024 21:53:58 +0300 Subject: [PATCH] clean the code --- examples/mine.rs | 2 +- examples/mine_derivative.rs | 2 +- examples/send_transaction.rs | 5 ++-- src/blockchaintree.rs | 53 +++++++++++++++++++++--------------- src/chain.rs | 36 ++++++++++++++---------- src/static_values.rs | 14 +++++----- src/transaction.rs | 17 ++++++------ tests/blockchaintree_test.rs | 2 +- tests/chain_test.rs | 11 ++++---- tests/transaction_test.rs | 5 ++-- 10 files changed, 83 insertions(+), 64 deletions(-) diff --git a/examples/mine.rs b/examples/mine.rs index bf9437f..806f163 100644 --- a/examples/mine.rs +++ b/examples/mine.rs @@ -7,7 +7,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; fn main() { let rt = tokio::runtime::Runtime::new().unwrap(); - let mut tree = BlockChainTree::new().unwrap(); + let mut tree = BlockChainTree::new("./BlockChainTree").unwrap(); let main_chain = tree.get_main_chain(); diff --git a/examples/mine_derivative.rs b/examples/mine_derivative.rs index a2c4cfe..0331391 100644 --- a/examples/mine_derivative.rs +++ b/examples/mine_derivative.rs @@ -7,7 +7,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; fn main() { let rt = tokio::runtime::Runtime::new().unwrap(); - let mut tree = BlockChainTree::new().unwrap(); + let mut tree = BlockChainTree::new("./BlockChainTree").unwrap(); let wallet: [u8; 33] = [ 2, 178, 140, 81, 31, 206, 208, 171, 143, 240, 128, 134, 115, 82, 188, 63, 146, 189, 14, 59, diff --git a/examples/send_transaction.rs b/examples/send_transaction.rs index 38672db..3a961ba 100644 --- a/examples/send_transaction.rs +++ b/examples/send_transaction.rs @@ -9,7 +9,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; fn main() { let rt = tokio::runtime::Runtime::new().unwrap(); - let mut tree = BlockChainTree::new().unwrap(); + let mut tree = BlockChainTree::new("./BlockChainTree").unwrap(); let main_chain = tree.get_main_chain(); @@ -38,7 +38,8 @@ fn main() { U256::from_str_radix("228", 10).unwrap(), wallet_private, None, - ); + ) + .unwrap(); let transaction_hash = transaction.hash(); tree.send_transaction(&transaction).unwrap(); diff --git a/src/blockchaintree.rs b/src/blockchaintree.rs index 6208846..079d9ff 100644 --- a/src/blockchaintree.rs +++ b/src/blockchaintree.rs @@ -6,8 +6,8 @@ use crate::{ errors::{BCTreeErrorKind, BlockChainTreeError, ChainErrorKind}, merkletree, static_values::{ - self, AMMOUNT_SUMMARY, BLOCKS_PER_EPOCH, BYTE_GAS_PRICE, COINS_PER_CYCLE, GAS_SUMMARY, - MAIN_CHAIN_PAYMENT, OLD_AMMOUNT_SUMMARY, OLD_GAS_SUMMARY, ROOT_PUBLIC_ADDRESS, + self, AMOUNT_SUMMARY, BLOCKS_PER_EPOCH, BYTE_GAS_PRICE, COINS_PER_CYCLE, GAS_SUMMARY, + MAIN_CHAIN_PAYMENT, OLD_AMOUNT_SUMMARY, OLD_GAS_SUMMARY, ROOT_PUBLIC_ADDRESS, }, tools, transaction::Transaction, @@ -27,14 +27,17 @@ pub struct BlockChainTree { old_summary_db: Db, gas_db: Db, old_gas_db: Db, + root_folder: String, } impl BlockChainTree { - pub fn new() -> Result> { - let path_summary = Path::new(AMMOUNT_SUMMARY); - let path_summary_old = Path::new(OLD_AMMOUNT_SUMMARY); - let path_gas = Path::new(GAS_SUMMARY); - let path_gas_old = Path::new(OLD_GAS_SUMMARY); + pub fn new(root_folder: &str) -> Result> { + let root = Path::new(root_folder); + + let path_summary = root.join(AMOUNT_SUMMARY); + let path_summary_old = root.join(OLD_AMOUNT_SUMMARY); + let path_gas = root.join(GAS_SUMMARY); + let path_gas_old = root.join(OLD_GAS_SUMMARY); // open summary DB let summary_db = sled::open(path_summary) @@ -54,7 +57,7 @@ impl BlockChainTree { let old_gas_db = sled::open(path_gas_old) .change_context(BlockChainTreeError::BlockChainTree(BCTreeErrorKind::Init)) .attach_printable("failed to open old gas db")?; - let main_chain = chain::MainChain::new()?; + let main_chain = chain::MainChain::new(root_folder)?; if main_chain.get_height() == U256::one() { summary_db @@ -76,6 +79,7 @@ impl BlockChainTree { old_summary_db, gas_db, old_gas_db, + root_folder: root_folder.into(), }) } @@ -87,8 +91,11 @@ impl BlockChainTree { return Ok(chain.clone()); } let last_block = self.main_chain.get_last_block()?.unwrap(); // practically cannot fail - let derivative_chain = - chain::DerivativeChain::new(&hex::encode(owner), &last_block.hash().unwrap())?; + let derivative_chain = chain::DerivativeChain::new( + &self.root_folder, + &hex::encode(owner), + &last_block.hash().unwrap(), + )?; self.derivative_chains .insert(*owner, derivative_chain.clone()); Ok(derivative_chain) @@ -370,7 +377,7 @@ impl BlockChainTree { block.hash().unwrap(), block.get_info().difficulty, block.get_info().timestamp, - block.get_info().height, + block.get_info().height + 1, ) } else { let block = self @@ -393,7 +400,7 @@ impl BlockChainTree { timestamp, pow: *pow, previous_hash: prev_hash, - height: height + 1, + height, difficulty, founder: *founder, }; @@ -536,42 +543,44 @@ impl BlockChainTree { async fn rotate_dbs(&mut self) -> Result<(), Report> { self.flush().await?; - let path_summary = Path::new(AMMOUNT_SUMMARY); - let path_summary_old = Path::new(OLD_AMMOUNT_SUMMARY); - let path_gas = Path::new(GAS_SUMMARY); - let path_gas_old = Path::new(OLD_GAS_SUMMARY); + let root = Path::new(&self.root_folder); + + let path_summary = root.join(AMOUNT_SUMMARY); + let path_summary_old = root.join(OLD_AMOUNT_SUMMARY); + let path_gas = root.join(GAS_SUMMARY); + let path_gas_old = root.join(OLD_GAS_SUMMARY); - fs::remove_dir_all(path_summary_old) + fs::remove_dir_all(&path_summary_old) .change_context(BlockChainTreeError::BlockChainTree( BCTreeErrorKind::MoveSummaryDB, )) .attach_printable("failed to remove previous summary database")?; - fs::create_dir(path_summary_old) + fs::create_dir(&path_summary_old) .change_context(BlockChainTreeError::BlockChainTree( BCTreeErrorKind::MoveSummaryDB, )) .attach_printable("failed to create previous summary database folder")?; - fs::remove_dir_all(path_gas_old) + fs::remove_dir_all(&path_gas_old) .change_context(BlockChainTreeError::BlockChainTree( BCTreeErrorKind::MoveSummaryDB, )) .attach_printable("failed to remove previous gas database")?; - fs::create_dir(path_gas_old) + fs::create_dir(&path_gas_old) .change_context(BlockChainTreeError::BlockChainTree( BCTreeErrorKind::MoveSummaryDB, )) .attach_printable("failed to remove previous gas database folder")?; - tools::copy_dir_all(path_summary, path_summary_old) + tools::copy_dir_all(path_summary, &path_summary_old) .change_context(BlockChainTreeError::BlockChainTree( BCTreeErrorKind::MoveSummaryDB, )) .attach_printable("failed to copy summary database")?; - tools::copy_dir_all(path_gas, path_gas_old) + tools::copy_dir_all(path_gas, &path_gas_old) .change_context(BlockChainTreeError::BlockChainTree( BCTreeErrorKind::MoveSummaryDB, )) diff --git a/src/chain.rs b/src/chain.rs index 5f2f880..1d0c2ab 100644 --- a/src/chain.rs +++ b/src/chain.rs @@ -55,16 +55,17 @@ pub struct MainChain { transactions: Db, height: Arc>, difficulty: Arc>, + root: String, } impl MainChain { - pub fn new() -> Result> { - let root = String::from(MAIN_CHAIN_DIRECTORY); + pub fn new(root: &str) -> Result> { + let root = Path::new(root).join(MAIN_CHAIN_DIRECTORY); - let path_blocks_st = root.clone() + BLOCKS_FOLDER; - let path_references_st = root.clone() + REFERENCES_FOLDER; - let path_transactions_st = root.clone() + TRANSACTIONS_FOLDER; - let path_height_st = root + CONFIG_FILE; + let path_blocks_st = root.join(BLOCKS_FOLDER); + let path_references_st = root.join(REFERENCES_FOLDER); + let path_transactions_st = root.join(TRANSACTIONS_FOLDER); + let path_height_st = root.join(CONFIG_FILE); let path_blocks = Path::new(&path_blocks_st); let path_reference = Path::new(&path_references_st); @@ -111,6 +112,7 @@ impl MainChain { transactions, height: Arc::new(RwLock::new(height)), difficulty: Arc::new(RwLock::new(difficulty)), + root: root.to_str().unwrap().to_string(), }; if height.is_zero() { let info = BasicInfo::new( @@ -144,8 +146,7 @@ impl MainChain { /// /// Dumps chain's config async fn dump_config(&self) -> Result<(), Report> { - let root = String::from(MAIN_CHAIN_DIRECTORY); - let path_config = root + CONFIG_FILE; + let path_config = Path::new(&self.root).join(CONFIG_FILE); let mut file = OpenOptions::new() .write(true) @@ -442,18 +443,22 @@ pub struct DerivativeChain { pub genesis_hash: Arc<[u8; 32]>, difficulty: Arc>, chain_owner: String, + root: String, } impl DerivativeChain { pub fn new( + root: &str, chain_owner: &str, provided_genesis_hash: &[u8; 32], ) -> Result> { - let root = String::from(DERIVATIVE_CHAINS_DIRECTORY) + chain_owner + "/"; + let root = Path::new(root) + .join(DERIVATIVE_CHAINS_DIRECTORY) + .join(chain_owner); - let path_blocks_st = root.clone() + BLOCKS_FOLDER; - let path_references_st = root.clone() + REFERENCES_FOLDER; - let path_height_st = root + CONFIG_FILE; + let path_blocks_st = root.join(BLOCKS_FOLDER); + let path_references_st = root.join(REFERENCES_FOLDER); + let path_height_st = root.join(CONFIG_FILE); let path_blocks = Path::new(&path_blocks_st); let path_reference = Path::new(&path_references_st); @@ -505,6 +510,7 @@ impl DerivativeChain { difficulty: Arc::new(RwLock::new(difficulty)), genesis_hash: Arc::new(genesis_hash), chain_owner: chain_owner.to_string(), + root: root.to_str().unwrap().to_string(), }; Ok(chain) @@ -518,8 +524,7 @@ impl DerivativeChain { /// /// Dumps chain's config async fn dump_config(&self) -> Result<(), Report> { - let root = String::from(DERIVATIVE_CHAINS_DIRECTORY) + &self.chain_owner + "/"; - let path_config = root + CONFIG_FILE; + let path_config = Path::new(&self.root).join(CONFIG_FILE); let mut file = OpenOptions::new() .write(true) @@ -581,7 +586,8 @@ impl DerivativeChain { let mut height = self.height.write(); - if block.get_info().height != *height + 1 { + if block.get_info().height != *height { + println!("{} {}", block.get_info().height, *height); return Err(BlockChainTreeError::Chain(ChainErrorKind::AddingBlock)).attach_printable( "The height of the chain is different from the height of the block", ); diff --git a/src/static_values.rs b/src/static_values.rs index 61470e3..224c179 100644 --- a/src/static_values.rs +++ b/src/static_values.rs @@ -1,17 +1,17 @@ use lazy_static::lazy_static; use primitive_types::U256; -pub static BLOCKCHAIN_DIRECTORY: &str = "./BlockChainTree/"; +//pub static BLOCKCHAIN_DIRECTORY: &str = "./BlockChainTree/"; -pub static AMMOUNT_SUMMARY: &str = "./BlockChainTree/SUMMARY/"; -pub static OLD_AMMOUNT_SUMMARY: &str = "./BlockChainTree/SUMMARYOLD/"; +pub static AMOUNT_SUMMARY: &str = "SUMMARY/"; +pub static OLD_AMOUNT_SUMMARY: &str = "SUMMARYOLD/"; -pub static GAS_SUMMARY: &str = "./BlockChainTree/GASSUMMARY/"; -pub static OLD_GAS_SUMMARY: &str = "./BlockChainTree/GASSUMMARYOLD/"; +pub static GAS_SUMMARY: &str = "GASSUMMARY/"; +pub static OLD_GAS_SUMMARY: &str = "GASSUMMARYOLD/"; -pub static MAIN_CHAIN_DIRECTORY: &str = "./BlockChainTree/MAIN/"; +pub static MAIN_CHAIN_DIRECTORY: &str = "MAIN/"; -pub static DERIVATIVE_CHAINS_DIRECTORY: &str = "./BlockChainTree/DERIVATIVES/"; +pub static DERIVATIVE_CHAINS_DIRECTORY: &str = "DERIVATIVES/"; pub static CHAINS_FOLDER: &str = "CHAINS/"; pub static BLOCKS_FOLDER: &str = "BLOCKS/"; diff --git a/src/transaction.rs b/src/transaction.rs index 76ad09a..683410b 100644 --- a/src/transaction.rs +++ b/src/transaction.rs @@ -94,7 +94,7 @@ impl Transaction { //gas_amount: &U256, data: Option<&[u8]>, private_key: &[u8; 32], - ) -> [u8; 64] { + ) -> Result<[u8; 64], TransactionError> { let mut hasher = Sha256::new(); let calculated_size: usize = @@ -113,8 +113,7 @@ impl Transaction { } tools::dump_u256(amount, &mut concatenated_input) .attach_printable("Error to dump amount") - .change_context(TransactionError::Tx(TxErrorKind::Dump)) - .unwrap(); + .change_context(TransactionError::Tx(TxErrorKind::Dump))?; if let Some(data) = data { concatenated_input.extend(data.iter()); } @@ -123,13 +122,15 @@ impl Transaction { let result: [u8; 32] = hasher.finalize().as_slice().try_into().unwrap(); let message = unsafe { Message::from_digest_slice(&result).unwrap_unchecked() }; - let secret_key = unsafe { SecretKey::from_slice(private_key).unwrap_unchecked() }; + let secret_key = SecretKey::from_slice(private_key) + .attach_printable("Error parsing private key") + .change_context(TransactionError::Tx(TxErrorKind::Parse))?; let signer = Secp256k1::new(); let signature = signer.sign_ecdsa(&message, &secret_key); - signature.serialize_compact() + Ok(signature.serialize_compact()) } pub fn new( @@ -139,7 +140,7 @@ impl Transaction { amount: U256, private_key: [u8; 32], data: Option>, - ) -> Transaction { + ) -> Result { let signature = Transaction::generate_signature( &sender, &receiver, @@ -147,7 +148,7 @@ impl Transaction { &amount, data.as_deref(), &private_key, - ); + )?; let mut tr = Transaction { sender, receiver, @@ -159,7 +160,7 @@ impl Transaction { }; tr.hash = tools::hash(&tr.dump().unwrap()); - tr + Ok(tr) } pub fn new_signed( diff --git a/tests/blockchaintree_test.rs b/tests/blockchaintree_test.rs index 13db1ba..10d6698 100644 --- a/tests/blockchaintree_test.rs +++ b/tests/blockchaintree_test.rs @@ -3,7 +3,7 @@ use primitive_types::U256; #[tokio::test] async fn test_amounts() { - let tree = BlockChainTree::new().unwrap(); + let tree = BlockChainTree::new("./BlockChainTree").unwrap(); let address_a = [0; 33]; let address_b = [1; 33]; diff --git a/tests/chain_test.rs b/tests/chain_test.rs index eab7a22..b40b5e3 100644 --- a/tests/chain_test.rs +++ b/tests/chain_test.rs @@ -8,13 +8,13 @@ use primitive_types::U256; #[tokio::test] async fn init_flush_get_block_by_height_chain_test() { - let main_chain = chain::MainChain::new().unwrap(); + let main_chain = chain::MainChain::new("./BlockChainTree").unwrap(); main_chain.flush().await.unwrap(); drop(main_chain); - let main_chain = chain::MainChain::new().unwrap(); + let main_chain = chain::MainChain::new("./BlockChainTree").unwrap(); let height = main_chain.get_height(); @@ -54,14 +54,13 @@ async fn init_flush_get_block_by_height_chain_test() { #[tokio::test] async fn init_get_transaction_chain_test() { - let main_chain = chain::MainChain::new().unwrap(); + let main_chain = chain::MainChain::new("./BlockChainTree").unwrap(); let transaction = transaction::Transaction::new_signed( - [10; 33], + [20; 33], [20; 33], 100, U256::from_dec_str("3627836287").unwrap(), - U256::from_dec_str("3627836287").unwrap(), Some(vec![228, 123]), [33; 64], ); @@ -85,6 +84,7 @@ async fn init_get_transaction_chain_test() { #[tokio::test] async fn init_flush_get_block_by_height_deriv_chain_test() { let deriv_chain = chain::DerivativeChain::new( + "./BlockChainTree", "deadbeef", &[ 57, 26, 43, 126, 188, 137, 234, 205, 234, 97, 128, 221, 242, 186, 198, 206, 3, 25, 250, @@ -97,6 +97,7 @@ async fn init_flush_get_block_by_height_deriv_chain_test() { drop(deriv_chain); let deriv_chain = chain::DerivativeChain::new( + "./BlockChainTree", "deadbeef", &[ 57, 26, 43, 126, 188, 137, 234, 205, 234, 97, 128, 221, 242, 186, 198, 206, 3, 25, 250, diff --git a/tests/transaction_test.rs b/tests/transaction_test.rs index 6c1cd70..53359e5 100644 --- a/tests/transaction_test.rs +++ b/tests/transaction_test.rs @@ -5,7 +5,7 @@ use secp256k1::Secp256k1; #[test] fn dump_parse_transaction() { let transaction = transaction::Transaction::new_signed( - [10; 33], + [0; 33], [20; 33], 100, U256::from_dec_str("3627836287").unwrap(), @@ -64,7 +64,8 @@ fn sign_verify_transaction() { U256::from_dec_str("3627836287").unwrap(), secret_key.secret_bytes(), Some(vec![1, 3, 3, 3, 3, 3, 3]), - ); + ) + .unwrap(); assert!(transaction.verify().unwrap()); }