evidencebook 0.0.23

Evidence book: records, epistemic types, typed links, retention, disclosure, index classes, request answers and reconcile/close over an embedded Checkpointed Local Log -- a Rust implementation of the Evidence Layer semantics.
Documentation
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
//! A History card stapled to the holder's own message (evidencebook#275):
//! the check a reader runs on a staple it received, as the Go
//! `CheckStaple` and the Python `check_staple` do, and a `history_card/1` or
//! `standard_history/1` staple built from a book.
//!
//! A staple is the holder's own evidence request (subject, derivation,
//! coverage pinned to its newest checkpoint, a fresh nonce) and the signed
//! envelope the holder's book answers it with. It carries `history_card/1`
//! over `checkpoints` or `standard_history/1` over `full_history` and
//! nothing else, so it never carries more than the standard card. Where it
//! sits, and the witness Receipts beside a card, are the carrier's.
//!
//! One departure from Go and Python, stated: for `standard_history/1` this
//! checks that the card has exactly the standard card's members and names
//! its derivation, not the rest of the card's form (SH §6 `card_form`),
//! which has no Rust checker yet. The same holds for `standard_history/3`
//! (a staple of it is read, none is built): a card with the right members
//! and a malformed value passes here where Go and Python refuse it; the
//! result says so (`StapleCheck::card_form_checked` is false). The
//! card's properties are the reader's verifier in every language.

use crate::answer::{self, DERIVATION_HISTORY_CARD, DERIVATION_HISTORY_CARD_2};
use crate::ask::Book;
use crate::canonical::jcs;
use crate::derivation::decode_strict;
use crate::respond::{respond, RespondOptions, Responder, ResponderPolicy, SharePolicy};
use crate::store::CheckpointedLog;
use cll::checkpoint::DecodedCheckpointCose;
use evidence_request::envelope::{parse_reply, Binding, Reply, PROFILE};
use evidence_request::request::{self, Coverage, Derivation, Subject};
use rand_core::{OsRng, RngCore};
use serde_json::json;
use serde_json::Value;
use sha2::{Digest, Sha256};

/// The registered token of the standard card (agent-action-capsule
/// `spec/standard-history-v0.md`).
pub const DERIVATION_STANDARD_HISTORY: &str = "standard_history/1";

/// The registered token of the shelf card (SH §11), which the host counts
/// from a shelf's book facts: [`check_staple`] reads a staple of it, and no
/// book builds one.
pub const DERIVATION_STANDARD_HISTORY_3: &str = "standard_history/3";

/// The standard card's members (SH §4).
const CARD_MEMBERS: [&str; 14] = [
    "anchor",
    "bands",
    "class_missing",
    "controller_class",
    "derivation",
    "disputes",
    "happened",
    "holder_kind",
    "in_window",
    "outcomes",
    "policy",
    "roles",
    "since",
    "window",
];

/// The `standard_history/3` card's members (SH §11), sorted.
const CARD_MEMBERS_3: [&str; 20] = [
    "anchor",
    "bands",
    "class_missing",
    "controller_class",
    "coverage_start",
    "derivation",
    "disputes",
    "happened",
    "holder_kind",
    "in_window",
    "local_times",
    "not_counted",
    "not_honoured",
    "outcomes",
    "policy",
    "remedied",
    "roles",
    "since",
    "unpriced",
    "window",
];

/// What [`check_staple`] read from a staple that passed.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StapleCheck {
    pub derivation: String,
    /// The digest of the holder checkpoint the card is as of.
    pub anchor: String,
    /// The holder's nonce, for the reader's replay check.
    pub nonce: String,
    pub issued_at: String,
    /// The card, in its canonical octets.
    pub artifact: Vec<u8>,
    /// Whether the card's whole form was checked. False for a
    /// `standard_history/1` or `/3` card, of which only the members and the
    /// derivation are checked (the departure in the module doc): a card with
    /// the right members and a malformed value passes with this false, where
    /// Go and Python refuse it. True for a `history_card/1` or `/2`.
    pub card_form_checked: bool,
}

