MCPcopy Create free account
hub / github.com/QMHTMY/RustBook / run

Method run

code/chapter09/blockchain/blockchain2/core/src/pow.rs:39–60  ·  view source on GitHub ↗

开启工作量证明任务,即挖矿

(&self, mut block: &mut Block)

Source from the content-addressed store, hash-verified

37
38 // 开启工作量证明任务,即挖矿
39 pub fn run(&self, mut block: &mut Block) {
40 println!("Start mining .... ");
41 thread::sleep(Duration::from_secs(3));
42
43 let mut nonce: u32 = 0;
44 while nonce <= MAX_NONCE {
45 // 计算值
46 let hd_ser = Self::prepare_data(&mut block, nonce);
47 let mut hash_u: [u8; 32] = [0; 32];
48 hash_u8(&hd_ser, &mut hash_u);
49
50 // 判断值是否满足要求,满足则计算并设置区块哈希值
51 let hash_int = U256::from(hash_u);
52 if hash_int <= self.target {
53 block.hash = hash_str(&hd_ser);
54 println!("Produce a new block!\n");
55 return;
56 }
57
58 nonce += 1;
59 }
60 }
61
62 // 准备区块头数据
63 fn prepare_data(block: &mut Block, nonce: u32) -> Vec<u8> {

Callers 1

newMethod · 0.45

Calls 2

hash_u8Function · 0.50
hash_strFunction · 0.50

Tested by

no test coverage detected