docs: Add test runner and backend startup guides for blockchain integration

This commit is contained in:
Alexis Bruneteau 2025-11-07 03:01:59 +01:00
parent 1a42b4d83b
commit d4ce64f097
2 changed files with 731 additions and 0 deletions

View File

@ -0,0 +1,447 @@
# Backend Startup Guide
## Quick Start
```bash
# Start all services (database, backend, frontend)
docker compose up -d
# Wait for initialization (30-40 seconds)
sleep 40
# Verify backend is running
curl http://localhost:8000/health
# Should return:
# {"status": "ok", "version": "0.1.0"}
```
## What Happens on Startup
### 1. MariaDB Database Starts (10-20 seconds)
- Container starts
- Database initialized from `docker/init.sql`
- Creates tables: voters, elections, candidates, votes, audit_logs
- Inserts sample election and candidates
- Runs `docker/populate_past_elections.sql` (adds 10 past elections)
- Runs `docker/create_active_election.sql` (ensures election 1 is active)
### 2. Backend Starts (5-10 seconds)
- FastAPI application loads
- Database connection established
- **Blockchain initialization begins**:
- Loads all elections from database
- Records each to blockchain if not already recorded
- Verifies blockchain integrity
- Prints status: `✓ Blockchain integrity verified - N blocks`
- Backend ready to serve requests
### 3. Frontend Starts (5-10 seconds)
- Next.js application builds and starts
- Connects to backend API
## Startup Timeline
```
docker compose up -d
|
├─ MariaDB starts (10-20s)
│ ├─ init.sql runs (create tables)
│ ├─ populate_past_elections.sql runs (past data)
│ └─ create_active_election.sql runs (make election 1 active)
├─ Backend starts (5-10s)
│ ├─ FastAPI loads
│ ├─ Blockchain initialization starts
│ │ ├─ Load elections from DB
│ │ ├─ Record to blockchain
│ │ └─ Verify integrity
│ └─ Backend ready
└─ Frontend starts (5-10s)
└─ Next.js ready
Total startup time: 30-45 seconds
```
## Status Checks
### Check All Services
```bash
docker compose ps
```
Expected:
```
NAME STATUS PORTS
evoting_mariadb healthy (running)
evoting_backend healthy (running) 127.0.0.1:8000->8000/tcp
evoting_frontend healthy (running) 127.0.0.1:3000->3000/tcp
evoting_adminer healthy (running) 127.0.0.1:8081->8080/tcp
```
### Check Backend Health
```bash
curl http://localhost:8000/health
```
Expected:
```json
{"status": "ok", "version": "0.1.0"}
```
If you get `502 Bad Gateway`:
- Backend is still starting
- Wait another 10-20 seconds
- Try again
### Check Database Health
```bash
# Connect to database
docker compose exec mariadb mariadb -u evoting_user -pevoting_pass123 evoting_db
# Query elections
MariaDB [evoting_db]> SELECT id, name, is_active FROM elections LIMIT 5;
# Expected: Election 1 should be active with recent dates
```
### Check Blockchain Initialization
```bash
# View backend logs
docker compose logs backend | grep -i blockchain
# Should show:
# ✓ Recorded election 1 (Election Présidentielle 2025) to blockchain
# ✓ Blockchain integrity verified - 1 blocks
```
## Common Startup Issues
### Issue 1: 502 Bad Gateway on All Endpoints
**Cause**: Backend is still initializing
**Solution**:
```bash
# Wait longer
sleep 30
# Check if backend is up
curl http://localhost:8000/health
# If still 502, check logs
docker compose logs backend | tail -50
```
### Issue 2: Database Won't Start
**Symptoms**:
```bash
docker compose logs mariadb
# Error: "InnoDB: Specified key was too long"
# or: "Address already in use"
```
**Solutions**:
Option A - Different port:
```bash
# Stop and remove containers
docker compose down
# Change port in docker-compose.yml:
# mariadb:
# ports:
# - "3307:3306" # Changed from 3306
docker compose up -d
```
Option B - Fresh database:
```bash
# Remove database volume
docker compose down -v
# Start fresh
docker compose up -d
sleep 40
```
### Issue 3: Backend Import Errors
**Symptoms**:
```bash
docker compose logs backend
# ModuleNotFoundError: No module named 'blockchain_elections'
# or: ImportError: cannot import name 'initialize_elections_blockchain'
```
**Solution**:
```bash
# Rebuild backend with new modules
docker compose down
docker compose up -d --build backend
sleep 40
```
### Issue 4: Port Already in Use
**Symptoms**:
```bash
docker compose up -d
# Error: "bind: address already in use"
```
**Solution**:
```bash
# Kill the process using the port
sudo lsof -i :8000
sudo kill -9 <PID>
# Or stop competing containers
docker ps
docker stop <container_name>
# Then start again
docker compose up -d
```
### Issue 5: Frontend Can't Connect to Backend
**Symptoms**:
- Frontend loads but shows error fetching elections
- Network requests to `/api/elections/active` return 502
**Solution**:
```bash
# Wait for backend to fully initialize
sleep 40
# Check backend is running
curl http://localhost:8000/api/elections/active
# Check frontend environment variable
docker compose logs frontend | grep NEXT_PUBLIC_API_URL
# Should be: http://localhost:8000
```
## Startup Verification Checklist
After `docker compose up -d`, verify each step:
- [ ] Wait 40 seconds
- [ ] Backend health: `curl http://localhost:8000/health` → 200 OK
- [ ] Database has elections: `curl http://localhost:8000/api/elections/debug/all` → shows elections
- [ ] Active election exists: `curl http://localhost:8000/api/elections/active` → shows 1+ elections
- [ ] Blockchain initialized: `curl http://localhost:8000/api/elections/blockchain` → shows blocks
- [ ] Blockchain verified: `curl http://localhost:8000/api/elections/1/blockchain-verify` → "verified": true
- [ ] Frontend loads: `curl http://localhost:3000` → 200 OK
- [ ] Frontend can fetch elections: Browser console shows no errors
## Debugging Tips
### View All Logs
```bash
docker compose logs -f
```
Follow output as services start.
### View Specific Service Logs
```bash
# Backend
docker compose logs backend -f
# Database
docker compose logs mariadb -f
# Frontend
docker compose logs frontend -f
```
### Check Database Content
```bash
# Connect to database
docker compose exec mariadb mariadb -u evoting_user -pevoting_pass123 evoting_db
# See elections
SELECT id, name, is_active, start_date, end_date FROM elections LIMIT 5;
# See candidates
SELECT c.id, c.name, c.election_id FROM candidates LIMIT 10;
# Exit
exit
```
### Check Backend API Directly
```bash
# Health check
curl http://localhost:8000/health
# Active elections
curl http://localhost:8000/api/elections/active
# All elections (with debug info)
curl http://localhost:8000/api/elections/debug/all
# Blockchain
curl http://localhost:8000/api/elections/blockchain
# Verify election
curl http://localhost:8000/api/elections/1/blockchain-verify
```
### Restart Services
```bash
# Restart just backend
docker compose restart backend
sleep 10
# Restart database
docker compose restart mariadb
sleep 20
# Restart frontend
docker compose restart frontend
sleep 5
# Restart all
docker compose down
docker compose up -d
sleep 40
```
### Fresh Start (Nuclear Option)
```bash
# Stop everything
docker compose down
# Remove all data
docker compose down -v
# Remove all containers/images
docker system prune -a
# Start fresh
docker compose up -d
sleep 40
# Verify
curl http://localhost:8000/health
```
## Expected Responses
### Healthy Backend
**GET `/health`**
```json
{"status": "ok", "version": "0.1.0"}
```
**GET `/api/elections/active`**
```json
[
{
"id": 1,
"name": "Election Présidentielle 2025",
"description": "Vote pour la présidence",
"start_date": "2025-11-07T01:59:00",
"end_date": "2025-11-14T01:59:00",
"is_active": true,
"results_published": false
}
]
```
**GET `/api/elections/blockchain`**
```json
{
"blocks": [
{
"index": 0,
"election_id": 1,
"election_name": "Election Présidentielle 2025",
"candidates_count": 4,
"block_hash": "...",
"signature": "...",
...
}
],
"verification": {
"chain_valid": true,
"total_blocks": 1,
"timestamp": "2025-11-07T03:00:00.123456"
}
}
```
**GET `/api/elections/1/blockchain-verify`**
```json
{
"verified": true,
"election_id": 1,
"election_name": "Election Présidentielle 2025",
"hash_valid": true,
"chain_valid": true,
"signature_valid": true
}
```
## Database Adminer
Access database management UI:
- **URL**: http://localhost:8081
- **Server**: mariadb
- **User**: evoting_user
- **Password**: evoting_pass123
- **Database**: evoting_db
Use this to:
- View tables
- Run SQL queries
- Add test data
- Inspect blockchain integrity
## Next Steps
Once backend is healthy:
1. **Test blockchain integration**
```bash
python3 test_blockchain_election.py
```
2. **Verify elections exist**
```bash
curl http://localhost:8000/api/elections/active | jq '.'
```
3. **Check blockchain**
```bash
curl http://localhost:8000/api/elections/blockchain | jq '.blocks | length'
```
4. **Register and vote**
- Open http://localhost:3000
- Register as voter
- Participate in active election
5. **View blockchain (future)**
- Create page with blockchain visualizer component
- Show elections on immutable blockchain
- Verify integrity status
## Support
If issues persist:
1. Check logs: `docker compose logs`
2. Read documentation: See `BLOCKCHAIN_*.md` files
3. Run tests: `python3 test_blockchain_election.py`
4. Try fresh start: `docker compose down -v && docker compose up -d`