/// Why a staple is refused.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
#[error("staple: {0}")]
pub struct StapleError(String);

fn refuse<T>(why: impl Into<String>) -> Result<T, StapleError> {
    Err(StapleError(why.into()))
}

/// Check that a staple, its request and reply both JSON, is presented by
/// `holder` (lowercase hex Ed25519) and stays inside the cap: the envelope
/// verifies under the holder's key and answers this very request, the
/// derivation and subject are one of the two pairs, and the anchor is the
/// one the request pinned, as is the profile. It does not check the
/// anchor's checkpoint, the card's properties or the nonce's freshness:
/// those are the reader's. A `history_card/1` artifact must have the card's
/// members and nothing else, and end at its anchor; a `history_card/2`
/// artifact passes [`check_history_card_2`].
pub fn check_staple(
    request: &[u8],
    reply: &[u8],
    holder: &str,
) -> Result<StapleCheck, StapleError> {
    let req = match request::parse_json(request) {
        Ok(req) => req,
        Err(e) => return refuse(format!("the request is malformed: {e}")),
    };
    let derivation = match &req.derivation {
        Some(Derivation::Token(t)) => t.as_str(),
        _ => "",
    };
    let capped = matches!(
        (derivation, &req.subject),
        (DERIVATION_HISTORY_CARD, Subject::Checkpoints)
            | (DERIVATION_HISTORY_CARD_2, Subject::Checkpoints)
            | (DERIVATION_STANDARD_HISTORY, Subject::FullHistory)
            | (DERIVATION_STANDARD_HISTORY_3, Subject::FullHistory)
    );
    if !capped {
        return refuse(format!(
            "a staple carries {DERIVATION_HISTORY_CARD} or {DERIVATION_HISTORY_CARD_2} over checkpoints or {DERIVATION_STANDARD_HISTORY} or {DERIVATION_STANDARD_HISTORY_3} over full_history, not {derivation:?}"
        ));
    }
    let (Coverage::ExpectedPin(pin), Some(nonce)) = (&req.coverage, &req.nonce) else {
        return refuse("the request pins its anchor and carries a nonce");
    };
    if nonce.is_empty() {
        return refuse("the request pins its anchor and carries a nonce");
    }
    let e = match parse_reply(reply, Binding::Json) {
        Ok(Reply::Envelope(e)) => e,
        Ok(Reply::Refusal(_)) => return refuse("the reply is a refusal"),
        Err(e) => return refuse(format!("the reply: {e}")),
    };
    if let Err(err) = e.verify() {
        return refuse(format!("the envelope: {err}"));
    }
    if e.responder != holder {
        return refuse("the staple is not presented by its holder");
    }
    if e.request_digest != hex::encode(Sha256::digest(request)) {
        return refuse("the envelope answers another request");
    }
    if e.derivation != req.derivation || e.subject != req.subject {
        return refuse("the envelope signs another derivation or subject");
    }
    if &e.anchor.digest != pin {
        return refuse("the envelope is as of another anchor");
    }
    // `verify` leaves the profile to its caller (profile §3.3 step 5); a
    // request naming none is answered as `evidence-interop/0`.
    let asked = decode_strict(request)
        .ok()
        .and_then(|v| v.get("profile").and_then(Value::as_str).map(str::to_owned))
        .unwrap_or_else(|| PROFILE.to_owned());
    if e.profile != asked {
        return refuse("the envelope names another profile");
    }
    if derivation == DERIVATION_HISTORY_CARD {
        history_card_form(&e.artifact, pin)?;
        history_card_chain(&e.artifact)?;
    }
    if derivation == DERIVATION_HISTORY_CARD_2 {
        check_history_card_2(&e.artifact, pin)?;
    }
    if derivation == DERIVATION_STANDARD_HISTORY || derivation == DERIVATION_STANDARD_HISTORY_3 {
        let members_of: &[&str] = if derivation == DERIVATION_STANDARD_HISTORY_3 {
            &CARD_MEMBERS_3
        } else {
            &CARD_MEMBERS
        };
        let card = match decode_strict(&e.artifact) {
            Ok(card) => card,
            Err(_) => return refuse("the stapled card is not JSON"),
        };
        let Some(members) = card.as_object() else {
            return refuse("the stapled card is not an object");
        };
        let mut names: Vec<&str> = members.keys().map(String::as_str).collect();
        names.sort_unstable();
        if names != members_of || members["derivation"] != derivation {
            return refuse("the stapled card is not the standard card's members");
        }
    }
    Ok(StapleCheck {
        derivation: derivation.to_owned(),
        anchor: pin.clone(),
        nonce: nonce.clone(),
        issued_at: e.issued_at.clone(),
        artifact: e.artifact.clone(),
        card_form_checked: derivation != DERIVATION_STANDARD_HISTORY
            && derivation != DERIVATION_STANDARD_HISTORY_3,
    })
}

