sedimentree_core 0.17.0

Sedimentree: a hash-linked CRDT storage structure with fragments, commits, and content-addressed blobs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Loose commit metadata for Sedimentree.

pub mod id;

use alloc::{collections::BTreeSet, vec::Vec};

use id::CommitId;

use crate::{
    blob::{Blob, BlobMeta, has_meta::HasBlobMeta},
    codec::{
        decode::{self, DecodeFields},
        encode::{self, EncodeFields},
        error::{Bijou64Error, BufferTooShort, DecodeError, ReadingType},
        schema::{self, Schema},
    },
    crypto::digest::Digest,
    id::SedimentreeId,
};

/// The smallest unit of metadata in a Sedimentree.
///
/// It includes metadata about the payload blob, plus pointers to any (causal) parents.
/// The `sedimentree_id` field cryptographically binds the commit to a specific
/// document, preventing replay attacks across documents.
///
/// The `head` field is a user-supplied opaque identifier for this commit.
/// It is _not_ computed by Sedimentree — the caller provides it at construction
/// time (e.g., from an Automerge `ChangeHash`). This is the identity used for
/// DAG traversal, fragment boundaries, and sync.
///
/// # Wire Format Limits
///
/// The parent count is encoded as a `u8`, limiting commits to **255 parents**.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct LooseCommit {
    sedimentree_id: SedimentreeId,
    head: CommitId,
    parents: BTreeSet<CommitId>,
    blob_meta: BlobMeta,
}

/// Maximum number of unique parents representable by the wire format.
pub const MAX_PARENTS: usize = u8::MAX as usize;

/// A commit's metadata exceeds a wire-format count limit.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum InvalidLooseCommit {
    /// The parent count must fit in one byte.
    #[error("expected at most {MAX_PARENTS} unique parents, got {actual}")]
    TooManyParents {
        /// Number of unique parents supplied.
        actual: usize,
    },
}

impl LooseCommit {
    /// Constructor for a [`LooseCommit`].
    ///
    /// # Errors
    ///
    /// Returns [`InvalidLooseCommit`] if there are more than [`MAX_PARENTS`] parents.
    pub fn new(
        sedimentree_id: SedimentreeId,
        head: CommitId,
        parents: BTreeSet<CommitId>,
        blob_meta: BlobMeta,
    ) -> Result<Self, InvalidLooseCommit> {
        if parents.len() > MAX_PARENTS {
            return Err(InvalidLooseCommit::TooManyParents {
                actual: parents.len(),
            });
        }
        Ok(Self {
            sedimentree_id,
            head,
            parents,
            blob_meta,
        })
    }

    /// The user-supplied identifier for this commit.
    #[must_use]
    pub const fn head(&self) -> CommitId {
        self.head
    }

    /// The [`SedimentreeId`] this commit belongs to.
    #[must_use]
    pub const fn sedimentree_id(&self) -> SedimentreeId {
        self.sedimentree_id
    }

    /// The (possibly empty) set of parent commits.
    #[must_use]
    pub const fn parents(&self) -> &BTreeSet<CommitId> {
        &self.parents
    }

    /// Metadata about the payload blob.
    #[must_use]
    pub const fn blob_meta(&self) -> &BlobMeta {
        &self.blob_meta
    }
}

impl HasBlobMeta for LooseCommit {
    type Args = (SedimentreeId, CommitId, BTreeSet<CommitId>);
    type Error = InvalidLooseCommit;

    fn blob_meta(&self) -> BlobMeta {
        self.blob_meta
    }

    fn from_args(
        (sedimentree_id, head, parents): Self::Args,
        blob_meta: BlobMeta,
    ) -> Result<Self, Self::Error> {
        Self::new(sedimentree_id, head, parents, blob_meta)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for LooseCommit {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(serde::Deserialize)]
        #[serde(rename = "LooseCommit")]
        struct Fields {
            sedimentree_id: SedimentreeId,
            head: CommitId,
            parents: BTreeSet<CommitId>,
            blob_meta: BlobMeta,
        }
        let fields = Fields::deserialize(deserializer)?;
        Self::new(
            fields.sedimentree_id,
            fields.head,
            fields.parents,
            fields.blob_meta,
        )
        .map_err(serde::de::Error::custom)
    }
}

#[cfg(feature = "arbitrary")]
impl<'a> arbitrary::Arbitrary<'a> for LooseCommit {
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        Self::new(
            u.arbitrary()?,
            u.arbitrary()?,
            u.arbitrary()?,
            u.arbitrary()?,
        )
        .map_err(|_| arbitrary::Error::IncorrectFormat)
    }
}

