transaction.rs (17654B)
1 use super::*; 2 use checkpoint::{Proof, Target}; 3 use radroots_domain::Sequence; 4 use radroots_storage::{ 5 command::{OperationError, protected::same_binding}, 6 workspace::seller_stock::StockListingCheckpointRef, 7 }; 8 use sha2::{Digest, Sha256}; 9 10 struct Access { 11 authority: Authority, 12 record: StockRecord, 13 root: Vec<u8>, 14 grant: Vec<u8>, 15 current: WorkspaceBinding, 16 minimum: Proof, 17 } 18 async fn access( 19 turn: &mut inventory::Turn<'_>, 20 binding: &WorkspaceBinding, 21 minimum: StockListingCheckpointRef, 22 proof: &AttachmentProof, 23 ) -> Result<Access, OperationError> { 24 if *turn.uncertain { 25 return Err(OperationError::RecoveryRequired); 26 } 27 turn.namespace.validate()?; 28 if !SellerAuthoritySelection::from_attachment(turn.selected).matches_attachment(binding.input()) 29 { 30 return Err(OperationError::Unauthorized); 31 } 32 let (authority, record, root, grant) = 33 super::super::read(turn.connection, binding.input(), turn.crypto).await?; 34 if !matches!(authority.catalog, 8..=20) || authority.public_sources.is_none() { 35 return Err(OperationError::UnsupportedOperation); 36 } 37 let current = record.authenticate(binding.input(), proof, turn.clock.now()?)?; 38 same_binding(binding, ¤t)?; 39 if current.scope() != WorkspaceScope::SellerStockOwner || !record.administrator() { 40 return Err(OperationError::Unauthorized); 41 } 42 if current.observed_at() < binding.observed_at() { 43 return Err(WorkspaceError::Unavailable.into()); 44 } 45 if minimum.authorization() != authority.authorization { 46 return Err(WorkspaceError::StaleCheckpoint.into()); 47 } 48 let minimum = checkpoint::authenticate( 49 turn.connection, 50 turn.selected, 51 turn.crypto, 52 &authority, 53 Target::Minimum(minimum), 54 ) 55 .await?; 56 Ok(Access { 57 authority, 58 record, 59 root, 60 grant, 61 current, 62 minimum, 63 }) 64 } 65 impl Access { 66 async fn confirm( 67 &self, 68 connection: &mut SqliteConnection, 69 namespace: &Namespace, 70 clock: &dyn WorkspaceClock, 71 proof: &AttachmentProof, 72 ) -> Result<WorkspaceBinding, OperationError> { 73 namespace.validate()?; 74 super::super::unchanged( 75 connection, 76 self.current.input(), 77 self.authority.catalog, 78 &self.root, 79 &self.grant, 80 ) 81 .await?; 82 grants::check_state( 83 connection, 84 self.authority 85 .authorization 86 .ok_or(OperationError::RecoveryRequired)?, 87 ) 88 .await?; 89 counts( 90 connection, 91 self.authority 92 .public_sources 93 .ok_or(OperationError::RecoveryRequired)?, 94 ) 95 .await?; 96 self.minimum.confirm(connection).await?; 97 let current = self 98 .record 99 .authenticate(self.current.input(), proof, clock.now()?)?; 100 same_binding(&self.current, ¤t)?; 101 if !self.record.administrator() { 102 return Err(OperationError::Unauthorized); 103 } 104 if current.observed_at() < self.current.observed_at() { 105 return Err(WorkspaceError::Unavailable.into()); 106 } 107 namespace.validate()?; 108 Ok(current) 109 } 110 } 111 fn add(value: Sequence, delta: u64) -> Result<Sequence, OperationError> { 112 Sequence::new( 113 value 114 .get() 115 .checked_add(delta) 116 .ok_or(WorkspaceError::Capacity)?, 117 ) 118 .map_err(|_| WorkspaceError::Capacity.into()) 119 } 120 121 pub(in crate::workspace) async fn retain( 122 turn: &mut inventory::Turn<'_>, 123 binding: WorkspaceBinding, 124 minimum: StockListingCheckpointRef, 125 capture: StockListingCapture, 126 proof: AttachmentProof, 127 ) -> Result<StockListingOutcome, OperationError> { 128 let access = access(turn, &binding, minimum, &proof).await?; 129 if capture.namespace != SellerAuthoritySelection::from_attachment(turn.selected) { 130 return Err(OperationError::Unauthorized); 131 } 132 let event = capture.listing.event_id(); 133 let coordinate = capture.listing.coordinate(); 134 let original = record::read( 135 turn.connection, 136 turn.selected, 137 turn.crypto, 138 access.authority.input.grant_id(), 139 event, 140 ) 141 .await?; 142 if let Some(original) = original { 143 if original.header.manifest.listing != capture.listing 144 || record::time(&original.header.manifest.created_at)? != capture.created_at 145 { 146 return Err(OperationError::RecoveryRequired); 147 } 148 // Both captures independently verified the same NIP01 identity. A 149 // transport re-encoding may deduplicate, never replace original bytes. 150 let parts = record::read_parts( 151 turn.connection, 152 turn.selected, 153 turn.crypto, 154 &original.header, 155 ) 156 .await?; 157 let identity = checkpoint::authenticate( 158 turn.connection, 159 turn.selected, 160 turn.crypto, 161 &access.authority, 162 Target::Event(event, Some(original.identity()?)), 163 ) 164 .await?; 165 let receipt = original.header.receipt()?; 166 let mut tx = turn 167 .connection 168 .begin_with("BEGIN IMMEDIATE") 169 .await 170 .map_err(|_| OperationError::StorageFailure)?; 171 let checked: Result<(), OperationError> = async { 172 access 173 .confirm(&mut tx, turn.namespace, turn.clock, &proof) 174 .await?; 175 identity.confirm(&mut tx).await?; 176 if record::parts_witness(&mut tx, event).await? 177 != (original.header.manifest.parts, parts.witness) 178 { 179 return Err(OperationError::RecoveryRequired); 180 } 181 Ok(()) 182 } 183 .await; 184 if tx.rollback().await.is_err() { 185 *turn.uncertain = true; 186 return Err(OperationError::RecoveryRequired); 187 } 188 checked?; 189 return Ok(StockListingOutcome::Committed(Box::new(receipt))); 190 } 191 let absence = checkpoint::authenticate( 192 turn.connection, 193 turn.selected, 194 turn.crypto, 195 &access.authority, 196 Target::Event(event, None), 197 ) 198 .await?; 199 let before = record::read_head(turn.connection, turn.selected, turn.crypto, coordinate).await?; 200 let projection = checkpoint::authenticate( 201 turn.connection, 202 turn.selected, 203 turn.crypto, 204 &access.authority, 205 Target::Coordinate(coordinate, before.as_ref().map(|value| value.head.clone())), 206 ) 207 .await?; 208 let progress = access 209 .authority 210 .public_sources 211 .ok_or(OperationError::RecoveryRequired)?; 212 let revision = add(progress.revision, 1)?; 213 let candidate = record::Head { 214 version: 1, 215 listing: capture.listing, 216 created_at: capture.created_at.to_string(), 217 revision, 218 }; 219 let after = record::select(before.as_ref().map(|value| &value.head), candidate)?; 220 let selected = after.listing.event_id() == event; 221 let authorization = access 222 .authority 223 .authorization 224 .ok_or(OperationError::RecoveryRequired)?; 225 let mut header = record::Header { 226 version: 1, 227 namespace: capture.namespace.clone(), 228 transaction: capture.transaction, 229 revision, 230 previous: progress.head, 231 head: None, 232 grant: access.current.input().grant_id(), 233 principal: access.current.principal_id().into(), 234 authorization, 235 observed_at: access.current.observed_at(), 236 minimum_revision: minimum.revision(), 237 minimum_head: minimum.head(), 238 manifest: record::Manifest { 239 listing: capture.listing, 240 created_at: capture.created_at.to_string(), 241 bytes: capture.raw.len() as u32, 242 digest: Sha256::digest(capture.raw.as_slice()).into(), 243 parts: capture.raw.len().div_ceil(record::PART_BYTES) as u8, 244 }, 245 before: before.as_ref().map(|value| value.head.clone()), 246 after, 247 }; 248 header.head = Some(header.calculate_head()?); 249 header.validate(turn.selected, access.authority.input.grant_id())?; 250 let receipt = header.receipt()?; 251 let parts = record::PreparedParts::prepare(turn.crypto, turn.selected, &capture).await?; 252 let protected = turn 253 .crypto 254 .seal_stock_record( 255 turn.selected, 256 "public_event", 257 event.as_bytes(), 258 &record::encode(&header)?, 259 ) 260 .await?; 261 let protected_head = if selected { 262 Some( 263 turn.crypto 264 .seal_stock_record( 265 turn.selected, 266 "public_head", 267 &record::coordinate_id(coordinate), 268 &record::encode(&header.after)?, 269 ) 270 .await?, 271 ) 272 } else { 273 None 274 }; 275 let mut next = access.authority.clone(); 276 next.public_sources = Some(PublicSourceCheckpoint { 277 revision, 278 events: add(progress.events, 1)?, 279 heads: add(progress.heads, u64::from(before.is_none()))?, 280 parts: add(progress.parts, u64::from(header.manifest.parts))?, 281 head: header.head, 282 }); 283 let root = turn 284 .crypto 285 .seal_stock_root(turn.selected, next.catalog, &next.encode()?) 286 .await?; 287 turn.namespace.validate()?; 288 let mut tx = turn 289 .connection 290 .begin_with("BEGIN IMMEDIATE") 291 .await 292 .map_err(|_| OperationError::StorageFailure)?; 293 let changed:Result<(),OperationError>=async { 294 access.confirm(&mut tx,turn.namespace,turn.clock,&proof).await?; 295 absence.confirm(&mut tx).await?;projection.confirm(&mut tx).await?; 296 record::confirm_head(&mut tx,coordinate,before.as_ref()).await?; 297 let present:i64=sqlx::query_scalar("SELECT count(*) FROM stock_public_events WHERE event_id=?").bind(event.as_bytes().as_slice()).fetch_one(&mut *tx).await.map_err(|_|OperationError::RecoveryRequired)?; 298 if present!=0 {return Err(OperationError::StaleState);} 299 sqlx::query("INSERT INTO stock_public_events(event_id,listing_author,listing_d,created_at,transaction_id,revision,chain_head,protected) VALUES(?,?,?,?,?,?,?,?)") 300 .bind(event.as_bytes().as_slice()).bind(coordinate.author().as_bytes().as_slice()).bind(coordinate.d().as_bytes().as_slice()) 301 .bind(capture.created_at.to_be_bytes().as_slice()).bind(capture.transaction.as_bytes().as_slice()).bind(revision.get() as i64) 302 .bind(header.head.ok_or(OperationError::RecoveryRequired)?.as_bytes().as_slice()).bind(&protected).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; 303 parts.insert(&mut tx,event).await?; 304 if let Some(protected)=&protected_head { 305 if let Some(before)=&before { 306 let changed=sqlx::query("UPDATE stock_public_heads SET event_id=?,revision=?,protected=? WHERE listing_author=? AND listing_d=? AND protected=?") 307 .bind(event.as_bytes().as_slice()).bind(revision.get() as i64).bind(protected) 308 .bind(coordinate.author().as_bytes().as_slice()).bind(coordinate.d().as_bytes().as_slice()).bind(&before.protected) 309 .execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; 310 if changed.rows_affected()!=1 {return Err(OperationError::RecoveryRequired);} 311 } else { 312 sqlx::query("INSERT INTO stock_public_heads(listing_author,listing_d,event_id,revision,protected) VALUES(?,?,?,?,?)") 313 .bind(coordinate.author().as_bytes().as_slice()).bind(coordinate.d().as_bytes().as_slice()) 314 .bind(event.as_bytes().as_slice()).bind(revision.get() as i64).bind(protected) 315 .execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; 316 } 317 } 318 let changed=sqlx::query("UPDATE stock_authority SET protected=? WHERE singleton=1 AND protected=?").bind(root).bind(&access.root) 319 .execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; 320 if changed.rows_affected()!=1 {return Err(OperationError::RecoveryRequired);} 321 turn.namespace.validate()?;Ok(()) 322 }.await; 323 let unknown = || StockListingOutcome::Unknown { 324 transaction: capture.transaction, 325 listing: capture.listing, 326 }; 327 if let Err(error) = changed { 328 if tx.rollback().await.is_err() { 329 *turn.uncertain = true; 330 return Ok(unknown()); 331 } 332 return Err(error); 333 } 334 if tx.commit().await.is_err() { 335 *turn.uncertain = true; 336 return Ok(unknown()); 337 } 338 Ok(StockListingOutcome::Committed(Box::new(receipt))) 339 } 340 341 pub(in crate::workspace) enum Lookup { 342 Revision(ListingRevision), 343 Coordinate(ListingCoordinate), 344 } 345 pub(in crate::workspace) async fn query( 346 turn: &mut inventory::Turn<'_>, 347 binding: WorkspaceBinding, 348 minimum: StockListingCheckpointRef, 349 lookup: Lookup, 350 proof: AttachmentProof, 351 ) -> Result<Option<StockListingSnapshot>, OperationError> { 352 let access = access(turn, &binding, minimum, &proof).await?; 353 let coordinate = match &lookup { 354 Lookup::Revision(value) => value.coordinate(), 355 Lookup::Coordinate(value) => *value, 356 }; 357 if coordinate.author() != turn.selected.participant() { 358 return Err(OperationError::Unauthorized); 359 } 360 let head = record::read_head(turn.connection, turn.selected, turn.crypto, coordinate).await?; 361 let projection = checkpoint::authenticate( 362 turn.connection, 363 turn.selected, 364 turn.crypto, 365 &access.authority, 366 Target::Coordinate(coordinate, head.as_ref().map(|value| value.head.clone())), 367 ) 368 .await?; 369 let wanted = match lookup { 370 Lookup::Revision(value) => Some(value), 371 Lookup::Coordinate(_) => head.as_ref().map(|value| value.head.listing), 372 }; 373 let original = if let Some(wanted) = wanted { 374 let original = record::read( 375 turn.connection, 376 turn.selected, 377 turn.crypto, 378 access.authority.input.grant_id(), 379 wanted.event_id(), 380 ) 381 .await?; 382 if original 383 .as_ref() 384 .is_some_and(|original| original.header.manifest.listing != wanted) 385 { 386 return Err(OperationError::InvalidCommand); 387 } 388 original 389 } else { 390 None 391 }; 392 let parts = if let Some(original) = &original { 393 Some( 394 record::read_parts( 395 turn.connection, 396 turn.selected, 397 turn.crypto, 398 &original.header, 399 ) 400 .await?, 401 ) 402 } else { 403 None 404 }; 405 let identity = if let Some(wanted) = wanted { 406 Some( 407 checkpoint::authenticate( 408 turn.connection, 409 turn.selected, 410 turn.crypto, 411 &access.authority, 412 Target::Event( 413 wanted.event_id(), 414 original 415 .as_ref() 416 .map(|original| original.identity()) 417 .transpose()?, 418 ), 419 ) 420 .await?, 421 ) 422 } else { 423 None 424 }; 425 let selected = original.as_ref().is_some_and(|original| { 426 head.as_ref() 427 .is_some_and(|head| head.head.listing == original.header.manifest.listing) 428 }); 429 let progress = access 430 .authority 431 .public_sources 432 .ok_or(OperationError::RecoveryRequired)?; 433 let selected_at = StockListingCheckpointRef::from_host_metadata( 434 turn.selected.authority(), 435 progress.revision, 436 progress.head, 437 )? 438 .with_optional_authorization(access.authority.authorization); 439 let mut tx = turn 440 .connection 441 .begin_with("BEGIN IMMEDIATE") 442 .await 443 .map_err(|_| OperationError::StorageFailure)?; 444 let checked: Result<WorkspaceBinding, OperationError> = async { 445 let current = access 446 .confirm(&mut tx, turn.namespace, turn.clock, &proof) 447 .await?; 448 projection.confirm(&mut tx).await?; 449 if let Some(identity) = &identity { 450 identity.confirm(&mut tx).await?; 451 } 452 record::confirm_head(&mut tx, coordinate, head.as_ref()).await?; 453 if let (Some(original), Some(parts)) = (&original, &parts) 454 && record::parts_witness(&mut tx, original.header.manifest.listing.event_id()).await? 455 != (original.header.manifest.parts, parts.witness) 456 { 457 return Err(OperationError::RecoveryRequired); 458 } 459 turn.namespace.validate()?; 460 Ok(current) 461 } 462 .await; 463 if tx.rollback().await.is_err() { 464 *turn.uncertain = true; 465 return Err(OperationError::RecoveryRequired); 466 } 467 let current = checked?; 468 match (original, parts) { 469 (Some(original), Some(parts)) => Ok(Some(StockListingSnapshot { 470 receipt: original.header.receipt()?, 471 selection_checkpoint: selected_at, 472 observed_at: current.observed_at(), 473 current: selected, 474 raw: Zeroizing::new( 475 String::from_utf8(parts.raw.to_vec()) 476 .map_err(|_| OperationError::RecoveryRequired)?, 477 ), 478 })), 479 (None, None) => Ok(None), 480 _ => Err(OperationError::RecoveryRequired), 481 } 482 }