如果您想学习如何构建区块链,那么您来对地方了。让我们深入了解如何在 python 中构建区块链

有大量关于区块链的文章,但并非所有文章都谈论从头开始构建区块链。作为开发者,理论固然重要,但你也需要创建一个区块链来完全理解其背后的概念。

区块链背后的核心思想是其去中心化的性质。你会被它内部如何运作的事实所吸引。区块链可能听起来很简单,但里面有很多协议和算法可以实现它。我们将使用 Python 从头开始​​创建区块链。

您还可以保存文章并将其添加为“如何构建我们的区块链”的书签。相信我; 从长远来看,这篇文章将对您有所帮助。

如何构建区块链

学习任何事情的最好方法是边做边学。为确保您与我在同一页面上,让我们先检查一下要求。我们还将简要描述区块链,以便我们都在同一页面上。

如何在 Python 中构建区块链

要求

遵循指南的基本要求是知道如何编码。如果您一生中从未编写过代码,那么本指南不适合您。我建议查看在线提供的各种初级课程。我推荐 EdX、Udacity 和 Coursera,以获得最佳学习体验。

你已经是编码员了?然后,您应该了解基本的 Python。此外,它将帮助您遵循“如何构建区块链”教程。

我们创建了教程,因此任何人都可以学习。所以,如果您不知道并且想学习如何从头开始构建区块链,欢迎您这样做!

 如果您不了解 Python,请不要担心,因为它很容易上手。查看Python 文档以开始使用。

我们将在本教程中使用 Python 3.6+。如果您决定使用其他版本的 Python,那么您可能需要进行更多研究才能使代码正常工作。出于教程目的,我建议安装我正在使用的版本。

最后,您还应该了解 HTTP——用于在 Internet 上的两方之间进行通信的协议。

使用 pip 安装 Python

您需要使用 pip 安装 Python。您还需要安装精彩的 Requests 和 Flask 库。为此,只需运行以下命令。

$pip install Flask==0.12.2 requests==2.18.4

如果你使用的是Windows环境,可以直接去python.org下载最新版本的Python。

至于我,我下载了 Python 3.8.1 — 编写本教程时的最新版本。

对于 IDE,我更喜欢使用 PyCharm。我在本教程中使用 Python 社区版。您可以自由使用您选择的任何 IDE。另一个不错的选择是 Visual Studio Code——一个免费的开源集成开发环境。

您将需要的最后一个工具是 Postman——一个 HTTP 客户端。或者,您也可以使用 cURL。

我还建议安装一个虚拟环境来为您的开发创建一个完全不同的环境。您可以按照本指南进行正确设置。

重访区块链

在我们开始构建区块链之前,我们需要刷新我们对区块链的想法。这将帮助我们保持在同一页面上。

区块链是一种分布式账本技术  ,同行可以参与、交互和执行交易,而无需集中实体。每个对等点都有一份账本副本,这使得黑客无法在系统中进行欺诈。区块链的主要特征包括透明性、不变性和安全性。它利用先进的加密货币算法来确保数据安全。此外,为了达成共识,区块链网络将利用工作量证明、股权证明等共识算法

开始构建区块链

完成所有先决条件安装后,我们现在准备开始我们的教程“如何构建区块链”。

首先,您需要创建一个 blockchain.py 文件。

1. 区块链创建

第一步是制作功能性区块链解决方案。首先,我们需要创建一个区块链类。在那里,我们将创建一个构造函数来启动链和交易列表。链表将存储我们的区块链,而交易将存储在 current_transactions 数组中。

def __init__(self):
self.chain = []
self.current_transactions = []

接下来,我们需要创建一个 new_block 函数,该函数将用于创建新块,然后将它们添加到现有链中。new_block 函数的代码如下:

def new_block(self):
#This function creates new blocks and then adds to the existing chain
pass

new_transcaction 方法将创建一个新事务,然后将该事务添加到已经存在的事务列表中。

def new_transaction(self):
#This function adds a new transaction to already existing transactions
pass

We also have a hash function that is used to create the hash for a block.

@staticmethod
def hash(block):
#Used for hashing a block

我们要创建 last_block 的最后一个函数。它用于调用链中的最后一个块。

我们还可以在这里创建另外三个函数。

  • register_node() → 注册一个新节点并将其添加到网络中
  • valid_proof() → 将确保向链提交的块是否能解决问题
  • valid_chain() → 这将检查链中的后续块是否有效。

blockchain.py 的蓝图如下所示。

class Blockchain(object):
def __init__(self):
self.chain = []
self.current_transactions = []
def new_block(self):
#This function creates new blocks and then adds to the existing chain
pass
def new_transaction(self):
#This function adds a new transaction to already existing transactions
pass
@staticmethod
def hash(block):
#Used for hashing a block
@property
def last_block(self):
# Calls and returns the last block of the chain
pass

Blockchain 类管理整个链。类下定义的定义管理区块链中的不同操作。

让我们逐一介绍以下方法。

块的结构

