polyc-crypto 2026.7.0

Provenance signatures (commonware-cryptography ed25519) for polychrome tool calls.
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
//! Canonical signing for AP2-style pre-authorization mandates.
//!
//! An AP2 mandate chain is three signed artifacts, each narrowing the one
//! before it: an **Intent** mandate (the human's up-front authorization
//! scope), a **Cart** mandate (a specific merchant + amount drawn from that
//! scope), and a **Payment** mandate (the exact tool call the cart pays for).
//! Each signs the canonical JSON encoding of its fields with `signed_by` /
//! `signature_hex` cleared — the same pattern [`crate::approval`] uses for
//! `approval_response` / `payment_receipt` — plus a literal `kind` tag so a
//! signed Cart can never be mistaken for a signed Intent even if their field
//! sets happened to overlap.
//!
//! A child mandate references its parent by [`mandate_hash`]: the sha256 hex
//! of the PARENT'S FULL signed payload (body + signature), not just its
//! unsigned fields. Hashing the signature too means the reference commits to
//! one exact, already-verified artifact — a parent re-signed by a different
//! key (even over byte-identical fields) produces a different hash and breaks
//! the chain.
//!
//! This module only mints and verifies individual signatures and computes the
//! chain-link hash; it knows nothing about amount narrowing, expiry ordering,
//! or which call a Payment mandate authorizes — that business logic lives in
//! `polyc_payments::mandate`, which calls back into the `verify_signed_*`
//! functions here exactly as [`crate::approval`]'s callers do.

use serde_json::Value;
use sha2::{Digest, Sha256};

use crate::{Signer, verify};

/// Signed `kind` tag for an Intent mandate's canonical JSON.
const KIND_INTENT: &str = "ap2.intent.v1";
/// Signed `kind` tag for a Cart mandate's canonical JSON.
const KIND_CART: &str = "ap2.cart.v1";
/// Signed `kind` tag for a Payment mandate's canonical JSON.
const KIND_PAYMENT: &str = "ap2.payment.v1";

/// Sha256 hex of a mandate's FULL signed payload bytes — the chain link.
///
/// Takes the bytes a `sign_*_mandate` function returned (or read back from
/// storage); the result is the value a child mandate signs into its
/// `intent_hash` / `cart_hash` field.
#[must_use]
pub fn mandate_hash(signed_payload: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(signed_payload);
    hex_lower(&hasher.finalize())
}

/// Named signed fields for an Intent mandate — the top-level, human-granted
/// authorization scope.
///
/// Passed as a single struct (mirrors [`crate::approval::ReceiptPayload`]) so
/// two same-typed `&str` fields can't be silently swapped at a call site.
#[derive(Debug, Clone, Copy)]
pub struct IntentFields<'a> {
    /// The identity that granted this authorization (mirrors
    /// `approval_response.caller`, e.g. `slack:T1:U9`).
    pub caller: &'a str,
    /// The conversation this intent is scoped to.
    pub conversation_id: &'a str,
    /// Free-form human-readable description of what was authorized (audit /
    /// display only; not itself a scope predicate).
    pub scope_description: &'a str,
    /// Settlement token contract address every descendant Cart/Payment must
    /// match.
    pub currency: &'a str,
    /// Decimal base-unit ceiling on the total this intent may ultimately
    /// authorize across every descendant Cart; empty ⇒ unbounded (a Cart's
    /// amount is still bounded by its own signed value, just not by this
    /// intent).
    pub max_total_base_units: &'a str,
    /// Unix seconds this mandate was issued.
    pub issued_at_unix: u64,
    /// Unix seconds after which this mandate (and every descendant) is no
    /// longer valid.
    pub expires_at_unix: u64,
    /// Per-mandate unique value (mirrors `approval_response.nonce`).
    pub nonce: &'a str,
}

impl IntentFields<'_> {
    fn canonical_json(&self) -> Value {
        serde_json::json!({
            "kind": KIND_INTENT,
            "caller": self.caller,
            "conversation_id": self.conversation_id,
            "scope_description": self.scope_description,
            "currency": self.currency,
            "max_total_base_units": self.max_total_base_units,
            "issued_at_unix": self.issued_at_unix,
            "expires_at_unix": self.expires_at_unix,
            "nonce": self.nonce,
        })
    }
}

