40行python开发一个区块链---实践小记

40行python开发一个区块链---实践小记


叮嘟!这里是小啊呜的学习课程资料整理。好记性不如烂笔头,今天也是努力进步的一天。一起加油进阶吧!
在这里插入图片描述

一、前言

本次实践指导详细参见文章:戳这儿!

  https://www.imooc.com/article/details/id/29636

二、关于区块链

区块链是一个公开的数字账本,它按时间顺序记录比特币或其他加密货币发生的交易。

更一般的讲,区块链是一个公共数据库,新的数据将存储在一个被称为”块“的容器中,然后块会被添加到一个不可篡改的链,因此被称为“区块链”。当我们谈到比特币或其他加密货币时,这些数据指的是交易记录。当然,你可以将任何类型的数据存入区块链。

区块链技术已经催生了全新的、完全数字化的货币,如比特币和莱特币,这些货币并不是由中央政府发行或管理的。这一技术给那些不认可当前银行系统人带来了新的自由。

区块链同时也为分布式计算带来了革命性的创新,例如,以太坊区块链引入了一些有趣的概念,比如智能合约。

在本文中,将用40多行的Python 3代码来做一个简单的区块链。我们称它为SnakeCoin。

我们首先将定义“块”的数据结构。在区块链中,每个块都存储一个时间戳和一个可选地索引。在SnakeCoin中,我们将把两者都存储起来。为了确保整个区块链的完整性,每个块都有一个用于自我标识的哈希。与比特币一样,每个块的哈希将是对块索引、时间戳、数据和前块哈希计算出的加密哈希值。其中你可以在数据中保存任何内容。

二、实践小记

import hashlib as hasher

class Block:
    def __init__(self, index, version, previous_hash, timestamp, data):
        self.index = index
        self.version = version
        self.previous_hash = previous_hash
        self.timestamp = timestamp
        self.data = data
        self.hash = self.hash_block()

    def hash_block(self):
        sha = hasher.sha256()
        sha.update((str(self.index) + str(self.timestamp) + str(self.data) + str(self.previous_hash)).encode("utf-8"))
        return sha.hexdigest()


import datetime as date


def create_genesis_block():
    # Manually construct a block with
    # index zero and arbitrary previous hash
    return Block(0, "v1.00", "0", date.datetime.now(), "Genesis Block")


def next_block(last_block, version):
    this_index = last_block.index + 1
    this_version = version
    this_hash = last_block.hash
    this_timestamp = date.datetime.now()
    this_data = "Hey! I'm block " + str(this_index)
    return Block(this_index, this_version, this_hash, this_timestamp, this_data)


# Create the blockchain and add the genesis block
blockchain = [create_genesis_block()]
previous_block = blockchain[0]

# How many blocks should we add to the chain
# after the genesis block
num_of_blocks_to_add = 20

# Add blocks to the chain
for i in range(0, num_of_blocks_to_add):
    block_to_add = next_block(previous_block, "v1.00")
    blockchain.append(block_to_add)
    previous_block = block_to_add
    # Tell everyone about it!
    print("Block #{} has been added to the blockchain!".format(block_to_add.index))
    print("Hash: {}\n".format(block_to_add.hash))

成功跑通!
如果希望在控制台中查看更多信息,可以编辑源文件并打印每个块的时间戳或块中的数据。

实验结果如下:

在这里插入图片描述
在这里插入图片描述

Ending!
更多课程知识学习记录随后再来吧!

就酱,嘎啦!

在这里插入图片描述

注:
人生在勤,不索何获。

猜你喜欢

转载自blog.csdn.net/qq_43543789/article/details/109237828
今日推荐