自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

從0到1 手把手教你建一個(gè)區(qū)塊鏈

譯文
區(qū)塊鏈 后端
近期的區(qū)塊鏈重回?zé)狳c(diǎn),如果你想深入了解區(qū)塊鏈,那就來(lái)看一下本文,手把手教你構(gòu)建一個(gè)自己的區(qū)塊鏈。

【51CTO.com快譯】近期的區(qū)塊鏈重回?zé)狳c(diǎn),如果你想深入了解區(qū)塊鏈,那就來(lái)看一下本文,手把手教你構(gòu)建一個(gè)自己的區(qū)塊鏈。

弄懂區(qū)塊鏈的最快方法-親自構(gòu)建一個(gè)

看到這篇文章,說(shuō)明您也是對(duì)加密貨幣的興起感興趣,想知道區(qū)塊鏈?zhǔn)侨绾喂ぷ鞯暮推浔澈筮\(yùn)行的技術(shù)原理。

但是想要搞懂區(qū)塊鏈并不容易。我在眾多的視頻中苦苦鉆研,跟隨著漏洞百出的教程,經(jīng)歷著因區(qū)塊鏈相關(guān)案例太少而產(chǎn)生的挫敗感。

我喜歡從行動(dòng)中學(xué)習(xí)。它迫使我從代碼層面處理問(wèn)題,從而解決問(wèn)題。如果您和我一樣做,那么在本指南的最后,您將擁有一個(gè)運(yùn)行正常的區(qū)塊鏈,并對(duì)它們的工作原理有深入的了解。

上手準(zhǔn)備

請(qǐng)記住,區(qū)塊鏈?zhǔn)且粋€(gè)不可變的、連續(xù)的記錄鏈,稱為塊。它們可以包含事務(wù)、文件或您喜歡的任何數(shù)據(jù)。但是重要的是,它們通過(guò)使用哈希而被鏈接在一起。

如果您不確定什么是哈希值,請(qǐng)參考這里。

教程面向的人群?

可以輕松地閱讀和編寫(xiě)一些基本的Python,并且對(duì)HTTP請(qǐng)求的工作方式有所了解,因?yàn)楸疚膶⑼ㄟ^(guò)HTTP與區(qū)塊鏈進(jìn)行交流。

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

確保已安裝 Python 3.6 +(以及pip)。您還需要安裝Flask和很棒的Requests庫(kù):

pip install Flask==0.12.2 requests==2.18.4

您還需要HTTP客戶端,例如Postman或cURL。

源代碼可在此處獲得。

步驟1:構(gòu)建一個(gè)區(qū)塊鏈

打開(kāi)你最喜歡的文本編輯器或IDE,我個(gè)人喜歡 PyCharm。創(chuàng)建一個(gè)名為blockchain.py的新文件。我們將只使用一個(gè)文件,但是如果您有困惑了,可以隨時(shí)參考源代碼。

展示區(qū)塊鏈

我們將創(chuàng)建一個(gè)Blockchain class,它的構(gòu)造函數(shù)會(huì)創(chuàng)建一個(gè)初始的空列表(用于存儲(chǔ)我們的區(qū)塊鏈),另一個(gè)用于存儲(chǔ)事務(wù)。這是腳本: 

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 class?? 的demo

我們的Blockchain class負(fù)責(zé)管理鏈。它將存儲(chǔ)事物,并具有一些將新塊添加到鏈中的輔助方法。讓我們來(lái)嘗試一些新的方法吧。

Block像什么?

每個(gè)Block都有以下的內(nèi)容:

  • 一個(gè)索引,
  • 一個(gè)時(shí)間戳(Unix時(shí)間),
  • 一個(gè)交易列表,
  • 一個(gè)證明(稍后會(huì)有更多說(shuō)明)
  • 前一個(gè)區(qū)塊的哈希值。

單個(gè)區(qū)塊示例: 

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

在這一點(diǎn)上,鏈的概念應(yīng)該很明顯--每個(gè)新區(qū)塊本身都包含前一個(gè)區(qū)塊的哈希值。這是至關(guān)重要的,因?yàn)檫@給予了區(qū)塊鏈的不可篡改性:如果攻擊者破壞了鏈中較早的區(qū)塊,則后續(xù)所有的區(qū)塊都將包含不正確的哈希值。

不知道你能理解嘛,請(qǐng)多花些時(shí)間去理解它—這是區(qū)塊鏈的核心思想。

添加事物到區(qū)塊中

我們需要一種將事物添加到區(qū)塊的方法。我們的new_transaction()方法有效,而且很簡(jiǎn)單: 

