zc2 0.0.53

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
//! `zc verify`: check a hub receipt offline (ADR ZC-0026 §1, §2, §4).
//!
//! A hub receipt (`zakuro.job_receipt` v2) is an Ed25519 signature over
//! `zakuro-receipt:v1\n` + the canonical JSON bytes the hub emitted, and is
//! addressed by the SHA-256 of those bytes. Same rule as `broker::voucher`:
//! the signature is checked over the bytes as received and only then are
//! fields read. The bytes are never re-serialized, so Python's and Rust's
//! float and whitespace formatting never enter into it.
//!
//! Keys: `--pubkey` when given; otherwise the hub's `GET /api/receipts/pubkeys`
//! over HTTPS, labelled as fetched and not pinned. No profile pins or caches
//! the hub's voucher key today (the broker keeps it in memory only, and the
//! profile's action trust roots are a different key), so there is nothing
//! older to prefer.
//!
//! The `trust_level` printed is the hub's own word for the receipt (today
//! `unattested`); zc never upgrades it.

use base64::engine::general_purpose::STANDARD as B64;
use base64::Engine;
use ring::digest::{digest, SHA256};
use ring::signature::{UnparsedPublicKey, ED25519};
use serde_json::Value;
use std::io::Read;
use std::time::Duration;

/// Domain separation: the receipt key is the voucher key, and a voucher is
/// signed over its bare JSON, so neither can be replayed as the other.
pub const DOMAIN: &[u8] = b"zakuro-receipt:v1\n";
const SCHEMA: &str = "zakuro.job_receipt";
/// The hub refuses anything larger, so a verifier need not parse it either.
pub const MAX_RECEIPT_BYTES: usize = 256_000;
const FETCH_TIMEOUT: Duration = Duration::from_secs(15);

pub fn sha256_hex(bytes: &[u8]) -> String {
    hex::encode(digest(&SHA256, bytes).as_ref())
}

/// An Ed25519 public key and its `kid`: the first 8 bytes of the SHA-256 of
/// the raw key, in hex (`voucher.fingerprint` on the hub).
#[derive(Debug, Clone, PartialEq)]
pub struct TrustedKey {
    pub raw: Vec<u8>,
    pub kid: String,
}

impl TrustedKey {
    pub fn from_raw(raw: Vec<u8>) -> Result<Self, String> {
        if raw.len() != 32 {
            return Err(format!(
                "an Ed25519 public key is 32 bytes, this one is {}",
                raw.len()
            ));
        }
        let kid = hex::encode(&digest(&SHA256, &raw).as_ref()[..8]);
        Ok(Self { raw, kid })
    }

    /// 64 hex characters, or base64 (what the hub publishes).
    pub fn parse(s: &str) -> Result<Self, String> {
        let s = s.trim();
        if s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit()) {
            return Self::from_raw(hex::decode(s).map_err(|e| e.to_string())?);
        }
        let raw = B64
            .decode(s)
            .map_err(|_| "a public key is 64 hex characters or base64 of 32 bytes".to_string())?;
        Self::from_raw(raw)
    }
}

/// Where the keys a verdict was checked against came from, said in the output.
#[derive(Debug, Clone, PartialEq)]
pub enum KeySource {
    Given,
    Fetched(String),
}

impl KeySource {
    pub fn label(&self) -> String {
        match self {
            KeySource::Given => "given with --pubkey".into(),
            KeySource::Fetched(url) => {
                format!("fetched from {url} (not pinned: this trusts the hub to name its own key)")
            }
        }
    }
}

/// A receipt as the hub serves it: the exact signed text and its signature.
#[derive(Debug, Clone, PartialEq)]
pub struct Signed {
    pub receipt_json: String,
    pub signature: String,
}

#[derive(Debug, Clone, PartialEq)]
pub enum VerifyError {
    Input(String),
    UnknownKey(String),
    BadSignature,
    Schema(String),
}

impl std::fmt::Display for VerifyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            VerifyError::Input(m) => write!(f, "{m}"),
            VerifyError::UnknownKey(kid) => write!(
                f,
                "the receipt was signed by key {kid}, which is not in the key set used"
            ),
            VerifyError::BadSignature => write!(f, "bad signature"),
            VerifyError::Schema(m) => write!(f, "{m}"),
        }
    }
}

#[derive(Debug, Clone)]
pub struct Verified {
    /// SHA-256 of the signed bytes: the receipt's address.
    pub receipt_hash: String,
    /// A v1 receipt, signed before domain separation.
    pub legacy: bool,
    pub kid: String,
    pub body: Value,
}

