def test_get_longest_chains_two_longest(storage, genesis): block1a = Block('Node0', 1, genesis) votes1a = [Vote(f'Node{i}', block1a) for i in range(3)] storage.add_block(block1a) [storage.add_vote(v) for v in votes1a] block1b = Block('Node1', 1, genesis) votes1b = [Vote(f'Node{i}', block1b) for i in range(3)] storage.add_block(block1b) [storage.add_vote(v) for v in votes1b] assert len(storage.get_longest_chains()) == 2
def test_get_longest_chains_new_longest(storage, genesis): block1 = Block('Node0', 1, genesis) votes1 = [Vote(f'Node{i}', block1) for i in range(3)] storage.add_block(block1) [storage.add_vote(v) for v in votes1] block2 = Block('Node0', 2, block1) votes2 = [Vote(f'Node{i}', block2) for i in range(3)] storage.add_block(block2) [storage.add_vote(v) for v in votes2] assert len(storage.get_longest_chains()) == 1 assert len(storage.get_longest_chains()[0]) == 3
def receive(self, message): """ Process received message. Args: message (Message): The incoming message """ if isinstance(message, Message) and message.verify(self.network): # Handle incoming blocks. if isinstance(message, Block): if not self.storage.contains(message): # 1. Re-braodcast the block and add it to storage. self.network.broadcast(self, message) self.storage.add_block(message) # 2. Decide whether to vote on the block. tips = [c[0] for c in self.storage.get_longest_chains()] hash_tips = [hash(b) for b in tips] if message.link in hash_tips: vote = Vote(self.name, message) self.log(f'Broadcasting vote: {vote}') self.network.broadcast(self, vote) # Handle incoming votes. elif isinstance(message, Vote): if not message.hash in self.storage.votes: self.network.broadcast(self, message) self.storage.add_vote(message) else: assert False # pragma: no cover else: assert False # pragma: no cover
def three_votes(block): return [Vote(i, block) for i in range(3)]
def vote(block): return Vote(0, block)
def test_get_longest_chains_incomplete(storage, block, genesis): block2 = Block('Node0', 2, block) votes2 = [Vote(f'Node{i}', block2) for i in range(3)] storage.add_block(block2) [storage.add_vote(v) for v in votes2] assert storage.get_longest_chains() == [[genesis]]
def test_vote_verify(vote, block, network): assert vote.verify(network) bad_vote = Vote('NodeX', block) assert not bad_vote.verify(network)
def test_vote_hash(vote, block): assert hash(vote) == hash(Vote(0, block)) assert hash(vote) != hash(Vote('NodeX', block))
def test_vote_eq(vote, block): assert vote == Vote(0, block) assert vote != Vote('NodeX', block)