Alexis Bruneteau f825a2392c feat: Implement dark theme for frontend with toggle
Changes:
- Add next-themes dependency for theme management
- Create ThemeProvider wrapper for app root layout
- Set dark mode as default theme
- Create ThemeToggle component with Sun/Moon icons
- Add theme toggle to home page navigation
- Add theme toggle to dashboard header
- App now starts in dark mode with ability to switch to light mode

Styling uses existing Tailwind dark mode variables configured in
tailwind.config.ts and globals.css. All existing components automatically
support dark theme.

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-07 16:35:44 +01:00

14 KiB

Proposal: Refactor to Proof-of-Authority (PoA) Blockchain Architecture

Summary

Migrate from a simple in-memory blockchain to a distributed Proof-of-Authority (PoA) blockchain network with multiple validator nodes, a bootnode for peer discovery, and a centralized API server for voter registration and vote submission.

Change ID: refactor-poa-blockchain-architecture

Status: Proposed

Priority: High

Complexity: High


Business Context

Problem Statement

Current system uses a simple in-memory blockchain stored in a single FastAPI backend process. This approach has limitations:

  1. No Distribution: Blockchain stored only in memory on one server - no redundancy
  2. No Consensus: No mechanism to agree on canonical chain across multiple nodes
  3. Centralized Trust: Single point of failure - if backend crashes, blockchain is lost
  4. No Verification: Other parties cannot verify the blockchain independently

Desired Outcome

Implement a true distributed blockchain network where:

  • Multiple validators can independently verify votes are recorded correctly
  • Peer discovery allows new validators to join the network automatically
  • Consensus mechanism ensures all validators agree on the canonical chain
  • Decentralized verification - anyone can run a validator to verify election integrity
  • Production-ready - meets regulatory requirements for transparent, auditable elections

Solution Architecture

High-Level Design

┌─────────────────────────────────────────────────────────────────┐
│                     Docker Network (evoting_network)             │
└─────────────────────────────────────────────────────────────────┘
                              │
         ┌────────────────────┼────────────────────┐
         │                    │                    │
         ↓                    ↓                    ↓
    ┌─────────┐         ┌─────────┐         ┌─────────┐
    │ Bootnode│         │Validator│         │Validator│
    │(8546)   │◄───────►│   #1    │◄───────►│   #2    │
    │         │         │ (30303) │         │ (30304) │
    └─────────┘         └────┬────┘         └────┬────┘
         │                   │                    │
         └───────────────────┼────────────────────┘
                             │
                             ↓
                    ┌──────────────────┐
                    │   API Server     │
                    │  (FastAPI/8000)  │
                    │- Registration    │
                    │- Vote Submission │
                    │- Results Query   │
                    └────────┬─────────┘
                             │
              ┌──────────────┴──────────────┐
              ↓                             ↓
         ┌─────────┐            ┌──────────────────┐
         │ Database│            │   Frontend UI    │
         │MariaDB  │            │  (Next.js/3000)  │
         │(3306)   │            │                  │
         └─────────┘            └──────────────────┘

Components

1. Bootnode Service (Port 8546)

  • Role: Peer discovery - helps nodes find each other on the network
  • Technology: Geth-based (lightweight mode) or custom P2P service
  • Responsibility:
    • Maintain list of known peers
    • Respond to peer discovery requests
    • Help new nodes bootstrap into the network
  • Data: Peer information (IP, port, node ID)

2. Validator Nodes (Ports 30303+)

  • Role: Run the blockchain client, validate blocks, maintain consensus
  • Quantity: 3 validators (configurable)
  • Technology: Custom PoA client in Python (FastAPI + custom consensus)
  • Responsibilities:
    • Maintain local copy of blockchain
    • Validate incoming blocks
    • Participate in PoA consensus
    • Respond to vote verification requests
    • Sync state with peer validators
  • Consensus: Proof-of-Authority - designated validators sign blocks
    • Only authorized validators can create new blocks
    • Validators must have their public key in genesis block
    • Simple majority consensus (2 of 3 validators must accept)

