[Python] How to simulate P2P nodes and a double-spending attack in a Flask-based blockchain?

Discussão em 'Python' iniciado por Stack, Julho 16, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working on a simple blockchain simulation using Python and Flask, mainly to understand how double-spending attacks and fork resolution work. Each node is a separate Flask app instance running on a different port. Nodes communicate by sending HTTP requests to each other (e.g., /receive_transaction, /receive_block), which works fine for basic transaction propagation and mining. Now I want to simulate a scenario where one node acts maliciously by:

    • Withholding blocks it mines (creating a private chain)
    • Later broadcasting its longer chain to override the public one
    • Causing a double-spend by including conflicting transactions

    I have basic Proof-of-Work and transaction validation working, but

    I’m not sure how to properly implement:

    • The attack logic: How to delay the attacker’s broadcast?
    • P2P simulation: How to make communication between nodes feel more realistic in Flask?
    • Hash rate simulation: Any ideas on modeling a higher mining power for the attacker node?

    Is Flask even the right tool to simulate P2P behavior in this case, or should I use sockets/async instead? Any pointers or suggestions would be appreciated.

    I set up multiple Flask apps running on different ports to act as individual nodes. Each node can receive and forward transactions or blocks via HTTP requests. I expected this to mimic basic P2P behavior, and it works for broadcasting single transactions or mined blocks.

    For the attack simulation, I created an "attacker" node that mines its own private chain and delays broadcasting. I expected that when it broadcasts the longer chain later, it would override the public chain on other nodes. But it doesn't always work as expected — sometimes nodes don’t accept the longer chain, or the synchronization between nodes becomes inconsistent.

    I'm trying to find a more reliable or realistic way to simulate this fork and override behavior.

    Continue reading...

Compartilhe esta Página