百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

如何用 Python 撸一个区块链(python blockchain)

toyiye 2024-08-19 01:15 9 浏览 0 评论

相信你和我一样对数字货币的崛起感到新奇,并且想知道其背后的技术——区块链是怎样实现的。

但是理解区块链并非易事,至少对于我来说是如此。晦涩难懂的视频、漏洞百出的教程以及示例的匮乏令我倍受挫折。

我喜欢在实践中学习,通过写代码来学习技术会掌握得更牢固。如果你也这样做,那么读完本文,你将获得一个可用的区块链以及对区块链的深刻理解。

开始之前...

首先你需要知道区块链是由被称为区块的记录构成的不可变的、有序的链式结构,这些记录可以是交易、文件或任何你想要的数据,最重要的是它们是通过 Hash 连接起来的。

如果你不了解 Hash,这里有个例子

其次,你需要安装 Python3.6+,Flask,Request

pip install Flask==0.12.2 requests==2.18.4


同时你还需要一个 HTTP 客户端,比如 Postman,cURL 或任何其它客户端。

最终的源代码在这里:

第一步: 打造一个 Blockchain

新建一个文件 blockchain.py,本文所有的代码都写在这一个文件中。首先创建一个 Blockchain 类,在构造函数中我们创建了两个列表,一个用于储存区块链,一个用于储存交易。

class Blockchain(object):
 def __init__(self):
 self.chain = []
 self.current_transactions = []
 def new_block(self):
 # Creates a new Block and adds it to the chain
 pass
 def new_transaction(self):
 # Adds a new transaction to the list of transactions
 pass
 @staticmethod
 def hash(block):
 # Hashes a Block
 pass
 @property
 def last_block(self):
 # Returns the last Block in the chain
 pass

一个区块有五个基本属性:index,timestamp(in Unix time),transaction 列表,工作量证明(稍后解释)以及前一个区块的 Hash 值。

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

到这里,区块链的概念应该比较清楚了:每个新的区块都会包含上一个区块的 Hash 值。这一点非常关键,它是区块链不可变性的根本保障。如果攻击者破坏了前面的某个区块,那么后面所有区块的 Hash 都会变得不正确。不理解?慢慢消化~

我们需要一个向区块添加交易的方法:

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() 方法向列表中添加一个交易记录,并返回该记录将被添加到的区块——下一个待挖掘的区块——的索引,稍后在用户提交交易时会有用。

当 Blockchain 实例化后,我们需要创建一个初始的区块(创世块),并且给它预设一个工作量证明。

除了添加创世块的代码,我们还需要补充 newblock(), newtransaction() 和 hash() 方法:

import hashlib
import json
from time import time
class Blockchain(object):
 def __init__(self):
 self.current_transactions = []
 self.chain = []
 # Create the genesis block
 self.new_block(previous_hash=1, proof=100)
 def new_block(self, proof, previous_hash=None):
 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):
 self.current_transactions.append({
 'sender': sender,
 'recipient': recipient,
 'amount': amount,
 })
 return self.last_block['index'] + 1
 @property
 def last_block(self):
 return self.chain[-1]
 @staticmethod
 def hash(block):
 block_string = json.dumps(block, sort_keys=True).encode()
 return hashlib.sha256(block_string).hexdigest()

上面的代码应该很直观,我们基本上有了区块链的雏形。但此时你肯定很想知道一个区块究竟是怎样被创建或挖掘出来的。

新的区块来自工作量证明(PoW)算法。PoW 的目标是计算出一个符合特定条件的数字,这个数字对于所有人而言必须在计算上非常困难,但易于验证。这就是工作量证明的核心思想。

举个例子:

假设一个整数 x 乘以另一个整数 y 的积的 Hash 值必须以 0 结尾,即 hash(x * y) = ac23dc...0。设 x = 5,求 y?

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 // hash(5 * 21) = 1253e9373e...5e3600155e860

在比特币中,工作量证明算法被称为 Hashcash,它和上面的问题很相似,只不过计算难度非常大。这就是矿工们为了争夺创建区块的权利而争相计算的问题。通常,计算难度与目标字符串需要满足的特定字符的数量成正比,矿工算出结果后,就会获得一定数量的比特币奖励(通过交易)。

网络要验证结果,当然非常容易。

让我们来实现一个 PoW 算法,和上面的例子非常相似,规则是:寻找一个数 p,使得它与前一个区块的 proof 拼接成的字符串的 Hash 值以 4 个零开头。