/// Check the signature over the bytes as received, then the schema.
pub fn verify(signed: &Signed, keys: &[TrustedKey]) -> Result<Verified, VerifyError> {
    if signed.receipt_json.len() > MAX_RECEIPT_BYTES {
        return Err(VerifyError::Input("receipt is too large".into()));
    }
    if signed.signature.len() > 256 {
        return Err(VerifyError::Input("signature is too long".into()));
    }
    let sig = B64
        .decode(signed.signature.trim())
        .map_err(|_| VerifyError::Input("signature is not base64".into()))?;
    let bytes = signed.receipt_json.as_bytes();
    // The kid names the key, so the bytes are parsed before the signature is
    // checked. Nothing read from them is trusted until it has been.
    let body: Value = serde_json::from_slice(bytes)
        .map_err(|_| VerifyError::Input("receipt is not JSON".into()))?;
    let kid = body
        .get("signer")
        .and_then(|s| s.get("kid"))
        .and_then(Value::as_str)
        .ok_or_else(|| VerifyError::Input("receipt has no signer".into()))?
        .to_string();
    let key = keys
        .iter()
        .find(|k| k.kid == kid)
        .ok_or_else(|| VerifyError::UnknownKey(kid.clone()))?;
    let pk = UnparsedPublicKey::new(&ED25519, &key.raw);
    let mut message = DOMAIN.to_vec();
    message.extend_from_slice(bytes);
    let legacy = if pk.verify(&message, &sig).is_ok() {
        false
    } else if pk.verify(bytes, &sig).is_ok() {
        true
    } else {
        return Err(VerifyError::BadSignature);
    };
    if body.get("schema").and_then(Value::as_str) != Some(SCHEMA) {
        return Err(VerifyError::Schema(
            "unknown receipt schema or version".into(),
        ));
    }
    let want_v = if legacy { 1 } else { 2 };
    if body.get("v").and_then(Value::as_u64) != Some(want_v) {
        // A v2 body under a bare-bytes signature (or the reverse) is a forgery
        // attempt or a bug; either way it is not a receipt.
        return Err(if legacy {
            VerifyError::BadSignature
        } else {
            VerifyError::Schema("unknown receipt schema or version".into())
        });
    }
    Ok(Verified {
        receipt_hash: sha256_hex(bytes),
        legacy,
        kid,
        body,
    })
}

/// The output digests a receipt signs (`outputs.hashes`, sorted, names
/// withheld), or `None` for a kind that carries none.
pub fn signed_output_hashes(body: &Value) -> Option<Vec<String>> {
    let hashes = body.get("outputs")?.get("hashes")?.as_array()?;
    let mut v: Vec<String> = hashes
        .iter()
        .filter_map(|h| h.as_str().map(str::to_string))
        .collect();
    v.sort();
    Some(v)
}

/// Compare the digests of files actually on disk with what the receipt
/// signs. The hub strips file names from a receipt, so the comparison is of
/// the sorted digest lists: same files, no extras, none missing.
pub fn check_output_digests(body: &Value, local: &[String]) -> Result<(), String> {
    let Some(signed) = signed_output_hashes(body) else {
        return Err("the receipt carries no output digests to compare with".into());
    };
    let count = body["outputs"]["count"].as_u64();
    if count.is_some_and(|c| c as usize != signed.len()) {
        return Err(
            "the receipt names more outputs than it carries valid digests for (hub flagged them invalid)"
                .into(),
        );
    }
    let mut local: Vec<String> = local.iter().map(|d| d.to_ascii_lowercase()).collect();
    local.sort();
    if local != signed {
        return Err(format!(
            "the outputs on disk ({} file(s)) do not match the digests the receipt signs ({})",
            local.len(),
            signed.len()
        ));
    }
    Ok(())
}

// ---- input and fetching -----------------------------------------------------

/// A receipt document: the hub's `GET /api/receipts/{hash}` answer, or any
/// JSON object holding `receipt_json` (a string) and `signature`.
pub fn parse_signed(text: &str) -> Result<Signed, String> {
    let v: Value =
        serde_json::from_str(text).map_err(|e| format!("not a receipt document: {e}"))?;
    let receipt_json = v
        .get("receipt_json")
        .and_then(Value::as_str)
        .ok_or("no `receipt_json` string in the document")?;
    let signature = v
        .get("signature")
        .and_then(Value::as_str)
        .ok_or("no `signature` string in the document")?;
    Ok(Signed {
        receipt_json: receipt_json.to_string(),
        signature: signature.to_string(),
    })
}

/// A hub URL is fetched over HTTPS; plain HTTP is for loopback (tests, a
/// local hub) only, so a key or receipt is never read over a wire that
/// someone can rewrite.
pub fn check_hub_url(base: &str) -> Result<String, String> {
    let base = base.trim().trim_end_matches('/');
    let rest = if let Some(r) = base.strip_prefix("https://") {
        r
    } else if let Some(r) = base.strip_prefix("http://") {
        let host = r.split(['/', ':']).next().unwrap_or("");
        if !matches!(host, "127.0.0.1" | "localhost" | "[::1]") {
            return Err(format!(
                "{base}: receipts and keys are fetched over HTTPS only"
            ));
        }
        r
    } else {
        return Err(format!("{base}: not an http(s) URL"));
    };
    if rest.is_empty() {
        return Err("empty hub URL".into());
    }
    Ok(base.to_string())
}

