monetize-embed 0.3.1

The thin client a monetized product compiles in: an Ed25519-verified entitlement cache with nanosecond verdicts that keeps answering while the licence server is unreachable. No network, no ledger β€” the product feeds it signed facts and asks.
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
//! **The one canonical form** an entitlement is signed over, and the verify side.
//!
//! Signing lives in `monetize` (it has the key); verifying lives here because a product
//! must check a fact without linking the core (redb, vendors). Core depends on this
//! crate for [`fact_message`] so there is exactly one canonical form.
//!
//! Canonical JSON: the fact's fields minus `signature`, objects with keys sorted
//! bytewise, no whitespace. `serde_json`'s map is sorted by default but that is a cargo
//! feature (`preserve_order`) any crate in the build could flip, so the sort is done
//! here, explicitly, and does not depend on it.

use ed25519_dalek::{Signature, Verifier, VerifyingKey};
use monetize_product::EntitlementFact;
use serde_json::Value;

/// A signed set of facts, the file monetize hands a product so it can start (or
/// restart) with the full picture before any push arrives.
#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
pub struct Snapshot {
    /// Monotonic: a cache refuses a snapshot older than the one it holds (replay).
    pub issued_unix_ms: u64,
    pub facts: Vec<EntitlementFact>,
    /// Ed25519 over [`snapshot_message`], by monetize's key.
    pub signature: Vec<u8>,
}

#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum SignatureError {
    #[error("signature is not 64 bytes")]
    Malformed,
    #[error("signature does not verify for tenant {0}")]
    Fact(String),
    /// The fact's ISSUE TIME is not signed by the same key, or the fact carries
    /// one half of the stamp without the other. Told apart from [`Self::Fact`]
    /// on purpose: the six fields were genuine and the monotonic half was not,
    /// which is a tampering attempt with a different shape and a different
    /// remedy from a wholly forged fact.
    #[error("the issue time on the fact for tenant {0} is not signed by the same key")]
    Issued(String),
    #[error("snapshot envelope signature does not verify")]
    Envelope,
    #[error("go-ahead signature does not verify for nonce {0}")]
    GoAhead(String),
    /// An actor ticket was refused. The string is the OPERATOR's reason and may
    /// name the ticket's own fields; see `crate::ticket::verify_ticket` for why
    /// none of them is a customer's to read.
    #[error("the actor ticket was refused: {0}")]
    Ticket(String),
    /// A shop's go-ahead to grow a sold estate's data does not verify.
    #[error("the shop's growth go-ahead for {0} does not verify")]
    Growth(String),
    /// A sold estate's call to its shop is not signed by the estate's key.
    #[error("the call is not signed by {0}'s key")]
    Call(String),
}

/// Write `value` as canonical JSON: keys sorted, no whitespace.
pub fn canonical_json(value: &Value, out: &mut String) {
    match value {
        Value::Object(map) => {
            let mut keys: Vec<&String> = map.keys().collect();
            keys.sort();
            out.push('{');
            for (i, k) in keys.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                // A key is a string: written as the JSON string serde_json writes for it.
                out.push_str(&Value::String((*k).clone()).to_string());
                out.push(':');
                canonical_json(&map[*k], out);
            }
            out.push('}');
        }
        Value::Array(items) => {
            out.push('[');
            for (i, v) in items.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                canonical_json(v, out);
            }
            out.push(']');
        }
        other => out.push_str(&other.to_string()),
    }
}

/// Canonical JSON of the fact with `drop` removed. The ONE writer of a fact's
/// signed bytes; the two forms below differ only in what they drop, so they
/// cannot drift apart.
fn fact_form(fact: &EntitlementFact, drop: &[&str]) -> Vec<u8> {
    let mut v = serde_json::to_value(fact).expect("fact serializes");
    let object = v.as_object_mut().expect("fact is an object");
    for key in drop {
        object.remove(*key);
    }
    let mut s = String::new();
    canonical_json(&v, &mut s);
    s.into_bytes()
}

/// **The V1 form**: every field except `signature`, `issued_unix_ms` and
/// `issued_signature`.
///
/// This is byte for byte what it was before the issue time existed, and it must
/// stay that way for ever: it is the form an appliance built before 2026-09-17
/// computes from the seven proto fields it knows, and every fact ever signed
/// carries a signature over it. Adding the issue time HERE instead of in a
/// second form would have invalidated every one of them at once.
pub fn fact_message(fact: &EntitlementFact) -> Vec<u8> {
    fact_form(fact, &["signature", "issued_unix_ms", "issued_signature"])
}