class Blockchain(object):
...
def new_transaction(self, sender, recipient, amount):
"""
Creates a new transaction to go into the next mined Block
:param sender: Address of the Sender
:param recipient: Address of the Recipient
:param amount: Amount
:return: 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()添加一個(gè)新的交易到列表中,它將返回到交易將被添加進(jìn)去、即將被開(kāi)采的區(qū)塊的索引。這對(duì)之后提交交易的用戶是很有用處的。

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

當(dāng)我們Blockchain被實(shí)例化,我們需要用一個(gè)genesis塊來(lái)播種它——一個(gè)沒(méi)有前處理的塊。還需要向我們的創(chuàng)世區(qū)塊添加一個(gè)“證明”,這是挖掘(或工作證明)的結(jié)果。稍后我們將詳細(xì)討論挖礦。

除了在構(gòu)造函數(shù)中創(chuàng)建genesis塊,我們還將充實(shí)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: The proof given by the Proof of Work algorithm
:param previous_hash: (Optional) Hash of previous Block
:return: 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: Address of the Sender
:param recipient: Address of the Recipient
:param amount: Amount
:return: 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: Block
:return:
"""
# 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()

上面的內(nèi)容應(yīng)該很簡(jiǎn)單—我添加了一些注釋和文檔字符串來(lái)幫助保持清楚明了。對(duì)區(qū)塊鏈的表示幾乎完成了。但此時(shí),您一定想知道如何創(chuàng)建、鍛造或挖掘新的區(qū)塊。

了解工作量證明

工作算法(PoW)是在區(qū)塊鏈上創(chuàng)建或挖掘新區(qū)塊的方式。PoW的目標(biāo)是發(fā)現(xiàn)可以解決問(wèn)題的數(shù)字。從數(shù)字上來(lái)說(shuō),很難找到該數(shù)字,但是很容易被網(wǎng)絡(luò)上的任何人進(jìn)行驗(yàn)證。這是工作證明的核心思想。

我們將看一個(gè)非常簡(jiǎn)單的示例來(lái)幫助理解。

讓我們決定某個(gè)整數(shù)X乘以另一個(gè)Y的哈希必須以0結(jié)尾。因此,對(duì)于這個(gè)簡(jiǎn)化的示例,讓我們修復(fù)。在Python中實(shí)現(xiàn):xy0hash(x * y) = ac23dc...0x = 5 

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。因?yàn)?,產(chǎn)生的哈希值以0結(jié)尾:

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

在比特幣中,工作證明算法稱為Hashcash。而且與我們上面的示例并沒(méi)有太大不同。這是礦工為了創(chuàng)建一個(gè)新的塊而競(jìng)相求解的算法。通常,難度由字符串中搜索的字符數(shù)決定。然后,通過(guò)在交易中獲得硬幣,礦工將借此獲得獎(jiǎng)勵(lì)。

網(wǎng)絡(luò)能夠輕松驗(yàn)證他們的解決方案。

實(shí)施基本的工作證明

讓我們?yōu)閰^(qū)塊鏈實(shí)現(xiàn)類似的算法。我們的規(guī)則將類似于上面的示例:

找出一個(gè)數(shù)字 p ,當(dāng)該數(shù)字與上一個(gè)塊的解決方案進(jìn)行哈希運(yùn)算時(shí),將產(chǎn)生一個(gè)帶有4個(gè)前導(dǎo)4個(gè)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:
:return:
"""
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: Previous Proof
:param proof: Current Proof
:return: True if correct, False if not.
"""
guess = f'{last_proof}{proof}'.encode()
guess_hash = hashlib.sha256(guess).hexdigest()
return guess_hash[:4] == "0000"

要調(diào)整算法的難度,我們可以修改前導(dǎo)零的數(shù)量。但是4就足夠了。您會(huì)發(fā)現(xiàn),添加單個(gè)前導(dǎo)零會(huì)極大地縮短尋找解決方案所需的時(shí)間。

我們的類快要完成了,我們已經(jīng)準(zhǔn)備好開(kāi)始使用HTTP請(qǐng)求與其進(jìn)行交互。

步驟2:我們的區(qū)塊鏈作為API

我們將使用Python Flask框架。這是一個(gè)微框架,可輕松將端點(diǎn)映射到Python函數(shù)。這使我們可以使用HTTP請(qǐng)求通過(guò)web與區(qū)塊鏈進(jìn)行通信。

