用Python实现区块链

2017/12/12 程序

近期比特币单价突破一万美元,我自14年开始认识比特币到现在短短不到4年,比特币单价翻了几十倍,出乎意料。抛离金融经济的因素,下面尝试使用Python语言实现一种自定义的区块链。

什么是区块链

维基百科提到,区块链(Block Chain)一词首次是由中本聪在《比特币白皮书》中提出。目前还没有关于区块链的定义,我查阅了其他的资料,对区块链的概念大致总结为:

  1. 区块链是一个处于非安全网络的、去中心化的分布式数据库。
  2. 区块链依赖密码学的方式确保已有的数据块不被篡改。
  3. 区块链采用共识算法来完成对新增加的数据块的共识。

区块链是一个公共数据库,其中不断产生的数据储存在块中,并将区块组装程链。这里的数据可以是一组交易,也可以是合约等任何类型。

比特币与区块链的联系

比特币是一种电子货币,总发行量是2100万枚。比特币的交易系统是基于区块链技术,将交易以数据的形式储存在区块链的块中。所以区块链实际上是比特币交易的账本,区块链由一群分散的客户端节点组成,记录所有比特币交易历史。区块中的交易记录保存着发起人的数字签名确保合法性与真实性,通过散列函数来确保区块不被篡改。

你会注意到比特币不完全等同于区块链,而区块链技术可以衍生出很多类似的电子货币,它们在其他特性上作出了改进。例如以太币、门罗币等等。

使用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.

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.

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

区块链的应用场景

区块链是一种创造信任的技术,它的最大优势在于点对点之间的信任传递。它可以应用于银行间清结算、医疗证明、合约证明、股权交易、供应链溯源、供应链金融等领域。

我们来看一看阿里巴巴公司在区块链上的技术应用案例:

2016年7月,阿里巴巴蚂蚁金服将区块链技术应用于支付宝爱心捐赠平台,使用区块链技术来实现捐赠溯源,目的是让每一笔款项的生命周期都记录在区块链上。

2016年10月,阿里巴巴邮箱与云大大合作,推出基于区块链技术的邮箱存证产品。用户可将重要邮件的特征数据同步保存至权威的第三方机构。当产生纠纷时,用户可以自行下载邮件全文,在发送至司法鉴定机构对原始邮件特征数据与之前存证数据进行比对后,即可生成相应的出证鉴定报告,依此报告用户就能够有效地维护自身的合法权益。

2017年3月24日,阿里巴巴与普华永道签署了一项新的跨境食品溯源的互信框架合作,双方宣布将应用“区块链”等新技术共同打造透明可追溯的跨境食品供应链,搭建更为安全的食品市场。通过将境内境外参与各方原本分散独立的信息串联起来,实现全球信息的可溯源、可追踪,在供应链中构建公信力和问责制。

类似的,腾讯、百度、网易、迅雷、京东金融等国内重量级的互联网公司都开始应用区块链新兴技术。2018年将会是区块链技术落地应用的创世纪。

Search

    Table of Contents