/// **The V2 form**: [`fact_message`] plus `issued_unix_ms`. What
/// [`EntitlementFact::issued_signature`] covers, and the reason the issue time
/// cannot be added, moved or bumped by anyone but monetize.
pub fn fact_message_issued(fact: &EntitlementFact) -> Vec<u8> {
    fact_form(fact, &["signature", "issued_signature"])
}

/// The bytes a snapshot's envelope signature covers. The facts inside keep their own
/// signatures (they are part of the message), so a snapshot vouches for the *set*.
pub fn snapshot_message(issued_unix_ms: u64, facts: &[EntitlementFact]) -> Vec<u8> {
    let v = serde_json::json!({ "issued_unix_ms": issued_unix_ms, "facts": facts });
    let mut s = String::new();
    canonical_json(&v, &mut s);
    s.into_bytes()
}

pub(crate) fn check(key: &VerifyingKey, msg: &[u8], sig: &[u8]) -> Result<bool, SignatureError> {
    let sig = Signature::from_slice(sig).map_err(|_| SignatureError::Malformed)?;
    Ok(key.verify(msg, &sig).is_ok())
}

/// **Both halves.** The V1 signature always, and the V2 signature whenever the
/// fact carries an issue time.
///
/// The two are checked together and never apart, which is what stops the issue
/// time being editable in transit. Three shapes are refused here and not later:
///
/// * a stamped fact whose `issued_signature` does not verify β€” someone ADDED or
///   BUMPED an issue time. Bumping matters as much as adding: a fact stamped
///   far in the future would latch a product's high-water mark past every
///   legitimate fact monetize will ever mint for that tenant, which is a lasting
///   denial of service dressed as a plan change;
/// * `issued_signature` with no `issued_unix_ms`, and
/// * `issued_unix_ms` with no `issued_signature` β€” an unsigned issue time is not
///   a weaker fact, it is a forged one.
pub fn verify_fact(fact: &EntitlementFact, key: &VerifyingKey) -> Result<(), SignatureError> {
    if !check(key, &fact_message(fact), &fact.signature)? {
        return Err(SignatureError::Fact(fact.tenant.0.clone()));
    }
    match (fact.issued_unix_ms, fact.issued_signature.is_empty()) {
        // Unstamped: a fact signed before the issue time existed. Legal.
        (None, true) => Ok(()),
        (Some(_), false) => {
            if check(key, &fact_message_issued(fact), &fact.issued_signature)? {
                Ok(())
            } else {
                Err(SignatureError::Issued(fact.tenant.0.clone()))
            }
        }
        (None, false) | (Some(_), true) => Err(SignatureError::Issued(fact.tenant.0.clone())),
    }
}

/// Envelope first, then every fact: one forged fact rejects the whole snapshot.
pub fn verify_snapshot(snap: &Snapshot, key: &VerifyingKey) -> Result<(), SignatureError> {
    if !check(key, &snapshot_message(snap.issued_unix_ms, &snap.facts), &snap.signature)? {
        return Err(SignatureError::Envelope);
    }
    snap.facts.iter().try_for_each(|f| verify_fact(f, key))
}

// ── the growth go-ahead (`DATA-SET-GROWTH-FLOW.md` D3 / T14) ───────────────

/// **The go-ahead a data-set growth is started on**, as gunnar's
/// `gunnar_server::grow::go_ahead::GoAhead` parses it:
///
/// ```json
/// {"v":1,"signer":"monetize","target_sectors":<u64>,"nonce":"<one line ≀256 B>",
///  "issued_unix_ms":<i64>,"signature":"<base64, standard alphabet, padded>"}
/// ```
///
/// The signature is Ed25519 by monetize's signing key over
/// [`go_ahead_message`]: the canonical JSON (keys sorted bytewise, no
/// whitespace) of the object MINUS `signature` β€” the same form and the same
/// key an [`EntitlementFact`] is signed with, so a metered gunnar verifies it
/// with the `--monetize-pubkey` it already holds. gunnar checks the structure
/// (`v`, a known `signer`, a non-empty nonce, `target_sectors` equal to the
/// request's, the nonce unspent on that box); a `monetize` policy plugged into
/// its `GoAheadPolicy` calls [`verify_go_ahead`].
#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
pub struct GoAhead {
    pub v: u32,
    pub signer: String,
    pub target_sectors: u64,
    pub nonce: String,
    pub issued_unix_ms: i64,
    #[serde(default)]
    pub signature: String,
}

