本文翻译自《Learn Blockchains by Building One》,作者@dvf,原文链接:https://hackernoon.com/learn-blockchains-by-building-one-117428612f46

去年10月24日,区块链被提升至国家战略地位,包括传统大企业、央企等在内的公司纷纷布局区块链。社会上掀起了一阵学习区块链的热潮,而区块链人才也成了“抢手货”。

对于我们这种写程序的工匠来说,学习区块链最快的方法不外乎自己创建一个区块链。下文,将带领大家建立一个简单的区块链,在实践中学习,既能加深对区块链的理解,又能获得技能。

区块链是由一个个不可变的、连续的记录信息的区块连接在一起的链。区块包含交易信息、文件或任何你想要记录的数据。最重要的是,各个区块由“哈希”链接在一起。

在开始前,你需要安装Python3.6+(以及pip)、Flask、Requests library:

pip install Flask==0.12.2 requests==2.18.4

另外,还需要一个HTTP客户端,Postman或cURL均可。

接下来可以开始了。

Step 1:创建一个区块链

打开文本编辑器或IDE,这里推荐PyCharm。

创建一个新文件,命名为blockchain.py。整个过程只会用一个文件,如果你弄丢了,可以在这里找到源文件:https://github.com/dvf/blockchain

呈现区块链

创建一个 blockchain class,在这个class中,constructor会创建一个原始的空白列表用以存储区块链,另一个用来存储交易。以下是class的蓝图:

class Blockchain(object):def __init__(self):self.chain = []self.current_transactions = []def new_block(self):# Creates a new Block and adds it to the chainpassdef new_transaction(self):# Adds a new transaction to the list of transactionspass@staticmethoddef hash(block):# Hashes a Blockpass@propertydef last_block(self):# Returns the last Block in the chainpass

Blockchain class负责管理链,能够存储交易,并能辅助添加新块到链上。

区块是什么样的?

每个区块都有一个index、一个时间戳、一个交易列表、一个证明,以及前一个块的哈希值。下面是一个示例:

block = {'index': 1,'timestamp': 1506057125.900785,'transactions': [{'sender': "8527147fe1f5426f9dd545de4b27ee00",'recipient': "a77f5cdfa2934df3954a5c7c7da5df1f",'amount': 5,}],'proof': 324984774000,'previous_hash': "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
}

从这个示例可以看出,“链”的思想还是非常明显的——每个新块都包含前一个块的哈希值。这点很关键,因为它使区块链具有了“不可变性”:如果攻击者损毁了链上的早期块,则所有后续块都将包含不正确的哈希值。

往块中添加交易

使用new_transaction():

class Blockchain(object):...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

new_transaction()将一个交易添加到列表中后,它将返回下一个将被挖出的块的index。这对提交交易的用户很有用。

创建新块

当Blockchain被具现化后,我们就需要创建“创世区块”了。首先需要在创世区块链中添加一个证明(proof),这个证明就是挖矿的结果(工作量证明)。关于挖矿,我们稍后再说。

除了在constructor里添加创世区块,还需要填充new_block()、new_transaction()、hash():

import hashlib
import json
from time import timeclass Blockchain(object):def __init__(self):self.current_transactions = []self.chain = []# Create the genesis blockself.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 transactionsself.current_transactions = []self.chain.append(block)return blockdef 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@propertydef last_block(self):return self.chain[-1]@staticmethoddef 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 hashesblock_string = json.dumps(block, sort_keys=True).encode()return hashlib.sha256(block_string).hexdigest()

上面的示例应该很清晰了,为了帮助大家理解,我也添加了一些注释和docstrings。我们已经几乎完成了区块链的展示。接下来,我们来看看一个新块是怎么被挖出来的。

