decode.rs (19088B)
1 use super::{EncodedRecord, RECORD_MAX_BYTES, RecordWireError}; 2 use crate::{ 3 command::{self, canonical_key, required_nullable}, 4 private_json::{self as text, RawArray}, 5 profile, terms, 6 }; 7 use alloc::{string::String, vec::Vec}; 8 use core::fmt; 9 use radroots_domain::listing::MeasurementUnit; 10 use radroots_domain::*; 11 use serde::Deserialize; 12 use serde_json::value::RawValue; 13 14 /// Complete self-consistent record claims and their checked canonical identity. 15 /// This value supplies no signature, consent, current authority or stock effect. 16 pub struct DecodedRecord { 17 content: CommerceContent, 18 identity: RecordId, 19 } 20 impl DecodedRecord { 21 /// Explicitly borrows private complete claims without authenticated evidence. 22 pub const fn content(&self) -> &CommerceContent { 23 &self.content 24 } 25 /// Returns the verified content hash, distinct from a NIP-01 rumor ID. 26 pub const fn record_id(&self) -> RecordId { 27 self.identity 28 } 29 /// Matches final carrier claims only; independent authenticated opening and 30 /// recipient binding remain mandatory before this can inform admission. 31 pub fn check_rumor_fields( 32 &self, 33 author: PublicKey, 34 created_at: u64, 35 kind: u16, 36 ) -> Result<(), RecordWireError> { 37 if author != self.content.header().author() 38 || created_at != self.content.header().created_at().get() 39 || kind != profile::COMMERCE_KIND 40 { 41 return Err(RecordWireError::CarrierMismatch); 42 } 43 Ok(()) 44 } 45 } 46 impl fmt::Debug for DecodedRecord { 47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 48 f.write_str("DecodedRecord(<redacted>)") 49 } 50 } 51 /// Decodes a closed bounded complete profile and checks its record-ID domain. 52 /// Callers own original private bytes and must retain unsupported raw evidence 53 /// at their protected boundary; this pure function never stores or discards it. 54 pub fn decode(raw: &[u8]) -> Result<DecodedRecord, RecordWireError> { 55 if raw.len() > RECORD_MAX_BYTES { 56 return Err(RecordWireError::LimitExceeded); 57 } 58 command::check_frame(raw).map_err(command_error)?; 59 let probe: ProfileProbe = command::parse_object(raw).map_err(command_error)?; 60 if probe.profile != profile::COMMERCE_PROFILE 61 || probe.version != profile::PROFILE_VERSION 62 || !known_type(&probe.kind) 63 { 64 return Err(RecordWireError::UnsupportedProfile); 65 } 66 let value: Record<'_> = command::parse_object(raw).map_err(command_error)?; 67 if value.profile != profile::COMMERCE_PROFILE || value.version != profile::PROFILE_VERSION { 68 return Err(RecordWireError::UnsupportedProfile); 69 } 70 let header = invalid(CommerceHeader::new( 71 value.thread_id, 72 value.order_id, 73 value.author, 74 value.buyer, 75 value.seller, 76 value.created_at, 77 value.author_sequence, 78 value.author_previous, 79 identifiers(value.parents)?, 80 ))?; 81 let content = invalid(CommerceContent::new( 82 header, 83 payload(&value.kind, value.payload)?, 84 ))?; 85 let encoded = EncodedRecord::capture(&content)?; 86 if encoded.record_id() != value.record_id { 87 return Err(RecordWireError::IdentityMismatch); 88 } 89 Ok(DecodedRecord { 90 content, 91 identity: encoded.record_id(), 92 }) 93 } 94 #[derive(Deserialize)] 95 struct ProfileProbe { 96 profile: String, 97 version: u32, 98 #[serde(rename = "type")] 99 kind: String, 100 } 101 fn known_type(value: &str) -> bool { 102 const TYPES: &[CommerceType] = &[ 103 CommerceType::Quote, 104 CommerceType::Request, 105 CommerceType::Decline, 106 CommerceType::TermsProposed, 107 CommerceType::TermsAuthorized, 108 CommerceType::TermsRejected, 109 CommerceType::AgreementCommitted, 110 CommerceType::WithdrawalRequested, 111 CommerceType::WithdrawalAcknowledged, 112 CommerceType::CancellationProposed, 113 CommerceType::CancellationAuthorized, 114 CommerceType::ResidualReleased, 115 CommerceType::Ready, 116 CommerceType::Handover, 117 CommerceType::Receipt, 118 CommerceType::Issue, 119 CommerceType::ResolutionProposed, 120 CommerceType::ResolutionAuthorized, 121 CommerceType::ResolutionCommitted, 122 ]; 123 TYPES.iter().any(|kind| kind.as_str() == value) 124 } 125 fn invalid<T, E>(value: Result<T, E>) -> Result<T, RecordWireError> { 126 value.map_err(|_| RecordWireError::InvalidInput) 127 } 128 fn command_error(value: command::CommandError) -> RecordWireError { 129 match value { 130 command::CommandError::LimitExceeded => RecordWireError::LimitExceeded, 131 command::CommandError::UnsupportedProfile => RecordWireError::UnsupportedProfile, 132 _ => RecordWireError::InvalidInput, 133 } 134 } 135 fn parse<'a, T: Deserialize<'a>>(raw: &'a RawValue) -> Result<T, RecordWireError> { 136 command::parse_object(raw.get().as_bytes()).map_err(command_error) 137 } 138 fn identifiers<'a, T: Deserialize<'a>, const N: usize>( 139 values: RawArray<'a, N>, 140 ) -> Result<Vec<T>, RecordWireError> { 141 values 142 .0 143 .into_iter() 144 .map(|raw| invalid(serde_json::from_str(raw.get()))) 145 .collect() 146 } 147 #[derive(Deserialize)] 148 #[serde(deny_unknown_fields)] 149 struct Record<'a> { 150 profile: String, 151 version: u32, 152 #[serde(rename = "type")] 153 kind: String, 154 record_id: RecordId, 155 thread_id: ThreadId, 156 #[serde(deserialize_with = "required_nullable")] 157 order_id: Option<OrderId>, 158 #[serde(deserialize_with = "canonical_key")] 159 author: PublicKey, 160 #[serde(deserialize_with = "canonical_key")] 161 buyer: PublicKey, 162 #[serde(deserialize_with = "canonical_key")] 163 seller: PublicKey, 164 created_at: UnixSeconds, 165 author_sequence: Sequence, 166 #[serde(deserialize_with = "required_nullable")] 167 author_previous: Option<RecordId>, 168 #[serde(borrow)] 169 parents: RawArray<'a, 8>, 170 #[serde(borrow)] 171 payload: &'a RawValue, 172 } 173 #[derive(Deserialize)] 174 #[serde(deny_unknown_fields)] 175 struct Quote<'a> { 176 #[serde(borrow)] 177 terms: &'a RawValue, 178 expires_at: UnixSeconds, 179 #[serde(deserialize_with = "required_nullable")] 180 in_reply_to: Option<SourceId>, 181 } 182 #[derive(Deserialize)] 183 #[serde(deny_unknown_fields)] 184 struct Request<'a> { 185 #[serde(borrow)] 186 terms: &'a RawValue, 187 expires_at: UnixSeconds, 188 #[serde(deserialize_with = "required_nullable")] 189 quote: Option<RecordId>, 190 } 191 macro_rules! reason { 192 ($name:ident,$field:ident) => { 193 #[derive(Deserialize)] 194 #[serde(deny_unknown_fields)] 195 struct $name<'a> { 196 $field: RecordId, 197 #[serde(borrow)] 198 reason: &'a RawValue, 199 } 200 }; 201 } 202 reason!(Decline, request); 203 reason!(Rejection, proposal); 204 reason!(Withdrawal, authorization); 205 #[derive(Deserialize)] 206 #[serde(deny_unknown_fields)] 207 struct Proposal<'a> { 208 #[serde(deserialize_with = "required_nullable")] 209 base_agreement: Option<RecordId>, 210 #[serde(borrow)] 211 terms: &'a RawValue, 212 expires_at: UnixSeconds, 213 #[serde(borrow)] 214 reason: &'a RawValue, 215 } 216 #[derive(Deserialize)] 217 #[serde(deny_unknown_fields)] 218 struct TermsApproval { 219 proposal: RecordId, 220 terms_digest: TermsDigest, 221 expires_at: UnixSeconds, 222 } 223 #[derive(Deserialize)] 224 #[serde(deny_unknown_fields)] 225 struct Agreement { 226 #[serde(deserialize_with = "required_nullable")] 227 base_agreement: Option<RecordId>, 228 authorization: RecordId, 229 terms_digest: TermsDigest, 230 authority: AuthorityRef, 231 seller_sequence: Sequence, 232 } 233 #[derive(Deserialize)] 234 #[serde(deny_unknown_fields)] 235 struct WithdrawalAck { 236 withdrawal: RecordId, 237 seller_sequence: Sequence, 238 } 239 #[derive(Deserialize)] 240 #[serde(deny_unknown_fields)] 241 struct Cancellation<'a> { 242 agreement: RecordId, 243 #[serde(borrow)] 244 residual: RawArray<'a, 32>, 245 #[serde(borrow)] 246 reason: &'a RawValue, 247 expires_at: UnixSeconds, 248 } 249 #[derive(Deserialize)] 250 #[serde(deny_unknown_fields)] 251 struct Approval { 252 proposal: RecordId, 253 expires_at: UnixSeconds, 254 } 255 #[derive(Deserialize)] 256 #[serde(deny_unknown_fields)] 257 struct Release<'a> { 258 proposal: RecordId, 259 authorization: RecordId, 260 agreement: RecordId, 261 #[serde(borrow)] 262 residual: RawArray<'a, 32>, 263 authority: AuthorityRef, 264 seller_sequence: Sequence, 265 } 266 #[derive(Deserialize)] 267 #[serde(deny_unknown_fields)] 268 struct Ready<'a> { 269 agreement: RecordId, 270 fulfillment_group: FulfillmentGroupId, 271 #[serde(borrow)] 272 lines: RawArray<'a, 32>, 273 #[serde(borrow)] 274 window: &'a RawValue, 275 } 276 #[derive(Deserialize)] 277 #[serde(deny_unknown_fields)] 278 struct Handover<'a> { 279 agreement: RecordId, 280 fulfillment_group: FulfillmentGroupId, 281 #[serde(borrow)] 282 lines: RawArray<'a, 32>, 283 #[serde(borrow)] 284 measurements: RawArray<'a, 32>, 285 occurred_at: UnixSeconds, 286 authority: AuthorityRef, 287 seller_sequence: Sequence, 288 } 289 #[derive(Deserialize)] 290 #[serde(deny_unknown_fields)] 291 struct Receipt<'a> { 292 handover: RecordId, 293 #[serde(borrow)] 294 lines: RawArray<'a, 32>, 295 #[serde(deserialize_with = "required_nullable")] 296 supersedes: Option<RecordId>, 297 occurred_at: UnixSeconds, 298 #[serde(borrow)] 299 note: &'a RawValue, 300 } 301 #[derive(Deserialize)] 302 #[serde(deny_unknown_fields)] 303 struct Issue<'a> { 304 code: String, 305 #[serde(borrow)] 306 description: &'a RawValue, 307 #[serde(borrow)] 308 lines: RawArray<'a, 32>, 309 #[serde(borrow)] 310 source_records: RawArray<'a, 32>, 311 } 312 #[derive(Deserialize)] 313 #[serde(deny_unknown_fields)] 314 struct Resolve<'a> { 315 agreement: RecordId, 316 #[serde(borrow)] 317 resolution: &'a RawValue, 318 expires_at: UnixSeconds, 319 } 320 #[derive(Deserialize)] 321 #[serde(deny_unknown_fields)] 322 struct Commitment { 323 proposal: RecordId, 324 authorization: RecordId, 325 authority: AuthorityRef, 326 seller_sequence: Sequence, 327 } 328 #[derive(Deserialize)] 329 #[serde(deny_unknown_fields)] 330 struct Line { 331 line_id: AgreementLineId, 332 amount: Decimal, 333 } 334 fn lines(values: RawArray<'_, 32>) -> Result<Vec<LineQuantity>, RecordWireError> { 335 values 336 .0 337 .into_iter() 338 .map(|raw| { 339 let value: Line = parse(raw)?; 340 Ok(LineQuantity::new(value.line_id, value.amount)) 341 }) 342 .collect() 343 } 344 #[derive(Deserialize)] 345 #[serde(deny_unknown_fields)] 346 struct Measurement<'a> { 347 line_id: AgreementLineId, 348 #[serde(borrow)] 349 quantity: &'a RawValue, 350 #[serde(borrow)] 351 line_total: &'a RawValue, 352 } 353 #[derive(Deserialize)] 354 #[serde(deny_unknown_fields)] 355 struct MeasuredQuantity { 356 amount: Decimal, 357 unit: String, 358 } 359 fn quantity(raw: &RawValue) -> Result<Quantity, RecordWireError> { 360 let value: MeasuredQuantity = parse(raw)?; 361 let unit = match value.unit.as_str() { 362 "g" => MeasurementUnit::Gram, 363 "kg" => MeasurementUnit::Kilogram, 364 "mL" => MeasurementUnit::Millilitre, 365 "L" => MeasurementUnit::Litre, 366 "each" => MeasurementUnit::Each, 367 _ => return Err(RecordWireError::UnsupportedProfile), 368 }; 369 invalid(Quantity::new(value.amount, unit)) 370 } 371 fn measurements(values: RawArray<'_, 32>) -> Result<Vec<FinalMeasurement>, RecordWireError> { 372 values 373 .0 374 .into_iter() 375 .map(|raw| { 376 let value: Measurement<'_> = parse(raw)?; 377 Ok(FinalMeasurement::new( 378 value.line_id, 379 quantity(value.quantity)?, 380 terms::decode::money(value.line_total)?, 381 )) 382 }) 383 .collect() 384 } 385 #[derive(Deserialize)] 386 #[serde(deny_unknown_fields)] 387 struct ResolutionInput<'a> { 388 #[serde(borrow)] 389 issues: RawArray<'a, 32>, 390 #[serde(borrow)] 391 accepted_receipts: RawArray<'a, 32>, 392 #[serde(borrow)] 393 release_residual: RawArray<'a, 32>, 394 #[serde(borrow)] 395 summary: &'a RawValue, 396 } 397 fn resolution(raw: &RawValue) -> Result<Resolution, RecordWireError> { 398 let value: ResolutionInput<'_> = parse(raw)?; 399 let summary = text::decode(value.summary.get(), 2048).map_err(command_error)?; 400 invalid(Resolution::new( 401 identifiers(value.issues)?, 402 identifiers(value.accepted_receipts)?, 403 lines(value.release_residual)?, 404 &summary, 405 )) 406 } 407 fn payload(kind: &str, raw: &RawValue) -> Result<CommercePayload, RecordWireError> { 408 Ok(match kind { 409 "quote" => { 410 let value: Quote<'_> = parse(raw)?; 411 CommercePayload::Quote(TermsQuote::new( 412 terms::decode(value.terms.get().as_bytes())?, 413 value.expires_at, 414 value.in_reply_to, 415 )) 416 } 417 "request" => { 418 let value: Request<'_> = parse(raw)?; 419 CommercePayload::Request(TermsRequest::new( 420 terms::decode(value.terms.get().as_bytes())?, 421 value.expires_at, 422 value.quote, 423 )) 424 } 425 "decline" => { 426 let value: Decline<'_> = parse(raw)?; 427 let reason = text::decode(value.reason.get(), 1024).map_err(command_error)?; 428 CommercePayload::Decline(invalid(RecordReason::new(value.request, &reason))?) 429 } 430 "terms_proposed" => { 431 let value: Proposal<'_> = parse(raw)?; 432 let reason = text::decode(value.reason.get(), 1024).map_err(command_error)?; 433 CommercePayload::TermsProposed(invalid(TermsProposal::new( 434 value.base_agreement, 435 terms::decode(value.terms.get().as_bytes())?, 436 value.expires_at, 437 &reason, 438 ))?) 439 } 440 "terms_authorized" => { 441 let value: TermsApproval = parse(raw)?; 442 CommercePayload::TermsAuthorized(TermsAuthorization::new( 443 value.proposal, 444 value.terms_digest, 445 value.expires_at, 446 )) 447 } 448 "terms_rejected" => { 449 let value: Rejection<'_> = parse(raw)?; 450 let reason = text::decode(value.reason.get(), 1024).map_err(command_error)?; 451 CommercePayload::TermsRejected(invalid(RecordReason::new(value.proposal, &reason))?) 452 } 453 "agreement_committed" => { 454 let value: Agreement = parse(raw)?; 455 CommercePayload::AgreementCommitted(invalid(AgreementCommitment::new( 456 value.base_agreement, 457 value.authorization, 458 value.terms_digest, 459 value.authority, 460 value.seller_sequence, 461 ))?) 462 } 463 "withdrawal_requested" => { 464 let value: Withdrawal<'_> = parse(raw)?; 465 let reason = text::decode(value.reason.get(), 1024).map_err(command_error)?; 466 CommercePayload::WithdrawalRequested(invalid(RecordReason::new( 467 value.authorization, 468 &reason, 469 ))?) 470 } 471 "withdrawal_acknowledged" => { 472 let value: WithdrawalAck = parse(raw)?; 473 CommercePayload::WithdrawalAcknowledged(invalid(WithdrawalAcknowledgement::new( 474 value.withdrawal, 475 value.seller_sequence, 476 ))?) 477 } 478 "cancellation_proposed" => { 479 let value: Cancellation<'_> = parse(raw)?; 480 let reason = text::decode(value.reason.get(), 1024).map_err(command_error)?; 481 CommercePayload::CancellationProposed(invalid(CancellationProposal::new( 482 value.agreement, 483 lines(value.residual)?, 484 &reason, 485 value.expires_at, 486 ))?) 487 } 488 "cancellation_authorized" => { 489 let value: Approval = parse(raw)?; 490 CommercePayload::CancellationAuthorized(ProposalAuthorization::new( 491 value.proposal, 492 value.expires_at, 493 )) 494 } 495 "residual_released" => { 496 let value: Release<'_> = parse(raw)?; 497 CommercePayload::ResidualReleased(invalid(ResidualRelease::new( 498 value.proposal, 499 value.authorization, 500 value.agreement, 501 lines(value.residual)?, 502 value.authority, 503 value.seller_sequence, 504 ))?) 505 } 506 "ready" => { 507 let value: Ready<'_> = parse(raw)?; 508 CommercePayload::Ready(invalid(ReadinessClaim::new( 509 value.agreement, 510 value.fulfillment_group, 511 lines(value.lines)?, 512 terms::decode::window(value.window)?, 513 ))?) 514 } 515 "handover" => { 516 let value: Handover<'_> = parse(raw)?; 517 CommercePayload::Handover(invalid(HandoverClaim::new( 518 value.agreement, 519 value.fulfillment_group, 520 lines(value.lines)?, 521 measurements(value.measurements)?, 522 value.occurred_at, 523 value.authority, 524 value.seller_sequence, 525 ))?) 526 } 527 "receipt" => { 528 let value: Receipt<'_> = parse(raw)?; 529 let note = text::decode(value.note.get(), 1024).map_err(command_error)?; 530 CommercePayload::Receipt(invalid(ReceiptObservation::new( 531 value.handover, 532 lines(value.lines)?, 533 value.supersedes, 534 value.occurred_at, 535 ¬e, 536 ))?) 537 } 538 "issue" => { 539 let value: Issue<'_> = parse(raw)?; 540 let description = text::decode(value.description.get(), 2048).map_err(command_error)?; 541 let code = match value.code.as_str() { 542 "shortage" => IssueCode::Shortage, 543 "quality" => IssueCode::Quality, 544 "substitution" => IssueCode::Substitution, 545 "collection" => IssueCode::Collection, 546 "excess" => IssueCode::Excess, 547 "other" => IssueCode::Other, 548 _ => return Err(RecordWireError::UnsupportedProfile), 549 }; 550 CommercePayload::Issue(invalid(IssueReport::new( 551 code, 552 &description, 553 lines(value.lines)?, 554 identifiers(value.source_records)?, 555 ))?) 556 } 557 "resolution_proposed" => { 558 let value: Resolve<'_> = parse(raw)?; 559 CommercePayload::ResolutionProposed(ResolutionProposal::new( 560 value.agreement, 561 resolution(value.resolution)?, 562 value.expires_at, 563 )) 564 } 565 "resolution_authorized" => { 566 let value: Approval = parse(raw)?; 567 CommercePayload::ResolutionAuthorized(ProposalAuthorization::new( 568 value.proposal, 569 value.expires_at, 570 )) 571 } 572 "resolution_committed" => { 573 let value: Commitment = parse(raw)?; 574 CommercePayload::ResolutionCommitted(invalid(ResolutionCommitment::new( 575 value.proposal, 576 value.authorization, 577 value.authority, 578 value.seller_sequence, 579 ))?) 580 } 581 _ => return Err(RecordWireError::UnsupportedProfile), 582 }) 583 }