Skip to content

Commit

Permalink
clean the code
Browse files Browse the repository at this point in the history
  • Loading branch information
YeahNotSewerSide committed May 16, 2024
1 parent aa11eae commit 7fd6c27
Show file tree
Hide file tree
Showing 10 changed files with 83 additions and 64 deletions.
2 changes: 1 addition & 1 deletion examples/mine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down
2 changes: 1 addition & 1 deletion examples/mine_derivative.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
5 changes: 3 additions & 2 deletions examples/send_transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down Expand Up @@ -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();

Expand Down
53 changes: 31 additions & 22 deletions src/blockchaintree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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<Self, Report<BlockChainTreeError>> {
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<Self, Report<BlockChainTreeError>> {
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)
Expand All @@ -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
Expand All @@ -76,6 +79,7 @@ impl BlockChainTree {
old_summary_db,
gas_db,
old_gas_db,
root_folder: root_folder.into(),
})
}

Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -393,7 +400,7 @@ impl BlockChainTree {
timestamp,
pow: *pow,
previous_hash: prev_hash,
height: height + 1,
height,
difficulty,
founder: *founder,
};
Expand Down Expand Up @@ -536,42 +543,44 @@ impl BlockChainTree {
async fn rotate_dbs(&mut self) -> Result<(), Report<BlockChainTreeError>> {
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,
))
Expand Down
36 changes: 21 additions & 15 deletions src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,16 +55,17 @@ pub struct MainChain {
transactions: Db,
height: Arc<RwLock<U256>>,
difficulty: Arc<RwLock<[u8; 32]>>,
root: String,
}

impl MainChain {
pub fn new() -> Result<Self, Report<BlockChainTreeError>> {
let root = String::from(MAIN_CHAIN_DIRECTORY);
pub fn new(root: &str) -> Result<Self, Report<BlockChainTreeError>> {
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);
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -144,8 +146,7 @@ impl MainChain {
///
/// Dumps chain's config
async fn dump_config(&self) -> Result<(), Report<BlockChainTreeError>> {
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)
Expand Down Expand Up @@ -442,18 +443,22 @@ pub struct DerivativeChain {
pub genesis_hash: Arc<[u8; 32]>,
difficulty: Arc<RwLock<[u8; 32]>>,
chain_owner: String,
root: String,
}

impl DerivativeChain {
pub fn new(
root: &str,
chain_owner: &str,
provided_genesis_hash: &[u8; 32],
) -> Result<Self, Report<BlockChainTreeError>> {
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);
Expand Down Expand Up @@ -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)
Expand All @@ -518,8 +524,7 @@ impl DerivativeChain {
///
/// Dumps chain's config
async fn dump_config(&self) -> Result<(), Report<BlockChainTreeError>> {
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)
Expand Down Expand Up @@ -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",
);
Expand Down
14 changes: 7 additions & 7 deletions src/static_values.rs
Original file line number Diff line number Diff line change
@@ -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/";
Expand Down
17 changes: 9 additions & 8 deletions src/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand All @@ -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());
}
Expand All @@ -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(
Expand All @@ -139,15 +140,15 @@ impl Transaction {
amount: U256,
private_key: [u8; 32],
data: Option<Vec<u8>>,
) -> Transaction {
) -> Result<Transaction, TransactionError> {
let signature = Transaction::generate_signature(
&sender,
&receiver,
timestamp,
&amount,
data.as_deref(),
&private_key,
);
)?;
let mut tr = Transaction {
sender,
receiver,
Expand All @@ -159,7 +160,7 @@ impl Transaction {
};
tr.hash = tools::hash(&tr.dump().unwrap());

tr
Ok(tr)
}

pub fn new_signed(
Expand Down
2 changes: 1 addition & 1 deletion tests/blockchaintree_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down
Loading

0 comments on commit 7fd6c27

Please sign in to comment.