fn http(timeout: Duration) -> ureq::Agent {
    ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            .http_status_as_error(false)
            .timeout_global(Some(timeout))
            .build(),
    )
}

/// A fetch that failed: the HTTP status when the hub answered one, so a
/// caller can tell a refusal (4xx) from a hub that is down.
#[derive(Debug, Clone, PartialEq)]
pub struct FetchError {
    pub status: Option<u16>,
    pub message: String,
}

impl FetchError {
    fn io(message: String) -> Self {
        Self {
            status: None,
            message,
        }
    }

    /// 4xx other than 408/429: the hub says no, and asking again will not change it.
    pub fn permanent(&self) -> bool {
        matches!(self.status, Some(s) if (400..500).contains(&s) && s != 408 && s != 429)
    }
}

impl std::fmt::Display for FetchError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.message)
    }
}

fn get_text(url: &str, timeout: Duration) -> Result<String, FetchError> {
    let resp = http(timeout)
        .get(url)
        .call()
        .map_err(|e| FetchError::io(format!("{url}: {e}")))?;
    let status = resp.status().as_u16();
    let mut body = String::new();
    resp.into_body()
        .into_reader()
        .take(MAX_RECEIPT_BYTES as u64 * 4)
        .read_to_string(&mut body)
        .map_err(|e| FetchError::io(format!("{url}: {e}")))?;
    if status != 200 {
        return Err(FetchError {
            status: Some(status),
            message: format!("{url} answered HTTP {status}"),
        });
    }
    Ok(body)
}

/// `GET {hub}/api/receipts/pubkeys` → the keys a receipt may be signed with.
pub fn fetch_pubkeys(base: &str) -> Result<(Vec<TrustedKey>, KeySource), FetchError> {
    fetch_pubkeys_within(base, FETCH_TIMEOUT)
}

/// [`fetch_pubkeys`] with its own bound, for a caller that answers a request
/// while it waits.
pub fn fetch_pubkeys_within(
    base: &str,
    timeout: Duration,
) -> Result<(Vec<TrustedKey>, KeySource), FetchError> {
    let base = check_hub_url(base).map_err(FetchError::io)?;
    let url = format!("{base}/api/receipts/pubkeys");
    let v: Value = serde_json::from_str(&get_text(&url, timeout)?)
        .map_err(|e| FetchError::io(format!("{url}: unreadable answer: {e}")))?;
    let mut keys = Vec::new();
    for k in v
        .get("keys")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
    {
        if let Some(key) = k
            .get("pubkey")
            .and_then(Value::as_str)
            .and_then(|s| TrustedKey::parse(s).ok())
        {
            if !keys.contains(&key) {
                keys.push(key);
            }
        }
    }
    if keys.is_empty() {
        return Err(FetchError::io(format!(
            "{url}: no usable key in the answer"
        )));
    }
    Ok((keys, KeySource::Fetched(url)))
}

/// `GET {hub}/api/receipts/{hash}`, checked to be the receipt asked for: the
/// SHA-256 of the bytes served must be the hash requested, or the hub (or
/// whoever sits in front of it) answered with a different receipt.
pub fn fetch_receipt(base: &str, hash: &str) -> Result<Signed, FetchError> {
    fetch_receipt_within(base, hash, FETCH_TIMEOUT)
}

/// [`fetch_receipt`] with its own bound (the executor's `/peer/earn` waits on it).
pub fn fetch_receipt_within(
    base: &str,
    hash: &str,
    timeout: Duration,
) -> Result<Signed, FetchError> {
    let base = check_hub_url(base).map_err(FetchError::io)?;
    let hash = hash.trim().to_ascii_lowercase();
    let url = format!("{base}/api/receipts/{hash}");
    let signed = parse_signed(&get_text(&url, timeout)?)
        .map_err(|e| FetchError::io(format!("{url}: {e}")))?;
    if sha256_hex(signed.receipt_json.as_bytes()) != hash {
        return Err(FetchError::io(format!(
            "{url}: the receipt served does not hash to {hash}; refusing it"
        )));
    }
    Ok(signed)
}

// ---- report -----------------------------------------------------------------

fn s(v: &Value, path: &[&str]) -> Option<String> {
    let mut cur = v;
    for p in path {
        cur = cur.get(p)?;
    }
    match cur {
        Value::Null => None,
        Value::String(x) => Some(x.clone()),
        other => Some(other.to_string()),
    }
}

