块说链语:用Python撸一串区块链

in #python7 years ago (edited)

简介

说到区块链,大家不免会想到比特币、加密货币、智能合约、交易、支付,但是这些都是区块链解决的问题,不是其本身,并且这些把理解区块链变得复杂,下面配合Python代码理解区块链结构。

先总结一下区块链的定义,区块链本质上是一个能够保证系统诚实可信的分布式数据库,是由多种技术整合而成,该数据库由使用密码学技术产生的数据区块有序链接而成,每个区块包含一定时间内产生的不可篡改信息。

下面使用Python语言一步步打造一个简单的区块链原型。

区块结构

学习区块链,就要先从区块的结构开始说起,因为价值信息就存在区块中,比如比特币的区块存储的是交易记录。除此以外,区块还含有一些技术信息,来维持区块的结构,抽取其中最关键的5个技术信息,分别是下标(Index),时间戳(Timestamp),前一个区块的哈希值(Previous Hash)和当前区块的哈希值(Current Hash),下面用类来封装这些信息,Python代码如下:

import hashlib

class Block(object):
    def __init__(self, index, data, prev_hash, timestamp):
        self.index = index
        self.data = data
        self.prev_hash = prev_hash
        self.timestamp = timestamp
        self.cur_hash = self.do_hash(index, data, prev_hash, timestamp)    
    def do_hash(self, *args):
        sha256 = hashlib.sha256()        
        for arg in args:
            sha256.update(str(arg).encode('utf-8'))        
        return sha256.hexdigest()

index、timestamp、prev_hash和cur_hash这四个技术信息构成了区块的头部数据,这是一个独立的数据结构;data参数储存价值信息,比如交易记录,也是一个单独的数据结构,但是在这里为了使其简单、便于理解,就混合在一个结构中。

上面代码的do_hash方法,是用来对区块进行哈希加密的,跟「挖矿」无关,没有解决工作量证明(POW)的问题,计算哈希是区块链中的重要环节。这里把区块里的字段数据关联起来后,使用SHA256算法进行哈希计算,得出当前哈希值cur_hash。

区块链结构

区块链本质上就是一个拥有特定结构的数据库,是一个有序且反向链接的列表,在这个列表里,区块按照插入的顺序排列,通过prev_hash这个字段找到上一个区块的哈希值,把每一个区块都链接到上一个区块上,如下图所示:

block_structure.jpg

下面我创建了一个Manager类,用来封装区块链的一些操作,达到维护区块链结构的目的:

import datetime
class Manager(object):    
    """Blockchain manager"""

    blockchain = []

    def __init__(self):
        self.origin_index = 0
        self.origin_prev_hash = '0'
        self.origin_data = 'origin block'
        self.origin_timestamp = datetime.datetime(2016, 4, 1, 0, 0).timestamp()
        Manager.blockchain.append(self.get_origin_block())

比特币使用LevelDB来存储区块链,为了简化,在上面代码上使用Python的列表(List)把区块链直接存储在内存中。刚刚初始化的时候区块链中没有区块,为了能够不断添加新的区块,我们需要区块链中至少有一个区块,这第一个区块被称为「创始块(Genesis Block)」,下面给出创建「创始块」的方法:

class Manager(object):
    ...
    def get_origin_block(self):
        return  Block(self.origin_index, self.origin_data, self.origin_prev_hash,
            self.origin_timestamp)
    ...

有了「创始块」之后,就可以根据当前最新的区块生成下一个区块,代码如下:

class Manager(object):
    ...
    def get_latest_block(self):
        return Manager.blockchain[-1]

    def generate_next_block(self, new_data):
        prev_block = self.get_latest_block()
        next_index = prev_block.index + 1

        next_timestamp = datetime.datetime.now().timestamp()
        return  Block(next_index, new_data, prev_block.cur_hash, next_timestamp)
    ...

结论

以上创建了一个简单的区块链原型,只是一个区块列表,真正的区块链在添加区块的时候需要经历大量的计算,这个过程就是传说中的「工作量证明」(POW,Proof-Of-Work),并且还需要全网「共识机制」的认可。

Sort:  

Thanks u informa

No sweat

Congratulations @heha37! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 2 years!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Do not miss the last post from @steemitboard:

Are you a DrugWars early adopter? Benvenuto in famiglia!
Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Congratulations @heha37! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s) :

You got more than 10 replies.
Your next target is to reach 50 replies.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Support the HiveBuzz project. Vote for our proposal!