import hashlib
import time

class Block:
    def __init__(self, index, prev_hash, data, nonce=0):
        self.index = index
        self.prev_hash = prev_hash
        self.timestamp = int(time.time())
        self.data = data
        self.nonce = nonce
        self.hash = self.calculate_hash()

    def calculate_hash(self):
        s = f"{self.index}{self.prev_hash}{self.timestamp}{self.data}{self.nonce}"
        return hashlib.sha256(s.encode()).hexdigest()


class Blockchain:
    def __init__(self):
        self.chain = [Block(0, "0", "Genesis Block")]
        self.difficulty = 2

    def mine_block(self, data):
        block = Block(len(self.chain), self.chain[-1].hash, data)

        while not block.hash.startswith("0" * self.difficulty):
            block.nonce += 1
            block.hash = block.calculate_hash()

        self.chain.append(block)

    def is_valid(self):
        for i in range(1, len(self.chain)):
            block = self.chain[i]
            previous = self.chain[i - 1]

            if (block.hash != block.calculate_hash() or
                block.prev_hash != previous.hash or
                not block.hash.startswith("0" * self.difficulty)):
                return False

        return True


def resolve_conflicts(node1, node2):
    longer = node1 if len(node1.chain) >= len(node2.chain) else node2

    if not longer.is_valid():
        print("Selected chain is invalid!")
        return False

    if longer != node1:
        node1.chain = list(node2.chain)
        print("Node 2's chain is chosen (longer) and adopted by Node 1.")
    else:
        print("Node 1's chain is chosen (longer or equal).")

    return True



node1 = Blockchain()
node2 = Blockchain()


print("Node 1 Mining Block 1...")
node1.mine_block("Node 1 - Block 1")

print("Node 2 Mining Block 1...")
node2.mine_block("Node 2 - Block 1")

print("Node 1 Mining Block 2...")
node1.mine_block("Node 1 - Block 2")

print("Node 2 Mining Block 2...")
node2.mine_block("Node 2 - Block 2")

print("\nResolving conflicts...")
resolve_conflicts(node1, node2)


for name, node in [("Node 1", node1), ("Node 2", node2)]:
    print(f"\n{name} Blockchain:")

    for block in node.chain:
        print(f"Block #{block.index} - Hash: {block.hash} - "
              f"Data: {block.data} - Nonce: {block.nonce}")

    print(f"Is {name}'s blockchain valid? {node.is_valid()}")