工作量证明(Proof of Work

工作量证明算法就是区块如何被创建或者如何被挖出的方法。工作量证明的目标是发现一个解决谜题的“数字”,这个数字很难找到但是很容易被网络中的人通过计算来验证。

来看一个非常简单的例子,进一步理解这个问题。

首先定义:某个整数X乘以Y的哈希值必须以0结尾,所以hash(x*y)=ac23dc……0,其中X=5。在Python中实现:

from hashlib import sha256
x = 5
y = 0  # We don't know what y should be yet...
while sha256(f'{x*y}'.encode()).hexdigest()[-1] != "0":y += 1
print(f'The solution is y = {y}')

这里的解是Y=21,因为生成的哈希以0结尾:

hash(5 * 21) = 1253e9373e...5e3600155e860

在比特币区块链中,工作量证明算法被称为Hashcash,和上面的例子没有太大区别。这是矿工们为了创建一个新的区块而竞相求解的算法,难度取决于在字符串中搜索的字符数。然后,成功挖出块的矿工将会收到比特币作为奖励。

网络能够很容易地验证他们的解决方案。

部署基本工作量证明

接下来,为我们的区块链部署一个类似的算法,规则和上面的示例类似。

当我们用前一个块的哈希值4进行哈希运算时,找到一个数字P,输出“0s”:

import hashlib
import jsonfrom time import time
from uuid import uuid4class Blockchain(object):...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 = 0while self.valid_proof(last_proof, proof) is False:proof += 1return proof@staticmethoddef 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"

为了调整算法的难度,我们可以修改前导零的数目。但4就足够了,你会发现加上一个前导零会使找到解决方案所需的时间产生巨大的差异。

到这里,class差不多完成了,接下来准备开始使用HTTP请求与它交互。

Step 2:Blockchain作为一个API

使用Python Flask Framework,创建三个路径:

/transactions/new添加新的交易到块中

/mine告诉服务器挖出一个新块

/chain返回整个区块链

设置Flask

我们的服务器在区块链网络中就是一个节点,接下来创建一些样板代码:

import hashlib
import json
from textwrap import dedent
from time import time
from uuid import uuid4from flask import Flaskclass Blockchain(object):...# Instantiate our Node
app = Flask(__name__)# Generate a globally unique address for this node
node_identifier = str(uuid4()).replace('-', '')# Instantiate the Blockchain
blockchain = Blockchain()@app.route('/mine', methods=['GET'])
def mine():return "We'll mine a new Block"@app.route('/transactions/new', methods=['POST'])
def new_transaction():return "We'll add a new transaction"@app.route('/chain', methods=['GET'])
def full_chain():response = {'chain': blockchain.chain,'length': len(blockchain.chain),}return jsonify(response), 200if __name__ == '__main__':app.run(host='0.0.0.0', port=5000)

对上面添加的内容做个简单解释:
Line15:具现化节点

Line18:为节点创建一个随机的名字

Line21:具现化Blockchain class

Line24-26:创建/mine端点,这是一个GET请求。

Line28-30:创建/transactions/new端点,这是一个POST请求,因为我们要向它发送数据。

Line32-38:创建/chain端点,返回整个区块链。

Line40-41:在端口5000上运行服务器。

交易端点

这是交易请求的示例。下面是用户发送给服务器的内容:

{"sender": "my address","recipient": "someone else's address","amount": 5
}

有了添加交易到块的class路径后,剩下的就很简单了。编写添加交易的函数:

import hashlib
import json
from textwrap import dedent
from time import time
from uuid import uuid4from flask import Flask, jsonify, request...@app.route('/transactions/new', methods=['POST'])
def new_transaction():values = request.get_json()# Check that the required fields are in the POST'ed datarequired = ['sender', 'recipient', 'amount']if not all(k in values for k in required):return 'Missing values', 400# Create a new Transactionindex = blockchain.new_transaction(values['sender'], values['recipient'], values['amount'])response = {'message': f'Transaction will be added to Block {index}'}return jsonify(response), 201

挖矿端点

挖矿端点是展现奇迹的地方,主要做三件事:

计算工作量证明

奖励添加块成功的旷工一个币

把新的块添加到链上

import hashlib
import jsonfrom time import time
from uuid import uuid4from flask import Flask, jsonify, request...@app.route('/mine', methods=['GET'])
def mine():# We run the proof of work algorithm to get the next proof...last_block = blockchain.last_blocklast_proof = last_block['proof']proof = blockchain.proof_of_work(last_proof)# We must receive a reward for finding the proof.# The sender is "0" to signify that this node has mined a new coin.blockchain.new_transaction(sender="0",recipient=node_identifier,amount=1,)# Forge the new Block by adding it to the chainprevious_hash = blockchain.hash(last_block)block = blockchain.new_block(proof, previous_hash)response = {'message': "New Block Forged",'index': block['index'],'transactions': block['transactions'],'proof': block['proof'],'previous_hash': block['previous_hash'],}return jsonify(response), 200

注意,挖出的块的接收者是我们节点的地址。我们所做的这些是为了和Blockchain class里的路径进行交互,现在可以和blockchain进行交互了。

Step3:和Blockchain进行交互

你可以使用普通的cURL或Postman通过网络与API交互。

启动服务器:

$ python blockchain.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

让我们尝试通过GET请求到 http://localhost:5000/mine: 挖一个区块。

(用Postman创建GET请求)

通过POST请求到http://localhost:5000/transactions/new创建一笔交易。

(用Postman创建POST请求)

如果你没用Postman,可以用cURL:

$ curl -X POST -H "Content-Type: application/json" -d '{"sender": "d4ee26eee15148ee92c6cd394edd974e","recipient": "someone-other-address","amount": 5
}' "http://localhost:5000/transactions/new"