/// What the receipt binds, as `(label, value)` lines. Fields the hub does not
/// sign for a given kind are left out, never guessed.
pub fn binds(body: &Value) -> Vec<(String, String)> {
    let mut out = Vec::new();
    let mut add = |label: &str, v: Option<String>| {
        if let Some(v) = v {
            out.push((label.to_string(), v));
        }
    };
    add("kind", s(body, &["kind"]));
    add("issued", s(body, &["issued_at"]));
    // The hub signs a salted commitment, never an account id: the owner opens
    // it with `GET /api/receipts/{hash}/owner`.
    add(
        "payer (commitment, opens with the owner view)",
        s(body, &["requester"]),
    );
    add("executor node", s(body, &["executor", "node"]));
    add("executor worker", s(body, &["executor", "worker"]));
    add(
        "node receipt digest",
        s(body, &["executor", "receipt_digest"]),
    );
    let cost = s(body, &["settlement", "amount"]).map(|a| {
        format!(
            "{a} {}",
            s(body, &["settlement", "currency"]).unwrap_or_default()
        )
        .trim()
        .to_string()
    });
    add("cost", cost);
    add("settlement", s(body, &["settlement", "status"]));
    add("settled", s(body, &["settlement", "settled_at"]));
    add("started", s(body, &["usage", "started_at"]));
    add("finished", s(body, &["usage", "finished_at"]));
    add("exit code", s(body, &["usage", "exit_code"]));
    if let Some(hashes) = signed_output_hashes(body) {
        add("outputs", Some(format!("{} file(s)", hashes.len())));
        for h in hashes {
            add("  output sha256", Some(h));
        }
    }
    add("trust level (the hub's word)", s(body, &["trust_level"]));
    out
}

