構建區塊鏈
前言
小編認爲學習區塊鏈如何工作的最快方法是建立一個區塊鏈。雖然網上有很多教程或視頻,小編也一一瀏覽過,但是覺得那些示例效果…小編喜歡邊做邊學,小編希望在看過這篇文章之後您將擁有一個運行正常的區塊鏈,並對它們的工作原理有紮實的瞭解。
請記住!!!區塊鏈是一個不變的順序記錄鏈,稱爲塊。它們可以包含事務,文件或您真正喜歡的任何數據。但是重要的是,它們使用哈希值鏈接在一起。
前期準備
pip install Flask==0.12.2 requests==2.18.4
開始流程
步驟1:建立區塊鏈
打開你最喜歡的文本編輯器或IDE,我個人❤️ PyCharm。創建一個新文件,名爲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
Blockchain類負責管理鏈。它將存儲事務,並具有一些用於將新塊添加到鏈中的輔助方法。
塊看起來像什麼?
每個Block都有一個索引,一個時間戳(以Unix時間表示),一個事務列表,一個證明以及前一個Block的哈希值。
這是單個塊的外觀示例:
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()將交易添加到列表中,它返回交易將添加到的區塊的索引給下一個要開採的區塊。以後,這對於提交事務的用戶很有用。
創建新塊
當我們的 Blockchain實例化後,我們需要使用創世塊(沒有前任的塊)爲它播種。我們還需要向我們的創始區塊添加“證明”,這是挖掘(或工作證明)的結果。除了在我們的構造函數中創建的塊之外,我們還將充實用於new_block(), new_transaction() 和 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):
"""
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 transactions
self.current_transactions = []
self.chain.append(block)
return block
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
@property
def last_block(self):
return self.chain[-1]
@staticmethod
def 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 hashes
block_string = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
代表區塊鏈幾乎完成了。但是在這一點上,您一點想知道如何創建,開採新塊。
瞭解工作量證明
工作量證明算法(PoW)是在區塊鏈上創建或挖掘新區塊的方式。PoW的目標是發現可以解決問題的數字。從數字上來說, 該數字必須很難找到,但要易於被網絡上的任何人驗證。這是工作量證明的核心思想。
我們將看一個非常簡單的示例來幫助解決這個問題。
讓我們決定某個整數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。而且與我們上面的基本示例並沒有太大不同。這是礦工競相解決以創建新區塊的算法。通常,難度由字符串中搜索的字符數決定。然後,通過在交易中獲得硬幣,礦工將獲得獎勵,以獎勵他們的解決方案。
實施基本的工作證明
讓我們爲區塊鏈實現類似的算法。我們的規則將類似於上面的示例:
找出一個數字 p ,該數字與前一個塊的解決方案進行哈希運算時,會導致4個前導0被生產。
import hashlib
import json
from time import time
from uuid import uuid4
class 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 = 0
while self.valid_proof(last_proof, proof) is False:
proof += 1
return proof
@staticmethod
def 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就足夠了。您會發現,添加單個前導零將使找到解決方案所需的時間產生巨大差異。