区块链的介绍

这个up主我超级喜欢 ,喜欢的也可以去关注一波

利用python实现区块链

视频中的up主通过js实现了一个区块链,觉得挺有意思的。于是自己也手撸了一个,没啥难度的

import hashlib

def sha256(dataNeedSha):
    sha256 = hashlib.sha256()
    sha256.update(dataNeedSha.encode('utf-8'))
    return sha256.hexdigest()

# 区块
class Block:
    def __init__(self, data, previousHash):
        self.data = data
        self.previousHash = previousHash
        self.hash = self.ComputeHash

    @property
    def ComputeHash(self):
        return str(sha256(self.data))

    def showBlock(self):
        print ({'data':self.data, 'previousHash': self.previousHash, 'hash': self.hash})


# 链
class Chain:
    def __init__(self):
        self.chain = [self.ancestorBlock]

    @property
    def ancestorBlock(self):
        ancestor_block = Block('祖先区块', '')
        return ancestor_block

    @property
    def getLatestBlock(self):
        return self.chain[len(self.chain) - 1]

    def addBlockToChain(self, newBlock):
        newBlock.previousHash = self.getLatestBlock.hash
        newBlock.hash = newBlock.ComputeHash
        self.chain.append(newBlock)

    def showChain(self):
        for i in self.chain:
            i.showBlock()

    def validateChain(self):
        if len(self.chain) == 1:
            if self.chain[0].hash != self.chain[0].ComputeHash:
                return False
            return True

        for i in range(1,len(self.chain)):
            blockToValidate = self.chain[i]
            if (blockToValidate.hash) != blockToValidate.ComputeHash:
                print('数据被篡改')
                return False
            previousBlock = self.chain[i-1]
            if blockToValidate.previousHash != previousBlock.hash:
                print('前后区块链接断裂')
                return False
        return True

block1 = Block('转账10', '')
block2 = Block('转账20', '')
bitChain = Chain()
bitChain.addBlockToChain(block1)
bitChain.addBlockToChain(block2)


# 尝试篡改区块
bitChain.chain[1].data = '转账500'
# 尝试修正hash
bitChain.chain[1].hash = bitChain.chain[1].ComputeHash
bitChain.showChain()
print(bitChain.validateChain())

最后

这个代码当然和生产环境的区块链的难度还是差了很多的,不过这就是它的一个大体的思想,还是很有意思的
GitHub stars

版权声明:本文为原创文章,版权归 heroyf 所有
本文链接: https://www.heroyf.club/2019/12/08/pythonblockchain/


“苹果是给那些为了爱选择死亡的人的奖励”