/// The signer word a monetize-minted go-ahead carries.
pub const GO_AHEAD_SIGNER_MONETIZE: &str = "monetize";

/// The bytes a go-ahead's signature covers: every field except `signature`,
/// canonical.
pub fn go_ahead_message(go: &GoAhead) -> Vec<u8> {
    let mut v = serde_json::to_value(go).expect("go-ahead serializes");
    v.as_object_mut().expect("go-ahead is an object").remove("signature");
    let mut s = String::new();
    canonical_json(&v, &mut s);
    s.into_bytes()
}

/// Parse the bytes handed on the wire and verify the signature under `key`.
/// Structure first (so a refusal names what is wrong), then the signature.
pub fn verify_go_ahead(bytes: &[u8], key: &VerifyingKey) -> Result<GoAhead, SignatureError> {
    let go: GoAhead = serde_json::from_slice(bytes).map_err(|_| SignatureError::Malformed)?;
    if go.v != 1 || go.signer != GO_AHEAD_SIGNER_MONETIZE || go.nonce.trim().is_empty() {
        return Err(SignatureError::Malformed);
    }
    let sig = base64_decode(&go.signature).ok_or(SignatureError::Malformed)?;
    if check(key, &go_ahead_message(&go), &sig)? {
        Ok(go)
    } else {
        Err(SignatureError::GoAhead(go.nonce.clone()))
    }
}

const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

/// Standard base64, padded β€” the alphabet `GoAhead.signature` is written in.
/// Twenty lines here rather than a dependency the two crates that need it
/// (this one and `monetize`) would otherwise add for one field.
pub fn base64_encode(bytes: &[u8]) -> String {
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for chunk in bytes.chunks(3) {
        let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)];
        let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
        out.push(B64[(n >> 18) as usize & 63] as char);
        out.push(B64[(n >> 12) as usize & 63] as char);
        out.push(if chunk.len() > 1 { B64[(n >> 6) as usize & 63] as char } else { '=' });
        out.push(if chunk.len() > 2 { B64[n as usize & 63] as char } else { '=' });
    }
    out
}

/// The inverse; `None` on anything that is not padded standard base64.
pub fn base64_decode(text: &str) -> Option<Vec<u8>> {
    let text = text.trim();
    if text.len() % 4 != 0 {
        return None;
    }
    let val = |c: u8| B64.iter().position(|b| *b == c).map(|p| p as u32);
    let mut out = Vec::with_capacity(text.len() / 4 * 3);
    for chunk in text.as_bytes().chunks(4) {
        let pad = chunk.iter().rev().take_while(|c| **c == b'=').count();
        if pad > 2 || chunk[..4 - pad].contains(&b'=') {
            return None;
        }
        let mut n = 0u32;
        for (i, c) in chunk.iter().enumerate() {
            let v = if i >= 4 - pad { 0 } else { val(*c)? };
            n = (n << 6) | v;
        }
        out.push((n >> 16) as u8);
        if pad < 2 {
            out.push((n >> 8) as u8);
        }
        if pad < 1 {
            out.push(n as u8);
        }
    }
    Some(out)
}

// ── a sold estate grows through its shop (one shop, 2026-10-07) ───────────

/// **The shop's go-ahead to grow a sold estate's data**: what the shop sold
/// (main's data GB per disk), for which estate, until when. The shop's
/// monetize signs it with its fact key once the step is paid; the estate
/// pulls it in a `grow_go_ahead` order (G16-d; no estate runs a monetize) and verifies it under the ONE monetize's
/// public key, fed at install, before its growth runs:
///
/// ```json
/// {"v":1,"signer":"shop","estate":"acme","main_data_gib_per_member":25,
///  "until_unix_ms":<i64>,"reference":"estate/acme/change-2",
///  "issued_unix_ms":<i64>,"signature":"<base64, standard alphabet, padded>"}
/// ```
///
/// Signed as [`GoAhead`] is: Ed25519 over the canonical JSON of every field
/// but `signature`.
#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
pub struct EstateGrowth {
    pub v: u32,
    pub signer: String,
    /// The estate's company name (`acme` of `acme.gunnar.rs`).
    pub estate: String,
    /// GB per data disk on main, as paid. The twin's data disk holds them all.
    pub main_data_gib_per_member: u64,
    /// The go-ahead is good until then: the end of the period it was paid for.
    pub until_unix_ms: i64,
    /// The shop's order reference the step was paid on.
    pub reference: String,
    pub issued_unix_ms: i64,
    #[serde(default)]
    pub signature: String,
}

