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))
  • 相关阅读:
    GitLab 介绍
    git 标签
    git 分支
    git 仓库 撤销提交 git reset and 查看本地历史操作 git reflog
    git 仓库 回退功能 git checkout
    python 并发编程 多进程 练习题
    git 命令 查看历史提交 git log
    git 命令 git diff 查看 Git 区域文件的具体改动
    POJ 2608
    POJ 2610
  • 原文地址:https://www.cnblogs.com/liu66blog/p/8470061.html
Copyright © 2011-2022 走看看