The blockchain application uses PubNub for real-time peer-to-peer communication between nodes. PubNub enables the publish/subscribe pattern that allows blockchain nodes to:
- Broadcast newly mined blocks to all peers
- Share transactions across the network
- Synchronize blockchain state in real-time
-
Create a PubNub Account
- Visit https://www.pubnub.com/
- Sign up for a free account (no credit card required)
-
Create a New App
- Once logged in, click "Create New App"
- Give it a name like "python-blockchain"
-
Get Your Keys
- You'll see two important keys:
- Publish Key - Used to send messages to channels
- Subscribe Key - Used to receive messages from channels
- Keep these keys handy!
- You'll see two important keys:
-
Copy the secrets template:
cp env.example .env
-
Edit secrets.env and add your keys:
PUBNUB_PUBLISH_KEY=pub-c-your-actual-publish-key PUBNUB_SUBSCRIBE_KEY=sub-c-your-actual-subscribe-key PUBNUB_USER_ID=blockchain-node-1
The backend/pubsub.py file now reads configuration from environment variables.
When running multiple nodes, ensure each has a unique PUBNUB_USER_ID:
# Node 1 (main)
export PUBNUB_USER_ID=blockchain-node-1
python3 -m backend.app
# Node 2 (peer) - in a different terminal
export PUBNUB_USER_ID=blockchain-node-2
export PEER=True
export PEER_PORT=5001
python3 -m backend.app
# Node 3 (seeded) - in another terminal
export PUBNUB_USER_ID=blockchain-node-3
export PEER=True
export SEED_DATA=True
export PEER_PORT=5002
python3 -m backend.appEach node should have a unique user_id:
blockchain-node-1- Main nodeblockchain-peer-1- Peer nodeblockchain-seed-1- Seeded node
You can monitor real-time activity in the PubNub dashboard:
- Log in to https://admin.pubnub.com/
- Select your app
- Go to "Debug Console"
- Subscribe to your channels to see messages in real-time
This is useful for:
- Debugging connection issues
- Monitoring message flow
- Verifying blockchain synchronization
The blockchain application uses the following channels:
BLOCK- Broadcasts newly mined blocks to all nodesTRANSACTION- Shares new transactions across the networkTEST- Used for testing connectivity (development only)
-
Get your PubNub keys:
- Sign up at https://www.pubnub.com/
- Create a new app
- Copy your Publish and Subscribe keys
-
Configure your environment:
# Copy the example file cp env.example .env # Edit .env with your actual keys nano .env
-
Run the application:
python3 -m backend.app
To test blockchain synchronization with multiple nodes:
# Terminal 1 - Main node
export PUBNUB_USER_ID=node-1
python3 -m backend.app
# Terminal 2 - Peer node
export PUBNUB_USER_ID=peer-1
export PEER=True
export PEER_PORT=5001
python3 -m backend.app