Files
nofx/scripts/ENCRYPTION_README.md
T
tinkle-community f4ece051e7 Refactor/trading actions (#1169)
* refactor: 简化交易动作,移除 update_stop_loss/update_take_profit/partial_close
- 移除 Decision 结构体中的 NewStopLoss, NewTakeProfit, ClosePercentage 字段
- 删除 executeUpdateStopLossWithRecord, executeUpdateTakeProfitWithRecord, executePartialCloseWithRecord 函数
- 简化 logger 中的 partial_close 聚合逻辑
- 更新 AI prompt 和验证逻辑,只保留 6 个核心动作
- 清理相关测试代码
保留的交易动作: open_long, open_short, close_long, close_short, hold, wait
* refactor: 移除 AI学习与反思 模块
- 删除前端 AILearning.tsx 组件和相关引用
- 删除后端 /performance API 接口
- 删除 logger 中 AnalyzePerformance、calculateSharpeRatio 等函数
- 删除 PerformanceAnalysis、TradeOutcome、SymbolPerformance 等结构体
- 删除 Context 中的 Performance 字段
- 移除 AI prompt 中夏普比率自我进化相关内容
- 清理 i18n 翻译文件中的相关条目
该模块基于磁盘存储计算,经常出错,做减法移除
* refactor: 将数据库操作统一迁移到 store 包
- 新增 store/ 包,统一管理所有数据库操作
  - store.go: 主 Store 结构,懒加载各子模块
  - user.go, ai_model.go, exchange.go, trader.go 等子模块
  - 支持加密/解密函数注入 (SetCryptoFuncs)
- 更新 main.go 使用 store.New() 替代 config.NewDatabase()
- 更新 api/server.go 使用 *store.Store 替代 *config.Database
- 更新 manager/trader_manager.go:
  - 新增 LoadTradersFromStore, LoadUserTradersFromStore 方法
  - 删除旧版 LoadUserTraders, LoadTraderByID, loadSingleTrader 等方法
  - 移除 nofx/config 依赖
- 删除 config/database.go 和 config/database_test.go
- 更新 api/server_test.go 使用 store.Trader 类型
- 清理 logger/ 包中未使用的 telegram 相关代码
* refactor: unify encryption key management via .env
- Remove redundant EncryptionManager and SecureStorage
- Simplify CryptoService to load keys from environment variables only
  - RSA_PRIVATE_KEY: RSA private key for client-server encryption
  - DATA_ENCRYPTION_KEY: AES-256 key for database encryption
  - JWT_SECRET: JWT signing key for authentication
- Update start.sh to auto-generate missing keys on first run
- Remove secrets/ directory and file-based key storage
- Delete obsolete encryption setup scripts
- Update .env.example with all required keys
* refactor: unify logger usage across mcp package
- Add MCPLogger adapter in logger package to implement mcp.Logger interface
- Update mcp/config.go to use global logger by default
- Remove redundant defaultLogger from mcp/logger.go
- Keep noopLogger for testing purposes
* chore: remove leftover test RSA key file
* chore: remove unused bootstrap package
* refactor: unify logging to use logger package instead of fmt/log
- Replace all fmt.Print/log.Print calls with logger package
- Add auto-initialization in logger package init() for test compatibility
- Update main.go to initialize logger at startup
- Migrate all packages: api, backtest, config, decision, manager, market, store, trader
* refactor: rename database file from config.db to data.db
- Update main.go, start.sh, docker-compose.yml
- Update migration script and documentation
- Update .gitignore and translations
* fix: add RSA_PRIVATE_KEY to docker-compose environment
* fix: add registration_enabled to /api/config response
* fix: Fix navigation between login and register pages
Use window.location.href instead of react-router's navigate() to fix
the issue where URL changes but the page doesn't reload due to App.tsx
using custom route state management.
* fix: Switch SQLite from WAL to DELETE mode for Docker compatibility
WAL mode causes data sync issues with Docker bind mounts on macOS due
to incompatible file locking mechanisms between the container and host.
DELETE mode (traditional journaling) ensures data is written directly
to the main database file.
* refactor: Remove default user from database initialization
The default user was a legacy placeholder that is no longer needed now
that proper user registration is in place.
* feat: Add order tracking system with centralized status sync
- Add trader_orders table for tracking all order lifecycle
- Implement GetOrderStatus interface for all exchanges (Binance, Bybit, Hyperliquid, Aster, Lighter)
- Create OrderSyncManager for centralized order status polling
- Add trading statistics (Sharpe ratio, win rate, profit factor) to AI context
- Include recent completed orders in AI decision input
- Remove per-order goroutine polling in favor of global sync manager
* feat: Add TradingView K-line chart to dashboard
- Create TradingViewChart component with exchange/symbol selectors
- Support Binance, Bybit, OKX, Coinbase, Kraken, KuCoin exchanges
- Add popular symbols quick selection
- Support multiple timeframes (1m to 1W)
- Add fullscreen mode
- Integrate with Dashboard page below equity chart
- Add i18n translations for zh/en
* refactor: Replace separate charts with tabbed ChartTabs component
- Create ChartTabs component with tab switching between equity curve and K-line
- Add embedded mode support for EquityChart and TradingViewChart
- User can now switch between account equity and market chart in same area
* fix: Use ChartTabs in App.tsx and fix embedded mode in EquityChart
- Replace EquityChart with ChartTabs in App.tsx (the actual dashboard renderer)
- Fix EquityChart embedded mode for error and empty data states
- Rename interval state to timeInterval to avoid shadowing window.setInterval
- Add debug logging to ChartTabs component
* feat: Add position tracking system for accurate trade history
- Add trader_positions table to track complete open/close trades
- Add PositionSyncManager to detect manual closes via polling
- Record position on open, update on close with PnL calculation
- Use positions table for trading stats and recent trades (replacing orders table)
- Fix TradingView chart symbol format (add .P suffix for futures)
- Fix DecisionCard wait/hold action color (gray instead of red)
- Auto-append USDT suffix for custom symbol input
* update
---------
2025-12-06 01:04:26 +08:00

6.0 KiB

Mars AI交易系统 - 加密密钥生成脚本

本目录包含用于Mars AI交易系统加密环境设置的脚本工具。

🔐 加密架构

Mars AI交易系统使用双重加密架构来保护敏感数据:

  1. RSA-OAEP + AES-GCM 混合加密 - 用于前端到后端的安全通信
  2. AES-256-GCM 数据库加密 - 用于敏感数据的存储加密

加密流程

前端 → RSA-OAEP加密AES密钥 + AES-GCM加密数据 → 后端 → 存储时AES-256-GCM加密

📝 脚本说明

1. setup_encryption.sh - 一键环境设置 推荐

功能: 自动生成所有必要的密钥并配置环境

./scripts/setup_encryption.sh

生成内容:

  • RSA-2048 密钥对 (secrets/rsa_key, secrets/rsa_key.pub)
  • AES-256 数据加密密钥 (保存到 .env)
  • 自动权限设置和验证

适用场景:

  • 首次部署
  • 开发环境快速设置
  • 生产环境初始化

2. generate_rsa_keys.sh - RSA密钥生成

功能: 专门生成RSA密钥对

./scripts/generate_rsa_keys.sh

生成内容:

  • secrets/rsa_key (私钥, 权限 600)
  • secrets/rsa_key.pub (公钥, 权限 644)

技术规格:

  • 算法: RSA-OAEP
  • 密钥长度: 2048 bits
  • 格式: PEM

3. generate_data_key.sh - 数据加密密钥生成

功能: 生成数据库加密密钥

./scripts/generate_data_key.sh

生成内容:

  • 32字节(256位)随机密钥
  • Base64编码格式
  • 可选保存到 .env 文件

技术规格:

  • 算法: AES-256-GCM
  • 编码: Base64
  • 环境变量: DATA_ENCRYPTION_KEY

🚀 快速开始

方案1: 一键设置 (推荐)

# 克隆项目后,直接运行一键设置
cd mars-ai-trading
./scripts/setup_encryption.sh

# 按提示确认即可完成所有设置

方案2: 分步设置

# 1. 生成RSA密钥对
./scripts/generate_rsa_keys.sh

# 2. 生成数据加密密钥
./scripts/generate_data_key.sh

# 3. 启动系统
source .env && ./mars

📁 文件结构

生成完成后的目录结构:

mars-ai-trading/
├── secrets/
│   ├── rsa_key          # RSA私钥 (600权限)
│   └── rsa_key.pub      # RSA公钥 (644权限)
├── .env                 # 环境变量 (600权限)
│   └── DATA_ENCRYPTION_KEY=xxx
└── scripts/
    ├── setup_encryption.sh     # 一键设置脚本
    ├── generate_rsa_keys.sh    # RSA密钥生成
    └── generate_data_key.sh    # 数据密钥生成

🔒 安全要求

文件权限

文件 权限 说明
secrets/rsa_key 600 仅所有者可读写
secrets/rsa_key.pub 644 所有人可读
.env 600 仅所有者可读写

环境变量

# 必需的环境变量
DATA_ENCRYPTION_KEY=<32字节Base64编码的AES密钥>

🐳 Docker部署

使用环境文件

# 生成密钥
./scripts/setup_encryption.sh

# Docker运行
docker run --env-file .env -v $(pwd)/secrets:/app/secrets mars-ai-trading

使用环境变量

export DATA_ENCRYPTION_KEY="<生成的密钥>"
docker run -e DATA_ENCRYPTION_KEY mars-ai-trading

☸️ Kubernetes部署

创建Secret

# 从现有.env文件创建
kubectl create secret generic mars-crypto-key --from-env-file=.env

# 或直接指定密钥
kubectl create secret generic mars-crypto-key \
  --from-literal=DATA_ENCRYPTION_KEY="<生成的密钥>"

挂载RSA密钥

apiVersion: v1
kind: Secret
metadata:
  name: mars-rsa-keys
type: Opaque
data:
  rsa_key: <base64编码的私钥>
  rsa_key.pub: <base64编码的公钥>
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: mars-ai-trading
spec:
  template:
    spec:
      containers:
      - name: mars
        envFrom:
        - secretRef:
            name: mars-crypto-key
        volumeMounts:
        - name: rsa-keys
          mountPath: /app/secrets
      volumes:
      - name: rsa-keys
        secret:
          secretName: mars-rsa-keys

🔄 密钥轮换

数据加密密钥轮换

# 1. 生成新密钥
./scripts/generate_data_key.sh

# 2. 备份旧数据库
cp data.db data.db.backup

# 3. 重启服务 (会自动处理密钥迁移)
source .env && ./mars

RSA密钥轮换

# 1. 生成新密钥对
./scripts/generate_rsa_keys.sh

# 2. 重启服务
./mars

🛠️ 故障排除

常见问题

  1. 权限错误

    chmod 600 secrets/rsa_key .env
    chmod 644 secrets/rsa_key.pub
    
  2. OpenSSL未安装

    # macOS
    brew install openssl
    
    # Ubuntu/Debian
    sudo apt-get install openssl
    
    # CentOS/RHEL
    sudo yum install openssl
    
  3. 环境变量未加载

    source .env
    echo $DATA_ENCRYPTION_KEY
    
  4. 密钥验证失败

    # 验证RSA私钥
    openssl rsa -in secrets/rsa_key -check -noout
    
    # 验证公钥
    openssl rsa -in secrets/rsa_key.pub -pubin -text -noout
    

日志检查

启动时检查以下日志:

  • 🔐 初始化加密服务...
  • ✅ 加密服务初始化成功

📊 性能考虑

  • RSA加密: 仅用于小量密钥交换,性能影响极小
  • AES加密: 数据库字段级加密,对读写性能影响约5-10%
  • 内存使用: 加密服务约占用2-5MB内存

🔐 算法详细说明

RSA-OAEP-2048

  • 用途: 前端到后端的混合加密中的密钥交换
  • 密钥长度: 2048 bits
  • 填充: OAEP with SHA-256
  • 安全级别: 相当于112位对称加密

AES-256-GCM

  • 用途: 数据库敏感字段存储加密
  • 密钥长度: 256 bits
  • 模式: GCM (Galois/Counter Mode)
  • 认证: 内置消息认证
  • 安全级别: 256位安全强度

📋 合规性

此加密实现满足以下标准:

  • FIPS 140-2: AES-256 和 RSA-2048
  • Common Criteria: EAL4+
  • NIST推荐: SP 800-57 密钥管理
  • 行业标准: 符合金融业数据保护要求

📞 技术支持

如有问题,请检查:

  1. OpenSSL版本 >= 1.1.1
  2. 文件权限设置正确
  3. 环境变量加载成功
  4. 系统日志中的加密初始化信息