50行Python代碼構建小型區塊鏈

來源:互聯網
上載者:User

標籤:console   source   crypto   ast   hash   element   waiting   lin   anything   

本文介紹了如何使用python構建一個小型的區塊鏈技術,使用Python2實現,代碼不到50行。

 

Although some think blockchain is a solution waiting for problems, there’s no doubt that this novel technology is a marvel of computing. But, what exactly is a blockchain?
雖然有人認為區塊鏈本身仍有很多問題需要解決,但毫無疑問,這種新穎的技術是電腦界的奇蹟。 但是,究竟什麼是一個區塊鏈?

Blockchain
a digital ledger in which transactions made in bitcoin or another cryptocurrency are recorded chronologically and publicly. >
區塊鏈一種數字記賬本,其中以比特幣或其他加密方式按時間順序並公開記錄地進行交易。

In more general terms, it’s a public database where new data are stored in a container called a block and are added to an immutable chain (hence blockchain) with data added in the past. In the case of Bitcoin and other cryptocurrencies, these data are groups of transactions. But, the data can be of any type, of course.
通俗的講,區塊鏈是一個公用資料庫,其中新產生的資料存放區在稱為塊的容器中,並被添加到具有已經存在資料的區塊構成的鏈中。在比特幣和其他加密貨幣的情況下,這些資料是一組交易。資料也可以是任何類型的。


Blockchain technology has given rise to new, fully digital currencies like Bitcoin and Litecoin that aren’t issued or managed by a central authority. This brings new freedom to individuals who believe that today’s banking systems are a scam or subject to failure. Blockchain has also revolutionized distributed computing in the form of technologies like Ethereum, which has introduced interesting concepts like smart contracts.
區塊鏈技術已經帶來了全新的,完全數字化的貨幣,如比特幣和萊特幣,它們不由中央機構發行或管理的,這給相信今天的銀行體系是騙局或失敗的個人帶來了新的自由。區塊鏈也以像以太坊這樣的技術形式革新了分散式運算,它引入了有趣的概念,如智能合約。


In this article, I’ll make a simple blockchain in less than 50 lines of Python 2 code. It’ll be called SnakeCoin.
在本文中,我將在不到50行的Python 2代碼中製作一個簡單的區塊鏈。這將被稱為SnakeCoin。


We’ll start by first defining what our blocks will look like. In blockchain, each block is stored with a timestamp and, optionally, an index. In SnakeCoin, we’re going to store both. And to help ensure integrity throughout the blockchain, each block will have a self-identifying hash. Like Bitcoin, each block’s hash will be a cryptographic hash of the block’s index, timestamp, data, and the hash of the previous block’s hash. Oh, and the data can be anything you want.
我們首先定義我們的區塊將是什麼樣子。在區塊鏈中,每個塊都儲存有時間戳記和可選的索引。在SnakeCoin中,我們將同時儲存兩者。並且為了協助確保整個塊鏈的完整性,每個塊將具有自識別雜湊值的功能。像比特幣一樣,每個區塊將包括作為區塊的索引的雜湊值,時間戳記,資料以及前一個塊的雜湊值。哦,資料可以是任何你想要的。

import hashlib as hasherclass Block:  def __init__(self, index, timestamp, data, previous_hash):    self.index = index    self.timestamp = timestamp    self.data = data    self.previous_hash = previous_hash    self.hash = self.hash_block()  def hash_block(self):    sha = hasher.sha256()    sha.update(str(self.index) +                str(self.timestamp) +                str(self.data) +                str(self.previous_hash))    return sha.hexdigest()    


Awesome! We have our block structure, but we’re creating a block chain. We need to start adding blocks to the actual chain. As I mentioned earlier, each block requires information from the previous block. But with that being said, a question arises: how does the first block in the blockchain get there? Well, the first block, or genesis block, is a special block. In many cases, it’s added manually or has unique logic allowing it to be added.
真棒!我們已經有了塊結構了,但是我們正在建立一個區塊鏈。我們需要開始向實際的鏈條添加區塊。如前所述,每個塊都需要上一個塊的資訊。但是這就出現了一個問題:塊區中的第一個區塊怎麼來的?那麼,第一個區塊,或起創世區塊,是一個特殊的塊。在許多情況下,它是手動添加的或具有允許添加的唯一邏輯。