/// A `history_card/1` artifact (ER §8.1) with the card's members and nothing
/// else, as Go's `historyCardForm` checks it: anchor, derivation,
/// evidence_stream, history and subject; each history entry exactly a
/// checkpoint and the consistency proof from the one before (null for the
/// first), as lowercase hex; the last checkpoint is the anchor. No signature
/// or proof is checked here: `history_card_chain` does.
fn history_card_form(artifact: &[u8], anchor: &str) -> Result<(), StapleError> {
    let bad = |why: &str| StapleError(format!("the stapled history_card/1 {why}"));
    let hex_text = |v: &Value| {
        v.as_str().is_some_and(|s| {
            !s.is_empty()
                && s.len() % 2 == 0
                && s.bytes().all(|c| matches!(c, b'0'..=b'9' | b'a'..=b'f'))
        })
    };
    // A duplicate member is refused, as Go's DecodeJSON and Python's
    // strict_json refuse it; serde_json would keep the last one.
    let card = decode_strict(artifact).map_err(|_| bad("is not a JSON object"))?;
    let Some(members) = card.as_object() else {
        return Err(bad("is not a JSON object"));
    };
    let mut names: Vec<&str> = members.keys().map(String::as_str).collect();
    names.sort_unstable();
    if names
        != [
            "anchor",
            "derivation",
            "evidence_stream",
            "history",
            "subject",
        ]
    {
        return Err(bad("has members other than the card's"));
    }
    let stream_ok = members["evidence_stream"]
        .as_str()
        .is_some_and(|s| !s.is_empty());
    if members["derivation"] != DERIVATION_HISTORY_CARD
        || members["anchor"] != anchor
        || !stream_ok
        || members["subject"] != serde_json::json!({"checkpoints": null})
    {
        return Err(bad(
            "does not name its derivation, anchor, stream and subject",
        ));
    }
    let history = match members["history"].as_array() {
        Some(h) if !h.is_empty() => h,
        _ => return Err(bad("has no history")),
    };
    for (i, entry) in history.iter().enumerate() {
        let Some(entry) = entry.as_object() else {
            return Err(bad(&format!(
                "entry {i} has members other than a checkpoint and its consistency proof"
            )));
        };
        let mut names: Vec<&str> = entry.keys().map(String::as_str).collect();
        names.sort_unstable();
        if names != ["checkpoint", "consistency_from_previous"] {
            return Err(bad(&format!(
                "entry {i} has members other than a checkpoint and its consistency proof"
            )));
        }
        let proof = &entry["consistency_from_previous"];
        if !hex_text(&entry["checkpoint"])
            || proof.is_null() != (i == 0)
            || (i > 0 && !hex_text(proof))
        {
            return Err(bad(&format!(
                "entry {i} is not a hex checkpoint with its consistency proof"
            )));
        }
    }
    let last = history[history.len() - 1]["checkpoint"]
        .as_str()
        .unwrap_or_default();
    let raw = hex::decode(last).map_err(|_| bad("does not end at its anchor"))?;
    if hex::encode(Sha256::digest(raw)) != anchor {
        return Err(bad("does not end at its anchor"));
    }
    Ok(())
}

