fulbody-cli 0.1.1

Command-line interface for interacting with Hop-Corr channels and relays
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
// CLI with Save, Load, Apply, Replay + OBDemo + Relay + SendBundle + GetState + Vault*
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; // local-bundle apply (non-network)
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 a channel with k = coeffs.len()
    Create { #[arg(long, value_delimiter = ',')] coeffs: Vec<u64> },

    /// Send an action to a simple in-memory channel (demo)
    Send { #[arg(long, value_delimiter = ',')] g: Vec<u64>, #[arg(long, default_value_t=0)] nonce: u64 },

    /// Demo: stream N outputs
    Tail { #[arg(long, default_value_t=10)] n: usize },

    /// Persistence: save a snapshot for an ID
    Save { #[arg(long)] id: String, #[arg(long, default_value = "./data")] dir: String },

    /// Persistence: apply and persist one action
    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
    },

    /// Persistence: load a snapshot
    Load { #[arg(long)] id: String, #[arg(long, default_value = "./data")] dir: String },

    /// Persistence: replay actions since last checkpoint
    Replay { #[arg(long)] id: String, #[arg(long, default_value = "./data")] dir: String },

    /// OBDemo: consensus-without-blocks + masking in one shot
    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,
    },

    /// Persisted obdemo: apply bundle, save, reload, verify same hash
    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,
    },

    /// Start the relay server (HTTP)
    Relay {
        #[arg(long, default_value = "127.0.0.1:8787")]
        listen: String
    },

    /// Send a bundle to the relay (HTTP)
    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,
    },

    /// Query state from the relay (HTTP)
    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,
    },

    // -------------------- Vault commands --------------------

    /// Create a new vault (manifest + bootstrap channel)
    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>,

        /// Policy (MVP)
        #[arg(long, default_value_t=false)]
        nonce_monotonic: bool,
        #[arg(long)]
        min_nonce: Option<u64>,
        /// Not used in MVP flow; placeholder for future server enforcement
        #[arg(long = "proj-whitelist", value_delimiter = ',', required = false)]
        projection_one_g: Option<Vec<u64>>,

        #[arg(long, default_value_t=false)]
        json: bool,
    },

    /// Append actions into a vault (writes transcript)
    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,
    },

    /// Get vault state + manifest (+ optional projection)
    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,
    },

    /// Fetch transcript entries since height (for external verification)
    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,
    },

    /// Verify a transcript locally by replaying it (client-side check)
    VaultVerify {
        #[arg(long)]
        id: String,
        #[arg(long, default_value = "./data")]
        dir: String,
        /// JSONL transcript file path (e.g. data/<id>/actions.jsonl)
        #[arg(long)]
        transcript: String,
        /// Optional explicit coeffs if manifest.json is not present
        #[arg(long, value_delimiter = ',', required = false)]
        coeffs: Option<Vec<u64>>,
        /// Expected final height/hash (optional but recommended)
        #[arg(long)]
        expect_height: Option<u64>,
        #[arg(long)]
        expect_hash: Option<String>,
    },

    /// Verify a /vault/append receipt (offline)
    ReceiptVerify {
        #[arg(long)] pubkey: String,           // base64
        #[arg(long)] id: String,               // 64 hex
        #[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 {
        // ---------------- Baseline commands ----------------
        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]); // demo
            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); // avoid unused when feature off
            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");
            });
        }

        // ---------------- HTTP Send/Get ----------------

        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); }
            }
        }

        // ---------------- Vault commands ----------------

        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);

            // Resolve coeffs: --coeffs > manifest.json > vault.json
            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()
            };

            // Fresh in-memory channel at genesis (bootstrap state[0] = 1)
            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);

            // Replay transcript JSONL; accept either {"action":{g,nonce}} or flat {g,nonce}
            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());
        }
    }
}