Esempio n. 1
0
    def test_find_consensus(self):

        tester_node = Node("Tester")

        blockchain1 = Blockchain(diff_threshold=10, g_data="Fiat Lux!")
        blockchain2 = Blockchain(diff_threshold=7, g_data="Fiat Lux!")

        for i in range(100):
            tester_node.write_data(data=str(i), chain=blockchain1)

        for i in range(80):
            tester_node.write_data(data=str(i), chain=blockchain2)

        # Blockchain 2 has a higher difficulty threshold, thus it will have a
        # higher cumulative proof-of-work despite mining fewer blocks:
        self.assertFalse(blockchain2.find_consensus(blockchain1))
        self.assertTrue(blockchain1.find_consensus(blockchain2))
        self.assertEqual(blockchain1.get_last_block(),
                         blockchain2.get_last_block())
Esempio n. 2
0
                          node_addr=user.get_node_addr())

# Mine 100 blocks on the first chain and 80 blocks on the second chain:
for i in range(100):
    if i < 80: user.write_data(data=str(i), chain=second_chain)
    user.write_data(data=str(i), chain=first_chain)

print(
    f"Last Block ID of first chain (before consensus): {first_chain.get_last_block().get_block_id()}"
)
print(
    f"Last Block ID of second chain (before consensus): {second_chain.get_last_block().get_block_id()}\n"
)

print("Finding consensus...\n")

# Even though there are more blocks in the first chain,
# the ledger of this chain will be replaced by the second ledger.
# This is because the second chain has a higher cumulative proof-of-work,
# since the difficulty is raised more often:
if not second_chain.find_consensus(f_chain=first_chain):
    first_chain.find_consensus(f_chain=second_chain)
""" We've found the consensus and brought both chains into the same state! """

print(
    f"Last Block ID of first chain (after consensus): {first_chain.get_last_block().get_block_id()}"
)
print(
    f"Last Block ID of second chain (after consensus): {second_chain.get_last_block().get_block_id()}"
)