/// A verified, decoded Intent mandate.
#[derive(Debug, Clone)]
pub struct VerifiedIntentMandate {
    /// The identity that granted this authorization.
    pub caller: String,
    /// The conversation this intent is scoped to.
    pub conversation_id: String,
    /// Human-readable description of what was authorized.
    pub scope_description: String,
    /// Settlement token contract address.
    pub currency: String,
    /// Decimal base-unit ceiling on the total; empty ⇒ unbounded.
    pub max_total_base_units: String,
    /// Unix seconds this mandate was issued.
    pub issued_at_unix: u64,
    /// Unix seconds after which this mandate is no longer valid.
    pub expires_at_unix: u64,
    /// Per-mandate unique value.
    pub nonce: String,
    /// The verified signer's public key (encoded).
    pub signer_public_key: Vec<u8>,
}

/// Sign the canonical bytes of `fields`.
///
/// Returns `(full_payload_bytes, signature_bytes, public_key_bytes)`; the
/// caller persists `full_payload_bytes` and, for a Cart mandate, feeds it
/// through [`mandate_hash`] to build the chain link.
#[must_use]
pub fn sign_intent_mandate(
    fields: &IntentFields<'_>,
    signer: &Signer,
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
    sign_envelope(fields.canonical_json(), signer)
}

/// Verify a persisted Intent mandate payload.
///
/// Returns `Some(record)` if the signature checks out against the embedded
/// public key and the payload carries the Intent `kind` tag. Returns `None` if the
/// payload is malformed, the hex fields don't decode, the `kind` tag doesn't
/// match, or the signature doesn't verify.
#[must_use]
pub fn verify_signed_intent_mandate(payload: &[u8]) -> Option<VerifiedIntentMandate> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    if v.get("kind")?.as_str()? != KIND_INTENT {
        return None;
    }
    let caller = v.get("caller")?.as_str()?.to_owned();
    let conversation_id = v.get("conversation_id")?.as_str()?.to_owned();
    let scope_description = v.get("scope_description")?.as_str()?.to_owned();
    let currency = v.get("currency")?.as_str()?.to_owned();
    let max_total_base_units = v.get("max_total_base_units")?.as_str()?.to_owned();
    let issued_at_unix = v.get("issued_at_unix")?.as_u64()?;
    let expires_at_unix = v.get("expires_at_unix")?.as_u64()?;
    let nonce = v.get("nonce")?.as_str()?.to_owned();
    let (pk, sig) = envelope_signature(&v)?;

    let fields = IntentFields {
        caller: &caller,
        conversation_id: &conversation_id,
        scope_description: &scope_description,
        currency: &currency,
        max_total_base_units: &max_total_base_units,
        issued_at_unix,
        expires_at_unix,
        nonce: &nonce,
    };
    if verify(&pk, &fields.canonical_json().to_string().into_bytes(), &sig) {
        Some(VerifiedIntentMandate {
            caller,
            conversation_id,
            scope_description,
            currency,
            max_total_base_units,
            issued_at_unix,
            expires_at_unix,
            nonce,
            signer_public_key: pk,
        })
    } else {
        None
    }
}

/// Named signed fields for a Cart mandate — narrows an Intent to a specific
/// merchant and amount.
#[derive(Debug, Clone, Copy)]
pub struct CartFields<'a> {
    /// [`mandate_hash`] of the parent Intent mandate's full signed payload.
    pub intent_hash: &'a str,
    /// The identity that granted this authorization (must equal the parent
    /// Intent's `caller`; checked by the chain validator, not here).
    pub caller: &'a str,
    /// The conversation this cart is scoped to.
    pub conversation_id: &'a str,
    /// The merchant host this cart authorizes payment to (lowercased).
    pub merchant_host: &'a str,
    /// Settlement token contract address.
    pub currency: &'a str,
    /// Decimal base-unit total for this cart.
    pub amount_base_units: &'a str,
    /// Unix seconds this mandate was issued.
    pub issued_at_unix: u64,
    /// Unix seconds after which this mandate is no longer valid.
    pub expires_at_unix: u64,
    /// Per-mandate unique value.
    pub nonce: &'a str,
}

