lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

commerce.rs (19829B)


      1 //! Carrier-independent private record claims. These values provide no content
      2 //! hash, signature, authenticated parent coverage, consent or installed effects.
      3 use crate::{OrderId, PublicKey, RecordId, Sequence, SourceId, Terms, ThreadId, UnixSeconds};
      4 use alloc::{boxed::Box, vec::Vec};
      5 use core::fmt;
      6 
      7 pub mod causal;
      8 mod value;
      9 pub use value::{FinalMeasurement, IssueCode, IssueReport, LineQuantity, Resolution};
     10 mod payload;
     11 pub use payload::{
     12     AgreementCommitment, CancellationProposal, HandoverClaim, ProposalAuthorization,
     13     ReadinessClaim, ReceiptObservation, RecordReason, ResidualRelease, ResolutionCommitment,
     14     ResolutionProposal, TermsAuthorization, TermsProposal, TermsQuote, TermsRequest,
     15     WithdrawalAcknowledgement,
     16 };
     17 
     18 /// Exact declared common record data; construction authenticates no participant.
     19 #[derive(Clone, Eq, PartialEq)]
     20 pub struct CommerceHeader {
     21     thread_id: ThreadId,
     22     order_id: Option<OrderId>,
     23     author: PublicKey,
     24     buyer: PublicKey,
     25     seller: PublicKey,
     26     created_at: UnixSeconds,
     27     author_sequence: Sequence,
     28     author_previous: Option<RecordId>,
     29     parents: Box<[SourceId]>,
     30 }
     31 impl CommerceHeader {
     32     /// Largest supported direct causal-parent set. Payload/source limits apply
     33     /// jointly; referenced data must never be silently omitted to fit this cap.
     34     pub const MAX_PARENTS: usize = 8;
     35     /// Validates declared participants, positive sequence/previous shape and a
     36     /// sorted unique parent set before capture. Previous author/thread/order,
     37     /// source signatures, sequence continuity and actual coverage need admission.
     38     #[allow(clippy::too_many_arguments)]
     39     pub fn new(
     40         thread_id: ThreadId,
     41         order_id: Option<OrderId>,
     42         author: PublicKey,
     43         buyer: PublicKey,
     44         seller: PublicKey,
     45         created_at: UnixSeconds,
     46         author_sequence: Sequence,
     47         author_previous: Option<RecordId>,
     48         parents: Vec<SourceId>,
     49     ) -> Result<Self, CommerceError> {
     50         if buyer == seller {
     51             return Err(CommerceError::PartiesCoincide);
     52         }
     53         if author != buyer && author != seller {
     54             return Err(CommerceError::InvalidAuthor);
     55         }
     56         if author_sequence.get() == 0 {
     57             return Err(CommerceError::InvalidSequence);
     58         }
     59         if (author_sequence.get() == 1) != author_previous.is_none() {
     60             return Err(CommerceError::InvalidPrevious);
     61         }
     62         if parents.len() > Self::MAX_PARENTS || parents.windows(2).any(|pair| pair[0] >= pair[1]) {
     63             return Err(CommerceError::InvalidParents);
     64         }
     65         if let Some(previous) = author_previous
     66             && !parents.contains(&source(previous))
     67         {
     68             return Err(CommerceError::MissingParent);
     69         }
     70         Ok(Self {
     71             thread_id,
     72             order_id,
     73             author,
     74             buyer,
     75             seller,
     76             created_at,
     77             author_sequence,
     78             author_previous,
     79             parents: parents.into_boxed_slice(),
     80         })
     81     }
     82     /// Returns the exact application thread claim.
     83     pub const fn thread_id(&self) -> ThreadId {
     84         self.thread_id
     85     }
     86     /// Returns the explicit order claim; only quotes may omit it in content.
     87     pub const fn order_id(&self) -> Option<OrderId> {
     88         self.order_id
     89     }
     90     /// Returns the claimed author, without signer or delegation proof.
     91     pub const fn author(&self) -> PublicKey {
     92         self.author
     93     }
     94     /// Returns the distinct buyer claim.
     95     pub const fn buyer(&self) -> PublicKey {
     96         self.buyer
     97     }
     98     /// Returns the distinct seller claim.
     99     pub const fn seller(&self) -> PublicKey {
    100         self.seller
    101     }
    102     /// Returns the claimed exact author time, without observing a clock.
    103     pub const fn created_at(&self) -> UnixSeconds {
    104         self.created_at
    105     }
    106     /// Returns the positive declared author sequence, not verified continuity.
    107     pub const fn author_sequence(&self) -> Sequence {
    108         self.author_sequence
    109     }
    110     /// Returns the explicit previous-record claim; sequence1 requires None.
    111     pub const fn author_previous(&self) -> Option<RecordId> {
    112         self.author_previous
    113     }
    114     /// Borrows sorted unique full digests. Generic source identity does not
    115     /// convert a chat rumor, structured record or signed carrier into another.
    116     pub fn parents(&self) -> &[SourceId] {
    117         &self.parents
    118     }
    119     fn require(&self, parent: SourceId) -> Result<(), CommerceError> {
    120         if self.parents.contains(&parent) {
    121             Ok(())
    122         } else {
    123             Err(CommerceError::MissingParent)
    124         }
    125     }
    126     fn require_record(&self, parent: RecordId) -> Result<(), CommerceError> {
    127         self.require(source(parent))
    128     }
    129     fn require_optional(&self, parent: Option<RecordId>) -> Result<(), CommerceError> {
    130         match parent {
    131             Some(parent) => self.require_record(parent),
    132             None => Ok(()),
    133         }
    134     }
    135     fn terms(&self, terms: &Terms) -> Result<(), CommerceError> {
    136         if terms.buyer() != self.buyer || terms.seller() != self.seller {
    137             return Err(CommerceError::TermsPartiesMismatch);
    138         }
    139         for line in terms.lines() {
    140             self.require(SourceId::from_bytes(line.source().event_id().into_bytes()))?;
    141         }
    142         Ok(())
    143     }
    144 }
    145 
    146 /// Closed logical record-family vocabulary; this is not a Nostr numeric kind.
    147 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    148 #[non_exhaustive]
    149 pub enum CommerceType {
    150     /// Complete seller quote.
    151     Quote,
    152     /// Complete buyer request.
    153     Request,
    154     /// Seller refusal of a request.
    155     Decline,
    156     /// Complete initial/replacement terms proposal.
    157     TermsProposed,
    158     /// Counterparty terms authorization claim.
    159     TermsAuthorized,
    160     /// Counterparty proposal rejection claim.
    161     TermsRejected,
    162     /// Seller agreement commitment claim.
    163     AgreementCommitted,
    164     /// Buyer request to withdraw an authorization.
    165     WithdrawalRequested,
    166     /// Seller withdrawal-decision acknowledgement.
    167     WithdrawalAcknowledged,
    168     /// Bilateral residual-cancellation proposal.
    169     CancellationProposed,
    170     /// Counterparty cancellation authorization claim.
    171     CancellationAuthorized,
    172     /// Seller residual-release claim.
    173     ResidualReleased,
    174     /// Seller readiness assertion.
    175     Ready,
    176     /// Seller handover assertion.
    177     Handover,
    178     /// Independent buyer observation.
    179     Receipt,
    180     /// Participant issue report.
    181     Issue,
    182     /// Complete issue-resolution proposal.
    183     ResolutionProposed,
    184     /// Counterparty resolution authorization claim.
    185     ResolutionAuthorized,
    186     /// Seller resolution-commitment claim.
    187     ResolutionCommitted,
    188 }
    189 impl CommerceType {
    190     /// Returns the exact closed content token, never a placeholder rumor kind.
    191     pub const fn as_str(self) -> &'static str {
    192         match self {
    193             Self::Quote => "quote",
    194             Self::Request => "request",
    195             Self::Decline => "decline",
    196             Self::TermsProposed => "terms_proposed",
    197             Self::TermsAuthorized => "terms_authorized",
    198             Self::TermsRejected => "terms_rejected",
    199             Self::AgreementCommitted => "agreement_committed",
    200             Self::WithdrawalRequested => "withdrawal_requested",
    201             Self::WithdrawalAcknowledged => "withdrawal_acknowledged",
    202             Self::CancellationProposed => "cancellation_proposed",
    203             Self::CancellationAuthorized => "cancellation_authorized",
    204             Self::ResidualReleased => "residual_released",
    205             Self::Ready => "ready",
    206             Self::Handover => "handover",
    207             Self::Receipt => "receipt",
    208             Self::Issue => "issue",
    209             Self::ResolutionProposed => "resolution_proposed",
    210             Self::ResolutionAuthorized => "resolution_authorized",
    211             Self::ResolutionCommitted => "resolution_committed",
    212         }
    213     }
    214     fn author(self, header: &CommerceHeader) -> Result<(), CommerceError> {
    215         let valid = match self {
    216             Self::Quote
    217             | Self::Decline
    218             | Self::AgreementCommitted
    219             | Self::WithdrawalAcknowledged
    220             | Self::ResidualReleased
    221             | Self::Ready
    222             | Self::Handover
    223             | Self::ResolutionCommitted => header.author == header.seller,
    224             Self::Request | Self::WithdrawalRequested | Self::Receipt => {
    225                 header.author == header.buyer
    226             }
    227             // The exact consenting/rejecting counterparty is determined from
    228             // authenticated parent proposals, never just these declarations.
    229             Self::TermsProposed
    230             | Self::TermsAuthorized
    231             | Self::TermsRejected
    232             | Self::CancellationProposed
    233             | Self::CancellationAuthorized
    234             | Self::Issue
    235             | Self::ResolutionProposed
    236             | Self::ResolutionAuthorized => true,
    237         };
    238         if valid {
    239             Ok(())
    240         } else {
    241             Err(CommerceError::InvalidAuthor)
    242         }
    243     }
    244 }
    245 
    246 /// Complete typed private payload alternatives. Each nested value is bounded;
    247 /// its asserted sources, authority and physical facts still need admission.
    248 #[derive(Clone, Eq, PartialEq)]
    249 #[non_exhaustive]
    250 pub enum CommercePayload {
    251     /// Complete seller quote with an optional generic inquiry/source reference.
    252     Quote(TermsQuote),
    253     /// Complete buyer request and optional exact structured quote.
    254     Request(TermsRequest),
    255     /// Request target and private refusal reason.
    256     Decline(RecordReason),
    257     /// Complete proposed terms and explicit optional base agreement.
    258     TermsProposed(TermsProposal),
    259     /// Exact proposal and complete-terms commitment claim.
    260     TermsAuthorized(TermsAuthorization),
    261     /// Exact proposal and private rejection reason.
    262     TermsRejected(RecordReason),
    263     /// Complete seller commitment metadata.
    264     AgreementCommitted(AgreementCommitment),
    265     /// Exact authorization and private withdrawal reason.
    266     WithdrawalRequested(RecordReason),
    267     /// Seller's explicit withdrawal-decision metadata.
    268     WithdrawalAcknowledged(WithdrawalAcknowledgement),
    269     /// Complete proposed residual release.
    270     CancellationProposed(CancellationProposal),
    271     /// Exact cancellation-proposal authorization claim.
    272     CancellationAuthorized(ProposalAuthorization),
    273     /// Complete seller residual-release metadata.
    274     ResidualReleased(ResidualRelease),
    275     /// Complete seller readiness assertion.
    276     Ready(ReadinessClaim),
    277     /// Complete seller handover/measurement assertion.
    278     Handover(HandoverClaim),
    279     /// Independent buyer receipt assertion.
    280     Receipt(ReceiptObservation),
    281     /// Complete bounded participant issue report.
    282     Issue(IssueReport),
    283     /// Complete proposed issue resolution.
    284     ResolutionProposed(ResolutionProposal),
    285     /// Exact resolution-proposal authorization claim.
    286     ResolutionAuthorized(ProposalAuthorization),
    287     /// Seller's complete resolution-commitment metadata.
    288     ResolutionCommitted(ResolutionCommitment),
    289 }
    290 impl CommercePayload {
    291     /// Returns the logical content family, without assigning a Nostr carrier kind.
    292     pub const fn record_type(&self) -> CommerceType {
    293         match self {
    294             Self::Quote(_) => CommerceType::Quote,
    295             Self::Request(_) => CommerceType::Request,
    296             Self::Decline(_) => CommerceType::Decline,
    297             Self::TermsProposed(_) => CommerceType::TermsProposed,
    298             Self::TermsAuthorized(_) => CommerceType::TermsAuthorized,
    299             Self::TermsRejected(_) => CommerceType::TermsRejected,
    300             Self::AgreementCommitted(_) => CommerceType::AgreementCommitted,
    301             Self::WithdrawalRequested(_) => CommerceType::WithdrawalRequested,
    302             Self::WithdrawalAcknowledged(_) => CommerceType::WithdrawalAcknowledged,
    303             Self::CancellationProposed(_) => CommerceType::CancellationProposed,
    304             Self::CancellationAuthorized(_) => CommerceType::CancellationAuthorized,
    305             Self::ResidualReleased(_) => CommerceType::ResidualReleased,
    306             Self::Ready(_) => CommerceType::Ready,
    307             Self::Handover(_) => CommerceType::Handover,
    308             Self::Receipt(_) => CommerceType::Receipt,
    309             Self::Issue(_) => CommerceType::Issue,
    310             Self::ResolutionProposed(_) => CommerceType::ResolutionProposed,
    311             Self::ResolutionAuthorized(_) => CommerceType::ResolutionAuthorized,
    312             Self::ResolutionCommitted(_) => CommerceType::ResolutionCommitted,
    313         }
    314     }
    315     fn references(&self, header: &CommerceHeader) -> Result<(), CommerceError> {
    316         match self {
    317             Self::Quote(value) => {
    318                 header.terms(value.terms())?;
    319                 if let Some(parent) = value.in_reply_to() {
    320                     header.require(parent)?;
    321                 }
    322             }
    323             Self::Request(value) => {
    324                 header.terms(value.terms())?;
    325                 header.require_optional(value.quote())?;
    326             }
    327             Self::Decline(value)
    328             | Self::TermsRejected(value)
    329             | Self::WithdrawalRequested(value) => header.require_record(value.target())?,
    330             Self::TermsProposed(value) => {
    331                 header.terms(value.terms())?;
    332                 header.require_optional(value.base_agreement())?;
    333             }
    334             Self::TermsAuthorized(value) => header.require_record(value.proposal())?,
    335             Self::AgreementCommitted(value) => {
    336                 header.require_optional(value.base_agreement())?;
    337                 header.require_record(value.authorization())?;
    338             }
    339             Self::WithdrawalAcknowledged(value) => header.require_record(value.withdrawal())?,
    340             Self::CancellationProposed(value) => header.require_record(value.agreement())?,
    341             Self::CancellationAuthorized(value) | Self::ResolutionAuthorized(value) => {
    342                 header.require_record(value.proposal())?
    343             }
    344             Self::ResidualReleased(value) => {
    345                 header.require_record(value.proposal())?;
    346                 header.require_record(value.authorization())?;
    347                 header.require_record(value.agreement())?;
    348             }
    349             Self::Ready(value) => header.require_record(value.agreement())?,
    350             Self::Handover(value) => header.require_record(value.agreement())?,
    351             Self::Receipt(value) => {
    352                 header.require_record(value.handover())?;
    353                 header.require_optional(value.supersedes())?;
    354             }
    355             Self::Issue(value) => {
    356                 for parent in value.source_records() {
    357                     header.require_record(*parent)?;
    358                 }
    359             }
    360             Self::ResolutionProposed(value) => {
    361                 header.require_record(value.agreement())?;
    362                 for parent in value
    363                     .resolution()
    364                     .issues()
    365                     .iter()
    366                     .chain(value.resolution().accepted_receipts())
    367                 {
    368                     header.require_record(*parent)?;
    369                 }
    370             }
    371             Self::ResolutionCommitted(value) => {
    372                 header.require_record(value.proposal())?;
    373                 header.require_record(value.authorization())?;
    374             }
    375         }
    376         Ok(())
    377     }
    378 }
    379 
    380 /// Complete version1 logical content before protocol-owned canonical record-ID
    381 /// computation. No automatic serialization, authentication or effect is exposed.
    382 #[derive(Clone, Eq, PartialEq)]
    383 pub struct CommerceContent {
    384     header: CommerceHeader,
    385     payload: CommercePayload,
    386 }
    387 impl CommerceContent {
    388     /// Checks self-contained declared role/order/terms/reference consistency.
    389     /// Parent authentication, exact cross-record scope/roles/coverage, deadline
    390     /// actionability, terms digests and agreement-relative economic/state checks
    391     /// remain mandatory before any consent, reduction, signing or stock effects.
    392     pub fn new(header: CommerceHeader, payload: CommercePayload) -> Result<Self, CommerceError> {
    393         let record_type = payload.record_type();
    394         if record_type != CommerceType::Quote && header.order_id.is_none() {
    395             return Err(CommerceError::InvalidOrder);
    396         }
    397         record_type.author(&header)?;
    398         payload.references(&header)?;
    399         Ok(Self { header, payload })
    400     }
    401     /// Returns the exact fixed supported content profile identity.
    402     pub const fn profile(&self) -> &'static str {
    403         "radroots.commerce"
    404     }
    405     /// Returns the exact fixed supported content version.
    406     pub const fn version(&self) -> u32 {
    407         1
    408     }
    409     /// Explicitly borrows the original declared causal/scope metadata.
    410     pub const fn header(&self) -> &CommerceHeader {
    411         &self.header
    412     }
    413     /// Explicitly borrows complete private payload data.
    414     pub const fn payload(&self) -> &CommercePayload {
    415         &self.payload
    416     }
    417     /// Returns the closed logical family; no numeric rumor kind is assigned.
    418     pub const fn record_type(&self) -> CommerceType {
    419         self.payload.record_type()
    420     }
    421 }
    422 fn source(record: RecordId) -> SourceId {
    423     SourceId::from_bytes(record.into_bytes())
    424 }
    425 
    426 /// Input-free record-value validation failure; no private text is retained.
    427 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    428 #[non_exhaustive]
    429 pub enum CommerceError {
    430     /// The declared buyer and seller are the same participant.
    431     PartiesCoincide,
    432     /// The declared author is not a participant or has the wrong fixed role.
    433     InvalidAuthor,
    434     /// A stateful order record lacks an order identity.
    435     InvalidOrder,
    436     /// A declared author/seller sequence is zero.
    437     InvalidSequence,
    438     /// First/later author sequence has the wrong explicit previous-link shape.
    439     InvalidPrevious,
    440     /// Parent references exceed8 or are not strictly sorted and unique.
    441     InvalidParents,
    442     /// A declared source required by this value is absent from the parent set.
    443     MissingParent,
    444     /// Complete terms name different participants from their common header.
    445     TermsPartiesMismatch,
    446     /// Bounded private text exceeds its declared character/UTF-8 limits.
    447     InvalidText,
    448     /// A line set has invalid count or duplicate line identities.
    449     InvalidLines,
    450     /// Measurements exceed bounds, repeat a line or name a line outside the claim.
    451     InvalidMeasurements,
    452     /// A source/reference set has invalid count or duplicate identities.
    453     InvalidReferences,
    454 }
    455 impl fmt::Display for CommerceError {
    456     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    457         f.write_str(match self {
    458             Self::PartiesCoincide => "commerce participants must be distinct",
    459             Self::InvalidAuthor => "invalid declared commerce author",
    460             Self::InvalidOrder => "commerce order identity required",
    461             Self::InvalidSequence => "commerce sequence must be positive",
    462             Self::InvalidPrevious => "invalid previous commerce record",
    463             Self::InvalidParents => "invalid commerce parent set",
    464             Self::MissingParent => "required commerce parent not declared",
    465             Self::TermsPartiesMismatch => "commerce terms participants differ",
    466             Self::InvalidText => "commerce text exceeds bound",
    467             Self::InvalidLines => "invalid commerce line set",
    468             Self::InvalidMeasurements => "invalid commerce measurements",
    469             Self::InvalidReferences => "invalid commerce references",
    470         })
    471     }
    472 }
    473 impl core::error::Error for CommerceError {}
    474 macro_rules! redacted {
    475     ($($name:ident),+)=> { $(impl fmt::Debug for $name {
    476         fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result { f.write_str(concat!(stringify!($name),"(<redacted>)")) }
    477     })+ };
    478 }
    479 redacted!(CommerceHeader, CommercePayload, CommerceContent);