dungnotnull/smart-contract-sentinel-agent
GitHub: dungnotnull/smart-contract-sentinel-agent
一个多链 DeFi 智能合约实时防御代理,通过 mempool 监听、状态模拟和 GNN 威胁评分在交易确认前拦截漏洞利用并自动暂停合约。
Stars: 2 | Forks: 0
# SmartSentinel
[](https://opensource.org/licenses/Apache-2.0)
[](https://www.typescriptlang.org/)
[](https://nodejs.org/)
[](https://www.python.org/)
## 概述
SmartSentinel 是一个为 DeFi 协议设计的自主、全天候防御 agent。它解决了静态分析工具(如 Slither, Mythril, Echidna)无法解决的根本问题:**在实时区块链状态上进行动态、runtime 攻击检测**。
当攻击者向 mempool 提交恶意交易时,他们通常在确认前有一个 **2-12 秒的时间窗口**。SmartSentinel 完全在这个关键的时间窗口内运作:
1. 通过 WebSocket 和私有 relay(Flashbots, Jito)**监听**公共 mempool
2. 使用快速启发式算法 (< 5ms) **预过滤**可疑交易
3. 针对本地 Anvil fork **模拟**被标记的交易,以测量流动性流失
4. 使用基于已知漏洞模式训练的 GNN 分类器对其进行**评分**
5. **决策** —— 如果威胁分数 > 阈值:触发 front-run bundle 以暂停目标合约
6. 向协议守护者**发送警报**,并附带完整的取证报告
### 当前状态:**v0.2.0 — Beta 就绪(约 80% 可投入生产)**
✅ **已实现:**
- 完整的 mempool 监听层(Ethereum + MEV-Share)
- 包含函数 selector、gas 异常和巨鲸追踪的 3 层预过滤器
- 带有 fork 池和流失计算的 Anvil 模拟引擎
- 采用 DA-GNN 架构的 GNN ML pipeline(推理服务器 + 客户端)
- 具有多信号威胁评估功能的决策引擎
- 警报系统(Telegram, PagerDuty, Slack)及取证报告
- 带有 gas 升级机制的 Flashbots front-run 响应
- 仅追加(Append-only)的 SQLite 事件日志
- 全面的测试套件(单元测试 + 集成测试)
- 漏洞重放验证框架
⚠️ **投入生产所需:**
- 训练好的 GNN 模型权重(目前使用占位符)
- 主网 RPC 凭证(Alchemy, Infura, QuickNode)
- 守护者钱包私钥(用于暂停交易)
- 生产环境监控部署
## 快速开始
### 前置条件
- **Node.js** >= 20.0.0
- **Python** >= 3.12
- **Anvil** (Foundry 工具链)
- **Git**
### 安装
```
# 克隆仓库
git clone https://github.com/your-org/smart-contract-sentinel-agent.git
cd smart-contract-sentinel-agent
# 安装 TypeScript 依赖
npm install
# 安装 Python ML 依赖
pip install -r ml-pipeline/requirements.txt --break-system-packages
# 验证 Anvil 安装
anvil --version
# 复制示例配置
cp config/chains.example.yml config/chains.yml
cp config/monitored-contracts.example.yml config/monitored-contracts.yml
cp config/thresholds.example.yml config/thresholds.yml
```
### 配置
编辑 `config/chains.yml` 以添加您的 RPC endpoint:
```
chains:
ethereum:
rpc_endpoints:
- "https://eth-mainnet.g.alchemy.com/v2/YOUR_API_KEY"
- "https://mainnet.infura.io/v3/YOUR_PROJECT_ID"
- "https://cloudflare-eth.com"
flashbots_relay: "https://relay.flashbots.net"
chain_id: 1
```
编辑 `config/monitored-contracts.yml` 以添加您想要防御的合约:
```
contracts:
- name: "Aave V3 Pool"
chain: ethereum
address: "0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2"
pause_method: "setPoolPause(bool)"
guardian_address: "0x..." # Multisig that owns pause rights
guardian_private_key_env: "AAVE_GUARDIAN_KEY"
tvl_usd: 5000000000
drain_threshold_pct: 3.0
gnn_threshold: 0.80
```
### 运行
```
# 开发模式(带详细日志)
npm run dev
# 生产环境 daemon
npm run start
# 监控但不触发响应(dry-run)
npm run start -- --chain ethereum --dry-run
# 检查系统健康状态
npm run status
# 查看事件日志
npm run incident-log
```
## 架构
SmartSentinel 采用**纵深防御**方法,包含三个过滤层:
### 1. 预过滤层 (< 5ms)
- **函数 Selector 匹配**:已知攻击模式的 4-byte 签名
- **受监控合约过滤器**:目标是否在白名单中?
- **已知攻击者注册表**:跨链攻击者钱包索引
- **Gas 异常检测**:异常的 gas 价格/限制模式
- **调用价值过滤器**:伴随调用的异常 ETH 价值
### 2. 模拟层 (200ms–1s)
- **Anvil Fork 池**:预热的主网状态本地 fork
- **交易模拟器**:在隔离的环境中执行 pending tx
- **流失计算器**:从状态变化中测量 % TVL 流失
- **重入检测**:解析调用 trace 以查找可疑深度
- **闪电贷检测**:识别对已知借贷池的调用
### 3. ML 评分层 (50–200ms)
- **GNN 分类器**:基于 bytecode CFG 的 DA-GNN 架构
- **特征提取器**:Bytecode → opcode → 图转换
- **威胁评分器**:将 ML 输出标准化为 0.0–1.0 分数
### 决策引擎
只有在满足**所有**条件时才会触发自动暂停:
```
gnn_score > config.gnn_threshold (default: 0.75)
AND drain_pct > config.drain_threshold (default: 3%)
AND heuristic_flags >= 1
```
否则,系统将在**仅警报模式**下运行 —— 仅通知守护者而不采取自主行动。
## 文档
- **[PROJECT-DETAIL.md](PROJECT-DETAIL.md)** — 完整的架构与设计规范
- **[PROJECT-DEVELOPMENT-PHASE-TRACKING.md](PROJECT-DEVELOPMENT-PHASE-TRACKING.md)** — Sprint 追踪器和实现状态
- **[CLAUDE.md](CLAUDE.md)** — Agent 操作手册
- **[RELEASE-NOTES.md](RELEASE-NOTES.md)** — 发布历史和变更
## 测试
SmartSentinel 包含各个层面的全面测试:
```
# 运行所有测试
npm test
# 运行特定测试套件
npm run test:unit # Unit tests only
npm run test:integration # Integration tests (requires Anvil)
npm run test:coverage # With coverage report
# 重放历史 exploits
npm run test:replay -- --exploit beanstalk-2022
# 生成测试 fixtures
npm run fixtures-generator
```
### 测试覆盖率
- **单元测试**:配置加载、日志记录、威胁评分、gas 升级
- **集成测试**:Anvil fork 管理、交易模拟、front-run 响应
- **漏洞重放**:Beanstalk (2022), Saddle Finance, Euler Finance, Nomad Bridge
## 开发
### 项目结构
```
smart-contract-sentinel-agent/
├── src/
│ ├── main.ts # Entry point (CLI + daemon)
│ ├── core/
│ │ ├── sentinel.ts # Main orchestrator
│ │ ├── decision-engine.ts # Multi-signal threat decision
│ │ └── config-loader.ts # Config validation
│ ├── listeners/ # Mempool + RPC pool
│ ├── filters/ # Pre-filter heuristics
│ ├── simulation/ # Anvil + drain calculator
│ ├── ml/ # GNN client + threat scorer
│ ├── response/ # Flashbots front-runner
│ ├── alerts/ # Dispatcher + Telegram/PagerDuty
│ └── storage/ # Incident log + attacker registry
├── ml-pipeline/ # Python GNN training + serving
│ ├── serve.py # FastAPI inference server
│ ├── train.py # Training entrypoint
│ └── models/
│ └── gnn_classifier.py # DA-GNN architecture
├── tests/
│ ├── unit/ # Unit tests
│ └── integration/ # Integration tests
├── config/ # YAML configurations
├── data/ # Runtime data
└── scripts/ # Utility scripts
```
### 关键命令
```
# 开发
npm run dev # Hot-reload development mode
npm run build # Build for production
npm run typecheck # TypeScript type checking
npm run lint # ESLint
# 运维
npm run status # System health check
npm run incident-log # View recent incidents
npm run replay-exploit # Simulate historical exploit
# Contract Management
npm run add-monitored-contract # Interactive CLI for adding contracts
```
## 部署
### Docker (推荐)
```
# 构建镜像
docker build -t smartsentinel:latest .
# 使用环境变量运行
docker run -d \
-e AAVE_GUARDIAN_KEY="0x..." \
-e TELEGRAM_BOT_TOKEN="..." \
-e PAGERDUTY_API_KEY="..." \
-v $(pwd)/config:/app/config \
-v $(pwd)/data:/app/data \
smartsentinel:latest
```
### Kubernetes
```
# 应用 Helm chart
helm install smartsentinel ./helm-chart \
--set chains.ethereum.rpcEndpoints[0]="https://..." \
--set guardians.aave.privateKeyEnv="AAVE_GUARDIAN_KEY"
```
### 手动部署
```
# 构建
npm run build
# 使用 PM2 运行
pm2 start dist/main.js --name smartsentinel
# 或者作为 systemd 服务
sudo systemctl enable smartsentinel
sudo systemctl start smartsentinel
```
## 安全与风险
### 风险缓解
- **三重门决策**:没有任何单一信号可以触发暂停
- **行动前模拟**:未确认流失绝不暂停
- **默认仅警报**:必须明确启用自动暂停
- **仅限私有 relay**:所有防御性 tx 均通过 Flashbots 发送,绝不进入公共 mempool
- **仅追加日志**:在 SQLite 中保留完整的审计跟踪
- **支持回滚**:GNN 模型版本控制,支持 30 秒内回滚
### 已知限制
- **私有 mempool 攻击**:使用 Flashbots Protect 的老练攻击者可能会逃避检测
- **Gas 战争**:攻击者可能会出价超过暂停 tx(通过 15% 的溢价来缓解)
- **模型过时**:随着新模式的出现,GNN 需要每月重新训练
## 许可证
Apache License 2.0 - 详情请参阅 [LICENSE](LICENSE)。
## 联系方式
- **问题**:[GitHub Issues](https://github.com/your-org/smart-contract-sentinel-agent/issues)
- **讨论**:[GitHub Discussions](https://github.com/your-org/smart-contract-sentinel-agent/discussions)
- **安全**:security@smartsentinel.io
## 路线图
### v0.3.0 (2026 年第二季度)
- [ ] 多链扩展(Arbitrum, Optimism, Base, Polygon)
- [ ] 带有重训练 pipeline 的增强 ML 模型
- [ ] 生产环境部署指南
### v0.4.0 (2026 年第三季度)
- [ ] 通过 Jito 集成提供 Solana 支持
- [ ] 知识大脑自动更新
- [ ] 用于监控的 Web 仪表板
### v1.0.0 (2026 年第四季度)
- [ ] 完整的生产版本发布
- [ ] 安全审计完成
- [ ] Beta 计划毕业
标签:DeFi, MEV, MITM代理, Python, TypeScript, 区块链安全, 图神经网络, 子域名突变, 安全插件, 无后门, 智能合约防御, 自动化攻击, 请求拦截, 逆向工具