fn invalid_fields(body: &Value) -> Vec<String> {
    body.get("invalid_fields")
        .and_then(Value::as_array)
        .map(|a| {
            a.iter()
                .filter_map(|x| x.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default()
}

// ---- CLI --------------------------------------------------------------------

const USAGE: &str =
    "usage: zc verify <receipt-file | receipt-hash | -> [--pubkey <hex|base64>]... [--json]";

#[derive(Debug, Default, PartialEq)]
pub struct Args {
    pub target: Option<String>,
    pub pubkeys: Vec<String>,
    pub json: bool,
    pub help: bool,
}

pub fn parse_args(args: &[String], json: bool) -> Result<Args, String> {
    let mut out = Args {
        json,
        ..Args::default()
    };
    let mut it = args.iter();
    while let Some(a) = it.next() {
        match a.as_str() {
            "-h" | "--help" => out.help = true,
            "--json" => out.json = true,
            "--pubkey" => out
                .pubkeys
                .push(it.next().ok_or("--pubkey needs a key")?.clone()),
            s if s.starts_with("--pubkey=") => out.pubkeys.push(s["--pubkey=".len()..].to_string()),
            "-" => set_target(&mut out, "-")?,
            s if s.starts_with('-') => return Err(format!("unknown argument '{s}'")),
            s => set_target(&mut out, s)?,
        }
    }
    Ok(out)
}

fn set_target(out: &mut Args, t: &str) -> Result<(), String> {
    if out.target.is_some() {
        return Err("one receipt at a time".into());
    }
    out.target = Some(t.to_string());
    Ok(())
}

fn is_hash(s: &str) -> bool {
    s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit())
}

/// A finished check, whatever its outcome, ready to print.
pub struct Outcome {
    pub ok: bool,
    pub error: Option<String>,
    pub verified: Option<Verified>,
    pub source: Option<KeySource>,
    pub warnings: Vec<String>,
}

/// The whole check with its network access injected, so a test covers the
/// logic without a hub.
pub fn check(
    args: &Args,
    stdin: impl FnOnce() -> std::io::Result<String>,
    hub_base: impl Fn() -> String,
) -> Outcome {
    let fail = |e: String, source: Option<KeySource>| Outcome {
        ok: false,
        error: Some(e),
        verified: None,
        source,
        warnings: vec![],
    };
    let Some(target) = args.target.as_deref() else {
        return fail("no receipt given".into(), None);
    };
    let mut hash_asked: Option<String> = None;
    let signed = if target == "-" {
        stdin()
            .map_err(|e| e.to_string())
            .and_then(|t| parse_signed(&t))
    } else if is_hash(target) {
        hash_asked = Some(target.to_ascii_lowercase());
        fetch_receipt(&hub_base(), target).map_err(|e| e.to_string())
    } else {
        std::fs::read_to_string(target)
            .map_err(|e| format!("{target}: {e}"))
            .and_then(|t| parse_signed(&t))
    };
    let signed = match signed {
        Ok(s) => s,
        Err(e) => return fail(e, None),
    };
    let (keys, source) = if args.pubkeys.is_empty() {
        match fetch_pubkeys(&hub_base()) {
            Ok(x) => x,
            Err(e) => return fail(format!("could not get the hub's receipt keys: {e}"), None),
        }
    } else {
        let mut keys = Vec::new();
        for k in &args.pubkeys {
            match TrustedKey::parse(k) {
                Ok(k) => keys.push(k),
                Err(e) => return fail(format!("--pubkey: {e}"), None),
            }
        }
        (keys, KeySource::Given)
    };
    match verify(&signed, &keys) {
        Ok(v) => {
            let mut ok = true;
            let mut error = None;
            if let Some(h) = &hash_asked {
                if &v.receipt_hash != h {
                    ok = false;
                    error = Some("the receipt does not hash to the hash given".into());
                }
            }
            let mut warnings = Vec::new();
            if v.legacy {
                warnings.push(
                    "legacy v1 receipt: signed before domain separation (still valid)".into(),
                );
            }
            let bad = invalid_fields(&v.body);
            if !bad.is_empty() {
                warnings.push(format!(
                    "the hub signed these fields as null because the node's report was malformed: {}",
                    bad.join(", ")
                ));
            }
            Outcome {
                ok,
                error,
                verified: Some(v),
                source: Some(source),
                warnings,
            }
        }
        Err(e) => fail(e.to_string(), Some(source)),
    }
}

pub fn render_json(o: &Outcome) -> Value {
    serde_json::json!({
        "valid": o.ok,
        "error": o.error,
        "receipt_hash": o.verified.as_ref().map(|v| v.receipt_hash.clone()),
        "legacy": o.verified.as_ref().map(|v| v.legacy),
        "signer_kid": o.verified.as_ref().map(|v| v.kid.clone()),
        "key_source": o.source.as_ref().map(|s| match s {
            KeySource::Given => "given".to_string(),
            KeySource::Fetched(_) => "fetched".to_string(),
        }),
        "key_source_detail": o.source.as_ref().map(KeySource::label),
        "trust_level": o.verified.as_ref().and_then(|v| s(&v.body, &["trust_level"])),
        "warnings": o.warnings,
        "receipt": o.verified.as_ref().map(|v| v.body.clone()),
    })
}

pub fn render_text(o: &Outcome) -> String {
    let mut out = String::new();
    match (&o.verified, o.ok) {
        (Some(v), true) => {
            out.push_str(&format!("VALID  receipt {}\n", v.receipt_hash));
            out.push_str(&format!(
                "signer key {} ({})\n",
                v.kid,
                o.source.as_ref().map(KeySource::label).unwrap_or_default()
            ));
            for (k, val) in binds(&v.body) {
                out.push_str(&format!("  {k}: {val}\n"));
            }
        }
        _ => {
            out.push_str(&format!(
                "INVALID  {}\n",
                o.error.as_deref().unwrap_or("not verified")
            ));
            if let Some(src) = &o.source {
                out.push_str(&format!("  keys: {}\n", src.label()));
            }
        }
    }
    for w in &o.warnings {
        out.push_str(&format!("  warning: {w}\n"));
    }
    out
}

/// `zc verify <file | hash | -> [--pubkey …] [--json]` → exit code: 0 only
/// when the receipt verifies.
pub fn run_cli(args: &[String], json: bool) -> i32 {
    let a = match parse_args(args, json) {
        Ok(a) => a,
        Err(e) => {
            eprintln!("zc verify: {e}\n{USAGE}");
            return 2;
        }
    };
    if a.help || a.target.is_none() {
        println!(
            "{USAGE}\n\nVerify a hub receipt offline: the Ed25519 signature over the exact bytes, then what\n\
             it binds. A hash is fetched from the hub; keys come from --pubkey, else from the hub\n\
             (labelled as fetched, not pinned). Exit 0 only when everything verifies."
        );
        return if a.help { 0 } else { 2 };
    }
    let o = check(
        &a,
        || {
            let mut t = String::new();
            std::io::stdin().read_to_string(&mut t)?;
            Ok(t)
        },
        crate::credentials::default_api_url,
    );
    if a.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&render_json(&o)).unwrap_or_default()
        );
    } else if o.ok {
        print!("{}", render_text(&o));
    } else {
        eprint!("{}", render_text(&o));
    }
    if o.ok {
        0
    } else {
        1
    }
}

#[cfg(test)]
pub(crate) mod testkit {
    //! A signer shaped like the hub's, for the verifier's and the outbox's tests.
    use super::*;
    use crate::broker::node_identity::NodeKey;

    pub struct Hub {
        pub key: NodeKey,
    }

    impl Hub {
        pub fn new() -> Self {
            Self {
                key: NodeKey::generate(),
            }
        }

