Skip to content

Commit 5a23fa2

Browse files
fix pow function
1 parent 5e5ebc5 commit 5a23fa2

File tree

6 files changed

+99
-32
lines changed

6 files changed

+99
-32
lines changed

gen_test_data.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import hashlib
2+
import os
3+
4+
5+
def leading_zeros(num):
6+
if num == 0:
7+
return 8
8+
9+
leading_zeros = 0
10+
while num & 0b10000000 == 0:
11+
leading_zeros += 1
12+
num = num << 1
13+
num = num & 0b11111111
14+
return leading_zeros
15+
16+
17+
def total_leading_zeros(hash):
18+
to_return = 0
19+
for byte in hash:
20+
l_zeros = leading_zeros(byte)
21+
to_return += l_zeros
22+
if l_zeros < 8:
23+
break
24+
25+
return to_return
26+
27+
28+
def gen(hash, difficulty):
29+
difficulty = total_leading_zeros(difficulty)
30+
for i in range(1000):
31+
pow = b'' + os.urandom(10)
32+
hasher = hashlib.sha256()
33+
hasher.update(hash)
34+
hasher.update(pow)
35+
36+
generated_hash = hasher.digest()
37+
ghash_leadin_zeros = total_leading_zeros(generated_hash)
38+
39+
if ghash_leadin_zeros >= difficulty:
40+
print(pow, True)
41+
else:
42+
print(pow, False)
43+
44+
45+
gen(hashlib.sha256(b'text').digest(),
46+
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')

src/blockchaintree.rs

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use std::{collections::HashMap, path::Path};
22

33
use crate::{
4-
block::TransactionBlock,
4+
block::{BlockArc, TransactionBlock},
55
chain,
66
errors::{BCTreeErrorKind, BlockChainTreeError},
77
tools,
@@ -303,16 +303,37 @@ impl BlockChainTree {
303303
Ok(())
304304
}
305305

306-
pub async fn new_block(
306+
pub async fn add_new_block(
307307
&self,
308-
block: TransactionBlock,
308+
block: BlockArc,
309309
transactions: &[Transaction],
310310
) -> Result<(), Report<BlockChainTreeError>> {
311-
self.main_chain.add_block(&block).await?;
311+
self.main_chain.add_block(block).await?;
312312

313313
self.main_chain.add_transactions(transactions).await
314314
}
315315

316+
pub async fn emmit_new_main_block(
317+
&self,
318+
pow: &[u8],
319+
founder: [u8; 33],
320+
) -> Result<[u8; 33], Report<BlockChainTreeError>> {
321+
let last_block = self.main_chain.get_last_block().await?.unwrap(); // practically cannot fail
322+
323+
if !tools::check_pow(
324+
&last_block
325+
.hash()
326+
.change_context(BlockChainTreeError::BlockChainTree(BCTreeErrorKind::DumpDb))
327+
.attach_printable("failed to hash block")?,
328+
&last_block.get_info().difficulty,
329+
pow,
330+
) {
331+
return Err(BlockChainTreeError::BlockChainTree(BCTreeErrorKind::WrongPow).into());
332+
};
333+
334+
todo!()
335+
}
336+
316337
pub async fn flush(&self) -> Result<(), Report<BlockChainTreeError>> {
317338
self.main_chain.flush().await?;
318339
self.summary_db

src/chain.rs

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use primitive_types::U256;
66
use sled::Db;
77
use tokio::{fs::OpenOptions, io::AsyncWriteExt, sync::RwLock};
88

9-
use crate::block::DerivativeBlock;
9+
use crate::block::{BlockArc, DerivativeBlock};
1010
use crate::dump_headers::Headers;
1111
use crate::{
1212
block::{self, BasicInfo, Block, SummarizeBlock},
@@ -126,10 +126,10 @@ impl MainChain {
126126

127127
let merkle_tree = MerkleTree::build_tree(&[tools::hash(&initial_amount)]);
128128
chain
129-
.add_block(&SummarizeBlock {
129+
.add_block(Arc::new(SummarizeBlock {
130130
default_info: info,
131131
merkle_tree_root: *merkle_tree.get_root(),
132-
})
132+
}))
133133
.await
134134
.change_context(BlockChainTreeError::Chain(ChainErrorKind::Init))
135135
.attach_printable("Failed to insert inception block")?;
@@ -266,10 +266,7 @@ impl MainChain {
266266
/// Adds block and sets height reference for it
267267
///
268268
/// Checks for blocks validity, adds it directly to the end of the chain
269-
pub async fn add_block(
270-
&self,
271-
block: &(impl Block + Sync),
272-
) -> Result<(), Report<BlockChainTreeError>> {
269+
pub async fn add_block(&self, block: BlockArc) -> Result<(), Report<BlockChainTreeError>> {
273270
let dump = block
274271
.dump()
275272
.change_context(BlockChainTreeError::Chain(ChainErrorKind::AddingBlock))?;

src/tools.rs

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -183,30 +183,29 @@ pub fn decompress_from_file(filename: String) -> Result<Vec<u8>, ToolsError> {
183183
Ok(decoded_data)
184184
}
185185

186+
#[inline]
187+
pub fn count_leading_zeros(data: &[u8]) -> u32 {
188+
let mut to_return = 0u32;
189+
for byte in data {
190+
let leading_zeros = byte.leading_zeros();
191+
to_return += leading_zeros;
192+
if leading_zeros < 8 {
193+
break;
194+
}
195+
}
196+
to_return
197+
}
198+
186199
pub fn check_pow(hash: &[u8; 32], difficulty: &[u8; 32], pow: &[u8]) -> bool {
187200
let mut hasher = Sha256::new();
188201
hasher.update(hash);
189202
hasher.update(pow);
190-
let result: [u8; 32] = unsafe { hasher.finalize().as_slice().try_into().unwrap_unchecked() };
191-
let result: [u64; 4] = unsafe { transmute(result) };
192-
193-
let difficulty: &[u64; 4] = unsafe { transmute(difficulty) };
203+
let result: [u8; 32] = hasher.finalize().into();
194204

195-
//println!("difficulty: {:?}", difficulty);
196-
197-
for (r, d) in result.iter().zip(difficulty) {
198-
match r.cmp(d) {
199-
std::cmp::Ordering::Less => {
200-
return true;
201-
}
202-
std::cmp::Ordering::Equal => {}
203-
std::cmp::Ordering::Greater => {
204-
return false;
205-
}
206-
}
205+
if count_leading_zeros(difficulty) <= count_leading_zeros(&result) {
206+
return true;
207207
}
208-
209-
true
208+
false
210209
}
211210

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

243242
use primitive_types::U256;
244243

245-
246-
247244
use super::{dump_u256, load_u256, recalculate_difficulty};
248245

249246
#[test]

tests/chain_test.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::sync::Arc;
2+
13
use blockchaintree::{
24
block, chain, tools,
35
transaction::{self, Transactionable},
@@ -32,7 +34,7 @@ async fn init_flush_get_block_by_height_chain_test() {
3234
vec![[0; 32], [1; 32]],
3335
);
3436

35-
main_chain.add_block(&main_block).await.unwrap();
37+
main_chain.add_block(Arc::new(main_block)).await.unwrap();
3638

3739
let height = main_chain.get_height().await;
3840
let block = main_chain.find_by_height(&(height - 1)).await.unwrap();

tests/tools_test.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
use blockchaintree::tools;
2+
3+
#[test]
4+
fn pow_test() {}

0 commit comments

Comments
 (0)