/// The signer word a shop-minted growth go-ahead carries.
pub const GROWTH_SIGNER_SHOP: &str = "shop";

/// The bytes an [`EstateGrowth`]'s signature covers.
pub fn estate_growth_message(g: &EstateGrowth) -> Vec<u8> {
    let mut v = serde_json::to_value(g).expect("a growth go-ahead serializes");
    v.as_object_mut().expect("a growth go-ahead is an object").remove("signature");
    let mut s = String::new();
    canonical_json(&v, &mut s);
    s.into_bytes()
}

/// Parse the bytes and verify them under the shop's `key`. Structure first,
/// then the signature. Expiry is the caller's: it holds the clock.
pub fn verify_estate_growth(bytes: &[u8], key: &VerifyingKey) -> Result<EstateGrowth, SignatureError> {
    let g: EstateGrowth = serde_json::from_slice(bytes).map_err(|_| SignatureError::Malformed)?;
    if g.v != 1 || g.signer != GROWTH_SIGNER_SHOP || g.estate.trim().is_empty() || g.main_data_gib_per_member == 0 {
        return Err(SignatureError::Malformed);
    }
    let sig = base64_decode(&g.signature).ok_or(SignatureError::Malformed)?;
    if check(key, &estate_growth_message(&g), &sig)? {
        Ok(g)
    } else {
        Err(SignatureError::Growth(g.estate.clone()))
    }
}

/// **A sold estate's call to its shop** (`SoldEstate.Recharge`, `Upgrade`, `TakeMaterial`,
/// `UpdateTake`, `UpdateReport`): what is asked, by which estate, when. The estate's
/// monetize signs it with the client key minted for it at install (kept in
/// the shop's custody); the shop verifies it under the key's public half,
/// recorded on the order. A call is fresh for [`CALL_FRESH_MS`] either side of
/// the shop's clock.
#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
pub struct EstateCall {
    pub v: u32,
    /// `grow-go-ahead` | `grow-set`.
    pub call: String,
    pub estate: String,
    /// `grow-set`: the data disks to size, by the estate's own names.
    #[serde(default)]
    pub members: Vec<String>,
    /// `grow-set`: GB each member is sized to.
    #[serde(default)]
    pub gib: u64,
    pub at_unix_ms: i64,
    /// `recharge` (F4, 2026-10-09): what the call carries besides its words β€” the seed a
    /// recharged box is laid with β€” so the signature covers it. Empty, and then absent from the
    /// canonical JSON, on every other call: their signatures are as before.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub carries: String,
}

/// How far a call's time may be from the shop's clock.
pub const CALL_FRESH_MS: i64 = 5 * 60 * 1000;

/// The bytes an [`EstateCall`]'s signature covers: its canonical JSON.
pub fn estate_call_message(c: &EstateCall) -> Vec<u8> {
    let v = serde_json::to_value(c).expect("an estate call serializes");
    let mut s = String::new();
    canonical_json(&v, &mut s);
    s.into_bytes()
}