        pub fn trusted(&self) -> TrustedKey {
            TrustedKey::parse(&self.key.public_b64()).unwrap()
        }

        pub fn kid(&self) -> String {
            self.key.fingerprint()
        }

        /// A v2 Spaces-batch receipt over `hashes`, as `(receipt_json, signature)`.
        pub fn batch_receipt(&self, hashes: &[String], amount: &str) -> Signed {
            let mut sorted = hashes.to_vec();
            sorted.sort();
            // Keys sorted, no spaces: what the hub's canonical_json emits.
            let receipt_json = format!(
                concat!(
                    r#"{{"environment":{{"image_digest_commitment":"aa"}},"#,
                    r#""executor":{{"node":"{node}","receipt_digest":"bb","receipt_signature":"cc"}},"#,
                    r#""inputs":{{"count":1}},"invalid_fields":[],"issued_at":"2026-11-10T00:00:00Z","#,
                    r#""issuer":"zakuro-hub","job":{{"attempts":1,"ref":"dd","space":"ee"}},"#,
                    r#""kind":"space_batch","outputs":{{"count":{n},"hashes":{hashes}}},"#,
                    r#""requester":"ff","schema":"zakuro.job_receipt","#,
                    r#""settlement":{{"amount":"{amount}","currency":"JPY","settled_at":"2026-11-10T00:00:05Z","status":"succeeded"}},"#,
                    r#""signer":{{"alg":"ed25519","kid":"{kid}"}},"trust_level":"unattested","#,
                    r#""usage":{{"exit_code":0,"finished_at":"2026-11-10T00:00:04Z","started_at":"2026-11-10T00:00:01Z"}},"v":2}}"#
                ),
                node = "0123456789abcdef",
                n = sorted.len(),
                hashes = serde_json::to_string(&sorted).unwrap(),
                amount = amount,
                kid = self.kid(),
            );
            self.sign(&receipt_json)
        }

        /// A v2 `transaction` receipt for a committed debit, shaped like the
        /// hub's `transaction_body`: `executor.worker` is the fingerprint of
        /// the worker name the debit carried (`worker_fp`), not of a node.
        pub fn transaction_receipt(
            &self,
            worker_name: Option<&str>,
            amount: &str,
            status: &str,
        ) -> Signed {
            self.transaction_receipt_on(None, worker_name, amount, status)
        }

        /// As [`Self::transaction_receipt`], with `executor.node_key` (the
        /// reporting broker's 16-hex fingerprint) when `node_key` is given.
        pub fn transaction_receipt_on(
            &self,
            node_key: Option<&str>,
            worker_name: Option<&str>,
            amount: &str,
            status: &str,
        ) -> Signed {
            let node_key = match node_key {
                Some(k) => format!(r#""node_key":"{k}","#),
                None => String::new(),
            };
            let worker = match worker_name {
                Some(n) => format!("\"{}\"", crate::broker::earn_receipt::worker_fingerprint(n)),
                None => "null".to_string(),
            };
            let receipt_json = format!(
                concat!(
                    r#"{{"executor":{{"node":"0123456789abcdef0123456789abcdef",{node_key}"worker":{worker}}},"#,
                    r#""issued_at":"2026-11-10T00:00:00Z","issuer":"zakuro-hub","#,
                    r#""job":{{"ref":"dd","route":"batch-sync","type":"job_execution"}},"#,
                    r#""kind":"transaction","requester":"ff","schema":"zakuro.job_receipt","#,
                    r#""settlement":{{"amount":"{amount}","currency":"JPY","settled_at":"2026-11-10T00:00:05Z","status":"{status}"}},"#,
                    r#""signer":{{"alg":"ed25519","kid":"{kid}"}},"trust_level":"unattested","#,
                    r#""usage":{{"compute_hours":null,"duration_ms":"1000.0000"}},"#,
                    r#""v":2,"voucher":{{"nonce_digest":null}}}}"#
                ),
                node_key = node_key,
                worker = worker,
                amount = amount,
                status = status,
                kid = self.kid(),
            );
            self.sign(&receipt_json)
        }

        pub fn sign(&self, receipt_json: &str) -> Signed {
            let mut msg = DOMAIN.to_vec();
            msg.extend_from_slice(receipt_json.as_bytes());
            Signed {
                receipt_json: receipt_json.to_string(),
                signature: self.key.sign(&msg),
            }
        }

        /// What `GET /api/receipts/{hash}` serves.
        pub fn public_view(&self, s: &Signed) -> Value {
            serde_json::json!({
                "receipt_hash": sha256_hex(s.receipt_json.as_bytes()),
                "receipt_json": s.receipt_json,
                "signature": s.signature,
            })
        }

        pub fn pubkeys_doc(&self) -> Value {
            serde_json::json!({"alg": "ed25519", "keys": [
                {"kid": self.kid(), "alg": "ed25519", "pubkey": self.key.public_b64(), "current": true}
            ]})
        }
    }
}

#[cfg(test)]
mod tests {
    use super::testkit::Hub;
    use super::*;

