Skip to content

Commit f41a8b5

Browse files
committed
feat(cli): add --chain flag to verify and status commands
1 parent 22e95a2 commit f41a8b5

3 files changed

Lines changed: 317 additions & 5 deletions

File tree

‎crates/chain/tests/integration.rs‎

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,137 @@ async fn submit_to_different_nodes() {
240240
}
241241
}
242242

243+
/// E2E: simulates CLI backup → RegisterFile → propose → get_file → VerifyIntegrity
244+
#[tokio::test]
245+
async fn e2e_cli_backup_verify_flow() {
246+
let net = TestNetwork::spawn(3).await;
247+
let client = reqwest::Client::new();
248+
let (sk, pk) = &net.keys[0];
249+
let base = &net.urls[0];
250+
251+
// 1. Simulate CLI backup: create RegisterFile tx
252+
let merkle_root = [0xDE; 32];
253+
let file_count = 3u32;
254+
let encrypted_size = 10240u64;
255+
let sig = sk.sign(&merkle_root);
256+
let tx = serde_json::json!({
257+
"RegisterFile": {
258+
"merkle_root": merkle_root,
259+
"file_count": file_count,
260+
"encrypted_size": encrypted_size,
261+
"owner_pk": *pk,
262+
"signature": sig.to_bytes().to_vec(),
263+
}
264+
});
265+
let tx_json = tx.to_string();
266+
267+
// 2. Submit via RPC (like CLI --chain does)
268+
let resp = client
269+
.post(format!("{base}/submit_tx"))
270+
.json(&rpc::SubmitTxRequest { tx_json })
271+
.send()
272+
.await
273+
.unwrap();
274+
assert_eq!(resp.status(), 200);
275+
let submit: SubmitTxResponse = resp.json().await.unwrap();
276+
assert!(!submit.tx_hash.is_empty());
277+
278+
// 3. Verify pending
279+
let status: StatusResponse = client
280+
.get(format!("{base}/status"))
281+
.send()
282+
.await
283+
.unwrap()
284+
.json()
285+
.await
286+
.unwrap();
287+
assert_eq!(status.pending_txs, 1);
288+
289+
// 4. Propose + broadcast
290+
net.propose_and_broadcast();
291+
292+
// 5. Verify committed
293+
let status: StatusResponse = client
294+
.get(format!("{base}/status"))
295+
.send()
296+
.await
297+
.unwrap()
298+
.json()
299+
.await
300+
.unwrap();
301+
assert_eq!(status.height, 1);
302+
assert_eq!(status.file_count, 1);
303+
assert_eq!(status.pending_txs, 0);
304+
305+
// 6. Query file (like CLI status --chain does)
306+
let file_resp = client
307+
.post(format!("{base}/get_file"))
308+
.json(&rpc::GetFileRequest {
309+
merkle_root: hex::encode(merkle_root),
310+
})
311+
.send()
312+
.await
313+
.unwrap();
314+
assert_eq!(file_resp.status(), 200);
315+
let file: rpc::FileResponse = file_resp.json().await.unwrap();
316+
assert_eq!(file.file_count, file_count);
317+
assert_eq!(file.encrypted_size, encrypted_size);
318+
assert_eq!(file.owner_pk, hex::encode(pk));
319+
assert_eq!(file.registered_at, 1);
320+
assert_eq!(file.verification_count, 0);
321+
322+
// 7. Simulate CLI verify --chain: submit VerifyIntegrity tx
323+
let verify_sig = sk.sign(&merkle_root);
324+
let verify_tx = serde_json::json!({
325+
"VerifyIntegrity": {
326+
"merkle_root": merkle_root,
327+
"verifier_pk": *pk,
328+
"signature": verify_sig.to_bytes().to_vec(),
329+
}
330+
});
331+
let verify_tx_json = verify_tx.to_string();
332+
333+
let resp = client
334+
.post(format!("{base}/submit_tx"))
335+
.json(&rpc::SubmitTxRequest {
336+
tx_json: verify_tx_json,
337+
})
338+
.send()
339+
.await
340+
.unwrap();
341+
assert_eq!(resp.status(), 200);
342+
343+
// 8. Propose + broadcast again
344+
net.propose_and_broadcast();
345+
346+
// 9. Verify verification_count increased
347+
let file_resp = client
348+
.post(format!("{base}/get_file"))
349+
.json(&rpc::GetFileRequest {
350+
merkle_root: hex::encode(merkle_root),
351+
})
352+
.send()
353+
.await
354+
.unwrap();
355+
assert_eq!(file_resp.status(), 200);
356+
let file: rpc::FileResponse = file_resp.json().await.unwrap();
357+
assert_eq!(file.verification_count, 1);
358+
359+
// 10. Final status: height 2, 1 file, 0 pending
360+
let status: StatusResponse = client
361+
.get(format!("{base}/status"))
362+
.send()
363+
.await
364+
.unwrap()
365+
.json()
366+
.await
367+
.unwrap();
368+
assert_eq!(status.height, 2);
369+
assert_eq!(status.file_count, 1);
370+
assert_eq!(status.pending_txs, 0);
371+
assert_eq!(status.blocks_committed, 2);
372+
}
373+
243374
#[tokio::test]
244375
async fn rejected_block_does_not_corrupt_state() {
245376
let net = TestNetwork::spawn(3).await;

‎crates/cli/src/main.rs‎

Lines changed: 186 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,16 @@ enum Commands {
4848
/// Backup ID or path to manifest file
4949
#[arg()]
5050
backup: String,
51+
/// Submit VerifyIntegrity attestation to chain (e.g., --chain http://localhost:3030)
52+
#[arg(long)]
53+
chain: Option<String>,
5154
},
5255
/// Show vault status
53-
Status,
56+
Status {
57+
/// Query chain node status (e.g., --chain http://localhost:3030)
58+
#[arg(long)]
59+
chain: Option<String>,
60+
},
5461
}
5562

