QQ登录

只需要一步,快速开始

APP扫码登录

只需要一步,快速开始

查看: 2539|回复: 0

[Python] 详解python实现简单区块链结构

[复制链接]

等级头衔

积分成就    金币 : 2861
   泡泡 : 1516
   精华 : 6
   在线时间 : 1321 小时
   最后登录 : 2025-7-2

丰功伟绩

优秀达人突出贡献荣誉管理论坛元老活跃会员

联系方式
发表于 2021-4-25 19:46:12 | 显示全部楼层 |阅读模式
       比特币从诞生到现在已经10年了,最近接触到了区块链相关的技术,为了揭开其背后的神秘面纱,我就从头开始构建一个简单的区块链。; k( y2 t1 w- F8 e' j: q% p
       从技术上来看:区块是一种记录交易的数据结构,反映了一笔交易的资金流向。系统中已经达成的交易的区块连接在一起形成了一条主链,所有参与计算的节点都记录了主链或主链的一部分。
0 y# D& |8 f5 {+ e5 t, I3 s. f1 x 1.jpg
5 l) s! c: }' {( i0 |一、比特币内部结构: g" q0 |6 m" {) S1 [
比特币内部结构有四部分:4 d' R, g! O- ]. t1 T4 b! L
  • previous hash: 上一个区块的hash
  • data:交易数据
  • time stamp:区块生成的时间戳
  • nonce:挖矿计算次数3 r  P. f" K0 j5 t
二、实现的比特币结构
" J1 Z& u, I- b8 J1 x8 v
  • index :当前区块索引
  • timestamp :该区块创建时的时间戳
  • data :交易信息
  • previous hash: 前一个区块的hash
  • hash: 当前区块的hash
  • nonce : 挖矿计算次数
    . P$ X5 R! j, t( E* E
注意:当前实现了一个简单的区块链结构,并不完整。1 d2 J8 N/ q$ ?' E4 t% A0 K' h
三、代码实现
8 I; @; s/ ^0 j$ ^9 r' n" ^1.定义区块的结构+ ^" K+ n$ A* h0 a  \0 w
"""
区块设计
"""
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.创世区块构造
5 F# B2 e* K( j2 r, ~4 ?3 t       创世区块:没有前一个区块,这里的previous_hash和data是自己写死的。0 g. z0 U4 J+ V( x* k5 ^$ D
# 生成创世区块,这是第一个区块,没有前一个区块
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()函数是后面的挖矿函数。
$ t/ U2 \/ e" {$ q' L! r3.挖矿函数定义/ T: N  _% i' e0 V$ C1 q) [5 I+ [* \
       代码如下:
5 F# [/ q; y2 d; M
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.定义区块链结构
! h! |  Y% _1 q8 B$ P' |; _       代码如下:
, s' B. F/ {9 T" A) U3 F
"""
区块链设计
"""
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
      在添加新区块到区块链时,先挖矿在将新区块加入区块链。+ z5 \( ^' s2 w$ Y$ h
四、代码运行6 S1 s0 v) ~* v7 O% c/ ?2 |3 ~) f
       测试代码:7 O% U! T6 J! l! b- f
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')
      运行结果:8 a0 o% P! U, n" i
2.jpg   i( R. _; I2 F3 s. M
       这里添加了4个区块(包括创世区块),处了创世区块,每个区块的pre_hash都与前一个区块的hash值相等,这代表区块没有被篡改,数据有效。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|paopaomj.COM ( 渝ICP备18007172号|渝公网安备50010502503914号 )

GMT+8, 2025-7-2 08:28

Powered by paopaomj X3.5 © 2016-2025 sitemap

快速回复 返回顶部 返回列表