Skip to content

Commit

Permalink
Merge pull request #57 from Sovenok-Hacker/rewrite
Browse files Browse the repository at this point in the history
Some clippy fixes
  • Loading branch information
YeahNotSewerSide authored Apr 28, 2024
2 parents 340510f + d42f4a3 commit fa65d9b
Show file tree
Hide file tree
Showing 8 changed files with 39 additions and 49 deletions.
6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@ log = "0.4.21"
num-bigint = "0.4.4"
num-traits = "0.2.18"
rsa = "0.9.6"
secp256k1 = { version = "0.28.2", features = ["rand-std"] }
secp256k1 = { version = "0.29.0", features = ["rand-std"] }
sha2 = "0.10.8"
sled = "0.34.7"
thiserror = "1.0.58"
thiserror = "1.0.59"
tokio = { version = "1.37.0", features = ["full"] }
zstd = "0.13.1"
primitive-types = "0.12.2"
async-trait = "0.1.79"
async-trait = "0.1.80"

[dev-dependencies]
rand = "0.8.5"
Expand Down
3 changes: 1 addition & 2 deletions src/blockchaintree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@ use std::{collections::HashMap, path::Path};
use crate::{
chain,
errors::{BCTreeErrorKind, BlockChainTreeError},
tools, txpool,
tools,
};
use error_stack::{Report, ResultExt};
use lazy_static::lazy_static;
use primitive_types::U256;
use sled::Db;

Expand Down
19 changes: 11 additions & 8 deletions src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,11 @@ use tokio::{fs::OpenOptions, io::AsyncWriteExt, sync::RwLock};
use crate::block::DerivativeBlock;
use crate::dump_headers::Headers;
use crate::{
block::{self, BasicInfo, Block, SummarizeBlock, TransactionBlock},
errors::DerivChainErrorKind,
block::{self, BasicInfo, Block, SummarizeBlock},
errors::{BlockChainTreeError, ChainErrorKind},
merkletree::MerkleTree,
tools,
transaction::{Transaction, Transactionable},
transaction::Transactionable,
};
use crate::{static_values::*, transaction};

