Skip to main content

reth_era/era/
file.rs

1//! Represents a complete Era file
2//!
3//! The structure of an Era file follows the specification:
4//! `Version | block* | era-state | other-entries* | slot-index(block)? | slot-index(state)`
5//!
6//! See also <https://github.com/eth-clients/e2store-format-specs/blob/main/formats/era.md>.
7
8use crate::{
9    common::file_ops::{EraFileFormat, StreamReader, StreamWriter},
10    e2s::{
11        error::E2sError,
12        file::{E2StoreReader, E2StoreWriter},
13        types::{Entry, IndexEntry, Version, SLOT_INDEX},
14    },
15    era::types::{
16        consensus::{
17            CompressedBeaconState, CompressedSignedBeaconBlock, COMPRESSED_BEACON_STATE,
18            COMPRESSED_SIGNED_BEACON_BLOCK,
19        },
20        group::{EraGroup, EraId, SlotIndex},
21    },
22};
23use std::io::{Read, Seek, Write};
24
25/// Era file interface
26#[derive(Debug)]
27pub struct EraFile {
28    /// Version record, must be the first record in the file
29    pub version: Version,
30
31    /// Main content group of the Era file
32    pub group: EraGroup,
33
34    /// File identifier
35    pub id: EraId,
36}
37
38impl EraFileFormat for EraFile {
39    type EraGroup = EraGroup;
40    type Id = EraId;
41
42    /// Create a new [`EraFile`]
43    fn new(group: EraGroup, id: EraId) -> Self {
44        Self { version: Version, group, id }
45    }
46
47    fn version(&self) -> &Version {
48        &self.version
49    }
50
51    fn group(&self) -> &Self::EraGroup {
52        &self.group
53    }
54
55    fn id(&self) -> &Self::Id {
56        &self.id
57    }
58}
59
60/// Reader for era files that builds on top of [`E2StoreReader`]
61#[derive(Debug)]
62pub struct EraReader<R: Read> {
63    reader: E2StoreReader<R>,
64}
65
66/// An iterator of [`BeaconBlockIterator`] streaming from [`E2StoreReader`].
67#[derive(Debug)]
68pub struct BeaconBlockIterator<R: Read> {
69    reader: E2StoreReader<R>,
70    state: Option<CompressedBeaconState>,
71    other_entries: Vec<Entry>,
72    block_slot_index: Option<SlotIndex>,
73    state_slot_index: Option<SlotIndex>,
74}
75
76impl<R: Read> BeaconBlockIterator<R> {
77    fn new(reader: E2StoreReader<R>) -> Self {
78        Self {
79            reader,
80            state: None,
81            other_entries: Default::default(),
82            block_slot_index: None,
83            state_slot_index: None,
84        }
85    }
86}
87
88impl<R: Read + Seek> Iterator for BeaconBlockIterator<R> {
89    type Item = Result<CompressedSignedBeaconBlock, E2sError>;
90
91    fn next(&mut self) -> Option<Self::Item> {
92        self.next_result().transpose()
93    }
94}
95
96impl<R: Read + Seek> BeaconBlockIterator<R> {
97    fn next_result(&mut self) -> Result<Option<CompressedSignedBeaconBlock>, E2sError> {
98        loop {
99            let Some(entry) = self.reader.read_next_entry()? else {
100                return Ok(None);
101            };
102
103            match entry.entry_type {
104                COMPRESSED_SIGNED_BEACON_BLOCK => {
105                    let block = CompressedSignedBeaconBlock::from_entry(&entry)?;
106                    return Ok(Some(block));
107                }
108                COMPRESSED_BEACON_STATE => {
109                    if self.state.is_some() {
110                        return Err(E2sError::Ssz("Multiple state entries found".to_string()));
111                    }
112                    self.state = Some(CompressedBeaconState::from_entry(&entry)?);
113                }
114                SLOT_INDEX => {
115                    let slot_index = SlotIndex::from_entry(&entry)?;
116                    // Both slot indices follow the state: the last one is the state index and
117                    // the one before it, absent in a genesis era, is the block index.
118                    if self.state.is_none() {
119                        return Err(E2sError::Ssz("Slot index before the state entry".to_string()));
120                    }
121                    if self.block_slot_index.is_some() {
122                        return Err(E2sError::Ssz("More than two slot index entries".to_string()));
123                    }
124                    self.block_slot_index = self.state_slot_index.replace(slot_index);
125                }
126                _ => {
127                    self.other_entries.push(entry);
128                }
129            }
130        }
131    }
132}
133
134impl<R: Read + Seek> StreamReader<R> for EraReader<R> {
135    type File = EraFile;
136    type Iterator = BeaconBlockIterator<R>;
137
138    /// Create a new [`EraReader`]
139    fn new(reader: R) -> Self {
140        Self { reader: E2StoreReader::new(reader) }
141    }
142
143    /// Returns an iterator of [`BeaconBlockIterator`] streaming from `reader`.
144    fn iter(self) -> BeaconBlockIterator<R> {
145        BeaconBlockIterator::new(self.reader)
146    }
147
148    fn read(self, network_name: String) -> Result<Self::File, E2sError> {
149        self.read_and_assemble(network_name)
150    }
151}
152
153impl<R: Read + Seek> EraReader<R> {
154    /// Reads and parses an era file from the underlying reader, assembling all components
155    /// into a complete [`EraFile`] with an [`EraId`] that includes the provided network name.
156    pub fn read_and_assemble(mut self, network_name: String) -> Result<EraFile, E2sError> {
157        // Validate version entry
158        let _version_entry = match self.reader.read_version()? {
159            Some(entry) if entry.is_version() => entry,
160            Some(_) => return Err(E2sError::Ssz("First entry is not a Version entry".to_string())),
161            None => return Err(E2sError::Ssz("Empty Era file".to_string())),
162        };
163
164        let mut iter = self.iter();
165        let blocks = (&mut iter).collect::<Result<Vec<_>, _>>()?;
166
167        let BeaconBlockIterator {
168            state, other_entries, block_slot_index, state_slot_index, ..
169        } = iter;
170
171        let state =
172            state.ok_or_else(|| E2sError::Ssz("Era file missing state entry".to_string()))?;
173
174        let state_slot_index = state_slot_index
175            .ok_or_else(|| E2sError::Ssz("Era file missing state slot index".to_string()))?;
176
177        // Create appropriate `EraGroup`, genesis vs non-genesis
178        let mut group = if let Some(block_index) = block_slot_index {
179            EraGroup::with_block_index(blocks, state, block_index, state_slot_index)
180        } else {
181            EraGroup::new(blocks, state, state_slot_index)
182        };
183
184        // Add other entries
185        for entry in other_entries {
186            group.add_entry(entry);
187        }
188
189        // The state slot index identifies the era, the block index starts one era earlier.
190        let id = EraId::new(network_name, group.state_slot_index.starting_slot, group.slot_count());
191
192        Ok(EraFile::new(group, id))
193    }
194}
195
196/// Writer for Era files that builds on top of [`E2StoreWriter`]
197#[derive(Debug)]
198pub struct EraWriter<W: Write> {
199    writer: E2StoreWriter<W>,
200    has_written_version: bool,
201    has_written_state: bool,
202    has_written_block_slot_index: bool,
203    has_written_state_slot_index: bool,
204}
205
206impl<W: Write> StreamWriter<W> for EraWriter<W> {
207    type File = EraFile;
208
209    /// Create a new [`EraWriter`]
210    fn new(writer: W) -> Self {
211        Self {
212            writer: E2StoreWriter::new(writer),
213            has_written_version: false,
214            has_written_state: false,
215            has_written_block_slot_index: false,
216            has_written_state_slot_index: false,
217        }
218    }
219
220    /// Write the version entry
221    fn write_version(&mut self) -> Result<(), E2sError> {
222        if self.has_written_version {
223            return Ok(());
224        }
225
226        self.writer.write_version()?;
227        self.has_written_version = true;
228        Ok(())
229    }
230
231    fn write_file(&mut self, file: &Self::File) -> Result<(), E2sError> {
232        // Write version
233        self.write_version()?;
234
235        // Write all blocks
236        for block in &file.group.blocks {
237            self.write_beacon_block(block)?;
238        }
239
240        // Write state
241        self.write_beacon_state(&file.group.era_state)?;
242
243        // Write other entries
244        for entry in &file.group.other_entries {
245            self.writer.write_entry(entry)?;
246        }
247
248        // Write slot index
249        if let Some(ref block_index) = file.group.slot_index {
250            self.write_block_slot_index(block_index)?;
251        }
252
253        // Write state index
254        self.write_state_slot_index(&file.group.state_slot_index)?;
255
256        self.writer.flush()?;
257        Ok(())
258    }
259
260    /// Flush any buffered data to the underlying writer
261    fn flush(&mut self) -> Result<(), E2sError> {
262        self.writer.flush()
263    }
264}
265
266impl<W: Write> EraWriter<W> {
267    /// Write beacon block
268    pub fn write_beacon_block(
269        &mut self,
270        block: &CompressedSignedBeaconBlock,
271    ) -> Result<(), E2sError> {
272        self.ensure_version_written()?;
273
274        // Ensure blocks are written before state/indices
275        if self.has_written_state ||
276            self.has_written_block_slot_index ||
277            self.has_written_state_slot_index
278        {
279            return Err(E2sError::Ssz("Cannot write blocks after state or indices".to_string()));
280        }
281
282        let entry = block.to_entry();
283        self.writer.write_entry(&entry)?;
284        Ok(())
285    }
286
287    // Write beacon state
288    fn write_beacon_state(&mut self, state: &CompressedBeaconState) -> Result<(), E2sError> {
289        self.ensure_version_written()?;
290
291        if self.has_written_state {
292            return Err(E2sError::Ssz("State already written".to_string()));
293        }
294
295        let entry = state.to_entry();
296        self.writer.write_entry(&entry)?;
297        self.has_written_state = true;
298        Ok(())
299    }
300
301    /// Write the block slot index
302    pub fn write_block_slot_index(&mut self, slot_index: &SlotIndex) -> Result<(), E2sError> {
303        self.ensure_version_written()?;
304
305        if self.has_written_block_slot_index {
306            return Err(E2sError::Ssz("Block slot index already written".to_string()));
307        }
308
309        let entry = slot_index.to_entry();
310        self.writer.write_entry(&entry)?;
311        self.has_written_block_slot_index = true;
312
313        Ok(())
314    }
315
316    /// Write the state slot index
317    pub fn write_state_slot_index(&mut self, slot_index: &SlotIndex) -> Result<(), E2sError> {
318        self.ensure_version_written()?;
319
320        if self.has_written_state_slot_index {
321            return Err(E2sError::Ssz("State slot index already written".to_string()));
322        }
323
324        let entry = slot_index.to_entry();
325        self.writer.write_entry(&entry)?;
326        self.has_written_state_slot_index = true;
327
328        Ok(())
329    }
330
331    /// Helper to ensure version is written before any data
332    fn ensure_version_written(&mut self) -> Result<(), E2sError> {
333        if !self.has_written_version {
334            self.write_version()?;
335        }
336        Ok(())
337    }
338}
339
340#[cfg(test)]
341mod tests {
342    use super::*;
343    use crate::{
344        common::file_ops::EraFileId,
345        e2s::types::IndexEntry,
346        test_utils::{create_beacon_block, create_beacon_state},
347    };
348    use std::io::Cursor;
349
350    fn write_era(file: &EraFile) -> Vec<u8> {
351        let mut buf = Vec::new();
352        EraWriter::new(&mut buf).write_file(file).unwrap();
353        buf
354    }
355
356    fn read_era(bytes: &[u8]) -> Result<EraFile, E2sError> {
357        EraReader::new(Cursor::new(bytes)).read("mainnet".into())
358    }
359
360    #[test]
361    fn read_keeps_block_slot_index() {
362        let blocks = vec![create_beacon_block(10), create_beacon_block(15)];
363        let block_index = SlotIndex::new(8192, vec![8, 30]);
364        let state_index = SlotIndex::new(16384, vec![60]);
365        let group = EraGroup::with_block_index(
366            blocks,
367            create_beacon_state(50),
368            block_index.clone(),
369            state_index.clone(),
370        );
371        let bytes = write_era(&EraFile::new(group, EraId::new("mainnet", 16384, 2)));
372
373        let read = read_era(&bytes).unwrap();
374
375        assert_eq!(read.group.slot_index, Some(block_index));
376        assert_eq!(read.group.state_slot_index, state_index);
377        assert_eq!(read.id.era_number(), 2);
378        assert_eq!(write_era(&read), bytes);
379    }
380
381    #[test]
382    fn read_genesis_has_no_block_slot_index() {
383        let state_index = SlotIndex::new(0, vec![16]);
384        let group = EraGroup::new(Vec::new(), create_beacon_state(50), state_index.clone());
385        let file = EraFile::new(group, EraId::new("mainnet", 0, 0));
386
387        let read = read_era(&write_era(&file)).unwrap();
388
389        assert_eq!(read.group.slot_index, None);
390        assert_eq!(read.group.state_slot_index, state_index);
391        assert_eq!(read.id.era_number(), 0);
392    }
393
394    #[test]
395    fn read_rejects_misplaced_slot_index() {
396        let group = EraGroup::new(Vec::new(), create_beacon_state(50), SlotIndex::new(0, vec![16]));
397        let mut third = write_era(&EraFile::new(group, EraId::new("mainnet", 0, 0)));
398        SlotIndex::new(0, vec![8]).to_entry().write(&mut third).unwrap();
399        SlotIndex::new(0, vec![8]).to_entry().write(&mut third).unwrap();
400        assert!(read_era(&third).is_err());
401
402        let mut before_state = b"e2\0\0\0\0\0\0".to_vec();
403        SlotIndex::new(0, vec![8]).to_entry().write(&mut before_state).unwrap();
404        create_beacon_state(50).to_entry().write(&mut before_state).unwrap();
405        assert!(read_era(&before_state).is_err());
406    }
407}