Skip to main content

hyprstream_pay/
lib.rs

1//! # hyprstream-pay — settlement/tariff RPC contract (MIT)
2//!
3//! The **protocol surface** for the pay-wave: `SettlementIssuer` +
4//! `TariffProvider` traits, shared types, capability model, and a client stub.
5//!
6//! This protocol crate is MIT-only; the Hyprstream application is
7//! AGPL-3.0-only. This crate contains
8//! ONLY the protocol definitions. The AGPL service implementation — which
9//! verifies PQ-hybrid attestations server-side, checks the restricted
10//! settlement store, and calls the ledger's internal credit path — lives in
11//! `hyprstream::services::pay`.
12//!
13//! ## Why a separate MIT crate (#1399)?
14//!
15//! `cyberdione-product` (and any other consumer) must link against the
16//! settlement/tariff contract without inheriting the AGPL. The protocol/stub
17//! crate is MIT; the service that actually moves money is AGPL. This is the
18//! standard protocol/impl split: the wire format is free; the implementation
19//! is copyleft.
20//!
21//! ## The two contracts
22//!
23//! - [`SettlementIssuer`] — verified settlement → deterministic credit
24//!   issuance. Idempotent: same settlement id → same transfer id, same
25//!   outcome, across retries and crashes. The only purchased-credit issuance
26//!   surface.
27//! - [`TariffProvider`] — resource → priced quote with a finite server-imposed
28//!   ceiling. The server owns the price, catalog, and maximum quantum; clients
29//!   cannot set these.
30//!
31//! ## Security model
32//!
33//! Peer auth is transport-level (TLS 1.3 on QUIC, UDS peer credentials on
34//! iroh). Then capability-gated at the RPC layer (`#[authorize]` on handlers).
35//! The attestation itself is PQ-hybrid-signed (EdDSA + ML-DSA-65 COSE
36//! composite) and **re-verified server-side** — never trusts a client
37//! assertion. This reuses the #1129 spend-authorization verification path.
38
39pub mod attestation;
40pub mod capability;
41pub mod types;
42
43pub use attestation::{SettlementAttestation, ATTESTATION_V1_TAG};
44pub use capability::ALL_SCOPES;
45pub use types::{IssueRequest, IssueResponse, TariffQuote, TariffRequest, UnitRef};
46
47use async_trait::async_trait;
48
49/// Errors from the settlement/tariff protocol.
50#[derive(Debug, thiserror::Error)]
51pub enum PayError {
52    /// The settlement attestation failed PQ-hybrid signature verification or
53    /// the issuer's key material is unknown.
54    #[error("settlement attestation verification failed: {0}")]
55    AttestationInvalid(String),
56
57    /// No committed settlement row was found for the given settlement id.
58    #[error("no committed settlement for id {0}")]
59    SettlementNotFound(String),
60
61    /// The settlement row exists but is not in the `settlement_committed`
62    /// state — issuance requires a fully verified, server-validated
63    /// settlement.
64    #[error("settlement {0} is not committed (state: {1})")]
65    SettlementNotCommitted(String, String),
66
67    /// The settlement row exists and is committed, but credits were already
68    /// issued for it. This is a success case (idempotent replay) — the
69    /// original transfer id and outcome are returned.
70    #[error("settlement {0} already issued")]
71    AlreadyIssued(String),
72
73    /// The ledger rejected the issuance (insufficient issuer liability,
74    /// unknown destination account, internal error, etc.).
75    #[error("ledger issuance failed: {0}")]
76    LedgerError(String),
77
78    /// The tariff request named an unknown resource class or catalog version.
79    #[error("unknown resource class or catalog: {0}")]
80    UnknownResourceClass(String),
81
82    /// The quote has expired.
83    #[error("quote expired")]
84    QuoteExpired,
85
86    /// The requested quantum exceeds the server-imposed maximum.
87    #[error("quantum {requested} exceeds server maximum {max}")]
88    QuantumExceedsMaximum { requested: u64, max: u64 },
89
90    /// An internal error (transport, serialization, etc.).
91    #[error("internal pay error: {0}")]
92    Internal(String),
93}
94
95/// The settlement-issuer contract: only a verified, server-revalidated
96/// settlement can cause purchased-credit issuance.
97///
98/// **Production impl (AGPL, `hyprstream::services::pay`):**
99/// 1. Verify the attestation's PQ-hybrid signature against the issuer's key
100///    material (reuse #1129 `verify_composite`).
101/// 2. Check the restricted settlement store for a committed settlement row
102///    matching `settlement_id`.
103/// 3. Derive the deterministic transfer ID (blake3 of `settlement_id` +
104///    `catalog_version` + line index — idempotent across retries/crashes).
105/// 4. Call the ledger's internal `credit()` (the restricted path, NOT the
106///    public `LedgerHandle::credit`).
107/// 5. Return the idempotent outcome.
108///
109/// A client redirect, client-supplied `paid` field, Checkout completion
110/// without a settled PaymentIntent, or unverified webhook can never reach
111/// issuance. The externally-reachable generic ledger `credit` is NOT on this
112/// path.
113#[async_trait]
114pub trait SettlementIssuer: Send + Sync {
115    /// Issue credits from a verified settlement attestation.
116    ///
117    /// Idempotent: replaying the same `settlement_id` returns the original
118    /// `IssueResponse` verbatim (same transfer id, same outcome). The server
119    /// never generates a second issuance after an ambiguous timeout — it
120    /// retries the same deterministic transfer id.
121    async fn issue(&self, req: IssueRequest) -> Result<IssueResponse, PayError>;
122
123    /// Query a prior issuance's status. Used for retry/recovery when the
124    /// original `issue` response was lost (e.g. network failure after the
125    /// ledger committed).
126    async fn status(&self, settlement_id: &str) -> Result<IssueResponse, PayError>;
127}
128
129/// The tariff-provider contract: resource → priced quote.
130///
131/// The server owns the price, catalog, and maximum quantum. A client cannot
132/// set the amount, price, or ceiling — those are derived server-side from the
133/// resource class, catalog version, and subject tier.
134#[async_trait]
135pub trait TariffProvider: Send + Sync {
136    /// Get a priced quote for a resource quantity. The quote has a finite
137    /// expiry and a server-imposed maximum quantum.
138    async fn quote(&self, req: TariffRequest) -> Result<TariffQuote, PayError>;
139
140    /// Resolve a unit reference for cross-cell federation (map an issuer DID +
141    /// resource class to the canonical `UnitRef`).
142    async fn resolve_unit(
143        &self,
144        issuer_did: &str,
145        resource_class: &str,
146    ) -> Result<UnitRef, PayError>;
147}