Skip to main content

hyprstream_ledger/
mint.rs

1//! Sealing the mint: issuance requires an unforgeable, key-bound capability.
2//!
3//! Issuance is the only operation that grows a unit's supply (INV-1), so "who
4//! may call this" is a monetary question rather than an access-control
5//! convenience.
6//!
7//! ## What the seal is, and what defeated the previous attempt
8//!
9//! An earlier revision gated `credit` on a [`MintCapability`] with a private
10//! field, but obtained that capability through an injectable `MintVerifier`
11//! **trait** plus a public `with_mint_verifier` setter. That is not a seal: a
12//! downstream crate could implement the trait as `fn verify(..) { Ok(()) }`,
13//! install it on an existing backend, and mint arbitrary amounts from
14//! meaningless bytes. Making the *capability* unforgeable is pointless if the
15//! *authority that mints capabilities* is publicly replaceable.
16//!
17//! So there is no trait and no setter. Verification is a concrete in-crate
18//! function over concrete key material:
19//!
20//! - [`MintAuthority`] holds **verifying keys**, not behaviour. There is no
21//!   downstream-implementable extension point to swap the check for `Ok(())`.
22//! - The authority is supplied **once, at backend construction**, and is
23//!   immutable thereafter. Holding a `&mut` backend does not let you change
24//!   what it will accept.
25//! - [`MintCapability`] has no public constructor. The only route is
26//!   [`LedgerBackend::authorize_mint`](crate::LedgerBackend::authorize_mint),
27//!   which verifies a hybrid-PQC composite signature over the canonical,
28//!   domain-separated encoding of **that exact transfer** against the
29//!   authority the backend was built with.
30//!
31//! The residual power a downstream crate has is to stand up *its own* ledger
32//! with *its own* keys, which is not an escalation — it mints only into its own
33//! database, against a supply it already owns. What it cannot do is mint
34//! against a ledger whose authority's signing key it does not hold.
35//!
36//! ## Why hybrid-PQC, concretely and not behind a seam
37//!
38//! Minted issuance authorizations are exactly the artifact class that must be
39//! EdDSA + ML-DSA-65 composite rather than classical-only. `hyprstream-crypto`
40//! is an unconditional, WASM-safe dependency of this crate (the same one
41//! `verify_checkpoint_signature` already uses), so the real verifier lives
42//! here. Nothing needs to be injected from outside, which is precisely what
43//! removes the injection point.
44//!
45//! A backend built with **no** authority cannot mint at all — the fail-closed
46//! direction. An operator who has not wired an issuance authority gets a
47//! mint-disabled ledger, never a mint-open one.
48
49use crate::errors::LedgerError;
50use crate::types::IssueTransfer;
51use ciborium::value::Value;
52use hyprstream_crypto::pq::MlDsaVerifyingKey;
53
54/// Domain-separation tag for the issuance-authorization signing input. Kept
55/// distinct from every other signed body in the system so a signature over one
56/// artifact can never be replayed as authorization for another.
57const MINT_DOMAIN: &str = "hs-ledger-mint-authorization-v1";
58
59/// The key material a ledger checks issuance authorizations against.
60///
61/// Deliberately **data, not behaviour**: there is no trait here, so there is
62/// nothing for a downstream crate to implement permissively. Supplied at
63/// backend construction and immutable afterwards.
64#[derive(Clone)]
65pub struct MintAuthority {
66    ed_vk: ed25519_dalek::VerifyingKey,
67    pq_vk: Option<MlDsaVerifyingKey>,
68    require_pq: bool,
69}
70
71impl std::fmt::Debug for MintAuthority {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        f.debug_struct("MintAuthority")
74            .field("require_pq", &self.require_pq)
75            .field("has_pq_key", &self.pq_vk.is_some())
76            .finish()
77    }
78}
79
80impl MintAuthority {
81    /// The production constructor: hybrid EdDSA + ML-DSA-65.
82    ///
83    /// A classical-only authorization is refused under this authority, so a
84    /// missing PQ arm fails closed instead of silently downgrading.
85    pub fn hybrid(ed_vk: ed25519_dalek::VerifyingKey, pq_vk: MlDsaVerifyingKey) -> Self {
86        Self {
87            ed_vk,
88            pq_vk: Some(pq_vk),
89            require_pq: true,
90        }
91    }
92
93    /// Classical-only (Ed25519). For tests and constrained environments —
94    /// production uses [`Self::hybrid`], matching the checkpoint-signer rule.
95    pub fn classical(ed_vk: ed25519_dalek::VerifyingKey) -> Self {
96        Self {
97            ed_vk,
98            pq_vk: None,
99            require_pq: false,
100        }
101    }
102
103    /// Verify an issuance authorization. Concrete, in-crate, not overridable.
104    fn verify(&self, signing_input: &[u8], sig: &[u8]) -> Result<(), LedgerError> {
105        hyprstream_crypto::cose_sign::verify_composite(
106            sig,
107            &self.ed_vk,
108            self.pq_vk.as_ref(),
109            signing_input,
110            &[],
111            self.require_pq,
112        )
113        .map(|_| ())
114        .map_err(|e| LedgerError::MintNotAuthorized(format!("issuance authorization invalid: {e}")))
115    }
116}
117
118/// The canonical, domain-separated bytes an issuance authorization signs.
119///
120/// Every field that determines what is minted, and where it lands, is bound:
121/// changing the amount, the destination, the unit, or the idempotency key
122/// changes the signing input and invalidates the signature. The encoding is
123/// canonical DAG-CBOR in a fixed array order (the same discipline
124/// [`crate::AccountId::derive`] uses), so an independent implementation can
125/// reproduce these bytes exactly.
126///
127/// ```text
128/// [
129///   "hs-ledger-mint-authorization-v1",
130///   <transfer_id  : bstr(16)>,   // big-endian u128
131///   <issuer_liab  : bstr(16)>,   // big-endian u128
132///   <destination  : bstr(16)>,   // big-endian u128
133///   <unit_issuer  : tstr>,
134///   <unit_class   : tstr>,
135///   <amount       : bstr(16)>,   // big-endian u128
136///   <grant_cid    : bstr>,       // empty when absent
137///   <user_data    : bstr(32)>
138/// ]
139/// ```
140pub fn mint_signing_input(t: &IssueTransfer) -> Result<Vec<u8>, LedgerError> {
141    let value = Value::Array(vec![
142        Value::Text(MINT_DOMAIN.to_owned()),
143        Value::Bytes(t.id.0.to_be_bytes().to_vec()),
144        Value::Bytes(t.issuer_liability.0.to_be_bytes().to_vec()),
145        Value::Bytes(t.destination.0.to_be_bytes().to_vec()),
146        Value::Text(t.unit.issuer.0.clone()),
147        Value::Text(t.unit.resource_class.clone()),
148        Value::Bytes(t.amount.to_be_bytes().to_vec()),
149        Value::Bytes(
150            t.grant_cid
151                .as_ref()
152                .map(|c| c.0.clone())
153                .unwrap_or_default(),
154        ),
155        Value::Bytes(t.user_data.to_vec()),
156    ]);
157    let mut buf = Vec::new();
158    ciborium::into_writer(&value, &mut buf)
159        .map_err(|e| LedgerError::Internal(format!("mint signing input encode failed: {e}")))?;
160    Ok(buf)
161}
162
163/// Proof that a specific issuance was authorized by the ledger's mint authority.
164///
165/// No public constructor, and no public route to one other than
166/// [`LedgerBackend::authorize_mint`](crate::LedgerBackend::authorize_mint).
167/// It borrows the transfer it authorized, so a capability obtained for one
168/// issuance cannot be spent on another — that is a type error, not a runtime
169/// check.
170#[derive(Debug)]
171pub struct MintCapability<'a> {
172    transfer: &'a IssueTransfer,
173}
174
175impl MintCapability<'_> {
176    /// The issuance this capability authorizes — the only one it can be spent
177    /// on, since the backend mints exactly this value.
178    pub fn transfer(&self) -> &IssueTransfer {
179        self.transfer
180    }
181}
182
183/// Verify an issuance authorization and mint the capability on success.
184///
185/// Crate-private on purpose: backends call it from `authorize_mint`, and there
186/// is deliberately no public route to a [`MintCapability`]. An absent authority
187/// refuses everything.
188pub(crate) fn authorize<'a>(
189    authority: Option<&MintAuthority>,
190    transfer: &'a IssueTransfer,
191    sig: &[u8],
192) -> Result<MintCapability<'a>, LedgerError> {
193    let authority = authority.ok_or_else(|| {
194        LedgerError::MintNotAuthorized(
195            "no issuance authority is configured for this ledger".to_owned(),
196        )
197    })?;
198    let input = mint_signing_input(transfer)?;
199    authority.verify(&input, sig)?;
200    Ok(MintCapability { transfer })
201}
202
203#[cfg(test)]
204mod tests {
205    // A test asserting a known-good value legitimately unwraps.
206    #![allow(clippy::unwrap_used, clippy::expect_used)]
207
208    use super::*;
209    use crate::types::{AccountId, Cid, Did, TransferId, UnitId};
210    use hyprstream_crypto::cose_sign::sign_composite;
211    use hyprstream_crypto::pq::ml_dsa_generate_keypair;
212
213    fn xfer(amount: u128) -> IssueTransfer {
214        IssueTransfer {
215            id: TransferId(7),
216            issuer_liability: AccountId(1),
217            destination: AccountId(2),
218            unit: UnitId {
219                issuer: Did("did:web:issuer.test".to_owned()),
220                resource_class: "gpu.h100.seconds".to_owned(),
221            },
222            amount,
223            grant_cid: Some(Cid(vec![9, 9])),
224            user_data: [3u8; 32],
225        }
226    }
227
228    #[test]
229    fn signing_input_is_deterministic() {
230        assert_eq!(
231            mint_signing_input(&xfer(100)).unwrap(),
232            mint_signing_input(&xfer(100)).unwrap()
233        );
234    }
235
236    #[test]
237    fn signing_input_binds_the_amount() {
238        assert_ne!(
239            mint_signing_input(&xfer(100)).unwrap(),
240            mint_signing_input(&xfer(101)).unwrap(),
241            "an authorization for one amount must not cover another"
242        );
243    }
244
245    #[test]
246    fn signing_input_binds_the_destination() {
247        let mut other = xfer(100);
248        other.destination = AccountId(3);
249        assert_ne!(
250            mint_signing_input(&xfer(100)).unwrap(),
251            mint_signing_input(&other).unwrap(),
252            "an authorization must not be redirectable to another account"
253        );
254    }
255
256    #[test]
257    fn an_absent_authority_refuses_everything() {
258        let t = xfer(100);
259        let err = authorize(None, &t, &[0u8; 64]).unwrap_err();
260        assert!(matches!(err, LedgerError::MintNotAuthorized(_)));
261    }
262
263    /// The exact shape of the R4 exploit: arbitrary transfer, meaningless bytes.
264    #[test]
265    fn garbage_bytes_are_refused() {
266        let ed_sk = ed25519_dalek::SigningKey::from_bytes(&[11u8; 32]);
267        let (_pq_sk, pq_vk) = ml_dsa_generate_keypair();
268        let authority = MintAuthority::hybrid(ed_sk.verifying_key(), pq_vk);
269        let t = xfer(1_000_000);
270        for sig in [Vec::new(), vec![0u8; 64], b"not a signature".to_vec()] {
271            let err = authorize(Some(&authority), &t, &sig).unwrap_err();
272            assert!(
273                matches!(err, LedgerError::MintNotAuthorized(_)),
274                "meaningless bytes must not authorize a mint"
275            );
276        }
277    }
278
279    #[test]
280    fn a_hybrid_signature_authorizes_exactly_its_own_transfer() {
281        let ed_sk = ed25519_dalek::SigningKey::from_bytes(&[11u8; 32]);
282        let (pq_sk, pq_vk) = ml_dsa_generate_keypair();
283        let authority = MintAuthority::hybrid(ed_sk.verifying_key(), pq_vk);
284
285        let t = xfer(100);
286        let sig =
287            sign_composite(&ed_sk, Some(&pq_sk), &mint_signing_input(&t).unwrap(), &[]).unwrap();
288        assert_eq!(
289            authorize(Some(&authority), &t, &sig).unwrap().transfer(),
290            &t
291        );
292
293        // The same signature must not carry over to a larger issuance.
294        let bigger = xfer(1_000_000);
295        assert!(
296            authorize(Some(&authority), &bigger, &sig).is_err(),
297            "an authorization must not cover a different issuance"
298        );
299    }
300
301    /// An attacker holding their own keypair gains nothing: the authority is
302    /// fixed at construction and cannot be swapped.
303    #[test]
304    fn a_signature_from_another_key_is_refused() {
305        let ed_sk = ed25519_dalek::SigningKey::from_bytes(&[11u8; 32]);
306        let (_pq_sk, pq_vk) = ml_dsa_generate_keypair();
307        let authority = MintAuthority::hybrid(ed_sk.verifying_key(), pq_vk);
308
309        let attacker_ed = ed25519_dalek::SigningKey::from_bytes(&[99u8; 32]);
310        let (attacker_pq, _) = ml_dsa_generate_keypair();
311        let t = xfer(1_000_000);
312        let sig = sign_composite(
313            &attacker_ed,
314            Some(&attacker_pq),
315            &mint_signing_input(&t).unwrap(),
316            &[],
317        )
318        .unwrap();
319
320        let err = authorize(Some(&authority), &t, &sig).unwrap_err();
321        assert!(matches!(err, LedgerError::MintNotAuthorized(_)));
322    }
323
324    #[test]
325    fn a_classical_only_signature_is_refused_under_a_hybrid_authority() {
326        let ed_sk = ed25519_dalek::SigningKey::from_bytes(&[11u8; 32]);
327        let (_pq_sk, pq_vk) = ml_dsa_generate_keypair();
328        let authority = MintAuthority::hybrid(ed_sk.verifying_key(), pq_vk);
329
330        let t = xfer(100);
331        let classical =
332            sign_composite(&ed_sk, None, &mint_signing_input(&t).unwrap(), &[]).unwrap();
333
334        let err = authorize(Some(&authority), &t, &classical).unwrap_err();
335        assert!(
336            matches!(err, LedgerError::MintNotAuthorized(_)),
337            "a hybrid authority must reject a classical-only authorization"
338        );
339    }
340}