/// The card's checkpoints form one chain, as Go's `historyCardChain`
/// checks it: every checkpoint signed under the key of the first, one log,
/// each entry's signed `prev_size` and `prev_root` the one before's size and
/// root, the log growing, and each consistency proof (`[tree-size-1,
/// tree-size-2, consistency-paths, right-peaks]`) reaching the next
/// commitment. The checkpoint key is the reader's to judge, so the first
/// checkpoint names it. The form is already checked.
fn history_card_chain(artifact: &[u8]) -> Result<(), StapleError> {
    let bad = |i: usize, why: &str| {
        StapleError(format!(
            "the stapled history_card/1's checkpoints are not one chain: entry {i} {why}"
        ))
    };
    let card = decode_strict(artifact).map_err(|_| bad(0, "is unreadable"))?;
    let history = card["history"].as_array().map_or(&[][..], Vec::as_slice);
    let mut previous: Option<DecodedCheckpointCose> = None;
    let mut key = String::new();
    for (i, entry) in history.iter().enumerate() {
        let statement = hex::decode(entry["checkpoint"].as_str().unwrap_or_default())
            .map_err(|_| bad(i, "is not hex"))?;
        // The strict signature check comes first (#108).
        if !crate::ed25519::statement_verifies(&statement) {
            return Err(bad(i, "has a checkpoint that does not verify"));
        }
        let verified = cll::checkpoint::verify_checkpoint_cose_offline(&statement);
        let cp = match verified.decoded {
            Some(cp) if verified.ok => cp,
            _ => return Err(bad(i, "has a checkpoint that does not verify")),
        };
        if i == 0 {
            key = cp.key_id.clone();
        } else if cp.key_id != key {
            return Err(bad(i, "is signed by another key than the first checkpoint"));
        }
        if let Some(prev) = &previous {
            if cp.log_id != prev.log_id || cp.mmr_size <= prev.mmr_size {
                return Err(bad(i, "does not extend the log"));
            }
            if cp.prev_size != prev.mmr_size || cp.prev_root != prev.root {
                return Err(bad(
                    i,
                    "has a signed prev_size and prev_root that are not the previous checkpoint's",
                ));
            }
            let proof = hex::decode(
                entry["consistency_from_previous"]
                    .as_str()
                    .unwrap_or_default(),
            )
            .map_err(|_| bad(i, "has a consistency proof that is not hex"))?;
            if !consistency_holds(prev, &cp, &proof) {
                return Err(bad(i, "has a consistency proof that does not verify"));
            }
        }
        previous = Some(cp);
    }
    Ok(())
}

