Skip to content

Commit

Permalink
fix pow function
Browse files Browse the repository at this point in the history
  • Loading branch information
YeahNotSewerSide committed Apr 28, 2024
1 parent 5e5ebc5 commit 5a23fa2
Show file tree
Hide file tree
Showing 6 changed files with 99 additions and 32 deletions.
46 changes: 46 additions & 0 deletions gen_test_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import hashlib
import os


def leading_zeros(num):
if num == 0:
return 8

leading_zeros = 0
while num & 0b10000000 == 0:
leading_zeros += 1
num = num << 1
num = num & 0b11111111
return leading_zeros


def total_leading_zeros(hash):
to_return = 0
for byte in hash:
l_zeros = leading_zeros(byte)
to_return += l_zeros
if l_zeros < 8:
break

return to_return


def gen(hash, difficulty):
difficulty = total_leading_zeros(difficulty)
for i in range(1000):
pow = b'' + os.urandom(10)
hasher = hashlib.sha256()
hasher.update(hash)
hasher.update(pow)

generated_hash = hasher.digest()
ghash_leadin_zeros = total_leading_zeros(generated_hash)

if ghash_leadin_zeros >= difficulty:
print(pow, True)
else:
print(pow, False)


gen(hashlib.sha256(b'text').digest(),
b'\x0F\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF')
29 changes: 25 additions & 4 deletions src/blockchaintree.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::{collections::HashMap, path::Path};

use crate::{
block::TransactionBlock,
block::{BlockArc, TransactionBlock},
chain,
errors::{BCTreeErrorKind, BlockChainTreeError},
tools,
Expand Down Expand Up @@ -303,16 +303,37 @@ impl BlockChainTree {
Ok(())
}

pub async fn new_block(
pub async fn add_new_block(
&self,
block: TransactionBlock,
block: BlockArc,
transactions: &[Transaction],
) -> Result<(), Report<BlockChainTreeError>> {
self.main_chain.add_block(&block).await?;
self.main_chain.add_block(block).await?;

self.main_chain.add_transactions(transactions).await
}

pub async fn emmit_new_main_block(
&self,
pow: &[u8],
founder: [u8; 33],
) -> Result<[u8; 33], Report<BlockChainTreeError>> {
let last_block = self.main_chain.get_last_block().await?.unwrap(); // practically cannot fail

if !tools::check_pow(
&last_block
.hash()
.change_context(BlockChainTreeError::BlockChainTree(BCTreeErrorKind::DumpDb))
.attach_printable("failed to hash block")?,
&last_block.get_info().difficulty,
pow,
) {
return Err(BlockChainTreeError::BlockChainTree(BCTreeErrorKind::WrongPow).into());
};

todo!()
}

pub async fn flush(&self) -> Result<(), Report<BlockChainTreeError>> {
self.main_chain.flush().await?;
self.summary_db
Expand Down
11 changes: 4 additions & 7 deletions src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use primitive_types::U256;
use sled::Db;
use tokio::{fs::OpenOptions, io::AsyncWriteExt, sync::RwLock};

use crate::block::DerivativeBlock;
use crate::block::{BlockArc, DerivativeBlock};
use crate::dump_headers::Headers;
use crate::{
block::{self, BasicInfo, Block, SummarizeBlock},
Expand Down Expand Up @@ -126,10 +126,10 @@ impl MainChain {

let merkle_tree = MerkleTree::build_tree(&[tools::hash(&initial_amount)]);
chain
.add_block(&SummarizeBlock {
.add_block(Arc::new(SummarizeBlock {
default_info: info,
merkle_tree_root: *merkle_tree.get_root(),
})
}))
.await
.change_context(BlockChainTreeError::Chain(ChainErrorKind::Init))
.attach_printable("Failed to insert inception block")?;
Expand Down Expand Up @@ -266,10 +266,7 @@ impl MainChain {
/// Adds block and sets height reference for it
///
/// Checks for blocks validity, adds it directly to the end of the chain
pub async fn add_block(
&self,
block: &(impl Block + Sync),
) -> Result<(), Report<BlockChainTreeError>> {
pub async fn add_block(&self, block: BlockArc) -> Result<(), Report<BlockChainTreeError>> {
let dump = block
.dump()
.change_context(BlockChainTreeError::Chain(ChainErrorKind::AddingBlock))?;
Expand Down
37 changes: 17 additions & 20 deletions src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,30 +183,29 @@ pub fn decompress_from_file(filename: String) -> Result<Vec<u8>, ToolsError> {
Ok(decoded_data)
}

#[inline]
pub fn count_leading_zeros(data: &[u8]) -> u32 {
let mut to_return = 0u32;
for byte in data {
let leading_zeros = byte.leading_zeros();
to_return += leading_zeros;
if leading_zeros < 8 {
break;
}
}
to_return
}

pub fn check_pow(hash: &[u8; 32], difficulty: &[u8; 32], pow: &[u8]) -> bool {
let mut hasher = Sha256::new();
hasher.update(hash);
hasher.update(pow);
let result: [u8; 32] = unsafe { hasher.finalize().as_slice().try_into().unwrap_unchecked() };
let result: [u64; 4] = unsafe { transmute(result) };

let difficulty: &[u64; 4] = unsafe { transmute(difficulty) };
let result: [u8; 32] = hasher.finalize().into();

//println!("difficulty: {:?}", difficulty);

for (r, d) in result.iter().zip(difficulty) {
match r.cmp(d) {
std::cmp::Ordering::Less => {
return true;
}
std::cmp::Ordering::Equal => {}
std::cmp::Ordering::Greater => {
return false;
}
}
if count_leading_zeros(difficulty) <= count_leading_zeros(&result) {
return true;
}

true
false
}

pub fn recalculate_difficulty(prev_timestamp: u64, timestamp: u64, prev_difficulty: &mut Hash) {
Expand Down Expand Up @@ -242,8 +241,6 @@ mod tests {

use primitive_types::U256;



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

#[test]
Expand Down
4 changes: 3 additions & 1 deletion tests/chain_test.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::sync::Arc;

use blockchaintree::{
block, chain, tools,
transaction::{self, Transactionable},
Expand Down Expand Up @@ -32,7 +34,7 @@ async fn init_flush_get_block_by_height_chain_test() {
vec![[0; 32], [1; 32]],
);

main_chain.add_block(&main_block).await.unwrap();
main_chain.add_block(Arc::new(main_block)).await.unwrap();

let height = main_chain.get_height().await;
let block = main_chain.find_by_height(&(height - 1)).await.unwrap();
Expand Down
4 changes: 4 additions & 0 deletions tests/tools_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
use blockchaintree::tools;

#[test]
fn pow_test() {}

0 comments on commit 5a23fa2

Please sign in to comment.