比特币核心结构实现

1. 区块结构设计

  • 定义Block结构体,包含时间戳、前哈希、数据和当前哈希
  • 实现计算当前哈希的方法

2. 区块链设计

  • 定义Blockchain结构体,包含区块数组
  • 实现添加区块的方法
  • 实现创世块生成功能

3. 工作量证明机制

  • 定义ProofOfWork结构体,包含区块引用和目标值
  • 实现构造函数,设置难度目标
  • 实现数据准备方法
  • 实现挖矿运行方法
  • 实现有效性验证

9.修改addblock函数,在其中调用工作量证明,run成功了才执行添加

10.定义确认区块有效区块,确认一下之前Run不是因为溢出而结束

基础数据结构

区块结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
use chrono::Utc;
use sha2::{Sha256, Digest};

#[derive(Debug)]
struct Block {
timestamp: i64,
prev_hash: String,
hash: String,
data: String,
}

impl Block {
fn calculate_hash(&self) -> String {
let mut hasher = Sha256::new();
let data = format!("{}{}{}", self.timestamp, self.prev_hash, self.data);
hasher.update(data);
format!("{:x}", hasher.finalize())
}
}

区块链结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#[derive(Debug)]
struct Blockchain {
blocks: Vec<Block>,
}

impl Blockchain {
fn new() -> Self {
let mut chain = Blockchain {
blocks: Vec::new(),
};
chain.create_genesis_block();
chain
}

fn create_genesis_block(&mut self) {
let genesis = Block {
timestamp: Utc::now().timestamp(),
prev_hash: String::from("0"),
data: String::from("Genesis Block"),
hash: String::new(),
};
let hash = genesis.calculate_hash();
self.blocks.push(Block {
hash,
..genesis
});
}
}

工作量证明实现

PoW结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
struct ProofOfWork<'a> {
block: &'a Block,
target: String,
}

impl<'a> ProofOfWork<'a> {
fn new(block: &'a Block) -> Self {
// 设置难度目标:前5位为0
let target = "00000".to_string() + &"f".repeat(59);
ProofOfWork { block, target }
}

fn prepare_data(&self, nonce: i64) -> String {
format!(
"{}{}{}{}",
self.block.timestamp,
self.block.prev_hash,
self.block.data,
nonce
)
}

fn run(&self) -> (i64, String) {
let mut nonce = 0;
let max_nonce = i64::MAX;
let mut hash = String::new();

while nonce < max_nonce {
let data = self.prepare_data(nonce);
let mut hasher = Sha256::new();
hasher.update(data);
hash = format!("{:x}", hasher.finalize());

if hash < self.target {
break;
}
nonce += 1;
}

(nonce, hash)
}

fn validate(&self, nonce: i64) -> bool {
let data = self.prepare_data(nonce);
let mut hasher = Sha256::new();
hasher.update(data);
let hash = format!("{:x}", hasher.finalize());
hash < self.target
}
}

添加新区块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
impl Blockchain {
fn add_block(&mut self, data: String) {
let prev_block = self.blocks.last().unwrap();
let new_block = Block {
timestamp: Utc::now().timestamp(),
prev_hash: prev_block.hash.clone(),
data,
hash: String::new(),
};

let pow = ProofOfWork::new(&new_block);
let (nonce, hash) = pow.run();

if pow.validate(nonce) {
self.blocks.push(Block {
hash,
..new_block
});
}
}
}

这个实现:

  1. 使用Rust的类型系统确保内存安全
  2. 采用trait实现更好的代码组织
  3. 使用chrono处理时间戳
  4. 使用sha2进行哈希计算
  5. 所有字符串采用String类型,避免字符串切片的生命周期问题

要使用这段代码,需要在Cargo.toml中添加以下依赖:

1
2
3
[dependencies]
chrono = "0.4"
sha2 = "0.10"