deficit.rs (11287B)
1 //! Catalog19 owner-private losses against retained, installed original allocations. 2 //! The SQL index is only a projection. Full protected ancestry authenticates its 3 //! complete contents and is reread under the same final transaction fence. 4 use super::*; 5 use radroots_domain::{ 6 AgreementLineId, PublicKey, 7 stock::{ObligationBacking, StockTicks}, 8 }; 9 10 pub(super) const MAX_LOSSES: usize = 32; 11 12 #[derive(Clone, Eq, PartialEq, Serialize, Deserialize)] 13 #[serde(deny_unknown_fields)] 14 pub(super) struct Loss { 15 pub(super) acceptance: OperationId, 16 pub(super) installation: OperationId, 17 pub(super) line: AgreementLineId, 18 pub(super) before: ObligationBacking, 19 pub(super) after: ObligationBacking, 20 } 21 impl Loss { 22 pub(super) fn quantity(&self) -> Result<StockTicks, OperationError> { 23 let quantity = self 24 .before 25 .backed() 26 .checked_sub(self.after.backed()) 27 .map_err(|_| OperationError::RecoveryRequired)?; 28 if quantity == StockTicks::ZERO 29 || self.before.lose_backing(quantity).ok() != Some(self.after) 30 { 31 return Err(OperationError::RecoveryRequired); 32 } 33 Ok(quantity) 34 } 35 pub(super) fn metadata(&self, pool: PoolId) -> radroots_storage::inventory::StockDeficit { 36 radroots_storage::inventory::StockDeficit::from_host_metadata( 37 self.acceptance, 38 self.installation, 39 self.line, 40 pool, 41 self.after, 42 ) 43 } 44 } 45 46 /// Available stock is corrected first. Any remainder selects still-backed 47 /// installed allocations by original installation revision then original line 48 /// order. Preparatory and quarantined claims are never silently depleted. 49 pub(super) async fn plan( 50 connection: &mut SqliteConnection, 51 input: &AttachmentInput, 52 crypto: &WorkspaceCrypto, 53 command: &radroots_storage::inventory::CapturedInventoryCommand, 54 before: Option<PoolSnapshot>, 55 before_revision: u64, 56 ) -> Result<Vec<Loss>, OperationError> { 57 use radroots_domain::stock::AvailableStockCorrection; 58 let radroots_storage::inventory::CapturedInventoryCommand::CorrectPool(command) = command 59 else { 60 return Ok(Vec::new()); 61 }; 62 if command.input().kind() == AvailableStockCorrection::Add { 63 return Ok(Vec::new()); 64 } 65 let pool = before.ok_or(OperationError::StaleState)?; 66 if pool.id() != command.input().pool_id() 67 || pool.version() != command.input().expected_version() 68 { 69 return Err(OperationError::StaleState); 70 } 71 let quantity = pool 72 .unit() 73 .ticks_for( 74 radroots_domain::Quantity::new(command.input().amount().amount(), pool.unit().unit()) 75 .map_err(|_| OperationError::InvalidCommand)?, 76 ) 77 .map_err(|_| OperationError::InvalidCommand)?; 78 let physical = pool.balances().physical(); 79 if quantity <= physical.available { 80 return Ok(Vec::new()); 81 } 82 let mut remaining = quantity 83 .checked_sub(physical.available) 84 .map_err(|_| OperationError::InvalidCommand)?; 85 if remaining > physical.committed_hold { 86 return Err(OperationError::StaleState); 87 } 88 let mut cursor = super::allocations::InstalledCursor::new(pool.id(), before_revision)?; 89 let mut losses = Vec::new(); 90 while remaining != StockTicks::ZERO { 91 let allocation = Box::pin(cursor.next(connection, input, crypto)) 92 .await? 93 .ok_or(OperationError::RecoveryRequired)?; 94 let before = allocation 95 .backing(connection, input, crypto, before_revision) 96 .await?; 97 let backed = before.backed(); 98 if backed == StockTicks::ZERO { 99 continue; 100 } 101 if losses.len() == MAX_LOSSES { 102 return Err(WorkspaceError::Capacity.into()); 103 } 104 let quantity = remaining.min(backed); 105 let after = before 106 .lose_backing(quantity) 107 .map_err(|_| OperationError::RecoveryRequired)?; 108 losses.push(Loss { 109 acceptance: allocation.acceptance, 110 installation: allocation.installation, 111 line: allocation.allocation.line_id(), 112 before, 113 after, 114 }); 115 remaining = remaining 116 .checked_sub(quantity) 117 .map_err(|_| OperationError::RecoveryRequired)?; 118 } 119 Ok(losses) 120 } 121 122 pub(super) fn quantity(losses: &[Loss]) -> Result<StockTicks, OperationError> { 123 if losses.len() > MAX_LOSSES { 124 return Err(WorkspaceError::Capacity.into()); 125 } 126 let mut quantity = StockTicks::ZERO; 127 for (index, loss) in losses.iter().enumerate() { 128 if losses[..index] 129 .iter() 130 .any(|prior| prior.acceptance == loss.acceptance && prior.line == loss.line) 131 { 132 return Err(OperationError::RecoveryRequired); 133 } 134 quantity = quantity 135 .checked_add(loss.quantity()?) 136 .map_err(|_| OperationError::RecoveryRequired)?; 137 } 138 Ok(quantity) 139 } 140 141 /// Index rows contain only identities. Actual prior quantities remain inside 142 /// bounded protected operation bodies; no plaintext numeric sum is authoritative. 143 #[expect( 144 clippy::too_many_arguments, 145 reason = "exact original allocation and revision boundary" 146 )] 147 pub(super) async fn prior_quantity( 148 connection: &mut SqliteConnection, 149 input: &AttachmentInput, 150 crypto: &WorkspaceCrypto, 151 acceptance: OperationId, 152 installation: OperationId, 153 line: AgreementLineId, 154 pool: PoolId, 155 before_revision: u64, 156 ) -> Result<StockTicks, OperationError> { 157 let mut quantity = StockTicks::ZERO; 158 let mut cursor = 0_u64; 159 loop { 160 let row = sqlx::query("SELECT o.revision,CASE WHEN length(o.operation_id)=32 THEN o.operation_id END FROM stock_deficits d JOIN stock_operations o ON o.actor=d.actor AND o.operation_id=d.operation_id WHERE d.actor=? AND d.acceptance_id=? AND d.installation_id=? AND d.line_id=? AND d.pool_id=? AND o.revision>? AND o.revision<? ORDER BY o.revision LIMIT 1") 161 .bind(input.participant().as_bytes().as_slice()).bind(acceptance.as_bytes().as_slice()) 162 .bind(installation.as_bytes().as_slice()).bind(line.as_bytes().as_slice()) 163 .bind(pool.as_bytes().as_slice()).bind(cursor as i64).bind(before_revision as i64) 164 .fetch_optional(&mut *connection).await.map_err(|_| OperationError::RecoveryRequired)?; 165 let Some(row) = row else { 166 return Ok(quantity); 167 }; 168 let revision: i64 = row 169 .try_get(0) 170 .map_err(|_| OperationError::RecoveryRequired)?; 171 let operation: Vec<u8> = row 172 .try_get::<Option<Vec<u8>>, _>(1) 173 .map_err(|_| OperationError::RecoveryRequired)? 174 .ok_or(OperationError::RecoveryRequired)?; 175 if revision <= 0 { 176 return Err(OperationError::RecoveryRequired); 177 } 178 cursor = revision as u64; 179 let operation = OperationId::from_bytes( 180 operation 181 .try_into() 182 .map_err(|_| OperationError::RecoveryRequired)?, 183 ); 184 let frame = super::super::ledger::read(connection, input, crypto, operation) 185 .await? 186 .ok_or(OperationError::RecoveryRequired)?; 187 let (request, data) = super::codec::decode_operation(&frame.body, 19)?; 188 if frame.header.family != super::super::ledger::Family::Inventory 189 || frame.header.actor.participant() != input.participant() 190 || frame.header.revision.get() != cursor 191 || frame.header.operation != operation 192 || request.command().context().operation_id() != operation 193 || request.command().digest() != frame.header.digest 194 || data.revision != frame.header.revision 195 || data.head != frame.header.head 196 || data.pool.id() != pool 197 { 198 return Err(OperationError::RecoveryRequired); 199 } 200 let mut matching = data.losses.iter().filter(|loss| { 201 loss.acceptance == acceptance && loss.installation == installation && loss.line == line 202 }); 203 let loss = matching.next().ok_or(OperationError::RecoveryRequired)?; 204 if matching.next().is_some() { 205 return Err(OperationError::RecoveryRequired); 206 } 207 quantity = quantity 208 .checked_add(loss.quantity()?) 209 .map_err(|_| OperationError::RecoveryRequired)?; 210 } 211 } 212 213 fn projection_hash() -> Sha256 { 214 let mut hash = Sha256::new(); 215 hash.update(b"radroots.seller_stock.deficit_projection.v1\0"); 216 hash 217 } 218 pub(super) fn digest(pool: PoolId, losses: &[Loss]) -> Result<[u8; 32], OperationError> { 219 let mut ordered: Vec<_> = losses.iter().collect(); 220 ordered.sort_by_key(|loss| (loss.acceptance, loss.line)); 221 let mut hash = projection_hash(); 222 hash.update((ordered.len() as u64).to_be_bytes()); 223 for loss in ordered { 224 hash.update(loss.acceptance.as_bytes()); 225 hash.update(loss.installation.as_bytes()); 226 hash.update(loss.line.as_bytes()); 227 hash.update(pool.as_bytes()); 228 } 229 Ok(hash.finalize().into()) 230 } 231 pub(in crate::workspace::stock) async fn raw_projection( 232 connection: &mut SqliteConnection, 233 actor: &[u8; 32], 234 operation: &[u8; 32], 235 ) -> Result<[u8; 32], OperationError> { 236 let rows = sqlx::query("SELECT CASE WHEN length(acceptance_id)=32 THEN acceptance_id END,CASE WHEN length(installation_id)=32 THEN installation_id END,CASE WHEN length(line_id)=32 THEN line_id END,CASE WHEN length(pool_id)=32 THEN pool_id END FROM stock_deficits WHERE actor=? AND operation_id=? ORDER BY acceptance_id,line_id LIMIT 33") 237 .bind(actor.as_slice()).bind(operation.as_slice()).fetch_all(connection).await 238 .map_err(|_| OperationError::RecoveryRequired)?; 239 if rows.len() > MAX_LOSSES { 240 return Err(OperationError::RecoveryRequired); 241 } 242 let mut hash = projection_hash(); 243 hash.update((rows.len() as u64).to_be_bytes()); 244 for row in rows { 245 for column in 0..4 { 246 let value: Vec<u8> = row 247 .try_get::<Option<Vec<u8>>, _>(column) 248 .map_err(|_| OperationError::RecoveryRequired)? 249 .ok_or(OperationError::RecoveryRequired)?; 250 hash.update(value); 251 } 252 } 253 Ok(hash.finalize().into()) 254 } 255 pub(super) async fn insert( 256 connection: &mut SqliteConnection, 257 actor: PublicKey, 258 operation: OperationId, 259 pool: PoolId, 260 losses: &[Loss], 261 ) -> Result<(), OperationError> { 262 for loss in losses { 263 sqlx::query("INSERT INTO stock_deficits(actor,operation_id,acceptance_id,installation_id,line_id,pool_id) VALUES(?,?,?,?,?,?)") 264 .bind(actor.as_bytes().as_slice()).bind(operation.as_bytes().as_slice()) 265 .bind(loss.acceptance.as_bytes().as_slice()).bind(loss.installation.as_bytes().as_slice()) 266 .bind(loss.line.as_bytes().as_slice()).bind(pool.as_bytes().as_slice()) 267 .execute(&mut *connection).await.map_err(|_| OperationError::StorageFailure)?; 268 } 269 if raw_projection(connection, actor.as_bytes(), operation.as_bytes()).await? 270 != digest(pool, losses)? 271 { 272 return Err(OperationError::RecoveryRequired); 273 } 274 Ok(()) 275 }