View File

@ -0,0 +1,284 @@
# Running Blockchain Election Tests
## Prerequisites
1. Backend is running on `http://localhost:8000`
2. Wait 30 seconds after backend starts for database initialization
3. Python 3.8+ with `requests` library installed
## Installation
```bash
# Install requests library if not already installed
pip install requests
```
## Run Tests
```bash
# From project root directory
python3 test_blockchain_election.py
```
## Expected Output
### Successful Test Run
```
╔════════════════════════════════════════════════════════════╗
║ ║
║ Elections Blockchain Integration Tests ║
║ ║
╚════════════════════════════════════════════════════════════╝
============================================================
TEST 0: Backend Health Check
============================================================
✓ Backend is running
Status: ok
Version: 0.1.0
============================================================
TEST 1: Get Elections Blockchain
============================================================
✓ Blockchain endpoint working
Total blocks: 1
Chain valid: true
First block:
Election ID: 1
Election name: Election Présidentielle 2025
Candidates: 4
Block hash: 7f3e9c2b1d4f8a5c3e1b9d2f...
Signature: 8a2e1f3d5c9b7a4e6c1d3f5a...
============================================================
TEST 2: Verify Election 1 Blockchain Integrity
============================================================
✓ Verification endpoint working
Verified: true
Hash valid: true
Chain valid: true
Signature valid: true
✓ Election blockchain integrity VERIFIED
============================================================
TEST 3: Get Active Elections
============================================================
✓ Active elections endpoint working
Active elections: 1
Election 1: Election Présidentielle 2025
Start: 2025-11-07T01:59:00
End: 2025-11-14T01:59:00
Active: true
============================================================
TEST 4: Debug All Elections
============================================================
✓ Debug endpoint working
Current server time: 2025-11-07T03:00:00.123456
Total elections: 1
Elections that should be active: 1
Active elections:
✓ Election 1: Election Présidentielle 2025
============================================================
TEST SUMMARY
============================================================
✓ PASS: Backend Health
✓ PASS: Blockchain Endpoint
✓ PASS: Active Elections
✓ PASS: Debug Elections
✓ PASS: Election Verification
Total: 5/5 tests passed
✓ All tests passed! Elections blockchain integration working correctly.
```
## Troubleshooting
### Error: Cannot connect to backend
```
✗ Cannot connect to backend
Is it running on http://localhost:8000?
```
**Solution**: Start backend with Docker:
```bash
docker compose up -d backend
# Wait 30 seconds for initialization
sleep 30
# Then run tests
python3 test_blockchain_election.py
```
### Error: No blocks in blockchain
```
✗ Blockchain endpoint working
Total blocks: 0
⚠ No blocks in blockchain yet
Elections may not have been initialized
```
**Solution**: This is expected if the backend just started. Wait for initialization:
```bash
# Wait for database initialization
sleep 30
# Run tests again
python3 test_blockchain_election.py
```
If still empty after 30 seconds, check backend logs:
```bash
docker compose logs backend | grep -i blockchain
```
Should see:
```
✓ Recorded election 1 (Election Présidentielle 2025) to blockchain
✓ Blockchain integrity verified - 1 blocks
```
### Error: Verification failed
```
⚠ Election blockchain verification FAILED
- Block hash mismatch (possible tampering)
```
This indicates possible data corruption. Check:
1. Is backend stable (no crashes)?
2. Are there any database errors?
3. Try restarting: `docker compose restart backend`
### Error: Module not found
```
ModuleNotFoundError: No module named 'blockchain_elections'
```
This means the backend isn't loading the blockchain module. Check:
1. File exists: `backend/blockchain_elections.py`
2. Permissions are correct
3. Backend rebuilt after adding module: `docker compose up -d --build backend`
## Manual Testing Commands
Instead of running the full test suite, you can test individual endpoints:
### Test Backend Health
```bash
curl http://localhost:8000/health
```
Expected:
```json
{"status": "ok", "version": "0.1.0"}
```
### Test Blockchain Endpoint
```bash
curl http://localhost:8000/api/elections/blockchain | jq '.'
```
Expected:
```json
{
"blocks": [...],
"verification": {
"chain_valid": true,
"total_blocks": 1
}
}
```
### Test Election Verification
```bash
curl http://localhost:8000/api/elections/1/blockchain-verify | jq '.'
```
Expected:
```json
{
"verified": true,
"election_id": 1,
"election_name": "...",
"hash_valid": true,
"chain_valid": true,
"signature_valid": true
}
```
### Test Active Elections
```bash
curl http://localhost:8000/api/elections/active | jq '.'
```
### Test Debug Elections
```bash
curl http://localhost:8000/api/elections/debug/all | jq '.elections'
```
## Interpreting Results
### ✓ Verified
Election blockchain integrity is valid. Election has not been tampered with.
### ✗ hash_valid: false
The block's data has been modified after creation. Tampering detected.
### ✗ chain_valid: false
A previous block in the chain has been modified, breaking the hash chain.
### ✗ signature_valid: false
The block's signature is missing, invalid, or doesn't match. Authentication failed.
## Next Steps
After confirming tests pass:
1. **View blockchain via API**
```bash
curl http://localhost:8000/api/elections/blockchain
```
2. **Verify an election**
```bash
curl http://localhost:8000/api/elections/1/blockchain-verify
```
3. **Integrate with Frontend** (optional)
- Use `frontend/components/blockchain-visualizer.tsx`
- Create a page to display blockchain data
- Show verification status and block details
4. **Extend Blockchain** (future)
- Add voter registration records
- Record votes to blockchain
- Implement voting proofs
## Test Script Source
The test script (`test_blockchain_election.py`) is ~290 lines and performs:
1. **Health Check** - Verifies backend is running
2. **Blockchain Endpoint** - Tests `/api/elections/blockchain`
3. **Active Elections** - Tests `/api/elections/active`
4. **Debug Elections** - Tests `/api/elections/debug/all`
5. **Election Verification** - Tests `/api/elections/{id}/blockchain-verify`
Each test:
- Makes HTTP request to backend
- Validates response structure
- Checks for expected fields
- Reports status (✓ PASS or ✗ FAIL)
- Provides debug information on failure
See the script for detailed implementation and test logic.