mapping.rs (10338B)
1 //! Owner-private configuration on the existing stock transaction owner. 2 use super::*; 3 use radroots_domain::stock::{OptionMappingKey, OptionPoolMapping}; 4 5 #[derive(Clone, Copy, Eq, PartialEq, Serialize)] 6 #[serde(deny_unknown_fields)] 7 pub(super) struct MappingEffect { 8 pub before: Option<OptionPoolMapping>, 9 pub after: OptionPoolMapping, 10 } 11 impl<'de> Deserialize<'de> for MappingEffect { 12 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { 13 #[derive(Deserialize)] 14 #[serde(deny_unknown_fields)] 15 struct Wire { 16 #[serde(deserialize_with = "super::super::required_nullable")] 17 before: Option<OptionPoolMapping>, 18 after: OptionPoolMapping, 19 } 20 let value: Wire = super::super::object(deserializer)?; 21 Ok(Self { 22 before: value.before, 23 after: value.after, 24 }) 25 } 26 } 27 pub(super) struct RetainedMapping { 28 pub value: OptionPoolMapping, 29 pub protected: Vec<u8>, 30 } 31 pub(super) struct MappingRead { 32 pub key: OptionMappingKey, 33 pub retained: Option<RetainedMapping>, 34 pub proof: MinimumProof, 35 } 36 impl MappingRead { 37 pub async fn confirm(&self, connection: &mut SqliteConnection) -> Result<(), OperationError> { 38 self.proof.confirm(connection).await?; 39 let key = self.key; 40 let protected:Option<Vec<u8>>=sqlx::query_scalar("SELECT CASE WHEN length(protected) BETWEEN 1 AND 262144 THEN protected END FROM stock_mappings WHERE listing_author=? AND listing_d=? AND option_id=?") 41 .bind(key.listing().author().as_bytes().as_slice()).bind(key.listing().d().as_bytes().as_slice()).bind(key.option_id().as_bytes().as_slice()).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?.flatten(); 42 if protected.as_ref() != self.retained.as_ref().map(|value| &value.protected) { 43 return Err(OperationError::RecoveryRequired); 44 } 45 if let Some(retained) = &self.retained { 46 let count:i64=sqlx::query_scalar("SELECT count(*) FROM stock_mappings WHERE listing_author=? AND listing_d=? AND option_id=? AND pool_id=? AND revision=?") 47 .bind(key.listing().author().as_bytes().as_slice()).bind(key.listing().d().as_bytes().as_slice()).bind(key.option_id().as_bytes().as_slice()).bind(retained.value.pool_id().as_bytes().as_slice()).bind(retained.value.version().get() as i64).fetch_one(connection).await.map_err(|_|OperationError::RecoveryRequired)?; 48 if count != 1 { 49 return Err(OperationError::RecoveryRequired); 50 } 51 } else { 52 let count:i64=sqlx::query_scalar("SELECT count(*) FROM stock_mappings WHERE listing_author=? AND listing_d=? AND option_id=?").bind(key.listing().author().as_bytes().as_slice()).bind(key.listing().d().as_bytes().as_slice()).bind(key.option_id().as_bytes().as_slice()).fetch_one(connection).await.map_err(|_|OperationError::RecoveryRequired)?; 53 if count != 0 { 54 return Err(OperationError::RecoveryRequired); 55 } 56 } 57 Ok(()) 58 } 59 } 60 pub(super) fn require(access: &Access, key: OptionMappingKey) -> Result<(), OperationError> { 61 if !(5..=20).contains(&access.authority.catalog) { 62 return Err(OperationError::UnsupportedOperation); 63 } 64 if !access.record.administrator() 65 || key.listing().author() != access.current.actor().participant() 66 { 67 return Err(OperationError::Unauthorized); 68 } 69 Ok(()) 70 } 71 pub(super) struct MappingPlan { 72 pub effect: MappingEffect, 73 pub protected: Vec<u8>, 74 pub original: Option<Vec<u8>>, 75 pub proof: MinimumProof, 76 } 77 #[derive(Serialize, Deserialize)] 78 #[serde(deny_unknown_fields)] 79 struct MappingWire { 80 version: u8, 81 mapping: OptionPoolMapping, 82 } 83 pub(super) fn key_id(key: OptionMappingKey) -> [u8; 32] { 84 let mut hash = Sha256::new(); 85 hash.update(b"radroots.seller_stock.mapping_key.v1\0"); 86 hash.update(key.listing().author().as_bytes()); 87 hash.update(key.listing().d().as_bytes()); 88 hash.update(key.option_id().as_bytes()); 89 hash.finalize().into() 90 } 91 pub(super) async fn read( 92 connection: &mut SqliteConnection, 93 input: &AttachmentInput, 94 crypto: &WorkspaceCrypto, 95 key: OptionMappingKey, 96 ) -> Result<Option<RetainedMapping>, OperationError> { 97 let row=sqlx::query("SELECT pool_id,revision,CASE WHEN length(protected) BETWEEN 1 AND 262144 THEN protected END FROM stock_mappings WHERE listing_author=? AND listing_d=? AND option_id=?") 98 .bind(key.listing().author().as_bytes().as_slice()).bind(key.listing().d().as_bytes().as_slice()).bind(key.option_id().as_bytes().as_slice()).fetch_optional(connection).await.map_err(|_|OperationError::RecoveryRequired)?; 99 let Some(row) = row else { return Ok(None) }; 100 let protected: Vec<u8> = row 101 .try_get::<Option<Vec<u8>>, _>(2) 102 .map_err(|_| OperationError::RecoveryRequired)? 103 .ok_or(OperationError::RecoveryRequired)?; 104 let clear = crypto 105 .open_stock_record(input, "mapping", &key_id(key), &protected) 106 .await?; 107 let wire: MappingWire = clear 108 .expose_secret(|bytes| super::super::closed_record(bytes)) 109 .map_err(|_| OperationError::RecoveryRequired)?; 110 let pool: Vec<u8> = row 111 .try_get(0) 112 .map_err(|_| OperationError::RecoveryRequired)?; 113 let revision: i64 = row 114 .try_get(1) 115 .map_err(|_| OperationError::RecoveryRequired)?; 116 if wire.version != 1 117 || wire.mapping.key() != key 118 || pool != wire.mapping.pool_id().as_bytes() 119 || revision <= 0 120 || revision as u64 != wire.mapping.version().get() 121 { 122 return Err(OperationError::RecoveryRequired); 123 } 124 Ok(Some(RetainedMapping { 125 value: wire.mapping, 126 protected, 127 })) 128 } 129 pub(super) fn effect( 130 command: &radroots_storage::inventory::CapturedInventoryCommand, 131 pool: PoolSnapshot, 132 before: Option<OptionPoolMapping>, 133 ) -> Result<Option<MappingEffect>, OperationError> { 134 let Some(input) = command.mapping_input() else { 135 return Ok(None); 136 }; 137 if pool.id() != input.pool_id() { 138 return Err(OperationError::RecoveryRequired); 139 } 140 if before.is_some_and(|value| value.key() != input.key()) { 141 return Err(OperationError::RecoveryRequired); 142 } 143 if input.expected_mapping_version().get() 144 != before.map(|value| value.version().get()).unwrap_or(0) 145 { 146 return Err(OperationError::StaleState); 147 } 148 let version = Sequence::new( 149 input 150 .expected_mapping_version() 151 .get() 152 .checked_add(1) 153 .ok_or(WorkspaceError::Capacity)?, 154 ) 155 .map_err(|_| WorkspaceError::Capacity)?; 156 let after = OptionPoolMapping::new( 157 input.key(), 158 input.pool_id(), 159 pool.unit(), 160 input.per_sale_unit(), 161 version, 162 ) 163 .map_err(|_| OperationError::InvalidCommand)?; 164 Ok(Some(MappingEffect { before, after })) 165 } 166 pub(super) async fn prepare( 167 turn: &mut Turn<'_>, 168 access: &Access, 169 request: &InventoryRequest, 170 pool: PoolSnapshot, 171 ) -> Result<Option<MappingPlan>, OperationError> { 172 let Some(input) = request.command().mapping_input() else { 173 return Ok(None); 174 }; 175 require(access, input.key())?; 176 let original = read(turn.connection, turn.selected, turn.crypto, input.key()).await?; 177 let before = original.as_ref().map(|value| value.value); 178 let proof = checkpoint::authenticate_mapping_projection( 179 turn.connection, 180 turn.selected, 181 turn.crypto, 182 &access.current, 183 &access.authority, 184 input.key(), 185 before, 186 ) 187 .await?; 188 let effect = 189 effect(request.command(), pool, before)?.ok_or(OperationError::RecoveryRequired)?; 190 let protected = turn 191 .crypto 192 .seal_stock_record( 193 turn.selected, 194 "mapping", 195 &key_id(input.key()), 196 &encode(&MappingWire { 197 version: 1, 198 mapping: effect.after, 199 })?, 200 ) 201 .await?; 202 Ok(Some(MappingPlan { 203 effect, 204 protected, 205 original: original.map(|value| value.protected), 206 proof, 207 })) 208 } 209 impl MappingPlan { 210 pub async fn apply(&self, connection: &mut SqliteConnection) -> Result<(), OperationError> { 211 self.proof.confirm(connection).await?; 212 let key = self.effect.after.key(); 213 if let (Some(before), Some(protected)) = (self.effect.before, self.original.as_ref()) { 214 let updated=sqlx::query("UPDATE stock_mappings SET pool_id=?,revision=?,protected=? WHERE listing_author=? AND listing_d=? AND option_id=? AND revision=? AND protected=? AND pool_id=?") 215 .bind(self.effect.after.pool_id().as_bytes().as_slice()).bind(self.effect.after.version().get() as i64).bind(&self.protected).bind(key.listing().author().as_bytes().as_slice()).bind(key.listing().d().as_bytes().as_slice()).bind(key.option_id().as_bytes().as_slice()).bind(before.version().get() as i64).bind(protected).bind(before.pool_id().as_bytes().as_slice()).execute(connection).await.map_err(|_|OperationError::StorageFailure)?; 216 if updated.rows_affected() != 1 { 217 return Err(OperationError::RecoveryRequired); 218 } 219 } else { 220 let count:i64=sqlx::query_scalar("SELECT count(*) FROM stock_mappings WHERE listing_author=? AND listing_d=? AND option_id=?").bind(key.listing().author().as_bytes().as_slice()).bind(key.listing().d().as_bytes().as_slice()).bind(key.option_id().as_bytes().as_slice()).fetch_one(&mut *connection).await.map_err(|_|OperationError::StorageFailure)?; 221 if count != 0 { 222 return Err(OperationError::RecoveryRequired); 223 } 224 sqlx::query("INSERT INTO stock_mappings(listing_author,listing_d,option_id,pool_id,revision,protected) VALUES(?,?,?,?,?,?)") 225 .bind(key.listing().author().as_bytes().as_slice()).bind(key.listing().d().as_bytes().as_slice()).bind(key.option_id().as_bytes().as_slice()).bind(self.effect.after.pool_id().as_bytes().as_slice()).bind(self.effect.after.version().get() as i64).bind(&self.protected).execute(connection).await.map_err(|_|OperationError::StorageFailure)?; 226 } 227 Ok(()) 228 } 229 }