/// A `history_card/2` artifact (ER -03 §8.1.2): the card's members and
/// nothing else, then the seven ordered checks, which are
/// `evidence_request::cll_material::check_history_card_2`'s, as Go's
/// `CheckHistoryCard2` runs them. The key every checkpoint must be signed by
/// is the first checkpoint's, which the reader judges; which receipts count
/// is the requester's policy.
pub fn check_history_card_2(artifact: &[u8], anchor: &str) -> Result<(), StapleError> {
    let bad = |why: &str| StapleError(format!("the history_card/2 {why}"));
    let card = decode_strict(artifact).map_err(|_| bad("is not a JSON object"))?;
    let Some(members) = card.as_object() else {
        return Err(bad("is not a JSON object"));
    };
    let mut names: Vec<&str> = members.keys().map(String::as_str).collect();
    names.sort_unstable();
    if names
        != [
            "anchor",
            "derivation",
            "evidence_stream",
            "history",
            "subject",
            "window",
        ]
    {
        return Err(bad("has members other than the card's"));
    }
    let stream_ok = members["evidence_stream"]
        .as_str()
        .is_some_and(|s| !s.is_empty());
    let subject_ok = members["subject"] == serde_json::json!({"checkpoints": null})
        || members["subject"] == serde_json::json!({"full_history": null});
    if members["derivation"] != DERIVATION_HISTORY_CARD_2
        || members["anchor"] != anchor
        || !stream_ok
        || !subject_ok
    {
        return Err(bad(
            "does not name its derivation, anchor, stream and subject",
        ));
    }
    // The profile's entry has these members and no other.
    for (i, entry) in members["history"]
        .as_array()
        .map_or(&[][..], Vec::as_slice)
        .iter()
        .enumerate()
    {
        let mut names: Vec<&str> = entry
            .as_object()
            .map_or(Vec::new(), |m| m.keys().map(String::as_str).collect());
        names.sort_unstable();
        if names
            != [
                "checkpoint",
                "consistency_from_previous",
                "position",
                "receipts",
            ]
        {
            return Err(bad(&format!(
                "entry {i} has members other than a position, checkpoint, receipts and consistency proof"
            )));
        }
    }
    let first_key = members["history"][0]["checkpoint"]
        .as_str()
        .and_then(|h| hex::decode(h).ok())
        .and_then(|raw| {
            let verified = cll::checkpoint::verify_checkpoint_cose_offline(&raw);
            verified.decoded.map(|cp| cp.key_id)
        })
        .unwrap_or_default();
    match evidence_request::cll_material::check_history_card_2(&card, anchor, &[first_key]) {
        None => Ok(()),
        Some(finding) => Err(bad(&format!("fails {finding}"))),
    }
}

/// Whether `proof` (consistency-proof octets, deterministic CBOR) shows
/// `next`'s commitment extends `prev`'s.
fn consistency_holds(
    prev: &DecodedCheckpointCose,
    next: &DecodedCheckpointCose,
    proof: &[u8],
) -> bool {
    use ciborium::value::Value as Cbor;
    // One item and nothing after it, as Go's strict CBOR decoder reads it.
    let mut rest = proof;
    let Ok(Cbor::Array(parts)) = ciborium::from_reader::<Cbor, _>(&mut rest) else {
        return false;
    };
    if !rest.is_empty() {
        return false;
    }
    let hashes = |v: &Cbor| -> Option<Vec<Vec<u8>>> {
        match v {
            Cbor::Array(items) => items
                .iter()
                .map(|i| match i {
                    Cbor::Bytes(b) => Some(b.clone()),
                    _ => None,
                })
                .collect(),
            _ => None,
        }
    };
    let size = |v: &Cbor| match v {
        Cbor::Integer(n) => u64::try_from(*n).ok(),
        _ => None,
    };
    let [size1, size2, paths, right] = parts.as_slice() else {
        return false;
    };
    let (Some(size1), Some(size2), Some(right), Cbor::Array(paths)) =
        (size(size1), size(size2), hashes(right), paths)
    else {
        return false;
    };
    if size1 != prev.mmr_size || size2 != next.mmr_size {
        return false;
    }
    let new_peaks = &next.new_peak_hashes;
    if right.len() > new_peaks.len()
        || !new_peaks[new_peaks.len() - right.len()..]
            .iter()
            .zip(&right)
            .all(|(a, b)| a.as_slice() == b.as_slice())
    {
        return false;
    }
    let Some(witness) = paths
        .iter()
        .map(|p| hashes(p).map(|h| h.iter().map(hex::encode).collect::<Vec<_>>()))
        .collect::<Option<Vec<_>>>()
    else {
        return false;
    };
    let (Ok(old_root), Ok(new_root)) = (hex_hash(&prev.root), hex_hash(&next.root)) else {
        return false;
    };
    let proof = cll::mmr::ConsistencyProof {
        v: 1,
        kind: "consistency".to_owned(),
        size_a: size1,
        size_b: size2,
        old_peaks: prev.new_peak_hashes.iter().map(hex::encode).collect(),
        witness,
        new_peaks: new_peaks.iter().map(hex::encode).collect(),
    };
    cll::mmr::verify_consistency(&old_root, size1, &new_root, size2, &proof)
}

