目录
用python构建区块链(1)---基本结构
用python构建区块链(2)---工作量证明共识算法(pow)
背景
比特币从诞生到现在已经10年了,最近一段时间因为工作原因接触到了区块链相关的技术,为了揭开其背后的神秘面纱,我们就从头开始构建一个简单的区块链。在行动之前我们先看一下比特币的整体结构.
比特币内部结构
可以看到比特币主要有四个部分
- previous hash(前一个区块的hash)
- merkle root(默克尔树根节点,内部存储交易数据)
- timestamp(当前区块生成的时间)
- nonce(旷工计算hash值次数)
我们实现的区块链数据结构(简单实现并不完整)
- index 当前第几个区块
- timestamp 该区块创建时的时间戳
- data 交易信息
- previousHash 前一个区块的hash
- hash 当前区块的hash
注意点
- 第一个区块叫做创世区块(genesis block),区块链创建的时候默认生产的
- 这里用的是单纯的链表,不是用默克尔树存储
coding
from hashlib import sha256
//区块schema
class Block:
def __init__(self,index,timestamp,data,previousHash=""):
self.index = index
self.timestamp = timestamp
self.data = data
self.previousHash = previousHash
self.hash = self.calculateHash()
//计算当前区块的hash值
def calculateHash(self):
plainData = str(self.index)+str(self.timestamp)+str(self.data)
return sha256(plainData.encode('utf-8')).hexdigest()
def __str__(self):
return str(self.__dict__)
//区块链schema
class BlockChain:
//初始化的时候 创建 创世区块
def __init__(self):
self.chain = [self.createGenesisBlock()]
//构建创世区块
def createGenesisBlock(self):
return Block(0,"01/01/2018","genesis block","0")
//获取最后一个区块
def getLatestBlock(self):
return self.chain[len(self.chain)-1]
//往区块链里面添加区块
def addBlock(self,newBlock):
newBlock.previousHash = self.getLatestBlock().hash
newBlock.hash = newBlock.calculateHash()
self.chain.append(newBlock)
def __str__(self):
return str(self.__dict__)
//校验区块链是不是有效的 有没有人被篡改
def chainIsValid(self):
for index in range(1,len(self.chain)):
currentBlock = self.chain[index]
previousBlock = self.chain[index-1]
if (currentBlock.hash != currentBlock.calculateHash()):
return False
if previousBlock.hash != currentBlock.previousHash:
return False
return True
myCoin = BlockChain()
myCoin.addBlock(Block(1,"02/01/2018","{amount:4}"))
myCoin.addBlock(Block(2,"03/01/2018","{amount:5}"))
#print block info 打印区块链信息
print("print block info ####:")
for block in myCoin.chain:
print(block)
#check blockchain is valid 检查区块链是不是有效的
print("before tamper block,blockchain is valid ###")
print(myCoin.chainIsValid())
#tamper the blockinfo 篡改区块2的数据
myCoin.chain[1].data = "{amount:1002}"
print("after tamper block,blockchain is valid ###")
print(myCoin.chainIsValid())
输出结果
print block info ####:
{'index': 0, 'timestamp': '01/01/2018', 'data': 'genesis block', 'previousHash': '0', 'hash': 'd8d21e5ba33780d5eb77d09d3b407ceb8ade4e5545ef951de1997b209d91e264'}
{'index': 1, 'timestamp': '02/01/2018', 'data': '{amount:4}', 'previousHash': 'd8d21e5ba33780d5eb77d09d3b407ceb8ade4e5545ef951de1997b209d91e264', 'hash': '15426e32db30f4b26aa719ba5e573f372f41e27e4728eb9e9ab0bea8eae63a9d'}
{'index': 2, 'timestamp': '03/01/2018', 'data': '{amount:5}', 'previousHash': '15426e32db30f4b26aa719ba5e573f372f41e27e4728eb9e9ab0bea8eae63a9d', 'hash': '75119e897f21c769acee6e32abcefc5e88e250a1f35cc95946379436050ac2f0'}
before tamper block,blockchain is valid ###
True
after tamper block,blockchain is valid ###
False
网友评论