import hashlib
import json
from time import time
from uuid import uuid4
class Blockchain(object):
 ...
 def proof_of_work(self, last_proof):
 proof = 0
 while self.valid_proof(last_proof, proof) is False:
 proof += 1
 return proof
 @staticmethod
 def valid_proof(last_proof, proof):
 guess = f'{last_proof}{proof}'.encode()
 guess_hash = hashlib.sha256(guess).hexdigest()
 return guess_hash[:4] == "0000"

衡量算法复杂度的办法是修改零的个数。4 个零足够用于演示了,你会发现哪怕多一个零都会大大增加计算出结果所需的时间。

我们的 Blockchain 基本已经完成了,接下来我们将使用 HTTP requests 来与之交互。

第二步:作为 API 的 Blockchain

我们将使用 Flask 框架,它十分轻量并且很容易将网络请求映射到 Python 函数。

我们将创建三个接口:

/transactions/new 创建一个交易并添加到区块
/mine 告诉服务器去挖掘新的区块
/chain 返回整个区块链

我们的服务器将扮演区块链网络中的一个节点。我们先添加一些常规代码:

import hashlib
import json
from textwrap import dedent
from time import time
from uuid import uuid4
from flask import Flask, jsonify, request
class 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), 200
if __name__ == '__main__':
 app.run(host='127.0.0.1', port=5000)

这是用户发起交易时发送到服务器的请求:

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

我们已经有了向区块添加交易的方法,因此剩下的部分就很简单了:

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

挖掘端正是奇迹发生的地方,它只做三件事:计算 PoW;通过新增一个交易授予矿工一定数量的比特币;构造新的区块并将其添加到区块链中。

@app.route('/mine', methods=['GET'])
def mine():
 # We run the proof of work algorithm to get the next proof...
 last_block = blockchain.last_block
 last_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 chain
 block = blockchain.new_block(proof)
 response = {
 'message': "New Block Forged",
 'index': block['index'],
 'transactions': block['transactions'],
 'proof': block['proof'],
 'previous_hash': block['previous_hash'],
 }
 return jsonify(response), 200

需注意交易的接收者是我们自己的服务器节点,目前我们做的大部分事情都只是围绕 Blockchain 类进行交互。到此,我们的区块链就算完成了。

第三步:交互演示

使用 Postman 演示,略。

第四步:一致性

这真的很棒,我们已经有了一个基本的区块链可以添加交易和挖矿。但是,整个区块链系统必须是分布式的。既然是分布式的,那么我们究竟拿什么保证所有节点运行在同一条链上呢?这就是一致性问题,我们要想在网络中添加新的节点,就必须实现保证一致性的算法。

在实现一致性算法之前,我们需要找到一种方式让一个节点知道它相邻的节点。每个节点都需要保存一份包含网络中其它节点的记录。让我们新增几个接口:

1. /nodes/register 接收以 URL 的形式表示的新节点的列表
2. /nodes/resolve 用于执行一致性算法,用于解决任何冲突,确保节点拥有正确的链
...
from urllib.parse import urlparse
...
class Blockchain(object):
 def __init__(self):
 ...
 self.nodes = set()
 ...
 def register_node(self, address):
 parsed_url = urlparse(address)
 self.nodes.add(parsed_url.netloc)

注意到我们用 set 来储存节点,这是一种避免重复添加节点的简便方法。

前面提到的冲突是指不同的节点拥有的链存在差异,要解决这个问题,我们规定最长的合规的链就是最有效的链,换句话说,只有最长且合规的链才是实际存在的链。

让我们再添加两个方法,一个用于添加相邻节点,另一个用于解决冲突。

...
import requests
class Blockchain(object)
 ...
 def valid_chain(self, chain):
 last_block = chain[0]
 current_index = 1
 while current_index < len(chain):
 block = chain[current_index]
 print(f'{last_block}')
 print(f'{block}')
 print("-----------")
 # Check that the hash of the block is correct
 if block['previous_hash'] != self.hash(last_block):
 return False
 # Check that the Proof of Work is correct
 if not self.valid_proof(last_block['proof'], block['proof']):
 return False
 last_block = block
 current_index += 1
 return True
 def resolve_conflicts(self):
 neighbours = self.nodes
 new_chain = None
 # We're only looking for chains longer than ours
 max_length = len(self.chain)
 # Grab and verify the chains from all the nodes in our network
 for 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 valid
 if length > max_length and self.valid_chain(chain):
 max_length = length
 new_chain = chain
 # Replace our chain if we discovered a new, valid chain longer than ours
 if new_chain:
 self.chain = new_chain
 return True
 return False

