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

用Python構建一個極小的區(qū)塊鏈

開發(fā) 后端 區(qū)塊鏈
更通俗的說,它是一個公開的數(shù)據(jù)庫,新的數(shù)據(jù)存儲在被稱之為區(qū)塊block的容器中,并被添加到一個不可變的鏈中,之前添加的數(shù)據(jù)也在該鏈中。對于比特幣或其它加密貨幣來說,這些數(shù)據(jù)就是一組組交易,不過,也可以是其它任何類型的數(shù)據(jù)。

[[222988]]

雖然有些人認為區(qū)塊鏈是一個早晚會出現(xiàn)問題的解決方案,但是毫無疑問,這個創(chuàng)新技術是一個計算機技術上的奇跡。那么,究竟什么是區(qū)塊鏈呢?

 

區(qū)塊鏈

比特幣Bitcoin或其它加密貨幣按時間順序公開地記錄交易的數(shù)字賬本。

更通俗的說,它是一個公開的數(shù)據(jù)庫,新的數(shù)據(jù)存儲在被稱之為區(qū)塊block的容器中,并被添加到一個不可變的chain中(因此被稱為區(qū)塊鏈blockchain),之前添加的數(shù)據(jù)也在該鏈中。對于比特幣或其它加密貨幣來說,這些數(shù)據(jù)就是一組組交易,不過,也可以是其它任何類型的數(shù)據(jù)。

區(qū)塊鏈技術帶來了全新的、完全數(shù)字化的貨幣,如比特幣和萊特幣Litecoin,它們并不由任何中心機構管理。這給那些認為當今的銀行系統(tǒng)是騙局并將最終走向失敗的人帶來了自由。區(qū)塊鏈也革命性地改變了分布式計算的技術形式,如以太坊Ethereum就引入了一種有趣的概念:智能合約smart contract。

在這篇文章中,我將用不到 50 行的 Python 2.x 代碼實現(xiàn)一個簡單的區(qū)塊鏈,我把它叫做 SnakeCoin。

 

不到 50 行代碼的區(qū)塊鏈

我們首先將從定義我們的區(qū)塊是什么開始。在區(qū)塊鏈中,每個區(qū)塊隨同時間戳及可選的索引一同存儲。在 SnakeCoin 中,我們會存儲這兩者。為了確保整個區(qū)塊鏈的完整性,每個區(qū)塊都會有一個自識別的哈希值。如在比特幣中,每個區(qū)塊的哈希是該塊的索引、時間戳、數(shù)據(jù)和前一個區(qū)塊的哈希值等數(shù)據(jù)的加密哈希值。這里提及的“數(shù)據(jù)”可以是任何你想要的數(shù)據(jù)。

  1. import hashlib as hasher
  2.  
  3. class Block:
  4. def __init__(self, index, timestamp, data, previous_hash):
  5. self.index = index
  6. self.timestamp = timestamp
  7. self.data = data
  8. self.previous_hash = previous_hash
  9. self.hash = self.hash_block()
  10. def hash_block(self):
  11. sha = hasher.sha256()
  12. sha.update(str(self.index) +
  13. str(self.timestamp) +
  14. str(self.data) +
  15. str(self.previous_hash))
  16. return sha.hexdigest()

真棒,現(xiàn)在我們有了區(qū)塊的結構了,不過我們需要創(chuàng)建的是一個區(qū)塊鏈。我們需要把區(qū)塊添加到一個實際的鏈中。如我們之前提到過的,每個區(qū)塊都需要前一個區(qū)塊的信息。但問題是,該區(qū)塊鏈中的***個區(qū)塊在哪里?好吧,這個***個區(qū)塊,也稱之為創(chuàng)世區(qū)塊,是一個特別的區(qū)塊。在很多情況下,它是手工添加的,或通過獨特的邏輯添加的。