一个块包含有关交易和链的重要信息。链上的任何块都将包含以下信息

  • 指数
  • Unix 时间的时间戳
  • 交易清单
  • 证明
  • 上一个区块哈希

块中的大部分信息都是不言自明的。这里,两个关键变量是previous_hash,它包含了前一个区块的哈希值。这很重要,因为它确保了区块链是不可变的,并且没有恶意行为者可以更新、删除或添加任何数据到链中。

将事务添加到块

了解了区块的结构后,现在让我们学习如何将交易添加到区块中。它的代码如下。

def new_transaction(self):
#This function adds a new transaction to already existing transactions
“””This will create a new transaction which will be sent to the next block. It will contain
three variables including sender, recipient and amount
“””
self.current_transactions.append(
{
‘sender’: sender,
‘recipient’: recipient
‘amount’: amount,
}
)
return self.last_block[‘index’] + 1

As you can see, it simply appends the current_transaction list with an object that contains three variables → sender, recipient, amount.

添加完成后,该方法将块索引发送到链。这是将要开采的下一个区块。

创建新块

在我们开始创建新块之前,我们需要创建创世块。为此,我们需要使用如下简单的代码行。

self.new_block(previous_hash=1, proof=100)复制

此行应添加到您的 Blockchain 类中。

对于 new_block() 方法,您需要发送两个变量作为其参数。它包括证明和previous_hash。

现在,让我们看看下面的 new_block() 方法。

def new_block(self, proof, previous_hash=None):
#This function creates new blocks and then adds to the existing chain
“””This method will contain two parameters proof, previous hash”””
block = {
‘index’: len(self.chain) + 1,
‘timestamp’ : time(),
‘proof’: proof,
previous_hash: previous_hash or self.hash(self.chain[-1]),
}

# 设置当前事务列表为空。

self.current_transactions=[]
self.chain.append(block)
return block

让我们解释一下new_block的代码。我们创建一个包含三个重要参数的阻止列表。一旦它们被定义,我们还编写代码来重置 current_transaction 列表,然后将块附加到链中。new_block 方法在调用时返回块。

让我们在下面定义 last_block 方法。

def hash(block):
#Used for hashing a block
“””The follow code will create a SHA-256 block hash and also ensure that the dictionary is ordered”””
block_string = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()

If you combine all the code until now, we will have the following blockchain.py. Check it below.

class Blockchain(object):
def __init__(self):
self.chain = []
self.current_transactions = []
self.new_block(previous_hash=1, proof=100)
def new_block(self, proof, previous_hash=None):
#This function creates new blocks and then adds to the existing chain
“””This method will contain two parameters proof, previous hash”””
block = {
‘index’: len(self.chain) + 1,
‘timestamp’ : time(),
‘proof’: proof,
previous_hash: previous_hash or self.hash(self.chain[-1]),
}
# Set the current transaction list to empty.
self.current_transactions=[]
self.chain.append(block)
return block
def new_transaction(self):
#This function adds a new transaction to already existing transactions
“””This will create a new transaction which will be sent to the next block. It will contain
three variables including sender, recipient and amount
“””
self.current_transactions.append(
{
‘sender’: sender,
‘recipient’: recipient,
‘amount’: amount,
}
)
return self.last_block[‘index’] + 1
@staticmethod
def hash(block):
#Used for hashing a block
“””The follow code will create a SHA-256 block hash and also ensure that the dictionary is ordered”””
block_string = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
@property
def last_block(self):
# Calls and returns the last block of the chain
return self.chain[-1]

工作证明实施

我们构建 blockchain.py 的下一步是工作量证明的实现。

那么,什么是工作量证明?它是一种共识方法,用于将新块添加到链中。它对矿工提出了挑战,一旦矿工解决了问题,区块就会被验证。作为回报,矿工会根据问题的复杂性获得奖励。

比特币的工作量证明被称为 Hashcash。它确保比特币网络共识按预期工作。

让我们定义 proof_of_work() 方法。该方法将成为 Blockchain 类的一部分。

def proof_of_work(self, last_proof):
“””This method is where you the consensus algorithm is implemented.
It takes two parameters including self and last_proof”””
proof = 0
while self.valid_proof(last_proof, proof) is False:
proof +=1
return proof
@staticmethod
def valid_proof(last_proof, proof):
“””This method validates the block”””
guess = f'{last_proof}{proof}’.encode()
guess_hash = hashlib.sha256(guess).hexigest()
return guess_hash[:4] == “0000”

第一种 proof_of_work 方法很简单;它只是将证明设置为 0,然后运行一个 while 循环来运行 valid_proof 方法。如果是 False,则在证明中加一。

您可以通过添加更多零来增加哈希的难度。

这导致我们结束我们的 Blockchain.py。我们的代码如下所示。

class Blockchain(object):
def __init__(self):
self.chain = []
self.current_transactions = []
self.new_block(previous_hash=1, proof=100)

