python区块链的开发

至此,已经完成了:交易记录,区块的开发,现在进行区块链的开发就比较容易了。实现代码如下:

from Block import InvalidBlock, Block
from Message import InvalidMessage, DaDaMessage

from Transaction import Transaction

# 区块链
class Dada_BlockCoin:
    def __init__(self):
        self.blocklist = []  # 装载所有区块

    def validate(self):#校验所有区块
        for i, block in enumerate(self.blocklist):
            try:
                block.validate()
            except InvalidBlockCoin as e:
                raise InvalidBlockCoin("区块校验错误,区块索引{}".format(i))

    def add_block(self, block):  # 增加区块
        if len(self.blocklist) > 0:
            block.link(self.blocklist[-1])  #连接区块
        block.seal()#密封
        block.validate()#校验
        self.blocklist.append(block)#添加到区块链中


    def __repr__(self):
        return "Dada_BlockCoin:{}".format(len(self.blocklist))

自定义异常:


class InvalidBlockCoin(Exception):
    def __init__(self, *args, **kwargs):
        super(Exception, self).__init__(*args, **kwargs)

编写测试模块:


if __name__ == "__main__":
    t1 = Transaction("yicheng", "ddd1", 100)
    t2 = Transaction("yicheng", "ddd2", 200)
    t3 = Transaction("yicheng", "ddd3", 300)
    t4 = Transaction("yicheng", "ddd4", 400)
    t5 = Transaction("yicheng", "ddd5", 500)
    t6 = Transaction("yicheng", "ddd6", 600)

    m1 = DaDaMessage(t1)
    m2 = DaDaMessage(t2)
    m3 = DaDaMessage(t3)
    m4 = DaDaMessage(t4)
    m5 = DaDaMessage(t5)
    m6 = DaDaMessage(t6)
    try:

        yin1 = Block(m1, m2)
        yin1.seal()
        yin2 = Block(m3, m4)
        yin2.seal()
        yin3 = Block(m5, m6)
        yin3.seal()

        # 篡改区块
        #yin3.messagelist.append(m1)

        coin = Dada_BlockCoin()  # 区块链
        coin.add_block(yin1)
        coin.add_block(yin2)
        coin.add_block(yin3)

        coin.validate()
        print(coin)
    except InvalidMessage as e:
        print(e)
    except InvalidBlock as e:
        print(e)
    except InvalidBlockCoin as e:
        print(e)

测试结果如下:
这里写图片描述
篡改区块链,测试模块区块链的内容,可以任意篡改,测试结果如下:
这里写图片描述
这里已经完成了数据层的部分开发,其余部分后续会完善。
喜欢区块链技术的小伙伴,欢迎加群加群交流学习:
区块链技术交流群

相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页