use clap::{Parser, Subcommand};
use sha2::{Digest, Sha256};
use serde_json::json;
use hop_core::{CompanionMatrix, Field, StreamGenerator};
use hop_actions::Action;
use hop_channels::Channel;
use hop_channels::store_fs::FsStore;
use hop_relay::apply_bundle; use hop_channels::proj::row0_of_poly;
#[cfg(feature="torsor_masking")]
use hop_channels::mask::apply_twist_row;
#[derive(Parser)]
#[command(name = "hop", version, about = "Hop-Corr CLI")]
struct Cli {
#[command(subcommand)]
cmd: Cmd
}
#[derive(Subcommand)]
enum Cmd {
Create { #[arg(long, value_delimiter = ',')] coeffs: Vec<u64> },
Send { #[arg(long, value_delimiter = ',')] g: Vec<u64>, #[arg(long, default_value_t=0)] nonce: u64 },
Tail { #[arg(long, default_value_t=10)] n: usize },
Save { #[arg(long)] id: String, #[arg(long, default_value = "./data")] dir: String },
Apply {
#[arg(long)] id: String,
#[arg(long, value_delimiter = ',')] g: Vec<u64>,
#[arg(long, default_value_t=0)] nonce: u64,
#[arg(long, default_value = "./data")] dir: String
},
Load { #[arg(long)] id: String, #[arg(long, default_value = "./data")] dir: String },
Replay { #[arg(long)] id: String, #[arg(long, default_value = "./data")] dir: String },
Obdemo {
#[arg(long, value_delimiter = ',')]
coeffs: Vec<u64>,
#[arg(long = "subs-g", value_delimiter = ',')]
subs_g: Vec<u64>,
#[arg(long, default_value = "1")]
batch: String,
#[arg(long, default_value_t = 0)]
nonce_start: u64,
#[arg(long, default_value_t = 3)]
mask_degree: usize,
#[arg(long, default_value_t = 7)]
mask_nonce: u64,
},
ObdemoPersist {
#[arg(long, value_delimiter = ',')] coeffs: Vec<u64>,
#[arg(long = "subs-g", value_delimiter = ',')] subs_g: Vec<u64>,
#[arg(long, default_value = "1")] batch: String,
#[arg(long, default_value_t = 0)] nonce_start: u64,
#[arg(long, default_value = "./data")] dir: String,
#[arg(long, default_value = "0000000000000000000000000000000000000000000000000000000000000000")]
id: String,
},
Relay {
#[arg(long, default_value = "127.0.0.1:8787")]
listen: String
},
SendBundle {
#[arg(long, default_value = "http://127.0.0.1:8787")]
addr: String,
#[arg(long, value_delimiter = ',')]
coeffs: Vec<u64>,
#[arg(long)]
id: String,
#[arg(long, default_value = "./data")]
dir: String,
#[arg(long, default_value = "1")]
batch: String,
#[arg(long, default_value_t=0)]
nonce_start: u64,
#[arg(long = "subs-g", value_delimiter = ',', required = false)]
subs_g: Option<Vec<u64>>,
#[arg(long, required = false)]
mask_degree: Option<usize>,
#[arg(long, required = false)]
mask_nonce: Option<u64>,
#[arg(long, default_value_t=false)]
json: bool,
},
GetState {
#[arg(long, default_value = "http://127.0.0.1:8787")]
addr: String,
#[arg(long)]
id: String,
#[arg(long, default_value = "./data")]
dir: String,
#[arg(long = "subs-g", value_delimiter = ',', required = false)]
subs_g: Option<Vec<u64>>,
#[arg(long, required = false)]
mask_degree: Option<usize>,
#[arg(long, required = false)]
mask_nonce: Option<u64>,
#[arg(long, default_value_t=false)]
json: bool,
},
VaultNew {
#[arg(long, default_value = "http://127.0.0.1:8787")]
addr: String,
#[arg(long)]
id: String,
#[arg(long, default_value = "./data")]
dir: String,
#[arg(long, value_delimiter = ',')]
coeffs: Vec<u64>,
#[arg(long, default_value_t=false)]
nonce_monotonic: bool,
#[arg(long)]
min_nonce: Option<u64>,
#[arg(long = "proj-whitelist", value_delimiter = ',', required = false)]
projection_one_g: Option<Vec<u64>>,
#[arg(long, default_value_t=false)]
json: bool,
},
VaultAppend {
#[arg(long, default_value = "http://127.0.0.1:8787")]
addr: String,
#[arg(long)]
id: String,
#[arg(long, default_value = "./data")]
dir: String,
#[arg(long, default_value = "1")]
batch: String,
#[arg(long, default_value_t=0)]
nonce_start: u64,
#[arg(long, default_value_t=false)]
json: bool,
},
VaultGet {
#[arg(long, default_value = "http://127.0.0.1:8787")]
addr: String,
#[arg(long)]
id: String,
#[arg(long, default_value = "./data")]
dir: String,
#[arg(long = "subs-g", value_delimiter = ',', required = false)]
subs_g: Option<Vec<u64>>,
#[arg(long, required = false)]
mask_degree: Option<usize>,
#[arg(long, required = false)]
mask_nonce: Option<u64>,
#[arg(long, default_value_t=false)]
json: bool,
},
VaultProve {
#[arg(long, default_value = "http://127.0.0.1:8787")]
addr: String,
#[arg(long)]
id: String,
#[arg(long, default_value = "./data")]
dir: String,
#[arg(long)]
since_height: Option<u64>,
#[arg(long, default_value_t=false)]
json: bool,
},
VaultVerify {
#[arg(long)]
id: String,
#[arg(long, default_value = "./data")]
dir: String,
#[arg(long)]
transcript: String,
#[arg(long, value_delimiter = ',', required = false)]
coeffs: Option<Vec<u64>>,
#[arg(long)]
expect_height: Option<u64>,
#[arg(long)]
expect_hash: Option<String>,
},
ReceiptVerify {
#[arg(long)] pubkey: String, #[arg(long)] id: String, #[arg(long)] height: u64,
#[arg(long, value_name="HEX")] state_hash: String,
#[arg(long, value_name="B64")] transcript_hash: String,
#[arg(long, value_name="B64")] sig: String,
},
}
fn parse_id_hex64(id_hex: &str) -> [u8;32] {
let mut id = [0u8;32];
let bytes = hex::decode(id_hex).unwrap_or_default();
for (i,b) in bytes.iter().take(32).enumerate() { id[i] = *b; }
id
}
fn hash_state(fields: &[Field]) -> String {
let mut h = Sha256::new();
for f in fields {
h.update(&f.v.to_le_bytes());
}
format!("{:x}", h.finalize())
}
fn parse_batch(batch: &str) -> Vec<Vec<u64>> {
batch
.split(';')
.filter(|s| !s.trim().is_empty())
.map(|seg| seg.split(',').filter(|t| !t.is_empty())
.map(|t| t.trim().parse::<u64>().expect("u64"))
.collect::<Vec<u64>>())
.collect::<Vec<_>>()
}
fn main() {
let cli = Cli::parse();
match cli.cmd {
Cmd::Create { coeffs } => {
let c = CompanionMatrix::from_coeffs(&coeffs);
let state = vec![Field::new(1), Field::new(0), Field::new(0)][..c.k.min(3)].to_vec();
let mut padded = vec![Field::zero(); c.k];
for (i, f) in state.into_iter().enumerate() { padded[i] = f; }
let ch = Channel::open(c, padded, [0u8;32]);
println!("Created channel with k={}", ch.k);
}
Cmd::Send { g, nonce } => {
let c = CompanionMatrix::from_coeffs(&[4,3,2]); let mut ch = Channel::open(c, vec![Field::new(1), Field::new(0), Field::new(0)], [0u8;32]);
let a = Action { g_coeffs: g, nonce, mask_row0: None };
let _ = ch.apply(&a);
println!("Applied action; state[0]={:?}", ch.state.get(0).map(|f| f.v));
}
Cmd::Tail { n } => {
let c = CompanionMatrix::from_coeffs(&[4,3,2]);
let k = c.k;
let mut t = vec![vec![Field::zero(); k]; k];
let mut row0 = vec![Field::zero(); k];
if k >= 1 { row0[0] = Field::new(1); }
if k >= 2 { row0[1] = Field::new(2); }
t[0] = row0;
let mut state = vec![Field::zero(); k];
state[0] = Field::new(1);
let mut sg = StreamGenerator::new(c, t, state);
for _ in 0..n { println!("{:?}", sg.step().v); }
}
Cmd::Save { id, dir } => {
let id = parse_id_hex64(&id);
let store = FsStore::new(&dir).expect("store");
let c = CompanionMatrix::from_coeffs(&[4,3,2]);
let mut init = vec![Field::zero(); c.k]; init[0] = Field::new(1);
let ch = Channel::open(c, init, id).with_store(Box::new(store));
ch.save_now().expect("save");
println!("Saved snapshot for id {}", hex::encode(id));
}
Cmd::Apply { id, g, nonce, dir } => {
let id = parse_id_hex64(&id);
let store = FsStore::new(&dir).expect("store");
let ch0 = Channel::restore(id, Box::new(store)).unwrap_or_else(|_| {
let c = CompanionMatrix::from_coeffs(&[4,3,2]);
let mut init = vec![Field::zero(); c.k]; init[0] = Field::new(1);
Channel::open(c, init, id)
});
let mut ch = ch0.with_store(Box::new(FsStore::new(&dir).unwrap()));
let a = Action { g_coeffs: g, nonce, mask_row0: None };
ch.apply(&a).expect("apply");
let _ = ch.save_now();
println!("Applied; height={}", ch.height);
}
Cmd::Load { id, dir } => {
let id = parse_id_hex64(&id);
let store = FsStore::new(&dir).expect("store");
let ch = Channel::restore(id, Box::new(store)).expect("restore");
println!("Loaded channel k={}, height={}", ch.k, ch.height);
}
Cmd::Replay { id, dir } => {
let id = parse_id_hex64(&id);
let store = FsStore::new(&dir).expect("store");
let ch = Channel::restore(id, Box::new(store)).expect("restore");
println!("Replayed to height={}", ch.height);
}
Cmd::Obdemo { coeffs, subs_g, batch, nonce_start, mask_degree, mask_nonce } => {
let _ = (&mask_degree, &mask_nonce); let c1 = CompanionMatrix::from_coeffs(&coeffs);
let c2 = CompanionMatrix::from_coeffs(&coeffs);
let k = c1.k;
let mut s = vec![Field::zero(); k]; s[0] = Field::new(1);
let mut ch_a = Channel::open(c1, s.clone(), [0xAA;32]);
let mut ch_b = Channel::open(c2, s, [0xBB;32]);
let polys = parse_batch(&batch);
let mut actions_a = Vec::with_capacity(polys.len());
let mut actions_b = Vec::with_capacity(polys.len());
for (i, g) in polys.iter().enumerate() {
let a = Action { g_coeffs: g.clone(), nonce: nonce_start + (i as u64), mask_row0: None };
actions_a.push(a.clone());
actions_b.push(a);
}
actions_b.rotate_left(1);
apply_bundle(&mut ch_a, &actions_a).expect("apply A");
apply_bundle(&mut ch_b, &actions_b).expect("apply B");
let hash_a = hash_state(&ch_a.state);
let hash_b = hash_state(&ch_b.state);
let converge = hash_a == hash_b;
let row = row0_of_poly(&ch_a.c, &subs_g);
let mut proj_unmasked = Field::zero();
for (w,x) in row.iter().zip(ch_a.state.iter()) { proj_unmasked = proj_unmasked + (*w * *x); }
#[cfg(feature="torsor_masking")]
let proj_masked = {
let row_twisted = apply_twist_row(&ch_a.c, &row, mask_nonce, mask_degree);
let mut acc = Field::zero();
for (w,x) in row_twisted.iter().zip(ch_a.state.iter()) { acc = acc + (*w * *x); }
acc
};
#[cfg(feature="torsor_masking")]
let mut out = json!({
"k": k, "coeffs": coeffs, "subs_g": subs_g, "actions": polys,
"state_hash": hash_a, "converged_same_state": converge,
"proj_unmasked": proj_unmasked.v,
});
#[cfg(not(feature="torsor_masking"))]
let out = json!({
"k": k, "coeffs": coeffs, "subs_g": subs_g, "actions": polys,
"state_hash": hash_a, "converged_same_state": converge,
"proj_unmasked": proj_unmasked.v,
});
#[cfg(feature="torsor_masking")]
{
let obj = out.as_object_mut().unwrap();
obj.insert("mask_degree".into(), json!(mask_degree));
obj.insert("mask_nonce".into(), json!(mask_nonce));
obj.insert("proj_masked".into(), json!(proj_masked.v));
}
println!("{}", serde_json::to_string_pretty(&out).unwrap());
}
Cmd::ObdemoPersist { coeffs, subs_g, batch, nonce_start, dir, id } => {
let c = CompanionMatrix::from_coeffs(&coeffs);
let k = c.k;
let mut s = vec![Field::zero(); k]; s[0] = Field::new(1);
let idb = parse_id_hex64(&id);
let mut ch = Channel::open(c, s, idb);
let polys = parse_batch(&batch);
let actions: Vec<Action> = polys.iter().enumerate()
.map(|(i,g)| Action { g_coeffs: g.clone(), nonce: nonce_start + (i as u64), mask_row0: None })
.collect();
apply_bundle(&mut ch, &actions).expect("apply bundle");
let hash_before = hash_state(&ch.state);
let store = FsStore::new(&dir).expect("store");
let ch_saved = ch.with_store(Box::new(store));
ch_saved.save_now().expect("save");
let store2 = FsStore::new(&dir).expect("store");
let ch2 = Channel::restore(idb, Box::new(store2)).expect("restore");
let hash_after = hash_state(&ch2.state);
let row = row0_of_poly(&ch2.c, &subs_g);
let mut proj_unmasked = Field::zero();
for (w, x) in row.iter().zip(ch2.state.iter()) {
proj_unmasked = proj_unmasked + (*w * *x);
}
println!("{}", serde_json::to_string_pretty(&json!({
"k": k, "coeffs": coeffs, "subs_g": subs_g, "actions": polys,
"state_hash_before": hash_before, "state_hash_after": hash_after,
"hash_equal": hash_before == hash_after, "proj_unmasked": proj_unmasked.v,
"dir": dir, "id": id,
})).unwrap());
}
Cmd::Relay { listen } => {
let rt = tokio::runtime::Runtime::new().expect("rt");
rt.block_on(async move {
hop_relay::net::serve(&listen).await.expect("serve");
});
}
Cmd::SendBundle { addr, coeffs, id, dir, batch, nonce_start, subs_g, mask_degree, mask_nonce, json } => {
let polys = parse_batch(&batch);
#[derive(serde::Serialize)]
struct ActionOut { g: Vec<u64>, nonce: u64 }
#[derive(serde::Serialize)]
struct BundleOut {
id: String, dir: String, coeffs: Vec<u64>, actions: Vec<ActionOut>,
#[serde(skip_serializing_if = "Option::is_none")] subs_g: Option<Vec<u64>>,
#[serde(skip_serializing_if = "Option::is_none")] mask_degree: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")] mask_nonce: Option<u64>,
}
let actions: Vec<ActionOut> = polys.iter().enumerate()
.map(|(i,g)| ActionOut { g: g.clone(), nonce: nonce_start + i as u64 })
.collect();
let body = BundleOut { id, dir, coeffs, actions, subs_g, mask_degree, mask_nonce };
let client = reqwest::blocking::Client::new();
let url = format!("{}/bundle", addr.trim_end_matches('/'));
let resp = client.post(&url).json(&body).send();
match resp {
Ok(r) if r.status().is_success() => {
let txt = r.text().unwrap_or_else(|_| "{}".into());
if json {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&txt) {
println!("{}", serde_json::to_string_pretty(&val).unwrap());
} else { println!("{}", txt); }
} else { println!("{}", txt); }
}
Ok(r) => { eprintln!("HTTP error: {}", r.status()); std::process::exit(1); }
Err(e) => { eprintln!("Request failed: {}", e); std::process::exit(1); }
}
}
Cmd::GetState { addr, id, dir, subs_g, mask_degree, mask_nonce, json } => {
#[derive(serde::Serialize)]
struct Query {
id: String, dir: String,
#[serde(skip_serializing_if = "Option::is_none")] subs_g: Option<Vec<u64>>,
#[serde(skip_serializing_if = "Option::is_none")] mask_degree: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")] mask_nonce: Option<u64>,
}
let client = reqwest::blocking::Client::new();
let url = format!("{}/state", addr.trim_end_matches('/'));
let resp = client.post(&url).json(&Query { id, dir, subs_g, mask_degree, mask_nonce }).send();
match resp {
Ok(r) if r.status().is_success() => {
let txt = r.text().unwrap_or_else(|_| "{}".into());
if json {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&txt) {
println!("{}", serde_json::to_string_pretty(&val).unwrap());
} else { println!("{}", txt); }
} else { println!("{}", txt); }
}
Ok(r) => { eprintln!("HTTP error: {}", r.status()); std::process::exit(1); }
Err(e) => { eprintln!("Request failed: {}", e); std::process::exit(1); }
}
}
Cmd::VaultNew { addr, id, dir, coeffs, nonce_monotonic, min_nonce, projection_one_g, json } => {
#[derive(serde::Serialize)]
struct Policy {
nonce_monotonic: bool,
#[serde(skip_serializing_if = "Option::is_none")] min_nonce: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")] projection_whitelist: Option<Vec<Vec<u64>>>,
}
#[derive(serde::Serialize)]
struct Body {
id: String, dir: String, coeffs: Vec<u64>,
#[serde(skip_serializing_if = "Option::is_none")] policy: Option<Policy>,
}
let policy = Some(Policy {
nonce_monotonic,
min_nonce,
projection_whitelist: projection_one_g.map(|g| vec![g]),
});
let body = Body { id, dir, coeffs, policy };
let client = reqwest::blocking::Client::new();
let url = format!("{}/vault/new", addr.trim_end_matches('/'));
let r = client.post(&url).json(&body).send();
match r {
Ok(r) if r.status().is_success() => {
let txt = r.text().unwrap_or_else(|_| "{}".into());
if json {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&txt) {
println!("{}", serde_json::to_string_pretty(&val).unwrap());
} else { println!("{}", txt); }
} else { println!("{}", txt); }
}
Ok(r) => { eprintln!("HTTP error: {}", r.status()); std::process::exit(1); }
Err(e) => { eprintln!("Request failed: {}", e); std::process::exit(1); }
}
}
Cmd::VaultAppend { addr, id, dir, batch, nonce_start, json } => {
let polys = parse_batch(&batch);
#[derive(serde::Serialize)]
struct A { g: Vec<u64>, nonce: u64 }
#[derive(serde::Serialize)]
struct Body { id: String, dir: String, actions: Vec<A> }
let actions: Vec<A> = polys.into_iter().enumerate()
.map(|(i,g)| A { g, nonce: nonce_start + i as u64 }).collect();
let body = Body { id, dir, actions };
let client = reqwest::blocking::Client::new();
let url = format!("{}/vault/append", addr.trim_end_matches('/'));
let r = client.post(&url).json(&body).send();
match r {
Ok(r) if r.status().is_success() => {
let txt = r.text().unwrap_or_else(|_| "{}".into());
if json {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&txt) {
println!("{}", serde_json::to_string_pretty(&val).unwrap());
} else { println!("{}", txt); }
} else { println!("{}", txt); }
}
Ok(r) => { eprintln!("HTTP error: {}", r.status()); std::process::exit(1); }
Err(e) => { eprintln!("Request failed: {}", e); std::process::exit(1); }
}
}
Cmd::VaultGet { addr, id, dir, subs_g, mask_degree, mask_nonce, json } => {
#[derive(serde::Serialize)]
struct Body {
id: String, dir: String,
#[serde(skip_serializing_if = "Option::is_none")] subs_g: Option<Vec<u64>>,
#[serde(skip_serializing_if = "Option::is_none")] mask_degree: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")] mask_nonce: Option<u64>,
}
let client = reqwest::blocking::Client::new();
let url = format!("{}/vault/get", addr.trim_end_matches('/'));
let r = client.post(&url).json(&Body { id, dir, subs_g, mask_degree, mask_nonce }).send();
match r {
Ok(r) if r.status().is_success() => {
let txt = r.text().unwrap_or_else(|_| "{}".into());
if json {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&txt) {
println!("{}", serde_json::to_string_pretty(&val).unwrap());
} else { println!("{}", txt); }
} else { println!("{}", txt); }
}
Ok(r) => { eprintln!("HTTP error: {}", r.status()); std::process::exit(1); }
Err(e) => { eprintln!("Request failed: {}", e); std::process::exit(1); }
}
}
Cmd::VaultProve { addr, id, dir, since_height, json } => {
#[derive(serde::Serialize)]
struct Body { id: String, dir: String, #[serde(skip_serializing_if = "Option::is_none")] since_height: Option<u64> }
let client = reqwest::blocking::Client::new();
let url = format!("{}/vault/prove", addr.trim_end_matches('/'));
let r = client.post(&url).json(&Body { id, dir, since_height }).send();
match r {
Ok(r) if r.status().is_success() => {
let txt = r.text().unwrap_or_else(|_| "{}".into());
if json {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&txt) {
println!("{}", serde_json::to_string_pretty(&val).unwrap());
} else { println!("{}", txt); }
} else { println!("{}", txt); }
}
Ok(r) => { eprintln!("HTTP error: {}", r.status()); std::process::exit(1); }
Err(e) => { eprintln!("Request failed: {}", e); std::process::exit(1); }
}
}
Cmd::VaultVerify { id, dir, transcript, coeffs, expect_height, expect_hash } => {
use std::path::Path;
use std::fs;
let idb = parse_id_hex64(&id);
let coeffs_vec: Vec<u64> = if let Some(c) = coeffs {
c
} else {
let base = Path::new(&dir).join(&id);
let newp = base.join("manifest.json");
let oldp = base.join("vault.json");
let path = if newp.exists() {
newp
} else if oldp.exists() {
oldp
} else {
eprintln!(
"manifest.json not found at {} and vault.json not found at {}.\n\
Provide channel coefficients with --coeffs a,b,c",
base.join("manifest.json").display(),
base.join("vault.json").display()
);
std::process::exit(2);
};
let mani_str = fs::read_to_string(&path)
.unwrap_or_else(|e| { eprintln!("read manifest {} failed: {}", path.display(), e); std::process::exit(2); });
let mani_val: serde_json::Value = serde_json::from_str(&mani_str)
.unwrap_or_else(|e| { eprintln!("parse manifest {} failed: {}", path.display(), e); std::process::exit(2); });
mani_val["coeffs"].as_array()
.unwrap_or_else(|| { eprintln!("manifest {} missing/invalid `coeffs`", path.display()); std::process::exit(2); })
.iter().map(|x| x.as_u64().unwrap()).collect()
};
let c = CompanionMatrix::from_coeffs(&coeffs_vec);
let mut init = vec![Field::zero(); c.k];
if c.k > 0 { init[0] = Field::new(1); }
let mut ch = Channel::open(c, init, idb);
let raw = fs::read_to_string(&transcript)
.unwrap_or_else(|e| { eprintln!("read transcript {} failed: {}", transcript, e); std::process::exit(2); });
for (lineno, line) in raw.lines().enumerate() {
if line.trim().is_empty() { continue; }
let e: serde_json::Value = serde_json::from_str(line)
.unwrap_or_else(|err| { eprintln!("transcript parse error at line {}: {}", lineno+1, err); std::process::exit(2); });
let (g, n) = if e.get("action").is_some() {
let a = &e["action"];
let g = a["g"].as_array().expect("action.g")
.iter().map(|x| x.as_u64().unwrap()).collect::<Vec<_>>();
let n = a["nonce"].as_u64().expect("action.nonce");
(g, n)
} else {
let g = e["g"].as_array().expect("g")
.iter().map(|x| x.as_u64().unwrap()).collect::<Vec<_>>();
let n = e["nonce"].as_u64().expect("nonce");
(g, n)
};
let a = Action { g_coeffs: g, nonce: n, mask_row0: None };
ch.apply(&a).unwrap_or_else(|e| { eprintln!("apply failed: {:?}", e); std::process::exit(2); });
}
let h = hash_state(&ch.state);
if let Some(must) = expect_height {
if ch.height != must { eprintln!("height mismatch: {} != {}", ch.height, must); std::process::exit(2); }
}
if let Some(must) = expect_hash {
if h != must { eprintln!("hash mismatch: {} != {}", h, must); std::process::exit(2); }
}
println!("{}", serde_json::to_string_pretty(&json!({
"ok": true, "height": ch.height, "state_hash": h
})).unwrap());
}
Cmd::ReceiptVerify { pubkey, id, height, state_hash, transcript_hash, sig } => {
use ed25519_dalek::{Signature, VerifyingKey};
use base64::engine::general_purpose::STANDARD as B64;
use base64::Engine;
let ctx = b"HOP_VAULT_APPEND_V1";
if id.len() != 64 {
eprintln!("bad `--id`: must be 64 hex chars"); std::process::exit(2);
}
let th = match B64.decode(&transcript_hash) {
Ok(b) if b.len()==32 => b,
_ => { eprintln!("`--transcript-hash` must be base64 of 32 bytes"); std::process::exit(2); }
};
let msg = [ ctx.as_slice(), id.as_bytes(), &height.to_le_bytes(), state_hash.as_bytes(), &th ].concat();
let pk_bytes: [u8;32] = B64.decode(&pubkey).ok().and_then(|b| b.try_into().ok())
.unwrap_or_else(|| { eprintln!("bad base64 pubkey"); std::process::exit(2); });
let sig_bytes: [u8;64] = B64.decode(&sig).ok().and_then(|b| b.try_into().ok())
.unwrap_or_else(|| { eprintln!("bad base64 signature"); std::process::exit(2); });
let vk = VerifyingKey::from_bytes(&pk_bytes).unwrap_or_else(|e| { eprintln!("pubkey error: {e}"); std::process::exit(2); });
let sig = Signature::from_bytes(&sig_bytes);
if let Err(e) = vk.verify_strict(&msg, &sig) {
eprintln!("signature invalid: {e}");
std::process::exit(2);
}
println!("{}", serde_json::to_string_pretty(&json!({"ok": true})).unwrap());
}
}
}