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))
  • 相关阅读:
    (纯代码)QQ登录界面:
    (纯代码)图片浏览器:
    (纯代码 )transform旋转:
    苹果API常用英语名词:
    纯代码创建Button控件:
    GCD
    UISegmentedControl 开发笔记
    UISwitch 开关控件 开发笔记
    Xcode6中怎么添加空工程模板
    HTTP Live Streaming直播(iOS直播)技术分析与实现
  • 原文地址:https://www.cnblogs.com/liu66blog/p/8470061.html
Copyright © 2011-2022 走看看