程序员区块链研习社

来吧,创造一条区块链(上)

2018-07-24  本文已影响26人  Andytl的世界

看到一篇外文文章《Let’s Build the Tiniest Blockchain》(搭梯子出去看哦),很适合初学者理解区块链,而且用不到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?
虽然有人认为区块链是无本之木,解决不了实际问题,但毫无疑问区块链是个奇迹,居然通过计算机实现了去中介。到底什么是区块链呢?

1.区块链
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代码创造一条简单的区块链。这条区块链我们就叫它‘蛇链’吧。

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.
像比特币,每个区块的专属哈希值是由本区块索引、时间戳、数据、前一个区块的哈希值一起计算而来。别忘了,其中数据可以是任何你想要的东西。

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 blockchain. 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,数据为任意值,上一区块哈希值也是任意值。

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中的列表。第一个元素是创世区块。接下来产生连续的去块,成为区块链。‘蛇链’是个迷你区块链,我们就用循环产生20个区块意思一下。

# 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.
测试一下我们的杰作。

别慌,会跑到20

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.
这就是‘蛇链’的基本构造。为了使得‘蛇链’像个区块链产品(而不是个玩具),还需要给它增加一些性能。比如,增加服务层以跟踪区块链在多台机器上的变化,增加‘工作量证明’以限制一定时间内区块的数量。

If you’d like to get more technical, you can view the original Bitcoin whitepaper here. Best of luck and happy hacking!
如果想了解更多技术,建议去阅读比特币白皮书。祝你好运,开心就好!

Note: Part 2 of this piece can be found here.
备注:本文的下半部分已经放出。

上一篇 下一篇

猜你喜欢

热点阅读