用不到 50 行的 Python 代码构建最小的区块链

(点击上方公众号,可快速关注)


译文:黑色巧克力 

geek.csdn.net/news/detail/228355

如有好文章投稿,请点击 → 这里了解详情



尽管一些人认为区块链是一个等待问题的解决方案,但毫无疑问,这种新技术是计算机的奇迹。但是,区块链到底是什么呢?


区块链


它是比特币或其他加密货币进行交易的数字账本,账本按时间顺序记录并对外公开。


在更一般的术语中,它是一个公共数据库,新数据存储在一个名为块的容器中,并被添加到一个不可变链(后来的区块链)中添加了过去的数据。在比特币和其他加密货币的情况下,这些数据是一组交易记录。当然,数据可以是任何类型的。


区块链技术已经催生了新的、完全数字化的货币,如比特币和莱特币,这些货币并不是由中央政府发行或管理的。因此为那些认为今天的银行系统是骗局或终将失败的人带来了新的自由。区块链所包含的以太坊技术对分布式计算进行了变革创新,它引入了一些有趣的概念,比如智能合约。


在本文中,我将用不到50行的Python2代码来做一个简单的区块链。我称它为SnakeCoin。


首先将定义块将是什么样子。在区块链中,每个块都存储一个时间戳和一个索引。在SnakeCoin中,需要把两者都存储起来。为了确保整个区块链的完整性,每个块都有一个自动识别散列。与比特币一样,每个块的散列将是块索引、时间戳、数据和前块哈希的加密哈希。数据可以是你想要的任何东西。


import hashlib as hasher

 

class Block:

  def __init__(self, index, timestamp, data, previous_hash):

    self.index = index

    self.timestamp = timestamp

    self.data = data

    self.previous_hash = previous_hash

    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))

    return sha.hexdigest()


这一步后有块结构,但现在是创建区块链,所以需要向实际的链中添加块。如前所述,每个块都需要上一个块的信息。但是按照这个说法就有一个问题,区块链的第一个区块是如何到达那里的呢?不得不说,第一个块,或者说是起源块,它是一个特殊的块。在很多情况下,它是手动添加的,或者有独特的逻辑允许添加。


下面将创建一个函数简单地返回一个起源块以便产生第一个区块。这个块是索引0,它具有任意的数据值和“前一个哈希”参数中的任意值。


import datetime as date

 

def create_genesis_block():

  # Manually construct a block with

  # index zero and arbitrary previous hash

  return Block(0, date.datetime.now(), "Genesis Block", "0")


现在已经创建好了起源块,接下来需要一个函数,以便在区块链中生成后续的块。这个函数将把链中的前一个块作为参数,创建要生成的块的数据,并使用适当的数据返回新块。当新的块哈希信息来自前面的块时,区块链的完整性会随着每个新块而增加。如果不这样做,外部组织就更容易“改变过去”,用全新的方式取代已有的链条。这一系列的散列可以作为加密的证据,有助于确保一旦将块添加到区块链,它就不能被替换或删除。


def next_block(last_block):

  this_index = last_block.index + 1

  this_timestamp = date.datetime.now()

  this_data = "Hey! I'm block " + str(this_index)

  this_hash = last_block.hash

  return Block(this_index, this_timestamp, this_data, this_hash)


大部分的工作已经完成,现在可以创建区块链了。在这次的示例中,区块链本身是一个简单的Python列表。列表的第一个元素是起源块。当然,还需要添加后续的块,因为SnakeCoin是最小的区块链,这里只添加20个新的块。可以用for循环来生成新块。


# 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)

  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)


下面来测试一下目前产生的区块链。



看到了吧,这就是区块链。如果希望在控制台中查看更多信息,可以编辑完整的源文件并打印每个块的时间戳或数据。


这就是SnakeCoin要提供的所有东西。为了使SnakeCoin规模达到今天生产区块链的规模,必须添加更多的功能,比如服务器层,以跟踪多台机器上的链变化,以及在给定的时间段内限制添加的块数量的工作算法。


看完本文有收获?请转发分享给更多人

关注「Python开发者」,提升Python技能

淘口令复制以下红色内容,再打开手淘即可购买

范品社,使用¥极客T恤¥抢先预览(长按复制整段文案,打开手机淘宝即可进入活动内容)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
很高兴回答您的问题。下面是200代码构建一个简单的区块链的示例: ```python import hashlib import json from time import time class Blockchain(object): def __init__(self): self.chain = [] self.current_transactions = [] # Create the genesis block self.new_block(previous_hash=1, proof=100) def new_block(self, proof, previous_hash=None): """ Create a new Block in the Blockchain :param proof: <int> The proof given by the Proof of Work algorithm :param previous_hash: (Optional) <str> Hash of previous Block :return: <dict> New Block """ block = { 'index': len(self.chain) + 1, 'timestamp': time(), 'transactions': self.current_transactions, 'proof': proof, 'previous_hash': previous_hash or self.hash(self.chain[-1]), } # Reset the current list of transactions self.current_transactions = [] self.chain.append(block) return block def new_transaction(self, sender, recipient, amount): """ Creates a new transaction to go into the next mined Block :param sender: <str> Address of the Sender :param recipient: <str> Address of the Recipient :param amount: <int> Amount :return: <int> The index of the Block that will hold this transaction """ self.current_transactions.append({ 'sender': sender, 'recipient': recipient, 'amount': amount, }) return self.last_block['index'] + 1 @staticmethod def hash(block): """ Creates a SHA-256 hash of a Block :param block: <dict> Block :return: <str> """ # We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes block_string = json.dumps(block, sort_keys=True).encode() return hashlib.sha256(block_string).hexdigest() @property def last_block(self): return self.chain[-1] def proof_of_work(self, last_proof): """ Simple Proof of Work Algorithm: - Find a number p' such that hash(pp') contains leading 4 zeroes, where p is the previous p' - p is the previous proof, and p' is the new proof :param last_proof: <int> :return: <int> """ proof = 0 while self.valid_proof(last_proof, proof) is False: proof += 1 return proof @staticmethod def valid_proof(last_proof, proof): """ Validates the Proof: Does hash(last_proof, proof) contain 4 leading zeroes? :param last_proof: <int> Previous Proof :param proof: <int> Current Proof :return: <bool> True if correct, False if not. """ guess = f'{last_proof}{proof}'.encode() guess_hash = hashlib.sha256(guess).hexdigest() return guess_hash[:4] == "0000" ``` 这是一个区块链的基本数据结构和功能。您可以使用该代码测试和开发。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值