A comprehensive Vehicle Ad-Hoc Network (VANET) security system that combines Machine Learning anomaly detection with blockchain-based immutable logging. This system detects and records vehicle misbehavior in real-time using advanced ML models and Ethereum smart contracts.
βββββββββββββββββββ
β Vehicles β Send Basic Safety Messages (BSMs)
ββββββββββ¬βββββββββ
β
ββββββββββΌβββββββββ
β RSUs β Receive and preprocess messages
ββββββββββ¬βββββββββ
β
ββββββββββΌβββββββββ
β ML Detection β Anomaly detection (RF/SVM/DNN)
ββββββββββ¬βββββββββ
β
ββββββββββΌβββββββββ
β Smart Contract β Log misbehavior to blockchain
βββββββββββββββββββ
This project leverages a modern, production-ready technology stack across three main layers: Backend (Python), Blockchain (Ethereum/Solidity), and Frontend (React).
- Purpose: Lightweight, flexible Python web framework for building RESTful APIs
- Usage: Powers the backend API server (
backend/app.py) that handles HTTP requests, serves real-time data via Server-Sent Events (SSE), and manages the detection system - Features Used:
- RESTful API endpoints for detection, training, and monitoring
- Server-Sent Events (SSE) for real-time data streaming to frontend
- Blueprint architecture for modular API organization
- CORS support for cross-origin requests
- Purpose: Enables secure cross-origin HTTP requests between frontend and backend
- Usage: Allows React frontend (running on different port) to communicate with Flask backend
- Purpose: Fundamental library for numerical operations and array processing
- Usage: Core data structure for ML model inputs/outputs, feature extraction, and mathematical operations
- Why: Provides efficient multi-dimensional arrays and mathematical functions essential for ML computations
- Purpose: Powerful data manipulation and analysis library
- Usage:
- Loading and preprocessing VeReMi dataset
- Feature engineering from VANET message data
- Data cleaning and transformation
- Time-series analysis of detection patterns
- Purpose: Comprehensive ML toolkit with pre-built algorithms
- Algorithms Used:
- Random Forest Classifier: Ensemble method using multiple decision trees for robust misbehavior detection
- Support Vector Machine (SVM): Kernel-based classifier for high-dimensional feature spaces
- StandardScaler: Feature normalization for consistent model training
- Cross-validation: Model evaluation and hyperparameter tuning
- Usage: Primary ML framework for traditional machine learning models (
src/ml/models.py)
- Purpose: Modern deep learning framework with dynamic computation graphs
- Usage:
- Implements Deep Neural Network (DNN) classifier for misbehavior detection
- Multi-layer perceptron architecture with dropout regularization
- GPU acceleration support (when available)
- Model serialization and loading
- Why: Provides state-of-the-art deep learning capabilities, achieving 99.9% accuracy in misbehavior detection
- Purpose: Alternative DNN implementation option
- Usage: Can be used instead of PyTorch for DNN models (install via
install_tensorflow_mac.sh) - Note: PyTorch is recommended for Mac systems due to easier installation
- Purpose: Comprehensive 2D plotting library for Python
- Usage:
- Training visualization (
ml/visualize_results.py) - Model performance charts
- Detection pattern analysis
- Feature importance visualization
- Training visualization (
- Purpose: High-level interface for statistical graphics built on Matplotlib
- Usage: Enhanced visualizations for ML model comparisons, correlation matrices, and distribution plots
- Purpose: Library for scientific and technical computing
- Usage: Statistical functions, optimization algorithms, and signal processing utilities
- Purpose: Python library for interacting with Ethereum blockchain
- Usage:
- Connects to Ethereum networks (local, Goerli, Sepolia)
- Deploys and interacts with smart contracts (
src/blockchain/web3_client.py) - Sends transactions to log misbehavior events
- Reads blockchain state (trust scores, misbehavior counts)
- Event filtering and monitoring
- Features:
- Support for Proof-of-Authority (PoA) networks via middleware
- Transaction signing and gas estimation
- Contract ABI encoding/decoding
- Purpose: Ethereum account creation and transaction signing
- Usage:
- Private key management
- Transaction signing for blockchain interactions
- Address generation and validation
- Purpose: Modern, feature-rich logging library
- Usage:
- Structured logging throughout the application
- Color-coded console output
- File rotation and retention
- Exception tracking and stack traces
- Why: Provides better developer experience than standard
loggingmodule
- Purpose: Loads environment variables from
.envfiles - Usage:
- Secure storage of blockchain private keys
- Network configuration (RPC URLs, contract addresses)
- API keys and sensitive configuration
- Purpose: YAML file parsing and generation
- Usage: Configuration file management (
config/config.json)
- Purpose: Fast, extensible progress bars for loops
- Usage: Visual feedback during ML model training and data processing
- Purpose: Download large files from Google Drive
- Usage: Automated VeReMi dataset download (
utils/download_dataset.py)
- Purpose: Read/write Excel files (.xlsx)
- Usage: Processing VeReMi dataset files in Excel format
- Purpose: Modern Python testing framework
- Usage:
- Unit tests for ML models (
test/test_ml.py) - Integration tests (
scripts/integration_test.py) - Test fixtures and parametrization
- Unit tests for ML models (
- Purpose: Coverage plugin for pytest
- Usage: Measure test coverage and identify untested code paths
- Purpose: Uncompromising Python code formatter
- Usage: Enforces consistent code style across the project
- Purpose: Style guide enforcement (PEP 8)
- Usage: Static code analysis for code quality and style compliance
- Purpose: High-level, statically-typed programming language for Ethereum smart contracts
- Usage:
contracts/MisbehaviorDetection.sol- Main smart contract- Defines data structures (MisbehaviorRecord, trust scores)
- Implements business logic (logging, blacklisting, trust score updates)
- Emits events for real-time monitoring
- Features Used:
- Structs for complex data types
- Mappings for efficient key-value storage
- Enums for misbehavior types (Sybil, Falsification, Replay, DoS)
- Events for off-chain monitoring
- Access control and security patterns
- Purpose: Battle-tested, community-audited smart contract components
- Usage:
- Security patterns and best practices
- Access control mechanisms
- Reentrancy protection
- Why: Industry standard for secure smart contract development
- Purpose: Complete development environment for Ethereum smart contracts
- Features:
- Compilation: Compiles Solidity contracts
- Testing: Built-in testing framework with Chai assertions
- Deployment: Automated contract deployment scripts
- Local Network: Built-in Ethereum node for development
- Network Management: Support for multiple networks (localhost, Goerli, Sepolia)
- Verification: Contract verification on Etherscan
- Configuration:
hardhat.config.jsdefines networks, compiler settings, and optimization
- Purpose: Collection of essential Hardhat plugins
- Includes:
- Hardhat-Ethers: Ethereum library integration
- Hardhat-Chai-Matchers: Testing utilities
- Hardhat-Etherscan: Contract verification
- Hardhat-Gas-Reporter: Gas usage analysis
- Purpose: Verify smart contracts on Etherscan
- Usage: Publishes source code for transparency and verification
- Localhost (Hardhat Network):
- Chain ID: 1337
- Purpose: Local development and testing
- Features: Instant block mining, zero gas costs
- Goerli Testnet:
- Chain ID: 5
- Purpose: Public testnet for integration testing
- Features: Free test ETH, real network conditions
- Sepolia Testnet:
- Chain ID: 11155111
- Purpose: Modern Ethereum testnet
- Features: Stable test environment
- Purpose: JavaScript library for interacting with Ethereum blockchain
- Usage:
- Deployment scripts (
scripts/deploy.js) - Contract interaction from Node.js
- Transaction management
- Deployment scripts (
- Note: Python uses
web3.py, Node.js usesweb3.js- both serve the same purpose in their respective environments
- Purpose: Minimal web framework for Node.js
- Usage:
- Simple HTTP server (
server.js) - API endpoints for blockchain status
- Middleware for request handling
- Simple HTTP server (
- Purpose: Enable CORS in Express server
- Usage: Allow cross-origin requests from frontend
- Purpose: Load environment variables in Node.js
- Usage: Secure configuration management for blockchain credentials
- Purpose: Declarative, component-based JavaScript library for building user interfaces
- Usage:
- Component architecture (
frontend/src/components/) - State management with hooks (useState, useEffect)
- Real-time data updates via API polling
- Interactive dashboards and forms
- Component architecture (
- Features Used:
- Functional components with hooks
- Component composition
- Event handling
- Conditional rendering
- Purpose: React package for DOM rendering
- Usage: Renders React components to the browser DOM
- Purpose: Lightning-fast build tool and development server
- Features:
- Hot Module Replacement (HMR): Instant updates during development
- Fast Builds: Optimized production builds
- ES Modules: Native ES module support
- Proxy Configuration: API proxying for development
- Configuration:
frontend/vite.config.jsdefines build settings and dev server
- Purpose: Official React plugin for Vite
- Usage: Enables JSX transformation and React Fast Refresh
- Purpose: Redefined chart library built on React and D3
- Charts Used:
- LineChart: Time-series detection trends
- AreaChart: Cumulative detection patterns
- BarChart: Detection counts and gas usage
- PieChart: Misbehavior type distribution
- ScatterChart: Confidence vs detection patterns
- ComposedChart: Multi-metric visualizations
- RadarChart: Multi-metric performance comparison
- Usage:
- Real-time dashboard charts (
components/Charts.jsx) - ML training visualization (
components/MLTraining.jsx) - Responsive, interactive visualizations
- Real-time dashboard charts (
- Why: React-native, highly customizable, and performant
- Purpose: HTTP client for making API requests
- Usage:
- Fetching detection data from Flask backend
- Training API calls
- Blockchain status queries
- Error handling and request interceptors
- Why: Better than fetch API with automatic JSON parsing, request/response interceptors, and better error handling
- Purpose: TypeScript type definitions for React
- Usage: Type safety during development (if using TypeScript)
- Purpose: TypeScript type definitions for React DOM
- Usage: Type safety for DOM-related React APIs
- Node.js >= 18.0.0 - JavaScript runtime for blockchain tools and frontend
- Python >= 3.9 - Backend runtime and ML framework
- npm or yarn - Package manager for Node.js dependencies
- pip - Python package installer
- MetaMask - Browser extension for Ethereum wallet (for testnet interactions)
- Ganache - Local blockchain for development (alternative to Hardhat node)
- Git - Version control system
# Install Node.js dependencies (blockchain tools, frontend build tools)
npm install
# Install frontend dependencies
cd frontend && npm install && cd ..
# Install Python dependencies (ML libraries, Flask, Web3)
pip install -r requirements.txtCreate a .env file in the project root:
# Blockchain Configuration
PRIVATE_KEY=your_private_key_here
GOERLI_URL=https://goerli.infura.io/v3/YOUR_INFURA_KEY
SEPOLIA_URL=https://sepolia.infura.io/v3/YOUR_INFURA_KEY
# Backend Configuration
FLASK_PORT=5001
VITE_PORT=3000# Option 1: Use Hardhat's built-in network (Recommended)
npx hardhat node
# Option 2: Use Ganache GUI
# Download from https://trufflesuite.com/ganache/# Deploy to local network
npx hardhat run scripts/deploy.js --network localhost
# Deploy to Goerli testnet
npx hardhat run scripts/deploy.js --network goerli
# Deploy to Sepolia testnet
npx hardhat run scripts/deploy.js --network sepoliaThe deployment script will output the contract address. Update config/config.json with this address.
# Train all models (Random Forest, SVM, DNN)
python ml/train_models.py
# This will:
# - Load VeReMi dataset
# - Preprocess features
# - Train three models
# - Evaluate performance
# - Save models to disk# Start Flask backend (Terminal 1)
cd backend
python app.py
# Start frontend dev server (Terminal 2)
cd frontend
npm run dev
# Or use the integrated start script
./start_web.shAccess the application at http://localhost:3000
| Metric | Value | Technology |
|---|---|---|
| ML Accuracy | 99.9% | PyTorch DNN |
| Precision | 1.00 | scikit-learn |
| Recall | 0.99 | scikit-learn |
| F1-Score | 1.00 | scikit-learn |
| Local Latency | 1-3s | Hardhat Network |
| Testnet Latency | 10-15s | Goerli/Sepolia |
| Gas per Transaction | 45,000-70,000 | Solidity (optimized) |
Edit config/config.json to configure:
- Blockchain Settings: Network URLs, contract addresses, gas limits
- ML Parameters: Model selection, confidence thresholds, feature weights
- RSU Configuration: Roadside unit settings, detection zones
- Detection Thresholds: Misbehavior classification criteria
vanet-blockchain-ml/
βββ backend/ # Flask API server
β βββ app.py # Main Flask application
β βββ detect.py # Detection endpoints
β βββ training_api.py # ML training API
β βββ blockchain_status.py # Blockchain monitoring
βββ contracts/ # Solidity smart contracts
β βββ MisbehaviorDetection.sol # Main contract
βββ frontend/ # React application
β βββ src/
β β βββ components/ # React components
β β β βββ Dashboard.jsx
β β β βββ Charts.jsx
β β β βββ DetectionForm.jsx
β β β βββ MLTraining.jsx
β β βββ App.jsx # Main app component
β βββ vite.config.js # Vite configuration
βββ ml/ # Machine learning models
β βββ train_models.py # Model training script
β βββ use_dataset.py # Dataset utilities
β βββ visualize_results.py # Visualization
βββ scripts/ # Deployment & utility scripts
β βββ deploy.js # Hardhat deployment
β βββ integration_test.py # System tests
βββ src/ # Core Python modules
β βββ ml/
β β βββ models.py # ML model implementations
β βββ blockchain/
β βββ web3_client.py # Blockchain client
βββ test/ # Test files
β βββ test_ml.py # ML unit tests
β βββ MisbehaviorDetection.test.js # Contract tests
βββ config/ # Configuration files
β βββ config.json # System configuration
βββ data/ # VeReMi dataset
βββ hardhat.config.js # Hardhat configuration
βββ package.json # Node.js dependencies
βββ requirements.txt # Python dependencies
βββ README.md # This file
# Check all dependencies and configurations
python verify_setup.py# Run Hardhat tests
npx hardhat test
# Test specific contract
npx hardhat test test/MisbehaviorDetection.test.js# Run pytest tests
pytest test/test_ml.py
# With coverage
pytest test/test_ml.py --cov=src/ml# Run complete system test
./run_test.sh
# Or manually
python scripts/integration_test.py- Vehicles generate Basic Safety Messages (BSMs) with location, speed, and trajectory data
- RSUs (Roadside Units) receive and preprocess BSMs, extracting features
- ML Detection System analyzes features using trained models:
- Random Forest: Ensemble of decision trees
- SVM: Support Vector Machine with kernel functions
- DNN: Deep Neural Network with multiple hidden layers
- Smart Contract logs detected misbehavior to blockchain:
- Immutable record storage
- Trust score updates
- Automatic blacklisting
- Event emission for monitoring
- Python β Blockchain: Web3.py connects Flask backend to Ethereum
- Frontend β Backend: Axios HTTP client communicates with Flask API
- Backend β ML: NumPy/Pandas arrays passed between Flask and ML models
- Frontend β Visualization: Recharts renders data from Flask API responses
- 99.9% Detection Accuracy using Deep Neural Network (PyTorch)
- Real-time Processing with optimized feature extraction
- Multiple Model Support (RF, SVM, DNN) for comparison
- Confidence Scoring for each detection
- Immutable Audit Trail of all misbehavior events
- Decentralized Trust - no single point of failure
- Transparent Logging - all events publicly verifiable
- Automatic Blacklisting based on trust scores
- Gas Optimization - efficient contract design (45k-70k gas)
- 1-3s Latency on local blockchain (Hardhat)
- 10-15s Latency on public testnets (Goerli/Sepolia)
- Real-time Dashboard with live updates via SSE
- Scalable Architecture - handles high-volume BSM processing
- OpenZeppelin Contracts: Industry-standard security patterns
- Access Control: Role-based permissions
- Input Validation: All parameters validated before execution
- Gas Optimization: Efficient storage patterns to minimize costs
- CORS Configuration: Restricted cross-origin access
- Input Validation: All API inputs validated
- Environment Variables: Sensitive data stored securely
- Error Handling: Graceful error responses without exposing internals
- Model Validation: Cross-validation prevents overfitting
- Feature Validation: Input features checked before prediction
- Confidence Thresholds: Configurable detection sensitivity
- Hardhat local network
- Flask development server
- Vite dev server with HMR
- Deploy contracts to Goerli or Sepolia
- Use testnet ETH for transactions
- Monitor via Etherscan
- Use production-grade Ethereum node (Infura, Alchemy)
- Deploy to mainnet (requires real ETH)
- Use production WSGI server (Gunicorn) for Flask
- Build optimized React bundle (
npm run build) - Set up monitoring and logging
MIT License - See LICENSE file for details
- VeReMi Dataset: Vehicle misbehavior detection research dataset
- Ethereum Foundation: Blockchain infrastructure and tooling
- OpenZeppelin: Secure smart contract libraries
- scikit-learn Community: Machine learning algorithms
- PyTorch Team: Deep learning framework
- React Team: UI library and ecosystem
For detailed documentation on specific technologies:
- Flask: https://flask.palletsprojects.com/
- PyTorch: https://pytorch.org/docs/
- scikit-learn: https://scikit-learn.org/stable/
- Hardhat: https://hardhat.org/docs
- Solidity: https://docs.soliditylang.org/
- React: https://react.dev/
- Vite: https://vitejs.dev/
- Recharts: https://recharts.org/
- Web3.py: https://web3py.readthedocs.io/
- Python: 3.9+
- Node.js: 18.0+
- Solidity: 0.8.20
- React: 18.2+
- Flask: 3.0+
- PyTorch: 2.0+
- Hardhat: 2.19+
Last Updated: 2024