區塊鏈研究實驗室 | 如何從0構建區塊鏈(三)

買賣虛擬貨幣

在前2集中,我們使用Go和Javascript構建了兩個基本DEMO,傳送門:

Go:區塊鏈研究實驗室 | 如何從0構建區塊鏈(一)

Javascript:區塊鏈研究實驗室 | 如何從0構建區塊鏈(二)

現在讓我們使用Python來構建另一個分類帳DEMO,這是增長最快且最受歡迎的程式語言之一。

回顧一下,一個區塊鏈是一個區塊鏈,每個區塊包含圖1中列出的一些資訊。由於我們正在構建一個分類帳DEMO,因此讓我們遠離將來將涉及的複雜術語和機制。我將使用註釋符號(#)來解釋每一行程式碼,記住#之後的所有內容都是註釋。

我們開始吧!

讓我們先匯入兩個重要的庫:

    # Startimport datetime as d # import the datetime library for our block timestamp and rename it as d for simplicity while typing import hashlib as h # import the library for hashing our block data and rename it as h for simplicity while typing 

    這兩個庫用於對生成的每個塊進行雜湊處理和加時間戳。

    建立一個名為Block的類:

      classBlock: # create a class called Blockdef__init__(self,index,timestamp,data ,prevhash): # declare an initial method that defines a block, a block contains the following informationself.index = index # a block contains an IDself.timestamp =timestamp # a block contains a timestampself.data = data # a block contains some transactionsself.prevhash =prevhash # a block contains a hash of the previous blockself.hash =self.hashblock() # a block contains a hash, the hash is obtained by hashing all the data contained in the block

      此類具有一個包含所有塊資訊的初始方法,但是沒有任何方法返回塊雜湊,因此讓我們繼續在Block類下建立它。

        defhashblock(self): # define a method for data encryption, this method will retain a hash of the block block_encryption=h.sha256() # We need a sha256 function to hash the content of the block, so let's declare it here block_encryption.update(str(self.index)+str(self.timestamp)+str(self.data)+str(self.prevhash)) # to encrypt the data in the block, We need just to sum everything and apply the hash function on itreturn block_encryption.hexdigest() # let's return that hash result

        部署區塊鏈時,它只有一個區塊,即有史以來的第一個區塊,第一個區塊稱為創世區塊,以下所有區塊將被新增到第一個區塊之上,因此讓我們建立一個靜態方法,該方法將返回起源塊。

           @staticmethod # declaring a static method for the genesis blockdefgenesisblock(): # this method is for generating the first block named genesis blockreturn Block(0,d.datetime.now(),"genesis block transaction"," "# return the genesis block

          每個塊之後是下一個塊,下一個塊是鏈上最近新增的塊,我們必須宣告另一個靜態方法來返回每個新塊,讓我們建立它。

             @staticmethod# let's declare another static method to get the next block def newblock(lastblock): # get the next block, the block that comes after the previous block (prevblock+1)index = lastblock.index+1# the id of this block will be equals to the previous block + 1, which is logic timestamp = d.datetime.now() # The timestamp of the next block hashblock = lastblock.hash # the hash of this block data = "Transaction " +str(index) # The data or transactions containing in that blockreturn Block(index,timestamp,data,hashblock)# return the entire block

            製作區塊並建立新的區塊方法,現在我們需要初始化區塊鏈以接收所有傳入的區塊。

              blockchain = [Block.genesisblock()] # now it's time to initialize our blockchain with a genesis block in itprevblock = blockchain[0] # the previous block is the genesis block itself since there is no block that comes before it at the indice 0 

              鏈上只有創世塊,讓我們向分類賬中新增更多塊並進行列印。

                for i in range (0,5): # the loop starts from here, we will print 5 blocks, this number can be increased if needed addblock = Block.newblock(prevblock) # the block to be added to our chain  blockchain.append(addblock) # we add that block to our chain of blocks prevblock =addblock #now the previous block becomes the last block so we can add another one if needed
                print"Block ID #{} ".format(addblock.index) # show the block idprint"Timestamp:{}".format(addblock.timestamp)# show the block timestampprint"Hash of the block:{}".format(addblock.hash)# show the hash of the added blockprint"Previous Block Hash:{}".format(addblock.prevhash)# show the previous block hashprint"data:{}\n".format(addblock.data)# show the transactions or data contained in that block

                # end

                結果如下:

                編號為1的區塊具有創世區塊的雜湊值,該雜湊值未在我們的區塊鏈中顯示,由我們決定是否顯示創世區塊,讓我向您展示如何列印其內容。在之前for loop,新增以下行:

                  # let's print the genesis block informationprint"Block ID :{} ".format(prevblock.index) print"Timestamp:{}".format(prevblock.timestamp)print"Hash of the block:{}".format(prevblock.hash)print"Previous Block Hash:{}".format(prevblock.prevhash)print"data:{}\n".format(prevblock.data)

                  這是最終結果:

                  現在,創始塊在分類帳中變得可見。

                  恭喜你!您剛剛使用Python建立了另一個區塊鏈DEMO。

                  保持關注下一個高階概念。

                  整個程式碼:

                    # Startimport datetime as d # import the datetime library for our block timestamp and rename it as d for simplicity while typing import hashlib as h # import the library for hashing our block data and rename it as h for simplicity while typing 

                    classBlock: # create a Block classdef__init__(self,index,timestamp,data ,prevhash): # declare an initial method that defines a block, a block contains the following informationself.index = index # a block contains an IDself.timestamp =timestamp # a block contains a timestampself.data = data # a block contains some transactionsself.prevhash =prevhash # a block contains a hash of the previous blockself.hash =self.hashblock() # a block contains a hash, the hash is obtained by hashing all the data contained in the block
                    defhashblock(self): # define a method for data encryption, this method will retain a hash of the block block_encryption=h.sha256() # We need a sha256 function to hash the content of the block, so let's declare it here block_encryption.update(str(self.index)+str(self.timestamp)+str(self.data)+str(self.prevhash)) # to encrypt the data in the block, We need just to sum everything and apply the hash function on itreturn block_encryption.hexdigest() # let's return that hash result @staticmethod # declaring a static method for the genesis blockdefgenesisblock(): # delcare a function for generating the first block named genesisreturn Block(0,d.datetime.now(),"genesis block transaction"," ") # return the genesis block @staticmethod# let's declare another static method to get the next blockdefnewblock(lastblock): # get the next block, the block that comes after the previous block (prevblock+1) index = lastblock.index+1# the id of this block will be equals to the previous block + 1, which is logic timestamp = d.datetime.now() # The timestamp of the next block hashblock = lastblock.hash # the hash of this block data = "Transaction " +str(index) # The data or transactions containing in that blockreturn Block(index,timestamp,data,hashblock)# return the entire block
                    blockchain = [Block.genesisblock()] # now it's time to initialize our blockchain with a genesis block in itprevblock = blockchain[0] # the previous block is the genesis block itself since there is no block that comes before it at the indice 0
                    # let's print the genesis block informationprint"Block ID :{} ".format(prevblock.index) print"Timestamp:{}".format(prevblock.timestamp)print"Hash of the block:{}".format(prevblock.hash)print"Previous Block Hash:{}".format(prevblock.prevhash)print"data:{}\n".format(prevblock.data)

                    for i in range (0,5): # the loop starts from here, we will need only 5 blocks in our ledger for now, this number can be increased addblock = Block.newblock(prevblock) # the block to be added to our chain blockchain.append(addblock) # we add that block to our chain of blocks prevblock =addblock #now the previous block becomes the last block so we can add another one if needed
                    print"Block ID #{} ".format(addblock.index) # show the block id print"Timestamp:{}".format(addblock.timestamp)# show the block timestamp print"Hash of the block:{}".format(addblock.hash)# show the hash of the added block print"Previous Block Hash:{}".format(addblock.prevhash)# show the previous block hash print"data:{}\n".format(addblock.data)# show the transactions or data contained in that block

                    # end 

                    作者:鏈三豐,來源:區塊鏈研究實驗室

                    免責聲明:

                    1. 本文版權歸原作者所有,僅代表作者本人觀點,不代表鏈報觀點或立場。
                    2. 如發現文章、圖片等侵權行爲,侵權責任將由作者本人承擔。
                    3. 鏈報僅提供相關項目信息,不構成任何投資建議

                    推荐阅读

                    ;