3. API Server (Port 8000)

  • Role: Frontend/Registration Authority - handles voter registration and vote submission
  • Technology: FastAPI (existing backend)
  • Responsibilities:
    • Voter registration and authentication
    • Issue JWT tokens for authenticated voters
    • Accept encrypted votes from voters
    • Submit votes to validator network via JSON-RPC
    • Query results from validators
    • Serve web interface
  • Note: Does NOT run a full blockchain node - delegates to validators

4. Database (Port 3306)

  • Role: Persistent storage for voter data and election metadata
  • Technology: MariaDB/MySQL (existing)
  • Data:
    • Voter credentials and profiles
    • Election definitions and candidates
    • Vote metadata (voter_id, election_id, timestamp, ballot_hash)
    • Note: Actual encrypted votes stored on blockchain, not in DB

5. Frontend UI (Port 3000)

  • Role: User interface for voting
  • Technology: Next.js (existing)
  • Interaction:
    • Register via API Server
    • Login to get JWT token
    • Submit vote via API Server
    • Query results via API Server
    • View blockchain verification via API Server

Technical Details

PoA Consensus Mechanism

Key Features:

  • Authorized set of validators defined in genesis block
  • Each validator has a private key and public key stored securely
  • Validator creates block by:
    1. Collecting pending votes from vote pool
    2. Computing block hash
    3. Signing block with their private key
    4. Broadcasting to network
  • Other validators verify:
    1. Block hash is valid
    2. Signature is valid (matches authorized validator)
    3. Block extends previous block
    4. No double-spending of votes
  • Block accepted when majority (2/3) of validators acknowledge it

Data Flow: Vote Submission

1. Voter fills registration form on UI
   │
2. Frontend POSTs to API Server (/api/auth/register)
   │
3. API Server:
   - Validates voter data
   - Creates voter record in database
   - Returns JWT token
   │
4. Voter logs in and submits vote
   │
5. Frontend encrypts vote (ElGamal) + generates ZKP
   │
6. Frontend POSTs encrypted vote to API Server (/api/votes/submit)
   │
7. API Server:
   - Validates voter JWT
   - Checks voter hasn't already voted
   - Calls validator node via JSON-RPC: eth_sendTransaction
   │
8. Vote submitted to blockchain:
   - Validator node receives vote
   - Creates pending block with vote
   - Broadcasts to peer validators
   - Other validators verify and sign
   - Block is committed to chain
   │
9. API Server queries validator for confirmation:
   - eth_getTransactionReceipt
   - eth_blockNumber
   │
10. Returns vote confirmation to frontend

Vote Storage on Blockchain

Each block contains:

{
  "index": 0,
  "prev_hash": "0x000...",
  "timestamp": 1699360000,
  "transactions": [
    {
      "voter_id": "anon-tx-abc123",
      "election_id": 1,
      "encrypted_vote": "0x7f3a...",
      "ballot_hash": "0x9f2b...",
      "proof": "0xabcd...",
      "timestamp": 1699360001
    }
  ],
  "block_hash": "0xdeadbeef...",
  "validator": "0x1234567...",
  "signature": "0x5678..."
}

Implementation Phases

Phase 1: Bootnode Service (Peer Discovery)

  • Create lightweight bootnode
  • Simple HTTP endpoint for peer discovery
  • Track active validator nodes
  • Deliverable: Working bootnode that validators can register with

Phase 2: Validator Node Service (Blockchain Client)

  • Implement PoA consensus logic
  • Block creation and validation
  • Peer synchronization
  • JSON-RPC interface for API Server communication
  • Deliverable: 3 validator containers that form a chain

Phase 3: API Server Integration

  • Connect existing API Server to validator network
  • Implement JSON-RPC calls for vote submission
  • Query validator for results
  • Deliverable: Votes submitted to blockchain via validator network

Phase 4: Testing & Documentation

  • Test complete voting workflow
  • Verify blockchain integrity across validators
  • Document deployment and operation
  • Deliverable: Working distributed blockchain voting system

Technology Choices

Why Proof-of-Authority?

  • Suitable for this use case: Small number of known, trusted validators
  • Simpler than PoW: No energy waste, instant finality
  • Simpler than PoS: No stake or locking mechanisms needed
  • Fast consensus: Validators can reach agreement quickly
  • Transparent: Validator set is public and known

