terms.rs (8546B)
1 //! Explicit private Terms v1 disclosure and digest. Encoding authenticates no 2 //! source, consent, participant, authority, reservation or installed agreement. 3 4 use alloc::string::String; 5 use core::fmt; 6 use radroots_domain::{ 7 AgreementPrice, Money, SupplyCommitment, Terms, TermsDigest, Window, listing::FulfillmentMode, 8 }; 9 use sha2::{Digest as _, Sha256}; 10 use zeroize::Zeroizing; 11 12 pub(crate) mod writer; 13 use writer::Writer; 14 pub(crate) mod decode; 15 pub use decode::decode; 16 17 /// Private content budget. A complete record additionally includes its header; 18 /// fitting this Terms object alone does not prove that a record or rumor fits. 19 pub const TERMS_MAX_BYTES: usize = 16_384; 20 21 /// Fixed failures without private caller data or dependency diagnostics. 22 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 23 #[non_exhaustive] 24 pub enum TermsWireError { 25 /// A value cannot be represented by this exact canonical profile. 26 InvalidInput, 27 /// Complete escaped UTF-8 content exceeds its fixed byte limit. 28 LimitExceeded, 29 /// A future domain variant has no supported v1 wire representation. 30 UnsupportedProfile, 31 } 32 impl fmt::Display for TermsWireError { 33 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 34 f.write_str(match self { 35 Self::InvalidInput => "invalid terms profile", 36 Self::LimitExceeded => "terms byte limit exceeded", 37 Self::UnsupportedProfile => "unsupported terms profile", 38 }) 39 } 40 } 41 impl core::error::Error for TermsWireError {} 42 43 /// One explicit protected canonical disclosure. It has no automatic serialization 44 /// or cloning and supplies no authenticated evidence or permission to issue. 45 /// 46 /// ```compile_fail 47 /// use radroots_protocol::terms::EncodedTerms; 48 /// fn automatic<T: serde::Serialize>() {} 49 /// automatic::<EncodedTerms>(); 50 /// ``` 51 /// 52 /// ```compile_fail 53 /// use radroots_protocol::terms::EncodedTerms; 54 /// fn duplicate<T: Clone>() {} 55 /// duplicate::<EncodedTerms>(); 56 /// ``` 57 pub struct EncodedTerms { 58 wire: Zeroizing<String>, 59 digest: TermsDigest, 60 } 61 impl EncodedTerms { 62 /// Counts the complete escaped representation before allocating its sole 63 /// private output buffer, then computes the domain-separated Terms identity. 64 pub fn capture(terms: &Terms) -> Result<Self, TermsWireError> { 65 let mut count = Writer::counting(); 66 encode(terms, &mut count)?; 67 let mut output = Writer::emitting(count.len()); 68 encode(terms, &mut output)?; 69 if output.len() != count.len() { 70 return Err(TermsWireError::InvalidInput); 71 } 72 let wire = output.finish()?; 73 let mut hash = Sha256::new(); 74 hash.update(b"radroots.terms.v1\0"); 75 hash.update(wire.as_bytes()); 76 Ok(Self { 77 wire, 78 digest: TermsDigest::from_bytes(hash.finalize().into()), 79 }) 80 } 81 /// Explicitly borrows private complete canonical bytes for protected handling. 82 pub fn protected_wire(&self) -> &[u8] { 83 self.wire.as_bytes() 84 } 85 /// Returns the v1 content identity, without approval or signature evidence. 86 pub const fn digest(&self) -> TermsDigest { 87 self.digest 88 } 89 /// Returns this owner's fixed object plus retained private buffer capacity. 90 /// Caller-owned domain values and outer record/rumor costs are separate. 91 pub fn retained_bytes(&self) -> usize { 92 core::mem::size_of::<Self>() + self.wire.capacity() 93 } 94 } 95 impl fmt::Debug for EncodedTerms { 96 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 97 f.write_str("EncodedTerms(<redacted>)") 98 } 99 } 100 101 pub(crate) fn money(value: Money, out: &mut Writer) -> Result<(), TermsWireError> { 102 out.raw("{\"currency\":")?; 103 out.string(value.currency().code())?; 104 out.raw(",\"exponent\":")?; 105 out.integer(u16::from(value.currency().exponent()))?; 106 out.raw(",\"minor\":")?; 107 out.exact_string(value.minor())?; 108 out.raw("}") 109 } 110 pub(crate) fn window(value: Window, out: &mut Writer) -> Result<(), TermsWireError> { 111 out.raw("{\"end\":")?; 112 out.exact_string(value.end())?; 113 out.raw(",\"start\":")?; 114 out.exact_string(value.start())?; 115 out.raw(",\"timezone\":")?; 116 out.string(value.timezone().name())?; 117 out.raw("}") 118 } 119 pub(crate) fn encode(value: &Terms, out: &mut Writer) -> Result<(), TermsWireError> { 120 out.raw("{\"buyer\":")?; 121 out.string(&value.buyer().to_hex())?; 122 out.raw(",\"cancellation\":")?; 123 out.string(value.cancellation())?; 124 out.raw(",\"fulfillment\":[")?; 125 for (index, group) in value.fulfillment().iter().enumerate() { 126 if index != 0 { 127 out.raw(",")?; 128 } 129 out.raw("{\"id\":")?; 130 out.exact_string(group.id())?; 131 out.raw(",\"terms\":{\"address\":")?; 132 out.string(group.terms().address())?; 133 out.raw(",\"contact\":")?; 134 out.optional_string(group.terms().contact())?; 135 out.raw(",\"instructions\":")?; 136 out.string(group.terms().instructions())?; 137 out.raw(",\"mode\":")?; 138 out.string(match group.terms().mode() { 139 FulfillmentMode::Pickup => "pickup", 140 FulfillmentMode::Delivery => "delivery", 141 })?; 142 out.raw(",\"window\":")?; 143 window(group.terms().window(), out)?; 144 out.raw("}}")?; 145 } 146 out.raw("],\"fulfillment_charge\":")?; 147 money(value.fulfillment_charge(), out)?; 148 out.raw(",\"lines\":[")?; 149 for (index, line) in value.lines().iter().enumerate() { 150 if index != 0 { 151 out.raw(",")?; 152 } 153 out.raw("{\"amount\":")?; 154 out.exact_string(line.amount())?; 155 out.raw(",\"fulfillment_group\":")?; 156 out.exact_string(line.fulfillment_group())?; 157 out.raw(",\"id\":")?; 158 out.exact_string(line.id())?; 159 out.raw(",\"maximum_line_total\":")?; 160 money(line.maximum_line_total(), out)?; 161 out.raw(",\"option\":")?; 162 out.public_snapshot(line.option())?; 163 out.raw(",\"option_id\":")?; 164 out.exact_string(line.option_id())?; 165 out.raw(",\"price\":")?; 166 match line.price() { 167 AgreementPrice::Fixed(price) => { 168 out.raw("{\"basis\":")?; 169 out.exact_string(price.basis())?; 170 out.raw(",\"discount_bps\":")?; 171 out.integer(price.discount_bps().get())?; 172 out.raw(",\"rate\":")?; 173 money(price.rate(), out)?; 174 out.raw(",\"selected_tier_from\":")?; 175 match price.selected_tier_from() { 176 Some(value) => out.exact_string(value)?, 177 None => out.raw("null")?, 178 } 179 out.raw(",\"type\":\"fixed\"}")?; 180 } 181 AgreementPrice::VariableWeight(price) => { 182 out.raw("{\"basis\":")?; 183 out.exact_string(price.basis())?; 184 out.raw(",\"maximum\":")?; 185 out.exact_string(price.maximum())?; 186 out.raw(",\"maximum_total\":")?; 187 money(price.maximum_total(), out)?; 188 out.raw(",\"measurement_unit\":")?; 189 out.string(price.measurement_unit().symbol())?; 190 out.raw(",\"minimum\":")?; 191 out.exact_string(price.minimum())?; 192 out.raw(",\"rate\":")?; 193 money(price.rate(), out)?; 194 out.raw(",\"type\":\"variable_weight\"}")?; 195 } 196 _ => return Err(TermsWireError::UnsupportedProfile), 197 } 198 out.raw(",\"product\":")?; 199 out.public_snapshot(line.product())?; 200 out.raw(",\"source\":")?; 201 out.public_snapshot(&line.source())?; 202 out.raw(",\"source_lot_label\":")?; 203 out.optional_string(line.source_lot_label())?; 204 out.raw("}")?; 205 } 206 out.raw("],\"maximum_total\":")?; 207 money(value.maximum_total(), out)?; 208 out.raw(",\"rounding\":")?; 209 out.string(value.rounding())?; 210 out.raw(",\"seller\":")?; 211 out.string(&value.seller().to_hex())?; 212 out.raw(",\"supply\":")?; 213 match value.supply() { 214 SupplyCommitment::StockBacked => out.raw("{\"type\":\"stock_backed\"}")?, 215 SupplyCommitment::FuturePromise(promise) => { 216 out.raw("{\"expected_window\":")?; 217 window(promise.expected_window(), out)?; 218 out.raw(",\"risk_disclosure\":")?; 219 out.string(promise.risk_disclosure())?; 220 out.raw(",\"type\":\"future_promise\"}")?; 221 } 222 _ => return Err(TermsWireError::UnsupportedProfile), 223 } 224 out.raw("}") 225 }