现在你可以新开一台机器,或者在本机上开启不同的网络接口来模拟多节点的网络,或者邀请一些朋友一起来测试你的区块链。

我希望本文能激励你创造更多新东西。我之所以对数字货币入迷,是因为我相信区块链会很快改变我们看待事物的方式,包括经济、政府、档案管理等。

相关推荐

# Python 3 # Python 3字典Dictionary(1)

Python3字典字典是另一种可变容器模型,且可存储任意类型对象。字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中,格式如...

Python第八课:数据类型中的字典及其函数与方法

Python3字典字典是另一种可变容器模型,且可存储任意类型对象。字典的每个键值...

Python中字典详解(python 中字典)

字典是Python中使用键进行索引的重要数据结构。它们是无序的项序列(键值对),这意味着顺序不被保留。键是不可变的。与列表一样,字典的值可以保存异构数据,即整数、浮点、字符串、NaN、布尔值、列表、数...

Python3.9又更新了:dict内置新功能,正式版十月见面

机器之心报道参与:一鸣、JaminPython3.8的热乎劲还没过去,Python就又双叒叕要更新了。近日,3.9版本的第四个alpha版已经开源。从文档中,我们可以看到官方透露的对dic...

Python3 基本数据类型详解(python三种基本数据类型)

文章来源:加米谷大数据Python中的变量不需要声明。每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。在Python中,变量就是变量,它没有类型,我们所说的"类型"是变...

一文掌握Python的字典(python字典用法大全)

字典是Python中最强大、最灵活的内置数据结构之一。它们允许存储键值对,从而实现高效的数据检索、操作和组织。本文深入探讨了字典,涵盖了它们的创建、操作和高级用法,以帮助中级Python开发...

超级完整|Python字典详解(python字典的方法或操作)

一、字典概述01字典的格式Python字典是一种可变容器模型,且可存储任意类型对象,如字符串、数字、元组等其他容器模型。字典的每个键值key=>value对用冒号:分割,每个对之间用逗号,...

Python3.9版本新特性:字典合并操作的详细解读

处于测试阶段的Python3.9版本中有一个新特性:我们在使用Python字典时,将能够编写出更可读、更紧凑的代码啦!Python版本你现在使用哪种版本的Python?3.7分?3.5分?还是2.7...

python 自学,字典3(一些例子)(python字典有哪些基本操作)

例子11;如何批量复制字典里的内容2;如何批量修改字典的内容3;如何批量修改字典里某些指定的内容...

Python3.9中的字典合并和更新,几乎影响了所有Python程序员

全文共2837字,预计学习时长9分钟Python3.9正在积极开发,并计划于今年10月发布。2月26日,开发团队发布了alpha4版本。该版本引入了新的合并(|)和更新(|=)运算符,这个新特性几乎...

Python3大字典:《Python3自学速查手册.pdf》限时下载中

最近有人会想了,2022了,想学Python晚不晚,学习python有前途吗?IT行业行业薪资高,发展前景好,是很多求职群里严重的香饽饽,而要进入这个高薪行业,也不是那么轻而易举的,拿信工专业的大学生...

python学习——字典(python字典基本操作)

字典Python的字典数据类型是基于hash散列算法实现的,采用键值对(key:value)的形式,根据key的值计算value的地址,具有非常快的查取和插入速度。但它是无序的,包含的元素个数不限,值...

324页清华教授撰写【Python 3 菜鸟查询手册】火了,小白入门字典

如何入门学习python...

Python3.9中的字典合并和更新,了解一下

全文共2837字,预计学习时长9分钟Python3.9正在积极开发,并计划于今年10月发布。2月26日,开发团队发布了alpha4版本。该版本引入了新的合并(|)和更新(|=)运算符,这个新特性几乎...

python3基础之字典(python中字典的基本操作)

字典和列表一样,也是python内置的一种数据结构。字典的结构如下图:列表用中括号[]把元素包起来,而字典是用大括号{}把元素包起来,只不过字典的每一个元素都包含键和值两部分。键和值是一一对应的...

取消回复欢迎 发表评论:

请填写验证码