def proof_of_work(self, last_proof):
“””This method is where you the consensus algorithm is implemented.
It takes two parameters including self and last_proof”””
proof = 0
while self.valid_proof(last_proof, proof) is False:
proof +=1
return proof
@staticmethod
def valid_proof(last_proof, proof):
“””This method validates the block”””
guess = f'{last_proof}{proof}’.encode()
guess_hash = hashlib.sha256(guess).hexigest()
return guess_hash[:4] == “0000”
def new_block(self, proof, previous_hash=None):
#This function creates new blocks and then adds to the existing chain
“””This method will contain two parameters proof, previous hash”””
block = {
‘index’: len(self.chain) + 1,
‘timestamp’ : time(),
‘proof’: proof,
previous_hash: previous_hash or self.hash(self.chain[-1]),
}
# Set the current transaction list to empty.
self.current_transactions=[]
self.chain.append(block)
return block
def new_transaction(self):
#This function adds a new transaction to already existing transactions
“””This will create a new transaction which will be sent to the next block. It will contain
three variables including sender, recipient and amount
“””
self.current_transactions.append(
{
‘sender’: sender,
‘recipient’: recipient,
‘amount’: amount,
}
)

return self.last_block[‘index’] + 1

@staticmethod

def hash(block):

#Used for hashing a block

“””The follow code will create a SHA-256 block hash and also ensure that the dictionary is ordered”””

block_string = json.dumps(block, sort_keys=True).encode()

return hashlib.sha256(block_string).hexdigest()

@property

def last_block(self):

# Calls and returns the last block of the chain

return self.chain[-1]

2. API 集成

太好了,我们创建了一个有效的区块链!现在,为了有效地使用它,我们需要创建一个 API(应用程序编程接口)。

为此,我们将使用流行的 Python 框架:Flask。

Flask 是一个微型框架,这意味着它是轻量级的,你可以添加你需要的库。它还使您能够轻松创建 Python 函数端点。

要创建 API,我们首先需要确保我们的区块链可以接受 HTTP 请求。为此,我们必须创建更多方法。

现在,我们将修改 blockchain.py。

# Creating the app node
app = Flask(__name__)
node_identifier = str(uuid4()).replace(‘-‘,”)
# Initializing blockchain
blockchain = Blockchain()
@app.route(‘/mine’, methods=[‘GET’])
def mine():
return “Mining a new Block”
@app.route(‘/transactions/new’, methods=[‘POST’])
def new_transaction():
return “Adding a new transaction”
@app.router(‘/chain’, methods=[‘GET’])
def full_chain():
response = {
‘chain’ : blockchain.chain,
‘length’ : len(blockchain.chain)
}
return jsonify(response), 200
if __name__ == ‘__main__’:
app.run(host=”0.0.0.0″, port=5000)

该代码在很大程度上是不言自明的。我们首先做一个节点初始化。接下来,我们创建一个随机节点。完成后,我们将初始化我们的区块链类。完成后,我们需要创建三个端点,如下所示。

  • /我的端点
  • /transactions/新端点
  • /chain 端点

最后,我们在 5000 端口上运行服务器。

该应用程序现在几乎已创建。我们需要做的就是创建事务类方法。

@app.route(‘/transactions/new’, methods=[‘POST’])
def new_transaction():
values = request.get_json()
# Checking if the required data is there or not
required = [‘sender’,’recipient’,’amount’]
if not all(k in values for k in required):
return ‘Missing values’, 400
# creating a new transaction
index = blockchain.new_transaction(values[‘sender’], values[‘recipient’, values[‘amount’]])
response = {‘message’: f’Transaction is scheduled to be added to Block No. {index}’}
return jsonify(response), 201

挖矿端点

我们要创建的最后一个端点是挖掘端点。为此,我们必须确保它完成以下三件事。

  • 工作证明计算
  • 锻造新的区块链,然后将其添加到链中
  • 奖励矿工的工作

@app.route(‘/mine’, methods=[‘GET’])
def mine():
“””Here we make the proof of work algorithm work”””
last_block = blockchain.last_block
last_proof = last_block[‘proof’]
proof = blockchain.proof_of_work(last_proof)
# rewarding the miner for his contribution. 0 specifies new coin has been mined
blockchain.new_transaction(
sender=”0″,
recipient = node_identifier,
amount = 1,
)
# now create the new block and add it to the chain
previous_hash = blockchain.hash(last_block)
block = blockchain.new_block(proof, previous_hash)
response = {
‘message’: ‘The new block has been forged’,
‘index’: block[‘index’],
‘transactions’: block[‘transactions’],
‘proof’: block[‘proof’],
‘previous_hash’ : block[‘previous_hash’]
}
return jsonify(response), 200

3. 区块链交互

最后一步是与区块链交互。我们将使用 Postman 使用我们刚刚创建的 API 与区块链网络进行交互。

在 Python 控制台上运行以下代码

python blockchain.py

结论

这导致我们结束了如何构建区块链。希望上面的步骤和代码能帮助您在 Python 中构建区块链。

发表回复

后才能评论