重启服务器,挖出两个块,现在总共有3个区块,接下来通过请求http://localhost:5000/chain检视整个链。

{"chain": [{"index": 1,"previous_hash": 1,"proof": 100,"timestamp": 1506280650.770839,"transactions": []},{"index": 2,"previous_hash": "c099bc...bfb7","proof": 35293,"timestamp": 1506280664.717925,"transactions": [{"amount": 1,"recipient": "8bbcb347e0634905b0cac7955bae152b","sender": "0"}]},{"index": 3,"previous_hash": "eff91a...10f2","proof": 35089,"timestamp": 1506280666.1086972,"transactions": [{"amount": 1,"recipient": "8bbcb347e0634905b0cac7955bae152b","sender": "0"}]}],"length": 3
}

Step4:共识

现在,我们已经有了一个最基本的区块链,能够实现接收交易、挖出区块。但区块链最核心的点时“去中心化”。另外,如果它们是去中心化的,又该如何确保它们映射的是整条链呢?这就涉及到共识问题。如果我们想要做到去中心化,就要确保网络中有多个节点,有了多个节点,就需要有共识算法。

注册新节点

在部署共识算法之前,我们需要找到一个方法让节点知道网络上的相邻节点。网络上的每个节点都应该保存其它节点的注册表。因此,我们需要更多的端点:

/nodes/register接收URL形式的新节点列表

/nodes/resolve部署共识算法,解决冲突,确保所有节点都在正确的链上。

我们需要修改区块链的constructor,并提供注册节点的方法:

...
from urllib.parse import urlparse
...class Blockchain(object):def __init__(self):...self.nodes = set()...def register_node(self, address):"""Add a new node to the list of nodes:param address: <str> Address of node. Eg. 'http://192.168.0.5:5000':return: None"""parsed_url = urlparse(address)self.nodes.add(parsed_url.netloc)

注意,我们使用了set()来保存节点列表。这可以确保新节点的添加是幂等的,也就是同一个节点无论添加多少次,都只出现一次。

部署共识算法

节点冲突是指一个节点与另一个节点产生分歧,有了不同的链。为了解决这个问题,我们制定一个规则,即最长的链是正确的链。使用这个算法,网络中的节点之间达成共识。

