在數字貨幣盛行的檔口,比特幣,這幣那幣到底值不值得信賴呢。也許你像很多人一樣感到新奇,想接近它,但只因背後的區塊鏈技術,阻斷了向新領域嘗試的步伐。不過,對於程式員來說,想真正搞懂比特幣,搞懂區塊鏈,可不是難題,因為他們能邊玩邊學,通過一行行pyhton代碼,就能真正理解數字貨幣的底層秘密。能用這麼有逼格的方式來學習區塊鏈的,也只有程式員了。
作者 | Daniel van Flymen 紐約區塊鏈工程師
譯者 | 熊麗兵 牛娃軟體CTO
準備工作
本文要求讀者對Python有基本的理解,能讀寫基本的Python,並且需要對HTTP請求有基本的瞭解。
我們知道區塊鏈是由區塊的記錄構成的不可變、有序的鏈結構,記錄可以是交易、檔案或任何你想要的資料,重要的是它們是通過雜湊值(hashes)連結起來的。
如果你還不是很瞭解雜湊,可以查看這篇文章https://learncryptography.com/hash-functions/what-are-hash-functions
環境準備
環境準備,確保已經安裝Python3.6+, pip , Flask, requests
安裝方法:
pip install Flask==0.12.2 requests==2.18.4
同時還需要一個HTTP用戶端,比如Postman,cURL或其它用戶端。
參考原始碼(原代碼在我翻譯的時候,無法運行,我fork了一份,修複了其中的錯誤,並添加了翻譯,感謝star)
開始建立Blockchain
建立一個檔案 blockchain.py,本文所有的代碼都寫在這一個檔案中,可以隨時參考原始碼。
Blockchain類
首先建立一個Blockchain類,在建構函式中建立了兩個列表,一個用於儲存區塊鏈,一個用於儲存交易。
以下是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類用來管理鏈條,它能儲存體交易,加入新塊等,下面我們來進一步完善這些方法。
塊結構
每個區塊包含屬性:索引(index),Unix時間戳記(timestamp),交易列表(transactions),工作量證明(稍後解釋)以及前一個區塊的Hash值。
以下是一個區塊的結構:
block = {
'index': 1,
'timestamp': 1506057125.900785,
'transactions': [
{
'sender': "8527147fe1f5426f9dd545de4b27ee00",
'recipient': "a77f5cdfa2934df3954a5c7c7da5df1f",
'amount': 5,
}
],
'proof': 324984774000,
'previous_hash': "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
}
到這裡,區塊鏈的概念就清楚了,每個新的區塊都包含上一個區塊的Hash,這是關鍵的一點,它保障了區塊鏈不可變性。如果攻擊者破壞了前面的某個區塊,那麼後面所有區塊的Hash都會變得不正確。不理解的話,慢慢消化,可參考{% post_link whatbc 區塊鏈技術原理 %}
加入交易
接下來我們需要添加一個交易,來完善下new_transaction方法
class Blockchain(object):
...
def new_transaction(self, sender, recipient, amount):
"""
產生新交易資訊,資訊將加入到下一個待挖的區塊中
: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
方法向列表中添加一個交易記錄,並返回該記錄將被添加到的區塊(下一個待挖掘的區塊)的索引,等下在使用者提交交易時會有用。
建立新塊
當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):
"""
產生新塊
: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):
"""
產生新交易資訊,資訊將加入到下一個待挖的區塊中
: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({