fn hex_hash(s: &str) -> Result<cll::mmr::Hash, ()> {
    hex::decode(s).map_err(|_| ())?.try_into().map_err(|_| ())
}

/// A staple as built: the holder's own request and the reply its book
/// answered it with, both JSON.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Staple {
    pub request: Vec<u8>,
    pub reply: Vec<u8>,
}

/// Build a `history_card/1` staple from `book`, as of its newest checkpoint
/// (cut now if the book grew past it), as Go's `Book.Staple` does. A public
/// card grows no record.
pub fn staple_history_card<B: Book + CheckpointedLog>(
    book: &mut B,
    responder: &Responder<'_>,
) -> Result<Staple, StapleError> {
    staple_of(book, responder, DERIVATION_HISTORY_CARD)
}

/// Build a `history_card/2` staple from `book`, as of its newest checkpoint,
/// as Go's `Book.Staple` does. A public card grows no record.
pub fn staple_history_card_2<B: Book + CheckpointedLog>(
    book: &mut B,
    responder: &Responder<'_>,
) -> Result<Staple, StapleError> {
    staple_of(book, responder, DERIVATION_HISTORY_CARD_2)
}

/// Build a `standard_history/1` staple from `book`, as Go's `Book.Staple`
/// does: the holder asks its own book as its own authenticated requester, so
/// the answer is sealed as an `evidence_request_answered` record and the
/// responder needs a [`StandardHistorySource`](crate::standard_history::StandardHistorySource).
/// A responder without one refuses its own request.
pub fn staple_standard_history<B: Book + CheckpointedLog>(
    book: &mut B,
    responder: &Responder<'_>,
) -> Result<Staple, StapleError> {
    staple_of(book, responder, DERIVATION_STANDARD_HISTORY)
}

