Skip to main content

ab_core_primitives/block/header/
owned.rs

1//! Data structures related to the owned version of [`BlockHeader`]
2
3// Slow under Miri and these features don't change what the tests exercise, so under Miri they only
4// run with just `alloc` or with all features (like when testing the whole workspace)
5#[cfg(all(
6    test,
7    any(
8        not(miri),
9        not(any(
10            feature = "ed25519",
11            feature = "parallel",
12            feature = "scale-codec",
13            feature = "serde"
14        )),
15        all(
16            feature = "ed25519",
17            feature = "parallel",
18            feature = "scale-codec",
19            feature = "serde"
20        ),
21    ),
22))]
23mod tests;
24
25use crate::block::BlockRoot;
26use crate::block::header::{
27    BeaconChainHeader, BlockHeader, BlockHeaderBeaconChainInfo, BlockHeaderConsensusInfo,
28    BlockHeaderConsensusParameters, BlockHeaderConsistencyError,
29    BlockHeaderFixedConsensusParameters, BlockHeaderPrefix, BlockHeaderResult, BlockHeaderSeal,
30    BlockHeaderSealType, GenericBlockHeader, IntermediateShardHeader, LeafShardHeader,
31    OwnedBlockHeaderConsensusParameters,
32};
33use crate::hashes::Blake3Hash;
34use crate::shard::{NumShardsUnchecked, RealShardKind};
35use ab_aligned_buffer::alignment::Align16;
36use ab_aligned_buffer::{OwnedAlignedBuffer, SharedAlignedBuffer};
37use ab_io_type::trivial_type::TrivialType;
38use core::fmt;
39use core::ops::Deref;
40use derive_more::From;
41use triomphe::Arc;
42use yoke::Yoke;
43
44/// Generic owned block header
45pub trait GenericOwnedBlockHeader:
46    Clone + fmt::Debug + Send + Sync + Into<OwnedBlockHeader> + 'static
47{
48    /// Shard kind
49    const SHARD_KIND: RealShardKind;
50
51    /// Block header
52    type Header<'a>: GenericBlockHeader<'a>
53    where
54        Self: 'a;
55
56    /// Create an owned header from a buffer
57    fn from_buffer(buffer: SharedAlignedBuffer) -> Result<Self, SharedAlignedBuffer>;
58
59    /// Inner buffer with block header contents
60    fn buffer(&self) -> &SharedAlignedBuffer;
61
62    /// Number of clones in memory
63    fn ref_count(&self) -> usize;
64
65    /// Get a regular block header out of the owned version
66    fn header(&self) -> &Self::Header<'_>;
67
68    /// Block root, see [`GenericBlockHeader::root()`] for details
69    fn root(&self) -> impl Deref<Target = BlockRoot> + Send + Sync;
70}
71
72fn append_seal(buffer: &mut OwnedAlignedBuffer, seal: BlockHeaderSeal<'_>) {
73    match seal {
74        BlockHeaderSeal::Ed25519(seal) => {
75            buffer
76                .append(&[BlockHeaderSealType::Ed25519 as u8])
77                .expect("Unsealed headers are only created when the largest seal fits; qed");
78            buffer
79                .append(seal.as_bytes())
80                .expect("Unsealed headers are only created when the largest seal fits; qed");
81        }
82    }
83}
84
85/// Errors for [`OwnedBeaconChainHeader`]
86#[derive(Debug, thiserror::Error)]
87pub enum OwnedBeaconChainHeaderError {
88    /// Header with the largest possible consensus parameters and seal doesn't fit into the buffer
89    /// after the bytes already there
90    #[error("The header is too large")]
91    HeaderTooLarge,
92    /// Header parts are not consistent with each other or with the shard kind
93    #[error("Invalid header parts: {error}")]
94    InvalidParts {
95        /// Block header consistency error
96        #[from]
97        error: BlockHeaderConsistencyError,
98    },
99}
100
101/// An owned version of [`BeaconChainHeader`].
102///
103/// It is correctly aligned in memory and well suited for sending and receiving over the network
104/// efficiently or storing in memory or on disk.
105#[derive(Debug, Clone)]
106pub struct OwnedBeaconChainHeader {
107    inner: Arc<Yoke<BeaconChainHeader<'static>, SharedAlignedBuffer>>,
108}
109
110impl GenericOwnedBlockHeader for OwnedBeaconChainHeader {
111    const SHARD_KIND: RealShardKind = RealShardKind::BeaconChain;
112
113    type Header<'a> = BeaconChainHeader<'a>;
114
115    #[inline(always)]
116    fn from_buffer(buffer: SharedAlignedBuffer) -> Result<Self, SharedAlignedBuffer> {
117        Self::from_buffer(buffer)
118    }
119
120    #[inline(always)]
121    fn buffer(&self) -> &SharedAlignedBuffer {
122        self.buffer()
123    }
124
125    #[inline(always)]
126    fn ref_count(&self) -> usize {
127        self.ref_count()
128    }
129
130    #[inline(always)]
131    fn header(&self) -> &Self::Header<'_> {
132        self.header()
133    }
134
135    #[inline(always)]
136    fn root(&self) -> impl Deref<Target = BlockRoot> + Send + Sync {
137        self.root()
138    }
139}
140
141impl OwnedBeaconChainHeader {
142    /// Max allocation needed by this header
143    pub const MAX_ALLOCATION: u32 = BlockHeaderPrefix::SIZE
144        + BlockHeaderResult::SIZE
145        + BlockHeaderConsensusInfo::SIZE
146        + <Blake3Hash as TrivialType>::SIZE
147        + BlockHeaderConsensusParameters::MAX_SIZE
148        + BlockHeaderSeal::MAX_SIZE;
149
150    /// Create a new [`OwnedBeaconChainHeader`] from its parts.
151    ///
152    /// Returns an error if the parts are not consistent with each other or with the shard kind.
153    pub fn from_parts(
154        prefix: &BlockHeaderPrefix,
155        result: &BlockHeaderResult,
156        consensus_info: &BlockHeaderConsensusInfo,
157        intermediate_shard_blocks_root: &Blake3Hash,
158        consensus_parameters: &OwnedBlockHeaderConsensusParameters,
159    ) -> Result<OwnedBeaconChainHeaderUnsealed, BlockHeaderConsistencyError> {
160        BlockHeader::check_shared_parts(prefix, RealShardKind::BeaconChain)?;
161
162        let mut buffer = OwnedAlignedBuffer::with_capacity(Self::MAX_ALLOCATION);
163
164        Self::append_unsealed(
165            prefix,
166            result,
167            consensus_info,
168            intermediate_shard_blocks_root,
169            consensus_parameters,
170            &mut buffer,
171        )
172        .expect("The header with the largest seal fits into an empty buffer; qed");
173
174        Ok(OwnedBeaconChainHeaderUnsealed {
175            buffer,
176            public_key_hash: consensus_info.solution.public_key_hash,
177        })
178    }
179
180    /// Write a header from its parts into the provided buffer, after the bytes already there.
181    ///
182    /// The length of the buffer must be a multiple of 8 for the header to parse.
183    /// Returns an error if the parts are not consistent with each other or with the shard kind.
184    /// The seal is not attached, the header in the buffer is complete only after
185    /// [`OwnedBeaconChainHeaderUnsealedRef::with_seal()`] attaches it. Nothing is written when an
186    /// error is returned, otherwise the seal is guaranteed to fit.
187    pub fn from_parts_into<'a>(
188        prefix: &BlockHeaderPrefix,
189        result: &BlockHeaderResult,
190        consensus_info: &BlockHeaderConsensusInfo,
191        intermediate_shard_blocks_root: &Blake3Hash,
192        consensus_parameters: &OwnedBlockHeaderConsensusParameters,
193        buffer: &'a mut OwnedAlignedBuffer,
194    ) -> Result<OwnedBeaconChainHeaderUnsealedRef<'a>, OwnedBeaconChainHeaderError> {
195        BlockHeader::check_shared_parts(prefix, RealShardKind::BeaconChain)?;
196
197        let header_offset = buffer.len();
198
199        Self::append_unsealed(
200            prefix,
201            result,
202            consensus_info,
203            intermediate_shard_blocks_root,
204            consensus_parameters,
205            buffer,
206        )?;
207
208        Ok(OwnedBeaconChainHeaderUnsealedRef {
209            buffer,
210            header_offset,
211            public_key_hash: consensus_info.solution.public_key_hash,
212        })
213    }
214
215    /// Append everything except the seal to the buffer
216    fn append_unsealed(
217        prefix: &BlockHeaderPrefix,
218        result: &BlockHeaderResult,
219        consensus_info: &BlockHeaderConsensusInfo,
220        intermediate_shard_blocks_root: &Blake3Hash,
221        consensus_parameters: &OwnedBlockHeaderConsensusParameters,
222        buffer: &mut OwnedAlignedBuffer,
223    ) -> Result<(), OwnedBeaconChainHeaderError> {
224        let OwnedBlockHeaderConsensusParameters {
225            fixed_parameters,
226            super_segment_root,
227            next_solution_range,
228            pot_parameters_change,
229        } = consensus_parameters;
230        let BlockHeaderFixedConsensusParameters {
231            solution_range,
232            slot_iterations,
233            num_shards,
234        } = fixed_parameters;
235
236        // The header with the largest seal must fit after the bytes already in the buffer, so
237        // that neither the appends below nor the seal appended later can fail. The length of a
238        // buffer is never larger than its maximum capacity.
239        if OwnedAlignedBuffer::<Align16>::MAX_CAPACITY - buffer.len() < Self::MAX_ALLOCATION {
240            return Err(OwnedBeaconChainHeaderError::HeaderTooLarge);
241        }
242        buffer
243            .append(prefix.as_bytes())
244            .expect("Checked size above; qed");
245        buffer
246            .append(result.as_bytes())
247            .expect("Checked size above; qed");
248        buffer
249            .append(consensus_info.as_bytes())
250            .expect("Checked size above; qed");
251        buffer
252            .append(intermediate_shard_blocks_root.as_bytes())
253            .expect("Checked size above; qed");
254        // TODO: Would be nice for `OwnedBlockHeaderConsensusParameters` to have API to write this
255        //  by itself
256        {
257            buffer
258                .append(&solution_range.to_bytes())
259                .expect("Checked size above; qed");
260            buffer
261                .append(&slot_iterations.get().to_le_bytes())
262                .expect("Checked size above; qed");
263            buffer
264                .append(NumShardsUnchecked::from(*num_shards).as_bytes())
265                .expect("Checked size above; qed");
266
267            let bitflags = {
268                let mut bitflags = 0u8;
269
270                if super_segment_root.is_some() {
271                    bitflags |= BlockHeaderConsensusParameters::SUPER_SEGMENT_ROOT_MASK;
272                }
273                if next_solution_range.is_some() {
274                    bitflags |= BlockHeaderConsensusParameters::NEXT_SOLUTION_RANGE_MASK;
275                }
276                if pot_parameters_change.is_some() {
277                    bitflags |= BlockHeaderConsensusParameters::POT_PARAMETERS_CHANGE_MASK;
278                }
279
280                bitflags
281            };
282
283            buffer.append(&[bitflags]).expect("Checked size above; qed");
284
285            if let Some(super_segment_root) = super_segment_root {
286                buffer
287                    .append(super_segment_root.as_ref())
288                    .expect("Checked size above; qed");
289            }
290
291            if let Some(next_solution_range) = next_solution_range {
292                buffer
293                    .append(&next_solution_range.to_bytes())
294                    .expect("Checked size above; qed");
295            }
296
297            if let Some(pot_parameters_change) = pot_parameters_change {
298                buffer
299                    .append(&pot_parameters_change.slot.to_bytes())
300                    .expect("Checked size above; qed");
301                buffer
302                    .append(&pot_parameters_change.slot_iterations.get().to_le_bytes())
303                    .expect("Checked size above; qed");
304                buffer
305                    .append(pot_parameters_change.entropy.as_ref())
306                    .expect("Checked size above; qed");
307            }
308        }
309
310        Ok(())
311    }
312
313    /// Create an owned header from a buffer
314    #[inline]
315    pub fn from_buffer(buffer: SharedAlignedBuffer) -> Result<Self, SharedAlignedBuffer> {
316        // TODO: Cloning is cheap, but will not be necessary if/when this is resolved:
317        //  https://github.com/unicode-org/icu4x/issues/6665
318        let inner = Yoke::try_attach_to_cart(buffer.clone(), |buffer| {
319            let Some((header, extra_bytes)) = BeaconChainHeader::try_from_bytes(buffer) else {
320                return Err(());
321            };
322            if !extra_bytes.is_empty() {
323                return Err(());
324            }
325
326            Ok(header)
327        })
328        .map_err(move |()| buffer)?;
329
330        Ok(Self {
331            inner: Arc::new(inner),
332        })
333    }
334
335    /// Create an owned header from the beginning of a buffer.
336    ///
337    /// Bytes after the header don't belong to it, the buffer of the owned header ends where the
338    /// header ends, but its allocation still holds them. Returns the buffer back if it doesn't
339    /// start with a header.
340    pub(crate) fn from_buffer_start(
341        buffer: SharedAlignedBuffer,
342    ) -> Result<Self, SharedAlignedBuffer> {
343        let mut header_len = 0;
344        // TODO: Cloning is cheap, but will not be necessary if/when this is resolved:
345        //  https://github.com/unicode-org/icu4x/issues/6665
346        let inner = Yoke::try_attach_to_cart(buffer.clone(), |buffer| {
347            let Some((header, remainder)) = BeaconChainHeader::try_from_bytes(buffer) else {
348                return Err(());
349            };
350            header_len = buffer.len() - remainder.len();
351
352            Ok(header)
353        })
354        .map_err(move |()| buffer)?;
355        let header_len = u32::try_from(header_len)
356            .expect("Header is a part of the buffer, whose length is `u32`; qed");
357
358        // SAFETY: Truncation only shortens the buffer, which keeps referencing the same bytes of
359        // the same allocation. The header is not empty, so the allocation is kept, and it only
360        // references bytes within its length.
361        let inner = unsafe {
362            inner.replace_cart(|mut buffer| {
363                buffer.truncate(header_len);
364                buffer
365            })
366        };
367
368        Ok(Self {
369            inner: Arc::new(inner),
370        })
371    }
372
373    /// Inner buffer with block header contents
374    #[inline(always)]
375    pub fn buffer(&self) -> &SharedAlignedBuffer {
376        self.inner.backing_cart()
377    }
378
379    /// Number of clones in memory
380    #[inline(always)]
381    pub fn ref_count(&self) -> usize {
382        Arc::count(&self.inner)
383    }
384
385    /// Get [`BeaconChainHeader`] out of [`OwnedBeaconChainHeader`]
386    #[inline(always)]
387    pub fn header(&self) -> &BeaconChainHeader<'_> {
388        self.inner.get()
389    }
390
391    /// Block root, see [`BeaconChainHeader::root()`] for details
392    #[inline(always)]
393    pub fn root(&self) -> impl Deref<Target = BlockRoot> + Send + Sync {
394        self.header().root()
395    }
396}
397
398/// Owned beacon chain block header, which is not sealed yet
399#[derive(Debug, Clone)]
400pub struct OwnedBeaconChainHeaderUnsealed {
401    buffer: OwnedAlignedBuffer,
402    /// Public key hash of the solution, the seal must correspond to it
403    public_key_hash: Blake3Hash,
404}
405
406impl OwnedBeaconChainHeaderUnsealed {
407    /// Hash of the block before seal is applied to it
408    #[inline(always)]
409    pub fn pre_seal_hash(&self) -> Blake3Hash {
410        Blake3Hash::from(blake3::hash(self.buffer.as_slice()))
411    }
412
413    /// Add seal and return [`OwnedBeaconChainHeader`].
414    ///
415    /// Returns an error if the seal doesn't correspond to the public key hash of the solution.
416    pub fn with_seal(
417        self,
418        seal: BlockHeaderSeal<'_>,
419    ) -> Result<OwnedBeaconChainHeader, BlockHeaderConsistencyError> {
420        let Self {
421            mut buffer,
422            public_key_hash,
423        } = self;
424        BlockHeader::check_seal(&public_key_hash, seal)?;
425        append_seal(&mut buffer, seal);
426
427        let header = OwnedBeaconChainHeader::from_buffer(buffer.into_shared())
428            .expect("`from_parts()` checked the parts it wrote, the seal is checked above; qed");
429
430        Ok(header)
431    }
432}
433
434/// Beacon chain block header written into a buffer by
435/// [`OwnedBeaconChainHeader::from_parts_into()`], which is not sealed yet.
436///
437/// The header in the buffer is not complete until [`Self::with_seal()`] attaches the seal.
438#[derive(Debug)]
439#[must_use = "The header in the buffer is not complete until `with_seal()` attaches the seal"]
440pub struct OwnedBeaconChainHeaderUnsealedRef<'a> {
441    buffer: &'a mut OwnedAlignedBuffer,
442    header_offset: u32,
443    /// Public key hash of the solution, the seal must correspond to it
444    public_key_hash: Blake3Hash,
445}
446
447impl OwnedBeaconChainHeaderUnsealedRef<'_> {
448    /// Hash of the block before seal is applied to it
449    #[inline(always)]
450    pub fn pre_seal_hash(&self) -> Blake3Hash {
451        let header_bytes = self
452            .buffer
453            .as_slice()
454            .get(self.header_offset as usize..)
455            .expect("The buffer only grew since `header_offset` was its length; qed");
456        Blake3Hash::from(blake3::hash(header_bytes))
457    }
458
459    /// Attach the seal after the header in the buffer, which completes the header.
460    ///
461    /// Returns an error if the seal doesn't correspond to the public key hash of the solution. The
462    /// seal is not attached then, and the buffer ends with the unsealed header, which must not be
463    /// treated as a complete header.
464    #[inline(always)]
465    pub fn with_seal(self, seal: BlockHeaderSeal<'_>) -> Result<(), BlockHeaderConsistencyError> {
466        let Self {
467            buffer,
468            header_offset: _,
469            public_key_hash,
470        } = self;
471        BlockHeader::check_seal(&public_key_hash, seal)?;
472        append_seal(buffer, seal);
473
474        Ok(())
475    }
476}
477
478/// Errors for [`OwnedIntermediateShardHeader`]
479#[derive(Debug, thiserror::Error)]
480pub enum OwnedIntermediateShardHeaderError {
481    /// Header doesn't fit into the buffer after the bytes already there
482    #[error("The header is too large")]
483    HeaderTooLarge,
484    /// Header parts are not consistent with each other or with the shard kind
485    #[error("Invalid header parts: {error}")]
486    InvalidParts {
487        /// Block header consistency error
488        #[from]
489        error: BlockHeaderConsistencyError,
490    },
491}
492
493/// An owned version of [`IntermediateShardHeader`].
494///
495/// It is correctly aligned in memory and well suited for sending and receiving over the network
496/// efficiently or storing in memory or on disk.
497#[derive(Debug, Clone)]
498pub struct OwnedIntermediateShardHeader {
499    inner: Arc<Yoke<IntermediateShardHeader<'static>, SharedAlignedBuffer>>,
500}
501
502impl GenericOwnedBlockHeader for OwnedIntermediateShardHeader {
503    const SHARD_KIND: RealShardKind = RealShardKind::IntermediateShard;
504
505    type Header<'a> = IntermediateShardHeader<'a>;
506
507    #[inline(always)]
508    fn from_buffer(buffer: SharedAlignedBuffer) -> Result<Self, SharedAlignedBuffer> {
509        Self::from_buffer(buffer)
510    }
511
512    #[inline(always)]
513    fn buffer(&self) -> &SharedAlignedBuffer {
514        self.buffer()
515    }
516
517    #[inline(always)]
518    fn ref_count(&self) -> usize {
519        self.ref_count()
520    }
521
522    #[inline(always)]
523    fn header(&self) -> &Self::Header<'_> {
524        self.header()
525    }
526
527    #[inline(always)]
528    fn root(&self) -> impl Deref<Target = BlockRoot> + Send + Sync {
529        self.root()
530    }
531}
532
533impl OwnedIntermediateShardHeader {
534    /// Max allocation needed by this header
535    pub const MAX_ALLOCATION: u32 = BlockHeaderPrefix::SIZE
536        + BlockHeaderResult::SIZE
537        + BlockHeaderConsensusInfo::SIZE
538        + BlockHeaderBeaconChainInfo::SIZE
539        + <Blake3Hash as TrivialType>::SIZE
540        + BlockHeaderSeal::MAX_SIZE;
541
542    /// Create a new [`OwnedIntermediateShardHeader`] from its parts.
543    ///
544    /// Returns an error if the parts are not consistent with each other or with the shard kind.
545    pub fn from_parts(
546        prefix: &BlockHeaderPrefix,
547        result: &BlockHeaderResult,
548        consensus_info: &BlockHeaderConsensusInfo,
549        beacon_chain_info: &BlockHeaderBeaconChainInfo,
550        leaf_shard_blocks_root: &Blake3Hash,
551    ) -> Result<OwnedIntermediateShardHeaderUnsealed, BlockHeaderConsistencyError> {
552        BlockHeader::check_shared_parts(prefix, RealShardKind::IntermediateShard)?;
553
554        let mut buffer = OwnedAlignedBuffer::with_capacity(Self::MAX_ALLOCATION);
555
556        Self::append_unsealed(
557            prefix,
558            result,
559            consensus_info,
560            beacon_chain_info,
561            leaf_shard_blocks_root,
562            &mut buffer,
563        )
564        .expect("The header with the largest seal fits into an empty buffer; qed");
565
566        Ok(OwnedIntermediateShardHeaderUnsealed {
567            buffer,
568            public_key_hash: consensus_info.solution.public_key_hash,
569        })
570    }
571
572    /// Write a header from its parts into the provided buffer, after the bytes already there.
573    ///
574    /// The length of the buffer must be a multiple of 8 for the header to parse.
575    /// Returns an error if the parts are not consistent with each other or with the shard kind.
576    /// The seal is not attached, the header in the buffer is complete only after
577    /// [`OwnedIntermediateShardHeaderUnsealedRef::with_seal()`] attaches it. Nothing is written
578    /// when an error is returned, otherwise the seal is guaranteed to fit.
579    pub fn from_parts_into<'a>(
580        prefix: &BlockHeaderPrefix,
581        result: &BlockHeaderResult,
582        consensus_info: &BlockHeaderConsensusInfo,
583        beacon_chain_info: &BlockHeaderBeaconChainInfo,
584        leaf_shard_blocks_root: &Blake3Hash,
585        buffer: &'a mut OwnedAlignedBuffer,
586    ) -> Result<OwnedIntermediateShardHeaderUnsealedRef<'a>, OwnedIntermediateShardHeaderError>
587    {
588        BlockHeader::check_shared_parts(prefix, RealShardKind::IntermediateShard)?;
589
590        let header_offset = buffer.len();
591
592        Self::append_unsealed(
593            prefix,
594            result,
595            consensus_info,
596            beacon_chain_info,
597            leaf_shard_blocks_root,
598            buffer,
599        )?;
600
601        Ok(OwnedIntermediateShardHeaderUnsealedRef {
602            buffer,
603            header_offset,
604            public_key_hash: consensus_info.solution.public_key_hash,
605        })
606    }
607
608    /// Append everything except the seal to the buffer
609    fn append_unsealed(
610        prefix: &BlockHeaderPrefix,
611        result: &BlockHeaderResult,
612        consensus_info: &BlockHeaderConsensusInfo,
613        beacon_chain_info: &BlockHeaderBeaconChainInfo,
614        leaf_shard_blocks_root: &Blake3Hash,
615        buffer: &mut OwnedAlignedBuffer,
616    ) -> Result<(), OwnedIntermediateShardHeaderError> {
617        // The header with the largest seal must fit after the bytes already in the buffer, so
618        // that neither the appends below nor the seal appended later can fail. The length of a
619        // buffer is never larger than its maximum capacity.
620        if OwnedAlignedBuffer::<Align16>::MAX_CAPACITY - buffer.len() < Self::MAX_ALLOCATION {
621            return Err(OwnedIntermediateShardHeaderError::HeaderTooLarge);
622        }
623        buffer
624            .append(prefix.as_bytes())
625            .expect("Checked size above; qed");
626        buffer
627            .append(result.as_bytes())
628            .expect("Checked size above; qed");
629        buffer
630            .append(consensus_info.as_bytes())
631            .expect("Checked size above; qed");
632        buffer
633            .append(beacon_chain_info.as_bytes())
634            .expect("Checked size above; qed");
635        buffer
636            .append(leaf_shard_blocks_root.as_bytes())
637            .expect("Checked size above; qed");
638
639        Ok(())
640    }
641
642    /// Create an owned header from a buffer
643    #[inline]
644    pub fn from_buffer(buffer: SharedAlignedBuffer) -> Result<Self, SharedAlignedBuffer> {
645        // TODO: Cloning is cheap, but will not be necessary if/when this is resolved:
646        //  https://github.com/unicode-org/icu4x/issues/6665
647        let inner = Yoke::try_attach_to_cart(buffer.clone(), |buffer| {
648            let Some((header, extra_bytes)) = IntermediateShardHeader::try_from_bytes(buffer)
649            else {
650                return Err(());
651            };
652            if !extra_bytes.is_empty() {
653                return Err(());
654            }
655
656            Ok(header)
657        })
658        .map_err(move |()| buffer)?;
659
660        Ok(Self {
661            inner: Arc::new(inner),
662        })
663    }
664
665    /// Create an owned header from the beginning of a buffer.
666    ///
667    /// Bytes after the header don't belong to it, the buffer of the owned header ends where the
668    /// header ends, but its allocation still holds them. Returns the buffer back if it doesn't
669    /// start with a header.
670    pub(crate) fn from_buffer_start(
671        buffer: SharedAlignedBuffer,
672    ) -> Result<Self, SharedAlignedBuffer> {
673        let mut header_len = 0;
674        // TODO: Cloning is cheap, but will not be necessary if/when this is resolved:
675        //  https://github.com/unicode-org/icu4x/issues/6665
676        let inner = Yoke::try_attach_to_cart(buffer.clone(), |buffer| {
677            let Some((header, remainder)) = IntermediateShardHeader::try_from_bytes(buffer) else {
678                return Err(());
679            };
680            header_len = buffer.len() - remainder.len();
681
682            Ok(header)
683        })
684        .map_err(move |()| buffer)?;
685        let header_len = u32::try_from(header_len)
686            .expect("Header is a part of the buffer, whose length is `u32`; qed");
687
688        // SAFETY: Truncation only shortens the buffer, which keeps referencing the same bytes of
689        // the same allocation. The header is not empty, so the allocation is kept, and it only
690        // references bytes within its length.
691        let inner = unsafe {
692            inner.replace_cart(|mut buffer| {
693                buffer.truncate(header_len);
694                buffer
695            })
696        };
697
698        Ok(Self {
699            inner: Arc::new(inner),
700        })
701    }
702
703    /// Inner buffer with block header contents
704    #[inline(always)]
705    pub fn buffer(&self) -> &SharedAlignedBuffer {
706        self.inner.backing_cart()
707    }
708
709    /// Number of clones in memory
710    #[inline(always)]
711    pub fn ref_count(&self) -> usize {
712        Arc::count(&self.inner)
713    }
714
715    /// Get [`IntermediateShardHeader`] out of [`OwnedIntermediateShardHeader`]
716    #[inline(always)]
717    pub fn header(&self) -> &IntermediateShardHeader<'_> {
718        self.inner.get()
719    }
720
721    /// Block root, see [`IntermediateShardHeader::root()`] for details
722    #[inline(always)]
723    pub fn root(&self) -> impl Deref<Target = BlockRoot> + Send + Sync {
724        self.header().root()
725    }
726}
727
728/// Owned intermediate shard block header, which is not sealed yet
729#[derive(Debug, Clone)]
730pub struct OwnedIntermediateShardHeaderUnsealed {
731    buffer: OwnedAlignedBuffer,
732    /// Public key hash of the solution, the seal must correspond to it
733    public_key_hash: Blake3Hash,
734}
735
736impl OwnedIntermediateShardHeaderUnsealed {
737    /// Hash of the block before seal is applied to it
738    #[inline(always)]
739    pub fn pre_seal_hash(&self) -> Blake3Hash {
740        Blake3Hash::from(blake3::hash(self.buffer.as_slice()))
741    }
742
743    /// Add seal and return [`OwnedIntermediateShardHeader`].
744    ///
745    /// Returns an error if the seal doesn't correspond to the public key hash of the solution.
746    pub fn with_seal(
747        self,
748        seal: BlockHeaderSeal<'_>,
749    ) -> Result<OwnedIntermediateShardHeader, BlockHeaderConsistencyError> {
750        let Self {
751            mut buffer,
752            public_key_hash,
753        } = self;
754        BlockHeader::check_seal(&public_key_hash, seal)?;
755        append_seal(&mut buffer, seal);
756
757        let header = OwnedIntermediateShardHeader::from_buffer(buffer.into_shared())
758            .expect("`from_parts()` checked the parts it wrote, the seal is checked above; qed");
759
760        Ok(header)
761    }
762}
763
764/// Intermediate shard block header written into a buffer by
765/// [`OwnedIntermediateShardHeader::from_parts_into()`], which is not sealed yet.
766///
767/// The header in the buffer is not complete until [`Self::with_seal()`] attaches the seal.
768#[derive(Debug)]
769#[must_use = "The header in the buffer is not complete until `with_seal()` attaches the seal"]
770pub struct OwnedIntermediateShardHeaderUnsealedRef<'a> {
771    buffer: &'a mut OwnedAlignedBuffer,
772    header_offset: u32,
773    /// Public key hash of the solution, the seal must correspond to it
774    public_key_hash: Blake3Hash,
775}
776
777impl OwnedIntermediateShardHeaderUnsealedRef<'_> {
778    /// Hash of the block before seal is applied to it
779    #[inline(always)]
780    pub fn pre_seal_hash(&self) -> Blake3Hash {
781        let header_bytes = self
782            .buffer
783            .as_slice()
784            .get(self.header_offset as usize..)
785            .expect("The buffer only grew since `header_offset` was its length; qed");
786        Blake3Hash::from(blake3::hash(header_bytes))
787    }
788
789    /// Attach the seal after the header in the buffer, which completes the header.
790    ///
791    /// Returns an error if the seal doesn't correspond to the public key hash of the solution. The
792    /// seal is not attached then, and the buffer ends with the unsealed header, which must not be
793    /// treated as a complete header.
794    #[inline(always)]
795    pub fn with_seal(self, seal: BlockHeaderSeal<'_>) -> Result<(), BlockHeaderConsistencyError> {
796        let Self {
797            buffer,
798            header_offset: _,
799            public_key_hash,
800        } = self;
801        BlockHeader::check_seal(&public_key_hash, seal)?;
802        append_seal(buffer, seal);
803
804        Ok(())
805    }
806}
807
808/// Errors for [`OwnedLeafShardHeader`]
809#[derive(Debug, thiserror::Error)]
810pub enum OwnedLeafShardHeaderError {
811    /// Header doesn't fit into the buffer after the bytes already there
812    #[error("The header is too large")]
813    HeaderTooLarge,
814    /// Header parts are not consistent with each other or with the shard kind
815    #[error("Invalid header parts: {error}")]
816    InvalidParts {
817        /// Block header consistency error
818        #[from]
819        error: BlockHeaderConsistencyError,
820    },
821}
822
823/// An owned version of [`LeafShardHeader`].
824///
825/// It is correctly aligned in memory and well suited for sending and receiving over the network
826/// efficiently or storing in memory or on disk.
827#[derive(Debug, Clone)]
828pub struct OwnedLeafShardHeader {
829    inner: Arc<Yoke<LeafShardHeader<'static>, SharedAlignedBuffer>>,
830}
831
832impl GenericOwnedBlockHeader for OwnedLeafShardHeader {
833    const SHARD_KIND: RealShardKind = RealShardKind::LeafShard;
834
835    type Header<'a> = LeafShardHeader<'a>;
836
837    #[inline(always)]
838    fn from_buffer(buffer: SharedAlignedBuffer) -> Result<Self, SharedAlignedBuffer> {
839        Self::from_buffer(buffer)
840    }
841
842    #[inline(always)]
843    fn buffer(&self) -> &SharedAlignedBuffer {
844        self.buffer()
845    }
846
847    #[inline(always)]
848    fn ref_count(&self) -> usize {
849        self.ref_count()
850    }
851
852    #[inline(always)]
853    fn header(&self) -> &Self::Header<'_> {
854        self.header()
855    }
856
857    #[inline(always)]
858    fn root(&self) -> impl Deref<Target = BlockRoot> + Send + Sync {
859        self.root()
860    }
861}
862
863impl OwnedLeafShardHeader {
864    /// Max allocation needed by this header
865    pub const MAX_ALLOCATION: u32 = BlockHeaderPrefix::SIZE
866        + BlockHeaderResult::SIZE
867        + BlockHeaderConsensusInfo::SIZE
868        + BlockHeaderBeaconChainInfo::SIZE
869        + BlockHeaderSeal::MAX_SIZE;
870
871    /// Create a new [`OwnedLeafShardHeader`] from its parts.
872    ///
873    /// Returns an error if the parts are not consistent with each other or with the shard kind.
874    pub fn from_parts(
875        prefix: &BlockHeaderPrefix,
876        result: &BlockHeaderResult,
877        consensus_info: &BlockHeaderConsensusInfo,
878        beacon_chain_info: &BlockHeaderBeaconChainInfo,
879    ) -> Result<OwnedLeafShardHeaderUnsealed, BlockHeaderConsistencyError> {
880        BlockHeader::check_shared_parts(prefix, RealShardKind::LeafShard)?;
881
882        let mut buffer = OwnedAlignedBuffer::with_capacity(Self::MAX_ALLOCATION);
883
884        Self::append_unsealed(
885            prefix,
886            result,
887            consensus_info,
888            beacon_chain_info,
889            &mut buffer,
890        )
891        .expect("The header with the largest seal fits into an empty buffer; qed");
892
893        Ok(OwnedLeafShardHeaderUnsealed {
894            buffer,
895            public_key_hash: consensus_info.solution.public_key_hash,
896        })
897    }
898
899    /// Write a header from its parts into the provided buffer, after the bytes already there.
900    ///
901    /// The length of the buffer must be a multiple of 8 for the header to parse.
902    /// Returns an error if the parts are not consistent with each other or with the shard kind.
903    /// The seal is not attached, the header in the buffer is complete only after
904    /// [`OwnedLeafShardHeaderUnsealedRef::with_seal()`] attaches it. Nothing is written when an
905    /// error is returned, otherwise the seal is guaranteed to fit.
906    pub fn from_parts_into<'a>(
907        prefix: &BlockHeaderPrefix,
908        result: &BlockHeaderResult,
909        consensus_info: &BlockHeaderConsensusInfo,
910        beacon_chain_info: &BlockHeaderBeaconChainInfo,
911        buffer: &'a mut OwnedAlignedBuffer,
912    ) -> Result<OwnedLeafShardHeaderUnsealedRef<'a>, OwnedLeafShardHeaderError> {
913        BlockHeader::check_shared_parts(prefix, RealShardKind::LeafShard)?;
914
915        let header_offset = buffer.len();
916
917        Self::append_unsealed(prefix, result, consensus_info, beacon_chain_info, buffer)?;
918
919        Ok(OwnedLeafShardHeaderUnsealedRef {
920            buffer,
921            header_offset,
922            public_key_hash: consensus_info.solution.public_key_hash,
923        })
924    }
925
926    /// Append everything except the seal to the buffer
927    fn append_unsealed(
928        prefix: &BlockHeaderPrefix,
929        result: &BlockHeaderResult,
930        consensus_info: &BlockHeaderConsensusInfo,
931        beacon_chain_info: &BlockHeaderBeaconChainInfo,
932        buffer: &mut OwnedAlignedBuffer,
933    ) -> Result<(), OwnedLeafShardHeaderError> {
934        // The header with the largest seal must fit after the bytes already in the buffer, so
935        // that neither the appends below nor the seal appended later can fail. The length of a
936        // buffer is never larger than its maximum capacity.
937        if OwnedAlignedBuffer::<Align16>::MAX_CAPACITY - buffer.len() < Self::MAX_ALLOCATION {
938            return Err(OwnedLeafShardHeaderError::HeaderTooLarge);
939        }
940        buffer
941            .append(prefix.as_bytes())
942            .expect("Checked size above; qed");
943        buffer
944            .append(result.as_bytes())
945            .expect("Checked size above; qed");
946        buffer
947            .append(consensus_info.as_bytes())
948            .expect("Checked size above; qed");
949        buffer
950            .append(beacon_chain_info.as_bytes())
951            .expect("Checked size above; qed");
952
953        Ok(())
954    }
955
956    /// Create an owned header from a buffer
957    #[inline]
958    pub fn from_buffer(buffer: SharedAlignedBuffer) -> Result<Self, SharedAlignedBuffer> {
959        // TODO: Cloning is cheap, but will not be necessary if/when this is resolved:
960        //  https://github.com/unicode-org/icu4x/issues/6665
961        let inner = Yoke::try_attach_to_cart(buffer.clone(), |buffer| {
962            let Some((header, extra_bytes)) = LeafShardHeader::try_from_bytes(buffer) else {
963                return Err(());
964            };
965            if !extra_bytes.is_empty() {
966                return Err(());
967            }
968
969            Ok(header)
970        })
971        .map_err(move |()| buffer)?;
972
973        Ok(Self {
974            inner: Arc::new(inner),
975        })
976    }
977
978    /// Create an owned header from the beginning of a buffer.
979    ///
980    /// Bytes after the header don't belong to it, the buffer of the owned header ends where the
981    /// header ends, but its allocation still holds them. Returns the buffer back if it doesn't
982    /// start with a header.
983    pub(crate) fn from_buffer_start(
984        buffer: SharedAlignedBuffer,
985    ) -> Result<Self, SharedAlignedBuffer> {
986        let mut header_len = 0;
987        // TODO: Cloning is cheap, but will not be necessary if/when this is resolved:
988        //  https://github.com/unicode-org/icu4x/issues/6665
989        let inner = Yoke::try_attach_to_cart(buffer.clone(), |buffer| {
990            let Some((header, remainder)) = LeafShardHeader::try_from_bytes(buffer) else {
991                return Err(());
992            };
993            header_len = buffer.len() - remainder.len();
994
995            Ok(header)
996        })
997        .map_err(move |()| buffer)?;
998        let header_len = u32::try_from(header_len)
999            .expect("Header is a part of the buffer, whose length is `u32`; qed");
1000
1001        // SAFETY: Truncation only shortens the buffer, which keeps referencing the same bytes of
1002        // the same allocation. The header is not empty, so the allocation is kept, and it only
1003        // references bytes within its length.
1004        let inner = unsafe {
1005            inner.replace_cart(|mut buffer| {
1006                buffer.truncate(header_len);
1007                buffer
1008            })
1009        };
1010
1011        Ok(Self {
1012            inner: Arc::new(inner),
1013        })
1014    }
1015
1016    /// Inner buffer with block header contents
1017    #[inline(always)]
1018    pub fn buffer(&self) -> &SharedAlignedBuffer {
1019        self.inner.backing_cart()
1020    }
1021
1022    /// Number of clones in memory
1023    #[inline(always)]
1024    pub fn ref_count(&self) -> usize {
1025        Arc::count(&self.inner)
1026    }
1027
1028    /// Get [`LeafShardHeader`] out of [`OwnedLeafShardHeader`]
1029    #[inline(always)]
1030    pub fn header(&self) -> &LeafShardHeader<'_> {
1031        self.inner.get()
1032    }
1033
1034    /// Block root, see [`LeafShardHeader::root()`] for details
1035    #[inline(always)]
1036    pub fn root(&self) -> impl Deref<Target = BlockRoot> + Send + Sync {
1037        self.header().root()
1038    }
1039}
1040
1041/// Owned leaf shard block header, which is not sealed yet
1042#[derive(Debug, Clone)]
1043pub struct OwnedLeafShardHeaderUnsealed {
1044    buffer: OwnedAlignedBuffer,
1045    /// Public key hash of the solution, the seal must correspond to it
1046    public_key_hash: Blake3Hash,
1047}
1048
1049impl OwnedLeafShardHeaderUnsealed {
1050    /// Hash of the block before seal is applied to it
1051    #[inline(always)]
1052    pub fn pre_seal_hash(&self) -> Blake3Hash {
1053        Blake3Hash::from(blake3::hash(self.buffer.as_slice()))
1054    }
1055
1056    /// Add seal and return [`OwnedLeafShardHeader`].
1057    ///
1058    /// Returns an error if the seal doesn't correspond to the public key hash of the solution.
1059    pub fn with_seal(
1060        self,
1061        seal: BlockHeaderSeal<'_>,
1062    ) -> Result<OwnedLeafShardHeader, BlockHeaderConsistencyError> {
1063        let Self {
1064            mut buffer,
1065            public_key_hash,
1066        } = self;
1067        BlockHeader::check_seal(&public_key_hash, seal)?;
1068        append_seal(&mut buffer, seal);
1069
1070        let header = OwnedLeafShardHeader::from_buffer(buffer.into_shared())
1071            .expect("`from_parts()` checked the parts it wrote, the seal is checked above; qed");
1072
1073        Ok(header)
1074    }
1075}
1076
1077/// Leaf shard block header written into a buffer by [`OwnedLeafShardHeader::from_parts_into()`],
1078/// which is not sealed yet.
1079///
1080/// The header in the buffer is not complete until [`Self::with_seal()`] attaches the seal.
1081#[derive(Debug)]
1082#[must_use = "The header in the buffer is not complete until `with_seal()` attaches the seal"]
1083pub struct OwnedLeafShardHeaderUnsealedRef<'a> {
1084    buffer: &'a mut OwnedAlignedBuffer,
1085    header_offset: u32,
1086    /// Public key hash of the solution, the seal must correspond to it
1087    public_key_hash: Blake3Hash,
1088}
1089
1090impl OwnedLeafShardHeaderUnsealedRef<'_> {
1091    /// Hash of the block before seal is applied to it
1092    #[inline(always)]
1093    pub fn pre_seal_hash(&self) -> Blake3Hash {
1094        let header_bytes = self
1095            .buffer
1096            .as_slice()
1097            .get(self.header_offset as usize..)
1098            .expect("The buffer only grew since `header_offset` was its length; qed");
1099        Blake3Hash::from(blake3::hash(header_bytes))
1100    }
1101
1102    /// Attach the seal after the header in the buffer, which completes the header.
1103    ///
1104    /// Returns an error if the seal doesn't correspond to the public key hash of the solution. The
1105    /// seal is not attached then, and the buffer ends with the unsealed header, which must not be
1106    /// treated as a complete header.
1107    #[inline(always)]
1108    pub fn with_seal(self, seal: BlockHeaderSeal<'_>) -> Result<(), BlockHeaderConsistencyError> {
1109        let Self {
1110            buffer,
1111            header_offset: _,
1112            public_key_hash,
1113        } = self;
1114        BlockHeader::check_seal(&public_key_hash, seal)?;
1115        append_seal(buffer, seal);
1116
1117        Ok(())
1118    }
1119}
1120
1121/// An owned version of [`BlockHeader`].
1122///
1123/// It is correctly aligned in memory and well suited for sending and receiving over the network
1124/// efficiently or storing in memory or on disk.
1125#[derive(Debug, Clone, From)]
1126pub enum OwnedBlockHeader {
1127    /// Block header corresponds to the beacon chain
1128    BeaconChain(OwnedBeaconChainHeader),
1129    /// Block header corresponds to an intermediate shard
1130    IntermediateShard(OwnedIntermediateShardHeader),
1131    /// Block header corresponds to a leaf shard
1132    LeafShard(OwnedLeafShardHeader),
1133}
1134
1135impl OwnedBlockHeader {
1136    /// Create an owned header from a buffer.
1137    ///
1138    /// The shard kind of the header is that of the shard index in its prefix, see
1139    /// [`BlockHeader::shard_kind_from_bytes()`].
1140    #[inline]
1141    pub fn from_buffer(buffer: SharedAlignedBuffer) -> Result<Self, SharedAlignedBuffer> {
1142        let Some(shard_kind) = BlockHeader::shard_kind_from_bytes(buffer.as_slice()) else {
1143            return Err(buffer);
1144        };
1145
1146        Ok(match shard_kind {
1147            RealShardKind::BeaconChain => {
1148                Self::BeaconChain(OwnedBeaconChainHeader::from_buffer(buffer)?)
1149            }
1150            RealShardKind::IntermediateShard => {
1151                Self::IntermediateShard(OwnedIntermediateShardHeader::from_buffer(buffer)?)
1152            }
1153            RealShardKind::LeafShard => Self::LeafShard(OwnedLeafShardHeader::from_buffer(buffer)?),
1154        })
1155    }
1156
1157    /// Inner buffer block header contents
1158    #[inline]
1159    pub fn buffer(&self) -> &SharedAlignedBuffer {
1160        match self {
1161            Self::BeaconChain(owned_header) => owned_header.buffer(),
1162            Self::IntermediateShard(owned_header) => owned_header.buffer(),
1163            Self::LeafShard(owned_header) => owned_header.buffer(),
1164        }
1165    }
1166
1167    /// Number of clones in memory
1168    #[inline]
1169    pub fn ref_count(&self) -> usize {
1170        match self {
1171            Self::BeaconChain(owned_header) => owned_header.ref_count(),
1172            Self::IntermediateShard(owned_header) => owned_header.ref_count(),
1173            Self::LeafShard(owned_header) => owned_header.ref_count(),
1174        }
1175    }
1176
1177    /// Get [`BlockHeader`] out of [`OwnedBlockHeader`]
1178    #[inline]
1179    pub fn header(&self) -> BlockHeader<'_> {
1180        match self {
1181            Self::BeaconChain(owned_header) => {
1182                BlockHeader::BeaconChain(owned_header.header().clone())
1183            }
1184            Self::IntermediateShard(owned_header) => {
1185                BlockHeader::IntermediateShard(owned_header.header().clone())
1186            }
1187            Self::LeafShard(owned_header) => BlockHeader::LeafShard(owned_header.header().clone()),
1188        }
1189    }
1190}