Skip to main content

dpp/document/lifecycle/
mod.rs

1//! The lifecycle record of a keep-history document.
2//!
3//! A keep-history document that has been deleted keeps its retained revisions
4//! but loses its current pointer and its index references, so nothing in the
5//! primary-key tree distinguishes it from a document that never existed. The
6//! record supplies that distinction: it exists exactly while the document is
7//! deleted or erasing, names the block time it was deleted at, and, once an
8//! erasure has been authorized, the block time that erasure started and the
9//! revision it started from. Drive stores it beside the document's history and
10//! proof verifiers decode it from a proof.
11
12use crate::ProtocolError;
13use bincode::{Decode, DecodeUntrusted, Encode};
14use derive_more::From;
15use platform_serialization_derive::{
16    PlatformDeserializeTrusted, PlatformDeserializeUntrusted, PlatformSerialize,
17};
18use platform_versioning::PlatformVersioned;
19
20pub mod v0;
21
22pub use v0::DocumentLifecycleRecordV0;
23
24/// Largest number of bytes an encoded record can occupy: the format
25/// discriminant and six variable-length `u64`s at their widest. Estimates
26/// that have to price a record without reading it use this bound.
27pub const DOCUMENT_LIFECYCLE_RECORD_MAX_SIZE: u32 = 1 + 6 * 9;
28
29/// A lifecycle record in whichever layout it was written with.
30#[derive(
31    Debug,
32    Clone,
33    Copy,
34    Encode,
35    Decode,
36    DecodeUntrusted,
37    PlatformDeserializeTrusted,
38    PlatformDeserializeUntrusted,
39    PlatformSerialize,
40    PlatformVersioned,
41    From,
42    PartialEq,
43    Eq,
44)]
45#[cfg_attr(
46    feature = "serde-conversion",
47    derive(serde::Serialize, serde::Deserialize),
48    serde(tag = "$formatVersion")
49)]
50#[platform_serialize(unversioned)]
51pub enum DocumentLifecycleRecord {
52    /// The original layout.
53    #[cfg_attr(feature = "serde-conversion", serde(rename = "0"))]
54    V0(DocumentLifecycleRecordV0),
55}
56
57impl DocumentLifecycleRecord {
58    /// Builds the record a delete writes: the deletion time, what the deleted
59    /// document's revision was and how many revisions its history retained,
60    /// and no erasure.
61    pub fn deleted_at(deleted_at_ms: u64, latest_revision: u64, revision_count: u64) -> Self {
62        DocumentLifecycleRecord::V0(DocumentLifecycleRecordV0 {
63            deleted_at_ms,
64            latest_revision,
65            revision_count,
66            ..Default::default()
67        })
68    }
69
70    /// Block time the document was deleted at.
71    pub fn deleted_at_ms(&self) -> u64 {
72        match self {
73            DocumentLifecycleRecord::V0(v0) => v0.deleted_at_ms,
74        }
75    }
76
77    /// Revision the document carried when it was deleted.
78    pub fn latest_revision(&self) -> u64 {
79        match self {
80            DocumentLifecycleRecord::V0(v0) => v0.latest_revision,
81        }
82    }
83
84    /// Number of revisions the history retained when the document was deleted.
85    pub fn revision_count(&self) -> u64 {
86        match self {
87            DocumentLifecycleRecord::V0(v0) => v0.revision_count,
88        }
89    }
90
91    /// Whether the revisions retained at deletion numbered one through the
92    /// deleted revision without a gap, which is what lets a by-revision read
93    /// map a revision onto a position in the history.
94    ///
95    /// A gap can only come from a history written before protocol 15, where
96    /// two writes in one block overwrote each other's revision; an erase
97    /// removes the newest revisions first and so never opens one.
98    pub fn revisions_are_contiguous(&self) -> bool {
99        self.latest_revision() == self.revision_count()
100    }
101
102    /// Block time an authorized erasure started at, or zero while none has.
103    pub fn erasing_started_at_ms(&self) -> u64 {
104        match self {
105            DocumentLifecycleRecord::V0(v0) => v0.erasing_started_at_ms,
106        }
107    }
108
109    /// Timestamp component of the newest revision retained at erase start.
110    pub fn erasing_from_time_ms(&self) -> u64 {
111        match self {
112            DocumentLifecycleRecord::V0(v0) => v0.erasing_from_time_ms,
113        }
114    }
115
116    /// History sequence of the newest revision retained at erase start.
117    pub fn erasing_from_revision(&self) -> u64 {
118        match self {
119            DocumentLifecycleRecord::V0(v0) => v0.erasing_from_revision,
120        }
121    }
122
123    /// Whether an authorized erasure has already started, which is what lets a
124    /// continuation run without any authorization of its own.
125    ///
126    /// Read off the revision the erasure started from rather than the time it
127    /// started at: a history sequence is one or more for every real revision,
128    /// so zero can only mean the field was never written, while a block time of
129    /// zero is a value a clock could in principle produce.
130    pub fn is_erasing(&self) -> bool {
131        self.erasing_from_revision() != 0
132    }
133
134    /// Whether the record describes a possible deletion and erase start. The
135    /// remaining count belongs to the authenticated history tree and is checked
136    /// by history-page decoders rather than inferred from this record.
137    pub fn is_coherent(&self) -> bool {
138        if self.revision_count() == 0 || self.latest_revision() < self.revision_count() {
139            return false;
140        }
141        if self.is_erasing() {
142            self.erasing_from_revision() == self.latest_revision()
143                && self.erasing_started_at_ms() >= self.deleted_at_ms()
144                && self.erasing_from_time_ms() <= self.deleted_at_ms()
145        } else {
146            self.erasing_started_at_ms() == 0 && self.erasing_from_time_ms() == 0
147        }
148    }
149
150    /// Returns the record an erase start writes over this one, keeping the
151    /// deletion time and recording the erasure it authorizes.
152    pub fn starting_erase_at(
153        &self,
154        erasing_started_at_ms: u64,
155        erasing_from_time_ms: u64,
156        erasing_from_revision: u64,
157    ) -> Self {
158        DocumentLifecycleRecord::V0(DocumentLifecycleRecordV0 {
159            deleted_at_ms: self.deleted_at_ms(),
160            latest_revision: self.latest_revision(),
161            revision_count: self.revision_count(),
162            erasing_started_at_ms,
163            erasing_from_time_ms,
164            erasing_from_revision,
165        })
166    }
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172    use crate::serialization::{PlatformDeserializableUntrusted, PlatformSerializable};
173
174    #[test]
175    fn should_round_trip_every_field() {
176        let record = DocumentLifecycleRecord::deleted_at(7, 12, 11).starting_erase_at(8, 9, 10);
177        let bytes = record.serialize_to_bytes().expect("serialize");
178        let recovered =
179            DocumentLifecycleRecord::deserialize_from_bytes_untrusted(&bytes).expect("round trip");
180        assert_eq!(record, recovered);
181        assert!(recovered.is_erasing());
182        assert_eq!(recovered.latest_revision(), 12);
183        assert_eq!(recovered.revision_count(), 11);
184        assert!(!recovered.revisions_are_contiguous());
185        assert!(DocumentLifecycleRecord::deleted_at(7, 11, 11).revisions_are_contiguous());
186    }
187
188    /// The bound prices a record nobody has read yet, so it must hold for the
189    /// widest values every field can take.
190    #[test]
191    fn should_never_encode_past_the_size_bound() {
192        let widest = DocumentLifecycleRecord::deleted_at(u64::MAX, u64::MAX, u64::MAX)
193            .starting_erase_at(u64::MAX, u64::MAX, u64::MAX);
194        assert_eq!(
195            widest.serialize_to_bytes().expect("serialize").len(),
196            DOCUMENT_LIFECYCLE_RECORD_MAX_SIZE as usize
197        );
198        let narrowest = DocumentLifecycleRecord::deleted_at(0, 0, 0);
199        assert!(
200            narrowest.serialize_to_bytes().expect("serialize").len()
201                <= DOCUMENT_LIFECYCLE_RECORD_MAX_SIZE as usize
202        );
203    }
204
205    #[test]
206    fn should_report_a_record_without_erase_fields_as_deleted_not_erasing() {
207        let record = DocumentLifecycleRecord::deleted_at(7, 1, 1);
208        assert!(!record.is_erasing());
209        assert_eq!(record.erasing_from_revision(), 0);
210    }
211
212    /// A block whose time is zero must not make a committed erasure look like
213    /// one that never started.
214    #[test]
215    fn should_report_an_erasure_started_in_a_block_at_time_zero_as_erasing() {
216        let record = DocumentLifecycleRecord::deleted_at(0, 1, 1).starting_erase_at(0, 0, 1);
217        assert!(record.is_erasing());
218    }
219
220    #[test]
221    fn should_reject_bytes_that_are_not_a_record() {
222        assert!(DocumentLifecycleRecord::deserialize_from_bytes_untrusted(&[]).is_err());
223        assert!(DocumentLifecycleRecord::deserialize_from_bytes_untrusted(&[9]).is_err());
224    }
225}