fn staple_of<B: Book + CheckpointedLog>(
    book: &mut B,
    responder: &Responder<'_>,
    derivation: &str,
) -> Result<Staple, StapleError> {
    let fail = |e: &dyn std::fmt::Display| StapleError(e.to_string());
    let covered = answer::anchors(book)
        .map_err(|e| fail(&e))?
        .last()
        .map(|a| a.size);
    let leaves = book.leaf_count().map_err(|e| fail(&e))?;
    if covered != Some(leaves) {
        book.checkpoint().map_err(|e| fail(&e))?;
    }
    let Some(newest) = book.stated_checkpoints().map_err(|e| fail(&e))?.pop() else {
        return refuse("the book has no checkpoint to staple");
    };
    let mut nonce = [0u8; 16];
    OsRng.fill_bytes(&mut nonce);
    let subject = if derivation == DERIVATION_STANDARD_HISTORY {
        json!({"full_history": null})
    } else {
        json!({"checkpoints": null})
    };
    let request = jcs(&json!({
        "coverage": {"expected_pin": answer::anchor_digest(&newest)},
        "derivation": derivation,
        "nonce": hex::encode(nonce),
        "profile": PROFILE,
        "subject": subject,
    }))
    .map_err(|e| fail(&e))?;
    // The holder answers itself; standard_history/1 is answered only to an
    // authenticated requester.
    let holder = hex::encode(responder.signer.verifying_key().to_bytes());
    let opts = RespondOptions {
        authenticated_requester: (derivation == DERIVATION_STANDARD_HISTORY).then_some(&holder),
        policy: SharePolicy::default(),
    };
    // The holder's own request is not counted by the limiter, which is for
    // askers; the rest of the caller's policy applies.
    let own = ResponderPolicy {
        refusal_policy: responder.policy.refusal_policy,
        limiter: None,
        max_request_bytes: responder.policy.max_request_bytes,
        max_answer_items: responder.policy.max_answer_items,
        history_window: responder.policy.history_window,
    };
    let responder = Responder {
        signer: responder.signer,
        derivations: responder.derivations,
        policy: &own,
        standard_history: responder.standard_history,
    };
    let (reply, _) =
        respond(book, &responder, &request, Binding::Json, &opts).map_err(|e| fail(&e))?;
    if !matches!(parse_reply(&reply, Binding::Json), Ok(Reply::Envelope(_))) {
        return refuse(format!("the book refused its own {derivation} request"));
    }
    Ok(Staple { request, reply })
}

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

    #[derive(serde::Deserialize)]
    struct Vector {
        name: String,
        holder: String,
        request: String,
        reply: String,
        pass: bool,
        /// Go and Python refuse it; Rust passes it, with `card_form_checked`
        /// false (it checks a standard card's members, not its values).
        #[serde(default)]
        members_only: bool,
        #[serde(default)]
        nonce: String,
        #[serde(default)]
        anchor: String,
    }

    /// The vectors Go writes (testdata/staple/staples.json).
    #[test]
    fn agrees_with_the_go_vectors() {
        let path = concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../testdata/staple/staples.json"
        );
        let vectors: Vec<Vector> =
            serde_json::from_slice(&std::fs::read(path).expect("vectors")).expect("parse");
        assert!(vectors.len() >= 2);
        for v in vectors {
            let got = check_staple(v.request.as_bytes(), v.reply.as_bytes(), &v.holder);
            assert_eq!(got.is_ok(), v.pass, "{}: {got:?}", v.name);
            if let Ok(c) = got {
                let standard = c.derivation == DERIVATION_STANDARD_HISTORY;
                assert_eq!(c.card_form_checked, !standard, "{}", v.name);
                assert_eq!((c.nonce, c.anchor), (v.nonce, v.anchor), "{}", v.name);
            }
        }
    }

    /// The `history_card/2` vectors Go writes (testdata/history-card-2).
    #[test]
    fn agrees_with_the_go_history_card_2_vectors() {
        let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../testdata/history-card-2");
        let vectors: Vec<Vector> =
            serde_json::from_slice(&std::fs::read(format!("{dir}/staples.json")).unwrap()).unwrap();
        assert!(vectors.len() >= 10);
        for v in vectors {
            let got = check_staple(v.request.as_bytes(), v.reply.as_bytes(), &v.holder);
            assert_eq!(got.is_ok(), v.pass, "{}: {got:?}", v.name);
            if let Ok(c) = got {
                assert_eq!((c.nonce, c.anchor), (v.nonce, v.anchor), "{}", v.name);
            }
        }
    }

    /// The `standard_history/3` vectors Go writes (testdata/staple-3).
    #[test]
    fn agrees_with_the_go_standard_history_3_vectors() {
        let path = concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../testdata/staple-3/staples.json"
        );
        let vectors: Vec<Vector> =
            serde_json::from_slice(&std::fs::read(path).expect("vectors")).expect("parse");
        assert!(vectors.len() >= 6);
        for v in vectors {
            let got = check_staple(v.request.as_bytes(), v.reply.as_bytes(), &v.holder);
            assert_eq!(got.is_ok(), v.pass || v.members_only, "{}: {got:?}", v.name);
            if let Ok(c) = got {
                assert_eq!(
                    (c.derivation.as_str(), c.nonce, c.anchor),
                    (DERIVATION_STANDARD_HISTORY_3, v.nonce, v.anchor),
                    "{}",
                    v.name
                );
                // The departure is in the result, never a plain pass.
                assert!(!c.card_form_checked, "{}", v.name);
            }
        }
    }

    #[test]
    fn card_members_are_sorted() {
        let mut sorted = CARD_MEMBERS;
        sorted.sort_unstable();
        assert_eq!(sorted, CARD_MEMBERS);
        let mut sorted = CARD_MEMBERS_3;
        sorted.sort_unstable();
        assert_eq!(sorted, CARD_MEMBERS_3);
    }
}