We’ll create a function that simply returns a genesis block to make things easy. This block is of index 0, and it has an arbitrary data value and an arbitrary value in the “previous hash” parameter.
為了簡化,我們將建立一個函數,只需返回一個創世區塊,該區塊的索引為0,它在“previous hash”參數中具有任意資料值和任意值。

import datetime as datedef create_genesis_block():  # Manually construct a block with  # index zero and arbitrary previous hash  return Block(0, date.datetime.now(), "Genesis Block", "0")

Now that we’re able to create a genesis block, we need a function that will generate succeeding blocks in the blockchain. This function will take the previous block in the chain as a parameter, create the data for the block to be generated, and return the new block with its appropriate data. When new blocks hash information from previous blocks, the integrity of the blockchain increases with each new block. If we didn’t do this, it would be easier for an outside party to “change the past” and replace our chain with an entirely new one of their own. This chain of hashes acts as cryptographic proof and helps ensure that once a block is added to the blockchain it cannot be replaced or removed.
現在我們建立了一個創世區塊,我們需要一個函數來產生區塊鏈中的後續區塊。該函數將將鏈中的前一個區塊作為參數,建立要產生的區塊的資料,並返回具有其相應資料的新塊。新產生的區塊會儲存先前區塊中的雜湊值,區塊鏈的完整性隨著每個新的區塊而增加。如果我們沒有這樣做,其他人會很容易篡改記錄,並用自己的全新資料替代我們的鏈條。這個雜湊鏈作為加密證明,有助於確保一旦新區塊被添加到區塊鏈中,它不能被替換或刪除。

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

 
That’s the majority of the hard work. Now, we can create our blockchain! In our case, the blockchain itself is a simple Python list. The first element of the list is the genesis block. And of course, we need to add the succeeding blocks. Because SnakeCoin is the tiniest blockchain, we’ll only add 20 new blocks. We can do this with a for loop.
這是本次任務的重心。現在我們可以建立我們的區塊鏈!在我們的例子中,區塊鏈本身就是一個簡單的Python列表。列表的第一個元素是創世區塊。當然,我們需要添加後續的區塊。因為SnakeCoin是最小的區塊鏈,所以我們只添加了20個新的塊。我們可以用for迴圈來做到這一點。

# Create the blockchain and add the genesis blockblockchain = [create_genesis_block()]previous_block = blockchain[0]# How many blocks should we add to the chain# after the genesis blocknum_of_blocks_to_add = 20# Add blocks to the chainfor i in range(0, num_of_blocks_to_add):  block_to_add = next_block(previous_block)  blockchain.append(block_to_add)  previous_block = block_to_add  # Tell everyone about it!  print "Block #{} has been added to the blockchain!".format(block_to_add.index)  print "Hash: {}\n".format(block_to_add.hash)

 
Let’s test what we’ve made so far.
我們來測試一下已有成果。


There we go! Our blockchain works. If you want to see more information in the console, you could edit the complete source file and print each block’s timestamp or data.
我去!我們的區塊鏈生效了!如果要在控制台中查看更多資訊,可以編輯完整的源檔案並列印每個塊的時間戳記或資料。

That’s about all that SnakeCoin has to offer. To make SnakeCoin scale to the size of today’s production blockchains, we’d have to add more features like a server layer to track changes to the chain on multiple machines and a proof-of-work algorithm to limit the amount of blocks added in a given time period.
那就是SnakeCoin所提供的一切。為了使SnakeCoin縮小到當今生產塊鏈的大小,我們必須添加更多的功能,如伺服器層,以跟蹤多台機器上鏈的變化,並提供工作證明演算法,以在給定時間段限制塊鏈數量。

If you’d like to get more technical, you can view the original Bitcoin whitepaper here. Best of luck and happy hacking!
如果您想獲得更多技術細節,您可以查看原始的比特幣白皮書。 祝好運!

Thank you very much for reading!
感謝閱讀!

 

英文原文:https://dev.to/aunyks/lets-build-the-tiniest-blockchain
原創翻譯:http://www.cnblogs.com/fangbei/

 

50行Python代碼構建小型區塊鏈

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.