/// Verify a call's `signature` under the estate's client `key`, and that it
/// is fresh at `now_unix_ms`.
pub fn verify_estate_call(c: &EstateCall, signature: &[u8], key: &VerifyingKey, now_unix_ms: i64) -> Result<(), SignatureError> {
    if c.v != 1 || c.estate.trim().is_empty() || (c.at_unix_ms - now_unix_ms).abs() > CALL_FRESH_MS {
        return Err(SignatureError::Call(c.estate.clone()));
    }
    if check(key, &estate_call_message(c), signature)? {
        Ok(())
    } else {
        Err(SignatureError::Call(c.estate.clone()))
    }
}

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

    #[test]
    fn base64_round_trips_every_padding_shape_and_refuses_junk() {
        for n in 0..10 {
            let bytes: Vec<u8> = (0..n).map(|i| (i * 37 + 11) as u8).collect();
            let enc = base64_encode(&bytes);
            assert_eq!(enc.len() % 4, 0);
            assert_eq!(base64_decode(&enc).unwrap(), bytes, "{enc}");
        }
        assert_eq!(base64_encode(b"Man"), "TWFu");
        assert_eq!(base64_encode(b"Ma"), "TWE=");
        assert_eq!(base64_encode(b"M"), "TQ==");
        assert_eq!(base64_decode("TQ="), None);
        assert_eq!(base64_decode("T@=="), None);
        assert_eq!(base64_decode("TQ=x"), None);
    }

    #[test]
    fn the_go_ahead_message_is_canonical_and_excludes_the_signature() {
        let go = GoAhead { v: 1, signer: "monetize".into(), target_sectors: 134_217_728, nonce: "n-1".into(), issued_unix_ms: 1_800_000_000_000, signature: "zzz".into() };
        let msg = String::from_utf8(go_ahead_message(&go)).unwrap();
        assert_eq!(msg, r#"{"issued_unix_ms":1800000000000,"nonce":"n-1","signer":"monetize","target_sectors":134217728,"v":1}"#);
    }
}

// ── the two compatibility directions ───────────────────────────────────────

/// **The issue time was added on 2026-09-17, and nothing signed before it may
/// break.** These tests are the promise, written down where the forms are.
///
/// The two directions a change to a signed form has to answer:
///
/// * an OLD fact meeting NEW code β€” every signature ever minted still verifies,
///   because the V1 form is untouched;
/// * a NEW fact meeting an OLD appliance β€” it reads seven proto fields, computes
///   the V1 form and checks `signature`, which is exactly what
///   [`v1_of_a_stamped_fact_is_byte_for_byte_the_old_form`] measures.
///
/// Neither direction ends in service withdrawn from a paying customer. The
/// guard itself is the product's (gunnar's `EntitlementSlot::set`); what is
/// promised here is only that both generations can still read the fact.
#[cfg(test)]
mod stamp_tests {
    use super::*;
    use ed25519_dalek::{Signer as _, SigningKey};
    use monetize_product::{State, TenantId};

    fn key() -> SigningKey {
        SigningKey::from_bytes(&[3u8; 32])
    }

    fn bare() -> EntitlementFact {
        EntitlementFact {
            tenant: TenantId("team/sub".into()),
            plan: "gunnar/team/sub/2026-09-03".into(),
            state: State::Paid,
            paid_until_unix_ms: Some(1_790_812_800_000),
            caps: [("pack_bytes".to_string(), 10u64 << 30)].into(),
            source: "payment:invoice:ocr-42".into(),
            signature: vec![],
            issued_unix_ms: None,
            issued_signature: vec![],
        }
    }

    /// A fact as it was signed before the field existed: V1 only.
    fn v1(k: &SigningKey) -> EntitlementFact {
        let mut f = bare();
        f.signature = k.sign(&fact_message(&f)).to_bytes().to_vec();
        f
    }

    /// A fact as monetize mints one now: both signatures, stamped.
    fn stamped(k: &SigningKey, issued: u64) -> EntitlementFact {
        let mut f = bare();
        f.issued_unix_ms = Some(issued);
        f.signature = k.sign(&fact_message(&f)).to_bytes().to_vec();
        f.issued_signature = k.sign(&fact_message_issued(&f)).to_bytes().to_vec();
        f
    }

    /// **The old form is frozen.** The bytes below are what `fact_message`
    /// produced before the stamp existed, written out in full rather than
    /// computed, so a future field that forgets to exclude itself fails HERE
    /// and not on a customer's appliance.
    const V1_BYTES: &str = concat!(
        r#"{"caps":{"pack_bytes":10737418240},"paid_until_unix_ms":1790812800000,"#,
        r#""plan":"gunnar/team/sub/2026-09-03","source":"payment:invoice:ocr-42","#,
        r#""state":"Paid","tenant":"team/sub"}"#
    );

