区块链研究实验室 | 如何从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 importhashlibash#importthelibraryforhashingourblockdataandrenameitashforsimplicitywhiletyping

这两个库用于对生成的每个块进行哈希处理和加时间戳。

创建一个名为Block的类:

class Block: # create a class called Block def __init__(self,index,timestamp,data ,prevhash): # declare an initial method that defines a block, a block contains the following information self.index = index # a block contains an ID self.timestamp =timestamp # a block contains a timestamp self.data = data # a block contains some transactions self.prevhash =prevhash # a block contains a hash of the previous blockself.hash=self.hashblock()#ablockcontainsahash,thehashisobtainedbyhashingallthedatacontainedintheblock

此类具有一个包含所有块信息的初始方法,但是没有任何方法返回块哈希,因此让我们继续在Block类下创建它。

 def hashblock (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 it return block_encryption.hexdigest() # let's return that hash result

部署区块链时,它只有一个区块,即有史以来的第一个区块,第一个区块称为创世区块,以下所有区块将被添加到第一个区块之上,因此让我们创建一个静态方法,该方法将返回起源块。

 @staticmethod # declaring a static method for the genesis block def genesisblock(): # this method is for generating the first block named genesis blockreturnBlock(0,d.datetime.now(),"genesisblocktransaction","")#returnthegenesisblock

每个块之后是下一个块,下一个块是链上最近添加的块,我们必须声明另一个静态方法来返回每个新块,让我们创建它。

 @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 block return 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]#thepreviousblockisthegenesisblockitselfsincethereisnoblockthatcomesbeforeitattheindice0

链上只有创世块,让我们向分类账中添加更多块并进行打印。

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 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的区块具有创世区块的哈希值,该哈希值未在我们的区块链中显示,由我们决定是否显示创世区块,让我向您展示如何打印其内容。在之前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 

class Block: # create a Block class def __init__(self,index,timestamp,data ,prevhash): # declare an initial method that defines a block, a block contains the following information self.index = index # a block contains an ID self.timestamp =timestamp # a block contains a timestamp self.data = data # a block contains some transactions self.prevhash =prevhash # a block contains a hash of the previous block self.hash =self.hashblock() # a block contains a hash, the hash is obtained by hashing all the data contained in the block
def hashblock (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 it return block_encryption.hexdigest() # let's return that hash result @staticmethod # declaring a static method for the genesis block def genesisblock(): # delcare a function for generating the first block named genesis return 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 block return 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

作者:链三丰,来源:区块链研究实验室

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。

留言与评论(共有 0 条评论)
   
验证码:
微信号已复制,请打开微信添加咨询详情!