    fn h(c: char) -> String {
        c.to_string().repeat(64)
    }

    #[test]
    fn a_hub_receipt_verifies_and_says_what_it_binds() {
        let hub = Hub::new();
        let r = hub.batch_receipt(&[h('b'), h('a')], "50.000000");
        let v = verify(&r, &[hub.trusted()]).unwrap();
        assert!(!v.legacy);
        assert_eq!(v.receipt_hash, sha256_hex(r.receipt_json.as_bytes()));
        let lines = binds(&v.body);
        let get = |k: &str| {
            lines
                .iter()
                .find(|(l, _)| l == k)
                .map(|(_, v)| v.clone())
                .unwrap()
        };
        assert_eq!(get("cost"), "50.000000 JPY");
        assert_eq!(get("trust level (the hub's word)"), "unattested");
        assert_eq!(get("outputs"), "2 file(s)");
        assert_eq!(get("executor node"), "0123456789abcdef");
    }

    #[test]
    fn tampering_with_one_byte_breaks_the_signature() {
        let hub = Hub::new();
        let mut r = hub.batch_receipt(&[h('a')], "50.000000");
        r.receipt_json = r.receipt_json.replace("50.000000", "51.000000");
        assert_eq!(
            verify(&r, &[hub.trusted()]).unwrap_err(),
            VerifyError::BadSignature
        );
    }

    #[test]
    fn a_key_outside_the_set_is_named_not_guessed() {
        let hub = Hub::new();
        let other = Hub::new();
        let r = hub.batch_receipt(&[h('a')], "1.000000");
        let e = verify(&r, &[other.trusted()]).unwrap_err();
        assert!(matches!(e, VerifyError::UnknownKey(k) if k == hub.kid()));
        assert!(verify(&r, &[]).is_err());
    }