我們將創(chuàng)建一個函數(shù)來簡單地返回一個創(chuàng)世區(qū)塊解決這個問題。這個區(qū)塊的索引為 0 ,其包含一些任意的數(shù)據(jù)值,其“前一哈希值”參數(shù)也是任意值。

  1. import datetime as date
  2.  
  3. def create_genesis_block():
  4. # Manually construct a block with
  5. # index zero and arbitrary previous hash
  6. return Block(0, date.datetime.now(), "Genesis Block", "0")

現(xiàn)在我們可以創(chuàng)建創(chuàng)世區(qū)塊了,我們需要一個函數(shù)來生成該區(qū)塊鏈中的后繼區(qū)塊。該函數(shù)將獲取鏈中的前一個區(qū)塊作為參數(shù),為要生成的區(qū)塊創(chuàng)建數(shù)據(jù),并用相應的數(shù)據(jù)返回新的區(qū)塊。新的區(qū)塊的哈希值來自于之前的區(qū)塊,這樣每個新的區(qū)塊都提升了該區(qū)塊鏈的完整性。如果我們不這樣做,外部參與者就很容易“改變過去”,把我們的鏈替換為他們的新鏈了。這個哈希鏈起到了加密的證明作用,并有助于確保一旦一個區(qū)塊被添加到鏈中,就不能被替換或移除。

  1. def next_block(last_block):
  2. this_index = last_block.index + 1
  3. this_timestamp = date.datetime.now()
  4. this_data = "Hey! I'm block " + str(this_index)
  5. this_hash = last_block.hash
  6. return Block(this_index, this_timestamp, this_data, this_hash)

這就是主要的部分。

現(xiàn)在我們能創(chuàng)建自己的區(qū)塊鏈了!在這里,這個區(qū)塊鏈是一個簡單的 Python 列表。其***個的元素是我們的創(chuàng)世區(qū)塊,我們會添加后繼區(qū)塊。因為 SnakeCoin 是一個極小的區(qū)塊鏈,我們僅僅添加了 20 個區(qū)塊。我們通過循環(huán)來完成它。

  1. # Create the blockchain and add the genesis block
  2. blockchain = [create_genesis_block()]
  3. previous_block = blockchain[0]
  4.  
  5. # How many blocks should we add to the chain
  6. # after the genesis block
  7. num_of_blocks_to_add = 20
  8.  
  9. # Add blocks to the chain
  10. for i in range(0, num_of_blocks_to_add):
  11. block_to_add = next_block(previous_block)
  12. blockchain.append(block_to_add)
  13. previous_block = block_to_add
  14. # Tell everyone about it!
  15. print "Block #{} has been added to the blockchain!".format(block_to_add.index)
  16. print "Hash: {}\n".format(block_to_add.hash)

讓我們看看我們的成果:

別擔心,它將一直添加到 20 個區(qū)塊

別擔心,它將一直添加到 20 個區(qū)塊

很好,我們的區(qū)塊鏈可以工作了。如果你想要在主控臺查看更多的信息,你可以編輯其完整的源代碼并輸出每個區(qū)塊的時間戳或數(shù)據(jù)。

這就是 SnakeCoin 所具有的功能。要使 SnakeCoin 達到現(xiàn)今的產(chǎn)品級的區(qū)塊鏈的高度,我們需要添加更多的功能,如服務器層,以在多臺機器上跟蹤鏈的改變,并通過工作量證明算法(POW)來限制給定時間周期內(nèi)可以添加的區(qū)塊數(shù)量。

如果你想了解更多技術細節(jié),你可以在這里查看最初的比特幣白皮書。

 

讓這個極小區(qū)塊鏈稍微變大些

這個極小的區(qū)塊鏈及其簡單,自然也相對容易完成。但是因其簡單也帶來了一些缺陷。首先,SnakeCoin 僅能運行在單一的一臺機器上,所以它相距分布式甚遠,更別提去中心化了。其次,區(qū)塊添加到區(qū)塊鏈中的速度同在主機上創(chuàng)建一個 Python 對象并添加到列表中一樣快。在我們的這個簡單的區(qū)塊鏈中,這不是問題,但是如果我們想讓 SnakeCoin 成為一個實際的加密貨幣,我們就需要控制在給定時間內(nèi)能創(chuàng)建的區(qū)塊(和幣)的數(shù)量。

