NAC_Blockchain/docs/modules/nac-cli分析报告.md

20 KiB
Raw Blame History

nac-cli 模块深度分析报告

模块名称: nac-cli
版本: 2.0.0
分析日期: 2026-02-18
分析人员: NAC开发团队


📋 模块概览

功能定位: NAC Developer Toolbox v2.0 - 完美中心化框架下的去中心化开发工具
英文全称: NAC Command Line Interface
代码行数: 1,570行
完成度: 30%
测试覆盖: 10% (2个测试)
编译状态: 通过


🏗️ 架构设计

核心功能

nac-cli是NAC公链的命令行工具提供以下功能

  1. 账户管理: 创建、导入、导出、查询账户
  2. 交易管理: 发送、查询、签名、广播交易
  3. 合约管理: 部署、调用、查询合约
  4. 宪法查询: 查看宪法条款和参数
  5. 节点管理: 查看节点信息和状态
  6. 区块查询: 查看区块信息
  7. 配置管理: 管理CLI配置
  8. 工具功能: 密钥生成、哈希计算、GNACS编码
  9. 开发工具箱v2.0: 项目创建、编译、测试、沙箱

技术栈

组件 技术 版本 说明
CLI框架 clap 4.5 命令行解析
异步运行时 tokio 1.0 异步执行
HTTP客户端 reqwest 0.12 RPC调用
密码学 secp256k1 0.29 签名验证
序列化 serde 1.0 数据序列化
日志 env_logger 0.11 日志记录

目录结构

nac-cli/
├── src/
│   ├── main.rs (144行) - 程序入口
│   ├── cli.rs (419行) - 命令定义
│   ├── config.rs - 配置管理
│   ├── error.rs - 错误定义
│   ├── commands/ (164行) - 命令实现
│   │   ├── account.rs - 账户命令
│   │   ├── transaction.rs - 交易命令
│   │   ├── contract.rs - 合约命令
│   │   ├── constitution.rs - 宪法命令
│   │   ├── node.rs - 节点命令
│   │   ├── block.rs - 区块命令
│   │   ├── config.rs - 配置命令
│   │   └── utils.rs - 工具命令
│   ├── client/ (80行) - RPC客户端
│   │   ├── mod.rs - 客户端模块
│   │   └── nrpc.rs - NAC Lens客户端
│   ├── toolbox/ (317行) - 开发工具箱v2.0
│   │   ├── templates.rs - 项目模板
│   │   ├── sandbox.rs - 宪法沙箱
│   │   ├── lsp.rs - LSP服务器
│   │   ├── version.rs - 版本管理
│   │   └── audit.rs - 审计工具
│   └── utils/ (110行) - 工具函数
│       ├── crypto.rs - 密码学工具
│       ├── format.rs - 格式化工具
│       └── gnacs.rs - GNACS编码
└── Cargo.toml

🔍 核心功能详解

1. 命令定义 (cli.rs - 419行)

1.1 主命令

pub struct Cli {
    #[command(subcommand)]
    pub command: Commands,

    /// 输出格式 (json, yaml, table)
    #[arg(long, short = 'o', default_value = "table", global = true)]
    pub output: String,

    /// 详细输出
    #[arg(long, short = 'v', global = true)]
    pub verbose: bool,

    /// RPC节点地址
    #[arg(long, global = true)]
    pub rpc_url: Option<String>,
}

全局参数:

  • --output, -o: 输出格式json/yaml/table
  • --verbose, -v: 详细输出
  • --rpc-url: RPC节点地址

1.2 子命令列表

命令 说明 实现状态
account 账户管理 ⚠️ 部分实现
transaction 交易管理 ⚠️ 部分实现
contract 合约管理 ⚠️ 部分实现
constitution 宪法查询 ⚠️ 部分实现
node 节点管理 ⚠️ 部分实现
block 区块查询 ⚠️ 部分实现
config 配置管理 已实现
utils 工具功能 ⚠️ 部分实现
new 创建新项目 ⚠️ 框架实现
init 初始化项目 ⚠️ 框架实现
build 编译项目 仅占位
check 宪法检查 仅占位
test 运行测试 仅占位
sandbox 宪法沙箱 ⚠️ 框架实现
tool 工具链管理 ⚠️ 框架实现
lsp LSP服务器 ⚠️ 框架实现
completions Shell补全 仅占位
docs 打开文档 仅占位
show-version 显示版本 已实现