impl CartFields<'_> {
    fn canonical_json(&self) -> Value {
        serde_json::json!({
            "kind": KIND_CART,
            "intent_hash": self.intent_hash,
            "caller": self.caller,
            "conversation_id": self.conversation_id,
            "merchant_host": self.merchant_host,
            "currency": self.currency,
            "amount_base_units": self.amount_base_units,
            "issued_at_unix": self.issued_at_unix,
            "expires_at_unix": self.expires_at_unix,
            "nonce": self.nonce,
        })
    }
}

/// A verified, decoded Cart mandate.
#[derive(Debug, Clone)]
pub struct VerifiedCartMandate {
    /// [`mandate_hash`] of the parent Intent mandate this cart chains to.
    pub intent_hash: String,
    /// The identity that granted this authorization.
    pub caller: String,
    /// The conversation this cart is scoped to.
    pub conversation_id: String,
    /// The merchant host this cart authorizes payment to.
    pub merchant_host: String,
    /// Settlement token contract address.
    pub currency: String,
    /// Decimal base-unit total for this cart.
    pub amount_base_units: String,
    /// Unix seconds this mandate was issued.
    pub issued_at_unix: u64,
    /// Unix seconds after which this mandate is no longer valid.
    pub expires_at_unix: u64,
    /// Per-mandate unique value.
    pub nonce: String,
    /// The verified signer's public key (encoded).
    pub signer_public_key: Vec<u8>,
}

/// Sign the canonical bytes of `fields`. Returns
/// `(full_payload_bytes, signature_bytes, public_key_bytes)`.
#[must_use]
pub fn sign_cart_mandate(fields: &CartFields<'_>, signer: &Signer) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
    sign_envelope(fields.canonical_json(), signer)
}

/// Verify a persisted Cart mandate payload. See
/// [`verify_signed_intent_mandate`] for the failure modes.
#[must_use]
pub fn verify_signed_cart_mandate(payload: &[u8]) -> Option<VerifiedCartMandate> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    if v.get("kind")?.as_str()? != KIND_CART {
        return None;
    }
    let intent_hash = v.get("intent_hash")?.as_str()?.to_owned();
    let caller = v.get("caller")?.as_str()?.to_owned();
    let conversation_id = v.get("conversation_id")?.as_str()?.to_owned();
    let merchant_host = v.get("merchant_host")?.as_str()?.to_owned();
    let currency = v.get("currency")?.as_str()?.to_owned();
    let amount_base_units = v.get("amount_base_units")?.as_str()?.to_owned();
    let issued_at_unix = v.get("issued_at_unix")?.as_u64()?;
    let expires_at_unix = v.get("expires_at_unix")?.as_u64()?;
    let nonce = v.get("nonce")?.as_str()?.to_owned();
    let (pk, sig) = envelope_signature(&v)?;

    let fields = CartFields {
        intent_hash: &intent_hash,
        caller: &caller,
        conversation_id: &conversation_id,
        merchant_host: &merchant_host,
        currency: &currency,
        amount_base_units: &amount_base_units,
        issued_at_unix,
        expires_at_unix,
        nonce: &nonce,
    };
    if verify(&pk, &fields.canonical_json().to_string().into_bytes(), &sig) {
        Some(VerifiedCartMandate {
            intent_hash,
            caller,
            conversation_id,
            merchant_host,
            currency,
            amount_base_units,
            issued_at_unix,
            expires_at_unix,
            nonce,
            signer_public_key: pk,
        })
    } else {
        None
    }
}

/// Named signed fields for a Payment mandate — the final authorization bound
/// to one exact tool call.
#[derive(Debug, Clone, Copy)]
pub struct PaymentFields<'a> {
    /// [`mandate_hash`] of the parent Cart mandate's full signed payload.
    pub cart_hash: &'a str,
    /// The identity that granted this authorization.
    pub caller: &'a str,
    /// The conversation this payment is scoped to.
    pub conversation_id: &'a str,
    /// The exact `paid_fetch` `args_json` this payment authorizes (mirrors
    /// `approval_response.args_json` binding — a captured mandate cannot be
    /// replayed against a different call).
    pub args_json: &'a str,
    /// Settlement token contract address.
    pub currency: &'a str,
    /// Decimal base-unit amount for this payment.
    pub amount_base_units: &'a str,
    /// Unix seconds this mandate was issued.
    pub issued_at_unix: u64,
    /// Unix seconds after which this mandate is no longer valid.
    pub expires_at_unix: u64,
    /// Per-mandate unique value.
    pub nonce: &'a str,
}