5663
#[tokio::main]
@@ -72,8 +79,8 @@ async fn main() {
7279
chain,
7380
} => cmd_backup(paths, local, chain).await,
7481
Commands::Restore { backup, output } => cmd_restore(backup, output).await,
75-
Commands::Verify { backup } => cmd_verify(backup).await,
76-
Commands::Status => cmd_status(),
82+
Commands::Verify { backup, chain } => cmd_verify(backup, chain).await,
83+
Commands::Status { chain } => cmd_status(chain).await,
7784
}
7885
}
7986

@@ -767,7 +774,7 @@ async fn fetch_bundle(
767774
None
768775
}
769776

770-
async fn cmd_verify(backup: String) {
777+
async fn cmd_verify(backup: String, chain_url: Option<String>) {
771778
// 1. Load manifest
772779
let manifest_path = resolve_manifest_path(&backup);
773780
let manifest_json = std::fs::read_to_string(&manifest_path).unwrap_or_else(|e| {
@@ -908,6 +915,82 @@ async fn cmd_verify(backup: String) {
908915
println!("Verification FAILED ({checks_failed} failed, {checks_passed} passed).");
909916
std::process::exit(1);
910917
}
918+
919+
// Submit VerifyIntegrity attestation to chain (only if all checks passed)
920+
if let Some(chain_url) = chain_url {
921+
if all_passed {
922+
attest_on_chain(&chain_url, manifest.merkle_root).await;
923+
} else {
924+
eprintln!("Skipping chain attestation — verification failed.");
925+
}
926+
}
927+
}
928+
929+
/// Submit a VerifyIntegrity attestation to the chain.
930+
async fn attest_on_chain(chain_url: &str, merkle_root: [u8; 32]) {
931+
use ed25519_dalek::{Signer, SigningKey};
932+
933+
// Load and unlock keys for signing
934+
let store = match keys::load_key_store() {
935+
Ok(s) => s,
936+
Err(e) => {
937+
eprintln!("Chain attestation: cannot load keystore ({e})");
938+
return;
939+
}
940+
};
941+
942+
let passphrase = rpassword::prompt_password("Enter passphrase for chain attestation: ")
943+
.expect("Failed to read passphrase");
944+
945+
let unlocked = match keys::unlock_all_keys(passphrase.as_bytes(), &store) {
946+
Ok(u) => u,
947+
Err(e) => {
948+
eprintln!("Chain attestation: wrong passphrase ({e})");
949+
return;
950+
}
951+
};
952+
953+
println!();
954+
println!("Submitting VerifyIntegrity attestation ({chain_url})...");
955+
956+
let signing_key = SigningKey::from_bytes(&unlocked.ed25519_sk);
957+
let signature = signing_key.sign(&merkle_root);
958+
959+
let tx = serde_json::json!({
960+
"VerifyIntegrity": {
961+
"merkle_root": merkle_root,
962+
"verifier_pk": unlocked.ed25519_pk,
963+
"signature": signature.to_bytes().to_vec(),
964+
}
965+
});
966+
let tx_json = tx.to_string();
967+
968+
let client = reqwest::Client::new();
969+
let url = format!("{}/submit_tx", chain_url.trim_end_matches('/'));
970+
let body = serde_json::json!({ "tx_json": tx_json });
971+
972+
match client.post(&url).json(&body).send().await {
973+
Ok(resp) => {
974+
let status = resp.status();
975+
let body_text = resp.text().await.unwrap_or_default();
976+
977+
if status.is_success() {
978+
if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&body_text) {
979+
let tx_hash = parsed["tx_hash"].as_str().unwrap_or("?");
980+
println!(" Chain attestation: SUCCESS");
981+
println!(" tx_hash: {tx_hash}");
982+
} else {
983+
println!(" Chain attestation: SUCCESS");
984+
}
985+
} else {
986+
eprintln!(" Chain attestation: FAILED (HTTP {status})");
987+
eprintln!(" Response: {body_text}");
988+
}
989+
}
990+
Err(e) => {
991+
eprintln!(" Chain attestation: FAILED (connection error: {e})");
992+
}
993+
}
911994
}
912995

913996
/// Check if a file exists in any of its storage locations.
@@ -935,7 +1018,7 @@ async fn check_file_exists(
9351018
false
9361019
}
9371020

938-
fn cmd_status() {
1021+
async fn cmd_status(chain_url: Option<String>) {
9391022
println!("zk-vault status");
9401023
println!("===============");
9411024

@@ -1043,6 +1126,104 @@ fn cmd_status() {
10431126
} else {
10441127
println!("Backups: none");
10451128
}
1129+
1130+
// 5. Chain status (if --chain was specified)
1131+
if let Some(chain_url) = chain_url {
1132+
query_chain_status(&chain_url).await;
1133+
}
1134+
}
1135+
1136+
/// Query chain node status and display it.
1137+
async fn query_chain_status(chain_url: &str) {
1138+
println!();
1139+
println!("Chain: {chain_url}");
1140+
1141+
let client = reqwest::Client::new();
1142+
let base = chain_url.trim_end_matches('/');
1143+
1144+
// GET /status
1145+
match client.get(format!("{base}/status")).send().await {
1146+
Ok(resp) if resp.status().is_success() => {
1147+
let body = resp.text().await.unwrap_or_default();
1148+
if let Ok(status) = serde_json::from_str::<serde_json::Value>(&body) {
1149+
println!(" Height: {}", status["height"]);
1150+
println!(" Files: {}", status["file_count"]);
1151+
println!(" Validators: {}", status["validator_count"]);
1152+
println!(" Pending txs: {}", status["pending_txs"]);
1153+
println!(" Committed: {}", status["blocks_committed"]);
1154+
println!(
1155+
" State root: {}",
1156+
status["state_root"].as_str().unwrap_or("?")
1157+
);
1158+
}
1159+
}
1160+
Ok(resp) => {
1161+
eprintln!(" Chain status: HTTP {}", resp.status());
1162+
}
1163+
Err(e) => {
1164+
eprintln!(" Chain unreachable: {e}");
1165+
}
1166+
}
1167+
1168+
// Cross-reference local manifests with chain
1169+
let manifests_dir = keys::vault_dir().join("manifests");
1170+
if !manifests_dir.exists() {
1171+
return;
1172+
}
1173+
1174+
let manifest_files: Vec<_> = std::fs::read_dir(&manifests_dir)
1175+
.into_iter()
1176+
.flatten()
1177+
.flatten()
1178+
.filter(|e| e.path().extension().is_some_and(|ext| ext == "json"))
1179+
.collect();
1180+
1181+
if manifest_files.is_empty() {
1182+
return;
1183+
}
1184+
1185+
println!();
1186+
println!("On-chain status of local backups:");
1187+
1188+
for entry in &manifest_files {
1189+
let json = match std::fs::read_to_string(entry.path()) {
1190+
Ok(j) => j,
1191+
Err(_) => continue,
1192+
};
1193+
let manifest: zk_vault_core::manifest::BackupManifest = match serde_json::from_str(&json) {
1194+
Ok(m) => m,
1195+
Err(_) => continue,
1196+
};
1197+
1198+
let merkle_hex = hex::encode(manifest.merkle_root);
1199+
let short_id = &manifest.backup_id.to_string()[..8];
1200+
1201+
// Query chain for this file
1202+
let req = serde_json::json!({ "merkle_root": merkle_hex });
1203+
match client
1204+
.post(format!("{base}/get_file"))
1205+
.json(&req)
1206+
.send()
1207+
.await
1208+
{
1209+
Ok(resp) if resp.status().is_success() => {
1210+
let body = resp.text().await.unwrap_or_default();
1211+
if let Ok(file) = serde_json::from_str::<serde_json::Value>(&body) {
1212+
let verifications = file["verification_count"].as_u64().unwrap_or(0);
1213+
let registered_at = file["registered_at"].as_u64().unwrap_or(0);
1214+
println!(
1215+
" {short_id} | registered (height {registered_at}, {verifications} verification(s))"
1216+
);
1217+
}
1218+
}
1219+
Ok(_) => {
1220+
println!(" {short_id} | not registered");
1221+
}
1222+
Err(_) => {
1223+
println!(" {short_id} | query failed");
1224+
}
1225+
}
1226+
}
10461227
}
10471228

10481229
/// BLAKE3 fingerprint of a public key (first 8 bytes, hex-encoded).
File renamed without changes.

0 commit comments

Comments
 (0)