工作量证明python
时间: 2024-12-27 21:19:26 浏览: 7
### 工作量证明算法 Python 实现
工作量证明(Proof of Work, PoW)是一种通过计算难题来防止滥用资源的安全机制。PoW 要求参与者完成一项复杂的数学运算,通常涉及哈希函数。
#### 定义难度目标
为了模拟区块链中的挖矿过程,定义一个简单的难度级别,该级别决定了前导零的数量:
```python
import hashlib
import time
class ProofOfWork:
def __init__(self, data, difficulty=4):
"""初始化数据和难度"""
self.data = data
self.difficulty = difficulty
self.nonce = 0
```
#### 计算哈希值
使用 SHA-256 哈希算法生成区块头的哈希值,并检查是否满足给定的工作量证明条件:
```python
def calculate_hash(self, nonce=None):
"""基于nonce计算SHA-256哈希值"""
if nonce is None:
nonce = self.nonce
block_header = f"{self.data}{nonce}".encode('utf-8')
return hashlib.sha256(block_header).hexdigest()
```
#### 验证工作量证明
验证已找到的解是否符合设定的目标难度:
```python
def valid_proof(self, hash_value):
"""验证hash是否以指定数量的前置零开头"""
target_bits = '0' * self.difficulty
return hash_value.startswith(target_bits)
```
#### 进行挖掘操作
不断调整随机数直到找到符合条件的结果为止:
```python
def mine_block(self):
"""执行工作量证明的过程"""
start_time = time.time()
while True:
current_hash = self.calculate_hash()
if pow.valid_proof(current_hash):
end_time = time.time()
elapsed_time = round(end_time - start_time, 4)
print(f"\n成功挖到新区块!")
print(f"Hash: {current_hash}")
print(f"Nonce: {pow.nonce}")
print(f"耗时: {elapsed_time}秒\n")
break
# 尝试下一个随机数
self.nonce += 1
```
完整的类定义如下所示:
```python
import hashlib
import time
class ProofOfWork:
def __init__(self, data, difficulty=4):
self.data = data
self.difficulty = difficulty
self.nonce = 0
def calculate_hash(self, nonce=None):
if nonce is None:
nonce = self.nonce
block_header = f"{self.data}{nonce}".encode('utf-8')
return hashlib.sha256(block_header).hexdigest()
def valid_proof(self, hash_value):
target_bits = '0' * self.difficulty
return hash_value.startswith(target_bits)
def mine_block(self):
start_time = time.time()
while True:
current_hash = self.calculate_hash()
if self.valid_proof(current_hash):
end_time = time.time()
elapsed_time = round(end_time - start_time, 4)
print(f"\n成功挖到新区块!")
print(f"Hash: {current_hash}")
print(f"Nonce: {self.nonce}")
print(f"耗时: {elapsed_time}秒\n")
break
self.nonce += 1
if __name__ == "__main__":
message = "Hello Blockchain"
pow = ProofOfWork(message, difficulty=5)
pow.mine_block()
```
阅读全文