dto.rs (108470B)
1 //! Focused, versioned value types owned by the native boundary. 2 3 use crate::media_file::MEDIA_FILE_MAX_BYTES; 4 use crate::{FfiDraftStatusRecord, FfiMediaFile}; 5 6 use radroots_blossom::{BlobDescriptor, MediaType, Sha256}; 7 use radroots_event::{ 8 calendar::{AuthoredCalendarDateEvent, AuthoredCalendarTimeEvent, CalendarDate}, 9 food::availability::{ 10 FoodAvailabilityDetails, FoodAvailabilityDetailsParts, FoodAvailabilityImage, 11 FoodAvailabilityStatus, FoodContent, FoodCurrency, FoodIdentifier, FoodImageDimensions, 12 FoodPrice, FoodPublishedAt, FoodQuantity, FoodText, FoodUnit, 13 }, 14 media::AuthoredImage, 15 post::{AuthoredPostImage, PostImageDimensions}, 16 }; 17 use tera_core::runtime::{ 18 app_info::AppInfoPlatform, 19 info::{AppInfo, RuntimeBuildInfo, RuntimeInfo}, 20 product_surface::{ 21 AddCommandType, CardLifecycleState, CreateAsk, CreateEvent, CreateFoodAvailability, 22 CreatePhotoUpdate, CreateUpdate, LocalNetwork, LocalNetworkRelayPolicy, MeSnapshot, 23 MediaReference, Phase1AddCommand, Phase1CancellationPolicy, Phase1DraftEventTiming, 24 Phase1DraftFormSnapshot, Phase1DraftKind, Phase1DraftMediaSnapshot, 25 Phase1InboundMediaState, Phase1MediaPrerequisite, Phase1MediaStage, Phase1OutboxState, 26 Phase1QueuePolicy, Phase1RelaySatisfaction, Phase1UploadIntent, ProfileSummary, 27 SearchResult, SearchResultType, SupportingProfile, ThreadEntry, TodayCard, TodayCardType, 28 TodayPage, TodayProjectionUpdate, TodayRefreshReceipt, 29 }, 30 sdk::{ 31 SdkBlossomConfigurationRecord, SdkBlossomEvidenceRecord, SdkCapabilityRecord, 32 SdkRelayAccessRecord, SdkRelayStatusRecord, SdkRelayStatusReportRecord, SdkShutdownRecord, 33 SdkStorageStatusRecord, 34 }, 35 }; 36 37 use crate::TeraAppError; 38 39 mod viewer_calendar; 40 pub use viewer_calendar::{FfiViewerCalendarContext, TODAY_PAGE_FFI_SCHEMA_VERSION}; 41 mod calendar; 42 pub use calendar::{FfiCalendarTiming, FfiCivilDate, TODAY_CARD_FFI_SCHEMA_VERSION}; 43 44 mod local_network_debug; 45 #[cfg(test)] 46 mod native_upload_job_tests; 47 mod today_sync; 48 pub use today_sync::{ 49 FfiTodayDiscoveryRecord, FfiTodayRelaySyncState, FfiTodaySyncRecord, FfiTodaySyncTermination, 50 FfiTodayTargetPageSummary, FfiTodayTargetSyncRecord, FfiTodayTargetSyncState, 51 }; 52 53 pub const MOBILE_FFI_SCHEMA_VERSION: u16 = 1; 54 pub const PREPARED_MEDIA_FFI_SCHEMA_VERSION: u16 = 2; 55 /// Upload outputs separate canonical blob references from transport destinations. 56 pub const UPLOAD_OUTPUT_FFI_SCHEMA_VERSION: u16 = 2; 57 const MEDIA_REFERENCE_MAX_BYTES: usize = 256; 58 59 /// Final four-state trade-evidence coverage vocabulary. 60 #[derive(Clone, Copy, Debug, Eq, PartialEq, uniffi::Enum)] 61 pub enum FfiTradeEvidenceCoverage { 62 Missing, 63 Partial, 64 ScopeSatisfied, 65 Unsupported, 66 } 67 68 /// Final three-state trade-evidence outcome vocabulary. 69 #[derive(Clone, Copy, Debug, Eq, PartialEq, uniffi::Enum)] 70 pub enum FfiTradeEvidenceOutcome { 71 Valid, 72 Invalid, 73 Indeterminate, 74 } 75 76 /// Secret-free projection of one canonical evidence manifest. 77 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 78 pub struct FfiTradeEvidenceManifestRecord { 79 pub schema_version: u16, 80 pub contract_id: String, 81 pub contract_version: u16, 82 pub trade_id: String, 83 pub trade_generation: String, 84 pub observed_at_unix_s: String, 85 pub coverage: FfiTradeEvidenceCoverage, 86 pub evidence_policy_digest: String, 87 pub manifest_digest: String, 88 pub canonical_bytes_hex: String, 89 } 90 91 /// Secret-free projection of one canonical RHI evidence report. 92 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 93 pub struct FfiRhiEvidenceReportRecord { 94 pub schema_version: u16, 95 pub contract_id: String, 96 pub contract_version: u16, 97 pub issuer_pubkey: String, 98 pub trade_id: String, 99 pub claim_mutation_id: String, 100 pub outcome: FfiTradeEvidenceOutcome, 101 pub reason_codes: Vec<String>, 102 pub projection_digest: String, 103 pub evidence_manifest_digest: String, 104 pub evidence_policy_digest: String, 105 pub observed_at_unix_s: String, 106 pub trade_generation: String, 107 pub statement_digest: String, 108 pub supersedes_report_id: Option<String>, 109 pub supersedes_event_id: Option<String>, 110 pub canonical_content: String, 111 } 112 113 /// Unsigned typed event plan ready for host-owned signing. 114 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 115 pub struct FfiTypedEvidenceEventPlanRecord { 116 pub schema_version: u16, 117 pub contract_id: String, 118 pub kind: u32, 119 pub author_pubkey: String, 120 pub created_at_unix_s: String, 121 pub expected_event_id: String, 122 pub tags: Vec<Vec<String>>, 123 pub content: String, 124 } 125 126 /// Signed NIP-01 event input for verified attestation admission. 127 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 128 pub struct FfiSignedEvidenceEventRecord { 129 pub id: String, 130 pub author_pubkey: String, 131 pub created_at_unix_s: u64, 132 pub kind: u32, 133 pub tags: Vec<Vec<String>>, 134 pub content: String, 135 pub signature: String, 136 } 137 138 /// Secret-free supersession projection from one verified attestation. 139 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 140 pub struct FfiRhiEvidenceAttestationSupersessionRecord { 141 pub report_id: String, 142 pub event_id: String, 143 } 144 145 /// Verified final RHI evidence attestation. 146 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 147 pub struct FfiRhiEvidenceAttestationRecord { 148 pub schema_version: u16, 149 pub issuer_pubkey: String, 150 pub trade_id: String, 151 pub claim_mutation_id: String, 152 pub outcome: FfiTradeEvidenceOutcome, 153 pub observed_at_unix_s: String, 154 pub trade_generation: String, 155 pub statement_digest: String, 156 pub supersession: Option<FfiRhiEvidenceAttestationSupersessionRecord>, 157 pub canonical_content: String, 158 } 159 160 #[uniffi::export] 161 pub fn parse_trade_evidence_manifest( 162 canonical_bytes: Vec<u8>, 163 ) -> Result<FfiTradeEvidenceManifestRecord, TeraAppError> { 164 let manifest = radroots_sdk::trade::parse_evidence_manifest(&canonical_bytes) 165 .map_err(|_| TeraAppError::invalid_argument("invalid_evidence_manifest"))?; 166 Ok(FfiTradeEvidenceManifestRecord { 167 schema_version: MOBILE_FFI_SCHEMA_VERSION, 168 contract_id: manifest.contract_id().to_owned(), 169 contract_version: manifest.contract_version(), 170 trade_id: manifest.trade_id().to_string(), 171 trade_generation: manifest.trade_generation().get().to_string(), 172 observed_at_unix_s: manifest.observed_at_unix_s().to_string(), 173 coverage: manifest.coverage().into(), 174 evidence_policy_digest: manifest.evidence_policy_digest().to_hex(), 175 manifest_digest: manifest.digest().to_hex(), 176 canonical_bytes_hex: hex::encode(manifest.canonical_bytes()), 177 }) 178 } 179 180 #[uniffi::export] 181 pub fn parse_rhi_evidence_report( 182 canonical_content: String, 183 ) -> Result<FfiRhiEvidenceReportRecord, TeraAppError> { 184 let report = radroots_sdk::trade::parse_rhi_evidence_report(canonical_content.as_bytes()) 185 .map_err(|_| TeraAppError::invalid_argument("invalid_evidence_report"))?; 186 let supersession = report.supersession(); 187 Ok(FfiRhiEvidenceReportRecord { 188 schema_version: MOBILE_FFI_SCHEMA_VERSION, 189 contract_id: report.contract_id().to_owned(), 190 contract_version: report.contract_version(), 191 issuer_pubkey: report.issuer_public_key().to_hex(), 192 trade_id: report.trade_id().to_string(), 193 claim_mutation_id: report.claim_mutation_id().to_string(), 194 outcome: report.outcome().into(), 195 reason_codes: report 196 .reason_codes() 197 .iter() 198 .map(|code| code.as_str().to_owned()) 199 .collect(), 200 projection_digest: report.projection_digest().to_hex(), 201 evidence_manifest_digest: report.evidence_manifest_digest().to_hex(), 202 evidence_policy_digest: report.evidence_policy_digest().to_hex(), 203 observed_at_unix_s: report.observed_at_unix_s().to_string(), 204 trade_generation: report.trade_generation().get().to_string(), 205 statement_digest: report.statement_digest().to_hex(), 206 supersedes_report_id: supersession.map(|value| value.report_id().to_hex()), 207 supersedes_event_id: supersession.map(|value| value.event_id().to_hex()), 208 canonical_content: report.canonical_content().to_owned(), 209 }) 210 } 211 212 #[uniffi::export] 213 pub fn prepare_rhi_evidence_attestation( 214 canonical_content: String, 215 created_at_unix_s: u64, 216 ) -> Result<FfiTypedEvidenceEventPlanRecord, TeraAppError> { 217 let report = radroots_sdk::trade::parse_rhi_evidence_report(canonical_content.as_bytes()) 218 .map_err(|_| TeraAppError::invalid_argument("invalid_evidence_report"))?; 219 let plan = radroots_sdk::trade::prepare_rhi_evidence_attestation(&report, created_at_unix_s) 220 .map_err(|_| TeraAppError::invalid_argument("invalid_evidence_attestation_plan"))?; 221 Ok(FfiTypedEvidenceEventPlanRecord { 222 schema_version: MOBILE_FFI_SCHEMA_VERSION, 223 contract_id: plan.body().contract().contract_id().as_str().to_owned(), 224 kind: plan.body().kind(), 225 author_pubkey: plan.author().to_hex(), 226 created_at_unix_s: plan.created_at().to_string(), 227 expected_event_id: plan.expected_event_id().to_hex(), 228 tags: plan.body().tags().to_vec(), 229 content: plan.body().content().to_owned(), 230 }) 231 } 232 233 #[uniffi::export] 234 pub fn validate_rhi_evidence_attestation( 235 event: FfiSignedEvidenceEventRecord, 236 ) -> Result<FfiRhiEvidenceAttestationRecord, TeraAppError> { 237 let event = radroots_event::envelope::EventEnvelope::new( 238 radroots_event::envelope::EventEnvelopeParts { 239 id: event.id, 240 author: event.author_pubkey, 241 created_at: event.created_at_unix_s, 242 kind: event.kind, 243 tags: event.tags, 244 content: event.content, 245 sig: event.signature, 246 }, 247 ) 248 .map_err(|_| TeraAppError::invalid_argument("invalid_signed_event"))?; 249 let attestation = radroots_sdk::trade::validate_rhi_evidence_attestation(event).map_err( 250 |error| match error { 251 radroots_sdk::trade::EvidenceAttestationValidationError::Signature => { 252 TeraAppError::invalid_argument("invalid_event_signature") 253 } 254 radroots_sdk::trade::EvidenceAttestationValidationError::Contract => { 255 TeraAppError::invalid_argument("invalid_evidence_attestation") 256 } 257 }, 258 )?; 259 Ok(FfiRhiEvidenceAttestationRecord { 260 schema_version: MOBILE_FFI_SCHEMA_VERSION, 261 issuer_pubkey: attestation.issuer().to_hex(), 262 trade_id: attestation.trade_id().to_string(), 263 claim_mutation_id: attestation.claim_mutation_id().to_string(), 264 outcome: match attestation.outcome() { 265 radroots_sdk::trade::RadrootsRhiEvidenceAttestationOutcomeV1::Valid => { 266 FfiTradeEvidenceOutcome::Valid 267 } 268 radroots_sdk::trade::RadrootsRhiEvidenceAttestationOutcomeV1::Invalid => { 269 FfiTradeEvidenceOutcome::Invalid 270 } 271 radroots_sdk::trade::RadrootsRhiEvidenceAttestationOutcomeV1::Indeterminate => { 272 FfiTradeEvidenceOutcome::Indeterminate 273 } 274 }, 275 observed_at_unix_s: attestation.observed_at_unix_s().to_string(), 276 trade_generation: attestation.trade_generation().get().to_string(), 277 statement_digest: hex::encode(attestation.statement_digest()), 278 supersession: attestation.supersession().map(|value| { 279 FfiRhiEvidenceAttestationSupersessionRecord { 280 report_id: hex::encode(value.report_id()), 281 event_id: value.event_id().to_hex(), 282 } 283 }), 284 canonical_content: attestation.canonical_content().to_owned(), 285 }) 286 } 287 288 impl From<radroots_sdk::trade::RadrootsTradeEvidenceCoverageV1> for FfiTradeEvidenceCoverage { 289 fn from(value: radroots_sdk::trade::RadrootsTradeEvidenceCoverageV1) -> Self { 290 match value { 291 radroots_sdk::trade::RadrootsTradeEvidenceCoverageV1::Missing => Self::Missing, 292 radroots_sdk::trade::RadrootsTradeEvidenceCoverageV1::Partial => Self::Partial, 293 radroots_sdk::trade::RadrootsTradeEvidenceCoverageV1::ScopeSatisfied => { 294 Self::ScopeSatisfied 295 } 296 radroots_sdk::trade::RadrootsTradeEvidenceCoverageV1::Unsupported => Self::Unsupported, 297 } 298 } 299 } 300 301 impl From<radroots_sdk::trade::RadrootsTradeEvidenceOutcomeV1> for FfiTradeEvidenceOutcome { 302 fn from(value: radroots_sdk::trade::RadrootsTradeEvidenceOutcomeV1) -> Self { 303 match value { 304 radroots_sdk::trade::RadrootsTradeEvidenceOutcomeV1::Valid => Self::Valid, 305 radroots_sdk::trade::RadrootsTradeEvidenceOutcomeV1::Invalid => Self::Invalid, 306 radroots_sdk::trade::RadrootsTradeEvidenceOutcomeV1::Indeterminate => { 307 Self::Indeterminate 308 } 309 } 310 } 311 } 312 313 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 314 pub struct FfiBuildInfoRecord { 315 pub schema_version: u16, 316 pub crate_name: String, 317 pub crate_version: String, 318 pub rustc: Option<String>, 319 pub profile: Option<String>, 320 pub lib_revision: Option<String>, 321 pub consumer_revision: Option<String>, 322 pub build_time_unix: Option<u64>, 323 } 324 325 // These exhaustive field-for-field adapters are verified by the generated API 326 // snapshot and Swift compilation. Excluding the mechanical projection glue 327 // keeps the coverage gate focused on validation and behavior. 328 #[cfg_attr(coverage_nightly, coverage(off))] 329 impl From<RuntimeBuildInfo> for FfiBuildInfoRecord { 330 fn from(value: RuntimeBuildInfo) -> Self { 331 Self { 332 schema_version: MOBILE_FFI_SCHEMA_VERSION, 333 crate_name: value.crate_name, 334 crate_version: value.crate_version, 335 rustc: value.rustc, 336 profile: value.profile, 337 lib_revision: value.lib_revision, 338 consumer_revision: value.consumer_revision, 339 build_time_unix: value.build_time_unix, 340 } 341 } 342 } 343 344 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 345 pub struct FfiAppPlatformRecord { 346 pub schema_version: u16, 347 pub platform: Option<String>, 348 pub bundle_id: Option<String>, 349 pub version: Option<String>, 350 pub build_number: Option<String>, 351 pub build_sha: Option<String>, 352 } 353 354 #[cfg_attr(coverage_nightly, coverage(off))] 355 impl From<AppInfoPlatform> for FfiAppPlatformRecord { 356 fn from(value: AppInfoPlatform) -> Self { 357 Self { 358 schema_version: MOBILE_FFI_SCHEMA_VERSION, 359 platform: value.platform, 360 bundle_id: value.bundle_id, 361 version: value.version, 362 build_number: value.build_number, 363 build_sha: value.build_sha, 364 } 365 } 366 } 367 368 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 369 pub struct FfiAppInfoRecord { 370 pub schema_version: u16, 371 pub build: FfiBuildInfoRecord, 372 pub started_unix_ms: i64, 373 pub uptime_millis: i64, 374 pub shutting_down: bool, 375 pub platform: Option<FfiAppPlatformRecord>, 376 } 377 378 #[cfg_attr(coverage_nightly, coverage(off))] 379 impl From<AppInfo> for FfiAppInfoRecord { 380 fn from(value: AppInfo) -> Self { 381 Self { 382 schema_version: MOBILE_FFI_SCHEMA_VERSION, 383 build: value.build.into(), 384 started_unix_ms: value.started_unix_ms, 385 uptime_millis: value.uptime_millis, 386 shutting_down: value.shutting_down, 387 platform: value.platform.map(Into::into), 388 } 389 } 390 } 391 392 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 393 pub struct FfiRuntimeInfoRecord { 394 pub schema_version: u16, 395 pub app: FfiAppInfoRecord, 396 pub sdk: FfiBuildInfoRecord, 397 pub sdk_closed: bool, 398 } 399 400 #[cfg_attr(coverage_nightly, coverage(off))] 401 impl From<RuntimeInfo> for FfiRuntimeInfoRecord { 402 fn from(value: RuntimeInfo) -> Self { 403 Self { 404 schema_version: MOBILE_FFI_SCHEMA_VERSION, 405 app: value.app.into(), 406 sdk: value.sdk.into(), 407 sdk_closed: value.sdk_closed, 408 } 409 } 410 } 411 412 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 413 pub struct FfiIdentityStatusRecord { 414 pub schema_version: u16, 415 pub public_key: String, 416 pub host_signer_configured: bool, 417 } 418 419 #[derive(Clone, Copy, Debug, Eq, PartialEq, uniffi::Enum)] 420 pub enum FfiTodayCardType { 421 Update, 422 PhotoUpdate, 423 Ask, 424 Event, 425 FoodAvailability, 426 } 427 428 #[cfg_attr(coverage_nightly, coverage(off))] 429 impl From<TodayCardType> for FfiTodayCardType { 430 fn from(value: TodayCardType) -> Self { 431 match value { 432 TodayCardType::Update => Self::Update, 433 TodayCardType::PhotoUpdate => Self::PhotoUpdate, 434 TodayCardType::Ask => Self::Ask, 435 TodayCardType::Event => Self::Event, 436 TodayCardType::FoodAvailability => Self::FoodAvailability, 437 } 438 } 439 } 440 441 #[derive(Clone, Copy, Debug, Eq, PartialEq, uniffi::Enum)] 442 pub enum FfiAddCommandType { 443 CreateUpdate, 444 CreatePhotoUpdate, 445 CreateAsk, 446 CreateEvent, 447 CreateFoodAvailability, 448 } 449 450 #[cfg_attr(coverage_nightly, coverage(off))] 451 impl From<AddCommandType> for FfiAddCommandType { 452 fn from(value: AddCommandType) -> Self { 453 match value { 454 AddCommandType::CreateUpdate => Self::CreateUpdate, 455 AddCommandType::CreatePhotoUpdate => Self::CreatePhotoUpdate, 456 AddCommandType::CreateAsk => Self::CreateAsk, 457 AddCommandType::CreateEvent => Self::CreateEvent, 458 AddCommandType::CreateFoodAvailability => Self::CreateFoodAvailability, 459 } 460 } 461 } 462 463 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 464 pub struct FfiCardAddParityRecord { 465 pub schema_version: u16, 466 pub card_type: FfiTodayCardType, 467 pub command_type: FfiAddCommandType, 468 } 469 470 #[derive(Clone, Eq, PartialEq, uniffi::Record)] 471 pub struct FfiLocalNetworkRecord { 472 pub schema_version: u16, 473 pub id: String, 474 pub label: String, 475 pub relay_urls: Vec<String>, 476 pub locality: Option<String>, 477 pub followed_authors: Vec<String>, 478 pub generation: u64, 479 } 480 481 impl TryFrom<FfiLocalNetworkRecord> for LocalNetwork { 482 type Error = TeraAppError; 483 484 fn try_from(value: FfiLocalNetworkRecord) -> Result<Self, Self::Error> { 485 value.try_into_with_relay_policy(LocalNetworkRelayPolicy::Public) 486 } 487 } 488 489 impl FfiLocalNetworkRecord { 490 pub(crate) fn try_into_with_relay_policy( 491 self, 492 relay_policy: LocalNetworkRelayPolicy, 493 ) -> Result<LocalNetwork, TeraAppError> { 494 require_schema(self.schema_version)?; 495 LocalNetwork::new_for_relay_policy( 496 self.id, 497 self.label, 498 self.relay_urls, 499 self.locality, 500 self.followed_authors, 501 self.generation, 502 relay_policy, 503 ) 504 .map_err(|_| TeraAppError::invalid_argument("invalid_local_network")) 505 } 506 } 507 508 #[cfg_attr(coverage_nightly, coverage(off))] 509 impl From<LocalNetwork> for FfiLocalNetworkRecord { 510 fn from(value: LocalNetwork) -> Self { 511 Self { 512 schema_version: MOBILE_FFI_SCHEMA_VERSION, 513 id: value.id.into(), 514 label: value.label, 515 relay_urls: value.relay_urls, 516 locality: value.locality, 517 followed_authors: value.followed_authors, 518 generation: value.generation, 519 } 520 } 521 } 522 523 #[derive(Clone, Copy, Debug, Eq, PartialEq, uniffi::Enum)] 524 pub enum FfiMediaVerificationState { 525 Pending, 526 Verified, 527 Failed, 528 Unavailable, 529 } 530 531 #[cfg_attr(coverage_nightly, coverage(off))] 532 impl From<&Phase1InboundMediaState> for FfiMediaVerificationState { 533 fn from(value: &Phase1InboundMediaState) -> Self { 534 match value { 535 Phase1InboundMediaState::Pending(_) => Self::Pending, 536 Phase1InboundMediaState::Verified(_) => Self::Verified, 537 Phase1InboundMediaState::Failed(_) => Self::Failed, 538 Phase1InboundMediaState::Unavailable => Self::Unavailable, 539 } 540 } 541 } 542 543 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 544 pub struct FfiMediaReferenceRecord { 545 pub schema_version: u16, 546 pub reference_fingerprint: String, 547 pub url: String, 548 pub sha256: Option<String>, 549 pub media_type: Option<String>, 550 pub width: Option<u32>, 551 pub height: Option<u32>, 552 pub byte_size: Option<u64>, 553 pub alt: Option<String>, 554 pub verification: FfiMediaVerificationState, 555 } 556 557 #[cfg_attr(coverage_nightly, coverage(off))] 558 impl From<MediaReference> for FfiMediaReferenceRecord { 559 fn from(value: MediaReference) -> Self { 560 let structural = value.structural(); 561 Self { 562 schema_version: MOBILE_FFI_SCHEMA_VERSION, 563 reference_fingerprint: hex::encode(structural.fingerprint()), 564 url: structural.source_url().to_owned(), 565 sha256: structural.expected_sha256().map(str::to_owned), 566 media_type: structural.expected_media_type().map(str::to_owned), 567 width: structural.expected_width(), 568 height: structural.expected_height(), 569 byte_size: structural.expected_byte_size(), 570 alt: structural.alt().map(str::to_owned), 571 verification: value.retrieval().into(), 572 } 573 } 574 } 575 576 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 577 pub struct FfiProfileRecord { 578 pub schema_version: u16, 579 pub author_public_key: String, 580 pub name: Option<String>, 581 pub display_name: Option<String>, 582 pub about: Option<String>, 583 pub picture: Option<FfiMediaReferenceRecord>, 584 pub banner: Option<FfiMediaReferenceRecord>, 585 pub nip05: Option<String>, 586 pub website: Option<String>, 587 pub lightning_address: Option<String>, 588 } 589 590 #[cfg_attr(coverage_nightly, coverage(off))] 591 impl From<ProfileSummary> for FfiProfileRecord { 592 fn from(value: ProfileSummary) -> Self { 593 Self { 594 schema_version: MOBILE_FFI_SCHEMA_VERSION, 595 author_public_key: value.author_pubkey, 596 name: value.name, 597 display_name: value.display_name, 598 about: value.about, 599 picture: value.picture.map(Into::into), 600 banner: value.banner.map(Into::into), 601 nip05: value.nip05, 602 website: value.website, 603 lightning_address: value.lightning_address, 604 } 605 } 606 } 607 608 #[derive(Clone, Copy, Debug, Eq, PartialEq, uniffi::Enum)] 609 pub enum FfiThreadProfile { 610 Profile, 611 Reply, 612 Comment, 613 Deletion, 614 } 615 616 #[cfg_attr(coverage_nightly, coverage(off))] 617 impl From<SupportingProfile> for FfiThreadProfile { 618 fn from(value: SupportingProfile) -> Self { 619 match value { 620 SupportingProfile::Profile => Self::Profile, 621 SupportingProfile::Reply => Self::Reply, 622 SupportingProfile::Comment => Self::Comment, 623 SupportingProfile::Deletion => Self::Deletion, 624 } 625 } 626 } 627 628 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 629 pub struct FfiThreadEntryRecord { 630 pub schema_version: u16, 631 pub event_id: String, 632 pub author_public_key: String, 633 pub content: String, 634 pub authored_at_unix_s: u64, 635 pub profile: FfiThreadProfile, 636 pub root: String, 637 pub parent_event_id: String, 638 pub author_profile: Option<FfiProfileRecord>, 639 } 640 641 #[cfg_attr(coverage_nightly, coverage(off))] 642 impl From<ThreadEntry> for FfiThreadEntryRecord { 643 fn from(value: ThreadEntry) -> Self { 644 Self { 645 schema_version: MOBILE_FFI_SCHEMA_VERSION, 646 event_id: value.event_id, 647 author_public_key: value.author_pubkey, 648 content: value.content, 649 authored_at_unix_s: value.authored_at, 650 profile: value.reference.profile.into(), 651 root: value.reference.root, 652 parent_event_id: value.reference.parent_event_id, 653 author_profile: value.author_profile.map(Into::into), 654 } 655 } 656 } 657 658 #[derive(Clone, Copy, Debug, Eq, PartialEq, uniffi::Enum)] 659 pub enum FfiCardLifecycleState { 660 Active, 661 Sold, 662 Past, 663 } 664 665 #[cfg_attr(coverage_nightly, coverage(off))] 666 impl From<CardLifecycleState> for FfiCardLifecycleState { 667 fn from(value: CardLifecycleState) -> Self { 668 match value { 669 CardLifecycleState::Active => Self::Active, 670 CardLifecycleState::Sold => Self::Sold, 671 CardLifecycleState::Past => Self::Past, 672 } 673 } 674 } 675 676 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 677 pub struct FfiTodayCardRecord { 678 pub schema_version: u16, 679 pub card_id: String, 680 pub card_type: FfiTodayCardType, 681 pub source_event_id: String, 682 pub source_address: Option<String>, 683 pub author_public_key: String, 684 pub contract_id: String, 685 pub title: Option<String>, 686 pub content: String, 687 pub authored_at_unix_s: u64, 688 pub effective_at_unix_s: u64, 689 pub calendar_timing: Option<FfiCalendarTiming>, 690 pub location: Option<String>, 691 pub price_amount: Option<String>, 692 pub price_currency: Option<String>, 693 pub price_unit: Option<String>, 694 pub quantity: Option<String>, 695 pub food_summary: Option<String>, 696 pub food_published_at_unix_s: Option<u64>, 697 pub food_status: Option<String>, 698 pub context_rank: u8, 699 pub inclusion_reason: String, 700 pub media: Vec<FfiMediaReferenceRecord>, 701 pub lifecycle: FfiCardLifecycleState, 702 pub rank_digest: Option<String>, 703 pub author_profile: Option<FfiProfileRecord>, 704 pub thread: Vec<FfiThreadEntryRecord>, 705 pub thread_next_cursor: Option<String>, 706 pub local_source_draft_id: Option<String>, 707 pub local_operation_id: Option<String>, 708 pub local_operation_state: Option<String>, 709 } 710 711 #[cfg_attr(coverage_nightly, coverage(off))] 712 impl From<TodayCard> for FfiTodayCardRecord { 713 fn from(value: TodayCard) -> Self { 714 let card = value.card; 715 Self { 716 schema_version: TODAY_CARD_FFI_SCHEMA_VERSION, 717 card_id: card.card_id.to_hex(), 718 card_type: card.card_type.into(), 719 source_event_id: card.source_event_id, 720 source_address: card.source_address, 721 author_public_key: card.author_pubkey, 722 contract_id: card.contract_id, 723 title: card.title, 724 content: card.content, 725 authored_at_unix_s: card.authored_at, 726 effective_at_unix_s: card.effective_at, 727 calendar_timing: card.calendar_timing.map(Into::into), 728 location: card.location, 729 price_amount: card.price_amount, 730 price_currency: card.price_currency, 731 price_unit: card.price_unit, 732 quantity: card.quantity, 733 food_summary: card.food_summary, 734 food_published_at_unix_s: card.food_published_at, 735 food_status: card.food_status, 736 context_rank: card.context_rank.value(), 737 inclusion_reason: card.inclusion_reason, 738 media: card.media.into_iter().map(Into::into).collect(), 739 lifecycle: card.lifecycle.into(), 740 rank_digest: card.rank.map(|rank| rank.digest_hex()), 741 author_profile: value.author_profile.map(Into::into), 742 thread: value.thread.into_iter().map(Into::into).collect(), 743 thread_next_cursor: value.thread_next_cursor, 744 local_source_draft_id: value 745 .local_overlay 746 .as_ref() 747 .and_then(|overlay| overlay.source_draft_id.clone()), 748 local_operation_id: value 749 .local_overlay 750 .as_ref() 751 .map(|overlay| overlay.operation_id.clone()), 752 local_operation_state: value.local_overlay.map(|overlay| overlay.state), 753 } 754 } 755 } 756 757 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 758 pub struct FfiTodayPageRecord { 759 pub calendar: FfiViewerCalendarContext, 760 pub projection_generation: u64, 761 pub schema_version: u16, 762 pub as_of_unix_s: u64, 763 pub items: Vec<FfiTodayCardRecord>, 764 pub next_cursor: Option<String>, 765 } 766 767 #[derive(Clone, Copy, Debug, Eq, PartialEq, uniffi::Enum)] 768 pub enum FfiTodayProjectionUpdate { 769 Incremental, 770 Rebuild, 771 } 772 773 #[cfg_attr(coverage_nightly, coverage(off))] 774 impl From<FfiTodayProjectionUpdate> for TodayProjectionUpdate { 775 fn from(value: FfiTodayProjectionUpdate) -> Self { 776 match value { 777 FfiTodayProjectionUpdate::Incremental => Self::Incremental, 778 FfiTodayProjectionUpdate::Rebuild => Self::Rebuild, 779 } 780 } 781 } 782 783 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 784 pub struct FfiTodayRefreshRecord { 785 pub schema_version: u16, 786 pub update: FfiTodayProjectionUpdate, 787 pub source_events: u64, 788 pub visible_cards: u64, 789 pub profiles: u64, 790 pub thread_entries: u64, 791 pub content_generation: u64, 792 pub changed: bool, 793 } 794 795 #[cfg_attr(coverage_nightly, coverage(off))] 796 impl From<TodayRefreshReceipt> for FfiTodayRefreshRecord { 797 fn from(value: TodayRefreshReceipt) -> Self { 798 Self { 799 schema_version: MOBILE_FFI_SCHEMA_VERSION, 800 update: match value.update { 801 TodayProjectionUpdate::Incremental => FfiTodayProjectionUpdate::Incremental, 802 TodayProjectionUpdate::Rebuild => FfiTodayProjectionUpdate::Rebuild, 803 }, 804 source_events: value.source_events, 805 visible_cards: value.visible_cards, 806 profiles: value.profiles, 807 thread_entries: value.thread_entries, 808 content_generation: value.content_generation, 809 changed: value.changed, 810 } 811 } 812 } 813 814 #[cfg_attr(coverage_nightly, coverage(off))] 815 impl From<TodayPage> for FfiTodayPageRecord { 816 fn from(value: TodayPage) -> Self { 817 Self { 818 calendar: value.calendar.into(), 819 schema_version: TODAY_PAGE_FFI_SCHEMA_VERSION, 820 projection_generation: value.projection_generation, 821 as_of_unix_s: value.as_of, 822 items: value.items.into_iter().map(Into::into).collect(), 823 next_cursor: value.next_cursor, 824 } 825 } 826 } 827 828 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 829 pub struct FfiTodayThreadPageRecord { 830 pub card_id: String, 831 pub items: Vec<FfiThreadEntryRecord>, 832 pub next_cursor: Option<String>, 833 } 834 835 impl From<tera_core::runtime::product_surface::TodayThreadPage> for FfiTodayThreadPageRecord { 836 fn from(value: tera_core::runtime::product_surface::TodayThreadPage) -> Self { 837 Self { 838 card_id: value.card_id.to_hex(), 839 items: value.items.into_iter().map(Into::into).collect(), 840 next_cursor: value.next_cursor, 841 } 842 } 843 } 844 845 #[derive(Clone, Copy, Debug, Eq, PartialEq, uniffi::Enum)] 846 pub enum FfiSearchResultType { 847 Card, 848 Profile, 849 } 850 851 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 852 pub struct FfiSearchResultRecord { 853 pub schema_version: u16, 854 pub result_type: FfiSearchResultType, 855 pub stable_id: String, 856 pub card: Option<FfiTodayCardRecord>, 857 pub profile: Option<FfiProfileRecord>, 858 } 859 860 #[cfg_attr(coverage_nightly, coverage(off))] 861 impl From<SearchResult> for FfiSearchResultRecord { 862 fn from(value: SearchResult) -> Self { 863 Self { 864 schema_version: MOBILE_FFI_SCHEMA_VERSION, 865 result_type: match value.result_type { 866 SearchResultType::Card => FfiSearchResultType::Card, 867 SearchResultType::Profile => FfiSearchResultType::Profile, 868 }, 869 stable_id: value.stable_id, 870 card: value.card.map(Into::into), 871 profile: value.profile.map(Into::into), 872 } 873 } 874 } 875 876 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 877 pub struct FfiMeRecord { 878 pub schema_version: u16, 879 pub public_key: String, 880 pub profile: Option<FfiProfileRecord>, 881 pub cards: Vec<FfiTodayCardRecord>, 882 } 883 884 #[cfg_attr(coverage_nightly, coverage(off))] 885 impl From<MeSnapshot> for FfiMeRecord { 886 fn from(value: MeSnapshot) -> Self { 887 Self { 888 schema_version: MOBILE_FFI_SCHEMA_VERSION, 889 public_key: value.public_key, 890 profile: value.profile.map(Into::into), 891 cards: value.cards.into_iter().map(Into::into).collect(), 892 } 893 } 894 } 895 896 #[derive(Clone, Copy, Debug, Eq, PartialEq, uniffi::Enum)] 897 pub enum FfiAddFieldKind { 898 Text, 899 MultilineText, 900 Date, 901 DateTime, 902 Decimal, 903 Choice, 904 Location, 905 Media, 906 } 907 908 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 909 pub struct FfiAddFieldRecord { 910 pub schema_version: u16, 911 pub id: String, 912 pub label: String, 913 pub kind: FfiAddFieldKind, 914 pub required: bool, 915 pub choices: Vec<String>, 916 pub max_bytes: Option<u64>, 917 pub max_items: Option<u16>, 918 } 919 920 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 921 pub struct FfiAddSchemaRecord { 922 pub schema_version: u16, 923 pub command_type: FfiAddCommandType, 924 pub label: String, 925 pub fields: Vec<FfiAddFieldRecord>, 926 } 927 928 pub fn add_schemas() -> Vec<FfiAddSchemaRecord> { 929 use FfiAddCommandType as Command; 930 use FfiAddFieldKind as Kind; 931 932 let field = 933 |id: &str, label: &str, kind, required, choices: &[&str], max_bytes| FfiAddFieldRecord { 934 schema_version: MOBILE_FFI_SCHEMA_VERSION, 935 id: id.to_owned(), 936 label: label.to_owned(), 937 kind, 938 required, 939 choices: choices.iter().map(|value| (*value).to_owned()).collect(), 940 max_bytes, 941 max_items: None, 942 }; 943 let media_field = |label: &str, required: bool, max_items| FfiAddFieldRecord { 944 max_items: Some(max_items), 945 ..field( 946 "media", 947 label, 948 Kind::Media, 949 required, 950 &[], 951 Some(MEDIA_FILE_MAX_BYTES), 952 ) 953 }; 954 vec![ 955 FfiAddSchemaRecord { 956 schema_version: MOBILE_FFI_SCHEMA_VERSION, 957 command_type: Command::CreateUpdate, 958 label: "Update".to_owned(), 959 fields: vec![field( 960 "content", 961 "Update", 962 Kind::MultilineText, 963 true, 964 &[], 965 Some(65_535), 966 )], 967 }, 968 FfiAddSchemaRecord { 969 schema_version: MOBILE_FFI_SCHEMA_VERSION, 970 command_type: Command::CreatePhotoUpdate, 971 label: "Photo update".to_owned(), 972 fields: vec![ 973 field( 974 "content", 975 "Update", 976 Kind::MultilineText, 977 true, 978 &[], 979 Some(65_535), 980 ), 981 media_field("Photos", true, 20), 982 ], 983 }, 984 FfiAddSchemaRecord { 985 schema_version: MOBILE_FFI_SCHEMA_VERSION, 986 command_type: Command::CreateAsk, 987 label: "Ask".to_owned(), 988 fields: vec![ 989 field( 990 "content", 991 "Question", 992 Kind::MultilineText, 993 true, 994 &[], 995 Some(65_535), 996 ), 997 media_field("Photos", false, 20), 998 ], 999 }, 1000 FfiAddSchemaRecord { 1001 schema_version: MOBILE_FFI_SCHEMA_VERSION, 1002 command_type: Command::CreateEvent, 1003 label: "Event".to_owned(), 1004 fields: vec![ 1005 field("identifier", "Identifier", Kind::Text, true, &[], Some(256)), 1006 field("title", "Title", Kind::Text, true, &[], Some(256)), 1007 field( 1008 "content", 1009 "Description", 1010 Kind::MultilineText, 1011 false, 1012 &[], 1013 Some(65_535), 1014 ), 1015 field("event_start", "Starts", Kind::DateTime, true, &[], None), 1016 field("event_end", "Ends", Kind::DateTime, false, &[], None), 1017 field( 1018 "location", 1019 "Location", 1020 Kind::Location, 1021 false, 1022 &[], 1023 Some(256), 1024 ), 1025 media_field("Photo", false, 1), 1026 ], 1027 }, 1028 FfiAddSchemaRecord { 1029 schema_version: MOBILE_FFI_SCHEMA_VERSION, 1030 command_type: Command::CreateFoodAvailability, 1031 label: "Food availability".to_owned(), 1032 fields: vec![ 1033 field("identifier", "Identifier", Kind::Text, true, &[], Some(256)), 1034 field("title", "Food", Kind::Text, true, &[], Some(256)), 1035 field("summary", "Summary", Kind::Text, true, &[], Some(256)), 1036 field( 1037 "content", 1038 "Details", 1039 Kind::MultilineText, 1040 true, 1041 &[], 1042 Some(65_535), 1043 ), 1044 field( 1045 "location", 1046 "Pickup location", 1047 Kind::Location, 1048 true, 1049 &[], 1050 Some(256), 1051 ), 1052 field("price_amount", "Price", Kind::Decimal, true, &[], Some(64)), 1053 field("currency", "Currency", Kind::Choice, true, &[], Some(3)), 1054 field( 1055 "unit", 1056 "Unit", 1057 Kind::Choice, 1058 true, 1059 &[ 1060 "g", "kg", "lb", "oz", "each", "dozen", "bunch", "punnet", "bag", "basket", 1061 ], 1062 None, 1063 ), 1064 field( 1065 "quantity", 1066 "Available quantity", 1067 Kind::Decimal, 1068 false, 1069 &[], 1070 Some(64), 1071 ), 1072 media_field("Photos", false, 20), 1073 ], 1074 }, 1075 ] 1076 } 1077 1078 #[derive(Clone, Copy, Debug, Eq, PartialEq, uniffi::Enum)] 1079 pub enum FfiEventTimingKind { 1080 AllDay, 1081 Timed, 1082 } 1083 1084 #[derive(Clone, Debug, uniffi::Record)] 1085 pub struct FfiPreparedMediaInput { 1086 pub schema_version: u16, 1087 pub opaque_reference: String, 1088 pub file: std::sync::Arc<FfiMediaFile>, 1089 pub sha256: String, 1090 pub media_type: String, 1091 pub byte_size: u64, 1092 pub width: u32, 1093 pub height: u32, 1094 pub alt: String, 1095 pub prepared_at_unix_s: u64, 1096 } 1097 1098 #[derive(Clone, Debug, uniffi::Record)] 1099 pub struct FfiAddDraftInput { 1100 pub schema_version: u16, 1101 pub command_type: FfiAddCommandType, 1102 pub content: String, 1103 pub identifier: Option<String>, 1104 pub title: Option<String>, 1105 pub summary: Option<String>, 1106 pub location: Option<String>, 1107 pub event_timing: Option<FfiEventTimingKind>, 1108 pub event_start_date: Option<String>, 1109 pub event_end_date: Option<String>, 1110 pub event_start_unix_s: Option<u64>, 1111 pub event_end_unix_s: Option<u64>, 1112 pub event_timezone: Option<String>, 1113 pub price_amount: Option<String>, 1114 pub currency: Option<String>, 1115 pub unit: Option<String>, 1116 pub quantity: Option<String>, 1117 pub food_published_at_unix_s: Option<u64>, 1118 pub food_status: Option<String>, 1119 pub media: Vec<FfiPreparedMediaInput>, 1120 } 1121 1122 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 1123 pub struct FfiRetractionDraftInput { 1124 pub schema_version: u16, 1125 pub command_type: FfiAddCommandType, 1126 pub target_card_id: String, 1127 pub target_event_id: String, 1128 pub target_kind: u32, 1129 pub target_address: Option<String>, 1130 pub reason: String, 1131 } 1132 1133 #[derive(Clone, Debug, uniffi::Record)] 1134 pub struct FfiBlossomUploadInput { 1135 pub schema_version: u16, 1136 pub draft_id: String, 1137 pub expected_revision: u64, 1138 pub media: FfiPreparedMediaInput, 1139 pub authorization_content: String, 1140 pub authorization_created_at_unix_s: u64, 1141 pub authorization_lifetime_seconds: u64, 1142 pub operation_id: String, 1143 pub artifact_id: String, 1144 pub signing_deadline_unix_ms: u64, 1145 pub signing_cancellation: FfiCancellationPolicy, 1146 pub verified_at_unix_ms: u64, 1147 pub updated_at_unix_ms: u64, 1148 } 1149 1150 /// Minimal host input for a Rust-planned exact-byte upload attempt. 1151 #[derive(Clone, Debug, uniffi::Record)] 1152 pub struct FfiBlossomUploadIntent { 1153 pub schema_version: u16, 1154 pub draft_id: String, 1155 pub expected_revision: u64, 1156 pub media: FfiPreparedMediaInput, 1157 } 1158 1159 /// Secret-bearing native job. Hosts may use the authorization header for the 1160 /// immediate OS request but must not persist it in application metadata. 1161 /// Debug formatting omits every request field, including nested draft values. 1162 #[derive(Clone, Eq, PartialEq, uniffi::Record)] 1163 pub struct FfiNativeUploadJobRecord { 1164 pub schema_version: u16, 1165 pub operation_id: String, 1166 pub draft: FfiDraftStatusRecord, 1167 pub remote_url: String, 1168 pub upload_url: String, 1169 pub authorization_header: String, 1170 pub expected_sha256: String, 1171 pub media_type: String, 1172 pub byte_size: u64, 1173 } 1174 1175 impl std::fmt::Debug for FfiNativeUploadJobRecord { 1176 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 1177 formatter 1178 .debug_struct("FfiNativeUploadJobRecord") 1179 .finish_non_exhaustive() 1180 } 1181 } 1182 1183 #[derive(Clone, Debug, uniffi::Record)] 1184 pub struct FfiNativeUploadCompletionInput { 1185 pub schema_version: u16, 1186 pub draft_id: String, 1187 pub expected_revision: u64, 1188 pub media: FfiPreparedMediaInput, 1189 pub status_code: u16, 1190 pub response_media_type: Option<String>, 1191 pub response_content_encoding: Option<String>, 1192 pub response_body: Vec<u8>, 1193 } 1194 1195 impl FfiAddDraftInput { 1196 pub(crate) fn command_and_media( 1197 self, 1198 authored_at_unix_s: u64, 1199 blossom: Option<&radroots_sdk::transport::BlossomSlot>, 1200 ) -> Result<(Phase1AddCommand, Vec<Phase1MediaPrerequisite>), TeraAppError> { 1201 self.command_media_and_form(authored_at_unix_s, blossom) 1202 .map(|(command, media, _)| (command, media)) 1203 } 1204 1205 pub(crate) fn command_media_and_form( 1206 self, 1207 authored_at_unix_s: u64, 1208 blossom: Option<&radroots_sdk::transport::BlossomSlot>, 1209 ) -> Result< 1210 ( 1211 Phase1AddCommand, 1212 Vec<Phase1MediaPrerequisite>, 1213 Phase1DraftFormSnapshot, 1214 ), 1215 TeraAppError, 1216 > { 1217 require_schema(self.schema_version)?; 1218 if authored_at_unix_s == 0 || self.media.len() > 20 { 1219 return Err(TeraAppError::invalid_argument("invalid_add_draft")); 1220 } 1221 let prepared = self 1222 .media 1223 .iter() 1224 .cloned() 1225 .map(PreparedMedia::try_from) 1226 .map(|media| { 1227 media.and_then(|media| { 1228 let blossom = blossom 1229 .ok_or_else(|| TeraAppError::invalid_argument("blossom_not_configured"))?; 1230 media.bind(blossom) 1231 }) 1232 }) 1233 .collect::<Result<Vec<BoundPreparedMedia>, _>>()?; 1234 let prerequisites = prepared 1235 .iter() 1236 .map(|value| { 1237 Phase1MediaPrerequisite::new( 1238 value.media.opaque_reference.clone(), 1239 &value.descriptor, 1240 ) 1241 }) 1242 .collect::<Result<Vec<_>, _>>() 1243 .map_err(|_| TeraAppError::invalid_argument("invalid_media_reference"))?; 1244 let post_images = prepared 1245 .iter() 1246 .map(BoundPreparedMedia::post_image) 1247 .collect::<Result<Vec<_>, _>>()?; 1248 let form = self.form_snapshot(&prepared); 1249 let command = match self.command_type { 1250 FfiAddCommandType::CreateUpdate => { 1251 reject_media(&prepared)?; 1252 Phase1AddCommand::CreateUpdate( 1253 CreateUpdate::new(self.content) 1254 .map_err(|_| TeraAppError::invalid_argument("invalid_update"))?, 1255 ) 1256 } 1257 FfiAddCommandType::CreatePhotoUpdate => Phase1AddCommand::CreatePhotoUpdate( 1258 CreatePhotoUpdate::new( 1259 content_with_media_references(self.content, &prepared)?, 1260 post_images, 1261 ) 1262 .map_err(|_| TeraAppError::invalid_argument("invalid_photo_update"))?, 1263 ), 1264 FfiAddCommandType::CreateAsk => Phase1AddCommand::CreateAsk( 1265 CreateAsk::new( 1266 content_with_media_references(self.content, &prepared)?, 1267 post_images, 1268 ) 1269 .map_err(|_| TeraAppError::invalid_argument("invalid_ask"))?, 1270 ), 1271 FfiAddCommandType::CreateEvent => { 1272 Phase1AddCommand::CreateEvent(event_command(&self, prepared.first())?) 1273 } 1274 FfiAddCommandType::CreateFoodAvailability => Phase1AddCommand::CreateFoodAvailability( 1275 food_command(self, authored_at_unix_s, &prepared)?, 1276 ), 1277 }; 1278 Ok((command, prerequisites, form)) 1279 } 1280 1281 fn form_snapshot(&self, prepared: &[BoundPreparedMedia]) -> Phase1DraftFormSnapshot { 1282 Phase1DraftFormSnapshot { 1283 command_type: match self.command_type { 1284 FfiAddCommandType::CreateUpdate => AddCommandType::CreateUpdate, 1285 FfiAddCommandType::CreatePhotoUpdate => AddCommandType::CreatePhotoUpdate, 1286 FfiAddCommandType::CreateAsk => AddCommandType::CreateAsk, 1287 FfiAddCommandType::CreateEvent => AddCommandType::CreateEvent, 1288 FfiAddCommandType::CreateFoodAvailability => AddCommandType::CreateFoodAvailability, 1289 }, 1290 content: self.content.clone(), 1291 identifier: self.identifier.clone(), 1292 title: self.title.clone(), 1293 summary: self.summary.clone(), 1294 location: self.location.clone(), 1295 event_timing: self.event_timing.map(|value| match value { 1296 FfiEventTimingKind::AllDay => Phase1DraftEventTiming::AllDay, 1297 FfiEventTimingKind::Timed => Phase1DraftEventTiming::Timed, 1298 }), 1299 event_start_date: self.event_start_date.clone(), 1300 event_end_date: self.event_end_date.clone(), 1301 event_start_unix_s: self.event_start_unix_s, 1302 event_end_unix_s: self.event_end_unix_s, 1303 event_timezone: self.event_timezone.clone(), 1304 price_amount: self.price_amount.clone(), 1305 currency: self.currency.clone(), 1306 unit: self.unit.clone(), 1307 quantity: self.quantity.clone(), 1308 food_published_at_unix_s: self.food_published_at_unix_s, 1309 food_status: self.food_status.clone(), 1310 media: prepared 1311 .iter() 1312 .map(|value| Phase1DraftMediaSnapshot { 1313 opaque_reference: value.media.opaque_reference.clone(), 1314 url: value.descriptor.url().as_str().to_owned(), 1315 sha256: value.media.sha256.to_hex(), 1316 media_type: value.media.media_type.as_str().to_owned(), 1317 byte_size: value.media.byte_size, 1318 width: value.media.width, 1319 height: value.media.height, 1320 alt: value.media.alt.clone(), 1321 prepared_at_unix_s: value.media.prepared_at_unix_s, 1322 }) 1323 .collect(), 1324 } 1325 } 1326 } 1327 1328 pub(crate) struct PreparedMedia { 1329 opaque_reference: String, 1330 sha256: Sha256, 1331 byte_size: u64, 1332 prepared_at_unix_s: u64, 1333 bytes: std::sync::Arc<[u8]>, 1334 media_type: MediaType, 1335 width: u32, 1336 height: u32, 1337 alt: String, 1338 } 1339 1340 struct BoundPreparedMedia { 1341 media: PreparedMedia, 1342 descriptor: radroots_blossom::ByteVerifiedDescriptor, 1343 } 1344 1345 impl TryFrom<FfiPreparedMediaInput> for PreparedMedia { 1346 type Error = TeraAppError; 1347 1348 fn try_from(value: FfiPreparedMediaInput) -> Result<Self, Self::Error> { 1349 if value.schema_version != PREPARED_MEDIA_FFI_SCHEMA_VERSION { 1350 return Err(TeraAppError::invalid_argument("unsupported_schema_version")); 1351 } 1352 if !opaque_media_reference_is_valid(&value.opaque_reference) 1353 || value.byte_size == 0 1354 || value.byte_size > MEDIA_FILE_MAX_BYTES 1355 || value.width == 0 1356 || value.height == 0 1357 || value.prepared_at_unix_s == 0 1358 || value.alt.trim().is_empty() 1359 || value.alt.len() > 1_024 1360 { 1361 return Err(TeraAppError::invalid_argument("invalid_media_reference")); 1362 } 1363 let bytes = value.file.read(value.byte_size)?; 1364 let media_type = MediaType::parse(&value.media_type) 1365 .map_err(|_| TeraAppError::invalid_argument("invalid_media_type"))?; 1366 let sha256 = Sha256::from_hex(&value.sha256) 1367 .map_err(|_| TeraAppError::invalid_argument("invalid_media_digest"))?; 1368 if Sha256::digest(&bytes) != sha256 { 1369 return Err(TeraAppError::invalid_argument("media_verification_failed")); 1370 } 1371 let dimensions = 1372 radroots_sdk::transport::BlossomImageDimensions::new(value.width, value.height) 1373 .map_err(|_| TeraAppError::invalid_argument("invalid_image_dimensions"))?; 1374 let verified_at_unix_ms = value 1375 .prepared_at_unix_s 1376 .checked_mul(1_000) 1377 .ok_or_else(|| TeraAppError::invalid_argument("invalid_media_reference"))?; 1378 radroots_sdk::transport::BlossomUploadRequest::new( 1379 bytes.clone().into(), 1380 media_type.clone(), 1381 dimensions, 1382 verified_at_unix_ms, 1383 ) 1384 .map_err(|_| TeraAppError::invalid_argument("media_verification_failed"))?; 1385 Ok(Self { 1386 opaque_reference: value.opaque_reference, 1387 sha256, 1388 byte_size: value.byte_size, 1389 prepared_at_unix_s: value.prepared_at_unix_s, 1390 bytes: bytes.into(), 1391 media_type, 1392 width: value.width, 1393 height: value.height, 1394 alt: value.alt, 1395 }) 1396 } 1397 } 1398 1399 impl PreparedMedia { 1400 pub(crate) fn into_recovery_media( 1401 self, 1402 ) -> Result<tera_core::runtime::product_surface::recovery_completion::RecoveryMedia, TeraAppError> 1403 { 1404 tera_core::runtime::product_surface::recovery_completion::RecoveryMedia::new( 1405 self.opaque_reference, 1406 self.bytes, 1407 self.media_type, 1408 self.width, 1409 self.height, 1410 ) 1411 .map_err(Into::into) 1412 } 1413 1414 pub(crate) fn into_submission_bytes(self) -> std::sync::Arc<[u8]> { 1415 self.bytes 1416 } 1417 1418 pub(crate) fn into_submission_media( 1419 self, 1420 request: tera_core::runtime::product_surface::SubmissionReservationRequest, 1421 expected_revision: u64, 1422 ) -> Result<tera_core::runtime::product_surface::SubmissionMediaRequest, TeraAppError> { 1423 tera_core::runtime::product_surface::SubmissionMediaRequest::new( 1424 request, 1425 expected_revision, 1426 self.opaque_reference, 1427 self.bytes, 1428 ) 1429 .map_err(Into::into) 1430 } 1431 1432 pub(crate) fn into_authored_image( 1433 self, 1434 blossom: &radroots_sdk::transport::BlossomSlot, 1435 ) -> Result<AuthoredImage, TeraAppError> { 1436 self.bind(blossom)?.authored_image() 1437 } 1438 1439 pub(crate) fn into_upload_intent( 1440 self, 1441 draft_id: [u8; 16], 1442 expected_revision: u64, 1443 ) -> Result<Phase1UploadIntent, TeraAppError> { 1444 Phase1UploadIntent::new( 1445 draft_id, 1446 expected_revision, 1447 self.bytes, 1448 self.media_type, 1449 self.width, 1450 self.height, 1451 ) 1452 .map_err(|_| TeraAppError::invalid_argument("invalid_blossom_upload")) 1453 } 1454 1455 pub(crate) fn upload_request( 1456 &self, 1457 verified_at_unix_ms: u64, 1458 ) -> Result<radroots_sdk::transport::BlossomUploadRequest, TeraAppError> { 1459 let dimensions = 1460 radroots_sdk::transport::BlossomImageDimensions::new(self.width, self.height) 1461 .map_err(|_| TeraAppError::invalid_argument("invalid_image_dimensions"))?; 1462 radroots_sdk::transport::BlossomUploadRequest::new( 1463 std::sync::Arc::clone(&self.bytes), 1464 self.media_type.clone(), 1465 dimensions, 1466 verified_at_unix_ms, 1467 ) 1468 .map_err(|_| TeraAppError::invalid_argument("invalid_blossom_upload")) 1469 } 1470 1471 fn bind( 1472 self, 1473 blossom: &radroots_sdk::transport::BlossomSlot, 1474 ) -> Result<BoundPreparedMedia, TeraAppError> { 1475 let verified_at_unix_ms = self 1476 .prepared_at_unix_s 1477 .checked_mul(1_000) 1478 .ok_or_else(|| TeraAppError::invalid_argument("invalid_media_reference"))?; 1479 let transaction = blossom 1480 .prepare_upload(self.upload_request(verified_at_unix_ms)?) 1481 .map_err(|error| TeraAppError::invalid_argument(error.code()))?; 1482 let descriptor = BlobDescriptor::new( 1483 transaction.expected_url().clone(), 1484 self.sha256, 1485 self.byte_size, 1486 self.media_type.clone(), 1487 self.prepared_at_unix_s, 1488 ) 1489 .and_then(BlobDescriptor::approve_reference) 1490 .and_then(|descriptor| descriptor.verify_bytes(&self.bytes, &self.media_type)) 1491 .map_err(|_| TeraAppError::invalid_argument("media_verification_failed"))?; 1492 Ok(BoundPreparedMedia { 1493 media: self, 1494 descriptor, 1495 }) 1496 } 1497 } 1498 1499 impl BoundPreparedMedia { 1500 fn authored_image(&self) -> Result<AuthoredImage, TeraAppError> { 1501 AuthoredImage::try_from_verified_descriptor(self.descriptor.clone()) 1502 .map_err(|_| TeraAppError::invalid_argument("invalid_image_media")) 1503 } 1504 1505 fn post_image(&self) -> Result<AuthoredPostImage, TeraAppError> { 1506 AuthoredPostImage::new( 1507 self.authored_image()?, 1508 PostImageDimensions::new(self.media.width, self.media.height) 1509 .map_err(|_| TeraAppError::invalid_argument("invalid_image_dimensions"))?, 1510 self.media.alt.clone(), 1511 ) 1512 .map_err(|_| TeraAppError::invalid_argument("invalid_image")) 1513 } 1514 } 1515 1516 fn event_command( 1517 input: &FfiAddDraftInput, 1518 image: Option<&BoundPreparedMedia>, 1519 ) -> Result<CreateEvent, TeraAppError> { 1520 if input.media.len() > 1 { 1521 return Err(TeraAppError::invalid_argument("event_image_limit")); 1522 } 1523 let identifier = required(input.identifier.as_deref(), "event_identifier_required")?; 1524 let title = required(input.title.as_deref(), "event_title_required")?; 1525 let timing = input 1526 .event_timing 1527 .ok_or_else(|| TeraAppError::invalid_argument("event_timing_required"))?; 1528 match timing { 1529 FfiEventTimingKind::AllDay => { 1530 let start = CalendarDate::parse(required( 1531 input.event_start_date.as_deref(), 1532 "event_start_date_required", 1533 )?) 1534 .map_err(|_| TeraAppError::invalid_argument("invalid_event_start_date"))?; 1535 let mut event = AuthoredCalendarDateEvent::new(identifier, title, start) 1536 .map_err(|_| TeraAppError::invalid_argument("invalid_event"))?; 1537 if let Some(end) = input.event_end_date.as_deref() { 1538 event = 1539 event 1540 .with_end(CalendarDate::parse(end).map_err(|_| { 1541 TeraAppError::invalid_argument("invalid_event_end_date") 1542 })?) 1543 .map_err(|_| TeraAppError::invalid_argument("invalid_event_range"))?; 1544 } 1545 if !input.content.is_empty() { 1546 event = event 1547 .with_description(input.content.clone()) 1548 .map_err(|_| TeraAppError::invalid_argument("invalid_event_description"))?; 1549 } 1550 if let Some(location) = input.location.clone() { 1551 event = event 1552 .with_locations(vec![location]) 1553 .map_err(|_| TeraAppError::invalid_argument("invalid_event_location"))?; 1554 } 1555 if let Some(image) = image { 1556 event = event 1557 .with_image(image.authored_image()?) 1558 .map_err(|_| TeraAppError::invalid_argument("invalid_event_image"))?; 1559 } 1560 Ok(CreateEvent::date(event)) 1561 } 1562 FfiEventTimingKind::Timed => { 1563 let start = input 1564 .event_start_unix_s 1565 .filter(|value| *value != 0) 1566 .ok_or_else(|| TeraAppError::invalid_argument("event_start_required"))?; 1567 let mut event = AuthoredCalendarTimeEvent::new(identifier, title, start) 1568 .map_err(|_| TeraAppError::invalid_argument("invalid_event"))?; 1569 if let Some(end) = input.event_end_unix_s { 1570 event = event 1571 .with_end(end) 1572 .map_err(|_| TeraAppError::invalid_argument("invalid_event_range"))?; 1573 } 1574 if let Some(timezone) = input.event_timezone.as_deref() { 1575 event = event 1576 .with_start_tzid(timezone) 1577 .map_err(|_| TeraAppError::invalid_argument("invalid_event_timezone"))?; 1578 } 1579 if !input.content.is_empty() { 1580 event = event 1581 .with_description(input.content.clone()) 1582 .map_err(|_| TeraAppError::invalid_argument("invalid_event_description"))?; 1583 } 1584 if let Some(location) = input.location.clone() { 1585 event = event 1586 .with_locations(vec![location]) 1587 .map_err(|_| TeraAppError::invalid_argument("invalid_event_location"))?; 1588 } 1589 if let Some(image) = image { 1590 event = event 1591 .with_image(image.authored_image()?) 1592 .map_err(|_| TeraAppError::invalid_argument("invalid_event_image"))?; 1593 } 1594 Ok(CreateEvent::time(event)) 1595 } 1596 } 1597 } 1598 1599 fn food_command( 1600 input: FfiAddDraftInput, 1601 authored_at_unix_s: u64, 1602 media: &[BoundPreparedMedia], 1603 ) -> Result<CreateFoodAvailability, TeraAppError> { 1604 let unit = FoodUnit::parse(required(input.unit.as_deref(), "food_unit_required")?) 1605 .map_err(|_| TeraAppError::invalid_argument("invalid_food_unit"))?; 1606 let images = media 1607 .iter() 1608 .map(|image| { 1609 Ok(FoodAvailabilityImage::new( 1610 image.authored_image()?, 1611 FoodImageDimensions::new(image.media.width, image.media.height) 1612 .map_err(|_| TeraAppError::invalid_argument("invalid_image_dimensions"))?, 1613 )) 1614 }) 1615 .collect::<Result<Vec<_>, TeraAppError>>()?; 1616 let status = input.food_status.as_deref().unwrap_or("active"); 1617 let details = FoodAvailabilityDetails::new(FoodAvailabilityDetailsParts { 1618 content: FoodContent::new(input.content) 1619 .map_err(|_| TeraAppError::invalid_argument("invalid_food_content"))?, 1620 identifier: FoodIdentifier::parse(required( 1621 input.identifier.as_deref(), 1622 "food_identifier_required", 1623 )?) 1624 .map_err(|_| TeraAppError::invalid_argument("invalid_food_identifier"))?, 1625 title: FoodText::new(required(input.title, "food_title_required")?) 1626 .map_err(|_| TeraAppError::invalid_argument("invalid_food_title"))?, 1627 summary: FoodText::new(required(input.summary, "food_summary_required")?) 1628 .map_err(|_| TeraAppError::invalid_argument("invalid_food_summary"))?, 1629 published_at: FoodPublishedAt::new( 1630 input.food_published_at_unix_s.unwrap_or(authored_at_unix_s), 1631 ) 1632 .map_err(|_| TeraAppError::invalid_argument("invalid_food_published_at"))?, 1633 location: FoodText::new(required(input.location, "food_location_required")?) 1634 .map_err(|_| TeraAppError::invalid_argument("invalid_food_location"))?, 1635 price: FoodPrice::new( 1636 required(input.price_amount, "food_price_required")?, 1637 FoodCurrency::parse(required(input.currency, "food_currency_required")?) 1638 .map_err(|_| TeraAppError::invalid_argument("invalid_food_currency"))?, 1639 unit, 1640 ) 1641 .map_err(|_| TeraAppError::invalid_argument("invalid_food_price"))?, 1642 quantity: input 1643 .quantity 1644 .map(|quantity| FoodQuantity::new(quantity, unit)) 1645 .transpose() 1646 .map_err(|_| TeraAppError::invalid_argument("invalid_food_quantity"))?, 1647 status: FoodAvailabilityStatus::parse(status) 1648 .map_err(|_| TeraAppError::invalid_argument("invalid_food_status"))?, 1649 images, 1650 }) 1651 .map_err(|_| TeraAppError::invalid_argument("invalid_food_availability"))?; 1652 Ok(CreateFoodAvailability::new(details)) 1653 } 1654 1655 fn reject_media(media: &[BoundPreparedMedia]) -> Result<(), TeraAppError> { 1656 if media.is_empty() { 1657 Ok(()) 1658 } else { 1659 Err(TeraAppError::invalid_argument("media_not_allowed")) 1660 } 1661 } 1662 1663 fn content_with_media_references( 1664 mut content: String, 1665 media: &[BoundPreparedMedia], 1666 ) -> Result<String, TeraAppError> { 1667 if content.trim().is_empty() { 1668 return Err(TeraAppError::invalid_argument("content_required")); 1669 } 1670 for item in media { 1671 let url = item.descriptor.url().as_str(); 1672 match content.match_indices(url).count() { 1673 0 => { 1674 if !content.ends_with('\n') { 1675 content.push('\n'); 1676 } 1677 content.push_str(url); 1678 } 1679 1 => {} 1680 _ => { 1681 return Err(TeraAppError::invalid_argument("duplicate_media_reference")); 1682 } 1683 } 1684 } 1685 Ok(content) 1686 } 1687 1688 fn required<T>(value: Option<T>, code: &'static str) -> Result<T, TeraAppError> { 1689 value.ok_or_else(|| TeraAppError::invalid_argument(code)) 1690 } 1691 1692 fn opaque_media_reference_is_valid(value: &str) -> bool { 1693 value.len() > "media:".len() 1694 && value.len() <= MEDIA_REFERENCE_MAX_BYTES 1695 && value.starts_with("media:") 1696 && value["media:".len()..].bytes().all(|byte| { 1697 byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'-' | b'_') 1698 }) 1699 } 1700 1701 #[derive(Clone, Copy, Debug, Eq, PartialEq, uniffi::Enum)] 1702 pub enum FfiMediaStage { 1703 Pending, 1704 Preparing, 1705 Uploading, 1706 Verified, 1707 Failed, 1708 Orphaned, 1709 } 1710 1711 #[cfg_attr(coverage_nightly, coverage(off))] 1712 impl From<Phase1MediaStage> for FfiMediaStage { 1713 fn from(value: Phase1MediaStage) -> Self { 1714 match value { 1715 Phase1MediaStage::Pending => Self::Pending, 1716 Phase1MediaStage::Preparing => Self::Preparing, 1717 Phase1MediaStage::Uploading => Self::Uploading, 1718 Phase1MediaStage::Verified => Self::Verified, 1719 Phase1MediaStage::Failed => Self::Failed, 1720 Phase1MediaStage::Orphaned => Self::Orphaned, 1721 } 1722 } 1723 } 1724 1725 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 1726 pub struct FfiDraftMediaRecord { 1727 pub schema_version: u16, 1728 pub url: String, 1729 pub upload_url: Option<String>, 1730 pub stage: FfiMediaStage, 1731 pub upload_attempts: u8, 1732 pub verified_at_unix_ms: Option<u64>, 1733 pub possible_orphan: bool, 1734 pub orphan_reason_code: Option<String>, 1735 pub orphan_recorded_at_unix_ms: Option<u64>, 1736 } 1737 1738 #[cfg_attr(coverage_nightly, coverage(off))] 1739 impl From<&Phase1MediaPrerequisite> for FfiDraftMediaRecord { 1740 fn from(value: &Phase1MediaPrerequisite) -> Self { 1741 let orphan = value.orphan(); 1742 Self { 1743 schema_version: UPLOAD_OUTPUT_FFI_SCHEMA_VERSION, 1744 url: value.url().to_owned(), 1745 upload_url: radroots_blossom::BlobUrl::parse(value.url()) 1746 .ok() 1747 .map(|url| url.upload_url()), 1748 stage: value.stage().into(), 1749 upload_attempts: value.upload_attempts(), 1750 verified_at_unix_ms: value.verified_at_unix_ms(), 1751 possible_orphan: orphan.is_some(), 1752 orphan_reason_code: orphan.map(|value| value.reason_code().to_owned()), 1753 orphan_recorded_at_unix_ms: orphan.map(|value| value.recorded_at_unix_ms()), 1754 } 1755 } 1756 } 1757 1758 #[derive(Clone, Copy, Debug, Eq, PartialEq, uniffi::Enum)] 1759 pub enum FfiOutboxState { 1760 Draft, 1761 MediaPreparing, 1762 MediaUploading, 1763 ReadyToSign, 1764 Signing, 1765 Signed, 1766 Queued, 1767 Delivering, 1768 PartiallyDelivered, 1769 Retryable, 1770 Terminal, 1771 Cancelled, 1772 Complete, 1773 } 1774 1775 #[derive(Clone, Copy, Debug, Eq, PartialEq, uniffi::Enum)] 1776 pub enum FfiDraftKind { 1777 Add, 1778 Retraction, 1779 } 1780 1781 #[cfg_attr(coverage_nightly, coverage(off))] 1782 impl From<Phase1DraftKind> for FfiDraftKind { 1783 fn from(value: Phase1DraftKind) -> Self { 1784 match value { 1785 Phase1DraftKind::Add => Self::Add, 1786 Phase1DraftKind::Retraction => Self::Retraction, 1787 } 1788 } 1789 } 1790 1791 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 1792 pub struct FfiDraftFormMediaRecord { 1793 pub schema_version: u16, 1794 pub opaque_reference: String, 1795 pub url: String, 1796 pub sha256: String, 1797 pub media_type: String, 1798 pub byte_size: u64, 1799 pub width: u32, 1800 pub height: u32, 1801 pub alt: String, 1802 pub prepared_at_unix_s: u64, 1803 } 1804 1805 #[cfg_attr(coverage_nightly, coverage(off))] 1806 impl From<&Phase1DraftMediaSnapshot> for FfiDraftFormMediaRecord { 1807 fn from(value: &Phase1DraftMediaSnapshot) -> Self { 1808 Self { 1809 schema_version: MOBILE_FFI_SCHEMA_VERSION, 1810 opaque_reference: value.opaque_reference.clone(), 1811 url: value.url.clone(), 1812 sha256: value.sha256.clone(), 1813 media_type: value.media_type.clone(), 1814 byte_size: value.byte_size, 1815 width: value.width, 1816 height: value.height, 1817 alt: value.alt.clone(), 1818 prepared_at_unix_s: value.prepared_at_unix_s, 1819 } 1820 } 1821 } 1822 1823 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 1824 pub struct FfiDraftFormRecord { 1825 pub schema_version: u16, 1826 pub command_type: FfiAddCommandType, 1827 pub content: String, 1828 pub identifier: Option<String>, 1829 pub title: Option<String>, 1830 pub summary: Option<String>, 1831 pub location: Option<String>, 1832 pub event_timing: Option<FfiEventTimingKind>, 1833 pub event_start_date: Option<String>, 1834 pub event_end_date: Option<String>, 1835 pub event_start_unix_s: Option<u64>, 1836 pub event_end_unix_s: Option<u64>, 1837 pub event_timezone: Option<String>, 1838 pub price_amount: Option<String>, 1839 pub currency: Option<String>, 1840 pub unit: Option<String>, 1841 pub quantity: Option<String>, 1842 pub food_published_at_unix_s: Option<u64>, 1843 pub food_status: Option<String>, 1844 pub media: Vec<FfiDraftFormMediaRecord>, 1845 } 1846 1847 #[cfg_attr(coverage_nightly, coverage(off))] 1848 impl From<&Phase1DraftFormSnapshot> for FfiDraftFormRecord { 1849 fn from(value: &Phase1DraftFormSnapshot) -> Self { 1850 Self { 1851 schema_version: MOBILE_FFI_SCHEMA_VERSION, 1852 command_type: value.command_type.into(), 1853 content: value.content.clone(), 1854 identifier: value.identifier.clone(), 1855 title: value.title.clone(), 1856 summary: value.summary.clone(), 1857 location: value.location.clone(), 1858 event_timing: value.event_timing.map(|value| match value { 1859 Phase1DraftEventTiming::AllDay => FfiEventTimingKind::AllDay, 1860 Phase1DraftEventTiming::Timed => FfiEventTimingKind::Timed, 1861 }), 1862 event_start_date: value.event_start_date.clone(), 1863 event_end_date: value.event_end_date.clone(), 1864 event_start_unix_s: value.event_start_unix_s, 1865 event_end_unix_s: value.event_end_unix_s, 1866 event_timezone: value.event_timezone.clone(), 1867 price_amount: value.price_amount.clone(), 1868 currency: value.currency.clone(), 1869 unit: value.unit.clone(), 1870 quantity: value.quantity.clone(), 1871 food_published_at_unix_s: value.food_published_at_unix_s, 1872 food_status: value.food_status.clone(), 1873 media: value.media.iter().map(Into::into).collect(), 1874 } 1875 } 1876 } 1877 1878 #[cfg_attr(coverage_nightly, coverage(off))] 1879 impl From<Phase1OutboxState> for FfiOutboxState { 1880 fn from(value: Phase1OutboxState) -> Self { 1881 match value { 1882 Phase1OutboxState::Draft => Self::Draft, 1883 Phase1OutboxState::MediaPreparing => Self::MediaPreparing, 1884 Phase1OutboxState::MediaUploading => Self::MediaUploading, 1885 Phase1OutboxState::ReadyToSign => Self::ReadyToSign, 1886 Phase1OutboxState::Signing => Self::Signing, 1887 Phase1OutboxState::Signed => Self::Signed, 1888 Phase1OutboxState::Queued => Self::Queued, 1889 Phase1OutboxState::Delivering => Self::Delivering, 1890 Phase1OutboxState::PartiallyDelivered => Self::PartiallyDelivered, 1891 Phase1OutboxState::Retryable => Self::Retryable, 1892 Phase1OutboxState::Terminal => Self::Terminal, 1893 Phase1OutboxState::Cancelled => Self::Cancelled, 1894 Phase1OutboxState::Complete => Self::Complete, 1895 } 1896 } 1897 } 1898 1899 #[derive(Clone, Copy, Debug, Eq, PartialEq, uniffi::Record)] 1900 pub struct FfiOperationSettlementRecord { 1901 pub schema_version: u16, 1902 pub artifacts: u16, 1903 pub signed: u16, 1904 pub admitted: u16, 1905 pub pending: u16, 1906 pub retryable: u16, 1907 pub indeterminate: u16, 1908 pub failed_terminal: u16, 1909 pub cancelled: u16, 1910 pub delivery_plans: u16, 1911 pub delivery_satisfied: u16, 1912 pub delivery_pending: u16, 1913 pub delivery_retryable: u16, 1914 pub delivery_exhausted: u16, 1915 pub delivery_failed_terminal: u16, 1916 pub delivery_cancelled: u16, 1917 } 1918 1919 #[cfg_attr(coverage_nightly, coverage(off))] 1920 impl From<radroots_storage::authored::OperationSettlement> for FfiOperationSettlementRecord { 1921 fn from(value: radroots_storage::authored::OperationSettlement) -> Self { 1922 Self { 1923 schema_version: MOBILE_FFI_SCHEMA_VERSION, 1924 artifacts: value.artifacts(), 1925 signed: value.signed(), 1926 admitted: value.admitted(), 1927 pending: value.pending(), 1928 retryable: value.retryable(), 1929 indeterminate: value.indeterminate(), 1930 failed_terminal: value.failed_terminal(), 1931 cancelled: value.cancelled(), 1932 delivery_plans: value.delivery_plans(), 1933 delivery_satisfied: value.delivery_satisfied(), 1934 delivery_pending: value.delivery_pending(), 1935 delivery_retryable: value.delivery_retryable(), 1936 delivery_exhausted: value.delivery_exhausted(), 1937 delivery_failed_terminal: value.delivery_failed_terminal(), 1938 delivery_cancelled: value.delivery_cancelled(), 1939 } 1940 } 1941 } 1942 1943 #[derive(Clone, Copy, Debug, Eq, PartialEq, uniffi::Enum)] 1944 pub enum FfiRelaySatisfaction { 1945 AnyAccepted, 1946 AllAccepted, 1947 AnyDelivered, 1948 AllDelivered, 1949 } 1950 1951 #[derive(Clone, Copy, Debug, Eq, PartialEq, uniffi::Enum)] 1952 pub enum FfiCancellationPolicy { 1953 PreservePublishedRequest, 1954 LocalCooperative, 1955 } 1956 1957 impl FfiCancellationPolicy { 1958 pub(crate) const fn core(self) -> Phase1CancellationPolicy { 1959 match self { 1960 Self::PreservePublishedRequest => Phase1CancellationPolicy::PreservePublishedRequest, 1961 Self::LocalCooperative => Phase1CancellationPolicy::LocalCooperative, 1962 } 1963 } 1964 } 1965 1966 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 1967 pub struct FfiQueuePolicyRecord { 1968 pub schema_version: u16, 1969 pub relay_urls: Vec<String>, 1970 pub satisfaction: FfiRelaySatisfaction, 1971 pub delivery_deadline_unix_ms: u64, 1972 pub cancellation: FfiCancellationPolicy, 1973 } 1974 1975 impl TryFrom<FfiQueuePolicyRecord> for Phase1QueuePolicy { 1976 type Error = TeraAppError; 1977 1978 fn try_from(value: FfiQueuePolicyRecord) -> Result<Self, Self::Error> { 1979 require_schema(value.schema_version)?; 1980 Phase1QueuePolicy::new( 1981 value.relay_urls, 1982 match value.satisfaction { 1983 FfiRelaySatisfaction::AnyAccepted => Phase1RelaySatisfaction::AnyAccepted, 1984 FfiRelaySatisfaction::AllAccepted => Phase1RelaySatisfaction::AllAccepted, 1985 FfiRelaySatisfaction::AnyDelivered => Phase1RelaySatisfaction::AnyDelivered, 1986 FfiRelaySatisfaction::AllDelivered => Phase1RelaySatisfaction::AllDelivered, 1987 }, 1988 value.delivery_deadline_unix_ms, 1989 match value.cancellation { 1990 FfiCancellationPolicy::PreservePublishedRequest => { 1991 Phase1CancellationPolicy::PreservePublishedRequest 1992 } 1993 FfiCancellationPolicy::LocalCooperative => { 1994 Phase1CancellationPolicy::LocalCooperative 1995 } 1996 }, 1997 ) 1998 .map_err(|_| TeraAppError::invalid_argument("invalid_queue_policy")) 1999 } 2000 } 2001 2002 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 2003 pub struct FfiCapabilityRecord { 2004 pub schema_version: u16, 2005 pub id: String, 2006 pub compiled: bool, 2007 pub configured: bool, 2008 pub availability: String, 2009 pub maturity: String, 2010 } 2011 2012 #[cfg_attr(coverage_nightly, coverage(off))] 2013 impl From<SdkCapabilityRecord> for FfiCapabilityRecord { 2014 fn from(value: SdkCapabilityRecord) -> Self { 2015 Self { 2016 schema_version: MOBILE_FFI_SCHEMA_VERSION, 2017 id: value.id, 2018 compiled: value.compiled, 2019 configured: value.configured, 2020 availability: value.availability, 2021 maturity: value.maturity, 2022 } 2023 } 2024 } 2025 2026 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 2027 pub struct FfiStorageStatusRecord { 2028 pub schema_version: u16, 2029 pub backend: String, 2030 pub open_mode: String, 2031 pub shutdown: String, 2032 pub integrity: String, 2033 } 2034 2035 #[cfg_attr(coverage_nightly, coverage(off))] 2036 impl From<SdkStorageStatusRecord> for FfiStorageStatusRecord { 2037 fn from(value: SdkStorageStatusRecord) -> Self { 2038 Self { 2039 schema_version: MOBILE_FFI_SCHEMA_VERSION, 2040 backend: value.backend, 2041 open_mode: value.open_mode, 2042 shutdown: value.shutdown, 2043 integrity: value.integrity, 2044 } 2045 } 2046 } 2047 2048 #[derive(Clone, Copy, Debug, Eq, PartialEq, uniffi::Enum)] 2049 pub enum FfiRelayAccessRecord { 2050 ReadOnly, 2051 ReadWrite, 2052 } 2053 2054 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 2055 pub struct FfiRelayStatusRecord { 2056 pub schema_version: u16, 2057 pub relay_url: String, 2058 pub access: FfiRelayAccessRecord, 2059 pub read_state: String, 2060 pub write_state: String, 2061 pub read_last_attempt_unix_ms: Option<u64>, 2062 pub write_last_attempt_unix_ms: Option<u64>, 2063 pub read_next_attempt_unix_ms: Option<u64>, 2064 pub write_next_attempt_unix_ms: Option<u64>, 2065 } 2066 2067 #[cfg_attr(coverage_nightly, coverage(off))] 2068 impl From<SdkRelayStatusRecord> for FfiRelayStatusRecord { 2069 fn from(value: SdkRelayStatusRecord) -> Self { 2070 Self { 2071 schema_version: MOBILE_FFI_SCHEMA_VERSION, 2072 relay_url: value.relay_url, 2073 access: match value.access { 2074 SdkRelayAccessRecord::ReadOnly => FfiRelayAccessRecord::ReadOnly, 2075 SdkRelayAccessRecord::ReadWrite => FfiRelayAccessRecord::ReadWrite, 2076 }, 2077 read_state: value.read_state, 2078 write_state: value.write_state, 2079 read_last_attempt_unix_ms: value.read_last_attempt_unix_ms, 2080 write_last_attempt_unix_ms: value.write_last_attempt_unix_ms, 2081 read_next_attempt_unix_ms: value.read_next_attempt_unix_ms, 2082 write_next_attempt_unix_ms: value.write_next_attempt_unix_ms, 2083 } 2084 } 2085 } 2086 2087 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 2088 pub struct FfiRelayStatusReportRecord { 2089 pub schema_version: u16, 2090 pub profile: String, 2091 pub state: String, 2092 pub read_availability: String, 2093 pub write_availability: String, 2094 pub relays: Vec<FfiRelayStatusRecord>, 2095 } 2096 2097 #[derive(Clone, Copy, Debug, Eq, PartialEq, uniffi::Enum)] 2098 pub enum FfiBlossomHostKind { 2099 Native, 2100 Simulator, 2101 PhysicalDevice, 2102 } 2103 2104 impl From<FfiBlossomHostKind> for radroots_sdk::transport::BlossomHostKind { 2105 fn from(value: FfiBlossomHostKind) -> Self { 2106 match value { 2107 FfiBlossomHostKind::Native => Self::Native, 2108 FfiBlossomHostKind::Simulator => Self::Simulator, 2109 FfiBlossomHostKind::PhysicalDevice => Self::PhysicalDevice, 2110 } 2111 } 2112 } 2113 2114 #[derive(Clone, Copy, Debug, Eq, PartialEq, uniffi::Enum)] 2115 pub enum FfiBlossomEndpointAuthority { 2116 PublicWebPki, 2117 LoopbackDevelopment, 2118 PrivateNetworkDevelopment, 2119 } 2120 2121 impl From<FfiBlossomEndpointAuthority> for radroots_sdk::transport::BlossomEndpointAuthority { 2122 fn from(value: FfiBlossomEndpointAuthority) -> Self { 2123 match value { 2124 FfiBlossomEndpointAuthority::PublicWebPki => Self::PublicWebPki, 2125 FfiBlossomEndpointAuthority::LoopbackDevelopment => Self::LoopbackDevelopment, 2126 FfiBlossomEndpointAuthority::PrivateNetworkDevelopment => { 2127 Self::PrivateNetworkDevelopment 2128 } 2129 } 2130 } 2131 } 2132 2133 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 2134 pub struct FfiBlossomConfigurationRecord { 2135 pub schema_version: u16, 2136 pub host_kind: String, 2137 pub endpoint_authority: String, 2138 pub primary_origin: String, 2139 pub fallback_origins: Vec<String>, 2140 pub config_fingerprint: String, 2141 } 2142 2143 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 2144 pub struct FfiBlossomEvidenceRecord { 2145 pub schema_version: u16, 2146 pub origin: String, 2147 pub config_fingerprint: String, 2148 pub state: String, 2149 pub last_successful_state: String, 2150 pub transport_security: String, 2151 pub observed_at_unix_ms: Option<u64>, 2152 pub http_status: Option<u16>, 2153 pub error_code: Option<String>, 2154 pub server_error_code: Option<String>, 2155 pub error_phase: Option<String>, 2156 pub retryable: bool, 2157 pub possible_orphan: bool, 2158 pub attempts: u8, 2159 } 2160 2161 #[cfg_attr(coverage_nightly, coverage(off))] 2162 impl From<SdkBlossomConfigurationRecord> for FfiBlossomConfigurationRecord { 2163 fn from(value: SdkBlossomConfigurationRecord) -> Self { 2164 Self { 2165 schema_version: MOBILE_FFI_SCHEMA_VERSION, 2166 host_kind: value.host_kind, 2167 endpoint_authority: value.endpoint_authority, 2168 primary_origin: value.primary_origin, 2169 fallback_origins: value.fallback_origins, 2170 config_fingerprint: value.config_fingerprint, 2171 } 2172 } 2173 } 2174 2175 #[cfg_attr(coverage_nightly, coverage(off))] 2176 impl From<SdkBlossomEvidenceRecord> for FfiBlossomEvidenceRecord { 2177 fn from(value: SdkBlossomEvidenceRecord) -> Self { 2178 Self { 2179 schema_version: value.schema_version, 2180 origin: value.origin, 2181 config_fingerprint: value.config_fingerprint, 2182 state: value.state, 2183 last_successful_state: value.last_successful_state, 2184 transport_security: value.transport_security, 2185 observed_at_unix_ms: value.observed_at_unix_ms, 2186 http_status: value.http_status, 2187 error_code: value.error_code, 2188 server_error_code: value.server_error_code, 2189 error_phase: value.error_phase, 2190 retryable: value.retryable, 2191 possible_orphan: value.possible_orphan, 2192 attempts: value.attempts, 2193 } 2194 } 2195 } 2196 2197 #[cfg_attr(coverage_nightly, coverage(off))] 2198 impl From<SdkRelayStatusReportRecord> for FfiRelayStatusReportRecord { 2199 fn from(value: SdkRelayStatusReportRecord) -> Self { 2200 Self { 2201 schema_version: MOBILE_FFI_SCHEMA_VERSION, 2202 profile: value.profile, 2203 state: value.state, 2204 read_availability: value.read_availability, 2205 write_availability: value.write_availability, 2206 relays: value.relays.into_iter().map(Into::into).collect(), 2207 } 2208 } 2209 } 2210 2211 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] 2212 pub struct FfiShutdownRecord { 2213 pub schema_version: u16, 2214 pub state: String, 2215 pub already_closed: bool, 2216 } 2217 2218 #[cfg_attr(coverage_nightly, coverage(off))] 2219 impl From<SdkShutdownRecord> for FfiShutdownRecord { 2220 fn from(value: SdkShutdownRecord) -> Self { 2221 Self { 2222 schema_version: MOBILE_FFI_SCHEMA_VERSION, 2223 state: value.state, 2224 already_closed: value.already_closed, 2225 } 2226 } 2227 } 2228 2229 pub(crate) fn decode_id(value: &str, code: &'static str) -> Result<[u8; 16], TeraAppError> { 2230 if value.len() != 32 { 2231 return Err(TeraAppError::invalid_argument(code)); 2232 } 2233 let bytes = hex::decode(value).map_err(|_| TeraAppError::invalid_argument(code))?; 2234 bytes 2235 .try_into() 2236 .map_err(|_| TeraAppError::invalid_argument(code)) 2237 } 2238 2239 fn require_schema(schema_version: u16) -> Result<(), TeraAppError> { 2240 if schema_version == MOBILE_FFI_SCHEMA_VERSION { 2241 Ok(()) 2242 } else { 2243 Err(TeraAppError::invalid_argument("unsupported_schema_version")) 2244 } 2245 } 2246 2247 #[cfg(test)] 2248 mod tests { 2249 use core::num::NonZeroU64; 2250 use std::io::Write; 2251 use std::os::fd::AsRawFd; 2252 2253 use radroots_event::id::TradeId; 2254 2255 use super::*; 2256 2257 fn rhi_attestation_fixture() -> serde_json::Value { 2258 let fixture: serde_json::Value = serde_json::from_str(include_str!( 2259 "../../../test-fixtures/tera_ffi/authored_operations.v1.json" 2260 )) 2261 .expect("authored corpus"); 2262 fixture["vectors"] 2263 .as_array() 2264 .expect("operations") 2265 .iter() 2266 .find(|entry| entry["id"] == "typed_rhi_evidence_attestation_017") 2267 .expect("RHI operation") 2268 .get("expected") 2269 .expect("expected") 2270 .clone() 2271 } 2272 2273 #[test] 2274 fn evidence_report_plan_and_verified_event_use_final_mobile_vocabulary() { 2275 let expected = rhi_attestation_fixture(); 2276 let content = expected["content"].as_str().expect("content").to_owned(); 2277 let report = parse_rhi_evidence_report(content.clone()).expect("report"); 2278 assert_eq!(report.outcome, FfiTradeEvidenceOutcome::Indeterminate); 2279 assert_eq!(report.trade_generation, "7"); 2280 assert_eq!(report.observed_at_unix_s, "1800000000"); 2281 2282 let plan = prepare_rhi_evidence_attestation(content, 1_784_347_200).expect("plan"); 2283 assert_eq!(plan.kind, 3_441); 2284 assert_eq!(plan.created_at_unix_s, "1784347200"); 2285 assert_eq!( 2286 plan.expected_event_id, 2287 expected["event_id"].as_str().expect("event id") 2288 ); 2289 2290 let raw: serde_json::Value = 2291 serde_json::from_str(expected["raw_json"].as_str().expect("raw event")) 2292 .expect("raw event JSON"); 2293 let signed = FfiSignedEvidenceEventRecord { 2294 id: raw["id"].as_str().expect("id").to_owned(), 2295 author_pubkey: raw["pubkey"].as_str().expect("pubkey").to_owned(), 2296 created_at_unix_s: raw["created_at"].as_u64().expect("created_at"), 2297 kind: u32::try_from(raw["kind"].as_u64().expect("kind")).expect("u32 kind"), 2298 tags: serde_json::from_value(raw["tags"].clone()).expect("tags"), 2299 content: raw["content"].as_str().expect("content").to_owned(), 2300 signature: raw["sig"].as_str().expect("signature").to_owned(), 2301 }; 2302 let attestation = validate_rhi_evidence_attestation(signed).expect("attestation"); 2303 assert_eq!(attestation.outcome, FfiTradeEvidenceOutcome::Indeterminate); 2304 assert_eq!(attestation.trade_generation, "7"); 2305 } 2306 2307 #[test] 2308 fn evidence_manifest_and_supersession_project_the_complete_vocabulary() { 2309 use radroots_sdk::trade::{ 2310 RadrootsTradeEvidenceManifestSourceResultV1, RadrootsTradeEvidenceManifestV1, 2311 RadrootsTradeEvidencePolicyDigestV1, RadrootsTradeEvidenceScopePrerequisitesV1, 2312 RadrootsTradeEvidenceSourceCompletionV1, RadrootsTradeEvidenceSourceIdV1, 2313 RadrootsTradeEvidenceSourceRequirementV1, RadrootsTradeEvidenceSourceResultDigestV1, 2314 RadrootsTradeEvidenceSourceResultV1, 2315 }; 2316 2317 assert_eq!( 2318 FfiTradeEvidenceCoverage::from( 2319 radroots_sdk::trade::RadrootsTradeEvidenceCoverageV1::Missing 2320 ), 2321 FfiTradeEvidenceCoverage::Missing 2322 ); 2323 assert_eq!( 2324 FfiTradeEvidenceCoverage::from( 2325 radroots_sdk::trade::RadrootsTradeEvidenceCoverageV1::Partial 2326 ), 2327 FfiTradeEvidenceCoverage::Partial 2328 ); 2329 assert_eq!( 2330 FfiTradeEvidenceCoverage::from( 2331 radroots_sdk::trade::RadrootsTradeEvidenceCoverageV1::ScopeSatisfied 2332 ), 2333 FfiTradeEvidenceCoverage::ScopeSatisfied 2334 ); 2335 assert_eq!( 2336 FfiTradeEvidenceCoverage::from( 2337 radroots_sdk::trade::RadrootsTradeEvidenceCoverageV1::Unsupported 2338 ), 2339 FfiTradeEvidenceCoverage::Unsupported 2340 ); 2341 assert_eq!( 2342 FfiTradeEvidenceOutcome::from( 2343 radroots_sdk::trade::RadrootsTradeEvidenceOutcomeV1::Valid 2344 ), 2345 FfiTradeEvidenceOutcome::Valid 2346 ); 2347 assert_eq!( 2348 FfiTradeEvidenceOutcome::from( 2349 radroots_sdk::trade::RadrootsTradeEvidenceOutcomeV1::Invalid 2350 ), 2351 FfiTradeEvidenceOutcome::Invalid 2352 ); 2353 assert_eq!( 2354 FfiTradeEvidenceOutcome::from( 2355 radroots_sdk::trade::RadrootsTradeEvidenceOutcomeV1::Indeterminate 2356 ), 2357 FfiTradeEvidenceOutcome::Indeterminate 2358 ); 2359 2360 let source = RadrootsTradeEvidenceManifestSourceResultV1::new( 2361 RadrootsTradeEvidenceSourceIdV1::parse("typed_source").expect("source id"), 2362 RadrootsTradeEvidenceSourceResultV1::new( 2363 RadrootsTradeEvidenceSourceRequirementV1::Required, 2364 RadrootsTradeEvidenceSourceCompletionV1::Complete, 2365 0, 2366 ) 2367 .expect("source result"), 2368 RadrootsTradeEvidenceSourceResultDigestV1::from_bytes([0x33; 32]), 2369 ); 2370 let manifest = RadrootsTradeEvidenceManifestV1::new( 2371 TradeId::from_bytes([0x11; 16]), 2372 NonZeroU64::new(1).expect("nonzero generation"), 2373 RadrootsTradeEvidencePolicyDigestV1::from_bytes([0x22; 32]), 2374 1_800_000_000, 2375 RadrootsTradeEvidenceScopePrerequisitesV1::Satisfied, 2376 [source], 2377 [], 2378 ) 2379 .expect("manifest"); 2380 let projected = parse_trade_evidence_manifest(manifest.canonical_bytes().to_vec()) 2381 .expect("manifest projection"); 2382 assert_eq!(projected.coverage, FfiTradeEvidenceCoverage::ScopeSatisfied); 2383 assert_eq!( 2384 projected.canonical_bytes_hex, 2385 hex::encode(manifest.canonical_bytes()) 2386 ); 2387 2388 let decisions: serde_json::Value = serde_json::from_str(include_str!( 2389 "../../../test-fixtures/tera_ffi/evidence_attestation_decision.v1.json" 2390 )) 2391 .expect("RHI decision corpus"); 2392 let superseding = decisions["vectors"] 2393 .as_array() 2394 .expect("RHI decision vectors") 2395 .iter() 2396 .find(|entry| entry["id"] == "rhi_evidence_attestation_superseding_002") 2397 .expect("superseding vector"); 2398 let report = parse_rhi_evidence_report( 2399 superseding["expected"]["canonical_event_content_utf8"] 2400 .as_str() 2401 .expect("canonical event content") 2402 .to_owned(), 2403 ) 2404 .expect("superseding report"); 2405 assert_eq!(report.outcome, FfiTradeEvidenceOutcome::Valid); 2406 assert_eq!( 2407 report.supersedes_report_id.as_deref(), 2408 Some("7777777777777777777777777777777777777777777777777777777777777777") 2409 ); 2410 assert_eq!( 2411 report.supersedes_event_id.as_deref(), 2412 Some("8888888888888888888888888888888888888888888888888888888888888888") 2413 ); 2414 } 2415 2416 #[test] 2417 fn transport_policy_enums_map_every_closed_variant() { 2418 assert_eq!( 2419 FfiCancellationPolicy::PreservePublishedRequest.core(), 2420 Phase1CancellationPolicy::PreservePublishedRequest 2421 ); 2422 assert_eq!( 2423 FfiCancellationPolicy::LocalCooperative.core(), 2424 Phase1CancellationPolicy::LocalCooperative 2425 ); 2426 assert_eq!( 2427 radroots_sdk::transport::BlossomHostKind::from(FfiBlossomHostKind::Native), 2428 radroots_sdk::transport::BlossomHostKind::Native 2429 ); 2430 assert_eq!( 2431 radroots_sdk::transport::BlossomHostKind::from(FfiBlossomHostKind::Simulator), 2432 radroots_sdk::transport::BlossomHostKind::Simulator 2433 ); 2434 assert_eq!( 2435 radroots_sdk::transport::BlossomHostKind::from(FfiBlossomHostKind::PhysicalDevice), 2436 radroots_sdk::transport::BlossomHostKind::PhysicalDevice 2437 ); 2438 } 2439 2440 #[test] 2441 fn evidence_errors_do_not_render_untrusted_content() { 2442 let secret = "mobile-private-evidence"; 2443 let error = parse_rhi_evidence_report(secret.to_owned()).expect_err("malformed report"); 2444 assert!(!error.to_string().contains(secret)); 2445 assert!(!format!("{error:?}").contains(secret)); 2446 } 2447 2448 fn png(width: u32, height: u32) -> Vec<u8> { 2449 let mut bytes = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec(); 2450 bytes.extend_from_slice(&width.to_be_bytes()); 2451 bytes.extend_from_slice(&height.to_be_bytes()); 2452 bytes 2453 } 2454 2455 fn blossom_slot() -> radroots_sdk::transport::BlossomSlot { 2456 let profile = radroots_sdk::transport::BlossomProfile::new( 2457 radroots_sdk::transport::BlossomHostKind::Simulator, 2458 radroots_sdk::transport::BlossomEndpointAuthority::LoopbackDevelopment, 2459 "http://127.0.0.1:3000", 2460 std::iter::empty::<&str>(), 2461 ) 2462 .unwrap(); 2463 let slot = radroots_sdk::transport::BlossomSlot::new(); 2464 slot.configure(radroots_sdk::transport::BlossomConfig::from_profile( 2465 profile, 2466 )) 2467 .unwrap(); 2468 slot 2469 } 2470 2471 fn photo_input(file_descriptor: u64, bytes: &[u8], digest: String) -> FfiAddDraftInput { 2472 FfiAddDraftInput { 2473 schema_version: MOBILE_FFI_SCHEMA_VERSION, 2474 command_type: FfiAddCommandType::CreatePhotoUpdate, 2475 content: "Fresh carrots from this morning.".to_owned(), 2476 identifier: None, 2477 title: None, 2478 summary: None, 2479 location: None, 2480 event_timing: None, 2481 event_start_date: None, 2482 event_end_date: None, 2483 event_start_unix_s: None, 2484 event_end_unix_s: None, 2485 event_timezone: None, 2486 price_amount: None, 2487 currency: None, 2488 unit: None, 2489 quantity: None, 2490 food_published_at_unix_s: None, 2491 food_status: None, 2492 media: vec![FfiPreparedMediaInput { 2493 schema_version: PREPARED_MEDIA_FFI_SCHEMA_VERSION, 2494 opaque_reference: "media:carrots-01".to_owned(), 2495 file: std::sync::Arc::new( 2496 FfiMediaFile::new(file_descriptor, bytes.len() as u64).expect("admitted file"), 2497 ), 2498 sha256: digest, 2499 media_type: "image/png".to_owned(), 2500 byte_size: bytes.len() as u64, 2501 width: 2, 2502 height: 2, 2503 alt: "A basket of carrots".to_owned(), 2504 prepared_at_unix_s: 1_800_000_000, 2505 }], 2506 } 2507 } 2508 2509 fn text_input(command_type: FfiAddCommandType) -> FfiAddDraftInput { 2510 FfiAddDraftInput { 2511 schema_version: MOBILE_FFI_SCHEMA_VERSION, 2512 command_type, 2513 content: "Fresh from the farm".to_owned(), 2514 identifier: None, 2515 title: None, 2516 summary: None, 2517 location: None, 2518 event_timing: None, 2519 event_start_date: None, 2520 event_end_date: None, 2521 event_start_unix_s: None, 2522 event_end_unix_s: None, 2523 event_timezone: None, 2524 price_amount: None, 2525 currency: None, 2526 unit: None, 2527 quantity: None, 2528 food_published_at_unix_s: None, 2529 food_status: None, 2530 media: Vec::new(), 2531 } 2532 } 2533 2534 #[test] 2535 fn exact_five_add_inputs_build_their_typed_core_commands() { 2536 let (update, media) = text_input(FfiAddCommandType::CreateUpdate) 2537 .command_and_media(1_800_000_000, None) 2538 .expect("update"); 2539 assert!(matches!(update, Phase1AddCommand::CreateUpdate(_))); 2540 assert!(media.is_empty()); 2541 2542 let (ask, media) = text_input(FfiAddCommandType::CreateAsk) 2543 .command_and_media(1_800_000_000, None) 2544 .expect("ask"); 2545 assert!(matches!(ask, Phase1AddCommand::CreateAsk(_))); 2546 assert!(media.is_empty()); 2547 2548 let mut all_day = text_input(FfiAddCommandType::CreateEvent); 2549 all_day.identifier = Some("market-day".to_owned()); 2550 all_day.title = Some("Farmers market".to_owned()); 2551 all_day.location = Some("Town square".to_owned()); 2552 all_day.event_timing = Some(FfiEventTimingKind::AllDay); 2553 all_day.event_start_date = Some("2026-08-08".to_owned()); 2554 all_day.event_end_date = Some("2026-08-09".to_owned()); 2555 let (event, media) = all_day 2556 .command_and_media(1_800_000_000, None) 2557 .expect("all-day event"); 2558 assert!(matches!(event, Phase1AddCommand::CreateEvent(_))); 2559 assert!(media.is_empty()); 2560 2561 let mut timed = text_input(FfiAddCommandType::CreateEvent); 2562 timed.identifier = Some("harvest-tour".to_owned()); 2563 timed.title = Some("Harvest tour".to_owned()); 2564 timed.event_timing = Some(FfiEventTimingKind::Timed); 2565 timed.event_start_unix_s = Some(1_800_000_000); 2566 timed.event_end_unix_s = Some(1_800_003_600); 2567 timed.event_timezone = Some("America/Vancouver".to_owned()); 2568 let (event, media) = timed 2569 .command_and_media(1_800_000_000, None) 2570 .expect("timed event"); 2571 assert!(matches!(event, Phase1AddCommand::CreateEvent(_))); 2572 assert!(media.is_empty()); 2573 2574 let bytes = png(2, 2); 2575 let mut file = tempfile::NamedTempFile::new().expect("media file"); 2576 file.write_all(&bytes).expect("write media"); 2577 file.flush().expect("flush media"); 2578 let digest = Sha256::digest(&bytes).to_hex(); 2579 let mut food = photo_input(file.as_file().as_raw_fd() as u64, &bytes, digest); 2580 food.command_type = FfiAddCommandType::CreateFoodAvailability; 2581 food.identifier = Some("carrots-2026-08".to_owned()); 2582 food.title = Some("Carrots".to_owned()); 2583 food.summary = Some("Fresh bunches".to_owned()); 2584 food.location = Some("Victoria".to_owned()); 2585 food.price_amount = Some("4.5".to_owned()); 2586 food.currency = Some("CAD".to_owned()); 2587 food.unit = Some("bunch".to_owned()); 2588 food.quantity = Some("12".to_owned()); 2589 food.food_status = Some("active".to_owned()); 2590 let blossom = blossom_slot(); 2591 let (food, media) = food 2592 .command_and_media(1_800_000_000, Some(&blossom)) 2593 .expect("food availability"); 2594 assert!(matches!(food, Phase1AddCommand::CreateFoodAvailability(_))); 2595 assert_eq!(media.len(), 1); 2596 } 2597 2598 #[test] 2599 fn add_validation_reports_schema_shape_media_and_required_field_failures() { 2600 let mut wrong_schema = text_input(FfiAddCommandType::CreateUpdate); 2601 wrong_schema.schema_version = MOBILE_FFI_SCHEMA_VERSION + 1; 2602 assert_eq!( 2603 wrong_schema 2604 .command_and_media(1_800_000_000, None) 2605 .expect_err("schema") 2606 .report() 2607 .code, 2608 "unsupported_schema_version" 2609 ); 2610 assert_eq!( 2611 text_input(FfiAddCommandType::CreateUpdate) 2612 .command_and_media(0, None) 2613 .expect_err("authored time") 2614 .report() 2615 .code, 2616 "invalid_add_draft" 2617 ); 2618 assert_eq!( 2619 text_input(FfiAddCommandType::CreateEvent) 2620 .command_and_media(1_800_000_000, None) 2621 .expect_err("event identity") 2622 .report() 2623 .code, 2624 "event_identifier_required" 2625 ); 2626 let mut food = text_input(FfiAddCommandType::CreateFoodAvailability); 2627 food.unit = Some("crate".to_owned()); 2628 assert_eq!( 2629 food.command_and_media(1_800_000_000, None) 2630 .expect_err("food unit") 2631 .report() 2632 .code, 2633 "invalid_food_unit" 2634 ); 2635 } 2636 2637 #[test] 2638 fn prepared_media_accepts_only_the_exact_bounded_file_descriptor_bytes() { 2639 let bytes = png(2, 2); 2640 let mut file = tempfile::NamedTempFile::new().expect("media file"); 2641 file.write_all(&bytes).expect("write media"); 2642 file.flush().expect("flush media"); 2643 let digest = Sha256::digest(&bytes).to_hex(); 2644 let input = photo_input(file.as_file().as_raw_fd() as u64, &bytes, digest.clone()); 2645 let blossom = blossom_slot(); 2646 2647 let (command, media) = input 2648 .command_and_media(1_800_000_000, Some(&blossom)) 2649 .expect("verified media input"); 2650 assert!(matches!(command, Phase1AddCommand::CreatePhotoUpdate(_))); 2651 assert_eq!(media.len(), 1); 2652 assert_eq!( 2653 media[0].url(), 2654 format!("http://127.0.0.1:3000/{digest}.png") 2655 ); 2656 assert_eq!( 2657 file.as_file().metadata().expect("caller-owned media").len(), 2658 bytes.len() as u64 2659 ); 2660 } 2661 2662 #[test] 2663 fn prepared_media_rejects_file_descriptors_outside_the_platform_range() { 2664 assert_eq!( 2665 FfiMediaFile::new(u64::MAX, 1) 2666 .expect_err("out-of-range descriptor") 2667 .report() 2668 .code, 2669 "media_handle_unavailable" 2670 ); 2671 } 2672 2673 #[cfg(unix)] 2674 #[test] 2675 fn prepared_media_rejects_unavailable_in_range_file_descriptors() { 2676 assert_eq!( 2677 FfiMediaFile::new(i32::MAX as u64, 1) 2678 .expect_err("unavailable in-range descriptor") 2679 .report() 2680 .code, 2681 "media_handle_unavailable" 2682 ); 2683 } 2684 2685 #[test] 2686 fn prepared_media_rejects_digest_tamper_and_path_like_references() { 2687 let bytes = png(2, 2); 2688 let mut file = tempfile::NamedTempFile::new().expect("media file"); 2689 file.write_all(&bytes).expect("write media"); 2690 file.flush().expect("flush media"); 2691 2692 let tampered = photo_input( 2693 file.as_file().as_raw_fd() as u64, 2694 &bytes, 2695 Sha256::digest(b"other").to_hex(), 2696 ); 2697 let blossom = blossom_slot(); 2698 assert_eq!( 2699 tampered 2700 .command_and_media(1_800_000_000, Some(&blossom)) 2701 .expect_err("digest mismatch") 2702 .report() 2703 .code, 2704 "media_verification_failed" 2705 ); 2706 2707 let mut path_like = photo_input( 2708 file.as_file().as_raw_fd() as u64, 2709 &bytes, 2710 Sha256::digest(&bytes).to_hex(), 2711 ); 2712 path_like.media[0].opaque_reference = "file:/private/media.jpg".to_owned(); 2713 assert_eq!( 2714 path_like 2715 .command_and_media(1_800_000_000, Some(&blossom)) 2716 .expect_err("path-like reference") 2717 .report() 2718 .code, 2719 "invalid_media_reference" 2720 ); 2721 } 2722 2723 #[test] 2724 fn prepared_media_constructs_a_bounded_verified_upload_request() { 2725 let bytes = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR\0\0\0\x02\0\0\0\x02"; 2726 let mut file = tempfile::NamedTempFile::new().expect("media file"); 2727 file.write_all(bytes).expect("write media"); 2728 file.flush().expect("flush media"); 2729 let digest = Sha256::digest(bytes).to_hex(); 2730 let mut input = photo_input(file.as_file().as_raw_fd() as u64, bytes, digest.clone()); 2731 input.media[0].media_type = "image/png".to_owned(); 2732 2733 let prepared = PreparedMedia::try_from(input.media.remove(0)).expect("prepared media"); 2734 let request = prepared 2735 .upload_request(1_800_000_000_000) 2736 .expect("bounded upload request"); 2737 assert_eq!(request.sha256().to_hex(), digest); 2738 assert_eq!(request.byte_size(), bytes.len() as u64); 2739 assert_eq!(request.media_type().as_str(), "image/png"); 2740 assert_eq!(request.dimensions().width(), 2); 2741 assert_eq!(request.dimensions().height(), 2); 2742 } 2743 2744 #[test] 2745 fn media_validation_executes_every_bounded_shape_guard() { 2746 let bytes = png(2, 2); 2747 let mut file = tempfile::NamedTempFile::new().expect("media file"); 2748 file.write_all(&bytes).expect("write media"); 2749 file.flush().expect("flush media"); 2750 let digest = Sha256::digest(&bytes).to_hex(); 2751 let valid = photo_input(file.as_file().as_raw_fd() as u64, &bytes, digest).media[0].clone(); 2752 2753 let mut old_schema = valid.clone(); 2754 old_schema.schema_version = MOBILE_FFI_SCHEMA_VERSION; 2755 assert_eq!( 2756 PreparedMedia::try_from(old_schema) 2757 .err() 2758 .expect("borrowed schema rejected") 2759 .report() 2760 .code, 2761 "unsupported_schema_version" 2762 ); 2763 2764 let mut invalid_values = Vec::new(); 2765 let mut value = valid.clone(); 2766 value.byte_size = 0; 2767 invalid_values.push(value); 2768 let mut value = valid.clone(); 2769 value.byte_size = MEDIA_FILE_MAX_BYTES + 1; 2770 invalid_values.push(value); 2771 let mut value = valid.clone(); 2772 value.width = 0; 2773 invalid_values.push(value); 2774 let mut value = valid.clone(); 2775 value.height = 0; 2776 invalid_values.push(value); 2777 let mut value = valid.clone(); 2778 value.prepared_at_unix_s = 0; 2779 invalid_values.push(value); 2780 let mut value = valid.clone(); 2781 value.alt = " ".to_owned(); 2782 invalid_values.push(value); 2783 let mut value = valid.clone(); 2784 value.alt = "a".repeat(1_025); 2785 invalid_values.push(value); 2786 2787 for value in invalid_values { 2788 assert_eq!( 2789 PreparedMedia::try_from(value) 2790 .err() 2791 .expect("invalid bounded media") 2792 .report() 2793 .code, 2794 "invalid_media_reference" 2795 ); 2796 } 2797 2798 let mut wrong_size = valid.clone(); 2799 wrong_size.byte_size += 1; 2800 assert_eq!( 2801 PreparedMedia::try_from(wrong_size) 2802 .err() 2803 .expect("descriptor size") 2804 .report() 2805 .code, 2806 "media_size_mismatch" 2807 ); 2808 for reference in ["media:", "Media:item", "media:BAD", "media:item/path"] { 2809 assert!(!opaque_media_reference_is_valid(reference)); 2810 } 2811 assert!(opaque_media_reference_is_valid("media:item_01-a")); 2812 assert!(!opaque_media_reference_is_valid(&format!( 2813 "media:{}", 2814 "a".repeat(MEDIA_REFERENCE_MAX_BYTES) 2815 ))); 2816 } 2817 2818 #[test] 2819 fn event_and_post_optional_branches_remain_strict_and_complete() { 2820 let mut minimal_date = text_input(FfiAddCommandType::CreateEvent); 2821 minimal_date.content.clear(); 2822 minimal_date.identifier = Some("minimal-date".to_owned()); 2823 minimal_date.title = Some("Minimal date".to_owned()); 2824 minimal_date.event_timing = Some(FfiEventTimingKind::AllDay); 2825 minimal_date.event_start_date = Some("2026-08-08".to_owned()); 2826 assert!(minimal_date.command_and_media(1_800_000_000, None).is_ok()); 2827 2828 let mut minimal_time = text_input(FfiAddCommandType::CreateEvent); 2829 minimal_time.content.clear(); 2830 minimal_time.identifier = Some("minimal-time".to_owned()); 2831 minimal_time.title = Some("Minimal time".to_owned()); 2832 minimal_time.event_timing = Some(FfiEventTimingKind::Timed); 2833 minimal_time.event_start_unix_s = Some(1_800_000_000); 2834 assert!(minimal_time.command_and_media(1_800_000_000, None).is_ok()); 2835 2836 let bytes = png(2, 2); 2837 let mut file = tempfile::NamedTempFile::new().expect("media file"); 2838 file.write_all(&bytes).expect("write media"); 2839 file.flush().expect("flush media"); 2840 let digest = Sha256::digest(&bytes).to_hex(); 2841 let mut event = photo_input(file.as_file().as_raw_fd() as u64, &bytes, digest); 2842 event.command_type = FfiAddCommandType::CreateEvent; 2843 event.identifier = Some("event-image".to_owned()); 2844 event.title = Some("Event image".to_owned()); 2845 event.event_timing = Some(FfiEventTimingKind::Timed); 2846 event.event_start_unix_s = Some(1_800_000_000); 2847 let blossom = blossom_slot(); 2848 assert!( 2849 event 2850 .clone() 2851 .command_and_media(1_800_000_000, Some(&blossom)) 2852 .is_ok() 2853 ); 2854 2855 let mut second = event.media[0].clone(); 2856 second.opaque_reference = "media:event-image-two".to_owned(); 2857 event.media.push(second); 2858 assert_eq!( 2859 event 2860 .command_and_media(1_800_000_000, Some(&blossom)) 2861 .expect_err("event media limit") 2862 .report() 2863 .code, 2864 "event_image_limit" 2865 ); 2866 } 2867 2868 #[test] 2869 fn content_references_and_identifier_decoding_cover_all_outcomes() { 2870 let bytes = png(2, 2); 2871 let mut file = tempfile::NamedTempFile::new().expect("media file"); 2872 file.write_all(&bytes).expect("write media"); 2873 file.flush().expect("flush media"); 2874 let digest = Sha256::digest(&bytes).to_hex(); 2875 let input = photo_input(file.as_file().as_raw_fd() as u64, &bytes, digest); 2876 let blossom = blossom_slot(); 2877 let prepared = PreparedMedia::try_from(input.media[0].clone()) 2878 .expect("prepared media") 2879 .bind(&blossom) 2880 .expect("bound media"); 2881 let url = prepared.descriptor.url().as_str().to_owned(); 2882 2883 assert_eq!( 2884 content_with_media_references(" ".to_owned(), std::slice::from_ref(&prepared)) 2885 .expect_err("blank content") 2886 .report() 2887 .code, 2888 "content_required" 2889 ); 2890 assert_eq!( 2891 content_with_media_references( 2892 format!("caption\n{url}"), 2893 std::slice::from_ref(&prepared) 2894 ) 2895 .expect("one existing reference") 2896 .match_indices(&url) 2897 .count(), 2898 1 2899 ); 2900 assert!( 2901 content_with_media_references("caption\n".to_owned(), std::slice::from_ref(&prepared)) 2902 .expect("newline append") 2903 .ends_with(&url) 2904 ); 2905 assert_eq!( 2906 content_with_media_references( 2907 format!("{url}\n{url}"), 2908 std::slice::from_ref(&prepared), 2909 ) 2910 .expect_err("duplicate reference") 2911 .report() 2912 .code, 2913 "duplicate_media_reference" 2914 ); 2915 2916 let mut update = text_input(FfiAddCommandType::CreateUpdate); 2917 update.media.push(input.media[0].clone()); 2918 assert_eq!( 2919 update 2920 .command_and_media(1_800_000_000, Some(&blossom)) 2921 .expect_err("update media") 2922 .report() 2923 .code, 2924 "media_not_allowed" 2925 ); 2926 let mut over_limit = text_input(FfiAddCommandType::CreateUpdate); 2927 over_limit.media = vec![input.media[0].clone(); 21]; 2928 assert_eq!( 2929 over_limit 2930 .command_and_media(1_800_000_000, None) 2931 .expect_err("media count") 2932 .report() 2933 .code, 2934 "invalid_add_draft" 2935 ); 2936 2937 assert_eq!(decode_id(&"01".repeat(16), "bad").expect("id"), [1; 16]); 2938 assert_eq!( 2939 decode_id("01", "bad").expect_err("short id").report().code, 2940 "bad" 2941 ); 2942 assert_eq!( 2943 decode_id(&"gg".repeat(16), "bad") 2944 .expect_err("non-hex id") 2945 .report() 2946 .code, 2947 "bad" 2948 ); 2949 } 2950 }