- Using the freshest Python 3 syntax
- UTXO model
- Nakamoto consensus, or PoW
- P2P part is powered by
asyncio
andkademlia
- Elliptic curve part is powered by
coincurve
Install dependencies first by running poetry install
.
Open 3 terminals and run separately:
python -m chain 8999 --mine --debug # block time is around 5s
python -m chain 9000 -b 127.0.0.1 8999 --debug # no mining
python -m chain 9001 -b 127.0.0.1 9000 --debug --mine # connecting second node
This repo is leveraging Kademlia algorithm for finding peers via UDP and syncing blockchain via TCP.
You can create a UDP server and a TCP server listening at the same port to simplify the logic. When it's found peers by Kademlia, our node just directly connects to that IP and port to start syncing blockchain data.
A simple example about syncing the latest block:
- Sending
REQUEST_LATEST_BLOCK
message to a peer or peers. - When receiving
REQUEST_LATEST_BLOCK
, send back the messageRECEIVE_LATEST_BLOCK
with block data. - When receiving
RECEIVE_LATEST_BLOCK
:- Check the received block is valid or not;
- If valid, add it to our blockchain and broadcast it to peers;
- Else, check if the block is ahead;
- If ahead, sending
REQUEST_BLOCKCHAIN
to peers and wait for the incoming blockchain data. - Else, which means our blockchain is the freshest, do nothing.
- If ahead, sending
For more details, check the p2p.py
code. The logic is simple, but more powerful protocols (like log replication of Raft protocol) are based on the simple ideas behind the implementation here.
Go check this and this to learn the basics and stay tuned with this repo!