use anyhow::{bail, Context, Result};
use clap::{Parser, Subcommand};
use serde_json::json;
use sha2::{Digest, Sha256};
use hop_actions::Action;
use hop_channels::store_fs::FsStore;
use hop_channels::Channel;
use hop_core::{CompanionMatrix, Field, StreamGenerator};
#[cfg(feature = "torsor_masking")]
use hop_channels::mask::try_apply_twist_row;
use hop_channels::proj::try_row0_of_poly;
use hop_relay::apply_bundle;
#[derive(Parser)]
#[command(name = "hop", version, about = "Hop-Corr CLI")]
struct Cli {
#[arg(long, env = "HOP_AUTH_TOKEN", global = true)]
token: Option<String>,
#[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,
#[arg(long, default_value = "./data")]
data_dir: String,
#[arg(long)]
auth_token: Option<String>,
#[arg(long, default_value_t = 10_000)]
shutdown_grace_ms: u64,
#[arg(long, default_value_t = false)]
cors_any: bool,
#[arg(long = "cors-origin", value_delimiter = ',')]
cors_origins: Vec<String>,
#[arg(long, default_value_t = 1 * 1024 * 1024)]
max_body_bytes: u64,
#[arg(long, default_value_t = 1024)]
max_coeffs_len: usize,
#[arg(long, default_value_t = 4096)]
max_actions_per_request: usize,
#[arg(long, default_value_t = 10_000_000)]
max_action_work: u64,
#[arg(long, default_value_t = 10_000)]
max_prove_entries: usize,
#[arg(long, default_value_t = 128)]
max_in_flight_requests: usize,
#[arg(long, default_value_t = 30_000)]
request_timeout_ms: u64,
#[arg(long, default_value_t = 0)]
rate_limit_rps: u32,
#[arg(long, default_value_t = 0)]
rate_limit_burst: u32,
},
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)]
expected_height: u64,
#[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 = "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, 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)]
expected_height: u64,
#[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 = "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)]
since_height: Option<u64>,
#[arg(long)]
limit: Option<usize>,
#[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) -> Result<[u8; 32]> {
if id_hex.len() != 64 {
bail!("channel id must contain exactly 64 hexadecimal characters");
}
let bytes = hex::decode(id_hex).context("channel id is not valid hexadecimal")?;
bytes
.try_into()
.map_err(|_| anyhow::anyhow!("channel id must decode to exactly 32 bytes"))
}
fn hash_state(fields: &[Field]) -> String {
let mut h = Sha256::new();
h.update(b"HOP-STATE\0\x02");
h.update((fields.len() as u128).to_le_bytes());
for f in fields {
h.update(f.to_le_bytes());
}
format!("{:x}", h.finalize())
}
fn checked_companion(coefficients: &[u64]) -> Result<CompanionMatrix> {
if coefficients.is_empty() {
bail!("companion coefficients must not be empty");
}
if coefficients.iter().any(|value| *value >= Field::MOD) {
bail!(
"companion coefficients must be canonical values below {}",
Field::MOD
);
}
CompanionMatrix::try_from_coeffs(coefficients).context("construct companion matrix")
}
fn parse_batch(batch: &str) -> Result<Vec<Vec<u64>>> {
let actions = batch
.split(';')
.filter(|s| !s.trim().is_empty())
.map(|seg| {
seg.split(',')
.filter(|t| !t.is_empty())
.map(|t| {
t.trim()
.parse::<u64>()
.with_context(|| format!("invalid action coefficient `{}`", t.trim()))
})
.collect::<Result<Vec<u64>>>()
})
.collect::<Result<Vec<_>>>()?;
if actions.is_empty() || actions.iter().any(Vec::is_empty) {
bail!("batch must contain at least one non-empty action polynomial");
}
Ok(actions)
}
fn parse_json_u64_array(value: &serde_json::Value, label: &str) -> Result<Vec<u64>> {
let values = value
.as_array()
.with_context(|| format!("{label} must be an array"))?;
values
.iter()
.enumerate()
.map(|(index, value)| {
value
.as_u64()
.with_context(|| format!("{label}[{index}] must be an unsigned integer"))
})
.collect()
}
fn checked_nonce(start: u64, index: usize) -> Result<u64> {
let offset = u64::try_from(index).context("action index does not fit in a nonce")?;
start
.checked_add(offset)
.context("action nonce range overflows u64")
}
fn main() {
if let Err(error) = run() {
eprintln!("error: {error:#}");
std::process::exit(2);
}
}
fn run() -> Result<()> {
let cli = Cli::parse();
let token = cli.token.clone();
match cli.cmd {
Cmd::Create { coeffs } => {
let c = checked_companion(&coeffs)?;
let state =
vec![Field::new(1), Field::new(0), Field::new(0)][..c.dimension().min(3)].to_vec();
let mut padded = vec![Field::zero(); c.dimension()];
for (i, f) in state.into_iter().enumerate() {
padded[i] = f;
}
let ch = Channel::try_open(c, padded, [0u8; 32])?;
println!("Created channel with k={}", ch.dimension());
}
Cmd::Send { g, nonce } => {
let c = checked_companion(&[4, 3, 2])?; let mut ch = Channel::try_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().first().map(|f| f.value())
);
}
Cmd::Tail { n } => {
let c = checked_companion(&[4, 3, 2])?;
let k = c.dimension();
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().value());
}
}
Cmd::Save { id, dir } => {
let id = parse_id_hex64(&id)?;
let store = FsStore::new(&dir).context("open channel store")?;
let c = checked_companion(&[4, 3, 2])?;
let mut init = vec![Field::zero(); c.dimension()];
init[0] = Field::new(1);
let ch = Channel::try_open(c, init, id)?.with_store(Box::new(store));
ch.save_now().context("save channel snapshot")?;
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).context("open channel store")?;
let ch0 = match Channel::restore(id, Box::new(store)) {
Ok(channel) => channel,
Err(hop_channels::ChannelError::SnapshotNotFound) => {
let c = checked_companion(&[4, 3, 2])?;
let mut init = vec![Field::zero(); c.dimension()];
init[0] = Field::new(1);
Channel::try_open(c, init, id)?
}
Err(error) => return Err(error).context("restore existing channel"),
};
let mut ch =
ch0.with_store(Box::new(FsStore::new(&dir).context("open channel store")?));
let a = Action {
g_coeffs: g,
nonce,
mask_row0: None,
};
ch.apply(&a).context("apply channel action")?;
let _ = ch.save_now();
println!("Applied; height={}", ch.height());
}
Cmd::Load { id, dir } => {
let id = parse_id_hex64(&id)?;
let store = FsStore::new(&dir).context("open channel store")?;
let ch = Channel::restore(id, Box::new(store)).context("restore channel")?;
println!(
"Loaded channel k={}, height={}",
ch.dimension(),
ch.height()
);
}
Cmd::Replay { id, dir } => {
let id = parse_id_hex64(&id)?;
let store = FsStore::new(&dir).context("open channel store")?;
let ch = Channel::restore(id, Box::new(store)).context("restore channel")?;
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 = checked_companion(&coeffs)?;
let c2 = checked_companion(&coeffs)?;
let k = c1.dimension();
let mut s = vec![Field::zero(); k];
s[0] = Field::new(1);
let mut ch_a = Channel::try_open(c1, s.clone(), [0xAA; 32])?;
let mut ch_b = Channel::try_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: checked_nonce(nonce_start, i)?,
mask_row0: None,
};
actions_a.push(a.clone());
actions_b.push(a);
}
actions_b.rotate_left(1);
apply_bundle(&mut ch_a, &actions_a).context("apply first demo bundle")?;
apply_bundle(&mut ch_b, &actions_b).context("apply reordered demo bundle")?;
let hash_a = hash_state(ch_a.state());
let hash_b = hash_state(ch_b.state());
let converge = hash_a == hash_b;
let row = try_row0_of_poly(ch_a.companion(), &subs_g)
.context("build subscriber projection")?;
let mut proj_unmasked = Field::zero();
for (w, x) in row.iter().zip(ch_a.state().iter()) {
proj_unmasked += *w * *x;
}
#[cfg(feature = "torsor_masking")]
let proj_masked = {
let row_twisted =
try_apply_twist_row(ch_a.companion(), &row, mask_nonce, mask_degree)
.context("build projection twist")?;
let mut acc = Field::zero();
for (w, x) in row_twisted.iter().zip(ch_a.state().iter()) {
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.value(),
});
#[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.value(),
});
#[cfg(feature = "torsor_masking")]
{
let obj = out
.as_object_mut()
.context("internal demo output must be a JSON object")?;
obj.insert("mask_degree".into(), json!(mask_degree));
obj.insert("mask_nonce".into(), json!(mask_nonce));
obj.insert("proj_masked".into(), json!(proj_masked.value()));
}
println!("{}", serde_json::to_string_pretty(&out)?);
}
Cmd::ObdemoPersist {
coeffs,
subs_g,
batch,
nonce_start,
dir,
id,
} => {
let c = checked_companion(&coeffs)?;
let k = c.dimension();
let mut s = vec![Field::zero(); k];
s[0] = Field::new(1);
let idb = parse_id_hex64(&id)?;
let mut ch = Channel::try_open(c, s, idb)?;
let polys = parse_batch(&batch)?;
let actions: Vec<Action> = polys
.iter()
.enumerate()
.map(|(i, g)| {
Ok(Action {
g_coeffs: g.clone(),
nonce: checked_nonce(nonce_start, i)?,
mask_row0: None,
})
})
.collect::<Result<_>>()?;
apply_bundle(&mut ch, &actions).context("apply demo bundle")?;
let hash_before = hash_state(ch.state());
let store = FsStore::new(&dir).context("open channel store")?;
let ch_saved = ch.with_store(Box::new(store));
ch_saved.save_now().context("save channel snapshot")?;
let store2 = FsStore::new(&dir).context("reopen channel store")?;
let ch2 = Channel::restore(idb, Box::new(store2)).context("restore channel")?;
let hash_after = hash_state(ch2.state());
let row = try_row0_of_poly(ch2.companion(), &subs_g)
.context("build subscriber projection")?;
let mut proj_unmasked = Field::zero();
for (w, x) in row.iter().zip(ch2.state().iter()) {
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.value(),
"dir": dir, "id": id,
}))?
);
}
Cmd::Relay {
listen,
data_dir,
auth_token,
shutdown_grace_ms,
cors_any,
cors_origins,
max_body_bytes,
max_coeffs_len,
max_actions_per_request,
max_action_work,
max_prove_entries,
max_in_flight_requests,
request_timeout_ms,
rate_limit_rps,
rate_limit_burst,
} => {
use std::path::PathBuf;
let rt = tokio::runtime::Runtime::new().context("create Tokio runtime")?;
let cfg = hop_relay::net::ServerConfig {
data_dir: PathBuf::from(data_dir),
auth_token,
max_body_bytes,
max_coeffs_len,
max_actions_per_request,
max_action_work,
max_prove_entries,
max_in_flight_requests,
request_timeout_ms,
rate_limit_rps,
rate_limit_burst,
cors_allow_any_origin: cors_any,
cors_allow_origins: cors_origins,
shutdown_grace_ms,
};
rt.block_on(async move { hop_relay::net::serve(&listen, cfg).await })
.map_err(|error| anyhow::anyhow!("relay server failed: {error}"))?;
}
Cmd::SendBundle {
addr,
coeffs,
id,
expected_height,
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,
expected_height: u64,
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)| {
Ok(ActionOut {
g: g.clone(),
nonce: checked_nonce(nonce_start, i)?,
})
})
.collect::<Result<_>>()?;
let body = BundleOut {
id,
expected_height,
coeffs,
actions,
subs_g,
mask_degree,
mask_nonce,
};
let client = reqwest::blocking::Client::builder()
.timeout(std::time::Duration::from_secs(15))
.build()
.context("build HTTP client")?;
let url = format!("{}/bundle", addr.trim_end_matches('/'));
let mut req = client.post(&url).json(&body);
if let Some(tok) = &token {
req = req.bearer_auth(tok);
}
let resp = req.send();
match resp {
Ok(r) if r.status().is_success() => {
let txt = r.text().context("read HTTP response body")?;
if json {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&txt) {
println!("{}", serde_json::to_string_pretty(&val)?);
} 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,
subs_g,
mask_degree,
mask_nonce,
json,
} => {
#[derive(serde::Serialize)]
struct Query {
id: 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::builder()
.timeout(std::time::Duration::from_secs(15))
.build()
.context("build HTTP client")?;
let url = format!("{}/state", addr.trim_end_matches('/'));
let mut req = client.post(&url).json(&Query {
id,
subs_g,
mask_degree,
mask_nonce,
});
if let Some(tok) = &token {
req = req.bearer_auth(tok);
}
let resp = req.send();
match resp {
Ok(r) if r.status().is_success() => {
let txt = r.text().context("read HTTP response body")?;
if json {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&txt) {
println!("{}", serde_json::to_string_pretty(&val)?);
} 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,
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,
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, coeffs, policy };
let client = reqwest::blocking::Client::builder()
.timeout(std::time::Duration::from_secs(15))
.build()
.context("build HTTP client")?;
let url = format!("{}/vault/new", addr.trim_end_matches('/'));
let mut req = client.post(&url).json(&body);
if let Some(tok) = &token {
req = req.bearer_auth(tok);
}
let r = req.send();
match r {
Ok(r) if r.status().is_success() => {
let txt = r.text().context("read HTTP response body")?;
if json {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&txt) {
println!("{}", serde_json::to_string_pretty(&val)?);
} 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,
expected_height,
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,
expected_height: u64,
actions: Vec<A>,
}
let actions: Vec<A> = polys
.into_iter()
.enumerate()
.map(|(i, g)| {
Ok(A {
g,
nonce: checked_nonce(nonce_start, i)?,
})
})
.collect::<Result<_>>()?;
let body = Body {
id,
expected_height,
actions,
};
let client = reqwest::blocking::Client::builder()
.timeout(std::time::Duration::from_secs(15))
.build()
.context("build HTTP client")?;
let url = format!("{}/vault/append", addr.trim_end_matches('/'));
let mut req = client.post(&url).json(&body);
if let Some(tok) = &token {
req = req.bearer_auth(tok);
}
let r = req.send();
match r {
Ok(r) if r.status().is_success() => {
let txt = r.text().context("read HTTP response body")?;
if json {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&txt) {
println!("{}", serde_json::to_string_pretty(&val)?);
} 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,
subs_g,
mask_degree,
mask_nonce,
json,
} => {
#[derive(serde::Serialize)]
struct Body {
id: 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::builder()
.timeout(std::time::Duration::from_secs(15))
.build()
.context("build HTTP client")?;
let url = format!("{}/vault/get", addr.trim_end_matches('/'));
let mut req = client.post(&url).json(&Body {
id,
subs_g,
mask_degree,
mask_nonce,
});
if let Some(tok) = &token {
req = req.bearer_auth(tok);
}
let r = req.send();
match r {
Ok(r) if r.status().is_success() => {
let txt = r.text().context("read HTTP response body")?;
if json {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&txt) {
println!("{}", serde_json::to_string_pretty(&val)?);
} 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,
since_height,
limit,
json,
} => {
#[derive(serde::Serialize)]
struct Body {
id: String,
#[serde(skip_serializing_if = "Option::is_none")]
since_height: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
limit: Option<usize>,
}
let client = reqwest::blocking::Client::builder()
.timeout(std::time::Duration::from_secs(15))
.build()
.context("build HTTP client")?;
let url = format!("{}/vault/prove", addr.trim_end_matches('/'));
let mut req = client.post(&url).json(&Body {
id,
since_height,
limit,
});
if let Some(tok) = &token {
req = req.bearer_auth(tok);
}
let r = req.send();
match r {
Ok(r) if r.status().is_success() => {
let txt = r.text().context("read HTTP response body")?;
if json {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&txt) {
println!("{}", serde_json::to_string_pretty(&val)?);
} 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::fs;
use std::path::Path;
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)
.with_context(|| format!("read manifest {}", path.display()))?;
let mani_val: serde_json::Value = serde_json::from_str(&mani_str)
.with_context(|| format!("parse manifest {}", path.display()))?;
parse_json_u64_array(&mani_val["coeffs"], "manifest.coeffs")?
};
let c = checked_companion(&coeffs_vec)?;
let mut init = vec![Field::zero(); c.dimension()];
if c.dimension() > 0 {
init[0] = Field::new(1);
}
let mut ch = Channel::try_open(c, init, idb)?;
let raw = fs::read_to_string(&transcript)
.with_context(|| format!("read transcript {transcript}"))?;
for (lineno, line) in raw.lines().enumerate() {
if line.trim().is_empty() {
continue;
}
let e: serde_json::Value = serde_json::from_str(line)
.with_context(|| format!("parse transcript line {}", lineno + 1))?;
let (g, n) = if e.get("action").is_some() {
let a = &e["action"];
let g = parse_json_u64_array(&a["g"], "action.g")?;
let n = a["nonce"]
.as_u64()
.context("action.nonce must be an unsigned integer")?;
(g, n)
} else {
let g = parse_json_u64_array(&e["g"], "g")?;
let n = e["nonce"]
.as_u64()
.context("nonce must be an unsigned integer")?;
(g, n)
};
let a = Action {
g_coeffs: g,
nonce: n,
mask_row0: None,
};
ch.apply(&a)
.with_context(|| format!("apply transcript line {}", lineno + 1))?;
}
let h = hash_state(ch.state());
if let Some(must) = expect_height {
if ch.height() != must {
bail!("height mismatch: {} != {}", ch.height(), must);
}
}
if let Some(must) = expect_hash {
if h != must {
bail!("hash mismatch: {} != {}", h, must);
}
}
println!(
"{}",
serde_json::to_string_pretty(&json!({
"ok": true, "height": ch.height(), "state_hash": h
}))?
);
}
Cmd::ReceiptVerify {
pubkey,
id,
height,
state_hash,
transcript_hash,
sig,
} => {
use base64::engine::general_purpose::STANDARD as B64;
use base64::Engine;
use ed25519_dalek::{Signature, VerifyingKey};
let ctx = b"HOP_VAULT_APPEND_V2";
let id = hex::encode(parse_id_hex64(&id)?);
let state_hash_bytes =
hex::decode(&state_hash).context("state hash must be hexadecimal")?;
if state_hash_bytes.len() != 32 || state_hash != hex::encode(&state_hash_bytes) {
bail!("state hash must be 64 lowercase hexadecimal characters");
}
let th = B64
.decode(&transcript_hash)
.context("transcript hash is not valid base64")?;
if th.len() != 32 {
bail!("transcript hash must decode to 32 bytes");
}
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)
.context("public key is not valid base64")?
.try_into()
.map_err(|_| anyhow::anyhow!("public key must decode to 32 bytes"))?;
let sig_bytes: [u8; 64] = B64
.decode(&sig)
.context("signature is not valid base64")?
.try_into()
.map_err(|_| anyhow::anyhow!("signature must decode to 64 bytes"))?;
let vk = VerifyingKey::from_bytes(&pk_bytes).context("invalid Ed25519 public key")?;
let sig = Signature::from_bytes(&sig_bytes);
if let Err(e) = vk.verify_strict(&msg, &sig) {
bail!("signature invalid: {e}");
}
println!("{}", serde_json::to_string_pretty(&json!({"ok": true}))?);
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn strict_identifier_parser_rejects_padding_and_truncation() {
assert!(parse_id_hex64(&"00".repeat(32)).is_ok());
assert!(parse_id_hex64("01").is_err());
assert!(parse_id_hex64(&"00".repeat(33)).is_err());
assert!(parse_id_hex64(&"zz".repeat(32)).is_err());
}
#[test]
fn batch_parser_rejects_empty_and_malformed_actions() {
assert_eq!(parse_batch("1,2;3").unwrap(), vec![vec![1, 2], vec![3]]);
assert!(parse_batch("").is_err());
assert!(parse_batch(";").is_err());
assert!(parse_batch("1,nope").is_err());
}
#[test]
fn checked_boundaries_reject_overflow_and_noncanonical_coefficients() {
assert_eq!(checked_nonce(9, 2).unwrap(), 11);
assert!(checked_nonce(u64::MAX, 1).is_err());
assert!(checked_companion(&[]).is_err());
assert!(checked_companion(&[Field::MOD]).is_err());
}
}