当前位置: 首页 > 科技观察

如何从0开始构建区块链

时间:2023-03-17 16:55:20 科技观察

前2集,我们使用Go和Javascript构建了两个基础DEMO,传送门:Go:区块链研究实验室|如何从0(1)Javascript构建区块链:区块链研究实验室|如何从0开始构建区块链(二)现在让我们使用Python构建另一个账本DEMO,它是发展最快、最流行的编程语言之一。回顾一下,区块链是一连串的块,其中每个块都包含图1中列出的一些信息。由于我们正在构建分类帐DEMO,因此让我们摆脱将来会涉及的复杂术语和机制。我将使用注释符号(#)来解释每一行代码,记住#之后的所有内容都是注释。让我们开始吧!让我们从导入两个重要的库开始:#Startimportdatetimeasd#importthedatetimelibraryforourblocktimestampandrenameitasdforsimplicitywhiletypingimporthashlibash#importthelibraryforhashingourblockdataandrenameitashforsimplicitywhiletyping这两个库用于对生成的每个块进行哈希和时间戳。创建一个名为Block的类:)#ablockcontainsahash,thehashisobtainedbyhashingallthedatacontainedintheblock这个类有一个包含所有区块信息的初始方法,但是没有返回区块哈希的方法,所以我们继续在Block类下创建。defhashblock(self):#definemethodfordataencryption,thismethodwillretainahashoftheblockblock_encryption=h.sha256()#Weneedasha256functiontohashthecontentsoftheblock,solet'sdeclareeithereblock_encryption.update(str(self.index)+str(self.timestamp.vv)+prehself(strself))#toencrypttheblock中的数据,我们需要在块中加密数据,我们需要在它的函数上加密。hexdigest()#let'sreturnthathashresult部署区块链时,它只有一个块,第一个块,第一个块称为创世块,以下所有块将添加在第一个块之上,所以让我们创建一个静态返回创世块的方法。@staticmethod#declaringastaticmethodforthegenesisblockdefgenesisblock():#thismethoddisforgeneratingthefirstblocknamedgenesisblockreturnBlock(0,d.datetime.now(),"genesisblocktransaction","")#returnthegenesisblock每个块之后是下一个块,下一个块是链上最近添加的块,我们必须声明另一个静态方法来返回每个新块,让我们创建它。@staticmethod#let'sdeclareanotherstaticmethodtogetthenextblockdefnewblock(lastblock):#getthenextblock,thatcomesafterthepreviousblock(prevblock+1)index=lastblock.index+1#theidofthisblockwillbeequalstothepreviousblock+1,whichislogictimestamp=d.datetime.now()#Thetimestampofthenextblockhashblock=lastblock.hash#thehashofthisblockdata="Transaction"+str(index)#ThedataortransactionscontaininginthatblockreturnBlock(index,timestamp,data,hashblock)#returntheentireblock制作一个区块并创建一个新区块的方法,现在我们需要初始化区块链以接收所有传入的区块。blockchain=[Block.genesisblock()]#nowit'stimetoinitializeourblockchainwithgenesisblockinitprevblock=blockchain[0]#thepreviousblockisthegenesisblockitselfsincethereisnoblockthatcomesbeforeitattheindice0链上只有创世块,让我们添加更多块到账本并打印出来。foriinrange(0,5):#theloopstartsfromhere,wewillprint5blocks,thisnumbercanbeincreasedifneededaddblock=Block.newblock(prevblock)#theblocktobeaddedtoourchainblockchain.append(addblock)#weaddthatblocktoourchainofblocksprevblock=addblock#nowthepreviousblockbecomesthelastblocksowecanaddanotheroneifneededprint"BlockID#{}".格式#addblock.index)":{}".format(addblock.timestamp)#showtheblocktimestampprint"Hashoftheblock:{}".format(addblock.hash)#showthehashofthaddedblockprint"PreviousBlockHash:{}".format(addblock.prevhash)#showthepreviousblockhashprint"data:{}\n".format(addblock.data)#showthetransactionsordatacontainedinthatblock#end结果如下:1号区块有创世块的哈希值,我们的区块链中没有显示,由我们来显示创世块,让我向您展示如何打印其内容。在for循环之前,添加以下行:#let'sprintthegenesisblockinformationprint"BlockID:{}".format(prevblock.index)print"Timestamp:{}".format(prevblock.timestamp)print"Hashoftheblock:{}".format(prevblock.hash)print"PreviousBlockHash:{}".format(prevblock.prevhash)print"data:{}\n".format(prevblock.data)这是最终结果:账本。恭喜!您刚刚使用Python创建了另一个区块链DEMO。请继续关注下一个高级概念??。整个代码:#Startimportdatetimeasd#importthedatetimelibraryforourblocktimestampandrenameitasdforsimplicitywhiletypingimporthashlibash#importthelibraryforhashingourblockdataandrenameitashforsimplicitywhiletypingclassBlock:#createaBlockclassdef__init__(self,index,timestamp,data,prevhash):#declareaninitialmethodthatdefinesablock,ablockcontainsthefollowinginformationself.index=index#ablockcontainsanIDself.timestamp=timestamp#ablockcontainsatimestampself.data=data#ablockcontainssometransactionsself.prevhash=prevhash#ablockcontainsahashofthepreviousblockself.hash=self.hashblock()#ablockcontainsahash,thehashisobtainedhashingallthedatacontainedintheblockdefhashblock(self):#definemethodfordataencryption,thismethodwillretainahashoftheblockblock_encryption=h.sha256()#Weneedasha256functiontohashthecontentoftheblock,让我们声明+self.reblock.reblock(stringrecryption.reblock)+str(self.data)+str(self.prevhash))#toencryptthedataintheblock,我们需要justtosumeverythingandapplythehashfunctiononitreturnblock_encryption.hexdigest()#let'sreturnthathathashresult@staticmethod#declaringastaticmethodforthegenesisblockdefgenesisblock():#delcareafunctionforgeneratingthefirstblocknamedgenesisreturnBlock(0,d.datetime.now(),"genesisblocktransaction","")#returnthegenesisblock@staticmethod#让我们声明另一个静态方法来获取新块#xtblock(xtblock),theblockthatcomesafterthepreviousblock(prevblock+1)index=lastblock.index+1#theidofthisblockwillbeequalstothepreviousblock+1,whichislogictimestamp=d.datetime.now()#Thetimestampofthenextblockhashblock=lastblock.hash#thehashofthisblockdata="Transaction"+str(index)#ThedataortransactionscontaininginthatblockreturnBlock(index,时间戳,数据,哈希块)#returntheentireblockblockchain=[Block.genesisblock()]#nowit'stimetoinitializeourblockchainwithgenesisblockinitprevblock=blockchain[0]#thepreviousblockisthegenesisblockitselfsincethereisnoblockthatcomesbeforeitattheindice0#let'sprintthegenesisblockinformationprint"BlockID:{}".format(prevblock.index)print"Timestamp:{}".format(prevblock.timestamp)print"Hashoftheblock:{}".format(prevblock.hash)print"PreviousBlockHash:{}".format(prevblock.prevhash)print"data:{}\n".format(prevblock.data)foriinrange(0,5):#theloopsfromhere,wewillneedonly5blocksinourledgerfornow,thisnumbercanbeincreasedaddblock=Block.newblock(prevblock)#theblocktobeaddedtoourchainblockchain.append(addblock)#weaddthatblocktoourchainofblocksprevblock=addblock#nowthepreviousblockbecomesthelastblocksowecanaddanotheroneifneededprint"BlockID#{}".format(addblock.index)#showtheblockidprint"Timestamp:{}".format(addblock.timestamp)#showtheblocktimestampprint"Hashoftheblock:{}".format(addblock.hash)#showthehashoftheaddedblockprint"PreviousBlockHash:{}".format(addblock.prevhash)#showthepreviousblockhashprint"data:{}\n".format(addblock.data)#showthetransactionsordatacontainedinthatblock#end