This is a fork of the 'Learn Blockchains by Building One' project by dvf. Make sure to check out his blog post on the same.
I re-implemented the same functionality for learning purposes. Along the way I made some improvements over the original codebase:
- Use Python 3.10
- Better code structure
- Define Models for Block and Transaction instead of passing them around as raw dictionaries
- Function type-annotations
- Use FastAPI instead of Flask
- In our case, this mainly helps with easier request-response validation and auto generating the OpenAPI documentation.
- Make endpoints more RESTful
- For eg. /mine/ endpoint must be a POST operation since it changes the server state.
- Move all business logic to the service layer
- For eg. mining logic should reside in the Blockchain class instead of the endpoint function.
- Docker-compose file for spinning up multiple nodes at once
-
Make sure Python 3.10+ is installed.
-
Install pipenv.
$ pip install pipenv
-
Install requirements
$ pipenv install
-
Run some nodes:
$ pipenv run uvicorn src.node_server:app --port 8000
$ pipenv run uvicorn src.node_server:app --port 8001
Another option for running this program is to use Docker. Follow the instructions below to spawn two nodes.
-
Build the image
$ docker-compose build
-
Run 2 nodes
$ docker-compose up
-
To add more nodes, add more services to the docker-compose.yml
Tests can be run using pytest:
$ pipenv run pytest --cov=src
I made a note of some core blockchain features that are missing from this implementation. Interested readers can try working on these for a better understanding.
- Nodes using Public Key Infrastructure (such as for signing their transactions)
- Transaction Validation (person sending coins has the said amount or not?)
- Transaction Queuing (miners can work on transactions with a good payoff; at the same time the chain must make sure that no transactions starve)
- P2P communication between nodes
- Proof-of-Work Verification
- Mining difficulty proportional to remaining number of coins and the network's hash rate.
Contributions are welcome! Please feel free to submit a Pull Request.