    #[test]
    fn v1_of_a_stamped_fact_is_byte_for_byte_the_old_form() {
        let k = key();
        assert_eq!(String::from_utf8(fact_message(&bare())).unwrap(), V1_BYTES);
        let stamped = stamped(&k, 1_789_000_000_000);
        assert_eq!(
            String::from_utf8(fact_message(&stamped)).unwrap(),
            V1_BYTES,
            "an appliance that has never heard of the stamp computes exactly this"
        );
        // …and therefore the V1 signature on a stamped fact is the one such an
        // appliance checks, and it passes. This is the NEW-fact-meets-OLD-box
        // direction, and it must never become a refusal.
        assert!(check(&k.verifying_key(), V1_BYTES.as_bytes(), &stamped.signature).unwrap());
    }

    #[test]
    fn the_v2_form_is_the_v1_form_plus_the_issue_time_and_nothing_else() {
        let stamped = stamped(&key(), 1_789_000_000_000);
        assert_eq!(
            String::from_utf8(fact_message_issued(&stamped)).unwrap(),
            concat!(
                r#"{"caps":{"pack_bytes":10737418240},"issued_unix_ms":1789000000000,"#,
                r#""paid_until_unix_ms":1790812800000,"plan":"gunnar/team/sub/2026-09-03","#,
                r#""source":"payment:invoice:ocr-42","state":"Paid","tenant":"team/sub"}"#
            )
        );
    }

    #[test]
    fn a_fact_signed_before_the_stamp_existed_still_verifies() {
        let k = key();
        verify_fact(&v1(&k), &k.verifying_key()).expect("OLD fact, NEW code: accepted");
    }

    #[test]
    fn a_stamped_fact_verifies_both_halves() {
        let k = key();
        verify_fact(&stamped(&k, 1_789_000_000_000), &k.verifying_key()).unwrap();
    }

    /// **The issue time cannot be added, moved or bumped in transit.**
    ///
    /// Bumping is the one that would hurt most: a fact stamped far in the future
    /// moves a product's high-water mark past every fact monetize will ever mint
    /// for that tenant, so the tenant's plan can never be changed again. That is
    /// a lasting denial of service, and it is refused here, at the signature.
    #[test]
    fn refuse_twin_an_unsigned_or_bumped_issue_time_is_refused_by_its_own_name() {
        let k = key();
        let who = || SignatureError::Issued("team/sub".into());

        // Added to a fact that never had one.
        let mut added = v1(&k);
        added.issued_unix_ms = Some(u64::MAX);
        assert_eq!(verify_fact(&added, &k.verifying_key()), Err(who()));

        // Bumped on a genuinely stamped fact: the V1 signature still passes
        // (it never covered the field), and the V2 one does not.
        let mut bumped = stamped(&k, 1_789_000_000_000);
        bumped.issued_unix_ms = Some(u64::MAX);
        assert!(check(&k.verifying_key(), &fact_message(&bumped), &bumped.signature).unwrap());
        assert_eq!(verify_fact(&bumped, &k.verifying_key()), Err(who()));

        // Half a stamp, either way round.
        let mut no_sig = stamped(&k, 1_789_000_000_000);
        no_sig.issued_signature.clear();
        assert_eq!(verify_fact(&no_sig, &k.verifying_key()), Err(who()));
        let mut no_time = stamped(&k, 1_789_000_000_000);
        no_time.issued_unix_ms = None;
        assert_eq!(verify_fact(&no_time, &k.verifying_key()), Err(who()));

        // A stamp lifted off another fact for the same tenant.
        let mut moved = stamped(&k, 1_789_000_000_000);
        moved.issued_signature = stamped(&k, 1_789_000_000_001).issued_signature;
        assert_eq!(verify_fact(&moved, &k.verifying_key()), Err(who()));
    }

    /// A snapshot of stamped facts verifies whole, and one bumped stamp inside
    /// it rejects the whole snapshot β€” the envelope vouches for the SET.
    #[test]
    fn a_snapshot_carries_stamped_facts_and_one_bad_stamp_rejects_the_set() {
        let k = key();
        let good = stamped(&k, 1_789_000_000_000);
        let facts = vec![good.clone()];
        let signature = k.sign(&snapshot_message(9, &facts)).to_bytes().to_vec();
        let snap = Snapshot { issued_unix_ms: 9, facts, signature };
        verify_snapshot(&snap, &k.verifying_key()).unwrap();

        let mut bumped = good;
        bumped.issued_unix_ms = Some(u64::MAX);
        let facts = vec![bumped];
        let signature = k.sign(&snapshot_message(9, &facts)).to_bytes().to_vec();
        let snap = Snapshot { issued_unix_ms: 9, facts, signature };
        assert_eq!(
            verify_snapshot(&snap, &k.verifying_key()),
            Err(SignatureError::Issued("team/sub".into()))
        );
    }
}

