//! `mpc chain` —— 链上层命令行。 //! //! # 诚实边界(写在使用说明前面) //! //! 2026-11-07 用户拍板后,`mpc chain sign` 已经能用 OpenSSL **真的签出** //! SM2 签名(raw `r||s` 64B),但它是软件签名器、私钥可导出、密评不可过。 //! `flush` 发出去的 payload **仍是链上对象规范字节,不是已签名的 FISCO 交易**: //! FISCO **自有**交易编码(不是以太坊 RLP)待真机对拍、Tongsuo TLCP 握手 //! FFI 未落地。★ 国密链提交方法是自有 `sendTransaction`(4 参), //! **不是** `eth_sendRawTransaction` —— web3 端点固定 //! secp256k1 + keccak256(`Web3Transaction.cpp`),与 SM2/SM3 不兼容。 //! `flush` 的假链桩仍用 `eth_sendRawTransaction` 演练补链,输出里带 //! `methodIsStub=true` 与 `guomiSubmitMethod`,绝不把桩方法冒充真链入口。 //! 所以这一层能验证的是「签名 / distid 对齐 / 传输准入 / 幂等补链 / //! fail-open 与 fail-closed 分离 / JSON-RPC 判定」这些框架自己的契约, //! **不是「能上链」**。桩自测也只判这些。 use mpc_chain::admission::{chain_admit, MemberCache}; use mpc_chain::objects::{ object_digest, ChainObject, ComputeOrder, Member, PolicyBundleRecord, Receipt, }; use mpc_chain::outbox::{EnqueueOutcome, Outbox}; use mpc_chain::policy::{governance_boundary, HardRuleSet, OpaPolicyBundle}; use mpc_chain::rpc::{ChainClient, HttpChainClient}; use mpc_chain::signer::{ require_self_test, Signer, SignerPolicy, SignerSecurityProfile, SOFTWARE_DEV_WARNING, }; use mpc_chain::sm2::{ aligned_distid, distid_fingerprint, raw_rs_to_der, DistidConsumer, OpenSslSoftwareSigner, SM2_DISTID, }; use mpc_chain::tlcp::{ probe_tlcp_environment, TlcpBackend, TlcpConfig, TlcpReadiness, }; use mpc_chain::{to_hex, ChainConfig, TransportMode, PLAINTEXT_STUB_WARNING}; use std::collections::HashMap; use std::fs; pub fn cmd_chain(args: &[String]) -> Result<(), String> { match args.first().map(String::as_str) { Some("digest") => cmd_digest(&args[1..]), Some("submit") => cmd_submit(&args[1..]), Some("flush") => cmd_flush(&args[1..]), Some("status") => cmd_status(&args[1..]), Some("admit") => cmd_admit(&args[1..]), Some("keygen") => cmd_keygen(&args[1..]), Some("sign") => cmd_sign(&args[1..]), Some("align") => cmd_align(&args[1..]), Some("tlcp") => cmd_tlcp(&args[1..]), Some("governance") => cmd_governance(&args[1..]), _ => Err(CHAIN_USAGE.to_string()), } } const CHAIN_USAGE: &str = "用法: mpc chain digest 算链上对象的规范字节与 SM3 摘要 --config PATH --kind member|order|receipt|bundle --file PATH mpc chain submit 把回执写进 outbox(fail-open:链挂也照常入队) --config PATH --outbox PATH --file PATH (Receipt JSON) mpc chain flush 补链:把 Pending 条目发给 bcos-rpc,幂等 --config PATH --outbox PATH --transport stub|tlcp [--tlcp-config PATH] mpc chain status 从 outbox 回读条目状态 --outbox PATH mpc chain admit 链读侧准入(fail-closed) --cache PATH --now N --site NAME --participants A,B mpc chain keygen 生成【开发用】OpenSSL 软件 SM2 密钥(0600) --out PATH --pub-out PATH mpc chain sign 用 SM2 签一段字节(输出 raw r||s 与 DER) --key PATH --file PATH --policy production-module|development-software mpc chain align 校验 SM2 distid 三重对齐 [--chain-verifier-distid STR] [--csv-distid STR] mpc chain tlcp 报告国密 TLCP 通道就绪状态(诊断,不发起连接) [--file PATH] (TLCP 双证书配置) mpc chain governance 算治理对象摘要(硬规则 / OPA bundle) --config PATH --kind hard-rule|opa-bundle --file PATH ★ --transport 必须显式给:stub 只允许桩自测,tlcp 是生产路径。 ★ sign 的 --policy 必须显式给;production-module 会拒绝软件签名器。 ★ flush 的 payload 仍是规范字节,不是已签名交易(FISCO 自有交易编码 / Tongsuo TLCP FFI 未落地);桩方法 eth_sendRawTransaction 不是国密链入口, 真链必须走 sendTransaction(4 参)。"; fn opts(args: &[String], allowed: &[&str]) -> Result, String> { let mut m = HashMap::new(); let mut i = 0usize; while i < args.len() { let k = &args[i]; if !k.starts_with("--") || !allowed.contains(&k.as_str()) { return Err(format!("未知参数 {k}(允许: {})", allowed.join(" "))); } let v = args .get(i + 1) .ok_or_else(|| format!("{k} 缺少取值"))?; if m.insert(k.clone(), v.clone()).is_some() { return Err(format!("{k} 重复给出")); } i += 2; } Ok(m) } fn req<'a>(m: &'a HashMap, key: &str) -> Result<&'a str, String> { m.get(key) .map(String::as_str) .ok_or_else(|| format!("缺少必填参数 {key}")) } fn read(path: &str) -> Result { fs::read_to_string(path).map_err(|e| format!("读 {path} 失败: {e}")) } fn config(path: &str) -> Result { ChainConfig::from_json(&read(path)?).map_err(|e| e.to_string()) } fn esc(s: &str) -> String { let mut out = String::new(); for c in s.chars() { match c { '"' => out.push_str("\\\""), '\\' => out.push_str("\\\\"), '\n' => out.push_str("\\n"), '\r' => out.push_str("\\r"), '\t' => out.push_str("\\t"), c if c.is_control() => out.push_str(&format!("\\u{:04x}", c as u32)), c => out.push(c), } } out } fn parse_object(kind: &str, text: &str) -> Result, String> { let b: Box = match kind { "member" => Box::new(Member::from_json(text).map_err(|e| e.to_string())?), "order" => Box::new(ComputeOrder::from_json(text).map_err(|e| e.to_string())?), "receipt" => Box::new(Receipt::from_json(text).map_err(|e| e.to_string())?), "bundle" => Box::new(PolicyBundleRecord::from_json(text).map_err(|e| e.to_string())?), _ => return Err(format!("不认识的 --kind: {kind}")), }; Ok(b) } fn write_private(path: &str, bytes: &[u8]) -> Result<(), String> { use std::io::Write; let mut o = fs::OpenOptions::new(); o.write(true).create(true).truncate(true); #[cfg(unix)] { use std::os::unix::fs::OpenOptionsExt; o.mode(0o600); } let mut f = o.open(path).map_err(|e| format!("创建私钥文件 {path} 失败: {e}"))?; f.write_all(bytes).map_err(|e| format!("写私钥失败: {e}"))?; Ok(()) } fn cmd_digest(args: &[String]) -> Result<(), String> { let o = opts(args, &["--config", "--kind", "--file"])?; let cfg = config(req(&o, "--config")?)?; let kind = req(&o, "--kind")?; let obj = parse_object(kind, &read(req(&o, "--file")?)?)?; let bytes = obj.canonical_bytes(); let digest = object_digest(&cfg, obj.as_ref()).map_err(|e| e.to_string())?; println!( "{{\"kind\":\"{}\",\"hashSuite\":\"{}\",\"digest\":\"{}\",\"canonicalHex\":\"{}\",\"canonicalBytes\":{}}}", esc(kind), esc(cfg.hash_suite()), to_hex(&digest), to_hex(&bytes), bytes.len() ); Ok(()) } fn cmd_submit(args: &[String]) -> Result<(), String> { let o = opts(args, &["--config", "--outbox", "--file"])?; let cfg = config(req(&o, "--config")?)?; let receipt = Receipt::from_json(&read(req(&o, "--file")?)?).map_err(|e| e.to_string())?; let bytes = receipt.canonical_bytes(); let mut boxed = Outbox::open(req(&o, "--outbox")?).map_err(|e| e.to_string())?; let outcome = boxed .enqueue("receipt", &receipt.order_id, &receipt.decision_id, &bytes) .map_err(|e| e.to_string())?; let tag = match outcome { EnqueueOutcome::Added => "added", EnqueueOutcome::AlreadyPresent => "already_present", }; println!( "{{\"outcome\":\"{}\",\"key\":\"receipt:{}:{}\",\"pending\":{},\"hashSuite\":\"{}\"}}", tag, esc(&receipt.order_id), esc(&receipt.decision_id), boxed.pending_count(), esc(cfg.hash_suite()) ); Ok(()) } fn cmd_flush(args: &[String]) -> Result<(), String> { let o = opts(args, &["--config", "--outbox", "--transport", "--tlcp-config"])?; let cfg = config(req(&o, "--config")?)?; // ★ 传输形态必须显式给,没有默认值 —— 默认明文就是留后门。 let mode = match req(&o, "--transport")? { "stub" => TransportMode::PlaintextStub, "tlcp" => TransportMode::Tlcp, other => return Err(format!("--transport 只能是 stub|tlcp,得到 {other}")), }; let tlcp_cfg = match o.get("--tlcp-config") { Some(p) => Some(TlcpConfig::from_json(&read(p)?).map_err(|e| e.to_string())?), None => None, }; mpc_chain::require_transport(&cfg, mode, tlcp_cfg.as_ref()).map_err(|e| e.to_string())?; if mode == TransportMode::PlaintextStub { eprintln!("{PLAINTEXT_STUB_WARNING}"); } let client = HttpChainClient::new(&cfg.rpc_endpoint).map_err(|e| e.to_string())?; let mut boxed = Outbox::open(req(&o, "--outbox")?).map_err(|e| e.to_string())?; // ★ 守卫真跑一遍并把结论写进输出:桩自测能核对「国密链确实禁用 // eth_sendRawTransaction」,而不是只靠注释声称。cfg.sm_crypto // 在配置层已冻结为 true,所以正常路径下这里必然是 true。 let guomi_rejects_stub = mpc_chain::rpc::assert_submit_method_allowed( mpc_chain::rpc::METHOD_SEND_RAW_TX, cfg.sm_crypto, ) .is_err(); eprintln!( "注意: flush 的 payload 仍是链上对象规范字节,不是已签名交易(FISCO 自有交易编码 /\ TLCP 握手 FFI 未落地);此处只验证补链、幂等与传输准入契约。\ 桩方法 eth_sendRawTransaction 不是国密链入口,真链必须走 sendTransaction(4 参)。" ); let report = boxed .flush_with(|entry| { client .send_raw_transaction(&format!("0x{}", entry.payload_hex)) .map(|_| ()) }) .map_err(|e| e.to_string())?; let failed: Vec = report .failed .iter() .map(|(k, why)| format!("[\"{}\",\"{}\"]", esc(k), esc(why))) .collect(); println!( "{{\"attempted\":{},\"confirmed\":{},\"failed\":[{}],\"remaining\":{},\"method\":\"{}\",\"methodIsStub\":{},\"guomiSubmitMethod\":\"{}\",\"guomiChainRejectsStubMethod\":{},\"payload\":\"canonical-bytes-not-signed-tx\",\"transport\":\"{}\"}}", report.attempted, report.confirmed, failed.join(","), report.remaining, esc(mpc_chain::rpc::METHOD_SEND_RAW_TX), true, esc(mpc_chain::rpc::METHOD_SEND_TRANSACTION), guomi_rejects_stub, match mode { TransportMode::PlaintextStub => "plaintext-stub", TransportMode::Tlcp => "tlcp", } ); Ok(()) } fn cmd_status(args: &[String]) -> Result<(), String> { let o = opts(args, &["--outbox"])?; let boxed = Outbox::open(req(&o, "--outbox")?).map_err(|e| e.to_string())?; let items: Vec = boxed .entries() .iter() .map(|e| { format!( "{{\"key\":\"{}\",\"state\":\"{:?}\",\"attempts\":{},\"payloadBytes\":{},\"lastError\":{}}}", esc(&e.key), e.state, e.attempts, e.payload_hex.len() / 2, e.last_error .as_deref() .map(|s| format!("\"{}\"", esc(s))) .unwrap_or_else(|| String::from("null")) ) }) .collect(); println!("{{\"entries\":[{}],\"pending\":{}}}", items.join(","), boxed.pending_count()); Ok(()) } fn cmd_admit(args: &[String]) -> Result<(), String> { let o = opts(args, &["--cache", "--now", "--site", "--participants"])?; let cache = MemberCache::from_json(&read(req(&o, "--cache")?)?).map_err(|e| e.to_string())?; let now: u64 = req(&o, "--now")? .parse() .map_err(|_| String::from("--now 必须是非负整数"))?; let site = req(&o, "--site")?; let participants: Vec = req(&o, "--participants")? .split(',') .filter(|s| !s.is_empty()) .map(String::from) .collect(); chain_admit(Some(&cache), now, site, &participants).map_err(|e| e.to_string())?; println!("{{\"decision\":\"allow\",\"site\":\"{}\",\"participants\":{}}}", esc(site), participants.len()); Ok(()) } fn cmd_keygen(args: &[String]) -> Result<(), String> { let o = opts(args, &["--out", "--pub-out"])?; let s = OpenSslSoftwareSigner::generate_for_development().map_err(|e| e.to_string())?; let priv_pem = s.private_pem_pkcs8().map_err(|e| e.to_string())?; let pub_pem = s.public_pem().map_err(|e| e.to_string())?; write_private(req(&o, "--out")?, &priv_pem)?; fs::write(req(&o, "--pub-out")?, &pub_pem) .map_err(|e| format!("写公钥失败: {e}"))?; eprintln!("{SOFTWARE_DEV_WARNING}"); println!( "{{\"algorithm\":\"SM2\",\"signerProfile\":\"SoftwareDev\",\"pubkeyHex\":\"{}\",\"distid\":\"{}\",\"distidFingerprint\":\"{}\",\"warning\":\"{}\"}}", to_hex(s.public_key()), String::from_utf8_lossy(SM2_DISTID), to_hex(&distid_fingerprint()), esc(SOFTWARE_DEV_WARNING) ); Ok(()) } fn cmd_sign(args: &[String]) -> Result<(), String> { let o = opts(args, &["--key", "--file", "--policy"])?; let policy = match req(&o, "--policy")? { "production-module" => SignerPolicy::ProductionModule, "development-software" => SignerPolicy::DevelopmentSoftware, other => return Err(format!("--policy 只能是 production-module|development-software,得到 {other}")), }; let pem = fs::read(req(&o, "--key")?).map_err(|e| format!("读私钥失败: {e}"))?; let s = OpenSslSoftwareSigner::from_private_pem(&pem).map_err(|e| e.to_string())?; require_self_test(&s, policy).map_err(|e| e.to_string())?; let msg = fs::read(req(&o, "--file")?).map_err(|e| format!("读待签字节失败: {e}"))?; let raw = s.sign(&msg).map_err(|e| e.to_string())?; let arr: [u8; 64] = raw .as_slice() .try_into() .map_err(|_| String::from("签名不是 64 字节"))?; let der = raw_rs_to_der(&arr).map_err(|e| e.to_string())?; let st = s.self_test().map_err(|e| e.to_string())?; if policy == SignerPolicy::DevelopmentSoftware { eprintln!("{SOFTWARE_DEV_WARNING}"); } println!( "{{\"algorithm\":\"SM2\",\"signerProfile\":\"{}\",\"policy\":\"{}\",\"rawSigHex\":\"{}\",\"derSigHex\":\"{}\",\"pubkeyHex\":\"{}\",\"distid\":\"{}\",\"distidFingerprint\":\"{}\",\"selfTest\":{{\"providerLoaded\":{},\"privateKeyUnexportable\":{},\"katOk\":{}}}}}", match s.security_profile() { SignerSecurityProfile::HardwareModule => "HardwareModule", SignerSecurityProfile::SoftwareDev => "SoftwareDev", }, match policy { SignerPolicy::ProductionModule => "production-module", SignerPolicy::DevelopmentSoftware => "development-software", }, to_hex(&raw), to_hex(&der), to_hex(s.public_key()), String::from_utf8_lossy(SM2_DISTID), to_hex(&distid_fingerprint()), st.provider_loaded, st.private_key_unexportable, st.kat_ok ); Ok(()) } fn cmd_align(args: &[String]) -> Result<(), String> { let o = opts(args, &["--chain-verifier-distid", "--csv-distid"])?; let fallback = String::from_utf8_lossy(SM2_DISTID).to_string(); let cv = o.get("--chain-verifier-distid").map(String::as_str).unwrap_or(&fallback); let csv = o.get("--csv-distid").map(String::as_str).unwrap_or(&fallback); let decls: Vec<(DistidConsumer, &[u8])> = vec![ (DistidConsumer::ChainSigner, SM2_DISTID), (DistidConsumer::ChainVerifier, cv.as_bytes()), (DistidConsumer::AttestationCsvSm2, csv.as_bytes()), ]; let fp = aligned_distid(&decls).map_err(|e| e.to_string())?; println!( "{{\"aligned\":true,\"distid\":\"{}\",\"fingerprint\":\"{}\",\"consumers\":[\"chain_signer\",\"chain_verifier\",\"attestation_csv_sm2\"]}}", esc(&fallback), to_hex(&fp) ); Ok(()) } fn cmd_tlcp(args: &[String]) -> Result<(), String> { let o = opts(args, &["--file"])?; let p = probe_tlcp_environment(); let (config_ok, detail) = match o.get("--file") { Some(path) => match TlcpConfig::from_json(&read(path)?) { Ok(cfg) => match mpc_chain::tlcp::require_tlcp_transport(&cfg) { Ok(r) => (true, format!("{r:?}")), Err(e) => (false, e.to_string()), }, Err(e) => (false, e.to_string()), }, None => (false, String::from("未提供 TLCP 双证书配置")), }; let readiness = if p.backend == TlcpBackend::None { TlcpReadiness::MissingEnvironment } else { // ★ 环境齐备(含 GmSSL 本机握手已跑通)也只到 NeedsFfi: // Rust 侧把 JSON-RPC 经 TLCP 发到 bcos-rpc 的通道还没接。 TlcpReadiness::NeedsFfi }; let ready = readiness == TlcpReadiness::Ready && config_ok; let reason = match p.backend { TlcpBackend::None => format!( "本机既无 OpenSSL/Tongsuo TLCP 套件({}),也无可用 GmSSL;\ 需要 Tongsuo ≥ 8.4 或 GmSSL ≥ 3.2;拒绝以明文/标准 TLS 冒充国密通道", p.openssl_version ), TlcpBackend::GmSSL => String::from( "GmSSL TLCP 本机握手已可用,但 Rust 侧把 JSON-RPC 经 TLCP 发到 bcos-rpc 的\ 进程通道 / FFI 未落地,且未验证 bcos-rpc 是否启用 TLCP;拒绝宣称能发真交易", ), TlcpBackend::Tongsuo => String::from( "Tongsuo TLCP 环境齐备但 Rust 侧 FFI 握手未落地,拒绝宣称能发真交易", ), }; println!( "{{\"ready\":{},\"readiness\":\"{:?}\",\"configOk\":{},\"backend\":\"{:?}\",\"opensslVersion\":\"{}\",\"tlcpCipherAvailable\":{},\"tongsuoLib\":{},\"gmsslAvailable\":{},\"gmsslVersion\":{},\"gmsslTlcpCommands\":{},\"detail\":\"{}\",\"reason\":\"{}\"}}", ready, readiness, config_ok, p.backend, esc(&p.openssl_version), p.tlcp_cipher_available, p.tongsuo_lib .as_deref() .map(|s| format!("\"{}\"", esc(s))) .unwrap_or_else(|| String::from("null")), p.gmssl_version.is_some(), p.gmssl_version .as_deref() .map(|s| format!("\"{}\"", esc(s))) .unwrap_or_else(|| String::from("null")), p.gmssl_tlcp_commands, esc(&detail), esc(&reason) ); Ok(()) } fn cmd_governance(args: &[String]) -> Result<(), String> { let o = opts(args, &["--config", "--kind", "--file"])?; let cfg = config(req(&o, "--config")?)?; governance_boundary().map_err(|e| e.to_string())?; let text = read(req(&o, "--file")?)?; let kind = req(&o, "--kind")?; let obj: Box = match kind { "hard-rule" => Box::new(HardRuleSet::from_json(&text).map_err(|e| e.to_string())?), "opa-bundle" => Box::new(OpaPolicyBundle::from_json(&text).map_err(|e| e.to_string())?), other => return Err(format!("--kind 只能是 hard-rule|opa-bundle,得到 {other}")), }; let bytes = obj.canonical_bytes(); let digest = object_digest(&cfg, obj.as_ref()).map_err(|e| e.to_string())?; println!( "{{\"kind\":\"{}\",\"hashSuite\":\"{}\",\"digest\":\"{}\",\"canonicalHex\":\"{}\",\"canonicalBytes\":{},\"target\":\"{}\"}}", esc(kind), esc(cfg.hash_suite()), to_hex(&digest), to_hex(&bytes), bytes.len(), if kind == "hard-rule" { "合约" } else { "OPA(不上链)" } ); Ok(()) }