2. 账户管理 (account.rs)

2.1 账户命令

pub enum AccountCommands {
    /// 创建新账户
    Create { password: Option<String> },
    
    /// 列出所有账户
    List,
    
    /// 查看账户详情
    Show { address: String },
    
    /// 导入账户
    Import { private_key: String, password: Option<String> },
    
    /// 导出账户私钥
    Export { address: String, password: Option<String> },
    
    /// 查询账户余额
    Balance { address: String },
}

使用示例:

# 创建账户
nac account create --password mypassword

# 列出账户
nac account list

# 查询余额
nac account balance nac1...

# 导入账户
nac account import --private-key 0x... --password mypassword

# 导出私钥
nac account export nac1... --password mypassword

3. 交易管理 (transaction.rs)

3.1 交易命令

pub enum TransactionCommands {
    /// 发送交易
    Send {
        from: String,
        to: String,
        amount: String,
        gas_limit: Option<u64>,
        gas_price: Option<u64>,
    },
    
    /// 查看交易详情
    Show { tx_hash: String },
    
    /// 列出交易历史
    List { address: String, limit: usize },
    
    /// 签名交易
    Sign { tx_file: String, private_key: String },
    
    /// 广播已签名交易
    Broadcast { signed_tx: String },
}

使用示例:

# 发送交易
nac tx send nac1... nac2... 100 --gas-limit 21000

# 查看交易
nac tx show 0x...

# 交易历史
nac tx list nac1... --limit 20

# 签名交易
nac tx sign tx.json --private-key 0x...

# 广播交易
nac tx broadcast 0x...

4. 合约管理 (contract.rs)

4.1 合约命令

pub enum ContractCommands {
    /// 部署合约
    Deploy {
        wasm_file: String,
        from: String,
        init_args: Option<String>,
    },
    
    /// 调用合约方法
    Call {
        address: String,
        method: String,
        args: Option<String>,
        from: String,
    },
    
    /// 查询合约状态
    Query {
        address: String,
        method: String,
        args: Option<String>,
    },
    
    /// 查看合约代码
    Code { address: String },
}

使用示例:

# 部署合约
nac contract deploy contract.wasm --from nac1... --init-args '{"name":"MyToken"}'

# 调用合约
nac contract call nac1... transfer --args '["nac2...", 100]' --from nac1...

# 查询合约
nac contract query nac1... balanceOf --args '["nac2..."]'

# 查看代码
nac contract code nac1...

5. 宪法查询 (constitution.rs)

5.1 宪法命令

pub enum ConstitutionCommands {
    /// 列出所有宪法条款
    List,
    
    /// 查看条款详情
    Show { clause_id: String },
    
    /// 验证条款状态
    Verify { clause_id: String },
    
    /// 查看条款参数
    Params { clause_id: String },
}

使用示例:

# 列出条款
nac constitution list

# 查看条款
nac constitution show XTZH_GOLD_COVERAGE

# 验证条款
nac constitution verify XTZH_GOLD_COVERAGE

# 查看参数
nac constitution params XTZH_GOLD_COVERAGE

6. 开发工具箱v2.0 (toolbox/)

6.1 项目创建

Commands::New { name, r#type } => {
    let project_type = match r#type {
        ProjectType::Constitution => "constitution",
        ProjectType::Contract => "contract",
        ProjectType::NodePlugin => "node-plugin",
    };
    toolbox::templates::create_project(name, project_type)?;
    Ok(())
}

使用示例:

# 创建合约项目
nac new my-contract --type contract

# 创建宪法项目
nac new my-constitution --type constitution

# 创建节点插件
nac new my-plugin --type node-plugin

6.2 编译和测试

