commerce.rs (7627B)
1 //! Complete private record data and canonical identities. No authenticated 2 //! consent, current authority, issuance or stock capability is created here. 3 use crate::{ 4 profile, 5 terms::{TermsWireError, writer::Writer}, 6 }; 7 use alloc::string::String; 8 use core::fmt; 9 use radroots_domain::{CommerceContent, PublicKey, RecordId}; 10 use sha2::{Digest as _, Sha256}; 11 use zeroize::Zeroizing; 12 13 mod coverage; 14 mod decode; 15 pub use coverage::CapturedCausalCoverage; 16 mod seal; 17 pub use seal::CommerceSeal; 18 mod signing_plan; 19 pub use signing_plan::{CommerceSigningPlan, SIGNING_PLAN_MAX_BYTES}; 20 mod initial_commitment; 21 pub use initial_commitment::initial_commitment_rumor; 22 mod replacement_commitment; 23 pub use replacement_commitment::replacement_commitment_rumor; 24 mod payload; 25 pub use decode::{DecodedRecord, decode}; 26 mod rumor; 27 pub use rumor::EncodedCommerceRumor; 28 29 /// The complete private content budget, including record ID, header and payload. 30 pub const RECORD_MAX_BYTES: usize = profile::PRIVATE_RECORD_MAX_BYTES; 31 32 /// Input-free record codec failures. None contains private source data. 33 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 34 #[non_exhaustive] 35 pub enum RecordWireError { 36 /// A closed field or complete domain invariant is invalid. 37 InvalidInput, 38 /// Complete content or a nested profile exceeds a supported bound. 39 LimitExceeded, 40 /// A future profile or vocabulary has no supported representation. 41 UnsupportedProfile, 42 /// The supplied record identity differs from complete canonical content. 43 IdentityMismatch, 44 /// Final rumor kind, author or timestamp differs from the content claims. 45 CarrierMismatch, 46 } 47 impl fmt::Display for RecordWireError { 48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 49 f.write_str(match self { 50 Self::InvalidInput => "invalid record profile", 51 Self::LimitExceeded => "record byte limit exceeded", 52 Self::UnsupportedProfile => "unsupported record profile", 53 Self::IdentityMismatch => "record identity mismatch", 54 Self::CarrierMismatch => "record carrier mismatch", 55 }) 56 } 57 } 58 impl core::error::Error for RecordWireError {} 59 impl From<TermsWireError> for RecordWireError { 60 fn from(value: TermsWireError) -> Self { 61 match value { 62 TermsWireError::LimitExceeded => Self::LimitExceeded, 63 TermsWireError::UnsupportedProfile => Self::UnsupportedProfile, 64 _ => Self::InvalidInput, 65 } 66 } 67 } 68 69 /// Explicit canonical private disclosure, with no automatic serialization, 70 /// cloning or permission to issue a structured rumor. 71 /// 72 /// ```compile_fail 73 /// use radroots_protocol::commerce::EncodedRecord; 74 /// fn automatic<T: serde::Serialize>() {} 75 /// automatic::<EncodedRecord>(); 76 /// ``` 77 /// ```compile_fail 78 /// use radroots_protocol::commerce::EncodedRecord; 79 /// fn duplicate<T: Clone>() {} 80 /// duplicate::<EncodedRecord>(); 81 /// ``` 82 pub struct EncodedRecord { 83 wire: Zeroizing<String>, 84 identity: RecordId, 85 author: PublicKey, 86 created_at: u64, 87 } 88 impl EncodedRecord { 89 /// Checks the complete final size before private output allocation. The 90 /// zeroizing hash preimage is dropped before allocating the final wire. 91 pub fn capture(content: &CommerceContent) -> Result<Self, RecordWireError> { 92 if content.profile() != profile::COMMERCE_PROFILE 93 || content.version() != profile::PROFILE_VERSION 94 { 95 return Err(RecordWireError::UnsupportedProfile); 96 } 97 let mut complete = Writer::counting(); 98 encode(content, Some(RecordId::from_bytes([0; 32])), &mut complete)?; 99 if complete.len() > RECORD_MAX_BYTES { 100 return Err(RecordWireError::LimitExceeded); 101 } 102 let mut count = Writer::counting(); 103 encode(content, None, &mut count)?; 104 let mut preimage = Writer::emitting(count.len()); 105 encode(content, None, &mut preimage)?; 106 if preimage.len() != count.len() { 107 return Err(RecordWireError::InvalidInput); 108 } 109 let bytes = preimage.finish()?; 110 let mut hash = Sha256::new(); 111 hash.update(b"radroots.record.v1\0"); 112 hash.update(bytes.as_bytes()); 113 let identity = RecordId::from_bytes(hash.finalize().into()); 114 drop(bytes); 115 let mut output = Writer::emitting(complete.len()); 116 encode(content, Some(identity), &mut output)?; 117 if output.len() != complete.len() { 118 return Err(RecordWireError::InvalidInput); 119 } 120 Ok(Self { 121 wire: output.finish()?, 122 identity, 123 author: content.header().author(), 124 created_at: content.header().created_at().get(), 125 }) 126 } 127 /// Borrows complete private content for explicitly protected handling. 128 pub fn protected_wire(&self) -> &[u8] { 129 self.wire.as_bytes() 130 } 131 /// Returns the content identity, distinct from a rumor or envelope ID. 132 pub const fn record_id(&self) -> RecordId { 133 self.identity 134 } 135 /// Reports this owner's object and retained private buffer capacity. 136 pub fn retained_bytes(&self) -> usize { 137 core::mem::size_of::<Self>() + self.wire.capacity() 138 } 139 /// Checks equality with final rumor claims. The caller must separately 140 /// authenticate the original wrap/seal/rumor and bind its recipient; this 141 /// comparison creates no authenticated evidence or permission. 142 pub fn check_rumor_fields( 143 &self, 144 author: PublicKey, 145 created_at: u64, 146 kind: u16, 147 ) -> Result<(), RecordWireError> { 148 if kind != profile::COMMERCE_KIND || author != self.author || created_at != self.created_at 149 { 150 return Err(RecordWireError::CarrierMismatch); 151 } 152 Ok(()) 153 } 154 } 155 impl fmt::Debug for EncodedRecord { 156 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 157 f.write_str("EncodedRecord(<redacted>)") 158 } 159 } 160 fn optional<T: fmt::Display>(value: Option<T>, out: &mut Writer) -> Result<(), TermsWireError> { 161 match value { 162 Some(value) => out.exact_string(value), 163 None => out.raw("null"), 164 } 165 } 166 fn ids<T: fmt::Display>(values: &[T], out: &mut Writer) -> Result<(), TermsWireError> { 167 out.raw("[")?; 168 for (index, value) in values.iter().enumerate() { 169 if index != 0 { 170 out.raw(",")?; 171 } 172 out.exact_string(value)?; 173 } 174 out.raw("]") 175 } 176 fn encode( 177 value: &CommerceContent, 178 identity: Option<RecordId>, 179 out: &mut Writer, 180 ) -> Result<(), TermsWireError> { 181 let header = value.header(); 182 out.raw("{\"author\":")?; 183 out.exact_string(header.author())?; 184 out.raw(",\"author_previous\":")?; 185 optional(header.author_previous(), out)?; 186 out.raw(",\"author_sequence\":")?; 187 out.exact_string(header.author_sequence())?; 188 out.raw(",\"buyer\":")?; 189 out.exact_string(header.buyer())?; 190 out.raw(",\"created_at\":")?; 191 out.exact_string(header.created_at())?; 192 out.raw(",\"order_id\":")?; 193 optional(header.order_id(), out)?; 194 out.raw(",\"parents\":")?; 195 ids(header.parents(), out)?; 196 out.raw(",\"payload\":")?; 197 payload::encode(value.payload(), out)?; 198 out.raw(",\"profile\":")?; 199 out.string(value.profile())?; 200 if let Some(identity) = identity { 201 out.raw(",\"record_id\":")?; 202 out.exact_string(identity)?; 203 } 204 out.raw(",\"seller\":")?; 205 out.exact_string(header.seller())?; 206 out.raw(",\"thread_id\":")?; 207 out.exact_string(header.thread_id())?; 208 out.raw(",\"type\":")?; 209 out.string(value.record_type().as_str())?; 210 out.raw(",\"version\":1}") 211 }