從現(xiàn)在開始,SnakeCoin 中的“數(shù)據(jù)”將是交易數(shù)據(jù),每個區(qū)塊的“數(shù)據(jù)”字段都將是一些交易信息的列表。接著我們來定義“交易”。每個“交易”是一個 JSON 對象,其記錄了幣的發(fā)送者、接收者和轉(zhuǎn)移的 SnakeCoin 數(shù)量。注:交易信息是 JSON 格式,原因我很快就會說明。

  1. {
  2. "from": "71238uqirbfh894-random-public-key-a-alkjdflakjfewn204ij",
  3. "to": "93j4ivnqiopvh43-random-public-key-b-qjrgvnoeirbnferinfo",
  4. "amount": 3
  5. }

現(xiàn)在我們知道了交易信息看起來的樣子了,我們需要一個辦法來將其加到我們的區(qū)塊鏈網(wǎng)絡中的一臺計算機(稱之為節(jié)點)中。要做這個事情,我們會創(chuàng)建一個簡單的 HTTP 服務器,以便每個用戶都可以讓我們的節(jié)點知道發(fā)生了新的交易。節(jié)點可以接受  POST 請求,請求數(shù)據(jù)為如上的交易信息。這就是為什么交易信息是 JSON 格式的:我們需要它們可以放在請求信息中傳遞給服務器。

$ pip install flask # 首先安裝 Web 服務器框架
  1. from flask import Flask
  2. from flask import request
  3. node = Flask(__name__)
  4.  
  5. # Store the transactions that
  6. # this node has in a list
  7. this_nodes_transactions = []
  8.  
  9. @node.route('/txion', methods=['POST'])
  10. def transaction():
  11. if request.method == 'POST':
  12. # On each new POST request,
  13. # we extract the transaction data
  14. new_txion = request.get_json()
  15. # Then we add the transaction to our list
  16. this_nodes_transactions.append(new_txion)
  17. # Because the transaction was successfully
  18. # submitted, we log it to our console
  19. print "New transaction"
  20. print "FROM: {}".format(new_txion['from'])
  21. print "TO: {}".format(new_txion['to'])
  22. print "AMOUNT: {}\n".format(new_txion['amount'])
  23. # Then we let the client know it worked out
  24. return "Transaction submission successful\n"
  25.  
  26. node.run()

真棒!現(xiàn)在我們有了一種保存用戶彼此發(fā)送 SnakeCoin 的記錄的方式。這就是為什么人們將區(qū)塊鏈稱之為公共的、分布式賬本:所有的交易信息存儲給所有人看,并被存儲在該網(wǎng)絡的每個節(jié)點上。

但是,有個問題:人們從哪里得到 SnakeCoin 呢?現(xiàn)在還沒有辦法得到,還沒有一個稱之為 SnakeCoin 這樣的東西,因為我們還沒有創(chuàng)建和分發(fā)任何一個幣。要創(chuàng)建新的幣,人們需要“挖”一個新的 SnakeCoin 區(qū)塊。當他們成功地挖到了新區(qū)塊,就會創(chuàng)建出一個新的 SnakeCoin ,并獎勵給挖出該區(qū)塊的人(礦工)。一旦挖礦的礦工將 SnakeCoin 發(fā)送給別人,這個幣就流通起來了。

我們不想讓挖新的 SnakeCoin 區(qū)塊太容易,因為這將導致 SnakeCoin 太多了,其價值就變低了;同樣,我們也不想讓它變得太難,因為如果沒有足夠的幣供每個人使用,它們對于我們來說就太昂貴了。為了控制挖新的 SnakeCoin 區(qū)塊的難度,我們會實現(xiàn)一個工作量證明Proof-of-Work(PoW)算法。工作量證明基本上就是一個生成某個項目比較難,但是容易驗證(其正確性)的算法。這個項目被稱之為“證明”,聽起來就像是它證明了計算機執(zhí)行了特定的工作量。

