• <fieldset id="8imwq"><menu id="8imwq"></menu></fieldset>
  • <bdo id="8imwq"><input id="8imwq"></input></bdo>
    最新文章專題視頻專題問答1問答10問答100問答1000問答2000關(guān)鍵字專題1關(guān)鍵字專題50關(guān)鍵字專題500關(guān)鍵字專題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關(guān)鍵字專題關(guān)鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
    問答文章1 問答文章501 問答文章1001 問答文章1501 問答文章2001 問答文章2501 問答文章3001 問答文章3501 問答文章4001 問答文章4501 問答文章5001 問答文章5501 問答文章6001 問答文章6501 問答文章7001 問答文章7501 問答文章8001 問答文章8501 問答文章9001 問答文章9501
    當(dāng)前位置: 首頁 - 科技 - 知識百科 - 正文

    使用Python 搭建自己的區(qū)塊鏈

    來源:懂視網(wǎng) 責(zé)編:小采 時間:2020-11-02 18:25:24
    文檔

    使用Python 搭建自己的區(qū)塊鏈

    使用Python 搭建自己的區(qū)塊鏈:【相關(guān)學(xué)習(xí)推薦:python教程】你是否會和我一樣,對加密數(shù)字貨幣底層的區(qū)塊鏈技術(shù)非常感興趣,特別想了解他們的運行機制。但是學(xué)習(xí)區(qū)塊鏈技術(shù)并非一帆風(fēng)順,我看多了大量的視頻教程還有各種課程,最終的感覺就是真正可用的實戰(zhàn)課程太少。我喜歡在實踐中學(xué)習(xí),
    推薦度:
    導(dǎo)讀使用Python 搭建自己的區(qū)塊鏈:【相關(guān)學(xué)習(xí)推薦:python教程】你是否會和我一樣,對加密數(shù)字貨幣底層的區(qū)塊鏈技術(shù)非常感興趣,特別想了解他們的運行機制。但是學(xué)習(xí)區(qū)塊鏈技術(shù)并非一帆風(fēng)順,我看多了大量的視頻教程還有各種課程,最終的感覺就是真正可用的實戰(zhàn)課程太少。我喜歡在實踐中學(xué)習(xí),

    【相關(guān)學(xué)習(xí)推薦:python教程】

    你是否會和我一樣,對加密數(shù)字貨幣底層的區(qū)塊鏈技術(shù)非常感興趣,特別想了解他們的運行機制。

    但是學(xué)習(xí)區(qū)塊鏈技術(shù)并非一帆風(fēng)順,我看多了大量的視頻教程還有各種課程,最終的感覺就是真正可用的實戰(zhàn)課程太少。

    我喜歡在實踐中學(xué)習(xí),尤其喜歡一代碼為基礎(chǔ)去了解整個工作機制。如果你我一樣喜歡這種學(xué)習(xí)方式,當(dāng)你學(xué)完本教程時,你將會知道區(qū)塊鏈技術(shù)是如何工作的。

    寫在開始之前

    記住,區(qū)塊鏈?zhǔn)且粋€ 不可變的、有序的 被稱為塊的記錄鏈。它們可以包含交易、文件或任何您喜歡的數(shù)據(jù)。但重要的是,他們用哈希 一起被鏈接在一起。

    如果你不熟悉哈希,這里是一個解釋。

    該指南的目的是什么?

    你可以舒服地閱讀和編寫基礎(chǔ)的 Python,因為我們將通過 HTTP 與區(qū)塊鏈進行討論,所以你也要了解 HTTP 的工作原理。

    我需要準(zhǔn)備什么?

    確定安裝了 Python 3.6 + (還有 pip) ,你還需要安裝 Flask、 Requests 庫:

     pip install Flask==0.12.2 requests==2.18.4

    對了, 你還需要一個支持HTTP的客戶端, 比如 Postman 或者 cURL,其他也可以。

    源碼在哪兒?
    可以點擊這里

    Step 1: 創(chuàng)建一個區(qū)塊鏈

    打開你最喜歡的文本編輯器或者IDE, 我個人比較喜歡 PyCharm. 新建一個名為blockchain.py的文件。 我們將只用這一個文件就可以。但是如果你還是不太清楚, 你也可以參考 源碼.

    描述區(qū)塊鏈

    我們要創(chuàng)建一個 Blockchain 類 ,他的構(gòu)造函數(shù)創(chuàng)建了一個初始化的空列表(要存儲我們的區(qū)塊鏈),并且另一個存儲交易。下面是我們這個類的實例:

    blockchain.py

    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 類負(fù)責(zé)管理鏈?zhǔn)綌?shù)據(jù),它會存儲交易并且還有添加新的區(qū)塊到鏈?zhǔn)綌?shù)據(jù)的Method。讓我們開始擴充更多Method。

    塊是什么樣的 ?

    每個塊都有一個 索引,一個 時間戳(Unix時間戳),一個事務(wù)列表, 一個 校驗(稍后詳述) 和 前一個塊的散列

    下面是一個Block的例子 :

    blockchain.py

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

    在這一點上,一個 區(qū)塊鏈 的概念應(yīng)該是明顯的 - 每個新塊都包含在其內(nèi)的前一個塊的 散列 。 這是至關(guān)重要的,因為這是 區(qū)塊鏈 不可改變的原因:如果攻擊者損壞 區(qū)塊鏈 中較早的塊,則所有后續(xù)塊將包含不正確的哈希值。

    這有道理嗎? 如果你還沒有想通,花點時間仔細(xì)思考一下 - 這是區(qū)塊鏈背后的核心理念。

    添加交易到區(qū)塊

    我們將需要一個添加交易到區(qū)塊的方式。我們的 new_transaction() 方法的責(zé)任就是這個, 并且它非常的簡單:

    blockchain.py

    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() 方法添加了交易到列表,它返回了交易將被添加到的區(qū)塊的索引---講開采下一個這對稍后對提交交易的用戶有用。

    創(chuàng)建新的區(qū)塊

    當(dāng)我們的 Blockchain 被實例化后,我們需要將 創(chuàng)世 區(qū)塊(一個沒有前導(dǎo)區(qū)塊的區(qū)塊)添加進去進去。我們還需要向我們的起源塊添加一個 證明,這是挖礦的結(jié)果(或工作證明)。 我們稍后會詳細(xì)討論挖礦。

    除了在構(gòu)造函數(shù)中創(chuàng)建 創(chuàng)世 區(qū)塊外,我們還會補全 new_block()new_transaction()hash() 函數(shù):

    blockchain.py

    import hashlib
    import json
    from time import time
    
    class Blockchain(object):
     def __init__(self):
     self.current_transactions = []
     self.chain = []
    
     # 創(chuàng)建創(chuàng)世區(qū)塊
     self.new_block(previous_hash=1, proof=100)
    
     def new_block(self, proof, previous_hash=None):
     """
     創(chuàng)建一個新的區(qū)塊到區(qū)塊鏈中
     :param proof: <int> 由工作證明算法生成的證明
     :param previous_hash: (Optional) <str> 前一個區(qū)塊的 hash 值
     :return: <dict> 新區(qū)塊
     """
    
     block = {
     'index': len(self.chain) + 1,
     'timestamp': time(),
     'transactions': self.current_transactions,
     'proof': proof,
     'previous_hash': previous_hash or self.hash(self.chain[-1]),
     }
    
     # 重置當(dāng)前交易記錄
     self.current_transactions = []
    
     self.chain.append(block)
     return block
    
     def new_transaction(self, sender, recipient, amount):
     """
     創(chuàng)建一筆新的交易到下一個被挖掘的區(qū)塊中
     :param sender: <str> 發(fā)送人的地址
     :param recipient: <str> 接收人的地址
     :param amount: <int> 金額
     :return: <int> 持有本次交易的區(qū)塊索引
     """
     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):
     """
     給一個區(qū)塊生成 SHA-256 值
     :param block: <dict> Block
     :return: <str>
     """
    
     # 我們必須確保這個字典(區(qū)塊)是經(jīng)過排序的,否則我們將會得到不一致的散列
     block_string = json.dumps(block, sort_keys=True).encode()
     return hashlib.sha256(block_string).hexdigest()

    上面的代碼應(yīng)該是直白的 --- 為了讓代碼清晰,我添加了一些注釋和文檔說明。 我們差不多完成了我們的區(qū)塊鏈。 但在這個時候你一定很疑惑新的塊是怎么被創(chuàng)建、鍛造或挖掘的。

    工作量證明算法

    使用工作量證明(PoW)算法,來證明是如何在區(qū)塊鏈上創(chuàng)建或挖掘新的區(qū)塊。PoW 的目標(biāo)是計算出一個符合特定條件的數(shù)字,這個數(shù)字對于所有人而言必須在計算上非常困難,但易于驗證。這是工作證明背后的核心思想。

    我們將看到一個簡單的例子幫助你理解:

    假設(shè)一個整數(shù) x 乘以另一個整數(shù) y 的積的 Hash 值必須以 0 結(jié)尾,即 hash(x * y) = ac23dc...0。設(shè) x = 5,求y

    用 Python 實現(xiàn):

    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}')

    結(jié)果是:y = 21。因為,生成的 Hash 值結(jié)尾必須為 0

    hash(5 * 21) = 1253e9373e...5e3600155e860

    在比特幣中,工作量證明算法被稱為 Hashcash ,它和上面的問題很相似,只不過計算難度非常大。這就是礦工們?yōu)榱藸帄Z創(chuàng)建區(qū)塊的權(quán)利而爭相計算的問題。 通常,計算難度與目標(biāo)字符串需要滿足的特定字符的數(shù)量成正比,礦工算出結(jié)果后,就會獲得一定數(shù)量的比特幣獎勵(通過交易)。

    驗證結(jié)果,當(dāng)然非常容易。

    實現(xiàn)工作量證明

    讓我們來實現(xiàn)一個相似 PoW 算法。規(guī)則類似上面的例子:

    找到一個數(shù)字 P ,使得它與前一個區(qū)塊的 Proof 拼接成的字符串的 Hash 值以 4 個零開頭。

    blockchain.py

    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"

    衡量算法復(fù)雜度的辦法是修改零開頭的個數(shù)。使用 4 個來用于演示,你會發(fā)現(xiàn)多一個零都會大大增加計算出結(jié)果所需的時間。

    現(xiàn)在 Blockchain 類基本已經(jīng)完成了,接下來使用 HTTP Requests 來進行交互。

    Step 2: Blockchain 作為 API 接口

    我們將使用 Python Flask 框架,這是一個輕量 Web 應(yīng)用框架,它方便將網(wǎng)絡(luò)請求映射到 Python 函數(shù),現(xiàn)在我們來讓 Blockchain 運行在基于 Flask web 上。

    我們將創(chuàng)建三個接口:

  • /transactions/new 創(chuàng)建一個交易并添加到區(qū)塊
  • /mine 告訴服務(wù)器去挖掘新的區(qū)塊
  • /chain 返回整個區(qū)塊鏈
  • 創(chuàng)建節(jié)點

    我們的 Flask 服務(wù)器 將扮演區(qū)塊鏈網(wǎng)絡(luò)中的一個節(jié)點。我們先添加一些框架代碼:

    blockchain.py

    import hashlib
    import json
    from textwrap import dedent
    from time import time
    from uuid import uuid4
    
    from flask import Flask
    
    class Blockchain(object):
     ...
    
    # Instantiate our Node(實例化我們的節(jié)點)
    app = Flask(__name__)
    
    # Generate a globally unique address for this node(為這個節(jié)點生成一個全球唯一的地址)
    node_identifier = str(uuid4()).replace('-', '')
    
    # Instantiate the Blockchain(實例化 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='0.0.0.0', port=5000)

    簡單的說明一下以上代碼:

  • 第 15 行:實例化節(jié)點。閱讀更多關(guān)于 Flask 內(nèi)容。
  • 第 18 行:為節(jié)點創(chuàng)建一個隨機的名稱。.
  • 第 21 行:實例化 Blockchain 類。
  • 第 24--26 行:創(chuàng)建 /mine 接口,GET 方式請求。
  • 第 28--30 行:創(chuàng)建 /transactions/new 接口,POST 方式請求,可以給接口發(fā)送交易數(shù)據(jù)。
  • 第 32--38 行:創(chuàng)建 /chain 接口,返回整個區(qū)塊鏈。
  • 第 40--41 行:服務(wù)器運行端口 5000 。
  • 發(fā)送交易

    發(fā)送到節(jié)點的交易數(shù)據(jù)結(jié)構(gòu)如下:

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

    因為我們已經(jīng)有了添加交易的方法,所以基于接口來添加交易就很簡單了。讓我們?yōu)樘砑邮聞?wù)寫函數(shù):

    blockchain.py

    import hashlib
    import json
    from textwrap import dedent
    from time import time
    from uuid import uuid4
    
    from flask import Flask, jsonify, request
    
    ...
    
    @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

    挖礦

    挖礦正是神奇所在,它很簡單,做了一下三件事:

    1. 計算工作量證明 PoW
    2. 通過新增一個交易授予礦工(自己)一個幣
    3. 構(gòu)造新區(qū)塊并將其添加到鏈中

    blockchain.py

    import hashlib
    import json
    
    from time import time
    from uuid import uuid4
    
    from flask import Flask, jsonify, request
    
    ...
    
    @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
     previous_hash = blockchain.hash(last_block)
     block = blockchain.new_block(proof, previous_hash)
    
     response = {
     'message': "New Block Forged",
     'index': block['index'],
     'transactions': block['transactions'],
     'proof': block['proof'],
     'previous_hash': block['previous_hash'],
     }
     return jsonify(response), 200

    注意交易的接收者是我們自己的服務(wù)器節(jié)點,我們做的大部分工作都只是圍繞 Blockchain 類方法進行交互。到此,我們的區(qū)塊鏈就算完成了,我們來實際運行下。

    Step 3: 運行區(qū)塊鏈

    你可以使用 cURL 或 Postman 去和 API 進行交互

    啟動 Server:

    $ python blockchain.py
    * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

    讓我們通過請求 http://localhost:5000/mine ( GET )來進行挖礦:

    file

    用 Postman 發(fā)起一個 GET 請求.

    創(chuàng)建一個交易請求,請求 http://localhost:5000/transactions/new (POST),如圖

    file

    如果不是使用 Postman,則用一下的 cURL 語句也是一樣的:

    $ curl -X POST -H "Content-Type: application/json" -d '{
     "sender": "d4ee26eee15148ee92c6cd394edd974e",
     "recipient": "someone-other-address",
     "amount": 5
    }' "http://localhost:5000/transactions/new"

    在挖了兩次礦之后,就有 3 個塊了,通過請求 http://localhost:5000/chain 可以得到所有的塊信息

    {
     "chain": [
     {
     "index": 1,
     "previous_hash": 1,
     "proof": 100,
     "timestamp": 1506280650.770839,
     "transactions": []
     },
     {
     "index": 2,
     "previous_hash": "c099bc...bfb7",
     "proof": 35293,
     "timestamp": 1506280664.717925,
     "transactions": [
     {
     "amount": 1,
     "recipient": "8bbcb347e0634905b0cac7955bae152b",
     "sender": "0"
     }
     ]
     },
     {
     "index": 3,
     "previous_hash": "eff91a...10f2",
     "proof": 35089,
     "timestamp": 1506280666.1086972,
     "transactions": [
     {
     "amount": 1,
     "recipient": "8bbcb347e0634905b0cac7955bae152b",
     "sender": "0"
     }
     ]
     }
     ],
     "length": 3
    }

    Step 4: 一致性(共識)

    我們已經(jīng)有了一個基本的區(qū)塊鏈可以接受交易和挖礦。但是區(qū)塊鏈系統(tǒng)應(yīng)該是分布式的。既然是分布式的,那么我們究竟拿什么保證所有節(jié)點有同樣的鏈呢?這就是一致性問題,我們要想在網(wǎng)絡(luò)上有多個節(jié)點,就必須實現(xiàn)一個一致性的算法。

    注冊節(jié)點

    在實現(xiàn)一致性算法之前,我們需要找到一種方式讓一個節(jié)點知道它相鄰的節(jié)點。每個節(jié)點都需要保存一份包含網(wǎng)絡(luò)中其它節(jié)點的記錄。因此讓我們新增幾個接口:

    1. /nodes/register 接收 URL 形式的新節(jié)點列表.
    2. /nodes/resolve 執(zhí)行一致性算法,解決任何沖突,確保節(jié)點擁有正確的鏈.

    我們修改下 Blockchain 的 init 函數(shù)并提供一個注冊節(jié)點方法:

    blockchain.py

    ...
    from urllib.parse import urlparse
    ...
    
    class Blockchain(object):
     def __init__(self):
     ...
     self.nodes = set()
     ...
    
     def register_node(self, address):
     """
     Add a new node to the list of nodes
     :param address: <str> Address of node. Eg. 'http://192.168.0.5:5000'
     :return: None
     """
    
     parsed_url = urlparse(address)
     self.nodes.add(parsed_url.netloc)

    我們用 set 來儲存節(jié)點,這是一種避免重復(fù)添加節(jié)點的簡單方法.

    實現(xiàn)共識算法

    就像先前講的那樣,當(dāng)一個節(jié)點與另一個節(jié)點有不同的鏈時,就會產(chǎn)生沖突。 為了解決這個問題,我們將制定最長的有效鏈條是最權(quán)威的規(guī)則。換句話說就是:在這個網(wǎng)絡(luò)里最長的鏈就是最權(quán)威的。 我們將使用這個算法,在網(wǎng)絡(luò)中的節(jié)點之間達(dá)成共識。

    blockchain.py

    ...
    import requests
    
    class Blockchain(object)
     ...
    
     def valid_chain(self, chain):
     """
     Determine if a given blockchain is valid
     :param chain: <list> A blockchain
     :return: <bool> True if valid, False if not
     """
    
     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):
     """
     This is our Consensus Algorithm, it resolves conflicts
     by replacing our chain with the longest one in the network.
     :return: <bool> True if our chain was replaced, False if not
     """
    
     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

    第一個方法 valid_chain() 負(fù)責(zé)檢查一個鏈?zhǔn)欠裼行В椒ㄊ潜闅v每個塊并驗證散列和證明。

    resolve_conflicts() 是一個遍歷我們所有鄰居節(jié)點的方法,下載它們的鏈并使用上面的方法驗證它們。 如果找到一個長度大于我們的有效鏈條,我們就取代我們的鏈條。

    我們將兩個端點注冊到我們的API中,一個用于添加相鄰節(jié)點,另一個用于解決沖突:

    blockchain.py

    @app.route('/nodes/register', methods=['POST'])
    def register_nodes():
     values = request.get_json()
    
     nodes = values.get('nodes')
     if nodes is None:
     return "Error: Please supply a valid list of nodes", 400
    
     for node in nodes:
     blockchain.register_node(node)
    
     response = {
     'message': 'New nodes have been added',
     'total_nodes': list(blockchain.nodes),
     }
     return jsonify(response), 201
    
    @app.route('/nodes/resolve', methods=['GET'])
    def consensus():
     replaced = blockchain.resolve_conflicts()
    
     if replaced:
     response = {
     'message': 'Our chain was replaced',
     'new_chain': blockchain.chain
     }
     else:
     response = {
     'message': 'Our chain is authoritative',
     'chain': blockchain.chain
     }
    
     return jsonify(response), 200

    在這一點上,如果你喜歡,你可以使用一臺不同的機器,并在你的網(wǎng)絡(luò)上啟動不同的節(jié)點。 或者使用同一臺機器上的不同端口啟動進程。 我在我的機器上,不同的端口上創(chuàng)建了另一個節(jié)點,并將其注冊到當(dāng)前節(jié)點。 因此,我有兩個節(jié)點:http://localhost:5000http://localhost:5001。 注冊一個新節(jié)點:

    file

    然后我在節(jié)點 2 上挖掘了一些新的塊,以確保鏈條更長。 之后,我在節(jié)點1上調(diào)用 GET /nodes/resolve,其中鏈由一致性算法取代:

    file

    這是一個包,去找一些朋友一起,以幫助測試你的區(qū)塊鏈。

    我希望本文能激勵你創(chuàng)造更多新東西。我之所以對數(shù)字貨幣入迷,是因為我相信區(qū)塊鏈會很快改變我們看待事物的方式,包括經(jīng)濟、政府、檔案管理等。

    更新:我計劃在接下來的第2部分中繼續(xù)討論區(qū)塊鏈交易驗證機制,并討論一些可以讓區(qū)塊鏈進行生產(chǎn)的方法。

    聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

    文檔

    使用Python 搭建自己的區(qū)塊鏈

    使用Python 搭建自己的區(qū)塊鏈:【相關(guān)學(xué)習(xí)推薦:python教程】你是否會和我一樣,對加密數(shù)字貨幣底層的區(qū)塊鏈技術(shù)非常感興趣,特別想了解他們的運行機制。但是學(xué)習(xí)區(qū)塊鏈技術(shù)并非一帆風(fēng)順,我看多了大量的視頻教程還有各種課程,最終的感覺就是真正可用的實戰(zhàn)課程太少。我喜歡在實踐中學(xué)習(xí),
    推薦度:
    • 熱門焦點

    最新推薦

    猜你喜歡

    熱門推薦

    專題
    Top
    主站蜘蛛池模板: 国产精品婷婷午夜在线观看| 久久久91人妻无码精品蜜桃HD | 精品一区二区三区自拍图片区 | 久久这里只有精品18| 国产成人精品久久| 国产伦精品一区二区三区女| 欧美日韩精品一区二区三区不卡 | 精品午夜国产人人福利| 国产在线拍揄自揄视精品不卡| 亚洲第一极品精品无码久久| 久久精品国产精品亚洲艾草网美妙| 久久国产成人精品麻豆 | 亚洲AV无码精品色午夜果冻不卡 | 嫖妓丰满肥熟妇在线精品| 欧美日韩成人精品久久久免费看 | 少妇人妻偷人精品无码视频 | 人人妻人人澡人人爽人人精品97 | 久久66热人妻偷产精品9| 亚洲av永久无码精品网站| 欧美精品色精品一区二区三区| 国产精品爽爽ⅴa在线观看| 51精品资源视频在线播放| 国内精品91最新在线观看| 2022国内精品免费福利视频| 91精品视频观看| 99久久精品国内| 国产精品无码不卡一区二区三区| 国产精品视频网站你懂得| 2022免费国产精品福利在线| 精品一区二区三区东京热| 久久亚洲精品成人AV| 四虎影视永久在线观看精品| 亚洲精品乱码久久久久66| 亚洲国产另类久久久精品小说| 亚洲综合精品网站| 亚洲精品tv久久久久| 国产成人精品男人的天堂538| 国产欧美精品一区二区三区| 精品久久8x国产免费观看| 久久精品蜜芽亚洲国产AV| 精品乱码久久久久久久|