Commands::Build { release } => {
    println!("🔨 编译项目...");
    if *release {
        println!("  模式: Release");
    } else {
        println!("  模式: Debug");
    }
    println!("  ✓ 编译成功");
    Ok(())
}

Commands::Test { contract } => {
    println!("🧪 运行测试...");
    if *contract {
        println!("  类型: 合约测试");
    } else {
        println!("  类型: 全部测试");
    }
    println!("  ✓ 测试通过");
    Ok(())
}

问题: 只是占位实现,没有实际功能


6.3 宪法沙箱

Commands::Sandbox { duration, constitution } => {
    toolbox::sandbox::run_sandbox(duration, constitution.clone())?;
    Ok(())
}

功能: 模拟宪法变更影响

使用示例:

nac sandbox --duration 30d --constitution new_constitution.toml

6.4 工具链管理

pub enum ToolAction {
    /// 安装指定版本工具链
    Install { version: String },
    
    /// 切换默认版本
    Use { version: String },
    
    /// 列出已安装版本
    List,
    
    /// 同步项目锁定版本
    Sync,
    
    /// 验证工具箱完整性
    Verify,
}

使用示例:

# 安装工具链
nac tool install 2.0.0

# 切换版本
nac tool use 2.0.0

# 列出版本
nac tool list

# 同步版本
nac tool sync

# 验证完整性
nac tool verify

6.5 LSP服务器

Commands::Lsp { stdio } => {
    toolbox::lsp::start_lsp_server(*stdio)?;
    Ok(())
}

功能: 为IDE提供语言服务器协议支持

使用示例:

nac lsp --stdio

7. 工具函数 (utils/)

7.1 密钥生成

Commands::Utils(UtilsCommands::Keygen) => {
    // 生成密钥对
}

7.2 哈希计算

Commands::Utils(UtilsCommands::Hash { data }) => {
    // 计算哈希
}

7.3 GNACS编码

Commands::Utils(UtilsCommands::Encode { data }) => {
    // GNACS编码
}

Commands::Utils(UtilsCommands::Decode { gnacs }) => {
    // GNACS解码
}

🐛 发现的问题

问题1: 大部分命令只有框架

严重程度: ⚠️ 极高

描述: commands/目录下的大部分文件只有框架,没有实际实现

影响: CLI无法使用

建议: 实现所有命令

// commands/account.rs
pub async fn execute(cmd: &AccountCommands, cli: &Cli) -> Result<()> {
    let client = NrpcClient::new(cli.rpc_url.as_deref())?;
    
    match cmd {
        AccountCommands::Create { password } => {
            let (address, private_key) = crypto::generate_keypair();
            // 保存到keystore
            println!("地址: {}", address);
            Ok(())
        },
        AccountCommands::Balance { address } => {
            let balance = client.get_balance(address).await?;
            println!("余额: {}", balance);
            Ok(())
        },
        // ...
    }
}

状态: 待实现


问题2: RPC客户端未实现

严重程度: ⚠️ 极高

描述: client/nrpc.rs只有框架没有实际RPC调用

建议: 实现NAC Lens客户端

// client/nrpc.rs
pub struct NrpcClient {
    url: String,
    client: reqwest::Client,
}

impl NrpcClient {
    pub async fn get_balance(&self, address: &str) -> Result<u64> {
        let response: serde_json::Value = self.client
            .post(&self.url)
            .json(&json!({
                "jsonrpc": "2.0",
                "method": "nac_getBalance",
                "params": [address],
                "id": 1
            }))
            .send()
            .await?
            .json()
            .await?;
        
        Ok(response["result"].as_u64().unwrap_or(0))
    }
}

状态: 待实现


问题3: 工具箱功能未实现

严重程度: ⚠️

描述: toolbox/目录下的功能大部分未实现

建议: 实现工具箱功能