Expand Down Expand Up @@ -148,6 +147,7 @@ impl MainChain {
let mut file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(path_config)
.await
.change_context(BlockChainTreeError::Chain(ChainErrorKind::DumpConfig))?;
Expand Down Expand Up @@ -249,7 +249,7 @@ impl MainChain {
let raw_transaction = self.get_transaction_raw(transaction_hash)?;

if let Some(tr) = raw_transaction {
if !tr.get(0).unwrap_or(&10).eq(&(Headers::Transaction as u8)) {
if !tr.first().unwrap_or(&10).eq(&(Headers::Transaction as u8)) {
return Err(BlockChainTreeError::Chain(ChainErrorKind::FindByHashE).into());
}
return Ok(Some(
Expand Down Expand Up @@ -329,7 +329,7 @@ impl MainChain {
height.to_big_endian(&mut height_serialized);
let mut dump = self
.blocks
.get(&height_serialized)
.get(height_serialized)
.change_context(BlockChainTreeError::Chain(ChainErrorKind::FindByHeight))?;

if let Some(dump) = dump.take() {
Expand Down Expand Up @@ -529,6 +529,7 @@ impl DerivativeChain {
let mut file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(path_config)
.await
.change_context(BlockChainTreeError::Chain(ChainErrorKind::DumpConfig))?;
Expand Down Expand Up @@ -620,7 +621,7 @@ impl DerivativeChain {
let raw_transaction = self.get_transaction_raw(transaction_hash)?;

if let Some(tr) = raw_transaction {
if !tr.get(0).unwrap_or(&10).eq(&(Headers::Transaction as u8)) {
if !tr.first().unwrap_or(&10).eq(&(Headers::Transaction as u8)) {
return Err(BlockChainTreeError::Chain(ChainErrorKind::FindByHashE).into());
}
return Ok(Some(
Expand Down Expand Up @@ -700,7 +701,7 @@ impl DerivativeChain {
height.to_big_endian(&mut height_serialized);
let mut dump = self
.blocks
.get(&height_serialized)
.get(height_serialized)
.change_context(BlockChainTreeError::Chain(ChainErrorKind::FindByHeight))?;

if let Some(dump) = dump.take() {
Expand Down Expand Up @@ -774,7 +775,9 @@ impl DerivativeChain {
Some(Arc::new(
block::DerivativeBlock::parse(&data[1..])
.change_context(BlockChainTreeError::Chain(ChainErrorKind::FindByHeight))
.attach_printable(format!("Failed to deserialize latest main chain block",))?,
.attach_printable(
"Failed to deserialize latest main chain block".to_string(),
)?,
))
} else {
None
Expand Down
2 changes: 1 addition & 1 deletion src/merkletree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ impl MerkleTree {
}
//hasher.reset();

let hash = Sha256::digest(&to_hash);
let hash = Sha256::digest(to_hash);

*(array_representation.get_unchecked_mut((left_index - 1) / 2)) =
hash.as_slice().try_into().unwrap_unchecked();
Expand Down
31 changes: 18 additions & 13 deletions src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use error_stack::{Report, Result, ResultExt};
use num_bigint::BigUint;
use primitive_types::U256;
use sha2::{Digest, Sha256};
use std::cmp::Ordering;
use std::convert::TryInto;
use std::fs::File;
use std::io::Read;
Expand Down Expand Up @@ -35,7 +36,7 @@ pub fn dump_u256(number: &U256, buffer: &mut Vec<u8>) -> Result<(), ToolsError>
let mut counter: u8 = 0;

for num in number.0.iter().rev() {
let bytes = unsafe { transmute::<u64, [u8; 8]>(num.to_be()) };
let bytes = num.to_be().to_ne_bytes();
for byte in bytes {
if found_non_null {
buffer.push(byte);
Expand Down Expand Up @@ -216,19 +217,23 @@ pub fn recalculate_difficulty(prev_timestamp: u64, timestamp: u64, prev_difficul
break;
};
}
if timestamp - prev_timestamp < TIME_PER_BLOCK {
let val = unsafe { prev_difficulty.get_unchecked_mut(non_zero_index) };
*val = *val >> 1;
} else if timestamp - prev_timestamp > TIME_PER_BLOCK {
let mut val = unsafe { prev_difficulty.get_unchecked_mut(non_zero_index) };
if non_zero_index == 0 && *val == 0x7f {
return;
match (timestamp - prev_timestamp).cmp(&TIME_PER_BLOCK) {
Ordering::Less => {
let val = unsafe { prev_difficulty.get_unchecked_mut(non_zero_index) };
*val >>= 1;
}
if *val == 0xFF {
val = unsafe { prev_difficulty.get_unchecked_mut(non_zero_index - 1) };
Ordering::Greater => {
let mut val = unsafe { prev_difficulty.get_unchecked_mut(non_zero_index) };
if non_zero_index == 0 && *val == 0x7f {
return;
}
if *val == 0xFF {
val = unsafe { prev_difficulty.get_unchecked_mut(non_zero_index - 1) };
}
*val <<= 1;
*val += 1;
}
*val = *val << 1;
*val += 1;
Ordering::Equal => (),
}
}

Expand All @@ -237,7 +242,7 @@ mod tests {

use primitive_types::U256;

use crate::static_values::BEGINNING_DIFFICULTY;


use super::{dump_u256, load_u256, recalculate_difficulty};

Expand Down
18 changes: 1 addition & 17 deletions src/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,23 +42,7 @@ impl Ord for TransactionableItem {

impl PartialOrd for TransactionableItem {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(match self.get_timestamp().cmp(&other.get_timestamp()) {
Ordering::Less => Ordering::Greater,
Ordering::Equal => {
let tr_hash: [u64; 4] = unsafe { transmute(self.hash()) };
let other_hash: [u64; 4] = unsafe { transmute(other.hash()) };

for (left, right) in tr_hash.iter().zip(other_hash.iter()) {
match left.cmp(right) {
Ordering::Less => return Some(Ordering::Greater),
Ordering::Equal => {}
Ordering::Greater => return Some(Ordering::Less),
}
}
Ordering::Equal
}
Ordering::Greater => Ordering::Less,
})
Some(self.cmp(other))
}
}

Expand Down
6 changes: 3 additions & 3 deletions tests/block_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ fn dump_parse_derivative_block() {
payment_transaction,
};
let dumped_block = derivative_block.dump().unwrap();
let parsed_block = DerivativeBlock::parse(&dumped_block[1..].to_vec()).unwrap();
let parsed_block = DerivativeBlock::parse(&dumped_block[1..]).unwrap();

assert_eq!(
derivative_block.default_info.timestamp,
Expand Down Expand Up @@ -216,7 +216,7 @@ fn validate_derivative_block() {
};
let prev_block = DerivativeBlock {
default_info: basic_data,
payment_transaction: payment_transaction,
payment_transaction,
};
let payment_transaction = [0; 32];
let basic_data = block::BasicInfo {
Expand All @@ -229,7 +229,7 @@ fn validate_derivative_block() {
};
let derivative_block = DerivativeBlock {
default_info: basic_data,
payment_transaction: payment_transaction,
payment_transaction,
};

assert!(!derivative_block
Expand Down
3 changes: 1 addition & 2 deletions tests/chain_test.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use blockchaintree::{
block,
chain::{self, Chain, DerivativeChain},
static_values::{BEGINNING_DIFFICULTY, INCEPTION_TIMESTAMP, ROOT_PUBLIC_ADDRESS},
chain,
tools,
transaction::{self, Transactionable},
};
Expand Down

0 comments on commit fa65d9b

Please sign in to comment.