Added comprehensive MVP definition with: Core Components: - Paillier homomorphic encryption for vote secrecy - Kyber (ML-KEM) for post-quantum key protection - Dilithium (ML-DSA) for PQC signatures - Blockchain module with immutable vote recording - ZKP implementation for ballot validity MVP Features: 1. Cryptographic toolkit (Paillier, Kyber, Dilithium, ZKP) 2. Blockchain module (linked blocks, signatures, validation) 3. Voting API (setup, public-keys, submit, blockchain, count) 4. Voter client (encryption, signing, submission) 5. Blockchain visualizer (display, verification) 6. Scrutator module (counting, results) 6-Phase Implementation Plan: - Phase 1: Cryptographic foundations - Phase 2: Backend API integration - Phase 3: Frontend voting interface - Phase 4: Blockchain visualization - Phase 5: Results & reporting - Phase 6: Testing & technical report Security properties matrix with mechanisms. Progress tracking checklist for all phases. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
22 KiB
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):
-
Complete Source Code & Environment:
- Full e-voting system source code
- Independently deployable via Docker configuration
- Implemented cryptographic security mechanisms
- Ready for autonomous deployment
-
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 encryptionPOST /api/votes/submit- Submit encrypted ballot with signatureGET /api/votes/blockchain- Retrieve blockchain stateGET /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
- Voter selects candidate (0 or 1)
- Frontend encrypts ballot:
E(v) = Paillier.encrypt(v, public_key) - Frontend generates ZKP: proof that
E(v)is valid (0 or 1) - Frontend signs:
Signature = Dilithium.sign(E(v) || ZKP, voter_private_key) - Frontend submits:
{voter_id, E(v), ZKP, Signature}to API - API verifies signature and ZKP
- API checks voter hasn't already voted (emission list)
- API adds to blockchain:
Block{index, prev_hash, timestamp, E(v), tx_id, block_signature} - API returns confirmation
Étape 4: Vote Counting (Scrutator)
- Retrieve all blocks from blockchain
- Verify blockchain integrity (hash chain + all block signatures)
- Homomorphic operation:
E(total) = E(v1) × E(v2) × ... × E(vn) - Decrypt:
total = Paillier.decrypt(E(total), private_key) - 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
anytypes) - 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.jsondisables 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:
- User submits form (login/register)
- Frontend validates with Zod schema
- API request with JSON payload
- Backend validates and returns JWT token
- Frontend stores token in localStorage
- Token included in Authorization header for all subsequent requests
- 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 branchUI- Current frontend branch with Next.js rebuildbackup- Old React CRA frontend (preserved)- Feature branches off main development branch
Commit Conventions:
Format: <type>: <subject>
Types:
feat:- New featurefix:- Bug fixrefactor:- Code restructuringdocs:- Documentation updateschore:- Dependencies, config changestest:- 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 <noreply@anthropic.com>
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:
-
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)
-
Analysis & Cryptographic Application
- Fundamental cryptographic tools explanation
- Principles behind chosen algorithms
- Application of cryptography to voting security
- How tools guarantee chosen security properties
-
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:
-
Create
backend/crypto_tools.pywith:- 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
-
Create
backend/blockchain.pywith:- 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
-
Update
requirements.txt:python-paillierliboqs-pythonpycryptodomefor 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:
-
Update
backend/routes/votes.py:POST /api/votes/setup- Initialize election, generate Paillier/Kyber/Dilithium keysGET /api/votes/public-keys- Return public keys for client encryptionPOST /api/votes/register-voter- Register voter, generate their Dilithium keysPOST /api/votes/submit- Receive encrypted ballot, verify signature, add to blockchainGET /api/votes/blockchain- Return blockchain state for verificationGET /api/votes/results- Run scrutator, return homomorphic count
-
Update
backend/models.py:- Add Dilithium key storage for voters
- Add blockchain block storage
- Add vote submission tracking (emission list)
-
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:
-
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
-
Create
frontend/lib/crypto-client.ts:- Paillier encryption operations
- Dilithium signature operations
- ZKP generation
- Ballot serialization
-
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:
-
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
-
Create
frontend/components/blockchain-viewer.tsx:- Block display component
- Chain visualization
- Hash verification UI
-
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:
-
Create
frontend/app/dashboard/votes/results/page.tsx:- Display final vote count
- Show homomorphic verification
- Display blockchain integrity report
- Show audit trail
-
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:
-
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
-
-
Add tests:
- Unit tests for crypto operations
- Integration tests for voting workflow
- Blockchain integrity tests
-
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