Why Not Geth/Ethereum?

  • Could use Geth, but overkill for this use case
  • Learning value: Building custom PoA teaches blockchain fundamentals
  • Lightweight: Custom implementation is simpler and more understandable
  • Control: Full control over consensus rules and behavior

Why Custom P2P Network?

  • Isolation: Run entirely on private Docker network
  • Simplicity: Don't need complex protocol (libp2p)
  • Control: Define exactly what peers need to communicate

Benefits

For Users

  • Transparency: Can verify votes recorded on blockchain
  • Auditability: Complete chain of custody for each vote
  • Fairness: No central authority can change results

For System

  • Redundancy: Multiple validators prevent single point of failure
  • Consensus: Agreement across validators ensures accuracy
  • Scalability: Easy to add more validators if needed
  • Regulatory Compliance: Meets transparency requirements for elections

For Project

  • Educational: Demonstrates real blockchain implementation
  • Production-Ready: True distributed system, not just prototype
  • Future-Proof: Foundation for adding more features (e.g., multiparty computation)

Risks & Mitigation

Risk 1: Byzantine Validator

Problem: Validator signs invalid blocks or refuses to participate

Mitigation:

  • Validator set is known and trusted
  • Invalid blocks rejected by other validators
  • Watchdog service monitors validator health
  • Can remove misbehaving validator by governance (future work)

Risk 2: Network Partition

Problem: Validators split into groups that can't communicate

Mitigation:

  • Private Docker network prevents partition in single-host setup
  • Each validator boots from bootnode to ensure connectivity
  • Heartbeat mechanism detects disconnections
  • Recovery: rejoin and resync on network restoration

Risk 3: Byzantine Client (API Server)

Problem: API Server submits fraudulent votes to blockchain

Mitigation:

  • Votes encrypted before reaching API Server
  • Blockchain validates vote format and proof
  • Any party can run a validator to verify votes
  • Audit trail preserved on immutable blockchain

Risk 4: Performance

Problem: Consensus bottleneck limits vote submission rate

Mitigation:

  • 3-validator PoA can handle thousands of votes per second
  • Optional: Increase validator count if needed
  • Optional: Implement transaction batching

Success Criteria

  1. Bootnode operational - validators can discover each other
  2. Validators form stable network - all 3 stay synchronized
  3. Votes recorded on blockchain - each vote creates a block
  4. Consensus working - validators agree on canonical chain
  5. API Server integration - votes submitted and confirmed
  6. Complete workflow - registration → voting → verification → results
  7. Docker deployment - entire system deployable with docker compose up
  8. Documentation - clear operational procedures for running and maintaining system

Effort Estimate

Phase Task Complexity Effort
1 Bootnode service Medium 2-3 days
2 Validator node service High 5-7 days
3 API Server integration Medium 2-3 days
4 Testing & documentation Medium 2-3 days
Total High ~12-16 days

Dependencies

External

  • Docker & Docker Compose
  • Python 3.12+
  • Existing FastAPI backend
  • Existing MariaDB database

Internal

  • ElGamal encryption (existing crypto module)
  • Dilithium signatures (existing crypto module)
  • Blockchain hashing (existing utilities)

Scope & Constraints

In Scope

  • Bootnode for peer discovery
  • 3 validator nodes with PoA consensus
  • Custom blockchain client in Python
  • JSON-RPC interface for API communication
  • Docker Compose orchestration
  • Complete voting workflow via distributed blockchain

Out of Scope (Future Work)

  • Geth/Ethereum compatibility
  • Sharding or horizontal scaling
  • Multiparty computation for secret sharing
  • Zero-knowledge proof verification (already implemented)
  • Governance mechanisms for validator management
  • Persistent chain storage (database integration)

Next Steps

  1. Review & Approval: Get stakeholder approval for architecture
  2. Design: Create detailed technical design document
  3. Implementation: Build in phases with testing at each step
  4. Deployment: Deploy to production with monitoring
  5. Documentation: Create operational runbooks

  • design.md - Detailed technical design of PoA implementation
  • tasks.md - Implementation checklist and dependencies
  • specs/ - Specification changes for blockchain architecture