zoukankan      html  css  js  c++  java
  • [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))
  • 相关阅读:
    mybatis之衣服商城
    mybatis之增加操作
    There is no getter for property named 'answer' in 'class (N1)
    java.lang.ClassNotFoundException原因
    Openstack(Kilo)安装系列之环境准备(一)
    Python标识符
    Python命令行参数
    Python中文编码
    嵌入式数据库H2的安装与配置
    saltstack之nginx部署
  • 原文地址:https://www.cnblogs.com/liu66blog/p/8470061.html
Copyright © 2011-2022 走看看