#[cfg(feature = "bolero")]
impl bolero::generator::TypeGenerator for LooseCommit {
    fn generate<D: bolero::Driver>(driver: &mut D) -> Option<Self> {
        use bolero::generator::ValueGenerator;
        bolero::generator::gen_arbitrary::<Self>().generate(driver)
    }
}

/// Fixed fields size _excluding_ the variable-length blob size:
/// SedimentreeId(32) + Head(32) + Digest<Blob>(32) + |Parents|(1).
const CODEC_FIXED_FIELDS_SIZE: usize = 32 + 32 + 32 + 1;

/// Minimum fields size: fixed fields + smallest bijou64 (1 byte for values 0–247).
const CODEC_MIN_FIELDS_SIZE: usize = CODEC_FIXED_FIELDS_SIZE + 1;

/// Minimum signed message size: `Schema(4) + IssuerVK(32) + MinFields + Signature(64)`.
const CODEC_MIN_SIZE: usize = 4 + 32 + CODEC_MIN_FIELDS_SIZE + 64;

impl Schema for LooseCommit {
    const PREFIX: [u8; 2] = schema::SEDIMENTREE_PREFIX;
    const TYPE_BYTE: u8 = b'C';
    const VERSION: u8 = 0;
}

impl EncodeFields for LooseCommit {
    #[allow(
        clippy::expect_used,
        reason = "all construction paths validate the parent count"
    )]
    fn encode_fields(&self, buf: &mut Vec<u8>) {
        encode::array(self.sedimentree_id.as_bytes(), buf);
        encode::array(self.head.as_bytes(), buf);
        encode::array(self.blob_meta().digest().as_bytes(), buf);

        encode::u8(
            u8::try_from(self.parents().len()).expect("validated parent count"),
            buf,
        );

        bijoux::u64::encode(self.blob_meta().size_bytes(), buf);

        for parent in self.parents() {
            encode::array(parent.as_bytes(), buf);
        }
    }

    fn fields_size(&self) -> usize {
        CODEC_FIXED_FIELDS_SIZE
            + bijoux::u64::encoded_len(self.blob_meta().size_bytes())
            + (self.parents().len() * 32)
    }
}

impl DecodeFields for LooseCommit {
    const MIN_SIGNED_SIZE: usize = CODEC_MIN_SIZE;