impl PaymentFields<'_> {
    fn canonical_json(&self) -> Value {
        serde_json::json!({
            "kind": KIND_PAYMENT,
            "cart_hash": self.cart_hash,
            "caller": self.caller,
            "conversation_id": self.conversation_id,
            "args_json": self.args_json,
            "currency": self.currency,
            "amount_base_units": self.amount_base_units,
            "issued_at_unix": self.issued_at_unix,
            "expires_at_unix": self.expires_at_unix,
            "nonce": self.nonce,
        })
    }
}

/// A verified, decoded Payment mandate.
#[derive(Debug, Clone)]
pub struct VerifiedPaymentMandate {
    /// [`mandate_hash`] of the parent Cart mandate this payment chains to.
    pub cart_hash: String,
    /// The identity that granted this authorization.
    pub caller: String,
    /// The conversation this payment is scoped to.
    pub conversation_id: String,
    /// The exact `paid_fetch` `args_json` this payment authorizes.
    pub args_json: String,
    /// Settlement token contract address.
    pub currency: String,
    /// Decimal base-unit amount for this payment.
    pub amount_base_units: String,
    /// Unix seconds this mandate was issued.
    pub issued_at_unix: u64,
    /// Unix seconds after which this mandate is no longer valid.
    pub expires_at_unix: u64,
    /// Per-mandate unique value.
    pub nonce: String,
    /// The verified signer's public key (encoded).
    pub signer_public_key: Vec<u8>,
}

/// Sign the canonical bytes of `fields`. Returns
/// `(full_payload_bytes, signature_bytes, public_key_bytes)`.
#[must_use]
pub fn sign_payment_mandate(
    fields: &PaymentFields<'_>,
    signer: &Signer,
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
    sign_envelope(fields.canonical_json(), signer)
}

/// Verify a persisted Payment mandate payload. See
/// [`verify_signed_intent_mandate`] for the failure modes.
#[must_use]
pub fn verify_signed_payment_mandate(payload: &[u8]) -> Option<VerifiedPaymentMandate> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    if v.get("kind")?.as_str()? != KIND_PAYMENT {
        return None;
    }
    let cart_hash = v.get("cart_hash")?.as_str()?.to_owned();
    let caller = v.get("caller")?.as_str()?.to_owned();
    let conversation_id = v.get("conversation_id")?.as_str()?.to_owned();
    let args_json = v.get("args_json")?.as_str()?.to_owned();
    let currency = v.get("currency")?.as_str()?.to_owned();
    let amount_base_units = v.get("amount_base_units")?.as_str()?.to_owned();
    let issued_at_unix = v.get("issued_at_unix")?.as_u64()?;
    let expires_at_unix = v.get("expires_at_unix")?.as_u64()?;
    let nonce = v.get("nonce")?.as_str()?.to_owned();
    let (pk, sig) = envelope_signature(&v)?;

    let fields = PaymentFields {
        cart_hash: &cart_hash,
        caller: &caller,
        conversation_id: &conversation_id,
        args_json: &args_json,
        currency: &currency,
        amount_base_units: &amount_base_units,
        issued_at_unix,
        expires_at_unix,
        nonce: &nonce,
    };
    if verify(&pk, &fields.canonical_json().to_string().into_bytes(), &sig) {
        Some(VerifiedPaymentMandate {
            cart_hash,
            caller,
            conversation_id,
            args_json,
            currency,
            amount_base_units,
            issued_at_unix,
            expires_at_unix,
            nonce,
            signer_public_key: pk,
        })
    } else {
        None
    }
}

/// Signs `canonical` and appends the two signature fields, mirroring
/// [`crate::approval::receipt_payload`]'s "canonical object plus signature
/// fields" construction — the body field set stays owned by each
/// `*Fields::canonical_json`, this only adds the envelope.
fn sign_envelope(mut canonical: Value, signer: &Signer) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
    let canonical_bytes = canonical.to_string().into_bytes();
    let signature = signer.sign(&canonical_bytes);
    let pk = signer.public_key_bytes();
    if let Value::Object(map) = &mut canonical {
        map.insert("signed_by".to_owned(), Value::String(hex_lower(&pk)));
        map.insert(
            "signature_hex".to_owned(),
            Value::String(hex_lower(&signature)),
        );
    }
    (canonical.to_string().into_bytes(), signature, pk)
}

