从底层开始学写BlockChain__POW__共识算法

POW即工作量证明:因为记账有一定的奖励和手续费,所以自然会有竞争,POW (Proof of Work) 工作量证明共识机制就是用来在“谁有权记账”这一问题上达成共识。
简单来说,就是争夺记账权的多方通过付出计算资源解决一个数学难题,谁先解决谁就获得记账权,这个争夺的过程就是“挖矿”,也是比特币发行的过程。具体的计算问题是,计算出新区块的hash值,并且这个hash值要小于某个数,也就是要有足够多的前导零,前导零越多,计算难度越大,可以以此调整生成一个区块的所需的时间。新区块综合了上一区块的hash值、上一区块生成之后的新的验证过的交易内容的Markle Root值,以及一个待猜测的一定范围内的随机数Nonce,计算量就在于穷举Nonce值以计算出符合条件的hash值。POW还有一个最长链机制,即用户会把最长链作为主链并继续拼接下去。因此,系统中可能出现链的分叉(Fork),但最终会有一条链成为最长的链。

import hashlib as hasher
import datetime as date

class BlockData:
	def __init__(self, index, previous_hash, timestamp, hard, transactions,transactionlens):
		#区块体
		self.tindex = 0
		self.transactions = transactions
		self.transactionlens = transactionlens
		#区块头
		self.index = index
		self.version = "v1.0.0"
		self.previous_hash = previous_hash
		self.merkle_root = self.merkle_tree()
		self.timestamp = timestamp
		self.hard = hard
		

	def merkle_tree(self):
		if self.index==0: 
			return 0
		else:
			hashdata=[]
			sha = hasher.sha256()
			j=self.transactionlens
			for i in range(j):
				sha.update( str(self.transactions[i]["sender"] ).encode("utf-8") )
				hashdata.append( 
					sha.hexdigest()
				)

			while j>1:
				temp = int(j / 2) 
				for i in range(temp):
					hashdata[i] = sha.update( (str(hashdata[i*2]) + str(hashdata[i*2+1]) ).encode("utf-8") )
				if j%2 !=0:
					hashdata[temp] = hashdata[j-1]
					j=(j+1)/2
				else:
					j=j/2
			return hashdata[1]


class Block:
	def __init__(self, index, previous_hash, timestamp, hard, transactions, transactionlens=3, proof="POW"):
		'''
			params:区块索引值,前面区块哈希值,时间戳,区块可容纳交易数量default=5
		'''
		self.BlockBody = BlockData(index, previous_hash, timestamp, hard, transactions, transactionlens)
		self.proof = proof
		self.hash = self.hash_block()

	def hash_block(self):
		sha = hasher.sha256()
		sha.update( (str(self.BlockBody.index)  + str(self.BlockBody.timestamp) + str(self.BlockBody.previous_hash) + str(self.BlockBody.merkle_root) ).encode("utf-8") )
		return sha.hexdigest()


class Chain:
	def __init__(self):
		self.chain=[]

	def create_genesis_block(self):
		self.chain.append(
			Block(0, "0", date.datetime.now(), 0, 0)
		)

	def new_block(self, block):
		self.chain.append(block)

	def last_block(self):
		return self.chain[-1]


def proof_of_work(last_proof, hard):
	proof = 0
	while valid_proof(last_proof, proof, hard) is False:
		proof += 1
	return proof

def valid_proof(last_proof, proof, hard):
	guess = f'{last_proof}{proof}'.encode()
	guess_hash = hasher.sha256(guess).hexdigest()
	res = ''.join(str(i) for i in guess_hash[-hard:])
	last=""
	for i in range(hard):
		last = last + "0"
	print(res+"-->"+last)
	return res == last

def new_trans(sender, recipient, amount):
	return { 
		"sender":sender, 
		"recipient":recipient,
		"amount":amount,
	}

if __name__ == '__main__':
	chain = Chain()
	#GENESIS BLOCK
	chain.create_genesis_block()
	#LAST BLOCK
	last_block = chain.last_block()
	last_block_index = last_block.BlockBody.index
	last_block_hash  = last_block.hash
	#ADD TRANSACTION
	transactions = []
	transactions.append( new_trans("A","B",100) )
	transactions.append( new_trans("C","D",200) )
	transactions.append( new_trans("E","F",300) )
	hard = 2 ##POW  hard
	t = proof_of_work(last_block_hash,hard)
	print("PROOF",t)
	a_new_block = Block(last_block_index+1, last_block_hash, date.datetime.now(), hard, transactions)
	chain.new_block(a_new_block)
	last_block = chain.last_block()
	print(last_block.BlockBody.merkle_root)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值