Skip to main content

celestia_types/
sample.rs

1//! Types related to samples.
2//!
3//! Sample in Celestia is understood as a single [`Share`] located at an
4//! index in the particular [`row`] of the [`ExtendedDataSquare`].
5//!
6//! [`row`]: crate::row
7//! [`Share`]: crate::Share
8//! [`ExtendedDataSquare`]: crate::eds::ExtendedDataSquare
9
10use blockstore::block::CidError;
11use bytes::{Buf, BufMut, BytesMut};
12use celestia_proto::shwap::Share as RawShare;
13use cid::CidGeneric;
14use multihash::Multihash;
15use nmt_rs::nmt_proof::NamespaceProof as NmtNamespaceProof;
16use prost::Message;
17use serde::Serialize;
18
19use crate::eds::{AxisType, ExtendedDataSquare};
20use crate::nmt::NamespaceProof;
21use crate::row::{ROW_ID_SIZE, RowId};
22use crate::{DataAvailabilityHeader, Error, Result, Share, bail_validation, bail_verification};
23
24pub use celestia_proto::shwap::Sample as RawSample;
25
26/// Number of bytes needed to represent [`SampleId`] in `multihash`.
27const SAMPLE_ID_SIZE: usize = 12;
28/// The code of the [`SampleId`] hashing algorithm in `multihash`.
29pub const SAMPLE_ID_MULTIHASH_CODE: u64 = 0x7811;
30/// The id of codec used for the [`SampleId`] in `Cid`s.
31pub const SAMPLE_ID_CODEC: u64 = 0x7810;
32
33/// Identifies a particular [`Share`] located in the [`ExtendedDataSquare`].
34///
35/// [`Share`]: crate::Share
36/// [`ExtendedDataSquare`]: crate::eds::ExtendedDataSquare
37#[derive(Debug, PartialEq, Clone, Copy)]
38pub struct SampleId {
39    row_id: RowId,
40    column_index: u16,
41}
42
43/// Represents Sample, with proof of its inclusion
44#[derive(Clone, Debug, Serialize)]
45#[serde(into = "RawSample")]
46pub struct Sample {
47    /// Indication whether proving was done row or column-wise
48    pub proof_type: AxisType,
49    /// Share that is being sampled
50    pub share: Share,
51    /// Proof of the inclusion of the share
52    pub proof: NamespaceProof,
53}
54
55impl Sample {
56    /// Create a new [`Sample`] for the given index of the [`ExtendedDataSquare`] in a block.
57    ///
58    /// `row_index` and `column_index` specifies the [`Share`] position in EDS.
59    /// `proof_type` determines whether proof of inclusion of the [`Share`] should be
60    /// constructed for its row or column.
61    ///
62    /// # Errors
63    ///
64    /// This function will return an error, if:
65    ///
66    /// - `row_index`/`column_index` falls outside the provided [`ExtendedDataSquare`].
67    /// - [`ExtendedDataSquare`] is incorrect (either data shares don't have their namespace
68    ///   prefixed, or [`Share`]s aren't namespace ordered)
69    /// - Block height is zero
70    ///
71    /// # Example
72    ///
73    /// ```no_run
74    /// use celestia_types::AxisType;
75    /// use celestia_types::sample::{Sample, SampleId};
76    /// # use celestia_types::{ExtendedDataSquare, ExtendedHeader};
77    /// #
78    /// # fn get_extended_data_square(height: u64) -> ExtendedDataSquare {
79    /// #    unimplemented!()
80    /// # }
81    /// #
82    /// # fn get_extended_header(height: u64) -> ExtendedHeader {
83    /// #    unimplemented!()
84    /// # }
85    ///
86    /// let block_height = 15;
87    /// let eds = get_extended_data_square(block_height);
88    /// let header = get_extended_header(block_height);
89    ///
90    /// let sample_id = SampleId::new(2, 3, block_height).unwrap();
91    /// let sample = Sample::new(2, 3, AxisType::Row, &eds).unwrap();
92    ///
93    /// sample.verify(sample_id, &header.dah).unwrap();
94    /// ```
95    ///
96    /// [`Share`]: crate::Share
97    /// [`ExtendedDataSquare`]: crate::eds::ExtendedDataSquare
98    pub fn new(
99        row_index: u16,
100        column_index: u16,
101        proof_type: AxisType,
102        eds: &ExtendedDataSquare,
103    ) -> Result<Self> {
104        let share = eds.share(row_index, column_index)?.clone();
105
106        let range_proof = match proof_type {
107            AxisType::Row => eds
108                .row_nmt(row_index)?
109                .build_range_proof(usize::from(column_index)..usize::from(column_index) + 1),
110            AxisType::Col => eds
111                .column_nmt(column_index)?
112                .build_range_proof(usize::from(row_index)..usize::from(row_index) + 1),
113        };
114
115        let proof = NmtNamespaceProof::PresenceProof {
116            proof: range_proof,
117            ignore_max_ns: true,
118        };
119
120        Ok(Sample {
121            share,
122            proof: proof.into(),
123            proof_type,
124        })
125    }
126
127    /// Verify the sample against the root of its row or column from the [`DataAvailabilityHeader`],
128    /// checking that the proof is for the share at the sampled coordinates.
129    pub fn verify(&self, id: SampleId, dah: &DataAvailabilityHeader) -> Result<()> {
130        let (root, index) = match self.proof_type {
131            AxisType::Row => (
132                dah.row_root(id.row_index())
133                    .ok_or(Error::EdsIndexOutOfRange(id.row_index(), 0))?,
134                id.column_index(),
135            ),
136            AxisType::Col => (
137                dah.column_root(id.column_index())
138                    .ok_or(Error::EdsIndexOutOfRange(0, id.column_index()))?,
139                id.row_index(),
140            ),
141        };
142
143        let index = u32::from(index);
144        if self.proof.start_idx() != index || self.proof.end_idx() != index + 1 {
145            bail_verification!(
146                "proof is for range ({}..{}), expected the share at index ({})",
147                self.proof.start_idx(),
148                self.proof.end_idx(),
149                index
150            );
151        }
152
153        self.proof
154            .verify_range(&root, &[&self.share], *self.share.namespace())
155            .map_err(Error::RangeProofError)
156    }
157
158    /// Encode Sample into the raw binary representation.
159    pub fn encode(&self, bytes: &mut BytesMut) {
160        let raw = RawSample::from(self.clone());
161
162        bytes.reserve(raw.encoded_len());
163        raw.encode(bytes).expect("capacity reserved");
164    }
165
166    /// Decode Sample from the binary representation.
167    ///
168    /// # Errors
169    ///
170    /// This function will return an error if protobuf deserialization
171    /// fails and propagate errors from [`Sample::from_raw`].
172    pub fn decode(id: SampleId, buffer: &[u8]) -> Result<Self> {
173        let raw = RawSample::decode(buffer)?;
174        Self::from_raw(id, raw)
175    }
176
177    /// Recover Sample from it's raw representation.
178    ///
179    /// # Errors
180    ///
181    /// This function will return error if proof is missing or invalid shares are not in
182    /// the expected namespace, and will propagate errors from [`Share`] construction.
183    pub fn from_raw(id: SampleId, sample: RawSample) -> Result<Self> {
184        let Some(proof) = sample.proof else {
185            return Err(Error::MissingProof);
186        };
187
188        let proof: NamespaceProof = proof.try_into()?;
189        let proof_type = AxisType::try_from(sample.proof_type)?;
190
191        if proof.is_of_absence() {
192            return Err(Error::WrongProofType);
193        }
194
195        let Some(share) = sample.share else {
196            bail_validation!("missing share");
197        };
198        let Some(square_size) = proof.total_leaves() else {
199            bail_validation!("proof must be for a single leaf of a square");
200        };
201
202        let row_index = id.row_index() as usize;
203        let col_index = id.column_index() as usize;
204        let share = if row_index < square_size / 2 && col_index < square_size / 2 {
205            Share::from_raw(&share.data)?
206        } else {
207            Share::parity(&share.data)?
208        };
209
210        Ok(Sample {
211            proof_type,
212            share,
213            proof,
214        })
215    }
216}
217
218impl From<Sample> for RawSample {
219    fn from(sample: Sample) -> RawSample {
220        RawSample {
221            share: Some(RawShare {
222                data: sample.share.to_vec(),
223            }),
224            proof: Some(sample.proof.into()),
225            proof_type: sample.proof_type as i32,
226        }
227    }
228}
229
230impl SampleId {
231    /// Create a new [`SampleId`] for the given `row_index` and `column_index` of the
232    /// [`ExtendedDataSquare`] in a block.
233    ///
234    /// # Errors
235    ///
236    /// This function will return an error if the block height is zero.
237    ///
238    /// # Example
239    ///
240    /// ```no_run
241    /// use celestia_types::sample::SampleId;
242    ///
243    /// // Consider a 64th share of EDS with block height of 15
244    /// let header_height = 15;
245    /// SampleId::new(2, 1, header_height).unwrap();
246    /// ```
247    ///
248    /// [`Share`]: crate::Share
249    /// [`ExtendedDataSquare`]: crate::eds::ExtendedDataSquare
250    pub fn new(row_index: u16, column_index: u16, block_height: u64) -> Result<Self> {
251        if block_height == 0 {
252            return Err(Error::ZeroBlockHeight);
253        }
254
255        Ok(SampleId {
256            row_id: RowId::new(row_index, block_height)?,
257            column_index,
258        })
259    }
260
261    /// A height of the block which contains the sample.
262    pub fn block_height(&self) -> u64 {
263        self.row_id.block_height()
264    }
265
266    /// Row index of the [`ExtendedDataSquare`] that sample is located on.
267    ///
268    /// [`ExtendedDataSquare`]: crate::eds::ExtendedDataSquare
269    pub fn row_index(&self) -> u16 {
270        self.row_id.index()
271    }
272
273    /// Column index of the [`ExtendedDataSquare`] that sample is located on.
274    ///
275    /// [`ExtendedDataSquare`]: crate::eds::ExtendedDataSquare
276    pub fn column_index(&self) -> u16 {
277        self.column_index
278    }
279
280    /// Encode sample id into the byte representation.
281    pub fn encode(&self, bytes: &mut BytesMut) {
282        bytes.reserve(SAMPLE_ID_SIZE);
283        self.row_id.encode(bytes);
284        bytes.put_u16(self.column_index);
285    }
286
287    /// Decode sample id from the byte representation.
288    pub fn decode(buffer: &[u8]) -> Result<Self> {
289        if buffer.len() != SAMPLE_ID_SIZE {
290            return Err(Error::InvalidLength(buffer.len(), SAMPLE_ID_SIZE));
291        }
292
293        let (row_bytes, mut col_bytes) = buffer.split_at(ROW_ID_SIZE);
294        let row_id = RowId::decode(row_bytes)?;
295        let column_index = col_bytes.get_u16();
296
297        Ok(SampleId {
298            row_id,
299            column_index,
300        })
301    }
302}
303
304impl<const S: usize> TryFrom<&CidGeneric<S>> for SampleId {
305    type Error = CidError;
306
307    fn try_from(cid: &CidGeneric<S>) -> Result<Self, Self::Error> {
308        let codec = cid.codec();
309        if codec != SAMPLE_ID_CODEC {
310            return Err(CidError::InvalidCidCodec(codec));
311        }
312
313        let hash = cid.hash();
314
315        let size = hash.size() as usize;
316        if size != SAMPLE_ID_SIZE {
317            return Err(CidError::InvalidMultihashLength(size));
318        }
319
320        let code = hash.code();
321        if code != SAMPLE_ID_MULTIHASH_CODE {
322            return Err(CidError::InvalidMultihashCode(
323                code,
324                SAMPLE_ID_MULTIHASH_CODE,
325            ));
326        }
327
328        SampleId::decode(hash.digest()).map_err(|e| CidError::InvalidCid(e.to_string()))
329    }
330}
331
332impl<const S: usize> TryFrom<&mut CidGeneric<S>> for SampleId {
333    type Error = CidError;
334
335    fn try_from(cid: &mut CidGeneric<S>) -> Result<Self, Self::Error> {
336        Self::try_from(&*cid)
337    }
338}
339
340impl<const S: usize> TryFrom<CidGeneric<S>> for SampleId {
341    type Error = CidError;
342
343    fn try_from(cid: CidGeneric<S>) -> Result<Self, Self::Error> {
344        Self::try_from(&cid)
345    }
346}
347
348impl From<SampleId> for CidGeneric<SAMPLE_ID_SIZE> {
349    fn from(sample_id: SampleId) -> Self {
350        let mut bytes = BytesMut::with_capacity(SAMPLE_ID_SIZE);
351        // length is correct, so unwrap is safe
352        sample_id.encode(&mut bytes);
353
354        let mh = Multihash::wrap(SAMPLE_ID_MULTIHASH_CODE, &bytes[..]).unwrap();
355
356        CidGeneric::new_v1(SAMPLE_ID_CODEC, mh)
357    }
358}
359
360#[cfg(test)]
361mod tests {
362    use super::*;
363    use crate::test_utils::generate_dummy_eds;
364
365    #[test]
366    fn round_trip() {
367        let sample_id = SampleId::new(5, 10, 100).unwrap();
368        let cid = CidGeneric::from(sample_id);
369
370        let multihash = cid.hash();
371        assert_eq!(multihash.code(), SAMPLE_ID_MULTIHASH_CODE);
372        assert_eq!(multihash.size(), SAMPLE_ID_SIZE as u8);
373
374        let deserialized_sample_id = SampleId::try_from(cid).unwrap();
375        assert_eq!(sample_id, deserialized_sample_id);
376    }
377
378    #[test]
379    fn index_calculation() {
380        let eds = generate_dummy_eds(8);
381
382        Sample::new(0, 0, AxisType::Row, &eds).unwrap();
383        Sample::new(7, 6, AxisType::Row, &eds).unwrap();
384        Sample::new(7, 7, AxisType::Row, &eds).unwrap();
385
386        let sample_err = Sample::new(7, 8, AxisType::Row, &eds).unwrap_err();
387        assert!(matches!(sample_err, Error::EdsIndexOutOfRange(7, 8)));
388
389        let sample_err = Sample::new(12, 3, AxisType::Row, &eds).unwrap_err();
390        assert!(matches!(sample_err, Error::EdsIndexOutOfRange(12, 3)));
391    }
392
393    #[test]
394    fn sample_id_size() {
395        // Size MUST be 12 by the spec.
396        assert_eq!(SAMPLE_ID_SIZE, 12);
397
398        let sample_id = SampleId::new(0, 4, 1).unwrap();
399        let mut bytes = BytesMut::new();
400        sample_id.encode(&mut bytes);
401        assert_eq!(bytes.len(), SAMPLE_ID_SIZE);
402    }
403
404    #[test]
405    fn from_buffer() {
406        let bytes = [
407            0x01, // CIDv1
408            0x90, 0xF0, 0x01, // CID codec = 7810
409            0x91, 0xF0, 0x01, // multihash code = 7811
410            0x0C, // len = SAMPLE_ID_SIZE = 12
411            0, 0, 0, 0, 0, 0, 0, 64, // block height = 64
412            0, 7, // row index = 7
413            0, 5, // sample index = 5
414        ];
415
416        let cid = CidGeneric::<SAMPLE_ID_SIZE>::read_bytes(bytes.as_ref()).unwrap();
417        assert_eq!(cid.codec(), SAMPLE_ID_CODEC);
418        let mh = cid.hash();
419        assert_eq!(mh.code(), SAMPLE_ID_MULTIHASH_CODE);
420        assert_eq!(mh.size(), SAMPLE_ID_SIZE as u8);
421        let sample_id = SampleId::try_from(cid).unwrap();
422        assert_eq!(sample_id.block_height(), 64);
423        assert_eq!(sample_id.row_index(), 7);
424        assert_eq!(sample_id.column_index(), 5);
425    }
426
427    #[test]
428    fn multihash_invalid_code() {
429        let multihash = Multihash::<SAMPLE_ID_SIZE>::wrap(888, &[0; SAMPLE_ID_SIZE]).unwrap();
430        let cid = CidGeneric::<SAMPLE_ID_SIZE>::new_v1(SAMPLE_ID_CODEC, multihash);
431        let code_err = SampleId::try_from(cid).unwrap_err();
432        assert_eq!(
433            code_err,
434            CidError::InvalidMultihashCode(888, SAMPLE_ID_MULTIHASH_CODE)
435        );
436    }
437
438    #[test]
439    fn cid_invalid_codec() {
440        let multihash =
441            Multihash::<SAMPLE_ID_SIZE>::wrap(SAMPLE_ID_MULTIHASH_CODE, &[0; SAMPLE_ID_SIZE])
442                .unwrap();
443        let cid = CidGeneric::<SAMPLE_ID_SIZE>::new_v1(4321, multihash);
444        let codec_err = SampleId::try_from(cid).unwrap_err();
445        assert!(matches!(codec_err, CidError::InvalidCidCodec(4321)));
446    }
447
448    #[test]
449    fn test_roundtrip_verify() {
450        for _ in 0..5 {
451            let eds = generate_dummy_eds(2 << (rand::random::<usize>() % 8));
452            let dah = DataAvailabilityHeader::from_eds(&eds);
453
454            let row_index = rand::random::<u16>() % eds.square_width();
455            let col_index = rand::random::<u16>() % eds.square_width();
456            let proof_type = if rand::random() {
457                AxisType::Row
458            } else {
459                AxisType::Col
460            };
461
462            let id = SampleId::new(row_index, col_index, 1).unwrap();
463            let sample = Sample::new(row_index, col_index, proof_type, &eds).unwrap();
464
465            let mut buf = BytesMut::new();
466            sample.encode(&mut buf);
467            let decoded = Sample::decode(id, &buf).unwrap();
468
469            decoded.verify(id, &dah).unwrap();
470        }
471    }
472
473    #[test]
474    fn verify_rejects_share_from_another_column() {
475        let eds = generate_dummy_eds(8);
476        let dah = DataAvailabilityHeader::from_eds(&eds);
477
478        // genuine share and row proof of (1, 3), presented as the sample of (1, 2)
479        let sample = Sample::new(1, 3, AxisType::Row, &eds).unwrap();
480        let id = SampleId::new(1, 2, 1).unwrap();
481
482        sample.verify(id, &dah).unwrap_err();
483    }
484
485    #[test]
486    fn verify_rejects_share_from_another_row() {
487        let eds = generate_dummy_eds(8);
488        let dah = DataAvailabilityHeader::from_eds(&eds);
489
490        // genuine share and column proof of (3, 1), presented as the sample of (2, 1)
491        let sample = Sample::new(3, 1, AxisType::Col, &eds).unwrap();
492        let id = SampleId::new(2, 1, 1).unwrap();
493
494        sample.verify(id, &dah).unwrap_err();
495    }
496
497    #[test]
498    fn from_raw_rejects_proof_deeper_than_any_square() {
499        let eds = generate_dummy_eds(8);
500        let id = SampleId::new(0, 0, 1).unwrap();
501        let mut sample = Sample::new(0, 0, AxisType::Row, &eds).unwrap();
502
503        sample.proof = NmtNamespaceProof::PresenceProof {
504            proof: crate::nmt::Proof {
505                siblings: vec![crate::nmt::NamespacedHash::default(); usize::BITS as usize],
506                range: 0..1,
507            },
508            ignore_max_ns: true,
509        }
510        .into();
511
512        Sample::from_raw(id, RawSample::from(sample)).unwrap_err();
513    }
514}