...
import requestsclass Blockchain(object)...def valid_chain(self, chain):"""Determine if a given blockchain is valid:param chain: <list> A blockchain:return: <bool> True if valid, False if not"""last_block = chain[0]current_index = 1while current_index < len(chain):block = chain[current_index]print(f'{last_block}')print(f'{block}')print("\n-----------\n")# Check that the hash of the block is correctif block['previous_hash'] != self.hash(last_block):return False# Check that the Proof of Work is correctif not self.valid_proof(last_block['proof'], block['proof']):return Falselast_block = blockcurrent_index += 1return Truedef resolve_conflicts(self):"""This is our Consensus Algorithm, it resolves conflictsby replacing our chain with the longest one in the network.:return: <bool> True if our chain was replaced, False if not"""neighbours = self.nodesnew_chain = None# We're only looking for chains longer than oursmax_length = len(self.chain)# Grab and verify the chains from all the nodes in our networkfor node in neighbours:response = requests.get(f'http://{node}/chain')if response.status_code == 200:length = response.json()['length']chain = response.json()['chain']# Check if the length is longer and the chain is validif length > max_length and self.valid_chain(chain):max_length = lengthnew_chain = chain# Replace our chain if we discovered a new, valid chain longer than oursif new_chain:self.chain = new_chainreturn Truereturn False

第一个路径valid_chain()负责检查链是否有效,检查的方式是“巡逻”每个块,并验证块的哈希值和证明。

resolve_conflicts()负责“巡逻”所有的相邻节点,下载他们的链并验证他们是否使用上述路径。如果找到长度大于我们的有效链,这个链将替换我们的链。

让我们将这两个端点注册到我们的API中,一个用于添加相邻节点,另一个用于解决冲突:

@app.route('/nodes/register', methods=['POST'])
def register_nodes():values = request.get_json()nodes = values.get('nodes')if nodes is None:return "Error: Please supply a valid list of nodes", 400for node in nodes:blockchain.register_node(node)response = {'message': 'New nodes have been added','total_nodes': list(blockchain.nodes),}return jsonify(response), 201@app.route('/nodes/resolve', methods=['GET'])
def consensus():replaced = blockchain.resolve_conflicts()if replaced:response = {'message': 'Our chain was replaced','new_chain': blockchain.chain}else:response = {'message': 'Our chain is authoritative','chain': blockchain.chain}return jsonify(response), 200

这时,如果你喜欢的话,可以换一台不同的计算机,也可以在你的网络中旋转不同的节点。或者使用同一台计算机上的不同端口启动进程。我在计算机的另一个端口上创建了另一个节点,并将其注册到当前节点。这样,我有了两个节点:

http://localhost:5000

http://localhost:5001

(注册新节点)

然后我在节点2上挖出一些新的区块,以确保链更长。之后,我在节点1上调用GET /nodes/resolve,其中链被共识算法替代。

(共识算法在工作中)

到这里,一个完整的公有区块链差不多就成型了,你可以找一些你的朋友帮你测试一下。

万向区块链从2015年开始涉足区块链,如果你对区块链感兴趣,欢迎加入我们!