#[cfg(test)]
mod estate_growth_tests {
    use super::*;
    use ed25519_dalek::{Signer as _, SigningKey};

    fn growth(key: &SigningKey, gib: u64) -> Vec<u8> {
        let mut g = EstateGrowth { v: 1, signer: GROWTH_SIGNER_SHOP.into(), estate: "acme".into(), main_data_gib_per_member: gib, until_unix_ms: 9_000, reference: "estate/acme/change-2".into(), issued_unix_ms: 7, signature: String::new() };
        g.signature = base64_encode(&key.sign(&estate_growth_message(&g)).to_bytes());
        serde_json::to_vec(&g).unwrap()
    }

    #[test]
    fn a_shops_growth_go_ahead_verifies_under_its_key_alone() {
        let shop = SigningKey::from_bytes(&[3; 32]);
        let bytes = growth(&shop, 25);
        let g = verify_estate_growth(&bytes, &shop.verifying_key()).expect("the shop's own go-ahead verifies");
        assert_eq!((g.estate.as_str(), g.main_data_gib_per_member, g.until_unix_ms), ("acme", 25, 9_000));
        let other = SigningKey::from_bytes(&[4; 32]);
        assert_eq!(verify_estate_growth(&bytes, &other.verifying_key()), Err(SignatureError::Growth("acme".into())));
        let raised = String::from_utf8(bytes).unwrap().replace("\"main_data_gib_per_member\":25", "\"main_data_gib_per_member\":250");
        assert_eq!(verify_estate_growth(raised.as_bytes(), &shop.verifying_key()), Err(SignatureError::Growth("acme".into())), "a raised size is not the shop's");
    }

    #[test]
    fn an_estates_call_is_its_keys_and_fresh() {
        let acme = SigningKey::from_bytes(&[5; 32]);
        let call = EstateCall { v: 1, call: "grow-set".into(), estate: "acme".into(), members: vec!["main-data-1".into()], gib: 25, at_unix_ms: 1_000_000, carries: String::new() };
        // A call that carries nothing signs as it always did: `carries` is absent from its JSON.
        assert!(!String::from_utf8(estate_call_message(&call)).unwrap().contains("carries"));
        let recharge = EstateCall { call: "recharge".into(), carries: "estate = \"acme\"".into(), ..call.clone() };
        assert!(String::from_utf8(estate_call_message(&recharge)).unwrap().contains("carries"), "the seed is signed");
        let sig = acme.sign(&estate_call_message(&call)).to_bytes();
        assert_eq!(verify_estate_call(&call, &sig, &acme.verifying_key(), 1_000_000 + 60_000), Ok(()));
        assert!(verify_estate_call(&call, &sig, &acme.verifying_key(), 1_000_000 + CALL_FRESH_MS + 1).is_err(), "a stale call is refused");
        let more = EstateCall { gib: 250, ..call.clone() };
        assert!(verify_estate_call(&more, &sig, &acme.verifying_key(), 1_000_000).is_err(), "the signed size is the size");
        let other = SigningKey::from_bytes(&[6; 32]);
        assert!(verify_estate_call(&call, &sig, &other.verifying_key(), 1_000_000).is_err());
    }
}

/// R5a: the canonical form's keys are written without an expect. Signed bytes
/// must not move: each key is still the JSON string serde_json writes for it.
#[cfg(test)]
mod canonical_key_tests {
    use super::*;

    #[test]
    fn a_key_is_written_exactly_as_serde_json_writes_it() {
        for key in ["plain", "a\"quote", "back\\slash", "ΓΌ-ß", "tab\tnew\nline", "\u{1}ctl", "πŸ˜€"] {
            let mut out = String::new();
            canonical_json(&serde_json::json!({ key: 1 }), &mut out);
            assert_eq!(out, format!("{{{}:1}}", serde_json::to_string(key).unwrap()), "{key:?}");
        }
    }
}