contract.rs (12785B)
1 #![forbid(unsafe_code)] 2 3 #[cfg(all(not(feature = "std"), not(test)))] 4 use alloc::{string::String, vec::Vec}; 5 #[cfg(any(feature = "std", test))] 6 use std::{string::String, vec::Vec}; 7 8 use core::fmt; 9 10 /// Exact package version implementing this event contract surface. 11 pub const VERSION: &str = env!("CARGO_PKG_VERSION"); 12 13 #[doc(hidden)] 14 pub mod registry_v7; 15 16 /// Explicit profile-edit registry; the default registry remains frozen v7. 17 pub mod registry_v8; 18 19 pub use registry_v7::*; 20 21 /// Maximum UTF-8 byte length of a versioned Radroots event-contract ID. 22 pub const CONTRACT_ID_MAX_BYTES: usize = 255; 23 24 /// A syntactically valid, bounded Radroots event-contract identifier. 25 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] 26 pub struct ContractId(String); 27 28 impl ContractId { 29 pub fn parse(value: impl Into<String>) -> Result<Self, ContractIdentityError> { 30 let value = value.into(); 31 if value.is_empty() { 32 return Err(ContractIdentityError::ContractIdMissing); 33 } 34 if value.len() > CONTRACT_ID_MAX_BYTES { 35 return Err(ContractIdentityError::ContractIdTooLong { 36 max: CONTRACT_ID_MAX_BYTES, 37 actual: value.len(), 38 }); 39 } 40 if !value.starts_with("radroots.") { 41 return Err(ContractIdentityError::ContractIdNamespace); 42 } 43 let mut segments = value.split('.'); 44 let namespace = segments.next(); 45 let remaining = segments.collect::<Vec<_>>(); 46 let Some(version) = remaining.last() else { 47 return Err(ContractIdentityError::ContractIdSyntax); 48 }; 49 if namespace != Some("radroots") 50 || remaining.len() < 3 51 || remaining[..remaining.len() - 1].iter().any(|segment| { 52 segment.is_empty() 53 || !segment.bytes().all(|byte| { 54 byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_' 55 }) 56 }) 57 || !version.strip_prefix('v').is_some_and(|number| { 58 !number.is_empty() 59 && !number.starts_with('0') 60 && number.bytes().all(|byte| byte.is_ascii_digit()) 61 }) 62 { 63 return Err(ContractIdentityError::ContractIdSyntax); 64 } 65 Ok(Self(value)) 66 } 67 68 #[must_use] 69 pub fn as_str(&self) -> &str { 70 self.0.as_str() 71 } 72 73 #[must_use] 74 pub fn into_string(self) -> String { 75 self.0 76 } 77 } 78 79 impl fmt::Display for ContractId { 80 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 81 formatter.write_str(self.as_str()) 82 } 83 } 84 85 /// A nonzero immutable event-contract registry version. 86 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] 87 pub struct RegistryVersion(u32); 88 89 impl RegistryVersion { 90 /// Frozen registry profile used by the initial authored-plan storage wire. 91 pub const V7: Self = Self(7); 92 pub const V8: Self = Self(8); 93 pub const CURRENT: Self = Self(RADROOTS_EVENT_CONTRACT_REGISTRY_VERSION); 94 95 pub const fn new(value: u32) -> Result<Self, ContractIdentityError> { 96 if value == 0 { 97 return Err(ContractIdentityError::RegistryVersionZero); 98 } 99 Ok(Self(value)) 100 } 101 102 #[must_use] 103 pub const fn get(self) -> u32 { 104 self.0 105 } 106 } 107 108 impl fmt::Display for RegistryVersion { 109 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 110 write!(formatter, "{}", self.get()) 111 } 112 } 113 114 /// One event contract resolved against an immutable historical registry. 115 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] 116 pub struct ContractKey { 117 registry_version: RegistryVersion, 118 contract_id: ContractId, 119 } 120 121 impl ContractKey { 122 pub fn current(contract_id: impl Into<String>) -> Result<Self, ContractIdentityError> { 123 Self::new(RegistryVersion::CURRENT, ContractId::parse(contract_id)?) 124 } 125 126 pub fn new( 127 registry_version: RegistryVersion, 128 contract_id: ContractId, 129 ) -> Result<Self, ContractIdentityError> { 130 let contract = match registry_version { 131 RegistryVersion::V7 => event_contract_registry_v7(contract_id.as_str()), 132 RegistryVersion::V8 => registry_v8::event_contract_registry_v8(contract_id.as_str()), 133 _ => { 134 return Err(ContractIdentityError::UnsupportedRegistryVersion { 135 actual: registry_version.get(), 136 }); 137 } 138 }; 139 if contract.is_none() { 140 return Err(ContractIdentityError::UnknownContract { 141 contract_id: contract_id.into_string(), 142 }); 143 } 144 Ok(Self { 145 registry_version, 146 contract_id, 147 }) 148 } 149 150 #[must_use] 151 pub const fn registry_version(&self) -> RegistryVersion { 152 self.registry_version 153 } 154 155 #[must_use] 156 pub const fn contract_id(&self) -> &ContractId { 157 &self.contract_id 158 } 159 160 #[must_use] 161 pub fn contract(&self) -> &'static EventContract { 162 match self.registry_version { 163 RegistryVersion::V7 => event_contract_registry_v7(self.contract_id.as_str()) 164 .expect("validated registry-v7 contract key must remain resolvable"), 165 RegistryVersion::V8 => { 166 registry_v8::event_contract_registry_v8(self.contract_id.as_str()) 167 .expect("validated registry-v8 contract key must remain resolvable") 168 } 169 _ => unreachable!("validated contract key must have a supported registry profile"), 170 } 171 } 172 } 173 174 #[derive(Clone, Debug, PartialEq, Eq)] 175 pub enum ContractIdentityError { 176 ContractIdMissing, 177 ContractIdTooLong { max: usize, actual: usize }, 178 ContractIdNamespace, 179 ContractIdSyntax, 180 RegistryVersionZero, 181 UnsupportedRegistryVersion { actual: u32 }, 182 UnknownContract { contract_id: String }, 183 } 184 185 impl ContractIdentityError { 186 #[must_use] 187 pub const fn code(&self) -> &'static str { 188 match self { 189 Self::ContractIdMissing => "contract_id_missing", 190 Self::ContractIdTooLong { .. } => "contract_id_too_long", 191 Self::ContractIdNamespace => "contract_id_namespace", 192 Self::ContractIdSyntax => "contract_id_syntax", 193 Self::RegistryVersionZero => "registry_version_zero", 194 Self::UnsupportedRegistryVersion { .. } => "unsupported_registry_version", 195 Self::UnknownContract { .. } => "unknown_contract", 196 } 197 } 198 } 199 200 impl fmt::Display for ContractIdentityError { 201 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 202 match self { 203 Self::ContractIdMissing => formatter.write_str("event contract ID must not be empty"), 204 Self::ContractIdTooLong { max, actual } => { 205 write!( 206 formatter, 207 "event contract ID is {actual} bytes; max is {max}" 208 ) 209 } 210 Self::ContractIdNamespace => { 211 formatter.write_str("event contract ID must use the `radroots.` namespace") 212 } 213 Self::ContractIdSyntax => { 214 formatter.write_str("event contract ID must be a canonical versioned identifier") 215 } 216 Self::RegistryVersionZero => { 217 formatter.write_str("event contract registry version must be nonzero") 218 } 219 Self::UnsupportedRegistryVersion { actual } => { 220 write!( 221 formatter, 222 "unsupported event contract registry version {actual}" 223 ) 224 } 225 Self::UnknownContract { contract_id } => { 226 write!(formatter, "unknown event contract `{contract_id}`") 227 } 228 } 229 } 230 } 231 232 #[cfg(feature = "std")] 233 impl std::error::Error for ContractIdentityError {} 234 235 #[cfg(any(feature = "serde", test))] 236 impl serde::Serialize for ContractId { 237 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> 238 where 239 S: serde::Serializer, 240 { 241 serializer.serialize_str(self.as_str()) 242 } 243 } 244 245 #[cfg(any(feature = "serde", test))] 246 impl<'de> serde::Deserialize<'de> for ContractId { 247 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> 248 where 249 D: serde::Deserializer<'de>, 250 { 251 let value = String::deserialize(deserializer)?; 252 Self::parse(value).map_err(serde::de::Error::custom) 253 } 254 } 255 256 #[cfg(any(feature = "serde", test))] 257 impl serde::Serialize for RegistryVersion { 258 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> 259 where 260 S: serde::Serializer, 261 { 262 serializer.serialize_u32(self.get()) 263 } 264 } 265 266 #[cfg(any(feature = "serde", test))] 267 impl<'de> serde::Deserialize<'de> for RegistryVersion { 268 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> 269 where 270 D: serde::Deserializer<'de>, 271 { 272 Self::new(u32::deserialize(deserializer)?).map_err(serde::de::Error::custom) 273 } 274 } 275 276 #[cfg(any(feature = "serde", test))] 277 impl serde::Serialize for ContractKey { 278 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> 279 where 280 S: serde::Serializer, 281 { 282 use serde::ser::SerializeStruct; 283 284 let mut state = serializer.serialize_struct("ContractKey", 2)?; 285 state.serialize_field("registry_version", &self.registry_version)?; 286 state.serialize_field("contract_id", &self.contract_id)?; 287 state.end() 288 } 289 } 290 291 #[cfg(any(feature = "serde", test))] 292 impl<'de> serde::Deserialize<'de> for ContractKey { 293 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> 294 where 295 D: serde::Deserializer<'de>, 296 { 297 #[derive(serde::Deserialize)] 298 #[serde(deny_unknown_fields)] 299 struct ContractKeySerde { 300 registry_version: RegistryVersion, 301 contract_id: ContractId, 302 } 303 304 let value = ContractKeySerde::deserialize(deserializer)?; 305 Self::new(value.registry_version, value.contract_id).map_err(serde::de::Error::custom) 306 } 307 } 308 309 #[cfg(test)] 310 mod identity_tests { 311 use super::*; 312 313 #[test] 314 fn contract_identity_values_are_bounded_canonical_and_resolved() { 315 let id = ContractId::parse("radroots.social.geochat.v1").expect("contract ID"); 316 assert_eq!(id.as_str(), "radroots.social.geochat.v1"); 317 assert_eq!(RegistryVersion::CURRENT.get(), 7); 318 assert_eq!(RegistryVersion::V7.get(), 7); 319 let key = ContractKey::new(RegistryVersion::CURRENT, id).expect("contract key"); 320 assert_eq!(key.contract().id, "radroots.social.geochat.v1"); 321 322 for invalid in [ 323 "", 324 "social.geochat.v1", 325 "radroots.social.Geochat.v1", 326 "radroots.social.geochat", 327 "radroots.social.geochat.v01", 328 "radroots..geochat.v1", 329 ] { 330 assert!(ContractId::parse(invalid).is_err(), "{invalid}"); 331 } 332 assert!(ContractId::parse(format!("radroots.{}.event.v1", "x".repeat(256))).is_err()); 333 assert_eq!( 334 RegistryVersion::new(0), 335 Err(ContractIdentityError::RegistryVersionZero) 336 ); 337 assert!(matches!( 338 ContractKey::new( 339 RegistryVersion::new(9).expect("nonzero version"), 340 ContractId::parse("radroots.social.geochat.v1").expect("contract ID") 341 ), 342 Err(ContractIdentityError::UnsupportedRegistryVersion { actual: 9 }) 343 )); 344 assert!(matches!( 345 ContractKey::current("radroots.social.unknown.v1"), 346 Err(ContractIdentityError::UnknownContract { .. }) 347 )); 348 } 349 350 #[test] 351 fn serde_reconstruction_revalidates_identity_and_registry_membership() { 352 let key = ContractKey::current("radroots.social.geochat.v1").expect("contract key"); 353 let value = serde_json::to_value(&key).expect("key JSON"); 354 assert_eq!( 355 serde_json::from_value::<ContractKey>(value.clone()).expect("decoded key"), 356 key 357 ); 358 359 let mut invalid = value.clone(); 360 invalid["registry_version"] = serde_json::json!(0); 361 assert!(serde_json::from_value::<ContractKey>(invalid).is_err()); 362 let mut invalid = value.clone(); 363 invalid["registry_version"] = serde_json::json!(9); 364 assert!(serde_json::from_value::<ContractKey>(invalid).is_err()); 365 let mut invalid = value.clone(); 366 invalid["contract_id"] = serde_json::json!("radroots.social.unknown.v1"); 367 assert!(serde_json::from_value::<ContractKey>(invalid).is_err()); 368 let mut invalid = value; 369 invalid["unexpected"] = serde_json::json!(true); 370 assert!(serde_json::from_value::<ContractKey>(invalid).is_err()); 371 } 372 }