1#![forbid(unsafe_code)]
9
10use core::fmt;
11
12#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
14#[repr(u16)]
15pub enum ContractVersion {
16 V1 = 1,
17}
18
19#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
21#[repr(u16)]
22pub enum IntentFormatVersion {
23 V1 = 1,
24}
25
26#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
28#[repr(u16)]
29pub enum DigestSuite {
30 Blake3_256 = 1,
31}
32
33#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
35#[repr(u16)]
36pub enum SignatureSuite {
37 CompositeEd25519MlDsa65V1 = 1,
39}
40
41#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
42pub enum KeyPurpose {
43 MacResourceAttestation,
44 LedgerResourceAttestation,
45 RegistrarFinalization,
46}
47
48#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
49pub struct ResourceId([u8; 16]);
50
51impl ResourceId {
52 pub const fn from_bytes(bytes: [u8; 16]) -> Self {
53 Self(bytes)
54 }
55
56 pub const fn as_bytes(&self) -> &[u8; 16] {
57 &self.0
58 }
59}
60
61#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
62pub struct OperationId([u8; 16]);
63
64impl OperationId {
65 pub const fn from_bytes(bytes: [u8; 16]) -> Self {
66 Self(bytes)
67 }
68
69 pub const fn as_bytes(&self) -> &[u8; 16] {
70 &self.0
71 }
72}
73
74#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
75pub struct TransferId([u8; 16]);
76
77impl TransferId {
78 pub const fn from_bytes(bytes: [u8; 16]) -> Self {
79 Self(bytes)
80 }
81}
82
83#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
84pub struct IntentDigest([u8; 32]);
85
86impl IntentDigest {
87 const DOMAIN: &'static [u8] = b"hs-resource-intent-v1\0";
88
89 #[must_use]
90 pub fn compute(suite: DigestSuite, canonical_bytes: &[u8]) -> Self {
91 match suite {
92 DigestSuite::Blake3_256 => {
93 let mut hasher = blake3::Hasher::new();
94 hasher.update(Self::DOMAIN);
95 hasher.update(canonical_bytes);
96 Self(*hasher.finalize().as_bytes())
97 }
98 }
99 }
100
101 pub const fn from_bytes(bytes: [u8; 32]) -> Self {
102 Self(bytes)
103 }
104
105 pub const fn as_bytes(&self) -> &[u8; 32] {
106 &self.0
107 }
108}
109
110#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
111pub struct Cid(Vec<u8>);
112
113impl Cid {
114 pub fn from_validated_bytes(bytes: Vec<u8>) -> Self {
116 Self(bytes)
117 }
118
119 pub fn as_bytes(&self) -> &[u8] {
120 &self.0
121 }
122}
123
124#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
125pub struct Did(String);
126
127impl Did {
128 pub fn from_validated_string(value: String) -> Self {
130 Self(value)
131 }
132
133 pub fn as_str(&self) -> &str {
134 &self.0
135 }
136}
137
138#[derive(Clone, Debug, Eq, Hash, PartialEq)]
141pub struct OwnerCommitment(Vec<u8>);
142
143impl OwnerCommitment {
144 pub fn from_verified_bytes(bytes: Vec<u8>) -> Self {
146 Self(bytes)
147 }
148}
149
150#[derive(Clone, Debug, Eq, Hash, PartialEq)]
152pub struct OperationCapabilityCommitment {
153 intent_digest: IntentDigest,
154 bytes: Vec<u8>,
155}
156
157impl OperationCapabilityCommitment {
158 pub fn from_verified_bytes(intent_digest: IntentDigest, bytes: Vec<u8>) -> Self {
159 Self {
160 intent_digest,
161 bytes,
162 }
163 }
164
165 pub const fn intent_digest(&self) -> IntentDigest {
166 self.intent_digest
167 }
168}
169
170#[derive(Clone, Debug, Eq, Hash, PartialEq)]
172pub struct OperationEntitlementCommitment {
173 intent_digest: IntentDigest,
174 bytes: Vec<u8>,
175}
176
177impl OperationEntitlementCommitment {
178 pub fn from_verified_bytes(intent_digest: IntentDigest, bytes: Vec<u8>) -> Self {
179 Self {
180 intent_digest,
181 bytes,
182 }
183 }
184
185 pub const fn intent_digest(&self) -> IntentDigest {
186 self.intent_digest
187 }
188}
189
190#[derive(Clone, Debug, Eq, Hash, PartialEq)]
191pub struct ContentLabelCommitment(Vec<u8>);
192
193impl ContentLabelCommitment {
194 pub fn from_verified_bytes(bytes: Vec<u8>) -> Self {
195 Self(bytes)
196 }
197}
198
199#[derive(Clone, Debug, Eq, Hash, PartialEq)]
200pub struct PrivateEvidenceCommitment(Vec<u8>);
201
202impl PrivateEvidenceCommitment {
203 pub fn from_verified_bytes(bytes: Vec<u8>) -> Self {
204 Self(bytes)
205 }
206}
207
208#[derive(Clone, Debug, Eq, Hash, PartialEq)]
211pub struct PublicEvidenceCommitment {
212 intent_digest: IntentDigest,
213 bytes: Vec<u8>,
214}
215
216impl PublicEvidenceCommitment {
217 pub fn from_verified_bytes(intent_digest: IntentDigest, bytes: Vec<u8>) -> Self {
218 Self {
219 intent_digest,
220 bytes,
221 }
222 }
223
224 pub const fn intent_digest(&self) -> IntentDigest {
225 self.intent_digest
226 }
227}
228
229#[derive(Clone, Debug, Eq, PartialEq)]
230pub struct Signature(Vec<u8>);
231
232impl Signature {
233 pub fn from_envelope_bytes(bytes: Vec<u8>) -> Self {
234 Self(bytes)
235 }
236}
237
238#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
242#[repr(u8)]
243pub enum Assurance {
244 Unverified = 0,
245 Classical = 1,
246 PqHybrid = 2,
247}
248
249impl Assurance {
250 #[must_use]
251 pub fn minimum_all(values: impl IntoIterator<Item = Self>) -> Self {
252 values.into_iter().min().unwrap_or(Self::Unverified)
253 }
254}
255
256impl TryFrom<u8> for Assurance {
257 type Error = ContractError;
258
259 fn try_from(value: u8) -> Result<Self, Self::Error> {
260 match value {
261 0 => Ok(Self::Unverified),
262 1 => Ok(Self::Classical),
263 2 => Ok(Self::PqHybrid),
264 _ => Err(ContractError::UnsupportedAssurance),
265 }
266 }
267}
268
269impl From<Assurance> for u8 {
270 fn from(value: Assurance) -> Self {
271 value as u8
272 }
273}
274
275#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
279#[repr(u8)]
280pub enum RequiredAssurance {
281 Classical = 1,
282 PqHybrid = 2,
283}
284
285impl RequiredAssurance {
286 const fn is_met_by(self, effective: Assurance) -> bool {
287 (effective as u8) >= (self as u8)
288 }
289}
290
291#[derive(Clone, Debug, Eq, PartialEq)]
292pub enum OwnershipRef {
293 Identified(Did),
294 Pairwise(Did),
295 Committed(OwnerCommitment),
296}
297
298#[derive(Clone, Debug, Eq, PartialEq)]
299pub enum ControllerRef {
300 Identified(Did),
301 Pairwise(Did),
302 AnonymousCapability(OperationCapabilityCommitment),
303}
304
305#[derive(Clone, Debug, Eq, PartialEq)]
306pub enum PayerRef {
307 Identified(Did),
308 Pairwise(Did),
309 AnonymousEntitlement(OperationEntitlementCommitment),
310}
311
312#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
316pub enum ResourceOperation {
317 Create,
318 Mutate,
319 TransferTitle,
320 Delete,
321}
322
323#[derive(Clone, Debug, Eq, Hash, PartialEq)]
324pub enum ResourceKind {
325 ImmutableBlob,
326 MutableFile,
327 Directory,
328}
329
330#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
333enum ContentCidRequirement {
334 Required,
335 Forbidden,
336}
337
338const fn content_cid_requirement(
339 resource_kind: &ResourceKind,
340 operation: ResourceOperation,
341) -> Result<ContentCidRequirement, ContractError> {
342 match (resource_kind, operation) {
343 (ResourceKind::ImmutableBlob, ResourceOperation::Create)
344 | (ResourceKind::MutableFile, ResourceOperation::Create | ResourceOperation::Mutate) => {
345 Ok(ContentCidRequirement::Required)
346 }
347 (ResourceKind::Directory, ResourceOperation::Create | ResourceOperation::Mutate)
348 | (_, ResourceOperation::TransferTitle | ResourceOperation::Delete) => {
349 Ok(ContentCidRequirement::Forbidden)
350 }
351 (ResourceKind::ImmutableBlob, ResourceOperation::Mutate) => {
352 Err(ContractError::InvalidResourceOperation)
353 }
354 }
355}
356
357#[derive(Clone, Debug, Eq, PartialEq)]
358pub struct PredecessorRef {
359 pub manifest_cid: Cid,
360 pub version: u64,
361}
362
363#[derive(Clone, Debug, Eq, PartialEq)]
365pub struct IntentClaims {
366 pub resource_id: ResourceId,
367 pub operation_id: OperationId,
368 pub operation: ResourceOperation,
369 pub resource_kind: ResourceKind,
370 pub expected_predecessor: Option<PredecessorRef>,
371 pub owner: OwnershipRef,
372 pub controller: ControllerRef,
373 pub payer: PayerRef,
374 pub required_assurance: RequiredAssurance,
375 pub unit: String,
376 pub max_charge: u128,
377}
378
379pub struct IntentCandidate {
381 pub contract_version: ContractVersion,
382 pub format_version: IntentFormatVersion,
383 pub digest_suite: DigestSuite,
384 pub claimed_digest: IntentDigest,
385 pub canonical_bytes: Vec<u8>,
386}
387
388pub trait IntentValidator {
390 fn validate_and_decode(
391 &self,
392 version: IntentFormatVersion,
393 canonical_bytes: &[u8],
394 ) -> Result<IntentClaims, ContractError>;
395}
396
397#[derive(Clone, Debug, Eq, PartialEq)]
400pub struct CanonicalResourceIntent {
401 contract_version: ContractVersion,
402 format_version: IntentFormatVersion,
403 digest_suite: DigestSuite,
404 digest: IntentDigest,
405 canonical_bytes: Vec<u8>,
406 claims: IntentClaims,
407}
408
409impl CanonicalResourceIntent {
410 pub fn validate(
411 candidate: IntentCandidate,
412 validator: &dyn IntentValidator,
413 ) -> Result<Self, ContractError> {
414 if candidate.canonical_bytes.is_empty() || candidate.canonical_bytes.len() > 1_048_576 {
415 return Err(ContractError::IntentBounds);
416 }
417 let claims =
418 validator.validate_and_decode(candidate.format_version, &candidate.canonical_bytes)?;
419 let predecessor_is_valid = matches!(claims.operation, ResourceOperation::Create)
420 == claims.expected_predecessor.is_none();
421 if !predecessor_is_valid {
422 return Err(ContractError::InvalidPredecessor);
423 }
424 content_cid_requirement(&claims.resource_kind, claims.operation)?;
425 let digest = IntentDigest::compute(candidate.digest_suite, &candidate.canonical_bytes);
426 if digest != candidate.claimed_digest {
427 return Err(ContractError::DigestMismatch);
428 }
429 Ok(Self {
430 contract_version: candidate.contract_version,
431 format_version: candidate.format_version,
432 digest_suite: candidate.digest_suite,
433 digest,
434 canonical_bytes: candidate.canonical_bytes,
435 claims,
436 })
437 }
438
439 pub const fn digest(&self) -> IntentDigest {
440 self.digest
441 }
442
443 pub fn claims(&self) -> &IntentClaims {
444 &self.claims
445 }
446
447 pub fn canonical_bytes(&self) -> &[u8] {
448 &self.canonical_bytes
449 }
450
451 pub const fn contract_version(&self) -> ContractVersion {
452 self.contract_version
453 }
454
455 pub const fn format_version(&self) -> IntentFormatVersion {
456 self.format_version
457 }
458
459 pub const fn digest_suite(&self) -> DigestSuite {
460 self.digest_suite
461 }
462}
463
464#[derive(Clone, Debug, Eq, PartialEq)]
468pub struct SignatureEnvelope {
469 pub contract_version: ContractVersion,
470 pub suite: SignatureSuite,
471 pub signer: Did,
472 pub key_id: String,
473 pub key_epoch: u64,
474 pub purpose: KeyPurpose,
475 pub signed_domain: String,
476 pub signature: Signature,
477}
478
479#[derive(Clone, Debug, Eq, PartialEq)]
482pub enum CapabilityBinding {
483 IdentifiedRoot(Cid),
484 AnonymousOperationCommitment(OperationCapabilityCommitment),
485}
486
487#[derive(Clone, Debug, Eq, PartialEq)]
489pub struct MacAttestationCandidate {
490 pub contract_version: ContractVersion,
491 pub intent_digest: IntentDigest,
492 pub policy_epoch: u64,
493 pub state_epoch: u64,
494 pub controller: ControllerRef,
495 pub capability_binding: CapabilityBinding,
496 pub content_label_commitment: ContentLabelCommitment,
497 pub expires_at: u64,
499 pub envelope: SignatureEnvelope,
500}
501
502#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
503pub enum LedgerPhase {
504 Reserved,
505 Posted,
506 ZeroCostPosted,
507 Voided,
508 Compensated,
509}
510
511#[derive(Clone, Debug, Eq, PartialEq)]
514pub struct LedgerAttestationCandidate {
515 pub contract_version: ContractVersion,
516 pub intent_digest: IntentDigest,
517 pub ledger_id: Did,
518 pub payer: PayerRef,
519 pub issuer: Did,
520 pub unit: String,
521 pub amount: u128,
522 pub transfer_id: TransferId,
523 pub phase: LedgerPhase,
524 pub envelope: SignatureEnvelope,
525}
526
527#[derive(Clone, Debug, Eq, PartialEq)]
530pub struct AcceptedAuthority {
531 pub root: Cid,
532 pub signer: Did,
533 pub key_id: String,
534 pub key_epoch: u64,
535}
536
537#[derive(Clone, Debug, Eq, PartialEq)]
541pub struct VerifiedEvidence {
542 pub attestation_cid: Cid,
543 pub authority: AcceptedAuthority,
544 pub assurance: Assurance,
547}
548
549pub trait MacAttestationVerifier {
550 fn verify_accepted_current(
552 &self,
553 intent: &CanonicalResourceIntent,
554 candidate: &MacAttestationCandidate,
555 ) -> Result<VerifiedEvidence, ContractError>;
556}
557
558pub trait LedgerAttestationVerifier {
559 fn verify_accepted_current(
561 &self,
562 intent: &CanonicalResourceIntent,
563 candidate: &LedgerAttestationCandidate,
564 ) -> Result<VerifiedEvidence, ContractError>;
565}
566
567pub trait AttestationIndependencePolicy {
574 fn require_independence(
575 &self,
576 mac: &AcceptedAuthority,
577 ledger: &AcceptedAuthority,
578 ) -> Result<(), ContractError>;
579}
580
581pub struct RejectSharedAttester;
589
590impl AttestationIndependencePolicy for RejectSharedAttester {
591 fn require_independence(
592 &self,
593 mac: &AcceptedAuthority,
594 ledger: &AcceptedAuthority,
595 ) -> Result<(), ContractError> {
596 if mac.root == ledger.root || mac.signer == ledger.signer {
597 return Err(ContractError::SharedAttester);
598 }
599 Ok(())
600 }
601}
602
603#[derive(Clone, Debug, Eq, PartialEq)]
606pub struct VerifiedMacAttestation {
607 attestation: MacAttestationCandidate,
608 evidence: VerifiedEvidence,
609}
610
611impl VerifiedMacAttestation {
612 pub fn attestation(&self) -> &MacAttestationCandidate {
613 &self.attestation
614 }
615
616 pub fn attestation_cid(&self) -> &Cid {
617 &self.evidence.attestation_cid
618 }
619
620 pub fn authority(&self) -> &AcceptedAuthority {
621 &self.evidence.authority
622 }
623}
624
625#[derive(Clone, Debug, Eq, PartialEq)]
626pub struct VerifiedLedgerAttestation {
627 attestation: LedgerAttestationCandidate,
628 evidence: VerifiedEvidence,
629}
630
631impl VerifiedLedgerAttestation {
632 pub fn attestation(&self) -> &LedgerAttestationCandidate {
633 &self.attestation
634 }
635
636 pub fn attestation_cid(&self) -> &Cid {
637 &self.evidence.attestation_cid
638 }
639
640 pub fn authority(&self) -> &AcceptedAuthority {
641 &self.evidence.authority
642 }
643}
644
645#[derive(Clone, Debug, Eq, PartialEq)]
649pub struct DualAttestation {
650 mac: VerifiedMacAttestation,
651 ledger: VerifiedLedgerAttestation,
652 effective_assurance: Assurance,
653}
654
655impl DualAttestation {
656 pub fn verify_and_join(
657 intent: &CanonicalResourceIntent,
658 mac: MacAttestationCandidate,
659 ledger: LedgerAttestationCandidate,
660 mac_verifier: &dyn MacAttestationVerifier,
661 ledger_verifier: &dyn LedgerAttestationVerifier,
662 independence: &dyn AttestationIndependencePolicy,
663 ) -> Result<Self, ContractError> {
664 if mac.intent_digest != intent.digest()
665 || ledger.intent_digest != intent.digest()
666 || mac.intent_digest != ledger.intent_digest
667 || mac.controller != intent.claims().controller
668 || ledger.payer != intent.claims().payer
669 {
670 return Err(ContractError::IntentMismatch);
671 }
672 if !matches!(
673 ledger.phase,
674 LedgerPhase::Posted | LedgerPhase::ZeroCostPosted
675 ) {
676 return Err(ContractError::LedgerNotPosted);
677 }
678 if ledger.unit != intent.claims().unit || ledger.amount > intent.claims().max_charge {
679 return Err(ContractError::ChargeMismatch);
680 }
681 if mac.envelope.purpose != KeyPurpose::MacResourceAttestation
682 || ledger.envelope.purpose != KeyPurpose::LedgerResourceAttestation
683 {
684 return Err(ContractError::WrongKeyPurpose);
685 }
686 if let ControllerRef::AnonymousCapability(binding) = &mac.controller {
687 if binding.intent_digest() != intent.digest() {
688 return Err(ContractError::IntentMismatch);
689 }
690 }
691 if let CapabilityBinding::AnonymousOperationCommitment(binding) = &mac.capability_binding {
692 if binding.intent_digest() != intent.digest() {
693 return Err(ContractError::IntentMismatch);
694 }
695 }
696 if let PayerRef::AnonymousEntitlement(binding) = &ledger.payer {
697 if binding.intent_digest() != intent.digest() {
698 return Err(ContractError::IntentMismatch);
699 }
700 }
701 let mac_evidence = mac_verifier.verify_accepted_current(intent, &mac)?;
702 let ledger_evidence = ledger_verifier.verify_accepted_current(intent, &ledger)?;
703 if mac_evidence.authority.signer != mac.envelope.signer
704 || mac_evidence.authority.key_id != mac.envelope.key_id
705 || mac_evidence.authority.key_epoch != mac.envelope.key_epoch
706 || ledger_evidence.authority.signer != ledger.envelope.signer
707 || ledger_evidence.authority.key_id != ledger.envelope.key_id
708 || ledger_evidence.authority.key_epoch != ledger.envelope.key_epoch
709 {
710 return Err(ContractError::InvalidAttestationEvidence);
711 }
712 independence.require_independence(&mac_evidence.authority, &ledger_evidence.authority)?;
713 let effective_assurance =
714 Assurance::minimum_all([mac_evidence.assurance, ledger_evidence.assurance]);
715 if !intent
716 .claims()
717 .required_assurance
718 .is_met_by(effective_assurance)
719 {
720 return Err(ContractError::AssuranceRequirementNotMet);
721 }
722 Ok(Self {
723 mac: VerifiedMacAttestation {
724 attestation: mac,
725 evidence: mac_evidence,
726 },
727 ledger: VerifiedLedgerAttestation {
728 attestation: ledger,
729 evidence: ledger_evidence,
730 },
731 effective_assurance,
732 })
733 }
734
735 pub const fn effective_assurance(&self) -> Assurance {
736 self.effective_assurance
737 }
738
739 pub fn mac(&self) -> &VerifiedMacAttestation {
740 &self.mac
741 }
742
743 pub fn ledger(&self) -> &VerifiedLedgerAttestation {
744 &self.ledger
745 }
746}
747
748#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
754pub struct FencingToken {
755 pub resource_id: ResourceId,
756 pub registrar_term: u64,
757 pub generation: u64,
758}
759
760#[derive(Clone, Debug, Eq, PartialEq)]
763pub struct FinalizationStatement {
764 pub contract_version: ContractVersion,
765 pub operation_id: OperationId,
766 pub resource_id: ResourceId,
767 pub resource_version: u64,
768 pub intent_digest: IntentDigest,
769 pub fence: FencingToken,
770 pub manifest_cid: Cid,
771 pub content_cid: Option<Cid>,
772 pub mac_attestation_cid: Cid,
773 pub ledger_attestation_cid: Cid,
774 pub private_evidence_commitment: PrivateEvidenceCommitment,
775 pub envelope: SignatureEnvelope,
776}
777
778pub trait FinalizationProofVerifier {
779 fn verify(
782 &self,
783 statement: &FinalizationStatement,
784 dual: &DualAttestation,
785 ) -> Result<(), ContractError>;
786}
787
788#[derive(Clone, Debug, Eq, PartialEq)]
797pub struct FinalizedResource {
798 operation_id: OperationId,
799 resource_id: ResourceId,
800 resource_version: u64,
801 fence: FencingToken,
802 manifest_cid: Cid,
803 content_cid: Option<Cid>,
804 intent_digest: IntentDigest,
805 mac_attestation_cid: Cid,
806 ledger_attestation_cid: Cid,
807 private_evidence_commitment: PrivateEvidenceCommitment,
808}
809
810impl FinalizedResource {
811 pub fn verify(
812 intent: &CanonicalResourceIntent,
813 dual: &DualAttestation,
814 statement: &FinalizationStatement,
815 verifier: &dyn FinalizationProofVerifier,
816 ) -> Result<Self, ContractError> {
817 verifier.verify(statement, dual)?;
818 if statement.envelope.purpose != KeyPurpose::RegistrarFinalization {
819 return Err(ContractError::WrongKeyPurpose);
820 }
821 if statement.intent_digest != intent.digest()
822 || dual.mac().attestation().intent_digest != statement.intent_digest
827 || statement.operation_id != intent.claims().operation_id
828 || statement.resource_id != intent.claims().resource_id
829 || statement.fence.resource_id != statement.resource_id
830 {
831 return Err(ContractError::IntentMismatch);
832 }
833 if statement.mac_attestation_cid != *dual.mac().attestation_cid()
834 || statement.ledger_attestation_cid != *dual.ledger().attestation_cid()
835 {
836 return Err(ContractError::AttestationProvenanceMismatch);
837 }
838 match content_cid_requirement(&intent.claims().resource_kind, intent.claims().operation)? {
839 ContentCidRequirement::Required if statement.content_cid.is_none() => {
840 return Err(ContractError::ContentRequired);
841 }
842 ContentCidRequirement::Forbidden if statement.content_cid.is_some() => {
843 return Err(ContractError::ContentForbidden);
844 }
845 ContentCidRequirement::Required | ContentCidRequirement::Forbidden => {}
846 }
847 Ok(Self {
848 operation_id: statement.operation_id,
849 resource_id: statement.resource_id,
850 resource_version: statement.resource_version,
851 fence: statement.fence,
852 manifest_cid: statement.manifest_cid.clone(),
853 content_cid: statement.content_cid.clone(),
854 intent_digest: statement.intent_digest,
855 mac_attestation_cid: statement.mac_attestation_cid.clone(),
856 ledger_attestation_cid: statement.ledger_attestation_cid.clone(),
857 private_evidence_commitment: statement.private_evidence_commitment.clone(),
858 })
859 }
860
861 pub const fn operation_id(&self) -> OperationId {
862 self.operation_id
863 }
864
865 pub const fn resource_id(&self) -> ResourceId {
866 self.resource_id
867 }
868
869 pub const fn resource_version(&self) -> u64 {
870 self.resource_version
871 }
872
873 pub const fn fence(&self) -> FencingToken {
874 self.fence
875 }
876
877 pub fn manifest_cid(&self) -> &Cid {
878 &self.manifest_cid
879 }
880
881 pub fn content_cid(&self) -> Option<&Cid> {
882 self.content_cid.as_ref()
883 }
884
885 pub fn mac_attestation_cid(&self) -> &Cid {
886 &self.mac_attestation_cid
887 }
888
889 pub fn ledger_attestation_cid(&self) -> &Cid {
890 &self.ledger_attestation_cid
891 }
892
893 pub fn private_evidence_commitment(&self) -> &PrivateEvidenceCommitment {
894 &self.private_evidence_commitment
895 }
896
897 pub fn public_projection(
901 &self,
902 public_evidence_commitment: PublicEvidenceCommitment,
903 ) -> Result<PublicResourceProjection, ContractError> {
904 if public_evidence_commitment.intent_digest() != self.intent_digest {
905 return Err(ContractError::IntentMismatch);
906 }
907 Ok(PublicResourceProjection {
908 resource_id: self.resource_id,
909 resource_version: self.resource_version,
910 manifest_cid: self.manifest_cid.clone(),
911 content_cid: self.content_cid.clone(),
912 public_evidence_commitment,
913 })
914 }
915
916 pub fn publish_effect(
917 &self,
918 entry: Option<ProjectionEntryId>,
919 projection: PublicResourceProjection,
920 ) -> Result<ProjectionEffect, ContractError> {
921 if projection.resource_id != self.resource_id
922 || projection.resource_version != self.resource_version
923 {
924 return Err(ContractError::InvalidProjection);
925 }
926 Ok(ProjectionEffect {
927 operation_id: self.operation_id,
928 resource_id: self.resource_id,
929 resource_version: self.resource_version,
930 fence: self.fence,
931 entry,
932 action: ProjectionAction::Publish(projection),
933 })
934 }
935
936 pub fn withdraw_effect(
937 &self,
938 entry: Option<ProjectionEntryId>,
939 target: WithdrawalTarget,
940 ) -> Result<ProjectionEffect, ContractError> {
941 if target.resource_id != self.resource_id || target.fence.resource_id != self.resource_id {
942 return Err(ContractError::InvalidProjection);
943 }
944 Ok(ProjectionEffect {
945 operation_id: self.operation_id,
946 resource_id: self.resource_id,
947 resource_version: self.resource_version,
948 fence: self.fence,
949 entry,
950 action: ProjectionAction::Withdraw(target),
951 })
952 }
953}
954
955#[derive(Clone, Debug, Eq, PartialEq)]
959pub struct PublicResourceProjection {
960 resource_id: ResourceId,
961 resource_version: u64,
962 manifest_cid: Cid,
963 content_cid: Option<Cid>,
964 public_evidence_commitment: PublicEvidenceCommitment,
965}
966
967impl PublicResourceProjection {
968 pub const fn resource_id(&self) -> ResourceId {
969 self.resource_id
970 }
971
972 pub const fn resource_version(&self) -> u64 {
973 self.resource_version
974 }
975
976 pub fn manifest_cid(&self) -> &Cid {
977 &self.manifest_cid
978 }
979
980 pub fn content_cid(&self) -> Option<&Cid> {
981 self.content_cid.as_ref()
982 }
983
984 pub fn public_evidence_commitment(&self) -> &PublicEvidenceCommitment {
985 &self.public_evidence_commitment
986 }
987}
988
989#[derive(Clone, Debug, Eq, Hash, PartialEq)]
990pub struct ProjectionEntryId(Vec<u8>);
991
992impl ProjectionEntryId {
993 pub fn from_validated_bytes(bytes: Vec<u8>) -> Self {
994 Self(bytes)
995 }
996}
997
998#[derive(Clone, Debug, Eq, PartialEq)]
999pub struct WithdrawalTarget {
1000 pub resource_id: ResourceId,
1001 pub resource_version: u64,
1002 pub fence: FencingToken,
1003}
1004
1005#[derive(Clone, Debug, Eq, PartialEq)]
1006pub enum ProjectionAction {
1007 Publish(PublicResourceProjection),
1008 Withdraw(WithdrawalTarget),
1009}
1010
1011#[derive(Clone, Debug, Eq, PartialEq)]
1014pub struct ProjectionEffect {
1015 operation_id: OperationId,
1016 resource_id: ResourceId,
1017 resource_version: u64,
1018 fence: FencingToken,
1019 entry: Option<ProjectionEntryId>,
1020 action: ProjectionAction,
1021}
1022
1023impl ProjectionEffect {
1024 pub const fn operation_id(&self) -> OperationId {
1025 self.operation_id
1026 }
1027 pub const fn resource_id(&self) -> ResourceId {
1028 self.resource_id
1029 }
1030 pub const fn resource_version(&self) -> u64 {
1031 self.resource_version
1032 }
1033 pub const fn fence(&self) -> FencingToken {
1034 self.fence
1035 }
1036 pub fn entry(&self) -> Option<&ProjectionEntryId> {
1037 self.entry.as_ref()
1038 }
1039 pub const fn action(&self) -> &ProjectionAction {
1040 &self.action
1041 }
1042}
1043
1044#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1045pub enum RegistrarState {
1046 Requested,
1047 MacAuthorized,
1048 LedgerReserved,
1049 Materialized,
1050 LedgerPosted,
1051 Quarantined,
1052 ManualReview,
1053 Finalized,
1054 Voided,
1055 Compensated,
1056 RejectedConflict,
1057}
1058
1059impl RegistrarState {
1060 pub const fn is_terminal(self) -> bool {
1062 matches!(
1063 self,
1064 Self::Finalized | Self::Voided | Self::Compensated | Self::RejectedConflict
1065 )
1066 }
1067
1068 fn matches_resolution(self, resolution: &Resolution) -> bool {
1069 matches!(
1070 (self, resolution),
1071 (Self::Finalized, Resolution::Finalized { .. })
1072 | (Self::Voided, Resolution::Voided { .. })
1073 | (Self::Compensated, Resolution::Compensated { .. })
1074 | (Self::RejectedConflict, Resolution::RejectedConflict { .. })
1075 )
1076 }
1077}
1078
1079#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1080pub enum QuarantineReason {
1081 LedgerOutcomeUnknown,
1082 PostedBeforeFinalization,
1083 FinalizationConflict,
1084 CompensationFailed,
1085 DependencyStateUnverifiable,
1086 InvariantViolation,
1087}
1088
1089#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1094pub enum ConflictAccountingResolution {
1095 Voided { void_transfer_id: TransferId },
1097 Compensated {
1099 compensation_transfer_id: TransferId,
1100 },
1101}
1102
1103#[derive(Clone, Debug, Eq, PartialEq)]
1109pub enum Resolution {
1110 Finalized {
1111 target: ResolutionTarget,
1112 resource_version: u64,
1113 manifest_cid: Cid,
1114 },
1115 Voided {
1116 target: ResolutionTarget,
1117 void_transfer_id: TransferId,
1118 },
1119 Compensated {
1120 target: ResolutionTarget,
1121 compensation_transfer_id: TransferId,
1122 },
1123 RejectedConflict {
1124 target: ResolutionTarget,
1125 winning_operation_id: OperationId,
1126 winning_version: u64,
1127 losing_accounting: ConflictAccountingResolution,
1128 },
1129}
1130
1131#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1135pub struct ResolutionTarget {
1136 pub operation_id: OperationId,
1137 pub resource_id: ResourceId,
1138 pub fence: FencingToken,
1139}
1140
1141impl Resolution {
1142 pub const fn target(&self) -> ResolutionTarget {
1143 match self {
1144 Self::Finalized { target, .. }
1145 | Self::Voided { target, .. }
1146 | Self::Compensated { target, .. }
1147 | Self::RejectedConflict { target, .. } => *target,
1148 }
1149 }
1150}
1151
1152#[derive(Clone, Debug, Eq, PartialEq)]
1153pub struct ResolutionRef {
1154 pub record_cid: Cid,
1155 pub outcome: Resolution,
1156}
1157
1158#[derive(Clone, Debug, Eq, PartialEq)]
1169pub struct RegistrationSnapshot {
1170 operation_id: OperationId,
1171 intent_digest: IntentDigest,
1172 state: RegistrarState,
1173 fencing_token: FencingToken,
1174 quarantine_reason: Option<QuarantineReason>,
1175 resolution: Option<ResolutionRef>,
1176}
1177
1178impl RegistrationSnapshot {
1179 pub fn new(
1180 operation_id: OperationId,
1181 intent_digest: IntentDigest,
1182 state: RegistrarState,
1183 fencing_token: FencingToken,
1184 quarantine_reason: Option<QuarantineReason>,
1185 resolution: Option<ResolutionRef>,
1186 ) -> Result<Self, ContractError> {
1187 let consistent = match &resolution {
1188 Some(reference) => {
1189 state.is_terminal()
1190 && state.matches_resolution(&reference.outcome)
1191 && reference.outcome.target().operation_id == operation_id
1192 && reference.outcome.target().resource_id == fencing_token.resource_id
1193 && reference.outcome.target().fence == fencing_token
1194 }
1195 None => !state.is_terminal(),
1196 };
1197 let quarantine_is_consistent = matches!(
1198 state,
1199 RegistrarState::Quarantined | RegistrarState::ManualReview
1200 ) == quarantine_reason.is_some();
1201 if !consistent || !quarantine_is_consistent {
1202 return Err(ContractError::InconsistentResolution);
1203 }
1204 Ok(Self {
1205 operation_id,
1206 intent_digest,
1207 state,
1208 fencing_token,
1209 quarantine_reason,
1210 resolution,
1211 })
1212 }
1213
1214 pub const fn operation_id(&self) -> OperationId {
1215 self.operation_id
1216 }
1217
1218 pub const fn intent_digest(&self) -> IntentDigest {
1219 self.intent_digest
1220 }
1221
1222 pub const fn state(&self) -> RegistrarState {
1223 self.state
1224 }
1225
1226 pub const fn fencing_token(&self) -> FencingToken {
1227 self.fencing_token
1228 }
1229
1230 pub const fn quarantine_reason(&self) -> Option<QuarantineReason> {
1231 self.quarantine_reason
1232 }
1233
1234 pub const fn resolution(&self) -> Option<&ResolutionRef> {
1235 self.resolution.as_ref()
1236 }
1237}
1238
1239#[derive(Clone, Debug, Eq, PartialEq)]
1240pub enum AuthorityError {
1241 Denied,
1242 Unavailable,
1245 Stale,
1246 InvalidAttestation,
1247 IntentMismatch,
1248}
1249
1250impl fmt::Display for AuthorityError {
1251 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1252 write!(f, "{self:?}")
1253 }
1254}
1255
1256impl std::error::Error for AuthorityError {}
1257
1258#[derive(Clone, Debug, Eq, PartialEq)]
1259pub enum ContractError {
1260 UnsupportedAssurance,
1261 AssuranceRequirementNotMet,
1262 IntentBounds,
1263 NonCanonicalIntent,
1264 DigestMismatch,
1265 IntentMismatch,
1266 LedgerNotPosted,
1267 ChargeMismatch,
1268 WrongKeyPurpose,
1269 InvalidAttestationEvidence,
1270 SharedAttester,
1271 AttestationProvenanceMismatch,
1272 InvalidPredecessor,
1273 InvalidResourceOperation,
1274 ContentRequired,
1275 ContentForbidden,
1276 InvalidProjection,
1277 InvalidFinalizationProof,
1278 StaleProjection,
1279 InconsistentResolution,
1280}
1281
1282impl fmt::Display for ContractError {
1283 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1284 write!(f, "{self:?}")
1285 }
1286}
1287
1288impl std::error::Error for ContractError {}
1289
1290pub trait MacAuthority {
1291 fn attest(
1292 &self,
1293 intent: &CanonicalResourceIntent,
1294 ) -> Result<MacAttestationCandidate, AuthorityError>;
1295 fn revalidate(
1296 &self,
1297 intent: &CanonicalResourceIntent,
1298 attestation: &MacAttestationCandidate,
1299 ) -> Result<(), AuthorityError>;
1300}
1301
1302pub trait EconomicAuthority {
1303 fn reserve(
1304 &self,
1305 intent: &CanonicalResourceIntent,
1306 ) -> Result<LedgerAttestationCandidate, AuthorityError>;
1307
1308 fn post(
1311 &self,
1312 intent: &CanonicalResourceIntent,
1313 reservation: &LedgerAttestationCandidate,
1314 actual_amount: u128,
1315 ) -> Result<LedgerAttestationCandidate, AuthorityError>;
1316
1317 fn void(
1318 &self,
1319 intent: &CanonicalResourceIntent,
1320 reservation: &LedgerAttestationCandidate,
1321 ) -> Result<LedgerAttestationCandidate, AuthorityError>;
1322
1323 fn compensate(
1325 &self,
1326 intent: &CanonicalResourceIntent,
1327 posted: &LedgerAttestationCandidate,
1328 ) -> Result<LedgerAttestationCandidate, AuthorityError>;
1329}
1330
1331pub trait ResourceMaterializer {
1332 type Staged;
1333 type Error;
1334
1335 fn stage(
1336 &self,
1337 operation_id: OperationId,
1338 fence: FencingToken,
1339 ) -> Result<Self::Staged, Self::Error>;
1340 fn seal(&self, staged: &Self::Staged, fence: FencingToken) -> Result<Cid, Self::Error>;
1341 fn discard(&self, staged: &Self::Staged, fence: FencingToken) -> Result<(), Self::Error>;
1342}
1343
1344pub trait ResourceRegistrar {
1345 type Error;
1346
1347 fn begin(&self, intent: CanonicalResourceIntent) -> Result<RegistrationSnapshot, Self::Error>;
1348 fn get(&self, operation_id: OperationId) -> Result<RegistrationSnapshot, Self::Error>;
1349
1350 fn finalize(
1354 &self,
1355 operation_id: OperationId,
1356 fence: FencingToken,
1357 intent: &CanonicalResourceIntent,
1358 attestations: &DualAttestation,
1359 content_cid: Option<&Cid>,
1360 ) -> Result<FinalizedResource, Self::Error>;
1361
1362 fn resolve(
1369 &self,
1370 operation_id: OperationId,
1371 fence: FencingToken,
1372 resolution: Resolution,
1373 ) -> Result<RegistrationSnapshot, Self::Error>;
1374}
1375
1376pub trait ResourcePublisher {
1377 type Error;
1378
1379 fn compare_and_apply(&self, effect: &ProjectionEffect) -> Result<(), Self::Error>;
1382}