【区块链新手快速入门】如何构建一个区块链相关推荐

  1. 通过python构建一个区块链来学习区块链

    了解区块链Blockchains如何工作的最快方法就是构建一个区块链.你来到这里是因为,和我一样,你对加密钱币的崛起感到很兴奋.而且你想知道区块链是如何工作的,想了解它们背后的基本技术. 但理解区块链 ...

  2. 用 Go 构建一个区块链 ---- Part 1: 基本原型

    翻译的系列文章我已经放到了 GitHub 上:blockchain-tutorial,后续如有更新都会在 GitHub 上,可能就不在这里同步了.如果想直接运行代码,也可以 clone GitHub ...

  3. 用 Go 构建一个区块链 -- Part 1: 基本原型

    引言 区块链是 21 世纪最具革命性的技术之一,它仍然处于不断成长的阶段,而且还有很多潜力尚未显现出来. 本质上,区块链只是一个分布式数据库而已. 不过,使它独一无二的是,区块链是一个公开的数据库,而 ...

  4. php构建一个区块链(含源码)

    php构建一个区块链(含源码) 我们要用PHP编程语言构建区块链,区块链本身就是一个非常简单的概念,它是一个非常简单的数据结构,数字货币是很复杂,但区块链不是,它们复杂的原因是共识算法,挖矿机制和运行 ...

  5. 第三章、Ansible常用模块—新手快速入门

    第三章.Ansible常用模块--新手快速入门 文章目录 一. 查看系统上安装的所有模块 二.ansible常用模块 1.常用模块之–USER 2.常用模块之–shell 3.常用模块之–copy 4 ...

  6. 计算机入门新人必学,异世修真人怎么玩?新手快速入门必备技巧

    异世修真人怎么快速入门?最近新出来的一款文字修仙游戏,很多萌新不知道怎么玩?进小编给大家带来了游戏新手快速入门技巧攻略,希望可以帮到大家. 新手快速入门攻略 1.开局出来往下找婆婆,交互给点钱,旁边有 ...

  7. 如何:从Spring 4.0快速入门以构建简单的REST-Like API(演练)

    如何:从Spring 4.0快速入门以构建简单的REST-Like API(演练) 关于使用Spring MVC创建Web API的另一篇教程. 不太复杂. 只是一个演练. 生成的应用程序将提供简单的 ...

  8. 速卖通新手快速入门手册之一认识物流

    写在帖子之前的话 最近有一大批朋友想做速卖通或者有的刚做速卖通,遇到了不少问题,都来问我,我觉得这个是一个好的趋势,说明跨境电商的市场正在走向成熟,相关配套也会越来越完善.但是也是说明竞争将会前所未有 ...

  9. 计算机代码新手入门教程,VJPAGE微简代码生成器新手快速入门教程

    VJPAGE微简代码生成器新手快速入门教程: 第一步:新建项目 打开主菜单,文件->新建项目,输入项目名称:"我的项目",选择Jquery作为默认框架.单击确定按钮 第二步: ...

最新文章

  1. VM虚拟机报错:An error occurred during the file system check.
  2. java报错MalformedURLException: unknown protocol: c
  3. CTFshow php特性 web95
  4. 学电脑从新手到高手_小白如何学手绘插画?新手到高手必学的四套教程【614期】...
  5. wxWidgets:wxStyledTextCtrl类用法
  6. IT基础结构-1.DC-DNS-安装
  7. python的xpath用法_Python爬虫杂记 - Xpath高级用法
  8. 20145239杜文超 《Java程序设计》第7周学习总结
  9. 2018 ngChina —— “跨平台”版块简介
  10. Db4o数据库:快速入门
  11. zend studio html乱码,解决Eclipse/Zend Studio编辑xml/html乱码问题
  12. 航空三字代码表_目前最全的航空城市三字代码表
  13. 点击click触发两次事件解决办法
  14. larval框架的获取并存储(cache的使用)
  15. 手把手从0开始学会Python爬虫,从大一初学者视角,带你实现爬虫攥写
  16. 幼儿园科学教案计算机,幼儿园大班科学教案_大班科学教案_幼教网
  17. 一个web站点的欢迎页面
  18. 使用Everest和ACPI Patcher轻松生成dsdt.aml
  19. Python 对字典的认知
  20. 【转】暴风影音播放MKV高清电影一快进就卡死的问题

热门文章

  1. 改造Android手机为,便携式linux服务器,跑tomcat
  2. 监控远程log4.net日志
  3. Flask 框架设计模式
  4. 急!!!微信公众号数据迁移后openid无法转换
  5. Git分支的创建,切换及分支指针移动的理解
  6. C学习笔记——(4)数组和字符串说明,以及冒泡排序法
  7. GIS大数据可视化分析工具
  8. 微信摇一摇插件ios_iOS-仿微信摇一摇
  9. 微信摇一摇插件ios_苹果ios微信摇一摇代码实现
  10. 树梅派应用47:用树莓派给智能手机发送推送通知