    #[allow(
        clippy::expect_used,
        reason = "decoded u8 count cannot exceed the constructor limit"
    )]
    fn try_decode_fields(buf: &[u8]) -> Result<(Self, usize), DecodeError> {
        if buf.len() < CODEC_MIN_FIELDS_SIZE {
            return Err(DecodeError::MessageTooShort {
                type_name: "LooseCommit",
                need: CODEC_MIN_FIELDS_SIZE,
                have: buf.len(),
            });
        }

        let mut offset = 0;

        let sedimentree_id_bytes: [u8; 32] = decode::array(buf, offset)?;
        let sedimentree_id = SedimentreeId::new(sedimentree_id_bytes);
        offset += 32;

        let head_bytes: [u8; 32] = decode::array(buf, offset)?;
        let head = CommitId::new(head_bytes);
        offset += 32;

        let blob_digest_bytes: [u8; 32] = decode::array(buf, offset)?;
        let blob_digest = Digest::<Blob>::force_from_bytes(blob_digest_bytes);
        offset += 32;

        let parent_count = decode::u8(buf, offset)? as usize;
        offset += 1;

        let (blob_size, consumed) = bijoux::u64::decode(buf.get(offset..).unwrap_or_default())
            .map_err(|kind| Bijou64Error { offset, kind })?;
        offset += consumed;

        let parents_size = parent_count * 32;
        if buf.len() < offset + parents_size {
            return Err(BufferTooShort {
                reading: ReadingType::Slice { len: parents_size },
                offset,
                need: parents_size,
                have: buf.len().saturating_sub(offset),
            }
            .into());
        }

        let mut parent_arrays: Vec<[u8; 32]> = Vec::with_capacity(parent_count);
        for _ in 0..parent_count {
            let parent_bytes: [u8; 32] = decode::array(buf, offset)?;
            parent_arrays.push(parent_bytes);
            offset += 32;
        }

        decode::verify_sorted(&parent_arrays)?;

        let parents: BTreeSet<CommitId> = parent_arrays.into_iter().map(CommitId::new).collect();

        let blob_meta = BlobMeta::from_digest_size(blob_digest, blob_size);

        Ok((
            LooseCommit::new(sedimentree_id, head, parents, blob_meta)
                .expect("decoded parent count fits u8"),
            offset,
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;

    fn make_sedimentree_id(byte: u8) -> SedimentreeId {
        SedimentreeId::new([byte; 32])
    }

    #[test]
    fn codec_unsorted_parents_rejected() {
        let id = make_sedimentree_id(0x01);

        let mut buf = Vec::new();
        encode::array(id.as_bytes(), &mut buf);
        encode::array(&[0x10; 32], &mut buf); // head
        encode::array(&[0x20; 32], &mut buf); // blob digest
        encode::u8(2, &mut buf);
        bijoux::u64::encode(1024, &mut buf);
        encode::array(&[0x50; 32], &mut buf);
        encode::array(&[0x30; 32], &mut buf);

        let result = LooseCommit::try_decode_fields(&buf);
        assert!(matches!(result, Err(DecodeError::UnsortedArray(_))));
    }

    #[test]
    fn codec_buffer_too_short_rejected() {
        let buf = vec![0u8; 50];

        let result = LooseCommit::try_decode_fields(&buf);
        assert!(matches!(result, Err(DecodeError::MessageTooShort { .. })));
    }

    #[test]
    fn codec_schema_is_correct() {
        assert_eq!(LooseCommit::SCHEMA, *b"STC\x00");
    }

    #[test]
    fn codec_min_size_is_correct() {
        // Schema(4) + IssuerVK(32) + SedimentreeId(32) + Head(32) + BlobDigest(32) + ParentCnt(1) + BlobSize(bijou64 min=1) + Signature(64)
        assert_eq!(LooseCommit::MIN_SIGNED_SIZE, 198);
    }
}

#[cfg(all(test, feature = "bolero"))]
mod proptests {
    use super::*;
    use crate::codec::encode::Encode;

    /// Round-trip property: encode then decode yields the original value.
    #[test]
    #[allow(clippy::panic)]
    fn codec_round_trip() {
        bolero::check!()
            .with_arbitrary::<LooseCommit>()
            .for_each(|commit| {
                let mut buf = Vec::new();
                commit.encode_fields(&mut buf);
                match LooseCommit::try_decode_fields(&buf) {
                    Ok((decoded, consumed)) => {
                        assert_eq!(&decoded, commit);
                        assert_eq!(consumed, buf.len());
                    }
                    Err(e) => panic!("decode should succeed for valid encoded data: {e}"),
                }
            });
    }

    /// Fuzz the decoder with arbitrary bytes - should never panic.
    #[test]
    fn decode_does_not_panic() {
        bolero::check!()
            .with_arbitrary::<Vec<u8>>()
            .for_each(|bytes| {
                let _result = LooseCommit::try_decode_fields(bytes);
            });
    }

    /// Encoded size matches actual encoded length.
    #[test]
    fn fields_size_matches_encoded_length() {
        bolero::check!()
            .with_arbitrary::<LooseCommit>()
            .for_each(|commit| {
                let mut buf = Vec::new();
                commit.encode_fields(&mut buf);
                assert_eq!(buf.len(), commit.fields_size());
            });
    }

    /// Full encode (with schema) size matches `encoded_size()`.
    #[test]
    fn encoded_size_matches_actual() {
        bolero::check!()
            .with_arbitrary::<LooseCommit>()
            .for_each(|commit| {
                let encoded = commit.encode();
                assert_eq!(encoded.len(), commit.encoded_size());
            });
    }

    /// Decoded struct's `fields_size()` matches the consumed byte count
    /// returned by `try_decode_fields`. `Signed` decoding relies on these
    /// agreeing to locate the signature; a mismatch would corrupt it.
    #[test]
    #[allow(clippy::panic)]
    fn decoded_fields_size_matches_consumed() {
        bolero::check!()
            .with_arbitrary::<LooseCommit>()
            .for_each(|commit| {
                let mut buf = Vec::new();
                commit.encode_fields(&mut buf);
                match LooseCommit::try_decode_fields(&buf) {
                    Ok((decoded, consumed)) => {
                        assert_eq!(
                            consumed,
                            decoded.fields_size(),
                            "consumed byte count must equal decoded struct's fields_size()"
                        );
                    }
                    Err(e) => panic!("decode should succeed for valid encoded data: {e}"),
                }
            });
    }
}