在 SnakeCoin 中,我們創(chuàng)建了一個簡單的 PoW 算法。要創(chuàng)建一個新區(qū)塊,礦工的計算機需要遞增一個數(shù)字,當該數(shù)字能被 9 (“SnakeCoin” 這個單詞的字母數(shù))整除時,這就是***這個區(qū)塊的證明數(shù)字,就會挖出一個新的 SnakeCoin 區(qū)塊,而該礦工就會得到一個新的 SnakeCoin。

  1. # ...blockchain
  2. # ...Block class definition
  3.  
  4. miner_address = "q3nf394hjg-random-miner-address-34nf3i4nflkn3oi"
  5.  
  6. def proof_of_work(last_proof):
  7. # Create a variable that we will use to find
  8. # our next proof of work
  9. incrementor = last_proof + 1
  10. # Keep incrementing the incrementor until
  11. # it's equal to a number divisible by 9
  12. # and the proof of work of the previous
  13. # block in the chain
  14. while not (incrementor % 9 == 0 and incrementor % last_proof == 0):
  15. incrementor += 1
  16. # Once that number is found,
  17. # we can return it as a proof
  18. # of our work
  19. return incrementor
  20.  
  21. @node.route('/mine', methods = ['GET'])
  22. def mine():
  23. # Get the last proof of work
  24. last_block = blockchain[len(blockchain) - 1]
  25. last_proof = last_block.data['proof-of-work']
  26. # Find the proof of work for
  27. # the current block being mined
  28. # Note: The program will hang here until a new
  29. # proof of work is found
  30. proof = proof_of_work(last_proof)
  31. # Once we find a valid proof of work,
  32. # we know we can mine a block so
  33. # we reward the miner by adding a transaction
  34. this_nodes_transactions.append(
  35. { "from": "network", "to": miner_address, "amount": 1 }
  36. )
  37. # Now we can gather the data needed
  38. # to create the new block
  39. new_block_data = {
  40. "proof-of-work": proof,
  41. "transactions": list(this_nodes_transactions)
  42. }
  43. new_block_index = last_block.index + 1
  44. new_block_timestamp = this_timestamp = date.datetime.now()
  45. last_block_hash = last_block.hash
  46. # Empty transaction list
  47. this_nodes_transactions[:] = []
  48. # Now create the
  49. # new block!
  50. mined_block = Block(
  51. new_block_index,
  52. new_block_timestamp,
  53. new_block_data,
  54. last_block_hash
  55. )
  56. blockchain.append(mined_block)
  57. # Let the client know we mined a block
  58. return json.dumps({
  59. "index": new_block_index,
  60. "timestamp": str(new_block_timestamp),
  61. "data": new_block_data,
  62. "hash": last_block_hash
  63. }) + "\n"

現(xiàn)在,我們能控制特定的時間段內(nèi)挖到的區(qū)塊數(shù)量,并且我們給了網(wǎng)絡中的人新的幣,讓他們彼此發(fā)送。但是如我們說的,我們只是在一臺計算機上做的。如果區(qū)塊鏈是去中心化的,我們怎樣才能確保每個節(jié)點都有相同的鏈呢?要做到這一點,我們會使每個節(jié)點都廣播其(保存的)鏈的版本,并允許它們接受其它節(jié)點的鏈。然后,每個節(jié)點會校驗其它節(jié)點的鏈,以便網(wǎng)絡中每個節(jié)點都能夠達成最終的鏈的共識。這稱之為共識算法consensus algorithm