// toolbox/templates.rs
pub fn create_project(name: &str, project_type: &str) -> Result<()> {
    let template = match project_type {
        "contract" => include_str!("../../templates/contract/Cargo.toml"),
        "constitution" => include_str!("../../templates/constitution/Cargo.toml"),
        "node-plugin" => include_str!("../../templates/node-plugin/Cargo.toml"),
        _ => return Err(anyhow!("未知项目类型")),
    };
    
    // 创建项目目录
    std::fs::create_dir_all(name)?;
    
    // 写入模板文件
    std::fs::write(format!("{}/Cargo.toml", name), template)?;
    
    println!("✓ 项目创建成功: {}", name);
    Ok(())
}

状态: 待实现


问题4: 缺少Keystore管理

严重程度: ⚠️

描述: 没有Keystore管理功能

建议: 添加Keystore

// utils/keystore.rs
pub struct Keystore {
    path: PathBuf,
}

impl Keystore {
    pub fn save_account(&self, address: &str, private_key: &str, password: &str) -> Result<()> {
        // 加密私钥
        let encrypted = encrypt_private_key(private_key, password)?;
        
        // 保存到文件
        let filename = format!("{}.json", address);
        std::fs::write(self.path.join(filename), encrypted)?;
        
        Ok(())
    }
    
    pub fn load_account(&self, address: &str, password: &str) -> Result<String> {
        // 从文件加载
        let filename = format!("{}.json", address);
        let encrypted = std::fs::read_to_string(self.path.join(filename))?;
        
        // 解密私钥
        decrypt_private_key(&encrypted, password)
    }
}

状态: 待实现


问题5: 缺少配置文件支持

严重程度: ⚠️ 中等

描述: 虽然有config.rs但功能不完整

建议: 完善配置管理

// config.rs
#[derive(Serialize, Deserialize)]
pub struct Config {
    pub rpc_url: String,
    pub keystore_path: PathBuf,
    pub default_account: Option<String>,
    pub output_format: String,
}

impl Config {
    pub fn load() -> Result<Self> {
        let config_path = dirs::config_dir()
            .ok_or(anyhow!("无法获取配置目录"))?
            .join("nac/config.toml");
        
        if !config_path.exists() {
            return Ok(Self::default());
        }
        
        let content = std::fs::read_to_string(config_path)?;
        Ok(toml::from_str(&content)?)
    }
    
    pub fn save(&self) -> Result<()> {
        let config_path = dirs::config_dir()
            .ok_or(anyhow!("无法获取配置目录"))?
            .join("nac/config.toml");
        
        std::fs::create_dir_all(config_path.parent().unwrap())?;
        std::fs::write(config_path, toml::to_string(self)?)?;
        
        Ok(())
    }
}

状态: ⚠️ 部分实现


问题6: 缺少测试

严重程度: ⚠️ 中等

描述: 只有2个配置测试没有命令测试

建议: 添加集成测试

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_account_create() {
        let cli = Cli {
            command: Commands::Account(AccountCommands::Create {
                password: Some("test".to_string()),
            }),
            output: "json".to_string(),
            verbose: false,
            rpc_url: None,
        };
        
        assert!(execute_command(&cli).await.is_ok());
    }
}

状态: 待添加


问题7: 缺少错误处理

严重程度: ⚠️ 中等

描述: 错误处理不够细致

建议: 定义详细的错误类型

// error.rs
#[derive(thiserror::Error, Debug)]
pub enum CliError {
    #[error("RPC错误: {0}")]
    RpcError(String),
    
    #[error("账户不存在: {0}")]
    AccountNotFound(String),
    
    #[error("密码错误")]
    InvalidPassword,
    
    #[error("配置错误: {0}")]
    ConfigError(String),
    
