時間:2023-06-16|瀏覽:235
小編:記得 來源:幣成小助手
“學(xué)習(xí)區(qū)塊鏈的最快方法就是自己親手搭建一個”
如果您已經(jīng)掌握了一些基礎(chǔ)的python知識,那么跟著本文搭建區(qū)塊鏈對您來說將不是一件難事兒。
在開始之前,有一些概念需要您先明確:
1.區(qū)塊鏈?zhǔn)且粋€不變的順序記錄鏈,稱為塊。它們可以包含事務(wù),文件或任何您想要記錄的數(shù)據(jù)。您只需記住,它們使用哈希值鏈接在一起。
2.哈希函數(shù)就是一個簡單的函數(shù),它接受輸入值,并根據(jù)該輸入創(chuàng)建確定輸入值的輸出值。對于任何x輸入值,只要運(yùn)行哈希函數(shù),您將始終收到相同的y輸出值。這樣,每個輸入都有一個確定的輸出。哈希函數(shù)通常是不可逆的(單向),這意味著僅知道輸出就無法弄清楚輸入-除非嘗試所有可能的輸入(也稱為暴力破解)。
這是哈希函數(shù)md5,可從任何輸入數(shù)據(jù)創(chuàng)建一個32個字符的十六進(jìn)制輸出
掌握了區(qū)塊,哈希等基本概念之后,您還需要為搭建區(qū)塊鏈做一些環(huán)境準(zhǔn)備工作:請您確保您的電腦已安裝Python3.6以上(以及pip)、Flask和Requests庫。
pip install Flask==0.12.2 requests==2.18.4
Step1:搭建區(qū)塊鏈?
打開你最喜歡的文本編輯器或IDE,推薦使用PyCharm;創(chuàng)建一個新文件,名為blockchain.py
創(chuàng)建一個Blockchain類,創(chuàng)建兩個初始的空列表一個用于存儲我們的區(qū)塊鏈,另一個用于存儲交易。
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
這個區(qū)塊鏈類負(fù)責(zé)管理鏈。,它存儲事務(wù),并具有一些用于將新塊添加到鏈中的輔助方法。
“Block到底長什么樣?”
每個Block都有一個索引index,一個時間戳timestamp(以Unix時間表示),一個事務(wù)列表,一個proof證明(稍后會有更多介紹)以及前一個塊的哈希值。如下面代碼所示:
block={ "index": 1, "timestamp": 1506057125.900785, "transactions": [ { "sender": "8527147fe1f5426f9dd545de4b27ee00", "recipient": "a77f5cdfa2934df3954a5c7c7da5df1f", "amount": 5, } ], "proof": 324984774000, "previous_hash": "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" }
此時鏈的概念應(yīng)該很明顯了:每個新塊本身都包含前一個塊的哈希。這很關(guān)鍵,因為這使區(qū)塊鏈具有不變性,即:如果攻擊者破壞了鏈中較早的區(qū)塊,則所有后續(xù)區(qū)塊都將包含不正確的哈希。
“將交易添加到區(qū)塊”
創(chuàng)建一個new_transaction方法,將交易添加到區(qū)塊:
class Blockchain(object): ...
def new_transaction(self, sender, recipient, amount): """ Creates a new transaction to go into the next mined Block :param sender: :param recipient: :param amount: :return: """ self.current_transactions.append({ 'sender': sender, 'recipient': recipient, 'amount': amount, }) return self.last_block['index'] + 1
在new_transaction將事務(wù)添加到列表之后,它將返回要添加該事務(wù)的塊的索引:即下一個要挖掘的塊。這對于提交事務(wù)的用戶很有用。
“創(chuàng)建一個新區(qū)塊”
實例化我們的區(qū)塊鏈時,我們需要使用創(chuàng)世區(qū)塊(就是前面沒有任何區(qū)塊)。
我們還需要在創(chuàng)世區(qū)塊中添加“證明”,這是挖礦(或工作量證明ProofofWork)的結(jié)果。關(guān)于Pow可以參考我之前寫過的文章:金融小課堂|加密貨幣一級市場概述(上)。
除了在構(gòu)造函數(shù)中創(chuàng)建創(chuàng)世區(qū)塊之外,我們還需要實例化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: 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: @property
def last_block(self):
return self.chain[-1] @staticmethod
def hash(block):
"""
Creates a SHA-256 hash of a Block
:param block: # 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() 這樣一個簡單的區(qū)塊鏈就大功告成了。 如果您會好奇更深層的問題,比如如何創(chuàng)建,