我們的共識算法很簡單:如果一個節(jié)點的鏈與其它的節(jié)點的不同(例如有沖突),那么最長的鏈保留,更短的鏈會被刪除。如果我們網(wǎng)絡上的鏈沒有了沖突,那么就可以繼續(xù)了。

  1. @node.route('/blocks', methods=['GET'])
  2. def get_blocks():
  3. chain_to_send = blockchain
  4. # Convert our blocks into dictionaries
  5. # so we can send them as json objects later
  6. for block in chain_to_send:
  7. block_index = str(block.index)
  8. block_timestamp = str(block.timestamp)
  9. block_data = str(block.data)
  10. block_hash = block.hash
  11. block = {
  12. "index": block_index,
  13. "timestamp": block_timestamp,
  14. "data": block_data,
  15. "hash": block_hash
  16. }
  17. # Send our chain to whomever requested it
  18. chain_to_send = json.dumps(chain_to_send)
  19. return chain_to_send
  20.  
  21. def find_new_chains():
  22. # Get the blockchains of every
  23. # other node
  24. other_chains = []
  25. for node_url in peer_nodes:
  26. # Get their chains using a GET request
  27. block = requests.get(node_url + "/blocks").content
  28. # Convert the JSON object to a Python dictionary
  29. block = json.loads(block)
  30. # Add it to our list
  31. other_chains.append(block)
  32. return other_chains
  33.  
  34. def consensus():
  35. # Get the blocks from other nodes
  36. other_chains = find_new_chains()
  37. # If our chain isn't longest,
  38. # then we store the longest chain
  39. longest_chain = blockchain
  40. for chain in other_chains:
  41. if len(longest_chain) < len(chain):
  42. longest_chain = chain
  43. # If the longest chain wasn't ours,
  44. # then we set our chain to the longest
  45. blockchain = longest_chain

我們差不多就要完成了。在運行了完整的 SnakeCoin 服務器代碼之后,在你的終端可以運行如下代碼。(假設你已經(jīng)安裝了 cCUL)。

 

1、創(chuàng)建交易

curl "localhost:5000/txion" \
-H "Content-Type: application/json" \
-d '{"from": "akjflw", "to":"fjlakdj", "amount": 3}'

 

2、挖一個新區(qū)塊

curl localhost:5000/mine

 

3、 查看結果。從客戶端窗口,我們可以看到。

對代碼做下美化處理,我們看到挖礦后我們得到的新區(qū)塊的信息:

{
"index": 2,
"data": {
"transactions": [
{
"to": "fjlakdj",
"amount": 3,
"from": "akjflw"
},
{
"to": "q3nf394hjg-random-miner-address-34nf3i4nflkn3oi",
"amount": 1,
"from": "network"
}
],
"proof-of-work": 36
},
"hash": "151edd3ef6af2e7eb8272245cb8ea91b4ecfc3e60af22d8518ef0bba8b4a6b18",
"timestamp": "2017-07-23 11:23:10.140996"
}

大功告成!現(xiàn)在 SnakeCoin 可以運行在多個機器上,從而創(chuàng)建了一個網(wǎng)絡,而且真實的 SnakeCoin 也能被挖到了。

你可以根據(jù)你的喜好去修改 SnakeCoin 服務器代碼,并問各種問題了。 

責任編輯:龐桂玉 來源: Linux中國
相關推薦

2018-07-30 14:28:22

2018-08-22 17:32:45

2018-06-15 11:08:02

2018-09-30 08:00:15

區(qū)塊鏈碳排放氣候

2018-08-20 20:22:05

區(qū)塊鏈互聯(lián)網(wǎng)未來

2018-02-06 10:04:59

2018-03-05 18:30:27

區(qū)塊鏈側鏈共識算法

2021-02-24 13:58:07

區(qū)塊鏈比特幣安全

2019-06-27 08:45:02

區(qū)塊鏈加密貨幣DEFI

2020-12-11 11:19:54

區(qū)塊鏈資金投資

2019-10-30 13:30:29

Python區(qū)塊鏈編程語言

2019-04-18 13:40:31

區(qū)塊鏈分布式賬本數(shù)據(jù)庫

2020-08-13 17:59:20

區(qū)塊鏈區(qū)塊鏈項目數(shù)字貨幣

2021-03-12 19:17:38

區(qū)塊鏈GoPython

2018-04-13 10:31:14

2018-01-30 05:04:02

2019-05-14 12:30:07

PythonPygame游戲框架

2018-08-03 12:21:02

2021-07-07 14:21:26

區(qū)塊鏈數(shù)字錢包數(shù)字貨幣

2019-08-14 15:56:23

點贊
收藏

51CTO技術棧公眾號