narasimhabtech27-commits/bfl-project
GitHub: narasimhabtech27-commits/bfl-project
一个结合区块链、差分隐私与信任评分机制的联邦学习框架,旨在实现安全、隐私且可审计的分布式AI模型训练。
Stars: 134 | Forks: 1
# 区块链赋能的联邦学习实现隐私保护人工智能







## 概述
**问题:** 传统机器学习要求将所有训练数据发送到中央服务器,这违反了用户隐私,破坏了GDPR和HIPAA等法规,并创造了单点攻击目标。
**传统联邦学习为何失效:** 标准的联邦学习解决了数据共享问题,但仍易受恶意客户端提交投毒模型更新、贡献为零的搭便车者以及无法验证、无审计追踪的贡献的影响。
**我们的解决方案:** 一个区块链赋能的联邦学习系统,该系统使用联邦平均算法跨5个私有客户端训练一个数字识别CNN,通过一个Solidity智能合约将每个模型更新作为不可变的交易记录到本地以太坊区块链上,应用差分隐私噪声来保护客户端权重,并使用贡献证明信任评分机制来自动检测和永久阻断恶意客户端——整个过程无需任何原始数据离开客户端。
**使用的关键模型:** CNN(主分类器)、FedAvg(聚合)、余弦相似度信任评分(PoC)、以太坊智能合约(ModelRegistry.sol)。
**最终性能亮点:**
- 在MNIST测试集(10,000张图像)上达到 **96.78% 准确率**
- 在第2轮 **检测到并阻断恶意攻击者**
- **记录了61条防篡改的链上交易**
- 攻击者被移除后,模型在一轮内 **恢复至90.59%**
- 在全部15个训练轮次中 **原始数据零共享**
**关键词:** 联邦学习 · 区块链 · 隐私保护AI · 以太坊 · 差分隐私 · 智能合约 · 贡献证明 · 数据投毒 · MNIST · 网络安全
## 目录
1. [问题陈述](#1-problem-statement)
2. [提出架构](#2-proposed-architecture)
3. [工作原理](#3-how-it-works)
4. [数据集](#4-dataset)
5. [结果与指标](#5-results--metrics)
6. [代码架构](#6-code-architecture)
7. [核心模块深入解析](#7-core-modules--deep-dive)
8. [设置与使用](#8-setup--usage)
9. [实现 - 分阶段详解](#9-implementation--phase-by-phase)
10. [局限性与未来工作](#10-limitations--future-work)
11. [团队](#11-team)
[导师](#12-mentor)
## 1. 问题陈述
### 传统方法为何失效
| 方法 | 局限性 |
|---|---|
| 集中式机器学习 | 所有原始数据发送到一台服务器,完全侵犯隐私 |
| 标准联邦学习 | 未验证客户端更新,恶意客户端破坏全局模型 |
| 仅加密的联邦学习 | 无审计追踪、无问责机制、搭便车问题未解决 |
| 基于签名的入侵检测系统 | 无法检测新型投毒攻击模式 |
### 问题为何存在
- 联邦学习客户端不受信任——任何设备都可以提交任意的权重更新
- 在去中心化系统中,没有中央权威机构来验证贡献
- 模型投毒攻击(发送大量随机噪声作为权重)可以在单轮内破坏全局模型的准确性
- 现有的轻量级机制无法同时提供:隐私 + 验证 + 问责 + 抗攻击弹性
### 需要什么
- 一个**无需信任的验证层**(区块链),永久记录每次更新
- 一个**隐私机制**(差分隐私),防止权重重构
- 一个**信任评分系统**(贡献证明),识别并阻断恶意行为者
- 一个**可复现的仿真环境**,展示这三个机制协同工作
## 2. 提出架构
```
┌──────────────────────────────────────────────────────────────────┐
│ BFL SYSTEM ARCHITECTURE │
│ │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │Client 1 │ │Client 2 │ │Client 3 │ │Client 4 │ │Client 5 │ │
│ │ 12,000 │ │ 12,000 │ │ATTACKER │ │ 12,000 │ │ 12,000 │ │
│ │ images │ │ images │ │(poison) │ │ images │ │ images │ │
│ └────┬────┘ └────┬────┘ └────┬────┘ └────┬────┘ └────┬────┘ │
│ └───────────┴───────────┴───────────┴───────────┘ │
│ │ │
│ ┌────────────────▼──────────────────┐ │
│ │ Differential Privacy │ │
│ │ w_private = w + N(0, sigma) │ │
│ └────────────────┬──────────────────┘ │
│ │ │
│ ┌────────────────▼──────────────────┐ │
│ │ Ethereum Blockchain (Ganache) │ │
│ │ ModelRegistry.sol │ │
│ │ SHA-256 hash logged on-chain │ │
│ │ Client address + timestamp saved│ │
│ └────────────────┬──────────────────┘ │
│ │ │
│ ┌────────────────▼──────────────────┐ │
│ │ Trust Scoring - PoC │ │
│ │ T_i = alpha*T_i + (1-alpha)*S_i │ │
│ │ if T_i < 0.85 → REJECT │ │
│ └────────────────┬──────────────────┘ │
│ │ │
│ ┌────────────────▼──────────────────┐ │
│ │ Federated Server - FedAvg │ │
│ │ w = sum(p_i * w_i) │ │
│ │ honest clients only │ │
│ └───────────────────────────────────┘ │
└──────────────────────────────────────────────────────────────────┘
```
### 系统组件
| # | 组件 | 角色 | 输出 |
|---|---|---|---|
| 1 | 客户端 (x5) | 在私有MNIST分区上本地训练CNN | 本地模型权重 |
| 2 | 差分隐私 | 提交前添加高斯噪声 | 受保护的权重向量 |
| 3 | 区块链 (Ganache) | 将每次更新的SHA-256哈希值记录在链上 | 不可变的交易记录 |
| 4 | 智能合约 | 验证并存储模型更新元数据 | 链上审计日志 |
| 5 | 信任评分 (PoC) | 每个客户端的余弦相似度信任分数 | 接受 / 拒绝决定 |
| 6 | 联邦服务器 | 仅对已验证的更新执行FedAvg | 更新后的全局模型 |
| 7 | 全局模型 | 每轮在10,000张测试图像上评估 | 准确率 + 损失指标 |
## 3. 工作原理
### 决策逻辑
```
Each FL Round:
─────────────────────────────────────────────────────────────
For each client i:
1. Receive global model weights from server
2. Train locally on private dataset (2 epochs, SGD)
3. Add differential privacy noise to weights
4. Compute SHA-256 hash of noisy weights
5. Submit hash to blockchain (smart contract)
6. Compute cosine similarity with global model
7. Update trust score: T_i = 0.9*T_i + 0.1*S_i
If T_i >= 0.85 → ACCEPTED → included in FedAvg
If T_i < 0.85 → REJECTED → excluded permanently
(first rejection → global model RESET to clean state)
Server:
Collect only accepted updates
w_global = sum(p_i * w_i) [FedAvg]
Evaluate on 10,000 test images
Broadcast updated global model to all clients
─────────────────────────────────────────────────────────────
```
### 流程图
```
Raw MNIST Data
↓
Split across 5 Clients (12,000 each)
↓
Local CNN Training (SGD, 2 epochs per round)
↓
Differential Privacy Noise Added (epsilon=100)
↓
SHA-256 Hash → Ethereum Smart Contract (Ganache)
↓
Trust Score Computed via Cosine Similarity
↓
Accept / Reject Decision (threshold = 0.85)
↓
FedAvg Aggregation (honest clients only)
↓
Global Model Evaluated on Test Set
↓
Next Round ↺ (repeat up to 15 rounds)
```
### 关键公式
**FedAvg聚合:**
```
w_global(t+1) = sum over i of [ p_i * w_i(t+1) ]
p_i = m_i / sum(m_i) (data proportion of client i)
```
**本地SGD更新:**
```
w_i(t+1) = w_i(t) - eta * gradient_L_i(w_i(t))
eta = learning rate, L_i = cross-entropy loss
```
**差分隐私:**
```
w_private = w + N(0, sensitivity / epsilon)
epsilon = 100.0, sensitivity = 1.0, noise_scale = 0.01
```
**贡献证明信任评分:**
```
S_i(t) = dot(w_global, w_local) / (||w_global|| * ||w_local||)
T_i(t+1) = 0.9 * T_i(t) + 0.1 * S_i(t)
if T_i < 0.85 → REJECTED
```
**准确率:**
```
A = Correct Predictions / Total Predictions
```
## 4. 数据集
### MNIST - 手写数字识别
| 属性 | 值 |
|---|---|
| 全称 | 改进的国家标准与技术研究院数据集 |
| 总图像数 | 70,000张灰度图像 |
| 训练集 | 60,000张图像(跨5个客户端划分) |
| 测试集 | 10,000张图像(每轮进行全局评估) |
| 图像尺寸 | 28 x 28像素(每张图像784个特征) |
| 颜色 | 灰度(0=黑,255=白,归一化至0.0–1.0) |
| 类别数 | 10类(数字0到9) |
| 文件大小 | ~11 MB |
| 来源 | Yann LeCun, Corinna Cortes - NYU |
| 下载方式 | 通过 tf.keras.datasets.mnist.load_data() 自动下载 |
### 数据如何在客户端间划分
```
Total Training Images: 60,000
──────────────────────────────────────────
Client 1 → 12,000 images (honest)
Client 2 → 12,000 images (honest)
Client 3 → 12,000 images (ATTACKER - sends poisoned weights)
Client 4 → 12,000 images (honest)
Client 5 → 12,000 images (honest)
──────────────────────────────────────────
Test Set → 10,000 images (server only - never shared)
```
### 为何选择MNIST?
- 原始论文中三个基准数据集之一(另外两个是CIFAR-10和IoT-IDS)
- 训练速度快——一轮在CPU上约30秒完成
- 普遍认可——96%+的准确率对任何评审员都立即具有意义
- 足够简单,便于专注于区块链和隐私机制,而非数据集复杂性
## 5. 结果与指标
### 各阶段准确率
| 轮次 | 阶段 1 - FedAvg | 阶段 2 - BFL | 阶段 3 - BFL+DP+Trust |
|-------|-----------------|---------------|------------------------|
| 1 | 0.9086 | 0.9086 | 0.0434 (被攻击) |
| 2 | 0.9210 | 0.9210 | - (模型重置) |
| 3 | 0.9299 | 0.9299 | 0.9059 (已恢复) |
| 4 | 0.9401 | 0.9401 | 0.9232 |
| 5 | 0.9450 | 0.9450 | 0.9344 |
| 6 | 0.9502 | 0.9502 | 0.9385 |
| 7 | 0.9537 | 0.9537 | 0.9471 |
| 8 | 0.9575 | 0.9575 | 0.9503 |
| 9 | 0.9599 | 0.9599 | 0.9551 |
| 10 | 0.9620 | 0.9620 | 0.9547 |
| 15 | - | - | **0.9678** |
### 最终摘要表
| 指标 | 阶段 1 - FedAvg | 阶段 2 - BFL | 阶段 3 - BFL+DP+Trust |
|--------|-----------------|---------------|------------------------|
| 最终准确率 | 96.20% | 96.20% | **96.78%** |
| 检测到攻击 | 否 | 否 | **是 - 第2轮** |
| 攻击者最终信任度 | N/A | N/A | **0.206 (被拒绝)** |
| 链上更新数 | 0 | 50 | **61** |
| 隐私机制 | 无 | SHA-256 哈希 | **DP + 信任评分** |
| 原始数据共享 | 从未 | 从未 | 从未 |
| 收敛所需轮次 | 10 | 10 | 15 (包含恢复) |
### 攻击者信任评分衰减
```
Round 0: Trust = 1.000 starting value
Round 1: Trust = 0.900 ACCEPTED (not caught yet)
Round 2: Trust = 0.810 REJECTED ← blocked permanently
Round 3: Trust = 0.729 REJECTED
Round 4: Trust = 0.656 REJECTED
Round 5: Trust = 0.590 REJECTED
Round 7: Trust = 0.478 REJECTED
Round 10: Trust = 0.349 REJECTED
Round 15: Trust = 0.206 REJECTED (permanently flagged)
```
### 与论文对比
| 指标 | 论文 (完整 BFL) | 我们的实现 |
|--------|-----------------|-------------------|
| MNIST 准确率 | 99.2% | 96.78% |
| 抗攻击弹性 | 92.8% | 攻击者在第2轮被阻断 |
| 隐私机制 | HE + ZKP + DP | DP + 信任评分 |
| 区块链 | 以太坊 PoC | Ganache (本地以太坊) |
| 客户端数量 | 100 | 5 |
| 硬件 | NVIDIA Tesla V100 GPU | 本地 CPU (Windows) |
### 性能图表
```
Generated by: python generate_results.py
figure2_comparison.png Bar chart: final accuracy per phase
figure3_blockchain_updates.png On-chain update counts per phase
```
## 6. 代码架构
```
bfl_project/
│
├── fl_phase1.py Phase 1: Federated Learning baseline
├── bfl_phase2.py Phase 2: FL + Blockchain integration
├── bfl_phase3.py Phase 3: FL + DP + Trust scoring
│
├── blockchain.py Web3.py connection, hash, deploy, submit
├── ModelRegistry.sol Solidity smart contract (Ethereum)
│
├── generate_results.py Generate all result graphs
│
├── figure1_accuracy_trust.png Accuracy + trust score chart
├── figure2_comparison.png Phase comparison bar chart
├── figure3_blockchain_updates.png On-chain updates chart
│
├── project_report.md Full written project report
└── README.md This file
```
## 7. 核心模块深入解析
### 联邦学习核心 (`fl_phase1.py`)
**文件:** `fl_phase1.py`
**功能:** 模拟一个完整的联邦学习训练循环。5个客户端各自在12,000张私有MNIST图像上本地训练CNN,然后中央服务器使用FedAvg聚合10轮,期间无原始数据交换。
**CNN架构:**
```
Input: 28x28x1 image
Conv2D (32 filters, 3x3, ReLU) detects edges and digit patterns
MaxPooling2D reduces spatial size by half
Flatten converts 2D feature map to 1D
Dense (64 units, ReLU) learns high-level combinations
Dense (10 units, Softmax) outputs probability for each digit
Output: probability vector [digit 0, digit 1, ..., digit 9]
```
**公式:**
```
w_global = sum(p_i * w_i) where p_i = m_i / sum(m_i)
```
### 区块链层 (`blockchain.py` + `ModelRegistry.sol`)
**文件:** `blockchain.py`, `ModelRegistry.sol`
**功能:** 使用Web3.py将Python连接到本地以太坊区块链。编译并部署Solidity智能合约。每个客户端提交其权重的SHA-256指纹——与客户端地址、轮次和时间戳一起永久记录在链上。
**智能合约结构:**
```
struct ModelUpdate {
address client;
bytes32 updateHash;
uint256 roundNumber;
bool isVerified;
uint256 timestamp;
}
```
**关键函数:**
```
submitUpdate(bytes32 hash, uint256 round)
getVerifiedUpdates(uint256 round)
getTotalUpdates()
```
### 差分隐私 (`bfl_phase3.py`)
**函数:** `add_differential_privacy(weights, epsilon=100.0)`
**功能:** 在客户端提交权重前添加校准的高斯噪声。防止对手从截获的权重向量中重构原始训练数据。
**公式:**
```
w_private = w + N(0, sensitivity/epsilon)
epsilon = 100.0 (privacy budget)
noise = 0.01 per weight value
```
### 信任评分 - 贡献证明 (`bfl_phase3.py`)
**函数:** `compute_trust_score(global_weights, local_weights, prev_score)`
**功能:** 衡量每轮中客户端的更新方向与全局模型的相似程度。通过指数衰减维护运行历史记录。攻击者持续偏离 → 信任分低于阈值 → 被永久阻断。
**公式:**
```
S_i = dot(w_global, w_local) / (||w_global|| * ||w_local||)
T_i = 0.9 * T_i_prev + 0.1 * S_i
REJECT if T_i < 0.85
```
**为何有效:**
```
Honest client: S_i ~ 0.9–1.0 (update aligned with global) → trust stays high
Attacker: S_i ~ 0.000 (random noise, unrelated) → trust decays fast
```
### 攻击模拟 (`bfl_phase3.py`)
**函数:** `poison_weights(weights)`
**功能:** 模拟真实世界的数据投毒攻击。客户端3用大规模的随机噪声替换其合法的模型更新,以破坏全局模型。
```
def poison_weights(weights):
return [np.random.randn(*w.shape) * 10 for w in weights]
# Scale x10 ensures weights are wildly different from honest updates
# Cosine similarity with global model ≈ 0.000
```
### 结果生成 (`generate_results.py`)
## 8. 设置与使用
### 依赖项
| 组件 | 版本 |
|---|---|
| Python | 3.8+ (推荐3.11) |
| TensorFlow | 2.x |
| NumPy | 任何近期版本 |
| Web3.py | 6.x |
| py-solc-x | 任何版本 |
| Matplotlib | 任何版本 |
| Node.js | 用于Ganache |
| Ganache CLI | v7.9.2 |
### 安装
```
# 步骤 1: 安装 Ganache (本地 Ethereum 区块链)
npm install -g ganache
# 步骤 2: 安装 Python 依赖项
pip install tensorflow numpy matplotlib web3 py-solc-x
# 步骤 3: 安装 Solidity compiler (仅运行一次)
python -c "from solcx import install_solc; install_solc('0.8.0')"
```
### 运行项目
**终端 1 - 启动区块链(全程保持此终端打开):**
```
ganache --port 8545 --accounts 10 --deterministic
```
**终端 2 - 按顺序运行每个阶段:**
```
# 阶段 1: 基准 federated learning
python fl_phase1.py
# 阶段 2: FL + Blockchain 记录
python bfl_phase2.py
# 阶段 3: FL + Blockchain + DP + 攻击检测
python bfl_phase3.py
# 生成所有结果图表
python generate_results.py
```
### 常见错误及修复
| 错误 | 修复方法 |
|---|---|
| `ConnectionRefusedError` | Ganache未运行 - 重启终端1 |
| `ModuleNotFoundError: web3` | 运行 `pip install web3` |
| `ModuleNotFoundError: solcx` | 运行 `pip install py-solc-x` |
| `FileNotFoundError: ModelRegistry.sol` | 在 `bfl_project/` 文件夹内运行 |
| `SolcError` | 运行 `python -c "from solcx import install_solc; install_solc('0.8.0')"` |
| Windows上的TensorFlow GPU警告 | 可以安全忽略 - CPU训练正常工作 |
## 9. 实现 - 分阶段详解
### 阶段 1: 联邦学习基准
**文件:** `fl_phase1.py`
**目标:** 证明5个客户端可以在不共享原始数据的情况下协作训练一个数字分类器。
**每轮发生的事情:**
- 全局模型权重发送给所有5个客户端
- 每个客户端本地训练CNN 2个epoch(SGD优化器)
- 客户端将更新后的权重(非数据)返回给服务器
- 服务器计算FedAvg → 新的全局模型
- 全局模型在10,000张测试图像上进行评估
**结果:**
```
Round 1 → Accuracy: 90.86% Loss: 0.3296
Round 5 → Accuracy: 94.50% Loss: 0.1909
Round 10 → Accuracy: 96.20% Loss: 0.1292 ← final baseline
On-chain updates: 0
```
### 阶段 2: 区块链集成
**文件:** `bfl_phase2.py`, `blockchain.py`, `ModelRegistry.sol`
**目标:** 将每个模型更新永久记录在以太坊上,实现完全防篡改的审计追踪。
**新增内容:**
- 启动时编译并部署 `ModelRegistry.sol` 到Ganache
- 每个客户端计算权重的SHA-256哈希值 → 提交给智能合约
- 区块链记录:客户端钱包地址、哈希值、轮次、时间戳
- 服务器在运行FedAvg前从区块链读取已验证的更新列表
**结果:**
```
Contract deployed: 0xe78A0F7E598Cc8b0Bb87894B0F60dD2a88d6a8Ab
Round 1 → 5 updates logged on-chain | Accuracy: 90.86%
Round 5 → 5 updates logged on-chain | Accuracy: 94.50%
Round 10 → 5 updates logged on-chain | Accuracy: 96.20%
──────────────────────────────────────────────────────────
Total on-chain updates: 50 (5 clients × 10 rounds)
Final accuracy: 96.20%
```
### 阶段 3: 隐私 + 攻击检测(主要结果)
**文件:** `bfl_phase3.py`
**目标:** 检测并阻断恶意客户端,同时保护诚实客户端的隐私。
**新增的三个机制:**
1. 差分隐私 - 向所有客户端权重添加高斯噪声(epsilon=100)
2. 余弦相似度信任评分 - 每轮对每个客户端进行评分
3. 自动拒绝 - 信任评分低于0.85触发永久阻断
4. 模型重置 - 当首次捕获到攻击者时,重新初始化全局模型
**攻击时间线:**
```
Round 1:
Client 3 submits poison | similarity=-0.002 | trust=0.900 | ACCEPTED
Model corrupted → Accuracy drops to 4.34%
Round 2:
Client 3 submits poison | similarity=+0.001 | trust=0.810 | REJECTED
Global model RESET to clean state
Accepted clients: [1, 2, 4, 5]
Round 3:
4 clean clients train on reset model
Accuracy: 90.59% ← recovered in exactly 1 round
Round 5: Accuracy: 93.44%
Round 7: Accuracy: 94.71%
Round 10: Accuracy: 95.47%
Round 15: Accuracy: 96.78% ← final result
Attacker trust at round 15: 0.206 (permanently flagged)
Total on-chain updates: 61
```
## 10. 局限性与未来工作
| 论文特性 | 我们的实现 | 如何改进 |
|---|---|---|
| 100个客户端 | 5个模拟客户端 | 使用TensorFlow Federated扩展 |
| 同态加密 (HE) | 仅SHA-256哈希 | 集成Microsoft SEAL或PySyft HE |
| 零知识证明 (ZKP) | 通过信任评分模拟 | 实现ZoKrates或snarkjs |
| CIFAR-10 + IoT-IDS数据集 | 仅MNIST | 添加CIFAR-10并使用ResNet模型 |
| 云GPU部署 | 本地CPU (Windows) | 部署到AWS/GCP的GPU实例 |
| 以太坊公共测试网 | 仅本地Ganache | 部署到以太坊Sepolia测试网 |
| 自适应共识阈值 | 固定为0.85 | 每轮动态阈值 |
| 实时推理API | 批量模拟 | 添加Flask或FastAPI预测端点 |
## 关键概念术语表
| 术语 | 通俗解释 |
|---|---|
| **联邦学习** | 在多个设备上训练AI而不共享原始数据 |
| **FedAvg** | 服务器使用加权平均公式组合客户端更新 |
| **区块链** | 所有交易的永久防篡改公开记录 |
| **智能合约** | 以太坊上的自执行代码——自动运行,无需人工 |
| **Ganache** | 用于开发和测试的本地以太坊区块链 |
| **差分隐私** | 添加校准的随机噪声以防止数据被逆向工程 |
| **信任评分** | 一个运行中的分数,追踪客户端一段时间以来的诚实程度 |
| **余弦相似度** | 衡量两个向量是否指向同一方向(0=无关,1=相同) |
| **贡献证明** | 奖励诚实模型更新的共识机制 |
| **数据投毒攻击** | 恶意客户端发送随机垃圾权重以破坏全局模型 |
| **SHA-256** | 将权重转换为唯一指纹的加密哈希函数 |
| **Web3.py** | 与以太坊区块链通信的Python库 |
| **MNIST** | 70,000张手写数字图像的数据集,标准ML基准 |
## 11. 团队
| 姓名 | USN | 邮箱 |
|---|---|---|
| Aman Nayan | ENG23CY0004 | amannayan1905@gmail.com |
| Kushal M G | ENG23CY0022 | eng23cy0022@dsu.edu.in |
| Likith M | ENG23CY0023 | Likith.mib01@gmail.com |
| Madhukar N | ENG23CY0024 | madhukarnagaraju8050@gmail.com |
| Narasimha Murthy K | ENG23CY0026 | narasimhabtech27@gmail.com |
## 导师
**Prajwalasimha S N 博士**
计算机科学与工程系(网络安全)副教授
工程学院,Dayananda Sagar 大学,班加罗尔 - 562112
邮箱:prajwasimha.sn1@gmail.com
## 实现于
**Dayananda Sagar 大学**
### 🏫 系别
**计算机科学与工程系(网络安全)**
工程学院,Dayananda Sagar 大学
## 🧑🏫 导师
**Prajwalasimha S N 博士**
_博士,博士后 (NewRIIS)_
副教授
计算机科学与工程系(网络安全)
工程学院,Dayananda Sagar 大学
## 🔬 实验室
**TTEH 实验室**
工程学院
Dayananda Sagar 大学
📍 班加罗尔 – 562112, 卡纳塔克邦, 印度
## 12. 📄 IEEE 论文
**DOI:** https://doi.org/10.1109/ICISC65841.2025.11187566
## 6. 代码架构
```
bfl_project/
│
├── fl_phase1.py Phase 1: Federated Learning baseline
├── bfl_phase2.py Phase 2: FL + Blockchain integration
├── bfl_phase3.py Phase 3: FL + DP + Trust scoring
│
├── blockchain.py Web3.py connection, hash, deploy, submit
├── ModelRegistry.sol Solidity smart contract (Ethereum)
│
├── generate_results.py Generate all result graphs
│
├── figure1_accuracy_trust.png Accuracy + trust score chart
├── figure2_comparison.png Phase comparison bar chart
├── figure3_blockchain_updates.png On-chain updates chart
│
├── project_report.md Full written project report
└── README.md This file
```
## 7. 核心模块深入解析
### 联邦学习核心 (`fl_phase1.py`)
**文件:** `fl_phase1.py`
**功能:** 模拟一个完整的联邦学习训练循环。5个客户端各自在12,000张私有MNIST图像上本地训练CNN,然后中央服务器使用FedAvg聚合10轮,期间无原始数据交换。
**CNN架构:**
```
Input: 28x28x1 image
Conv2D (32 filters, 3x3, ReLU) detects edges and digit patterns
MaxPooling2D reduces spatial size by half
Flatten converts 2D feature map to 1D
Dense (64 units, ReLU) learns high-level combinations
Dense (10 units, Softmax) outputs probability for each digit
Output: probability vector [digit 0, digit 1, ..., digit 9]
```
**公式:**
```
w_global = sum(p_i * w_i) where p_i = m_i / sum(m_i)
```
### 区块链层 (`blockchain.py` + `ModelRegistry.sol`)
**文件:** `blockchain.py`, `ModelRegistry.sol`
**功能:** 使用Web3.py将Python连接到本地以太坊区块链。编译并部署Solidity智能合约。每个客户端提交其权重的SHA-256指纹——与客户端地址、轮次和时间戳一起永久记录在链上。
**智能合约结构:**
```
struct ModelUpdate {
address client;
bytes32 updateHash;
uint256 roundNumber;
bool isVerified;
uint256 timestamp;
}
```
**关键函数:**
```
submitUpdate(bytes32 hash, uint256 round)
getVerifiedUpdates(uint256 round)
getTotalUpdates()
```
### 差分隐私 (`bfl_phase3.py`)
**函数:** `add_differential_privacy(weights, epsilon=100.0)`
**功能:** 在客户端提交权重前添加校准的高斯噪声。防止对手从截获的权重向量中重构原始训练数据。
**公式:**
```
w_private = w + N(0, sensitivity/epsilon)
epsilon = 100.0 (privacy budget)
noise = 0.01 per weight value
```
### 信任评分 - 贡献证明 (`bfl_phase3.py`)
**函数:** `compute_trust_score(global_weights, local_weights, prev_score)`
**功能:** 衡量每轮中客户端的更新方向与全局模型的相似程度。通过指数衰减维护运行历史记录。攻击者持续偏离 → 信任分低于阈值 → 被永久阻断。
**公式:**
```
S_i = dot(w_global, w_local) / (||w_global|| * ||w_local||)
T_i = 0.9 * T_i_prev + 0.1 * S_i
REJECT if T_i < 0.85
```
**为何有效:**
```
Honest client: S_i ~ 0.9–1.0 (update aligned with global) → trust stays high
Attacker: S_i ~ 0.000 (random noise, unrelated) → trust decays fast
```
### 攻击模拟 (`bfl_phase3.py`)
**函数:** `poison_weights(weights)`
**功能:** 模拟真实世界的数据投毒攻击。客户端3用大规模的随机噪声替换其合法的模型更新,以破坏全局模型。
```
def poison_weights(weights):
return [np.random.randn(*w.shape) * 10 for w in weights]
# Scale x10 ensures weights are wildly different from honest updates
# Cosine similarity with global model ≈ 0.000
```
### 结果生成 (`generate_results.py`)
## 8. 设置与使用
### 依赖项
| 组件 | 版本 |
|---|---|
| Python | 3.8+ (推荐3.11) |
| TensorFlow | 2.x |
| NumPy | 任何近期版本 |
| Web3.py | 6.x |
| py-solc-x | 任何版本 |
| Matplotlib | 任何版本 |
| Node.js | 用于Ganache |
| Ganache CLI | v7.9.2 |
### 安装
```
# 步骤 1: 安装 Ganache (本地 Ethereum 区块链)
npm install -g ganache
# 步骤 2: 安装 Python 依赖项
pip install tensorflow numpy matplotlib web3 py-solc-x
# 步骤 3: 安装 Solidity compiler (仅运行一次)
python -c "from solcx import install_solc; install_solc('0.8.0')"
```
### 运行项目
**终端 1 - 启动区块链(全程保持此终端打开):**
```
ganache --port 8545 --accounts 10 --deterministic
```
**终端 2 - 按顺序运行每个阶段:**
```
# 阶段 1: 基准 federated learning
python fl_phase1.py
# 阶段 2: FL + Blockchain 记录
python bfl_phase2.py
# 阶段 3: FL + Blockchain + DP + 攻击检测
python bfl_phase3.py
# 生成所有结果图表
python generate_results.py
```
### 常见错误及修复
| 错误 | 修复方法 |
|---|---|
| `ConnectionRefusedError` | Ganache未运行 - 重启终端1 |
| `ModuleNotFoundError: web3` | 运行 `pip install web3` |
| `ModuleNotFoundError: solcx` | 运行 `pip install py-solc-x` |
| `FileNotFoundError: ModelRegistry.sol` | 在 `bfl_project/` 文件夹内运行 |
| `SolcError` | 运行 `python -c "from solcx import install_solc; install_solc('0.8.0')"` |
| Windows上的TensorFlow GPU警告 | 可以安全忽略 - CPU训练正常工作 |
## 9. 实现 - 分阶段详解
### 阶段 1: 联邦学习基准
**文件:** `fl_phase1.py`
**目标:** 证明5个客户端可以在不共享原始数据的情况下协作训练一个数字分类器。
**每轮发生的事情:**
- 全局模型权重发送给所有5个客户端
- 每个客户端本地训练CNN 2个epoch(SGD优化器)
- 客户端将更新后的权重(非数据)返回给服务器
- 服务器计算FedAvg → 新的全局模型
- 全局模型在10,000张测试图像上进行评估
**结果:**
```
Round 1 → Accuracy: 90.86% Loss: 0.3296
Round 5 → Accuracy: 94.50% Loss: 0.1909
Round 10 → Accuracy: 96.20% Loss: 0.1292 ← final baseline
On-chain updates: 0
```
### 阶段 2: 区块链集成
**文件:** `bfl_phase2.py`, `blockchain.py`, `ModelRegistry.sol`
**目标:** 将每个模型更新永久记录在以太坊上,实现完全防篡改的审计追踪。
**新增内容:**
- 启动时编译并部署 `ModelRegistry.sol` 到Ganache
- 每个客户端计算权重的SHA-256哈希值 → 提交给智能合约
- 区块链记录:客户端钱包地址、哈希值、轮次、时间戳
- 服务器在运行FedAvg前从区块链读取已验证的更新列表
**结果:**
```
Contract deployed: 0xe78A0F7E598Cc8b0Bb87894B0F60dD2a88d6a8Ab
Round 1 → 5 updates logged on-chain | Accuracy: 90.86%
Round 5 → 5 updates logged on-chain | Accuracy: 94.50%
Round 10 → 5 updates logged on-chain | Accuracy: 96.20%
──────────────────────────────────────────────────────────
Total on-chain updates: 50 (5 clients × 10 rounds)
Final accuracy: 96.20%
```
### 阶段 3: 隐私 + 攻击检测(主要结果)
**文件:** `bfl_phase3.py`
**目标:** 检测并阻断恶意客户端,同时保护诚实客户端的隐私。
**新增的三个机制:**
1. 差分隐私 - 向所有客户端权重添加高斯噪声(epsilon=100)
2. 余弦相似度信任评分 - 每轮对每个客户端进行评分
3. 自动拒绝 - 信任评分低于0.85触发永久阻断
4. 模型重置 - 当首次捕获到攻击者时,重新初始化全局模型
**攻击时间线:**
```
Round 1:
Client 3 submits poison | similarity=-0.002 | trust=0.900 | ACCEPTED
Model corrupted → Accuracy drops to 4.34%
Round 2:
Client 3 submits poison | similarity=+0.001 | trust=0.810 | REJECTED
Global model RESET to clean state
Accepted clients: [1, 2, 4, 5]
Round 3:
4 clean clients train on reset model
Accuracy: 90.59% ← recovered in exactly 1 round
Round 5: Accuracy: 93.44%
Round 7: Accuracy: 94.71%
Round 10: Accuracy: 95.47%
Round 15: Accuracy: 96.78% ← final result
Attacker trust at round 15: 0.206 (permanently flagged)
Total on-chain updates: 61
```
## 10. 局限性与未来工作
| 论文特性 | 我们的实现 | 如何改进 |
|---|---|---|
| 100个客户端 | 5个模拟客户端 | 使用TensorFlow Federated扩展 |
| 同态加密 (HE) | 仅SHA-256哈希 | 集成Microsoft SEAL或PySyft HE |
| 零知识证明 (ZKP) | 通过信任评分模拟 | 实现ZoKrates或snarkjs |
| CIFAR-10 + IoT-IDS数据集 | 仅MNIST | 添加CIFAR-10并使用ResNet模型 |
| 云GPU部署 | 本地CPU (Windows) | 部署到AWS/GCP的GPU实例 |
| 以太坊公共测试网 | 仅本地Ganache | 部署到以太坊Sepolia测试网 |
| 自适应共识阈值 | 固定为0.85 | 每轮动态阈值 |
| 实时推理API | 批量模拟 | 添加Flask或FastAPI预测端点 |
## 关键概念术语表
| 术语 | 通俗解释 |
|---|---|
| **联邦学习** | 在多个设备上训练AI而不共享原始数据 |
| **FedAvg** | 服务器使用加权平均公式组合客户端更新 |
| **区块链** | 所有交易的永久防篡改公开记录 |
| **智能合约** | 以太坊上的自执行代码——自动运行,无需人工 |
| **Ganache** | 用于开发和测试的本地以太坊区块链 |
| **差分隐私** | 添加校准的随机噪声以防止数据被逆向工程 |
| **信任评分** | 一个运行中的分数,追踪客户端一段时间以来的诚实程度 |
| **余弦相似度** | 衡量两个向量是否指向同一方向(0=无关,1=相同) |
| **贡献证明** | 奖励诚实模型更新的共识机制 |
| **数据投毒攻击** | 恶意客户端发送随机垃圾权重以破坏全局模型 |
| **SHA-256** | 将权重转换为唯一指纹的加密哈希函数 |
| **Web3.py** | 与以太坊区块链通信的Python库 |
| **MNIST** | 70,000张手写数字图像的数据集,标准ML基准 |
## 11. 团队
| 姓名 | USN | 邮箱 |
|---|---|---|
| Aman Nayan | ENG23CY0004 | amannayan1905@gmail.com |
| Kushal M G | ENG23CY0022 | eng23cy0022@dsu.edu.in |
| Likith M | ENG23CY0023 | Likith.mib01@gmail.com |
| Madhukar N | ENG23CY0024 | madhukarnagaraju8050@gmail.com |
| Narasimha Murthy K | ENG23CY0026 | narasimhabtech27@gmail.com |
## 导师
**Prajwalasimha S N 博士**
计算机科学与工程系(网络安全)副教授
工程学院,Dayananda Sagar 大学,班加罗尔 - 562112
邮箱:prajwasimha.sn1@gmail.com
## 实现于
**Dayananda Sagar 大学**
### 🏫 系别
**计算机科学与工程系(网络安全)**
工程学院,Dayananda Sagar 大学
## 🧑🏫 导师
**Prajwalasimha S N 博士**
_博士,博士后 (NewRIIS)_
副教授
计算机科学与工程系(网络安全)
工程学院,Dayananda Sagar 大学
## 🔬 实验室
**TTEH 实验室**
工程学院
Dayananda Sagar 大学
📍 班加罗尔 – 562112, 卡纳塔克邦, 印度
## 12. 📄 IEEE 论文
**DOI:** https://doi.org/10.1109/ICISC65841.2025.11187566标签:Apex, Ganache, MNIST数据集, ProjectDiscovery, Python, Solidity, TensorFlow, Web3, 人工智能, 人工智能安全, 以太坊, 信任评分机制, 分布式AI, 区块链, 区块链技术, 卷积神经网络, 去中心化学习, 合规性, 安全聚合, 审计跟踪, 差分隐私, 恶意客户端检测, 数据保护, 数据隐私, 无后门, 智能合约, 机器学习, 模型注册表, 用户模式Hook绕过, 联邦学习, 联邦学习安全, 联邦平均, 贡献证明, 逆向工具, 隐私保护AI, 隐私保护机器学习