比特币从诞生到现在已经10年了,最近接触到了区块链相关的技术,为了揭开其背后的神秘面纱,我就从头开始构建一个简单的区块链。
" W" b: b6 }8 V 从技术上来看:区块是一种记录交易的数据结构,反映了一笔交易的资金流向。系统中已经达成的交易的区块连接在一起形成了一条主链,所有参与计算的节点都记录了主链或主链的一部分。; w$ d( }' k1 R8 a
" s8 A, J- |4 T6 X: y) S9 J
一、比特币内部结构
; @+ W. G5 U! ^; I, i; c( Z比特币内部结构有四部分:
, p- o- r x6 J# p: V- previous hash: 上一个区块的hash
- data:交易数据
- time stamp:区块生成的时间戳
- nonce:挖矿计算次数
6 m/ }3 Y5 b* `9 ?+ W( y 二、实现的比特币结构1 H* e. S) U, h
- index :当前区块索引
- timestamp :该区块创建时的时间戳
- data :交易信息
- previous hash: 前一个区块的hash
- hash: 当前区块的hash
- nonce : 挖矿计算次数1 D d9 [) _! P2 Q! e9 p' u7 W
注意:当前实现了一个简单的区块链结构,并不完整。
3 m" h: b3 s6 y) M4 |( J三、代码实现
$ X0 c% b- b" Z& k9 z1.定义区块的结构) L# s4 n7 `3 b" b: g1 r% G
- """
- 区块设计
- """
- 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.创世区块构造
9 v/ M2 R) _6 p9 w7 ?8 [ 创世区块:没有前一个区块,这里的previous_hash和data是自己写死的。 " K, `% {6 G4 b- [ V% I
- # 生成创世区块,这是第一个区块,没有前一个区块
- 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()函数是后面的挖矿函数。
7 a) S: b) _$ W3.挖矿函数定义1 r# n; S0 U* {) k6 u) y
代码如下: Q% y. h) W' i: n# H
- 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.定义区块链结构
* D; }4 Z" w% [& u5 g+ r: j 代码如下:
8 v( l! E* T+ p- U5 d) c' 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
在添加新区块到区块链时,先挖矿在将新区块加入区块链。 8 N, @) k& S: Y% g) D& {2 V' {
四、代码运行
8 W% C" z5 k7 j5 b8 C8 H- [2 ] 测试代码:
) J; ]; w B; F/ T$ e- 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')
运行结果: ) w# n+ h9 W% I H' r4 a
4 g) l1 \* p" Y 这里添加了4个区块(包括创世区块),处了创世区块,每个区块的pre_hash都与前一个区块的hash值相等,这代表区块没有被篡改,数据有效。 |