比特币从诞生到现在已经10年了,最近接触到了区块链相关的技术,为了揭开其背后的神秘面纱,我就从头开始构建一个简单的区块链。! f* ?% O8 n" F; {8 _4 o
从技术上来看:区块是一种记录交易的数据结构,反映了一笔交易的资金流向。系统中已经达成的交易的区块连接在一起形成了一条主链,所有参与计算的节点都记录了主链或主链的一部分。
& g3 N6 ?$ u, T* O
* W: ?" p" j# H
一、比特币内部结构
) L6 a! M& t5 C7 ~. H% N比特币内部结构有四部分:
( s2 Q( m8 q) K" A, o8 Q2 s- previous hash: 上一个区块的hash
- data:交易数据
- time stamp:区块生成的时间戳
- nonce:挖矿计算次数/ r6 B. j7 C" Z5 e# z8 v0 E6 Z
二、实现的比特币结构& V* A+ A* g4 R7 N
- index :当前区块索引
- timestamp :该区块创建时的时间戳
- data :交易信息
- previous hash: 前一个区块的hash
- hash: 当前区块的hash
- nonce : 挖矿计算次数
8 g7 [( |' S( A9 M2 O7 p. ] 注意:当前实现了一个简单的区块链结构,并不完整。+ e) l3 R1 K1 O+ x& Y
三、代码实现
, z9 v+ @+ z+ f5 N( n& [: [1.定义区块的结构! u* M* ~4 D6 K- P% @* C: b
"""
区块设计
"""
import time
import hashlib
class Block:
# 初始化一个区块
def __init__(self,previous_hash,data):
self.index = 0
self.nonce = ''
self.previous_hash = previous_hash
self.time_stamp = time.time()
self.data = data
self.hash = self.get_hash()
# 获取区块的hash
def get_hash(self):
msg = hashlib.sha256()
msg.update(str(self.previous_hash).encode('utf-8'))
msg.update(str(self.data).encode('utf-8'))
msg.update(str(self.time_stamp).encode('utf-8'))
msg.update(str(self.index).encode('utf-8'))
return msg.hexdigest()
# 修改区块的hash值
def set_hash(self,hash):
self.hash = hash 2.创世区块构造! L# C; i4 L% G- V0 f; I
创世区块:没有前一个区块,这里的previous_hash和data是自己写死的。
3 l3 B+ Q! V' q( c6 m+ h& ]4 L' M b0 b# 生成创世区块,这是第一个区块,没有前一个区块
def creat_genesis_block():
block = Block(previous_hash= '0000',data='Genesis block')
nonce,digest = mime(block=block)
block.nonce = nonce
block.set_hash(digest)
return block 这里的mime()函数是后面的挖矿函数。
' z% L$ n# v! P' f# J# Z' _! h$ _3.挖矿函数定义6 r E% d7 \9 B6 u
代码如下:% s9 X. F4 b! g- h. v- N
def mime(block):
"""
挖矿函数——更新区块结构,加入nonce值
block:挖矿区块
"""
i = 0
prefix = '0000'
while True:
nonce = str(i)
msg = hashlib.sha256()
msg.update(str(block.previous_hash).encode('utf-8'))
msg.update(str(block.data).encode('utf-8'))
msg.update(str(block.time_stamp).encode('utf-8'))
msg.update(str(block.index).encode('utf-8'))
msg.update(nonce.encode('utf-8'))
digest = msg.hexdigest()
if digest.startswith(prefix):
return nonce,digest
i+=1 4.定义区块链结构
6 o3 d1 h$ @: T1 [8 Y/ c, @( R 代码如下:
, s6 M) |7 F+ b+ s4 |0 v- s/ @; D"""
区块链设计
"""
from Block import *
# 区块链
class BlockChain:
def __init__(self):
self.blocks = [creat_genesis_block()]
# 添加区块到区块链上
def add_block(self,data):
pre_block = self.blocks[len(self.blocks)-1]
new_block = Block(pre_block.hash,data)
new_block.index = len(self.blocks)
nonce,digest = mime(block=new_block)
new_block.nonce = nonce
new_block.set_hash(digest)
self.blocks.append(new_block)
return new_block 在添加新区块到区块链时,先挖矿在将新区块加入区块链。
* V; \4 e4 } K四、代码运行
5 I# K; U! \7 p, h) a- P4 B/ \ 测试代码:7 q( a- u% w! n4 y7 A
from BlockChain import *
# 创建一个区块链
bc = BlockChain()
# 添加区块
bc.add_block(data='second block')
bc.add_block(data='third block')
bc.add_block(data='fourth block')
for bl in bc.blocks:
print("Index:{}".format(bl.index))
print("Nonce:{}".format(bl.nonce))
print("Hash:{}".format(bl.hash))
print("Pre_Hash:{}".format(bl.previous_hash))
print("Time:{}".format(bl.time_stamp))
print("Data:{}".format(bl.data))
print('\n') 运行结果:
6 S, d3 I% d9 ?" |
- a( ^5 ~& c4 T' w: J 这里添加了4个区块(包括创世区块),处了创世区块,每个区块的pre_hash都与前一个区块的hash值相等,这代表区块没有被篡改,数据有效。 |