    #[test]
    fn a_receipt_signed_without_the_domain_prefix_is_only_a_legacy_v1() {
        let hub = Hub::new();
        let body = hub.batch_receipt(&[h('a')], "1.000000").receipt_json;
        // v2 body, bare-bytes signature: not a receipt.
        let bare = Signed {
            signature: hub.key.sign(body.as_bytes()),
            receipt_json: body.clone(),
        };
        assert_eq!(
            verify(&bare, &[hub.trusted()]).unwrap_err(),
            VerifyError::BadSignature
        );
        // v1 body, bare-bytes signature: accepted and flagged.
        let v1 = body.replace(r#""v":2"#, r#""v":1"#);
        let legacy = Signed {
            signature: hub.key.sign(v1.as_bytes()),
            receipt_json: v1,
        };
        assert!(verify(&legacy, &[hub.trusted()]).unwrap().legacy);
    }

    #[test]
    fn a_voucher_signature_cannot_pass_as_a_receipt() {
        let hub = Hub::new();
        let body = hub.batch_receipt(&[], "1.000000").receipt_json;
        let as_voucher = Signed {
            signature: hub.key.sign(body.as_bytes()), // a voucher: bare JSON
            receipt_json: body,
        };
        assert!(verify(&as_voucher, &[hub.trusted()]).is_err());
    }

    #[test]
    fn output_digests_are_compared_with_the_signed_list() {
        let hub = Hub::new();
        let r = hub.batch_receipt(&[h('b'), h('a')], "1.000000");
        let v = verify(&r, &[hub.trusted()]).unwrap();
        check_output_digests(&v.body, &[h('a'), h('b')]).unwrap();
        assert!(check_output_digests(&v.body, &[h('a')]).is_err(), "missing");
        assert!(
            check_output_digests(&v.body, &[h('a'), h('b'), h('c')]).is_err(),
            "extra"
        );
        assert!(check_output_digests(&v.body, &[h('a'), h('c')]).is_err());
    }

    #[test]
    fn keys_parse_from_hex_and_base64_and_reject_other_lengths() {
        let hub = Hub::new();
        let raw = TrustedKey::parse(&hub.key.public_b64()).unwrap();
        assert_eq!(TrustedKey::parse(&hex::encode(&raw.raw)).unwrap(), raw);
        assert_eq!(raw.kid, hub.kid());
        assert!(TrustedKey::parse("abcd").is_err());
        assert!(TrustedKey::parse(&B64.encode([1u8; 31])).is_err());
    }

    #[test]
    fn plain_http_is_for_loopback_only() {
        assert!(check_hub_url("https://hub.example/").is_ok());
        assert!(check_hub_url("http://127.0.0.1:9").is_ok());
        assert!(check_hub_url("http://hub.example").is_err());
        assert!(check_hub_url("ftp://x").is_err());
    }

    #[test]
    fn args_parse_the_documented_shapes() {
        let v = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        let a = parse_args(
            &v(&["r.json", "--pubkey", "k1", "--pubkey=k2", "--json"]),
            false,
        )
        .unwrap();
        assert_eq!(a.target.as_deref(), Some("r.json"));
        assert_eq!(a.pubkeys, vec!["k1", "k2"]);
        assert!(a.json);
        assert_eq!(
            parse_args(&v(&["-"]), false).unwrap().target.as_deref(),
            Some("-")
        );
        assert!(parse_args(&v(&["a", "b"]), false).is_err());
        assert!(parse_args(&v(&["--nope"]), false).is_err());
    }

    #[test]
    fn check_reads_a_file_and_a_pubkey_and_exits_ok_only_when_valid() {
        let hub = Hub::new();
        let r = hub.batch_receipt(&[h('a')], "5.000000");
        let dir = std::env::temp_dir().join(format!("zc-verify-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("r.json");
        std::fs::write(&file, hub.public_view(&r).to_string()).unwrap();
        let args = Args {
            target: Some(file.display().to_string()),
            pubkeys: vec![hex::encode(&hub.trusted().raw)],
            ..Args::default()
        };
        let o = check(&args, || unreachable!(), || unreachable!("no hub needed"));
        assert!(o.ok, "{:?}", o.error);
        assert!(render_text(&o).starts_with("VALID"));
        assert_eq!(render_json(&o)["key_source"], "given");

        // A different key: INVALID, and the verdict says which key signed.
        let other = Hub::new();
        let args = Args {
            pubkeys: vec![hex::encode(&other.trusted().raw)],
            ..args
        };
        let o = check(&args, || unreachable!(), || unreachable!());
        assert!(!o.ok);
        assert!(render_text(&o).starts_with("INVALID"));
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn check_reads_stdin() {
        let hub = Hub::new();
        let r = hub.batch_receipt(&[], "1.000000");
        let doc = hub.public_view(&r).to_string();
        let args = Args {
            target: Some("-".into()),
            pubkeys: vec![hub.key.public_b64()],
            ..Args::default()
        };
        let o = check(&args, || Ok(doc), || unreachable!());
        assert!(o.ok, "{:?}", o.error);
    }

    /// A one-shot loopback hub serving the receipt routes.
    fn serve(routes: Vec<(String, String)>) -> (String, std::thread::JoinHandle<()>) {
        let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
        let base = format!("http://{}", server.server_addr().to_ip().unwrap());
        let n = routes.len();
        let t = std::thread::spawn(move || {
            for _ in 0..n {
                let req = server.recv().unwrap();
                let body = routes
                    .iter()
                    .find(|(p, _)| p == req.url())
                    .map(|(_, b)| b.clone());
                match body {
                    Some(b) => req.respond(tiny_http::Response::from_string(b)).unwrap(),
                    None => req
                        .respond(tiny_http::Response::from_string("no").with_status_code(404))
                        .unwrap(),
                }
            }
        });
        (base, t)
    }

    #[test]
    fn a_hash_is_fetched_with_keys_from_the_hub_and_labelled_fetched() {
        let hub = Hub::new();
        let r = hub.batch_receipt(&[h('a')], "5.000000");
        let hash = sha256_hex(r.receipt_json.as_bytes());
        let (base, t) = serve(vec![
            (
                format!("/api/receipts/{hash}"),
                hub.public_view(&r).to_string(),
            ),
            (
                "/api/receipts/pubkeys".into(),
                hub.pubkeys_doc().to_string(),
            ),
        ]);
        let args = Args {
            target: Some(hash.clone()),
            ..Args::default()
        };
        let o = check(&args, || unreachable!(), || base.clone());
        t.join().unwrap();
        assert!(o.ok, "{:?}", o.error);
        assert_eq!(render_json(&o)["key_source"], "fetched");
        assert!(render_text(&o).contains("not pinned"));
    }

    #[test]
    fn a_hub_answering_with_another_receipt_is_refused() {
        let hub = Hub::new();
        let asked = hub.batch_receipt(&[h('a')], "5.000000");
        let served = hub.batch_receipt(&[h('b')], "5.000000");
        let hash = sha256_hex(asked.receipt_json.as_bytes());
        let (base, t) = serve(vec![(
            format!("/api/receipts/{hash}"),
            hub.public_view(&served).to_string(),
        )]);
        let args = Args {
            target: Some(hash),
            ..Args::default()
        };
        let o = check(&args, || unreachable!(), || base.clone());
        t.join().unwrap();
        assert!(!o.ok);
        assert!(o.error.unwrap().contains("does not hash to"));
    }
}