# Project Context ## Purpose E-Voting System - A secure electronic voting platform with blockchain-based vote recording, post-quantum cryptography, and real-time election management. Allows users to register, authenticate, and participate in elections through a web-based interface while ensuring vote integrity and transparency through distributed ledger technology. **Project Definition (Cryptographie Industrielle Avancée):** Conceive and implement a functional prototype of a secure electronic voting system emphasizing correct application of cryptographic principles to address specific challenges of online voting. **Key Goals:** - Provide secure, verifiable electronic voting - Ensure vote immutability via blockchain - Support post-quantum cryptographic algorithms (ML-KEM, ML-DSA) - Enable transparent election results - Maintain voter privacy and authentication - Address e-voting challenges: fraud prevention, voter intimidation resistance, anonymity preservation - Implement correct cryptographic mechanisms for vote security **Deliverables (Per Project Requirements):** 1. **Complete Source Code & Environment:** - Full e-voting system source code - Independently deployable via Docker configuration - Implemented cryptographic security mechanisms - Ready for autonomous deployment 2. **Technical & Scientific Report:** - Architecture and design approach - Cryptographic tools explanation and principles - Security properties and threat analysis - Application of cryptography to voting system ## Tech Stack ### Frontend - **Framework**: Next.js 15 (App Router) - **Language**: TypeScript 5.3 - **Styling**: Tailwind CSS 3.3.6 - **UI Components**: shadcn/ui (custom components) - **Forms**: React Hook Form 7.66.0 - **Validation**: Zod 4.1.12 - **Icons**: Lucide React - **Environment**: Node.js 18+, npm ### Backend - **Framework**: FastAPI (Python 3.12+) - **Authentication**: JWT tokens (30-minute expiry) - **Database**: MySQL 8.0+ / SQLite (dev) - **ORM**: SQLAlchemy - **Validation**: Pydantic - **Cryptography**: - bcrypt for password hashing - Post-quantum algorithms (ML-KEM, ML-DSA) - Ballot hashing for vote verification - **Middleware**: CORS enabled - **Documentation**: Swagger UI & ReDoc ### Infrastructure - **Containerization**: Docker & Docker Compose - **Development Server**: uvicorn (backend), Next.js dev (frontend) - **Production Build**: Next.js static export + Node.js server ### Cryptography Libraries - **Paillier Homomorphic Encryption**: `python-paillier` - Vote encryption & homomorphic summation - **Kyber (ML-KEM)**: `liboqs-python` - Post-quantum key encapsulation - **Dilithium (ML-DSA)**: `liboqs-python` - Post-quantum digital signatures - **SHA-256**: Built-in hashlib - Blockchain hashing - **ZKP (Zero-Knowledge Proofs)**: Custom implementation - Ballot validity proofs ### Blockchain/Distributed Ledger - Vote records stored with ballot hashes - Immutable vote recording via linked blocks - Transparent result verification - Chain integrity verification via SHA-256 hashing - Block signatures with Dilithium PQC ## MVP (Minimum Viable Product) Features ### Core Components **1. Cryptographic Toolkit (`backend/crypto_tools.py`)** - Paillier homomorphic encryption (key generation, encryption, decryption, homomorphic addition) - Kyber (ML-KEM) for post-quantum key encapsulation - Dilithium (ML-DSA) for post-quantum digital signatures - Simple Zero-Knowledge Proofs (prove ballot is 0 or 1 without revealing value) - SHA-256 for blockchain hashing **2. Blockchain Module (`backend/blockchain.py`)** - Block structure: index, previous hash, timestamp, encrypted votes, block hash, signature - Chain validation: verify hash chain integrity and block signatures - Ballot addition: add new encrypted votes to blockchain - Chain immutability: ensure votes cannot be altered **3. Voting API Endpoints (`backend/routes/votes.py`)** - `POST /api/votes/setup` - Initialize election (generate Paillier keys) - `GET /api/votes/public-keys` - Retrieve public keys for client encryption - `POST /api/votes/submit` - Submit encrypted ballot with signature - `GET /api/votes/blockchain` - Retrieve blockchain state - `GET /api/votes/count` - Homomorphic vote counting **4. Voter Client (`frontend/components/voting-interface.tsx`)** - Display election details and candidates - Client-side ballot encryption with Paillier - Generate simple ZKP for ballot validity - Sign ballot with voter's Dilithium key - Submit encrypted, signed ballot to blockchain - Display confirmation and vote receipt **5. Blockchain Visualizer (`frontend/app/dashboard/blockchain/page.tsx`)** - Display blockchain as linked blocks - Show: block index, previous hash, current hash, encrypted vote, signature - Chain integrity verification button - Visual representation of vote count progress **6. Scrutator Module (`backend/scripts/scrutator.py`)** - Access blockchain votes - Verify chain integrity and all signatures - Homomorphic summation: multiply all encrypted votes to get encrypted total - Decrypt result using Paillier private key (protected by Kyber) - Publish results with verification proofs ### MVP Voting Process **Étape 1: Election Setup** - System generates Paillier keypair - System generates Kyber keypair for private key protection - System generates Dilithium keypair for block signing - Public keys published for voters **Étape 2: Voter Registration & Key Generation** - Voter authenticates via JWT - Voter generates personal Dilithium keypair - System stores public key for vote verification **Étape 3: Voter's Ballot Submission** 1. Voter selects candidate (0 or 1) 2. Frontend encrypts ballot: `E(v) = Paillier.encrypt(v, public_key)` 3. Frontend generates ZKP: proof that `E(v)` is valid (0 or 1) 4. Frontend signs: `Signature = Dilithium.sign(E(v) || ZKP, voter_private_key)` 5. Frontend submits: `{voter_id, E(v), ZKP, Signature}` to API 6. API verifies signature and ZKP 7. API checks voter hasn't already voted (emission list) 8. API adds to blockchain: `Block{index, prev_hash, timestamp, E(v), tx_id, block_signature}` 9. API returns confirmation **Étape 4: Vote Counting (Scrutator)** 1. Retrieve all blocks from blockchain 2. Verify blockchain integrity (hash chain + all block signatures) 3. Homomorphic operation: `E(total) = E(v1) × E(v2) × ... × E(vn)` 4. Decrypt: `total = Paillier.decrypt(E(total), private_key)` 5. Publish results ### Security Properties Provided | Property | Mechanism | Implementation | |----------|-----------|-----------------| | **Vote Secrecy** | Paillier encryption | Votes encrypted before leaving client | | **Vote Integrity** | Blockchain + Dilithium signatures | Linked blocks + PQC signatures on blocks | | **Voter Authentication** | JWT tokens + Dilithium signatures | JWT for session, Dilithium for ballot auth | | **Anonymity** | Transaction ID instead of voter ID | Voter ID verified once, not stored with vote | | **Verifiability** | ZKP + blockchain verification | Client proves ballot validity, anyone verifies chain | | **Post-Quantum Ready** | Kyber + Dilithium | Protected against future quantum attacks | ## Project Conventions ### Code Style **TypeScript/JavaScript:** - Use TypeScript for all new code (no `any` types) - Use arrow functions and const declarations - Use camelCase for variables and functions - Use PascalCase for component names and types - Max line length: 100 characters - Indent with 2 spaces - Quote style: Double quotes for JSX, prefer template literals **Python:** - Follow PEP 8 naming conventions - snake_case for functions and variables - PascalCase for classes - 4-space indentation - Use type hints for all functions - Docstrings for public functions/classes **Git Formatting:** - ESLint config: `.eslintrc.json` disables unescaped entities rule - No Prettier config needed (uses Next.js defaults) ### Architecture Patterns **Frontend Architecture:** ``` app/ # Next.js App Router ├── page.tsx # Route components ├── layout.tsx # Route layouts ├── @modal/ # Optional slot routes components/ ├── ui/ # Reusable UI components (shadcn/ui) └── protected-route.tsx # Authentication wrapper lib/ ├── api.ts # API client with TypeScript types ├── auth-context.tsx # Global auth state (React Context) ├── validation.ts # Zod schemas for form validation └── utils.ts # Utility functions ``` **Authentication Flow:** 1. User submits form (login/register) 2. Frontend validates with Zod schema 3. API request with JSON payload 4. Backend validates and returns JWT token 5. Frontend stores token in localStorage 6. Token included in Authorization header for all subsequent requests 7. useAuth() hook provides user state across components **API Client Pattern:** - Centralized in `lib/api.ts` - Grouped by resource: `authApi`, `electionsApi`, `votesApi` - Returns `{ data?, error?, status }` structure - Automatic token injection in headers - Type-safe responses with TypeScript interfaces **Protected Routes:** - ProtectedRoute component wraps dashboard - Checks useAuth() context before rendering - Redirects to login if not authenticated - Shows loading spinner during auth check **Backend Architecture:** ``` backend/ ├── main.py # FastAPI app entry point ├── routes/ # Endpoint handlers │ ├── auth.py # Authentication endpoints │ ├── elections.py # Election management │ └── votes.py # Vote recording ├── models.py # SQLAlchemy ORM models ├── schemas.py # Pydantic request/response schemas ├── services.py # Business logic ├── auth.py # JWT and password utilities ├── database.py # Database connection └── crypto/ # Cryptographic utilities ``` ### Testing Strategy **Manual Testing (Current):** - Test registration with form validation - Test login/logout flow - Test protected routes redirect - Test election data loading - Test form validation errors - Test API error handling **Future Testing:** - **Unit Tests**: Jest for frontend components - **E2E Tests**: Cypress for user workflows - **Backend Tests**: pytest for API endpoints - **Integration Tests**: Full stack with Docker ### Git Workflow **Branching Strategy:** - `paul/evoting` - Main development branch - `UI` - Current frontend branch with Next.js rebuild - `backup` - Old React CRA frontend (preserved) - Feature branches off main development branch **Commit Conventions:** Format: `: ` **Types:** - `feat:` - New feature - `fix:` - Bug fix - `refactor:` - Code restructuring - `docs:` - Documentation updates - `chore:` - Dependencies, config changes - `test:` - Test additions/updates **Example:** ``` feat: Integrate backend API with frontend - Authentication & Elections fix: Update Docker config for Next.js frontend docs: Add comprehensive project status document ``` **Commit Messages:** - Use imperative mood ("add" not "added") - Keep subject under 50 characters - Include context in body if needed - Sign with: `🤖 Generated with Claude Code` - Co-author: `Co-Authored-By: Claude ` ## Domain Context ### E-Voting Concepts - **Election**: A voting event with candidates and a deadline - **Candidate**: Options users can vote for - **Voter/User**: Authenticated user who can vote in elections - **Vote**: Immutable record of voter choice (with ballot hash for verification) - **Ballot Hash**: Cryptographic hash of vote details for verification without exposing vote ### Election States - **Pending/Upcoming**: Not yet started, no voting allowed - **Active**: Currently accepting votes - **Completed**: Voting finished, results available ### Security Model - User authentication via JWT tokens (30-minute expiry) - Password hashing with bcrypt - Post-quantum cryptography for future-proofing - Vote recording with ballot hashes for transparency - Vote immutability via blockchain/ledger - No voter identification in vote records (privacy) ### French Language Convention - All UI text in French - Error messages: `Erreur`, validation messages, etc. - Date format: DD/MM/YYYY ## Important Constraints ### Technical Requirements - **Password Requirements**: - Minimum 8 characters - At least 1 uppercase letter - At least 1 digit - At least 1 special character (!@#$%^&*) - **Token Expiry**: 30 minutes - **Build Output**: Static pre-rendered pages + Node.js server - **Database**: MySQL for production, SQLite for development - **API URL**: Environment variable `NEXT_PUBLIC_API_URL` - **Docker Deployment**: System must be deployable autonomously via Docker - **Cryptographic Implementation**: All chosen cryptographic mechanisms must be implemented ### Security Properties & Design Challenges **E-Voting Challenges to Address:** - **Fraud Prevention**: Prevent vote tampering and false result reporting - **Voter Intimidation Resistance**: Ensure no voter can prove how they voted - **Anonymity Preservation**: Disconnect voter identity from vote content - **Vote Integrity**: Guarantee votes cannot be altered after submission - **Coercion Resistance**: System prevents voter coercion while voting - **Universal Verifiability**: Anyone can verify election results are correct - **Voter Verifiability**: Voter can verify their vote was recorded correctly **Cryptographic Security:** - **CORS**: Currently allow all origins (restrict to frontend domain in production) - **HTTPS**: Required for production - **HttpOnly Cookies**: Recommended instead of localStorage for production - **Rate Limiting**: Should be implemented on auth endpoints in production - **Audit Logging**: Should be added for compliance - **Post-Quantum Ready**: Support ML-KEM and ML-DSA algorithms ### Business/Regulatory - **Election Integrity**: Votes must be immutable once recorded - **Voter Privacy**: Vote contents never tied to voter identity - **Transparency**: Results and vote counts must be verifiable - **Blockchain**: All votes stored with cryptographic verification - **Compliance**: Consider GDPR and voting regulations - **Audit Trail**: System must support accountability and verification ### Development - No destructive git commands without explicit user confirmation - Always commit before major changes - Preserve working tree cleanly - Test Docker builds before deployment ### Report Structure Requirements **Technical & Scientific Report Must Include:** 1. **Introduction & Design Choices** - Motivation and context (e-voting challenges) - System architecture (client/server, blockchain-based, mixing servers) - Justification of technology choices (languages, frameworks, database) - Detailed voting process (registration to results publication) 2. **Analysis & Cryptographic Application** - Fundamental cryptographic tools explanation - Principles behind chosen algorithms - Application of cryptography to voting security - How tools guarantee chosen security properties 3. **Security Properties & Threat Analysis** - Voting security properties the system satisfies - Potential vulnerabilities evaluation - How design choices (especially cryptographic) address threats - Resistance to identified threats ## External Dependencies ### APIs/Services - **Backend Database**: MySQL server (localhost:3306 in dev) - **CORS-enabled**: Frontend communicates with backend via REST API ### Libraries/Packages - **shadcn/ui**: Component library (via npm) - **Radix UI**: Primitive components for shadcn/ui - **FastAPI**: Built-in Swagger/ReDoc documentation - **SQLAlchemy**: ORM for database abstraction ### Infrastructure - **Docker Hub**: Alpine Linux images for containers - **npm Registry**: Frontend dependencies - **PyPI**: Python backend dependencies - **MariaDB/MySQL**: Database provider ### Key Endpoints - Backend Health: `GET /health` - Backend Docs: `GET /docs` (Swagger) - Backend ReDoc: `GET /redoc` - Frontend: `http://localhost:3000` - Backend: `http://localhost:8000` ## Implementation Plan ### Phase 1: Cryptographic Foundations **Goal**: Build secure crypto toolkit for PQC-based voting **Tasks**: 1. Create `backend/crypto_tools.py` with: - Paillier homomorphic encryption (key generation, encrypt, decrypt, homomorphic ops) - Kyber (ML-KEM) integration via liboqs-python - Dilithium (ML-DSA) integration via liboqs-python - Simple ZKP implementation (prove 0 or 1 without revealing) - SHA-256 blockchain hashing utilities 2. Create `backend/blockchain.py` with: - Block class (index, prev_hash, timestamp, encrypted_votes, block_hash, signature) - Blockchain class (chain management, validation, immutability) - Hash verification and signature verification methods - Homomorphic vote summation 3. Update `requirements.txt`: - `python-paillier` - `liboqs-python` - `pycryptodome` for additional crypto utilities **Deliverables**: - ✅ Functional crypto toolkit - ✅ Blockchain data structure - ✅ Unit tests for crypto operations --- ### Phase 2: Backend API Integration **Goal**: Implement secure voting endpoints **Tasks**: 1. Update `backend/routes/votes.py`: - `POST /api/votes/setup` - Initialize election, generate Paillier/Kyber/Dilithium keys - `GET /api/votes/public-keys` - Return public keys for client encryption - `POST /api/votes/register-voter` - Register voter, generate their Dilithium keys - `POST /api/votes/submit` - Receive encrypted ballot, verify signature, add to blockchain - `GET /api/votes/blockchain` - Return blockchain state for verification - `GET /api/votes/results` - Run scrutator, return homomorphic count 2. Update `backend/models.py`: - Add Dilithium key storage for voters - Add blockchain block storage - Add vote submission tracking (emission list) 3. Create `backend/scripts/scrutator.py`: - Verify blockchain integrity - Compute homomorphic sum - Decrypt final results - Generate verification report **Deliverables**: - ✅ Secure API endpoints - ✅ Blockchain persistence - ✅ Vote scrutiny module --- ### Phase 3: Frontend Voting Interface **Goal**: Build client-side secure voting experience **Tasks**: 1. Create `frontend/components/voting-interface.tsx`: - Display election details - Fetch public keys from backend - Client-side Paillier encryption - Generate ballot validity ZKP - Sign with voter's Dilithium key - Submit encrypted ballot - Show vote confirmation 2. Create `frontend/lib/crypto-client.ts`: - Paillier encryption operations - Dilithium signature operations - ZKP generation - Ballot serialization 3. Update `frontend/app/dashboard/votes/active/page.tsx`: - Integrate voting interface - Show election details - Display vote submission form **Deliverables**: - ✅ Secure voting UI - ✅ Client-side crypto operations - ✅ Vote submission workflow --- ### Phase 4: Blockchain Visualization & Verification **Goal**: Display blockchain and enable verification **Tasks**: 1. Create `frontend/app/dashboard/blockchain/page.tsx`: - Fetch blockchain from API - Display blocks as linked chain - Show: index, prev_hash, current_hash, encrypted_vote, signature - Display vote count progress - Integrity verification button 2. Create `frontend/components/blockchain-viewer.tsx`: - Block display component - Chain visualization - Hash verification UI 3. Create `frontend/lib/blockchain-verify.ts`: - Verify hash chain locally - Verify block signatures - Display verification results **Deliverables**: - ✅ Blockchain visualization - ✅ Verification interface - ✅ Results display --- ### Phase 5: Results & Reporting **Goal**: Display counting results and verification proofs **Tasks**: 1. Create `frontend/app/dashboard/votes/results/page.tsx`: - Display final vote count - Show homomorphic verification - Display blockchain integrity report - Show audit trail 2. Update backend scrutator: - Generate detailed results - Create verification proofs - Provide transparency report **Deliverables**: - ✅ Results display page - ✅ Verification proofs - ✅ Audit report --- ### Phase 6: Testing & Documentation **Goal**: Ensure security and create technical report **Tasks**: 1. Create technical report document: - Section 1: Introduction & Design Choices - Motivation and e-voting challenges - System architecture (client/server + blockchain) - Technology justification - Voting process walkthrough - Section 2: Analysis & Cryptographic Application - Explain Paillier homomorphic encryption - Explain Kyber (ML-KEM) key encapsulation - Explain Dilithium (ML-DSA) signatures - Explain simple ZKP implementation - Explain blockchain hashing - How crypto tools guarantee properties - Section 3: Security Properties & Threat Analysis - Security properties provided - Threat analysis and mitigation - Resistance evaluation 2. Add tests: - Unit tests for crypto operations - Integration tests for voting workflow - Blockchain integrity tests 3. Docker testing: - Ensure full deployment via docker-compose - Test all endpoints - Verify blockchain functionality **Deliverables**: - ✅ Complete technical & scientific report - ✅ Test suite - ✅ Deployment documentation --- ## Development Progress Tracking ### Phase 1: Cryptographic Foundations - [ ] Paillier toolkit implementation - [ ] Kyber integration - [ ] Dilithium integration - [ ] ZKP implementation - [ ] Blockchain module - [ ] Crypto tests ### Phase 2: Backend API Integration - [ ] Voting endpoints - [ ] Database models - [ ] Blockchain persistence - [ ] Scrutator module - [ ] API tests ### Phase 3: Frontend Voting Interface - [ ] Voting component - [ ] Crypto client library - [ ] Vote submission flow - [ ] Confirmation display ### Phase 4: Blockchain Visualization - [ ] Blockchain viewer page - [ ] Block display component - [ ] Verification UI - [ ] Hash verification ### Phase 5: Results & Reporting - [ ] Results page - [ ] Verification proofs - [ ] Audit report - [ ] Results display ### Phase 6: Testing & Documentation - [ ] Technical report (Section 1) - [ ] Technical report (Section 2) - [ ] Technical report (Section 3) - [ ] Unit tests - [ ] Integration tests - [ ] Docker verification