我們將創(chuàng)建三種方法:

  • /transactions/new 創(chuàng)建一個(gè)新的交易塊。
  • /mine 告訴我們的服務(wù)器挖掘一個(gè)新塊。
  • /chain 返回完整的區(qū)塊鏈。

設(shè)置Flask

我們的“服務(wù)器”將在我們的區(qū)塊鏈網(wǎng)絡(luò)中形成單個(gè)節(jié)點(diǎn)。讓我們創(chuàng)建一個(gè)demo: 

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
app = Flask(__name__)
# Generate a globally unique address for this node
node_identifier = str(uuid4()).replace('-', '')
# Instantiate the 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)

簡(jiǎn)要說(shuō)明:

  • 第15行:實(shí)例化我們的節(jié)點(diǎn);??Flask更多信息??。
  • 第18行:為節(jié)點(diǎn)創(chuàng)建一個(gè)隨機(jī)名稱。
  • 第21行:實(shí)例化Blockchain類。
  • 第24–26行:創(chuàng)建/mine端點(diǎn),這是一個(gè)GET請(qǐng)求。
  • 第28–30行:創(chuàng)建/transactions/new端點(diǎn),這是一個(gè)POST請(qǐng)求,因?yàn)槲覀儗⑾蛩l(fā)送數(shù)據(jù)。
  • 第32–38行:創(chuàng)建/chain端點(diǎn),該端點(diǎn)返回完整的區(qū)塊鏈。
  • 40-41行:在端口5000上運(yùn)行服務(wù)器。

交易端點(diǎn)

這就是交易請(qǐng)求的樣子。這是用戶發(fā)送到服務(wù)器的內(nèi)容: 

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

由于我們已經(jīng)有了用于將事務(wù)添加到塊中的類方法,因此其余操作很簡(jiǎn)單。讓我們編寫(xiě)添加事務(wù)的函數(shù): 

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

創(chuàng)建交易的方法

步驟3:與區(qū)塊鏈交互

您可以使用普通的舊cURL或Postman通過(guò)網(wǎng)絡(luò)與我們的API進(jìn)行交互。

啟動(dòng)服務(wù)器: 

$ python blockchain.py
* Running on http://127.0.0.1:5000/ (按CTRL + C退出)

讓我們嘗試通過(guò)向http://localhost:5000/mine:發(fā)出GET請(qǐng)求來(lái)挖掘一個(gè)塊:

??

使用郵遞員發(fā)出GET請(qǐng)求讓我們創(chuàng)建一個(gè)新的事務(wù),通過(guò)發(fā)送POST請(qǐng)求到http://localhost:5000/transactions/new,其主體包含我們的事務(wù)結(jié)構(gòu):

??

使用郵遞員發(fā)出POST請(qǐng)求

如果您不使用Postman,可以使用cURL發(fā)出等效請(qǐng)求: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
}

步驟4:共識(shí)

我們目前已經(jīng)擁有一個(gè)基本的區(qū)塊鏈,可以接受交易并允許我們挖掘新的區(qū)塊。但是區(qū)塊鏈的重點(diǎn)在于它們應(yīng)該去中心化。而且,如果它們是去中心,我們?nèi)绾未_保它們都反映相同的鏈?這叫做共識(shí)問(wèn)題,如果我們要在網(wǎng)絡(luò)中擁有多個(gè)節(jié)點(diǎn),就必須實(shí)現(xiàn)共識(shí)算法。

注冊(cè)新節(jié)點(diǎn)

在實(shí)現(xiàn)共識(shí)算法之前,我們需要一種讓節(jié)點(diǎn)知道網(wǎng)絡(luò)上相鄰節(jié)點(diǎn)的方法。我們網(wǎng)絡(luò)上的每個(gè)節(jié)點(diǎn)都應(yīng)保留網(wǎng)絡(luò)上其他節(jié)點(diǎn)的注冊(cè)表。

因此,我們將需要更多的端點(diǎn):

  1. /nodes/register 接受URL形式的新節(jié)點(diǎn)列表。
  2. /nodes/resolve 實(shí)現(xiàn)我們的共識(shí)算法,該算法可以解決所有沖突-確保節(jié)點(diǎn)具有正確的鏈。

我們需要修改區(qū)塊鏈的構(gòu)造函數(shù),并提供一種注冊(cè)節(jié)點(diǎn)的方法: 

