stock.rs (16792B)
1 //! Pure physical-stock values. A balanced snapshot proves no provenance, 2 //! availability, permission, selected executor or durable stock effect. 3 4 use crate::{PoolId, Quantity, Sequence, listing::MeasurementUnit}; 5 use core::{fmt, str::FromStr}; 6 mod allocation; 7 mod mapping; 8 mod movements; 9 mod obligation; 10 mod replacement; 11 pub use allocation::{ 12 AllocationClaim, AllocationPlanError, PoolHoldProposal, StockAllocation, plan_allocations, 13 resolve_allocations, 14 }; 15 pub use mapping::{MappingError, OptionMappingKey, OptionPoolMapping}; 16 pub use movements::{HeldStockCategory, HeldStockLoss}; 17 pub use obligation::ObligationBacking; 18 pub use replacement::{ 19 ReplacementAllocationPlan, plan_replacement_allocations, resolve_replacement_allocations, 20 }; 21 22 /// A bounded, input-free stock value failure. 23 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 24 #[non_exhaustive] 25 pub enum StockError { 26 /// Integer input is not a canonical unsigned decimal string. 27 InvalidFormat, 28 /// Ticks exceed the supported maximum, including checked addition. 29 OutOfRange, 30 /// Subtraction would produce a negative balance. 31 Underflow, 32 /// A pool scale exceeds six fractional decimal places. 33 InvalidScale, 34 /// Each-count pools cannot have fractional precision. 35 FractionalCount, 36 /// The declared quantity and pool use different units. 37 UnitMismatch, 38 /// The quantity cannot be represented by integral pool ticks. 39 PrecisionLoss, 40 /// The seven physical categories do not sum to introduced stock. 41 ConservationViolation, 42 /// Backed remaining and deficit do not equal the remaining obligation. 43 ObligationMismatch, 44 /// An accounting movement cannot have zero quantity. 45 ZeroMovement, 46 } 47 impl fmt::Display for StockError { 48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 49 f.write_str(match self { 50 Self::InvalidFormat => "stock ticks must be a canonical unsigned integer", 51 Self::OutOfRange => "stock ticks exceed the supported bound", 52 Self::Underflow => "stock balance would be negative", 53 Self::InvalidScale => "stock scale exceeds six decimal places", 54 Self::FractionalCount => "each-count stock requires integral precision", 55 Self::UnitMismatch => "stock quantity unit differs from pool unit", 56 Self::PrecisionLoss => "stock quantity cannot be represented by integral ticks", 57 Self::ConservationViolation => { 58 "physical stock categories do not conserve introduced stock" 59 } 60 Self::ObligationMismatch => "backing and deficit do not reconcile the obligation", 61 Self::ZeroMovement => "accounting movement quantity must be positive", 62 }) 63 } 64 } 65 impl core::error::Error for StockError {} 66 67 /// Exact integral pool ticks, including zero, bounded by10^18. 68 #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] 69 pub struct StockTicks(u64); 70 impl StockTicks { 71 /// Largest admitted physical balance in ticks. 72 pub const MAX: Self = Self(1_000_000_000_000_000_000); 73 /// Exact zero ticks. 74 pub const ZERO: Self = Self(0); 75 /// Validates an integral Rust input; this grants no stock authority. 76 pub const fn new(value: u64) -> Result<Self, StockError> { 77 if value > Self::MAX.0 { 78 return Err(StockError::OutOfRange); 79 } 80 Ok(Self(value)) 81 } 82 /// Returns the exact integer; foreign numeric boundaries use integer strings. 83 pub const fn get(self) -> u64 { 84 self.0 85 } 86 /// Adds ticks without wrapping or exceeding the stock bound. 87 pub fn checked_add(self, other: Self) -> Result<Self, StockError> { 88 Self::new(self.0.checked_add(other.0).ok_or(StockError::OutOfRange)?) 89 } 90 /// Subtracts ticks without clamping a negative result to zero. 91 pub fn checked_sub(self, other: Self) -> Result<Self, StockError> { 92 Self::new(self.0.checked_sub(other.0).ok_or(StockError::Underflow)?) 93 } 94 } 95 impl FromStr for StockTicks { 96 type Err = StockError; 97 fn from_str(value: &str) -> Result<Self, Self::Err> { 98 if value.is_empty() 99 || value.len() > 19 100 || !value.bytes().all(|v| v.is_ascii_digit()) 101 || (value.len() > 1 && value.starts_with('0')) 102 { 103 return Err(StockError::InvalidFormat); 104 } 105 Self::new(value.parse().map_err(|_| StockError::OutOfRange)?) 106 } 107 } 108 impl fmt::Display for StockTicks { 109 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 110 self.0.fmt(f) 111 } 112 } 113 impl fmt::Debug for StockTicks { 114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 115 f.write_str("StockTicks(<redacted>)") 116 } 117 } 118 #[cfg(feature = "serde")] 119 impl serde::Serialize for StockTicks { 120 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { 121 serializer.collect_str(self) 122 } 123 } 124 #[cfg(feature = "serde")] 125 impl<'de> serde::Deserialize<'de> for StockTicks { 126 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { 127 struct Visitor; 128 impl serde::de::Visitor<'_> for Visitor { 129 type Value = StockTicks; 130 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 131 f.write_str("bounded stock ticks as a canonical integer string") 132 } 133 fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<StockTicks, E> { 134 value.parse().map_err(E::custom) 135 } 136 } 137 deserializer.deserialize_str(Visitor) 138 } 139 } 140 141 /// One explicit physical unit and fractional precision for an entire pool. 142 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 143 pub struct PoolUnit { 144 unit: MeasurementUnit, 145 scale: u8, 146 } 147 impl PoolUnit { 148 /// Admits precision0–6, with scale zero for each counts. 149 pub const fn new(unit: MeasurementUnit, scale: u8) -> Result<Self, StockError> { 150 if scale > 6 { 151 return Err(StockError::InvalidScale); 152 } 153 if matches!(unit, MeasurementUnit::Each) && scale != 0 { 154 return Err(StockError::FractionalCount); 155 } 156 Ok(Self { unit, scale }) 157 } 158 /// Returns the fixed pool unit, without converting another unit. 159 pub const fn unit(self) -> MeasurementUnit { 160 self.unit 161 } 162 /// Returns fractional decimal places represented by one tick. 163 pub const fn scale(self) -> u8 { 164 self.scale 165 } 166 /// Converts only an exactly matching declared unit and precision. Compatible 167 /// unit conversion must be requested explicitly on `Quantity` beforehand. 168 pub fn ticks_for(self, quantity: Quantity) -> Result<StockTicks, StockError> { 169 if quantity.unit() != self.unit { 170 return Err(StockError::UnitMismatch); 171 } 172 let amount = quantity.amount(); 173 let difference = self 174 .scale 175 .checked_sub(amount.scale()) 176 .ok_or(StockError::PrecisionLoss)?; 177 let factor = 10_u64.pow(u32::from(difference)); 178 StockTicks::new( 179 amount 180 .coefficient() 181 .checked_mul(factor) 182 .ok_or(StockError::OutOfRange)?, 183 ) 184 } 185 } 186 187 /// Seven disjoint claimed balances. Validate their total with `PoolBalances`. 188 /// Released quantities are movements back to available, never an eighth balance. 189 #[derive(Clone, Copy, Eq, PartialEq)] 190 pub struct PhysicalBalances { 191 /// Unheld physical stock. 192 pub available: StockTicks, 193 /// Physical stock held before commitment issuance is resolved. 194 pub preparatory_hold: StockTicks, 195 /// Remaining physical backing of installed commitments. 196 pub committed_hold: StockTicks, 197 /// Physical backing retained under unresolved risk. 198 pub physical_quarantine: StockTicks, 199 /// Cumulative physical stock consumed by handover. 200 pub consumed: StockTicks, 201 /// Cumulative physically present stock moved to waste. 202 pub waste: StockTicks, 203 /// Cumulative physical stock explicitly removed. 204 pub removed: StockTicks, 205 } 206 impl PhysicalBalances { 207 /// All seven categories are empty. 208 pub const ZERO: Self = Self { 209 available: StockTicks::ZERO, 210 preparatory_hold: StockTicks::ZERO, 211 committed_hold: StockTicks::ZERO, 212 physical_quarantine: StockTicks::ZERO, 213 consumed: StockTicks::ZERO, 214 waste: StockTicks::ZERO, 215 removed: StockTicks::ZERO, 216 }; 217 } 218 impl fmt::Debug for PhysicalBalances { 219 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 220 f.write_str("PhysicalBalances(<redacted>)") 221 } 222 } 223 224 /// A conservation-checked physical balance claim, without authority or effects. 225 #[derive(Clone, Copy, Eq, PartialEq)] 226 pub struct PoolBalances { 227 introduced: StockTicks, 228 physical: PhysicalBalances, 229 } 230 /// Claimed owner-private correction of available stock. Permission, current 231 /// versions and any held-stock obligation policy belong to the executor. 232 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 233 pub enum AvailableStockCorrection { 234 /// Increase cumulative introduced stock and currently available backing. 235 Add, 236 /// Move currently available physical backing to cumulative removed stock. 237 Remove, 238 /// Move currently available physical backing to cumulative waste. 239 Spoil, 240 } 241 impl PoolBalances { 242 /// Admits only an exact sum of the seven disjoint physical categories. 243 /// Future promises and obligation deficits cannot be counted as stock. 244 pub fn new(introduced: StockTicks, physical: PhysicalBalances) -> Result<Self, StockError> { 245 let values = [ 246 physical.available, 247 physical.preparatory_hold, 248 physical.committed_hold, 249 physical.physical_quarantine, 250 physical.consumed, 251 physical.waste, 252 physical.removed, 253 ]; 254 let sum = values 255 .into_iter() 256 .try_fold(StockTicks::ZERO, StockTicks::checked_add)?; 257 if sum != introduced { 258 return Err(StockError::ConservationViolation); 259 } 260 Ok(Self { 261 introduced, 262 physical, 263 }) 264 } 265 /// Returns cumulative introduced physical stock, including positive corrections. 266 pub const fn introduced(self) -> StockTicks { 267 self.introduced 268 } 269 /// Returns the seven conservation-checked balances. 270 pub const fn physical(self) -> PhysicalBalances { 271 self.physical 272 } 273 /// Proposes a positive transfer from available to preparatory backing. 274 /// Lifetime introduced and all other categories remain unchanged. This 275 /// value performs no reservation; the executor must atomically confirm its 276 /// authority, complete allocation, versions and order/operation fence. 277 pub fn hold_available(self, quantity: StockTicks) -> Result<Self, StockError> { 278 if quantity == StockTicks::ZERO { 279 return Err(StockError::ZeroMovement); 280 } 281 let mut physical = self.physical; 282 physical.available = physical.available.checked_sub(quantity)?; 283 physical.preparatory_hold = physical.preparatory_hold.checked_add(quantity)?; 284 Self::new(self.introduced, physical) 285 } 286 /// Proposes conversion of this exact positive preparatory quantity into 287 /// installed physical backing. Other orders' holds and lifetime introduced 288 /// stock remain unchanged. The executor must authenticate original allocation 289 /// and peer evidence and commit every affected pool with installation. 290 pub fn install_preparatory(self, quantity: StockTicks) -> Result<Self, StockError> { 291 if quantity == StockTicks::ZERO { 292 return Err(StockError::ZeroMovement); 293 } 294 let mut physical = self.physical; 295 physical.preparatory_hold = physical.preparatory_hold.checked_sub(quantity)?; 296 physical.committed_hold = physical.committed_hold.checked_add(quantity)?; 297 Self::new(self.introduced, physical) 298 } 299 /// Proposes release of this exact positive preparatory quantity back to 300 /// available backing. It creates no stock and changes no committed or 301 /// quarantined claim. The executor must prove the original operation is 302 /// unissued and atomically retain the abort, original quantities and release. 303 pub fn release_preparatory(self, quantity: StockTicks) -> Result<Self, StockError> { 304 if quantity == StockTicks::ZERO { 305 return Err(StockError::ZeroMovement); 306 } 307 let mut physical = self.physical; 308 physical.preparatory_hold = physical.preparatory_hold.checked_sub(quantity)?; 309 physical.available = physical.available.checked_add(quantity)?; 310 Self::new(self.introduced, physical) 311 } 312 /// Proposes a nonzero, exact correction against available backing only. 313 /// Held or quarantined stock is never silently substituted for available 314 /// stock. Depleting it needs a separate obligation/deficit transition. 315 /// Failure returns no changed value and preserves the original snapshot. 316 pub fn correct_available( 317 self, 318 kind: AvailableStockCorrection, 319 quantity: StockTicks, 320 ) -> Result<Self, StockError> { 321 if quantity == StockTicks::ZERO { 322 return Err(StockError::ZeroMovement); 323 } 324 let mut physical = self.physical; 325 let introduced = match kind { 326 AvailableStockCorrection::Add => { 327 let introduced = self.introduced.checked_add(quantity)?; 328 physical.available = physical.available.checked_add(quantity)?; 329 introduced 330 } 331 AvailableStockCorrection::Remove | AvailableStockCorrection::Spoil => { 332 physical.available = physical.available.checked_sub(quantity)?; 333 let cumulative = if kind == AvailableStockCorrection::Remove { 334 &mut physical.removed 335 } else { 336 &mut physical.waste 337 }; 338 *cumulative = cumulative.checked_add(quantity)?; 339 self.introduced 340 } 341 }; 342 Self::new(introduced, physical) 343 } 344 } 345 impl fmt::Debug for PoolBalances { 346 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 347 f.write_str("PoolBalances(<redacted>)") 348 } 349 } 350 351 /// A versioned claimed pool projection. Authentication and durable version 352 /// admission belong to the selected executor, never this value constructor. 353 #[derive(Clone, Copy, Eq, PartialEq)] 354 pub struct PoolSnapshot { 355 id: PoolId, 356 unit: PoolUnit, 357 balances: PoolBalances, 358 version: Sequence, 359 } 360 impl PoolSnapshot { 361 /// Combines already-validated values; version zero is an explicit genesis. 362 pub const fn new( 363 id: PoolId, 364 unit: PoolUnit, 365 balances: PoolBalances, 366 version: Sequence, 367 ) -> Self { 368 Self { 369 id, 370 unit, 371 balances, 372 version, 373 } 374 } 375 /// Returns the declared pool identity. 376 pub const fn id(self) -> PoolId { 377 self.id 378 } 379 /// Returns this pool's fixed unit/precision. 380 pub const fn unit(self) -> PoolUnit { 381 self.unit 382 } 383 /// Returns the validated physical balance claim. 384 pub const fn balances(self) -> PoolBalances { 385 self.balances 386 } 387 /// Returns the declared pool revision; this is not an authority generation. 388 pub const fn version(self) -> Sequence { 389 self.version 390 } 391 } 392 impl fmt::Debug for PoolSnapshot { 393 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 394 f.write_str("PoolSnapshot(<redacted>)") 395 } 396 } 397 398 #[cfg(feature = "serde")] 399 mod serialization; 400 401 /// Bounded owner-private pool metadata and its physical snapshot claim. 402 /// This view grants no authority and is not independent proof of availability. 403 #[derive(Clone, Eq, PartialEq)] 404 pub struct PoolView { 405 label: zeroize::Zeroizing<alloc::string::String>, 406 snapshot: PoolSnapshot, 407 } 408 impl PoolView { 409 /// Preserves a plain bounded label without normalization or hidden defaults. 410 pub fn new(label: &str, snapshot: PoolSnapshot) -> Result<Self, StockError> { 411 if label.len() > 160 || label.chars().any(char::is_control) { 412 return Err(StockError::InvalidFormat); 413 } 414 Ok(Self { 415 label: zeroize::Zeroizing::new(alloc::string::String::from(label)), 416 snapshot, 417 }) 418 } 419 /// Borrows the exact owner-private label. 420 pub fn label(&self) -> &str { 421 &self.label 422 } 423 /// Returns the associated validated physical snapshot claim. 424 pub const fn snapshot(&self) -> PoolSnapshot { 425 self.snapshot 426 } 427 } 428 impl fmt::Debug for PoolView { 429 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 430 f.write_str("PoolView(<redacted>)") 431 } 432 }