比特币从诞生到现在已经10年了,最近接触到了区块链相关的技术,为了揭开其背后的神秘面纱,我就从头开始构建一个简单的区块链。
% k$ S7 F" r9 q: L 从技术上来看:区块是一种记录交易的数据结构,反映了一笔交易的资金流向。系统中已经达成的交易的区块连接在一起形成了一条主链,所有参与计算的节点都记录了主链或主链的一部分。
& Y7 @. i1 a) z8 l/ Z" E
6 u: n/ d" w0 ]! V5 d9 J1 `
一、比特币内部结构% E/ g' w1 I6 y' K; n# F4 l# O- d
比特币内部结构有四部分:# A$ x5 G1 s( N: N$ a' m
- previous hash: 上一个区块的hash
- data:交易数据
- time stamp:区块生成的时间戳
- nonce:挖矿计算次数# T$ ?; q5 k) T( p$ A/ K
二、实现的比特币结构 q9 d& l# M' _9 P/ g
- index :当前区块索引
- timestamp :该区块创建时的时间戳
- data :交易信息
- previous hash: 前一个区块的hash
- hash: 当前区块的hash
- nonce : 挖矿计算次数
: V, H0 ]- T h8 s+ j4 e5 j 注意:当前实现了一个简单的区块链结构,并不完整。
4 R m0 o- q2 w& i三、代码实现1 U: I! s! k( D- B$ @4 a0 F9 o* T
1.定义区块的结构6 I7 j9 O4 U" a# I A3 Z
"""
区块设计
"""
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.创世区块构造
/ p$ g" w$ S4 I% U4 S 创世区块:没有前一个区块,这里的previous_hash和data是自己写死的。/ R1 c& D, P# G' r3 E. c) ]
# 生成创世区块,这是第一个区块,没有前一个区块
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()函数是后面的挖矿函数。, i. v* a$ w$ t0 w: u( K6 S
3.挖矿函数定义6 s! w4 r# h0 `$ c; t
代码如下:& d7 w# v# p5 l5 B; ~3 t- g, l
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.定义区块链结构5 y1 z! T, F: h
代码如下:* b3 s0 {7 A7 L
"""
区块链设计
"""
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 在添加新区块到区块链时,先挖矿在将新区块加入区块链。
# |$ A. G: O" H! T! r四、代码运行
; ?: G2 v/ H& D; O' C) s, ] 测试代码:$ r) G( L& K5 R5 A7 h4 B4 ~
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') 运行结果:, k* j3 T2 g/ ^3 z: I
( D4 l7 W! e: q: U/ s* W
这里添加了4个区块(包括创世区块),处了创世区块,每个区块的pre_hash都与前一个区块的hash值相等,这代表区块没有被篡改,数据有效。 |