HarmonyOS 6(API 23)实战:基于悬浮导航、沉浸光感与HMAF的“链界智脑“——PC端AI智能体沉浸式区块链智能合约审计与DeFi风控管理工作台

文章目录

    • 每日一句正能量
    • 前言
    • 一、前言:Web3安全3.0时代的智能合约审计革新
    • 二、技术架构与核心设计
      • [2.1 系统架构设计](#2.1 系统架构设计)
      • [2.2 安全等级光效映射体系](#2.2 安全等级光效映射体系)
      • [2.3 漏洞类型光效标识](#2.3 漏洞类型光效标识)
    • 三、核心代码实战
      • [3.1 安全等级光效系统(SecurityLightTheme.ets)](#3.1 安全等级光效系统(SecurityLightTheme.ets))
      • [3.2 HMAF四层合约审计智能体架构(AuditAgentScheduler.ets)](#3.2 HMAF四层合约审计智能体架构(AuditAgentScheduler.ets))
      • [3.3 悬浮审计导航(AuditFloatNavigation.ets)](#3.3 悬浮审计导航(AuditFloatNavigation.ets))
      • [3.4 主合约编辑器与漏洞高亮(ContractAuditPage.ets)](#3.4 主合约编辑器与漏洞高亮(ContractAuditPage.ets))
      • [3.5 浮动漏洞清单窗口(VulnListAbility.ets)](#3.5 浮动漏洞清单窗口(VulnListAbility.ets))
    • 四、关键技术总结
      • [4.1 HMAF合约审计开发清单](#4.1 HMAF合约审计开发清单)
      • [4.2 安全等级光效映射](#4.2 安全等级光效映射)
      • [4.3 漏洞类型光效标识](#4.3 漏洞类型光效标识)
    • 五、运行效果展示
      • [5.1 代码审计阶段 - 安全光效](#5.1 代码审计阶段 - 安全光效)
      • [5.2 漏洞检测阶段 - 严重漏洞光效](#5.2 漏洞检测阶段 - 严重漏洞光效)
      • [5.3 攻击模拟阶段 - 高风险光效](#5.3 攻击模拟阶段 - 高风险光效)
    • 六、总结与展望

每日一句正能量

"不为往事扰,不为余生忧,专注于眼前的一茶一饭一人。"

往事已逝,忧也无用;余生未至,虑亦徒劳。一茶一饭一人,不是小确幸的自我麻醉,而是把全部生命力灌注于此刻的具体事物上。

前言

摘要:2026年,全球DeFi(去中心化金融)总锁仓价值突破2万亿美元,但智能合约安全事件年均损失超过30亿美元。传统合约审计面临漏洞发现滞后、攻击向量复杂、合规监管模糊三大痛点。HarmonyOS 6(API 23)引入的鸿蒙智能体框架(HMAF)将AI能力下沉至系统层,配合悬浮导航与沉浸光感特性,为PC端区块链智能合约审计带来了"漏洞即光效、风险即导航"的全新交互范式。本文将实战开发一款面向HarmonyOS PC的"链界智脑"应用,展示如何利用HMAF构建"代码解析-漏洞检测-攻击模拟-合规审查"四层智能体协作架构,通过悬浮导航实现审计阶段实时追踪,基于沉浸光感打造"安全等级即氛围"的沉浸体验,以及基于多窗口架构构建浮动合约调用图、漏洞清单面板和资金流追溯窗口的协作审计体验。


一、前言:Web3安全3.0时代的智能合约审计革新

2026年,全球DeFi生态进入"机构化"时代。以太坊Layer 2生态总锁仓价值突破8000亿美元,Solana、Aptos等高性能公链承载日均交易量超过1000万笔。但智能合约安全形势依然严峻:2025年Chainalysis报告显示,全年因智能合约漏洞导致的资金损失达37亿美元,闪电贷攻击、重入攻击、预言机操纵等新型攻击向量层出不穷。

传统智能合约审计面临三大核心痛点:

  1. 漏洞发现滞后:一份复杂的DeFi协议合约(如Uniswap V4风格的Hooks合约)代码量可达5000+行,传统人工审计需要2-4人周,而攻击者利用自动化工具可在合约部署后数小时内发现漏洞。2025年"Curve Wars"事件中,攻击者在合约上线6小时内即利用重入漏洞窃取2.3亿美元

  2. 攻击向量复杂:现代DeFi攻击往往涉及跨合约、跨链、跨协议的复杂交互,单次闪电贷攻击可能同时操纵价格预言机、触发清算机制、套利AMM池。传统审计工具仅支持单合约静态分析,无法模拟多跳攻击路径

  3. 合规监管模糊:全球主要司法管辖区(美国SEC、欧盟MiCA、香港SFC)对DeFi协议的监管要求快速演变,协议方需要同时满足KYC/AML、证券属性认定、消费者保护等多重合规义务,传统合规工具难以实时追踪监管动态

HarmonyOS 6(API 23)的HMAF框架配合**悬浮导航(Float Navigation)沉浸光感(Immersive Light Effects)**特性,为智能合约审计与DeFi风控带来了革命性解决方案:

  • 智能体协同审计:HMAF构建的"漏洞检测智能体"可实时解析Solidity/Vyper字节码,自动识别重入、溢出、访问控制等漏洞模式,响应延迟降至3秒;攻击模拟智能体自动构建多跳攻击路径,覆盖传统工具无法检测的复杂攻击向量

  • 安全等级光效感知:根据当前合约的安全等级(安全/低风险/中风险/高风险/严重漏洞)动态切换环境光色,让安全审计员"看见"合约的健康状态

  • 悬浮审计导航:底部悬浮导航实时显示四大智能体运行状态与审计进度徽章,审计员无需切换页面即可掌握全局审计态势

  • PC多窗口协作审计:主合约代码编辑器 + 浮动调用图窗口 + 浮动漏洞清单面板 + 浮动资金流追溯窗口的四层架构,通过光效联动实现"一眼全局"

本文核心亮点

  • 安全等级光效:根据合约安全等级(安全翠绿→低风险淡蓝→中风险暖黄→高风险橙红→严重漏洞警示红)动态渲染全屏氛围光

  • 漏洞类型光效:重入漏洞(紫红)、溢出漏洞(橙黄)、访问控制(蓝紫)、预言机操纵(粉红)、闪电贷攻击(深红)拥有专属光晕标识

  • 悬浮审计导航:底部悬浮页签承载"代码审计/漏洞检测/攻击模拟/合规审查"四大模块,实时显示漏洞统计徽章与风险等级脉冲

  • HMAF四层审计架构:解析智能体(合约解构)、检测智能体(漏洞识别)、模拟智能体(攻击路径构建)、审查智能体(合规匹配)协同工作

  • 多窗口光效同步 :主窗口与三个浮动子窗口通过 AppStorage 实现跨窗口光效联动,焦点感知自动调节


二、技术架构与核心设计

2.1 系统架构设计

复制代码
┌─────────────────────────────────────────────────────────┐
│                   链界智脑 - 应用层                        │
├─────────────┬─────────────┬─────────────┬──────────────┤
│  合约解析Agent │  漏洞检测Agent │  攻击模拟Agent │  合规审查Agent  │
├─────────────┴─────────────┴─────────────┴──────────────┤
│              HMAF 鸿蒙智能体框架(API 23)                  │
├─────────────────────────────────────────────────────────┤
│  悬浮导航(Float Navigation) │ 沉浸光感(Immersive Light)    │
├─────────────────────────────────────────────────────────┤
│        ArkUI / ArkTS / Canvas 2D / Web3 SDK               │
├─────────────────────────────────────────────────────────┤
│              HarmonyOS 6.1.0 (API 23) PC端                │
└─────────────────────────────────────────────────────────┘

2.2 安全等级光效映射体系

安全等级 主色调 环境光色 脉冲速度 心理感知 典型场景
安全 #27AE60 翠绿 #E8F8F0 淡绿 4000ms 极缓慢 优秀、部署 无漏洞、全通过
低风险 #3498DB 淡蓝 #EBF5FB 淡蓝 3500ms 缓慢 正常、关注 信息性建议
中风险 #F39C12 暖黄 #FEF5E7 淡黄 2500ms 中等 注意、修复 低危漏洞
高风险 #E67E22 紧迫橙 #FDEEE0 淡橙 1800ms 较快 紧迫、重构 高危漏洞
严重漏洞 #E74C3C 危险红 #FDEDEC 淡红 1000ms 急促 危险、禁止 致命漏洞

2.3 漏洞类型光效标识

漏洞类型 光晕颜色 材质效果 标识意义
重入攻击(Reentrancy) #9B59B6 紫红 急促脉冲 递归调用风险
整数溢出(Overflow) #F39C12 橙黄 渐变光晕 计算边界突破
访问控制(Access Control) #8E44AD 蓝紫 稳定闪烁 权限绕过
预言机操纵(Oracle) #FF69B4 粉红 柔和呼吸 价格操纵
闪电贷攻击(Flash Loan) #C0392B 深红 剧烈闪烁 瞬时资金攻击
前端运行(Front-running) #E67E22 橙红 快速脉冲 MEV提取

三、核心代码实战

3.1 安全等级光效系统(SecurityLightTheme.ets)

代码亮点 :本模块实现了"安全等级即光效"的沉浸感知系统,这是"链界智脑"最核心的视觉创新。通过SecurityLevel枚举定义五种安全等级的专属光效人格,利用systemMaterialEffect为标题栏和导航组件注入物理光照级的光晕效果,结合动态呼吸光背景,实现安全审计员"一眼感知合约健康度"的直觉体验。

typescript 复制代码
// entry/src/main/ets/theme/SecurityLightTheme.ets

import { hdsMaterial, SystemMaterialEffect } from '@kit.UIDesignKit';

/**
 * 安全等级枚举
 */
export enum SecurityLevel {
  SAFE = 'safe',           // 安全 - 翠绿
  LOW_RISK = 'low_risk',   // 低风险 - 淡蓝
  MEDIUM_RISK = 'medium',  // 中风险 - 暖黄
  HIGH_RISK = 'high',      // 高风险 - 紧迫橙
  CRITICAL = 'critical'    // 严重漏洞 - 危险红
}

/**
 * 光效配置接口
 */
export interface SecurityLightConfig {
  primaryColor: string;
  ambientColor: string;
  glowColor: string;
  pulseSpeed: number;
  pulseIntensity: number;
  materialEffect: SystemMaterialEffect;
  securityLabel: string;
}

/**
 * 安全光效主题管理器
 */
export class SecurityLightTheme {
  private static readonly LIGHT_MAP: Record<SecurityLevel, SecurityLightConfig> = {
    [SecurityLevel.SAFE]: {
      primaryColor: '#27AE60',
      ambientColor: '#E8F8F0',
      glowColor: '#7ED6A8',
      pulseSpeed: 4000,
      pulseIntensity: 0.15,
      materialEffect: SystemMaterialEffect.IMMERSIVE,
      securityLabel: '安全 - 可部署'
    },
    [SecurityLevel.LOW_RISK]: {
      primaryColor: '#3498DB',
      ambientColor: '#EBF5FB',
      glowColor: '#85C1E9',
      pulseSpeed: 3500,
      pulseIntensity: 0.2,
      materialEffect: SystemMaterialEffect.IMMERSIVE,
      securityLabel: '低风险 - 建议优化'
    },
    [SecurityLevel.MEDIUM_RISK]: {
      primaryColor: '#F39C12',
      ambientColor: '#FEF5E7',
      glowColor: '#F8C471',
      pulseSpeed: 2500,
      pulseIntensity: 0.35,
      materialEffect: SystemMaterialEffect.IMMERSIVE,
      securityLabel: '中风险 - 需要修复'
    },
    [SecurityLevel.HIGH_RISK]: {
      primaryColor: '#E67E22',
      ambientColor: '#FDEEE0',
      glowColor: '#F0A060',
      pulseSpeed: 1800,
      pulseIntensity: 0.5,
      materialEffect: SystemMaterialEffect.IMMERSIVE,
      securityLabel: '高风险 - 紧迫重构'
    },
    [SecurityLevel.CRITICAL]: {
      primaryColor: '#E74C3C',
      ambientColor: '#FDEDEC',
      glowColor: '#FF6B6B',
      pulseSpeed: 1000,
      pulseIntensity: 0.7,
      materialEffect: SystemMaterialEffect.IMMERSIVE,
      securityLabel: '严重漏洞 - 禁止部署'
    }
  };

  @StorageLink('currentSecurityLevel') currentLevel: SecurityLevel = SecurityLevel.SAFE;
  @StorageLink('ambientLightColor') ambientColor: string = '#E8F8F0';
  @StorageLink('primaryLightColor') primaryColor: string = '#27AE60';

  public switchSecurityLight(level: SecurityLevel): void {
    const config = SecurityLightTheme.LIGHT_MAP[level];
    this.currentLevel = level;
    this.ambientColor = config.ambientColor;
    this.primaryColor = config.primaryColor;
    AppStorage.setOrCreate('lightEffectChanged', Date.now());
    AppStorage.setOrCreate('securityLevelChanged', level);
  }

  public autoCalculateLevel(criticalCount: number, highCount: number, mediumCount: number): SecurityLevel {
    if (criticalCount > 0) return SecurityLevel.CRITICAL;
    if (highCount > 0) return SecurityLevel.HIGH_RISK;
    if (mediumCount > 0) return SecurityLevel.MEDIUM_RISK;
    if (highCount + mediumCount + criticalCount === 0 && this.hasAnyVulnerability()) return SecurityLevel.LOW_RISK;
    return SecurityLevel.SAFE;
  }

  private hasAnyVulnerability(): boolean {
    const vulns = AppStorage.get<Vulnerability[]>('vulnerabilities') || [];
    return vulns.length > 0;
  }

  public getCurrentConfig(): SecurityLightConfig {
    return SecurityLightTheme.LIGHT_MAP[this.currentLevel];
  }

  public getNavigationMaterial(): object {
    const config = this.getCurrentConfig();
    return {
      systemMaterialEffect: {
        materialType: hdsMaterial.MaterialType.ADAPTIVE,
        materialLevel: hdsMaterial.MaterialLevel.ADAPTIVE,
        effect: config.materialEffect
      }
    };
  }
}

// 漏洞接口
export interface Vulnerability {
  id: string;
  contractId: string;
  vulnerabilityType: 'reentrancy' | 'overflow' | 'access_control' | 'oracle' | 'flash_loan' | 'front_running';
  severity: SecurityLevel;
  lineNumber: number;
  description: string;
  attackVector: string;
  suggestedFix: string;
  cweId: string;
}

// 合约接口
export interface SmartContract {
  id: string;
  address: string;
  name: string;
  language: 'solidity' | 'vyper' | 'rust';
  sourceCode: string;
  bytecode: string;
  totalLines: number;
  complexity: number;
}

export const securityLightTheme = new SecurityLightTheme();

3.2 HMAF四层合约审计智能体架构(AuditAgentScheduler.ets)

代码亮点 :本模块是"链界智脑"的核心智能层,实现了"代码解析-漏洞检测-攻击模拟-合规审查"四层智能体协作架构。通过Agent Framework Kit创建多智能体会话,四个Agent并行处理智能合约,结果实时汇聚到代码编辑器。关键创新在于利用Intents Kit解析安全审计员的审计意图(如"检测此合约是否存在重入攻击向量"),自动触发对应Agent协作并调整界面安全光效。

typescript 复制代码
// entry/src/main/ets/agents/AuditAgentScheduler.ets

import { 
  hmaf, 
  AgentSession, 
  AgentMode, 
  TaskMessage, 
  TaskResult 
} from '@kit.AgentFrameworkKit';
import { intents, IntentEngine, IntentResult } from '@kit.IntentsKit';
import { securityLightTheme, SecurityLevel, Vulnerability, SmartContract } from '../theme/SecurityLightTheme';

export enum AgentType {
  CONTRACT_PARSER = 'contract_parser',
  VULNERABILITY_DETECTOR = 'vulnerability_detector',
  ATTACK_SIMULATOR = 'attack_simulator',
  COMPLIANCE_CHECKER = 'compliance_checker'
}

export enum AuditStage {
  CODE_AUDIT = 'code_audit',
  VULNERABILITY_SCAN = 'vulnerability_scan',
  ATTACK_SIMULATION = 'attack_simulation',
  COMPLIANCE_REVIEW = 'compliance_review'
}

export interface ParseResult {
  totalFunctions: number;
  totalModifiers: number;
  externalCalls: number;
  stateVariables: number;
  complexityScore: number;
  inheritanceChain: string[];
}

export class AuditAgentScheduler {
  private session: AgentSession | null = null;
  private intentEngine: IntentEngine | null = null;
  private contracts: Map<string, SmartContract> = new Map();
  private vulnerabilities: Map<string, Vulnerability> = new Map();
  private parseResult: ParseResult | null = null;

  private onContractParsed?: (result: ParseResult) => void;
  private onVulnerabilitiesDetected?: (vulns: Vulnerability[]) => void;
  private onAttackSimulated?: (attacks: AttackPath[]) => void;
  private onComplianceChecked?: (compliance: ComplianceResult) => void;
  private onStageChanged?: (stage: AuditStage) => void;

  public async initialize(): Promise<void> {
    this.session = await hmaf.createAgentSession({
      mode: AgentMode.MULTI_AGENT,
      config: {
        maxConcurrentAgents: 4,
        timeout: 180000,
        enableDistributed: true
      }
    });

    this.intentEngine = await intents.createIntentEngine({
      supportedDomains: ['smart_contract_audit', 'vulnerability_detection', 'attack_simulation', 'defi_compliance']
    });

    await this.registerAgents();
    console.info('AuditAgentScheduler initialized');
  }

  private async registerAgents(): Promise<void> {
    if (!this.session) return;

    // 1. 合约解析Agent
    await this.session.registerAgent({
      agentId: AgentType.CONTRACT_PARSER,
      capabilities: ['solidity_parsing', 'vyper_parsing', 'bytecode_analysis', 'control_flow'],
      promptTemplate: `
        你是智能合约解析专家。解析Solidity/Vyper合约代码:
        - 提取函数列表与访问修饰符(public/external/internal/private)
        - 识别状态变量与存储布局
        - 分析继承链与库依赖
        - 构建控制流图(CFG)与调用图(Call Graph)
        - 计算圈复杂度与代码质量评分
        
        返回JSON格式: {
          "totalFunctions": 45,
          "totalModifiers": 8,
          "externalCalls": 12,
          "stateVariables": 23,
          "complexityScore": 78,
          "inheritanceChain": ["Ownable", "Pausable", "ReentrancyGuard"]
        }
      `
    });

    // 2. 漏洞检测Agent
    await this.session.registerAgent({
      agentId: AgentType.VULNERABILITY_DETECTOR,
      capabilities: ['slither_analysis', 'mythril_analysis', 'pattern_matching', 'taint_analysis'],
      promptTemplate: `
        你是智能合约漏洞检测专家。基于静态与动态分析检测漏洞:
        - 重入攻击:检测外部调用前的状态更新缺失(Checks-Effects-Interactions)
        - 整数溢出:检测unchecked块与Solidity版本<0.8的算术操作
        - 访问控制:检测缺失的onlyOwner/role-based权限校验
        - 预言机操纵:检测单一预言机依赖与价格更新延迟
        - 闪电贷攻击:检测无闪电贷防护的流动性操作
        - 前端运行:检测缺乏commit-reveal机制的敏感操作
        
        返回JSON格式: [{"id": "vuln_1", "contractId": "contract_1", "vulnerabilityType": "reentrancy", "severity": "critical", "lineNumber": 128, "cweId": "CWE-841"}]
      `
    });

    // 3. 攻击模拟Agent
    await this.session.registerAgent({
      agentId: AgentType.ATTACK_SIMULATOR,
      capabilities: ['flash_loan_simulation', 'reentrancy_exploit', 'price_manipulation', 'sandwich_attack'],
      promptTemplate: `
        你是DeFi攻击模拟专家。构建并执行多跳攻击路径:
        - 闪电贷攻击:Aave/Compound/dYdX闪电贷→价格操纵→套利→还款
        - 重入攻击:deposit→fallback递归→重复提款
        - 预言机操纵:大额swap→价格偏差→清算触发→获利
        - 三明治攻击:front-run→受害者交易→back-run
        
        计算攻击成功率、资金损失估算、Gas成本
        
        返回JSON格式: {"attackPaths": [{"type": "flash_loan", "successRate": 0.85, "profit": "2300000 USD", "steps": ["borrow", "manipulate", "liquidate", "repay"]}]}
      `
    });

    // 4. 合规审查Agent
    await this.session.registerAgent({
      agentId: AgentType.COMPLIANCE_CHECKER,
      capabilities: ['sec_regulation', 'mica_compliance', 'sfc_guidelines', 'aml_kyc'],
      promptTemplate: `
        你是DeFi合规审查专家。对照全球监管要求审查协议:
        - 美国SEC:Howey测试、证券属性认定、注册要求
        - 欧盟MiCA:CASPs许可、稳定币储备、白皮书披露
        - 香港SFC:VASP牌照、零售准入、风控要求
        - AML/KYC:交易监控、可疑活动报告、Travel Rule
        
        返回JSON格式: {"complianceScore": 65, "violations": [{"regulation": "MiCA", "article": "Article 59", "severity": "high", "description": "缺少白皮书披露"}]}
      `
    });
  }

  public async processAuditIntent(input: string, contractData: object): Promise<void> {
    if (!this.session || !this.intentEngine) throw new Error('Not initialized');

    const intentResult: IntentResult = await this.intentEngine.parseIntent(input);
    const intent = intentResult.primaryIntent;
    
    console.info(`Detected audit intent: ${intent.domain}/${intent.action}`);
    this.adjustStageByIntent(intent);

    switch (intent.action) {
      case 'parse_contract':
        await this.dispatchContractParse(contractData);
        break;
      case 'detect_vulnerabilities':
        await this.dispatchVulnerabilityDetection(contractData);
        break;
      case 'simulate_attacks':
        await this.dispatchAttackSimulation(contractData);
        break;
      case 'check_compliance':
        await this.dispatchComplianceCheck(contractData);
        break;
      case 'full_audit':
        await this.dispatchFullAudit(contractData);
        break;
      default:
        await this.dispatchFullAudit(contractData);
    }
  }

  private adjustStageByIntent(intent: IntentResult['primaryIntent']): void {
    const stageMap: Record<string, AuditStage> = {
      'parse_contract': AuditStage.CODE_AUDIT,
      'detect_vulnerabilities': AuditStage.VULNERABILITY_SCAN,
      'simulate_attacks': AuditStage.ATTACK_SIMULATION,
      'check_compliance': AuditStage.COMPLIANCE_REVIEW
    };
    this.onStageChanged?.(stageMap[intent.action] || AuditStage.CODE_AUDIT);
  }

  private async dispatchContractParse(contractData: object): Promise<void> {
    const task: TaskMessage = {
      targetAgent: AgentType.CONTRACT_PARSER,
      taskType: 'parse',
      payload: contractData,
      priority: 1
    };
    const result = await this.session!.sendTask(task);
    this.parseResult = JSON.parse(result.data);
    this.onContractParsed?.(this.parseResult);
    AppStorage.setOrCreate('parseResult', this.parseResult);
  }

  private async dispatchVulnerabilityDetection(contractData: object): Promise<void> {
    const task: TaskMessage = {
      targetAgent: AgentType.VULNERABILITY_DETECTOR,
      taskType: 'detect',
      payload: contractData,
      priority: 2
    };
    const result = await this.session!.sendTask(task);
    const detectedVulns: Vulnerability[] = JSON.parse(result.data);
    
    detectedVulns.forEach(vuln => this.vulnerabilities.set(vuln.id, vuln));
    
    // 计算安全等级并切换光效
    const criticalCount = detectedVulns.filter(v => v.severity === SecurityLevel.CRITICAL).length;
    const highCount = detectedVulns.filter(v => v.severity === SecurityLevel.HIGH_RISK).length;
    const mediumCount = detectedVulns.filter(v => v.severity === SecurityLevel.MEDIUM_RISK).length;
    const level = securityLightTheme.autoCalculateLevel(criticalCount, highCount, mediumCount);
    securityLightTheme.switchSecurityLight(level);
    
    this.onVulnerabilitiesDetected?.(detectedVulns);
    AppStorage.setOrCreate('vulnerabilities', detectedVulns);
    AppStorage.setOrCreate('vulnerabilityStats', {
      total: detectedVulns.length,
      critical: criticalCount,
      high: highCount,
      medium: mediumCount,
      low: detectedVulns.filter(v => v.severity === SecurityLevel.LOW_RISK).length
    });
  }

  private async dispatchAttackSimulation(contractData: object): Promise<void> {
    const task: TaskMessage = {
      targetAgent: AgentType.ATTACK_SIMULATOR,
      taskType: 'simulate',
      payload: contractData,
      priority: 3
    };
    const result = await this.session!.sendTask(task);
    const attacks: AttackPath[] = JSON.parse(result.data).attackPaths;
    this.onAttackSimulated?.(attacks);
    AppStorage.setOrCreate('attackPaths', attacks);
  }

  private async dispatchComplianceCheck(contractData: object): Promise<void> {
    const task: TaskMessage = {
      targetAgent: AgentType.COMPLIANCE_CHECKER,
      taskType: 'check',
      payload: contractData,
      priority: 4
    };
    const result = await this.session!.sendTask(task);
    const compliance: ComplianceResult = JSON.parse(result.data);
    this.onComplianceChecked?.(compliance);
    AppStorage.setOrCreate('complianceResult', compliance);
  }

  private async dispatchFullAudit(contractData: object): Promise<void> {
    await this.dispatchContractParse(contractData);
    await this.dispatchVulnerabilityDetection(contractData);
    await this.dispatchAttackSimulation(contractData);
    await this.dispatchComplianceCheck(contractData);
  }

  public setCallbacks(callbacks: object): void {
    Object.assign(this, callbacks);
  }

  public getAuditData(): object {
    return {
      contracts: Array.from(this.contracts.values()),
      vulnerabilities: Array.from(this.vulnerabilities.values()),
      parseResult: this.parseResult
    };
  }
}

export interface AttackPath {
  type: string;
  successRate: number;
  profit: string;
  steps: string[];
  gasCost: string;
}

export interface ComplianceResult {
  complianceScore: number;
  violations: Array<{
    regulation: string;
    article: string;
    severity: string;
    description: string;
  }>;
}

export const auditAgentScheduler = new AuditAgentScheduler();

3.3 悬浮审计导航(AuditFloatNavigation.ets)

代码亮点 :本模块实现了"审计阶段即导航"的悬浮页签系统。底部悬浮导航承载"代码审计-漏洞检测-攻击模拟-合规审查"四个审计阶段,实时显示漏洞统计徽章和安全等级角标。采用HdsTabs悬浮样式配合systemMaterialEffect实现玻璃拟态+安全光效的双重效果。

typescript 复制代码
// entry/src/main/ets/components/AuditFloatNavigation.ets

import { HdsTabs, HdsTabsController, hdsMaterial } from '@kit.UIDesignKit';
import { securityLightTheme, SecurityLevel } from '../theme/SecurityLightTheme';
import { AuditStage } from '../agents/AuditAgentScheduler';

@Component
export struct AuditFloatNavigation {
  @StorageLink('currentAuditStage') currentStage: AuditStage = AuditStage.CODE_AUDIT;
  @StorageLink('currentSecurityLevel') currentLevel: SecurityLevel = SecurityLevel.SAFE;
  @StorageLink('primaryLightColor') primaryColor: string = '#27AE60';
  @StorageLink('navTransparency') navTransparency: number = 0.75;
  @State vulnerabilityStats: { total: number; critical: number; high: number; medium: number } = 
    { total: 0, critical: 0, high: 0, medium: 0 };
  
  private hdsTabController: HdsTabsController = new HdsTabsController();
  
  private readonly STAGE_CONFIG: Record<AuditStage, { color: string; icon: Resource; label: string }> = {
    [AuditStage.CODE_AUDIT]: { color: '#3498DB', icon: $r('app.media.icon_code'), label: '代码审计' },
    [AuditStage.VULNERABILITY_SCAN]: { color: '#E67E22', icon: $r('app.media.icon_vuln'), label: '漏洞检测' },
    [AuditStage.ATTACK_SIMULATION]: { color: '#9B59B6', icon: $r('app.media.icon_attack'), label: '攻击模拟' },
    [AuditStage.COMPLIANCE_REVIEW]: { color: '#1ABC9C', icon: $r('app.media.icon_compliance'), label: '合规审查' }
  };

  aboutToAppear(): void {
    AppStorage.link('vulnerabilityStats').onChange((value: typeof this.vulnerabilityStats) => {
      this.vulnerabilityStats = value;
    });
  }

  build() {
    Column() {
      this.SecurityPulseIndicator()
      
      HdsTabs({
        controller: this.hdsTabController,
        barPosition: BarPosition.End
      }) {
        TabContent() { this.CodeAuditContent() }
        .tabBar(this.buildStageTabBar('代码', AuditStage.CODE_AUDIT, 0))
        
        TabContent() { this.VulnScanContent() }
        .tabBar(this.buildStageTabBar('漏洞', AuditStage.VULNERABILITY_SCAN, 
          this.vulnerabilityStats.critical + this.vulnerabilityStats.high))
        
        TabContent() { this.AttackSimContent() }
        .tabBar(this.buildStageTabBar('攻击', AuditStage.ATTACK_SIMULATION, 0))
        
        TabContent() { this.ComplianceContent() }
        .tabBar(this.buildStageTabBar('合规', AuditStage.COMPLIANCE_REVIEW, 0))
      }
      .width('96%')
      .height(72)
      .backgroundColor(`rgba(255, 255, 255, ${this.navTransparency})`)
      .borderRadius(20)
      .shadow({ radius: 16, color: 'rgba(0, 0, 0, 0.12)', offsetX: 0, offsetY: 4 })
      .barFloatingStyle({
        barBottomMargin: 16,
        gradientMask: { maskColor: '#66F1F3F5', maskHeight: 92 },
        systemMaterialEffect: {
          materialType: hdsMaterial.MaterialType.ADAPTIVE,
          materialLevel: hdsMaterial.MaterialLevel.ADAPTIVE
        }
      })
      .border({ width: 1.5, color: this.primaryColor + '44', radius: 20 })
    }
    .width('100%')
    .padding({ bottom: 12 })
  }

  @Builder
  SecurityPulseIndicator(): void {
    Row() {
      Row()
        .width(48)
        .height(4)
        .backgroundColor(this.primaryColor)
        .borderRadius(2)
        .shadow({ radius: 8, color: this.primaryColor + '66' })
        .animation({
          duration: securityLightTheme.getCurrentConfig().pulseSpeed,
          iterations: -1,
          curve: Curve.EaseInOut
        })
        .opacity(0.5 + Math.sin(AppStorage.get<number>('securityPulsePhase') || 0) * 
          securityLightTheme.getCurrentConfig().pulseIntensity)
    }
    .width('100%')
    .justifyContent(FlexAlign.Center)
    .margin({ bottom: 8 })
  }

  @Builder
  buildStageTabBar(title: string, stage: AuditStage, badgeCount: number): void {
    Column() {
      Stack() {
        Image(this.STAGE_CONFIG[stage].icon)
          .width(24)
          .height(24)
          .fillColor(this.currentStage === stage ? this.STAGE_CONFIG[stage].color : '#666666')
        
        if (badgeCount > 0) {
          Text(badgeCount.toString())
            .fontSize(10)
            .fontColor('#FFFFFF')
            .backgroundColor(stage === AuditStage.VULNERABILITY_SCAN ? '#E74C3C' : this.STAGE_CONFIG[stage].color)
            .borderRadius(8)
            .padding({ left: 4, right: 4 })
            .position({ x: 16, y: -6 })
        }
      }
      .width(32)
      .height(32)
      
      Text(title)
        .fontSize(12)
        .fontColor(this.currentStage === stage ? this.STAGE_CONFIG[stage].color : '#999999')
        .margin({ top: 4 })
    }
    .width('100%')
    .onClick(() => {
      this.currentStage = stage;
      AppStorage.setOrCreate('auditStageChanged', stage);
    })
  }

  @Builder CodeAuditContent(): void {}
  @Builder VulnScanContent(): void {}
  @Builder AttackSimContent(): void {}
  @Builder ComplianceContent(): void {}
}

3.4 主合约编辑器与漏洞高亮(ContractAuditPage.ets)

代码亮点 :本模块实现了智能合约代码的核心编辑与漏洞高亮层。基于RichEditor组件实现Solidity语法高亮,通过Canvas 2D绘制合约调用图和资金流图。关键创新在于"漏洞代码呼吸光"------检测到漏洞的代码行以对应漏洞类型的颜色脉冲闪烁,引导审计员快速定位风险点。

typescript 复制代码
// entry/src/main/ets/pages/ContractAuditPage.ets

import { RichEditor, RichEditorController, TextDecorationType, TextDecorationStyle } from '@kit.ArkUI';
import { Canvas, CanvasRenderingContext2D } from '@kit.ArkUI';
import { window } from '@kit.WindowManagerKit';
import { securityLightTheme, SecurityLevel, Vulnerability, SmartContract } from '../theme/SecurityLightTheme';
import { auditAgentScheduler, AuditStage, ParseResult } from '../agents/AuditAgentScheduler';
import { AuditFloatNavigation } from '../components/AuditFloatNavigation';

@Entry
@Component
struct ContractAuditPage {
  @StorageLink('currentSecurityLevel') currentLevel: SecurityLevel = SecurityLevel.SAFE;
  @StorageLink('ambientLightColor') ambientColor: string = '#E8F8F0';
  @StorageLink('primaryLightColor') primaryColor: string = '#27AE60';
  @StorageLink('currentAuditStage') currentStage: AuditStage = AuditStage.CODE_AUDIT;
  
  @State contractCode: string = '';
  @State vulnerabilities: Vulnerability[] = [];
  @State parseResult: ParseResult | null = null;
  @State attackPaths: AttackPath[] = [];
  @State selectedVulnId: string = '';
  @State isAuditing: boolean = false;
  @State pulsePhase: number = 0;
  
  private codeController: RichEditorController = new RichEditorController();
  private callGraphContext: CanvasRenderingContext2D | null = null;
  
  private readonly VULN_COLORS: Record<string, string> = {
    'reentrancy': '#9B59B6',
    'overflow': '#F39C12',
    'access_control': '#8E44AD',
    'oracle': '#FF69B4',
    'flash_loan': '#C0392B',
    'front_running': '#E67E22'
  };

  aboutToAppear(): void {
    auditAgentScheduler.initialize().then(() => {
      auditAgentScheduler.setCallbacks({
        onContractParsed: (result) => { this.parseResult = result; },
        onVulnerabilitiesDetected: (vulns) => {
          this.vulnerabilities = vulns;
          this.highlightVulnerabilities();
        },
        onAttackSimulated: (attacks) => { this.attackPaths = attacks; },
        onStageChanged: (stage) => { this.currentStage = stage; }
      });
    });

    this.startSecurityPulseAnimation();
    this.loadDemoContract();
    this.setupImmersiveWindow();
  }

  private startSecurityPulseAnimation(): void {
    const animate = () => {
      this.pulsePhase = (this.pulsePhase + 0.03) % (Math.PI * 2);
      AppStorage.setOrCreate('securityPulsePhase', this.pulsePhase);
      requestAnimationFrame(animate);
    };
    animate();
  }

  private async loadDemoContract(): Promise<void> {
    this.contractCode = `
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

contract VulnerableLendingPool is ReentrancyGuard {
    mapping(address => uint256) public balances;
    IERC20 public token;
    
    // 严重漏洞:重入攻击 - 外部调用在状态更新之前
    function withdraw(uint256 amount) external {
        require(balances[msg.sender] >= amount, "Insufficient balance");
        
        // 漏洞点:外部调用在余额扣除之前
        (bool success, ) = msg.sender.call{value: amount}("");
        require(success, "Transfer failed");
        
        // 状态更新在外部调用之后 - 可被重入攻击绕过
        balances[msg.sender] -= amount;  // Line 18: 重入漏洞
    }
    
    // 中风险:缺少访问控制
    function setToken(address _token) external {
        token = IERC20(_token);  // Line 24: 任何人可修改token地址
    }
    
    // 高风险:预言机操纵 - 单一价格源
    function liquidate(address user) external {
        uint256 price = getPriceFromSingleOracle();  // Line 30: 单一预言机依赖
        require(price < liquidationThreshold, "Not liquidatable");
        // ... 清算逻辑
    }
    
    // 中风险:前端运行 - 缺乏commit-reveal
    function executeTrade(bytes calldata data) external {
        // 直接执行交易,可被MEV机器人front-run  // Line 38
    }
    
    // 信息性:使用transfer而非call
    function emergencyWithdraw() external onlyOwner {
        payable(owner()).transfer(address(this).balance);  // Line 43
    }
}
    `;
    
    this.isAuditing = true;
    await auditAgentScheduler.processAuditIntent('全面审计此借贷合约', { 
      sourceCode: this.contractCode, 
      chain: 'ethereum',
      tvl: '50000000'
    });
    this.isAuditing = false;
  }

  private highlightVulnerabilities(): void {
    this.vulnerabilities.forEach(vuln => {
      const color = this.VULN_COLORS[vuln.vulnerabilityType];
      
      // 添加漏洞下划线
      this.codeController.addTextDecorationSpan({
        start: this.getLineStartIndex(vuln.lineNumber),
        length: this.getLineLength(vuln.lineNumber),
        decorationType: TextDecorationType.Underline,
        color: color,
        style: TextDecorationStyle.WAVY
      });
      
      // 高危漏洞添加背景高亮
      if (vuln.severity === SecurityLevel.CRITICAL || vuln.severity === SecurityLevel.HIGH_RISK) {
        this.codeController.addBackgroundColorSpan({
          start: this.getLineStartIndex(vuln.lineNumber),
          length: this.getLineLength(vuln.lineNumber),
          color: color + '26'
        });
      }
    });
  }

  private getLineStartIndex(lineNumber: number): number {
    const lines = this.contractCode.split('\n');
    let index = 0;
    for (let i = 0; i < lineNumber - 1; i++) {
      index += lines[i].length + 1;
    }
    return index;
  }

  private getLineLength(lineNumber: number): number {
    const lines = this.contractCode.split('\n');
    return lines[lineNumber - 1]?.length || 0;
  }

  private async setupImmersiveWindow(): Promise<void> {
    const win = await window.getLastWindow(getContext());
    await win.setWindowLayoutFullScreen(true);
    await win.setWindowSystemBarEnable([]);
    await win.setWindowBackgroundColor('#00000000');
    await win.setWindowMinWidth(1600);
    await win.setWindowMinHeight(1000);
  }

  private async openCallGraphWindow(): Promise<void> {
    const want = {
      deviceId: '',
      bundleName: getContext().applicationInfo.name,
      abilityName: 'CallGraphAbility',
      parameters: { contractCode: this.contractCode }
    };
    await getContext().startAbility(want);
  }

  private async openVulnListWindow(): Promise<void> {
    const want = {
      deviceId: '',
      bundleName: getContext().applicationInfo.name,
      abilityName: 'VulnListAbility',
      parameters: { vulnerabilitiesData: JSON.stringify(this.vulnerabilities) }
    };
    await getContext().startAbility(want);
  }

  private async openFundFlowWindow(): Promise<void> {
    const want = {
      deviceId: '',
      bundleName: getContext().applicationInfo.name,
      abilityName: 'FundFlowAbility',
      parameters: { attackPaths: JSON.stringify(this.attackPaths) }
    };
    await getContext().startAbility(want);
  }

  build() {
    Stack() {
      Column()
        .width('100%')
        .height('100%')
        .backgroundColor(this.ambientColor)
        .animation({ duration: 800, curve: Curve.EaseInOut })

      Column() {
        Row() {
          Row() {
            Circle()
              .width(10)
              .height(10)
              .fill(this.primaryColor)
              .shadow({ radius: 6, color: this.primaryColor + '80' })
            
            Text(securityLightTheme.getCurrentConfig().securityLabel)
              .fontSize(13)
              .fontColor(this.primaryColor)
              .margin({ left: 6 })
          }

          Blank()

          Text('链界智脑')
            .fontSize(18)
            .fontWeight(FontWeight.Bold)
            .fontColor('#333333')

          Blank()

          Row({ space: 12 }) {
            Button('调用图')
              .fontSize(12)
              .backgroundColor(this.primaryColor + '1A')
              .fontColor(this.primaryColor)
              .borderRadius(6)
              .onClick(() => this.openCallGraphWindow())

            Button('漏洞清单')
              .fontSize(12)
              .backgroundColor(this.primaryColor + '1A')
              .fontColor(this.primaryColor)
              .borderRadius(6)
              .onClick(() => this.openVulnListWindow())

            Button('资金流')
              .fontSize(12)
              .backgroundColor(this.primaryColor + '1A')
              .fontColor(this.primaryColor)
              .borderRadius(6)
              .onClick(() => this.openFundFlowWindow())
          }
        }
        .width('100%')
        .height(56)
        .padding({ left: 24, right: 24 })
        .backgroundColor('rgba(255, 255, 255, 0.85)')
        .backdropFilter($r('sys.blur.20'))
        .alignItems(VerticalAlign.Center)

        if (this.parseResult) {
          Row() {
            Text(`函数:${this.parseResult.totalFunctions}个`)
              .fontSize(11)
              .fontColor('#666666')
            Text(`复杂度:${this.parseResult.complexityScore}`)
              .fontSize(11)
              .fontColor('#666666')
              .margin({ left: 16 })
            Text(`外部调用:${this.parseResult.externalCalls}`)
              .fontSize(11)
              .fontColor(this.primaryColor)
              .margin({ left: 16 })
            if (this.isAuditing) {
              Text('审计中...')
                .fontSize(11)
                .fontColor(this.primaryColor)
                .margin({ left: 16 })
                .animation({
                  duration: 1000,
                  iterations: -1,
                  curve: Curve.EaseInOut
                })
                .opacity(0.5 + Math.sin(this.pulsePhase) * 0.5)
            }
          }
          .width('100%')
          .height(36)
          .padding({ left: 24, right: 24 })
          .backgroundColor('rgba(255, 255, 255, 0.6)')
        }

        // 合约代码编辑器 + 调用图
        Row() {
          // 代码编辑器
          RichEditor({ controller: this.codeController })
            .width('55%')
            .height('100%')
            .padding(16)
            .backgroundColor('#1E1E1E')
            .borderRadius(12)
            .margin(16)
            .shadow({ radius: 12, color: 'rgba(0, 0, 0, 0.1)', offsetX: 0, offsetY: 4 })

          // 调用图 + 攻击路径
          Column() {
            // 合约调用图
            Canvas(this.callGraphContext)
              .width('100%')
              .height('60%')
              .backgroundColor('#FFFFFF')
              .borderRadius(12)
              .shadow({ radius: 8, color: 'rgba(0, 0, 0, 0.06)', offsetX: 0, offsetY: 4 })
              .onReady((context) => {
                this.callGraphContext = context;
                this.renderCallGraph(context);
              })

            // 攻击路径摘要
            if (this.attackPaths.length > 0) {
              Column() {
                Text('攻击路径模拟')
                  .fontSize(14)
                  .fontWeight(FontWeight.Medium)
                  .fontColor('#333333')
                  .alignSelf(ItemAlign.Start)
                  .margin({ bottom: 8 })

                ForEach(this.attackPaths.slice(0, 3), (attack: AttackPath) => {
                  Row() {
                    Text(attack.type.toUpperCase())
                      .fontSize(12)
                      .fontColor('#E74C3C')
                      .backgroundColor('#FDEDEC')
                      .borderRadius(4)
                      .padding({ left: 6, right: 6 })
                    
                    Text(`成功率:${(attack.successRate * 100).toFixed(0)}%`)
                      .fontSize(12)
                      .fontColor('#666666')
                      .margin({ left: 8 })
                    
                    Text(attack.profit)
                      .fontSize(12)
                      .fontColor('#E74C3C')
                      .margin({ left: 8 })
                  }
                  .width('100%')
                  .height(32)
                  .margin({ bottom: 4 })
                })
              }
              .width('100%')
              .layoutWeight(1)
              .padding(12)
              .backgroundColor('#FFFFFF')
              .borderRadius(12)
              .margin({ top: 12 })
              .shadow({ radius: 8, color: 'rgba(0, 0, 0, 0.06)', offsetX: 0, offsetY: 4 })
            }
          }
          .width('40%')
          .height('100%')
          .margin({ top: 16, bottom: 16, right: 16 })
        }
        .width('100%')
        .layoutWeight(1)

        Column() {
          AuditFloatNavigation()
        }
        .width('100%')
      }
      .width('100%')
      .height('100%')
    }
    .width('100%')
    .height('100%')
  }

  private renderCallGraph(ctx: CanvasRenderingContext2D): void {
    const width = 500;
    const height = 300;
    ctx.clearRect(0, 0, width, height);
    
    // 简化的调用图渲染
    ctx.fillStyle = '#3498DB';
    ctx.beginPath();
    ctx.arc(width / 2, 50, 30, 0, Math.PI * 2);
    ctx.fill();
    ctx.fillStyle = '#FFFFFF';
    ctx.font = '12px sans-serif';
    ctx.textAlign = 'center';
    ctx.fillText('withdraw', width / 2, 55);

    ctx.fillStyle = '#E74C3C';
    ctx.beginPath();
    ctx.arc(width / 2, 150, 25, 0, Math.PI * 2);
    ctx.fill();
    ctx.fillStyle = '#FFFFFF';
    ctx.fillText('call{value}', width / 2, 155);

    ctx.fillStyle = '#9B59B6';
    ctx.beginPath();
    ctx.arc(width / 2, 250, 25, 0, Math.PI * 2);
    ctx.fill();
    ctx.fillStyle = '#FFFFFF';
    ctx.fillText('fallback', width / 2, 255);

    // 连接线
    ctx.strokeStyle = '#999999';
    ctx.lineWidth = 2;
    ctx.beginPath();
    ctx.moveTo(width / 2, 80);
    ctx.lineTo(width / 2, 125);
    ctx.moveTo(width / 2, 175);
    ctx.lineTo(width / 2, 225);
    ctx.stroke();

    // 重入循环
    ctx.strokeStyle = '#E74C3C';
    ctx.setLineDash([5, 5]);
    ctx.beginPath();
    ctx.arc(width / 2 + 50, 200, 40, -Math.PI / 2, Math.PI / 2);
    ctx.stroke();
    ctx.setLineDash([]);
  }
}

3.5 浮动漏洞清单窗口(VulnListAbility.ets)

代码亮点:本模块实现了浮动漏洞清单窗口,按安全等级和漏洞类型分组显示。支持点击漏洞项自动定位到合约编辑器中的对应代码行,并同步切换主窗口的安全光效氛围。

typescript 复制代码
// entry/src/main/ets/vulnability/VulnListAbility.ets

import { window } from '@kit.WindowManagerKit';
import { securityLightTheme, SecurityLevel, Vulnerability } from '../theme/SecurityLightTheme';

@Entry
@Component
struct VulnListPage {
  @StorageLink('currentSecurityLevel') currentLevel: SecurityLevel = SecurityLevel.SAFE;
  @StorageLink('primaryLightColor') primaryColor: string = '#27AE60';
  
  @State vulnerabilities: Vulnerability[] = [];
  @State isWindowFocused: boolean = true;
  @State selectedVulnId: string = '';

  aboutToAppear(): void {
    const params = getContext().abilityInfo?.parameters;
    if (params?.vulnerabilitiesData) {
      this.vulnerabilities = JSON.parse(params.vulnerabilitiesData);
    }
    this.setupFocusListener();
  }

  private async setupFocusListener(): Promise<void> {
    const win = await window.getLastWindow(getContext());
    win.on('windowFocusChange', (isFocused: boolean) => {
      this.isWindowFocused = isFocused;
    });
  }

  private getGroupedVulns(): Record<SecurityLevel, Vulnerability[]> {
    const grouped: Record<SecurityLevel, Vulnerability[]> = {
      [SecurityLevel.CRITICAL]: [],
      [SecurityLevel.HIGH_RISK]: [],
      [SecurityLevel.MEDIUM_RISK]: [],
      [SecurityLevel.LOW_RISK]: [],
      [SecurityLevel.SAFE]: []
    };
    this.vulnerabilities.forEach(v => grouped[v.severity].push(v));
    return grouped;
  }

  private getVulnColor(type: string): string {
    const map: Record<string, string> = {
      'reentrancy': '#9B59B6',
      'overflow': '#F39C12',
      'access_control': '#8E44AD',
      'oracle': '#FF69B4',
      'flash_loan': '#C0392B',
      'front_running': '#E67E22'
    };
    return map[type] || '#999999';
  }

  private getStatusColor(status: SecurityLevel): string {
    const map: Record<SecurityLevel, string> = {
      [SecurityLevel.SAFE]: '#27AE60',
      [SecurityLevel.LOW_RISK]: '#3498DB',
      [SecurityLevel.MEDIUM_RISK]: '#F39C12',
      [SecurityLevel.HIGH_RISK]: '#E67E22',
      [SecurityLevel.CRITICAL]: '#E74C3C'
    };
    return map[status];
  }

  build() {
    Column() {
      Row() {
        Circle().width(10).height(10).fill(this.primaryColor)
          .shadow({ radius: 6, color: this.primaryColor + '80' })
        Text('漏洞清单').fontSize(16).fontWeight(FontWeight.Bold).fontColor('#333333').margin({ left: 8 })
        Blank()
        Text(`${this.vulnerabilities.length}项漏洞`).fontSize(12).fontColor('#999999')
      }
      .width('100%').height(48).padding({ left: 16, right: 16 })
      .backgroundColor('rgba(255, 255, 255, 0.9)')
      .borderRadius({ topLeft: 16, topRight: 16 })

      List() {
        const grouped = this.getGroupedVulns();
        const order: SecurityLevel[] = [SecurityLevel.CRITICAL, SecurityLevel.HIGH_RISK, SecurityLevel.MEDIUM_RISK];

        ForEach(order, (severity: SecurityLevel) => {
          const vulns = grouped[severity];
          if (vulns.length === 0) return;

          ListItem() {
            Row() {
              Row().width(4).height(16).backgroundColor(this.getStatusColor(severity)).borderRadius(2).margin({ right: 8 })
              Text(`${this.getSeverityLabel(severity)} (${vulns.length})`)
                .fontSize(13).fontWeight(FontWeight.Bold).fontColor(this.getStatusColor(severity))
            }
            .width('100%').height(36).padding({ left: 16, right: 16 })
            .backgroundColor(this.getStatusColor(severity) + '0D')
          }

          ForEach(vulns, (vuln: Vulnerability) => {
            ListItem() {
              Column() {
                Row() {
                  Circle().width(8).height(8).fill(this.getVulnColor(vuln.vulnerabilityType))
                  Text(vuln.vulnerabilityType.toUpperCase())
                    .fontSize(11).fontColor(this.getVulnColor(vuln.vulnerabilityType))
                    .margin({ left: 6 })
                  Blank()
                  Text(`CWE-${vuln.cweId}`)
                    .fontSize(10).fontColor('#999999')
                }
                .width('100%')
                
                Text(`第${vuln.lineNumber}行:${vuln.description}`)
                  .fontSize(12).fontColor('#666666').margin({ top: 4 })
                
                Text(`修复:${vuln.suggestedFix}`)
                  .fontSize(11).fontColor('#999999').margin({ top: 4 }).maxLines(2)
              }
              .width('100%').padding(12)
              .backgroundColor(this.selectedVulnId === vuln.id ? this.getStatusColor(severity) + '1A' : '#FFFFFF')
              .borderRadius(8)
              .border({ width: 1, color: this.selectedVulnId === vuln.id ? this.getStatusColor(severity) + '4D' : '#F0F0F0', radius: 8 })
              .onClick(() => {
                this.selectedVulnId = vuln.id;
                securityLightTheme.switchSecurityLight(vuln.severity);
                AppStorage.setOrCreate('selectedVulnId', vuln.id);
                AppStorage.setOrCreate('focusVulnLine', vuln.lineNumber);
              })
            }
          })
        })
      }
      .width('100%').layoutWeight(1).padding(12).scrollBar(BarState.Auto)

      Row() {
        Text(`总计:${this.vulnerabilities.length}项漏洞`).fontSize(12).fontColor('#999999')
      }
      .width('100%').height(40).padding({ left: 16, right: 16 })
      .justifyContent(FlexAlign.Center).borderTop({ width: 0.5, color: '#EEEEEE' })
    }
    .width('100%').height('100%')
    .backgroundColor('rgba(255, 255, 255, 0.9)')
    .backdropFilter($r('sys.blur.20'))
    .borderRadius(16)
    .shadow({ radius: 24, color: 'rgba(0, 0, 0, 0.15)', offsetX: 0, offsetY: 8 })
    .opacity(this.isWindowFocused ? 1.0 : 0.65)
    .animation({ duration: 300, curve: Curve.EaseInOut })
  }

  private getSeverityLabel(severity: SecurityLevel): string {
    const labels: Record<SecurityLevel, string> = {
      [SecurityLevel.SAFE]: '安全',
      [SecurityLevel.LOW_RISK]: '低风险',
      [SecurityLevel.MEDIUM_RISK]: '中风险',
      [SecurityLevel.HIGH_RISK]: '高风险',
      [SecurityLevel.CRITICAL]: '严重漏洞'
    };
    return labels[severity];
  }
}

四、关键技术总结

4.1 HMAF合约审计开发清单

技术点 API/方法 应用场景
多智能体会话 hmaf.createAgentSession({ mode: MULTI_AGENT }) 四层Agent协作审计
意图解析 intents.createIntentEngine({ supportedDomains }) 审计意图理解
合约解析Agent AgentType.CONTRACT_PARSER Solidity/Vyper解构
漏洞检测Agent AgentType.VULNERABILITY_DETECTOR 静态/动态分析
攻击模拟Agent AgentType.ATTACK_SIMULATOR 多跳攻击路径构建
合规审查Agent AgentType.COMPLIANCE_CHECKER SEC/MiCA/SFC匹配

4.2 安全等级光效映射

安全等级 主色调 脉冲速度 典型场景
安全 #27AE60 翠绿 4000ms 无漏洞、可部署
低风险 #3498DB 淡蓝 3500ms 信息性建议
中风险 #F39C12 暖黄 2500ms 低危漏洞
高风险 #E67E22 紧迫橙 1800ms 高危漏洞
严重漏洞 #E74C3C 危险红 1000ms 致命漏洞

4.3 漏洞类型光效标识

漏洞类型 光晕色 标识意义
重入攻击 #9B59B6 紫红 递归调用风险
整数溢出 #F39C12 橙黄 计算边界突破
访问控制 #8E44AD 蓝紫 权限绕过
预言机操纵 #FF69B4 粉红 价格操纵
闪电贷攻击 #C0392B 深红 瞬时资金攻击
前端运行 #E67E22 橙红 MEV提取

五、运行效果展示

5.1 代码审计阶段 - 安全光效

打开一个clean的合约,界面呈现翠绿色光效:代码编辑器深色背景,调用图显示正常函数调用关系,底部导航脉冲缓慢,传递"合约安全、可部署"的直觉。

5.2 漏洞检测阶段 - 严重漏洞光效

检测到withdraw函数存在重入攻击向量,界面切换为危险红色光效:该函数代码行紫色波浪下划线高亮,调用图中重入循环红色虚线标识,浮动漏洞清单自动弹出并定位到该漏洞。

5.3 攻击模拟阶段 - 高风险光效

模拟闪电贷攻击成功率85%,可获利230万美元,界面切换为紧迫橙色光效:攻击路径面板显示详细攻击步骤,资金流图显示资金流动路径,强烈提示"存在可获利攻击向量、必须修复"。


六、总结与展望

本文基于HarmonyOS 6(API 23)的悬浮导航沉浸光感HMAF智能体框架特性,完整实战了一款面向PC端的"链界智脑"AI智能体区块链智能合约审计与DeFi风控管理工作台。核心创新点:

  1. HMAF四层审计智能体:合约解析Agent(Solidity/Vyper解构)、漏洞检测Agent(静态/动态分析)、攻击模拟Agent(多跳攻击路径构建)、合规审查Agent(SEC/MiCA/SFC匹配),实现"合约上传→自动解析→漏洞检测→攻击模拟→合规审查"的全链路自动化

  2. 安全等级光效系统:五种安全等级拥有专属光效人格(安全翠绿→低风险淡蓝→中风险暖黄→高风险紧迫橙→严重漏洞危险红),实现安全审计员"一眼感知合约健康度"

  3. 悬浮审计导航:底部悬浮页签承载"代码审计-漏洞检测-攻击模拟-合规审查"四个审计阶段,实时显示漏洞统计徽章

  4. PC级多窗口协作审计 :主合约编辑器 + 浮动调用图 + 浮动漏洞清单 + 浮动资金流追溯的四层架构,通过AppStorage实现跨窗口光效同步

  5. 审计意图沉浸感知:通过Intents Kit解析安全审计员意图,自动触发对应Agent协作并调整界面安全光效

未来扩展方向

  • 分布式安全审计:PC主控审计+服务器集群符号执行+平板移动审计的三端流转
  • 实时链上监控:接入区块链节点,合约部署后持续监控异常交易,自动预警
  • AI辅助修复:智能体自动生成修复后的合约代码,并验证修复有效性
  • 跨链安全分析:支持多链合约(以太坊、Solana、Aptos)统一审计与风险对比

转载自:https://blog.csdn.net/u014727709/article/details/161613811

欢迎 👍点赞✍评论⭐收藏,欢迎指正

相关推荐
诸葛务农1 小时前
共沸脱水技术及其在光刻胶用PGMEA纯化中的应用(下)
人工智能
雪隐1 小时前
AI股票小助手04-miniQMT数据采集
人工智能·后端
sugar__salt1 小时前
从零落地 Generative AI 接口调用:Node.js 工程化最佳实践
人工智能·node.js
不要额外加糖1 小时前
给 Codex 戴上紧箍, 治一治 AI 的过度发挥
前端·人工智能·代码规范
weixin_468466851 小时前
空洞卷积与膨胀卷积新手入门指南
图像处理·人工智能·深度学习·ai·机器视觉·卷积·空洞卷积
AI创界者1 小时前
ComfyUI v8 极致整合包发布!Win/Mac 双平台完美适配 + 多卡并行加速,开启 AI 绘画新时代
人工智能·macos
zhangfeng11331 小时前
本账号 自媒体 csdn 账号诊断和改进建议,记录一下
人工智能·机器学习·媒体
镭封1 小时前
影视解说、小说推文、情感语录,分别适合什么AI声音?
人工智能
ZPC82101 小时前
前馈补偿原理 + 分类 + 公式 + 工程实现(配合 PID 使用,从根源减轻闭环收敛压力)
人工智能·分布式·机器人