/// Extracts and hex-decodes the `signed_by` / `signature_hex` pair a
/// `verify_signed_*_mandate` needs, common to all three envelope shapes.
fn envelope_signature(v: &Value) -> Option<(Vec<u8>, Vec<u8>)> {
    let pk = hex_decode(v.get("signed_by")?.as_str()?)?;
    let sig = hex_decode(v.get("signature_hex")?.as_str()?)?;
    Some((pk, sig))
}

fn hex_lower(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        use std::fmt::Write as _;
        let _ = write!(&mut s, "{b:02x}");
    }
    s
}

fn hex_decode(s: &str) -> Option<Vec<u8>> {
    if !s.len().is_multiple_of(2) {
        return None;
    }
    (0..s.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok())
        .collect()
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]

    use super::*;

    fn intent(signer: &Signer) -> (Vec<u8>, IntentFields<'static>) {
        let fields = IntentFields {
            caller: "slack:T1:U9",
            conversation_id: "conv-1",
            scope_description: "research report purchases",
            currency: "0xUSD",
            max_total_base_units: "1000000",
            issued_at_unix: 1_000,
            expires_at_unix: 10_000,
            nonce: "intent-nonce-1",
        };
        let (payload, _sig, _pk) = sign_intent_mandate(&fields, signer);
        (payload, fields)
    }

    #[test]
    fn intent_mandate_round_trips() {
        let signer = Signer::from_seed(1);
        let (payload, fields) = intent(&signer);
        let verified = verify_signed_intent_mandate(&payload).expect("verifies");
        assert_eq!(verified.caller, fields.caller);
        assert_eq!(verified.conversation_id, fields.conversation_id);
        assert_eq!(verified.max_total_base_units, fields.max_total_base_units);
        assert_eq!(verified.signer_public_key, signer.public_key_bytes());
    }

    #[test]
    fn intent_mandate_tampered_amount_fails() {
        let signer = Signer::from_seed(1);
        let (payload, _fields) = intent(&signer);
        let mut v: Value = serde_json::from_slice(&payload).unwrap();
        v["max_total_base_units"] = Value::String("999999999".to_owned());
        assert!(verify_signed_intent_mandate(&v.to_string().into_bytes()).is_none());
    }

    #[test]
    fn intent_mandate_wrong_kind_rejected() {
        // A Cart payload must never verify as an Intent, even before the
        // signature is checked — the literal `kind` tag is the first gate.
        let signer = Signer::from_seed(1);
        let cart_fields = CartFields {
            intent_hash: "deadbeef",
            caller: "slack:T1:U9",
            conversation_id: "conv-1",
            merchant_host: "api.example.com",
            currency: "0xUSD",
            amount_base_units: "500000",
            issued_at_unix: 1_000,
            expires_at_unix: 5_000,
            nonce: "cart-nonce-1",
        };
        let (cart_payload, _sig, _pk) = sign_cart_mandate(&cart_fields, &signer);
        assert!(verify_signed_intent_mandate(&cart_payload).is_none());
    }

    #[test]
    fn cart_mandate_round_trips_and_chains_by_hash() {
        let signer = Signer::from_seed(2);
        let (intent_payload, _fields) = intent(&signer);
        let intent_hash = mandate_hash(&intent_payload);

        let cart_fields = CartFields {
            intent_hash: &intent_hash,
            caller: "slack:T1:U9",
            conversation_id: "conv-1",
            merchant_host: "api.example.com",
            currency: "0xUSD",
            amount_base_units: "500000",
            issued_at_unix: 1_000,
            expires_at_unix: 5_000,
            nonce: "cart-nonce-1",
        };
        let (cart_payload, _sig, _pk) = sign_cart_mandate(&cart_fields, &signer);
        let verified = verify_signed_cart_mandate(&cart_payload).expect("cart verifies");
        assert_eq!(verified.intent_hash, intent_hash);
        assert_eq!(verified.merchant_host, "api.example.com");
    }

    #[test]
    fn cart_mandate_tampered_intent_hash_fails() {
        let signer = Signer::from_seed(2);
        let (intent_payload, _fields) = intent(&signer);
        let intent_hash = mandate_hash(&intent_payload);
        let cart_fields = CartFields {
            intent_hash: &intent_hash,
            caller: "slack:T1:U9",
            conversation_id: "conv-1",
            merchant_host: "api.example.com",
            currency: "0xUSD",
            amount_base_units: "500000",
            issued_at_unix: 1_000,
            expires_at_unix: 5_000,
            nonce: "cart-nonce-1",
        };
        let (payload, _sig, _pk) = sign_cart_mandate(&cart_fields, &signer);
        let mut v: Value = serde_json::from_slice(&payload).unwrap();
        v["intent_hash"] = Value::String("0".repeat(64));
        assert!(verify_signed_cart_mandate(&v.to_string().into_bytes()).is_none());
    }

    #[test]
    fn payment_mandate_round_trips_and_chains_by_hash() {
        let signer = Signer::from_seed(3);
        let (intent_payload, _fields) = intent(&signer);
        let intent_hash = mandate_hash(&intent_payload);
        let cart_fields = CartFields {
            intent_hash: &intent_hash,
            caller: "slack:T1:U9",
            conversation_id: "conv-1",
            merchant_host: "api.example.com",
            currency: "0xUSD",
            amount_base_units: "500000",
            issued_at_unix: 1_000,
            expires_at_unix: 5_000,
            nonce: "cart-nonce-1",
        };
        let (cart_payload, _sig, _pk) = sign_cart_mandate(&cart_fields, &signer);
        let cart_hash = mandate_hash(&cart_payload);

        let payment_fields = PaymentFields {
            cart_hash: &cart_hash,
            caller: "slack:T1:U9",
            conversation_id: "conv-1",
            args_json: r#"{"url":"https://api.example.com/report"}"#,
            currency: "0xUSD",
            amount_base_units: "250000",
            issued_at_unix: 1_000,
            expires_at_unix: 4_000,
            nonce: "payment-nonce-1",
        };
        let (payment_payload, _sig, _pk) = sign_payment_mandate(&payment_fields, &signer);
        let verified = verify_signed_payment_mandate(&payment_payload).expect("payment verifies");
        assert_eq!(verified.cart_hash, cart_hash);
        assert_eq!(verified.amount_base_units, "250000");
        assert_eq!(verified.args_json, payment_fields.args_json);
    }

    #[test]
    fn payment_mandate_tampered_args_json_fails() {
        let signer = Signer::from_seed(3);
        let payment_fields = PaymentFields {
            cart_hash: "deadbeef",
            caller: "slack:T1:U9",
            conversation_id: "conv-1",
            args_json: r#"{"url":"https://api.example.com/report"}"#,
            currency: "0xUSD",
            amount_base_units: "250000",
            issued_at_unix: 1_000,
            expires_at_unix: 4_000,
            nonce: "payment-nonce-1",
        };
        let (payload, _sig, _pk) = sign_payment_mandate(&payment_fields, &signer);
        let mut v: Value = serde_json::from_slice(&payload).unwrap();
        v["args_json"] = Value::String(r#"{"url":"https://evil.example.com/steal"}"#.to_owned());
        assert!(verify_signed_payment_mandate(&v.to_string().into_bytes()).is_none());
    }

    #[test]
    fn mandate_hash_is_stable_and_sensitive_to_signature() {
        let signer_a = Signer::from_seed(9);
        let signer_b = Signer::from_seed(10);
        let fields = IntentFields {
            caller: "slack:T1:U9",
            conversation_id: "conv-1",
            scope_description: "x",
            currency: "0xUSD",
            max_total_base_units: "1000",
            issued_at_unix: 1,
            expires_at_unix: 2,
            nonce: "n",
        };
        let (payload_a, _s, _p) = sign_intent_mandate(&fields, &signer_a);
        let (payload_b, _s, _p) = sign_intent_mandate(&fields, &signer_b);
        // Same fields, deterministic re-hash.
        assert_eq!(mandate_hash(&payload_a), mandate_hash(&payload_a));
        // Different signer over IDENTICAL fields ⇒ a different signature ⇒ a
        // different hash, since the hash commits to the full signed artifact.
        assert_ne!(mandate_hash(&payload_a), mandate_hash(&payload_b));
    }

    #[test]
    fn garbage_payload_returns_none_not_panic() {
        assert!(verify_signed_intent_mandate(b"not json").is_none());
        assert!(verify_signed_cart_mandate(b"{}").is_none());
        assert!(verify_signed_payment_mandate(b"[]").is_none());
    }
}