谈到比特币,我们都知道挖矿,有些人并不太明白挖矿的含义。这里的挖矿其实就是哈希的碰撞,举个简单例子:
1
2
3
4
5
6
7
8
|
import hashlib
x = 11
y = 1
#这里可以调节挖矿难度,也就是哈希的长度
while hashlib.sha256(f '{x*y}' .encode( "utf-8" )).hexdigest()[ 5 : 7 ]! = "00" :
print (x * y)
y + = 1
print ( "找到了:" ,(x * y))
|
结果如下:
当然比特币的挖矿要比这个复杂太多,但是原理差不多,有个大概的认知。
关于节点的同步,是取整个节点中最长的区块链进行同步,如图所示:
有了以上内容铺垫,代码实现和理解就容易了,代码如下:
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
|
#挖矿原理与网络共识
import datetime
import hashlib
import json
import requests
class Blockchain2:
def __init__( self ):
self .chain = [] #区块链列表
self .nodes = set () #节点集合
self .current_tranactions = [] #交易列表
self .new_block(proof = 100 ,preHash = 1 ) #创建第一个区块
#新建一个区块,需要计算,才能追加
def new_block( self ,proof,preHash = None ):
block = {
"index" : len ( self .chain) + 1 , #区块索引
"timestamp" :datetime.datetiem.now(), #区块时间戳
"transactions" : self .current_tranactions, #区块交易记录集合
"proof" :proof, #算力凭证
"preHash" :preHash or self . hash ( self .chain[ - 1 ]), #上一块的哈希
}
self .current_tranactions = [] #开辟新的区块,初始化区块交易记录
self .chain.append(block)
@staticmethod
def hash (block):
#处理为json字符串格式的哈希
block_str = json.dumps(block,sort_keys = True ).encode( "utf-8" )
return hashlib.sha256(block_str).hexdigest()
#新增交易记录
def new_transaction( self ,sender,receiver,amount):
transaction = {
"sender" :sender,
"receiver" :receiver,
"amount" :amount,
}
self .current_tranactions.append(transaction)
return self .last_block[ "index" ] + 1
@property
def last_block( self ):
return self .chain[ - 1 ]
#挖矿,依赖上一个模块,获取工作量证明,即POW共识机制
def proof_of_work( self ,last_block):
last_proof = last_block[ "proof" ]
last_hash = self . hash (last_block)
proof = 0
while self .valid_proof(last_proof,proof,last_hash) is False :
proof + = 1
return proof
#校验工作量
@staticmethod
def valid_proof(last_proof,proof,last_hash):
guess = f '{last_proof}{proof}{last_hash}' .encode( "utf-8" )
guess_hash = hashlib.sha256(guess).hexdigest()
return guess_hash[: 6 ] = = "000000" #可以调整计算难度
#区块一致性,同步算法,
def resolve_conflicts( self ):
neighbours = self .nodes
new_chain = None
max_length = len ( self .chain)
#遍历所有节点,找出最长的链
for node in neighbours:
#获取节点区块链信息
response = requests.get(f 'http://{node}/chain' )
if response.status_code = = 200 :
length = response.json()[ "length" ]
chain = response.json()[ "chain" ]
if length>max_length and self .valid_chain(chain):
max_length = length
new_chain = chain
if new_chain:
self .chain = new_chain
return True
else :
return False
#校验区块链的合法性
def valid_chain( self ,chain):
last_block = chain[ 0 ]
current_index = 1
#校验每一个区块的prehash,proof合法性
while current_index < len (chain):
block = chain[current_index]
#校验哈希的合法性
if block[ "preHash" ] ! = self . hash (last_block):
return False
#校验算力的合法性
if not self .valid_proof(last_block[ "proof" ],block[ "proof" ],block[ "preHash" ]):
return False
last_block = block
current_index + = 1
return True
|
算力校验和pow共识基本实现了
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/baidu_17508977/article/details/80559120