...
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: Address of node. Eg. 'http://192.168.0.5:5000'
:return: None
"""
parsed_url = urlparse(address)
self.nodes.add(parsed_url.netloc)

一種將相鄰節(jié)點(diǎn)添加到網(wǎng)絡(luò)的方法

請(qǐng)注意,我們使用了a set()來(lái)保存節(jié)點(diǎn)列表。這是一種廉價(jià)方法,它確保添加新節(jié)點(diǎn)是冪等,這意味著無(wú)論我們添加特定節(jié)點(diǎn)多少次,它都將只出現(xiàn)一次。

實(shí)施共識(shí)算法

如上所述,當(dāng)一個(gè)節(jié)點(diǎn)與另一節(jié)點(diǎn)具有不同的鏈時(shí)會(huì)發(fā)生沖突。為了解決這個(gè)問(wèn)題,我們規(guī)定最長(zhǎng)的有效鏈?zhǔn)蔷哂凶罡邫?quán)威的。換句話說(shuō),網(wǎng)絡(luò)上最長(zhǎng)的鏈?zhǔn)鞘聦?shí)鏈。使用此算法,我們可以在網(wǎng)絡(luò)中的節(jié)點(diǎn)之間達(dá)成共識(shí)。 

...
import requests
class Blockchain(object)
...
def valid_chain(self, chain):
"""
Determine if a given blockchain is valid
:param chain: A blockchain
:return: 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("\n-----------\n")
# 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: 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é)通過(guò)檢查每個(gè)塊并驗(yàn)證哈希和檢驗(yàn)鏈?zhǔn)欠裼行А?/p>

resolve_conflicts()是一種方法,它會(huì)檢查我們所有的相鄰節(jié)點(diǎn),下載它們的鏈并使用上述方法驗(yàn)證它們。如果找到有效鏈,其長(zhǎng)度大于我們的長(zhǎng)度,我們將替換它。

讓我們將兩個(gè)端點(diǎn)注冊(cè)到我們的API,一個(gè)端點(diǎn)用于添加相鄰節(jié)點(diǎn),另一個(gè)端點(diǎn)用于解決沖突: 

@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

此時(shí),您可以根據(jù)需要使用其他計(jì)算機(jī),并在網(wǎng)絡(luò)上啟動(dòng)不同的節(jié)點(diǎn)。或使用同一臺(tái)計(jì)算機(jī)上的不同端口啟動(dòng)進(jìn)程。我在機(jī)器上的另一個(gè)端口上旋轉(zhuǎn)了另一個(gè)節(jié)點(diǎn),并將其注冊(cè)到當(dāng)前節(jié)點(diǎn)。因此,我有兩個(gè)節(jié)點(diǎn):http://localhost:5000和http://localhost:5001。

??

注冊(cè)新節(jié)點(diǎn)

然后,我在節(jié)點(diǎn)2上挖到了一些新區(qū)塊,以確保鏈更長(zhǎng)。之后,對(duì)GET /nodes/resolve在節(jié)點(diǎn)1上進(jìn)行了調(diào)用,在該節(jié)點(diǎn)上,該鏈被共識(shí)算法替換:

??

工作中的共識(shí)算法

目前為止已經(jīng)接近成功;可以去找一些朋友一起幫助測(cè)試您的區(qū)塊鏈。

原文標(biāo)題:Learn Blockchains by Building One,作者:Daniel van Flymen

【51CTO譯稿,合作站點(diǎn)轉(zhuǎn)載請(qǐng)注明原文譯者和出處為51CTO.com】


責(zé)任編輯:龐桂玉 來(lái)源: 51CTO
相關(guān)推薦

2022-08-25 14:41:51

集群搭建

2024-05-30 10:30:39

2019-08-26 09:25:23

RedisJavaLinux

2020-12-23 09:48:37

數(shù)據(jù)工具技術(shù)

2021-12-10 18:19:55

指標(biāo)體系設(shè)計(jì)

2025-04-07 09:40:00

智能體AI代碼

2021-06-22 10:43:03

Webpack loader plugin

2022-06-28 15:29:56

Python編程語(yǔ)言計(jì)時(shí)器

2022-08-26 08:01:38

DashWebJavaScrip

2022-09-22 12:38:46

antd form組件代碼

2016-11-01 09:46:04

2011-01-10 14:41:26

2011-05-03 15:59:00

黑盒打印機(jī)

2021-07-14 09:00:00

JavaFX開(kāi)發(fā)應(yīng)用

2021-08-31 10:02:10

KubernetesLinux集群

2022-05-18 08:51:44

調(diào)用模板后端并行

2020-05-09 09:59:52

Python數(shù)據(jù)土星

2023-03-22 09:00:38

2018-11-22 09:17:21

消息推送系統(tǒng)

2021-02-26 11:54:38

MyBatis 插件接口
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)