    #[error("IO错误: {0}")]
    IoError(#[from] std::io::Error),
}

状态: ⚠️ 部分实现


问题8: 缺少Shell补全

严重程度: ⚠️

描述: completions命令只是占位

建议: 生成Shell补全脚本

Commands::Completions { shell } => {
    use clap_complete::{generate, shells};
    
    let shell = match shell.as_str() {
        "bash" => shells::Bash,
        "zsh" => shells::Zsh,
        "fish" => shells::Fish,
        _ => return Err(anyhow!("不支持的shell: {}", shell)),
    };
    
    generate(shell, &mut Cli::command(), "nac", &mut std::io::stdout());
    Ok(())
}

状态: 待实现


📊 完成度评估

功能模块 代码行数 完成度 状态
命令定义 419行 100% 完成
账户管理 ~20行 10% 仅框架
交易管理 ~20行 10% 仅框架
合约管理 ~20行 10% 仅框架
宪法查询 ~20行 10% 仅框架
节点管理 ~20行 10% 仅框架
区块查询 ~20行 10% 仅框架
配置管理 ~20行 60% ⚠️ 部分实现
工具功能 ~20行 20% ⚠️ 部分实现
RPC客户端 80行 10% 仅框架
开发工具箱 317行 20% ⚠️ 部分实现
工具函数 110行 30% ⚠️ 部分实现
测试覆盖 ~20行 10% 不足
总计 1,570行 30% 🚧 进行中

待完善功能

  1. 高优先级:

    • 实现所有命令
    • 实现RPC客户端
    • 实现Keystore管理
    • 完善配置管理
  2. 中优先级:

    • 实现工具箱功能
    • 添加集成测试
    • 完善错误处理
  3. 低优先级:

    • 实现Shell补全
    • 添加文档
    • 优化用户体验

🌟 设计亮点

  1. 完整的命令结构

    • 8个主命令
    • 40+个子命令
    • 清晰的层次结构
  2. 开发工具箱v2.0

    • 项目创建
    • 宪法沙箱
    • LSP服务器
    • 工具链管理
  3. 灵活的输出格式

    • JSON
    • YAML
    • Table
  4. 全局参数

    • RPC地址
    • 输出格式
    • 详细模式

🔗 模块依赖关系

nac-cli
├── 依赖
│   ├── clap (CLI框架)
│   ├── tokio (异步运行时)
│   ├── reqwest (HTTP客户端)
│   ├── secp256k1 (密码学)
│   └── serde (序列化)
├── 应该依赖(未实现)
│   ├── nac-sdk (区块链SDK)
│   ├── nac-wallet-core (钱包核心)
│   └── nac-lens (RPC协议)
└── 被依赖
    └── 开发者使用

📝 开发建议

短期目标 (1周)

  1. 实现RPC客户端 (优先级P1)

    • NAC Lens协议实现
    • 所有RPC方法
    • 错误处理
  2. 实现账户管理 (优先级P1)

    • Keystore管理
    • 账户创建/导入/导出
    • 余额查询
  3. 实现交易管理 (优先级P1)

    • 交易发送
    • 交易签名
    • 交易查询

中期目标 (2周)

  1. 实现合约管理 (优先级P2)

    • 合约部署
    • 合约调用
    • 合约查询
  2. 实现工具箱功能 (优先级P2)

    • 项目模板
    • 编译功能
    • 测试功能
  3. 添加集成测试 (优先级P2)

    • 命令测试
    • RPC测试
    • E2E测试

长期目标 (1个月)

  1. 实现宪法功能 (优先级P3)

    • 宪法查询
    • 宪法沙箱
    • 宪法验证
  2. 实现LSP服务器 (优先级P3)

    • 语法高亮
    • 自动补全
    • 错误检查
  3. 优化用户体验 (优先级P4)

    • Shell补全
    • 进度条
    • 友好的错误信息

💡 使用示例

基础操作

# 初始化配置
nac config init

# 创建账户
nac account create --password mypassword

# 查询余额
nac account balance nac1...

# 发送交易
nac tx send nac1... nac2... 100

# 查看交易
nac tx show 0x...

合约操作

# 部署合约
nac contract deploy contract.wasm --from nac1...

# 调用合约
nac contract call nac1... transfer --args '["nac2...", 100]' --from nac1...

# 查询合约
nac contract query nac1... balanceOf --args '["nac2..."]'

开发工具箱

# 创建项目
nac new my-contract --type contract

# 编译项目
nac build --release

# 运行测试
nac test

# 宪法沙箱
nac sandbox --duration 30d --constitution new.toml

# 工具链管理
nac tool install 2.0.0
nac tool use 2.0.0

分析完成时间: 2026-02-18
下一步: 实现RPC客户端和核心命令功能