如何从0构建区块链之三

区块链
由于我们正在构建一个分类帐DEMO,因此让我们远离将来将涉及的复杂术语和机制。我将使用注释符号(#)来解释每一行代码,记住#之后的所有内容都是注释。

[[388228]]

在前2集中,我们使用Go和Javascript构建了两个基本DEMO,传送门:

Go:区块链研究实验室 | 如何从0构建区块链(一)

Javascript:区块链研究实验室 | 如何从0构建区块链(二)

现在让我们使用Python来构建另一个分类帐DEMO,这是增长最快且最受欢迎的编程语言之一。

回顾一下,一个区块链是一个区块链,每个区块包含图1中列出的一些信息。由于我们正在构建一个分类帐DEMO,因此让我们远离将来将涉及的复杂术语和机制。我将使用注释符号(#)来解释每一行代码,记住#之后的所有内容都是注释。

我们开始吧!

让我们先导入两个重要的库:

  1. # Start 
  2. import datetime as d # import the datetime library for our block timestamp and rename it as d for simplicity while typing  
  3. import hashlib as h # import the library for hashing our block data and rename it as h for simplicity while typing  

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

创建一个名为Block的类:

  1. class Block: # create a class called Block 
  2.     def __init__(self,index,timestamp,data ,prevhash): # declare an initial method that defines a block, a block contains the following information 
  3.         self.index = index # a block contains an ID 
  4.         self.timestamp =timestamp # a block contains a timestamp 
  5.         self.data = data # a block contains some transactions 
  6.         self.prevhash =prevhash # a block contains a hash of the previous block 
  7.         self.hash =self.hashblock() # a block contains a hash, the hash is obtained by hashing all the data contained in the block 

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

  1. def hashblock (self): # define a method for data encryption, this method will retain a hash of the block 
  2.         block_encryption=h.sha256() # We need a sha256 function to hash the content of the block, so let's declare it here 
  3.         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 
  4.         return block_encryption.hexdigest() # let's return that hash result 

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

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

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

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

制作区块并创建新的区块方法,现在我们需要初始化区块链以接收所有传入的区块。

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

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

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

结果如下:

编号为1的区块具有创世区块的哈希值,该哈希值未在我们的区块链中显示,由我们决定是否显示创世区块,让我向您展示如何打印其内容。在之前for loop,添加以下行:

  1. # let's print the genesis block information 
  2. print"Block ID :{} ".format(prevblock.index)  
  3. print"Timestamp:{}".format(prevblock.timestamp
  4. print"Hash of the block:{}".format(prevblock.hash) 
  5. print"Previous Block Hash:{}".format(prevblock.prevhash) 
  6. print"data:{}\n".format(prevblock.data) 

这是最终结果:

现在,创始块在分类帐中变得可见。

恭喜你!您刚刚使用Python创建了另一个区块链DEMO。

保持关注下一个高级概念??。

整个代码:

  1. # Start 
  2. import datetime as d # import the datetime library for our block timestamp and rename it as d for simplicity while typing  
  3. import hashlib as h # import the library for hashing our block data and rename it as h for simplicity while typing  
  4.  
  5.  
  6. class Block: # create a Block class 
  7.     def __init__(self,index,timestamp,data ,prevhash): # declare an initial method that defines a block, a block contains the following information 
  8.         self.index = index # a block contains an ID 
  9.         self.timestamp =timestamp # a block contains a timestamp 
  10.         self.data = data # a block contains some transactions 
  11.         self.prevhash =prevhash # a block contains a hash of the previous block 
  12.         self.hash =self.hashblock() # a block contains a hash, the hash is obtained by hashing all the data contained in the block 
  13.  
  14.     def hashblock (self): # define a method for data encryption, this method will retain a hash of the block 
  15.         block_encryption=h.sha256() # We need a sha256 function to hash the content of the block, so let's declare it here 
  16.         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 
  17.         return block_encryption.hexdigest() # let's return that hash result  
  18.      
  19.     @staticmethod # declaring a static method for the genesis block 
  20.     def genesisblock(): # delcare a function for generating the first block named genesis 
  21.         return Block(0,d.datetime.now(),"genesis block transaction"," ") # return the genesis block 
  22.      
  23.     @staticmethod# let's declare another static method to get the next block 
  24.     def newblock(lastblock): # get the next block, the block that comes after the previous block (prevblock+1) 
  25.         index = lastblock.index+1 # the id of this block will be equals to the previous block + 1, which is logic 
  26.         timestamp = d.datetime.now() # The timestamp of the next block 
  27.         hashblock = lastblock.hash # the hash of this block 
  28.         data = "Transaction " +str(index) # The data or transactions containing in that block 
  29.         return Block(index,timestamp,data,hashblock)# return the entire block 
  30.  
  31. blockchain = [Block.genesisblock()] # now it's time to initialize our blockchain with a genesis block in it 
  32. prevblock = blockchain[0] # the previous block is the genesis block itself since there is no block that comes before it at the indice 0  
  33.  
  34. # let's print the genesis block information 
  35. print"Block ID :{} ".format(prevblock.index)  
  36. print"Timestamp:{}".format(prevblock.timestamp
  37. print"Hash of the block:{}".format(prevblock.hash) 
  38. print"Previous Block Hash:{}".format(prevblock.prevhash) 
  39. print"data:{}\n".format(prevblock.data) 
  40.  
  41.  
  42. 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 
  43.     addblock = Block.newblock(prevblock) #  the block to be added to our chain  
  44.     blockchain.append(addblock) # we add that block to our chain of blocks 
  45.     prevblock =addblock #now the previous block becomes the last block so we can add another one if needed 
  46.  
  47.     print"Block ID #{} ".format(addblock.index) # show the block id 
  48.     print"Timestamp:{}".format(addblock.timestamp)# show the block timestamp 
  49.     print"Hash of the block:{}".format(addblock.hash)# show the hash of the added block 
  50.     print"Previous Block Hash:{}".format(addblock.prevhash)# show the previous block hash 
  51.     print"data:{}\n".format(addblock.data)# show the transactions or data contained in that block 
  52.  
  53.  
  54.     # end  

 

责任编辑:武晓燕 来源: 区块链研究实验室
相关推荐

2021-03-16 21:39:47

区块链DEMOGo

2021-03-12 19:17:38

区块链GoPython

2018-05-23 15:20:08

区块链数字货币比特币

2019-11-19 09:13:08

区块链金融去中心化

2021-04-16 20:43:18

Go区块链编程

2021-12-22 23:28:04

区块链人工智能技术

2021-02-26 10:28:24

区块链数字货币金融

2018-03-19 19:30:19

2021-09-23 22:40:10

区块链比特币技术

2018-03-27 09:52:30

区块链数字货币比特币

2019-10-29 15:46:07

区块链区块链技术

2018-01-23 11:09:04

区块链技术重用

2021-03-14 10:21:36

数据库区块链DNS

2022-10-18 08:00:00

2021-05-10 15:09:47

区块链互联网金融

2021-03-16 14:33:12

区块链比特币加密货币

2022-04-18 14:50:00

区块链安全交易

2018-05-06 16:17:01

2021-04-11 11:31:05

区块链记账比特币

2021-04-12 10:57:28

区块链信任银行
点赞
收藏

51CTO技术栈公众号