• [Python Study Notes]一个简单的区块链结构(python 2.7)


    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    >>文件: csv文件操作.py
    >>作者: liu yang
    >>邮箱: liuyang0001@outlook.com
    >>博客: www.cnblogs.com/liu66blog
    
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    
    # !/usr/bin/env python2.7
    import hashlib as hasher
    import datetime as date
    
    
    class Block:
        def __init__(self, index, data, time, previous_hash):
            self.index = index
            self.data = data
            self.time = time
            self.previous_hash = self.hash_block()
    
        def hash_block(self):
            sha = hasher.sha256()
            sha.update(str(self.index) + str(date) + str(self.time) + str(self.previous_hash))
            return sha.hexdigest()
    
    
    '''区块链的起源块'''
    def create_genesis_block():
        # 初始化一个区块
        return Block(index=0, time=date.datetime.now(), data='genesis block', previous_hash='0')
    
    '''定义下一个区块'''
    def next_block(last_block):
        this_index = last_block+1
        this_time = date.datetime.now()
        this_data = '数据'+str(this_index)
        this_previous_hash = last_block.hash
        return Block(index=this_index, time=this_time, data=this_data, previous_hash=this_previous_hash)
    
    
    if __name__ == '__main__':
    
        block_chain = [create_genesis_block()]
        previous_block = block_chain[0]
        num_of_block = 20
        # 添加区块到我们的链上
        for i in range(0,num_of_block):
            block_to_add=next_block(previous_block)
            blockchain.append(block_to_add)
            previous_block=block_to_add
            print('Block #{} has been added to the chain'.format(block_to_add.index))
  • 相关阅读:
    部署ArcGIS JS API 离线包(Tomcat与IIS)
    BootStrap入门教程 (一)
    找个些有用的网站(CSS生成)
    android 调用系统相机拍照 获取原图
    Android 拍照
    Android调用Webservice发送文件
    Android 开发添加控件事件的三种方式
    vim中的ctrl+s导致的“假死”、无响应、不接受输入
    Ubuntu下eclipse中运行Hadoop时所需要的JRE与JDK的搭配
    ubuntu下安装bin文件
  • 原文地址:https://www.cnblogs.com/liu66blog/p/8470061.html
Copyright © 2020-2023  润新知