首页 > 代码库 > 50行Python代码构建小型区块链

50行Python代码构建小型区块链

本文介绍了如何使用python构建一个小型的区块链技术,使用Python2实现,代码不到50行。

 

Although some think blockchain is a solution waiting for problems, there’s no doubt that this novel technology is a marvel of computing. But, what exactly is a blockchain?
虽然有人认为区块链本身仍有很多问题需要解决,但毫无疑问,这种新颖的技术是计算机界的奇迹。 但是,究竟什么是一个区块链?

Blockchain
a digital ledger in which transactions made in bitcoin or another cryptocurrency are recorded chronologically and publicly. >
区块链一种数字记账本,其中以比特币或其他加密方式按时间顺序并公开记录地进行交易。

In more general terms, it’s a public database where new data are stored in a container called a block and are added to an immutable chain (hence blockchain) with data added in the past. In the case of Bitcoin and other cryptocurrencies, these data are groups of transactions. But, the data can be of any type, of course.
通俗的讲,区块链是一个公共数据库,其中新产生的数据存储在称为块的容器中,并被添加到具有已经存在数据的区块构成的链中。在比特币和其他加密货币的情况下,这些数据是一组交易。数据也可以是任何类型的。


Blockchain technology has given rise to new, fully digital currencies like Bitcoin and Litecoin that aren’t issued or managed by a central authority. This brings new freedom to individuals who believe that today’s banking systems are a scam or subject to failure. Blockchain has also revolutionized distributed computing in the form of technologies like Ethereum, which has introduced interesting concepts like smart contracts.
区块链技术已经带来了全新的,完全数字化的货币,如比特币和莱特币,它们不由中央机构发行或管理的,这给相信今天的银行体系是骗局或失败的个人带来了新的自由。区块链也以像以太坊这样的技术形式革新了分布式计算,它引入了有趣的概念,如智能合约。


In this article, I’ll make a simple blockchain in less than 50 lines of Python 2 code. It’ll be called SnakeCoin.
在本文中,我将在不到50行的Python 2代码中制作一个简单的区块链。这将被称为SnakeCoin。


We’ll start by first defining what our blocks will look like. In blockchain, each block is stored with a timestamp and, optionally, an index. In SnakeCoin, we’re going to store both. And to help ensure integrity throughout the blockchain, each block will have a self-identifying hash. Like Bitcoin, each block’s hash will be a cryptographic hash of the block’s index, timestamp, data, and the hash of the previous block’s hash. Oh, and the data can be anything you want.
我们首先定义我们的区块将是什么样子。在区块链中,每个块都存储有时间戳和可选的索引。在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()
    


Awesome! We have our block structure, but we’re creating a block chain. We need to start adding blocks to the actual chain. As I mentioned earlier, each block requires information from the previous block. But with that being said, a question arises: how does the first block in the blockchain get there? Well, the first block, or genesis block, is a special block. In many cases, it’s added manually or has unique logic allowing it to be added.
真棒!我们已经有了块结构了,但是我们正在创建一个区块链。我们需要开始向实际的链条添加区块。如前所述,每个块都需要上一个块的信息。但是这就出现了一个问题:块区中的第一个区块怎么来的?那么,第一个区块,或起创世区块,是一个特殊的块。在许多情况下,它是手动添加的或具有允许添加的唯一逻辑。


We’ll create a function that simply returns a genesis block to make things easy. This block is of index 0, and it has an arbitrary data value and an arbitrary value in the “previous hash” parameter.
为了简化,我们将创建一个函数,只需返回一个创世区块,该区块的索引为0,它在“previous hash”参数中具有任意数据值和任意值。

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

Now that we’re able to create a genesis block, we need a function that will generate succeeding blocks in the blockchain. This function will take the previous block in the chain as a parameter, create the data for the block to be generated, and return the new block with its appropriate data. When new blocks hash information from previous blocks, the integrity of the blockchain increases with each new block. If we didn’t do this, it would be easier for an outside party to “change the past” and replace our chain with an entirely new one of their own. This chain of hashes acts as cryptographic proof and helps ensure that once a block is added to the blockchain it cannot be replaced or removed.
现在我们创建了一个创世区块,我们需要一个函数来生成区块链中的后续区块。该函数将将链中的前一个区块作为参数,创建要生成的区块的数据,并返回具有其相应数据的新块。新产生的区块会存储先前区块中的哈希值,区块链的完整性随着每个新的区块而增加。如果我们没有这样做,其他人会很容易篡改历史记录,并用自己的全新数据替代我们的链条。这个哈希链作为加密证明,有助于确保一旦新区块被添加到区块链中,它不能被替换或删除。

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)  

 
That’s the majority of the hard work. Now, we can create our blockchain! In our case, the blockchain itself is a simple Python list. The first element of the list is the genesis block. And of course, we need to add the succeeding blocks. Because SnakeCoin is the tiniest blockchain, we’ll only add 20 new blocks. We can do this with a for loop.
这是本次任务的重心。现在我们可以创建我们的区块链!在我们的例子中,区块链本身就是一个简单的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)

 
Let’s test what we’ve made so far.
我们来测试一下已有成果。

技术分享


There we go! Our blockchain works. If you want to see more information in the console, you could edit the complete source file and print each block’s timestamp or data.
我去!我们的区块链生效了!如果要在控制台中查看更多信息,可以编辑完整的源文件并打印每个块的时间戳或数据。

That’s about all that SnakeCoin has to offer. To make SnakeCoin scale to the size of today’s production blockchains, we’d have to add more features like a server layer to track changes to the chain on multiple machines and a proof-of-work algorithm to limit the amount of blocks added in a given time period.
那就是SnakeCoin所提供的一切。为了使SnakeCoin缩小到当今生产块链的大小,我们必须添加更多的功能,如服务器层,以跟踪多台机器上链的变化,并提供工作证明算法,以在给定时间段限制块链数量。

If you’d like to get more technical, you can view the original Bitcoin whitepaper here. Best of luck and happy hacking!
如果您想获得更多技术细节,您可以查看原始的比特币白皮书。 祝好运!

Thank you very much for reading!
感谢阅读!

 

英文原文:https://dev.to/aunyks/lets-build-the-tiniest-blockchain
原创翻译:http://www.cnblogs.com/fangbei/

 

50行Python代码构建小型区块链