Skip to main content

sc_consensus_subspace/
archiver.rs

1//! Consensus archiver responsible for archival of blockchain history, it is driven by block import
2//! pipeline.
3//!
4//! Implements archiving process in Subspace blockchain that converts blockchain history (blocks)
5//! into archived history (pieces).
6//!
7//! The main entry point here is [`create_subspace_archiver`] that will create a task, which while
8//! driven will perform the archiving itself.
9//!
10//! Archiving is triggered by block importing notification ([`SubspaceLink::block_importing_notification_stream`])
11//! and tries to archive the block at [`ChainConstants::confirmation_depth_k`](sp_consensus_subspace::ChainConstants::confirmation_depth_k)
12//! depth from the block being imported. Block import will then wait for archiver to acknowledge
13//! processing, which is necessary for ensuring that when the next block is imported, inherents will
14//! contain segment header of newly archived block (must happen exactly in the next block).
15//!
16//! Archiving itself will also wait for acknowledgement by various subscribers before proceeding,
17//! which includes farmer subscription, in case of reference implementation via RPC
18//! (`sc-consensus-subspace-rpc`), but could also be in other ways.
19//!
20//! [`SegmentHeadersStore`] is maintained as a data structure containing all known (including future
21//! in case of syncing) segment headers. This data structure contents is then made available to
22//! other parts of the protocol that need to know what correct archival history of the blockchain
23//! looks like. For example, it is used during node sync and farmer plotting in order to verify
24//! pieces of archival history received from other network participants.
25//!
26//! [`recreate_genesis_segment`] is a bit of a hack and is useful for deriving of the genesis
27//! segment that is special case since we don't have enough data in the blockchain history itself
28//! during genesis in order to do the archiving.
29//!
30//! [`encode_block`] and [`decode_block`] are symmetric encoding/decoding functions turning
31//! [`SignedBlock`]s into bytes and back.
32
33#[cfg(test)]
34mod tests;
35
36use crate::slot_worker::SubspaceSyncOracle;
37use crate::{SubspaceLink, SubspaceNotificationSender};
38use futures::StreamExt;
39use parity_scale_codec::{Decode, Encode};
40use parking_lot::RwLock;
41use rand::prelude::*;
42use rand_chacha::ChaCha8Rng;
43use rayon::ThreadPoolBuilder;
44use rayon::prelude::*;
45use sc_client_api::{
46    AuxStore, Backend as BackendT, BlockBackend, BlockImportOperation, BlockchainEvents, Finalizer,
47    LockImportRun,
48};
49use sc_telemetry::{CONSENSUS_INFO, TelemetryHandle, telemetry};
50use sc_utils::mpsc::{TracingUnboundedSender, tracing_unbounded};
51use sp_api::ProvideRuntimeApi;
52use sp_blockchain::{Backend as BlockchainBackend, HeaderBackend};
53use sp_consensus::SyncOracle;
54use sp_consensus_subspace::{SubspaceApi, SubspaceJustification};
55use sp_objects::ObjectsApi;
56use sp_runtime::Justifications;
57use sp_runtime::generic::SignedBlock;
58use sp_runtime::traits::{
59    Block as BlockT, BlockNumber as BlockNumberT, CheckedSub, Header, NumberFor, One, Zero,
60};
61use std::error::Error;
62use std::future::Future;
63use std::num::NonZeroU32;
64use std::slice;
65use std::sync::Arc;
66use std::sync::atomic::{AtomicU16, Ordering};
67use std::time::Duration;
68use subspace_archiving::archiver::{Archiver, NewArchivedSegment};
69use subspace_core_primitives::objects::{BlockObjectMapping, GlobalObject};
70use subspace_core_primitives::segments::{RecordedHistorySegment, SegmentHeader, SegmentIndex};
71use subspace_core_primitives::{BlockNumber, PublicKey};
72use subspace_erasure_coding::ErasureCoding;
73use subspace_kzg::Kzg;
74use tracing::{debug, info, trace, warn};
75
76/// Number of WASM instances is 8, this is a bit lower to avoid warnings exceeding number of
77/// instances
78const BLOCKS_TO_ARCHIVE_CONCURRENCY: usize = 6;
79/// Do not wait for acknowledgements beyond this time limit
80const ACKNOWLEDGEMENT_TIMEOUT: Duration = Duration::from_mins(2);
81
82/// How deep (in segments) should block be in order to be finalized.
83///
84/// This is required for full nodes to not prune recent history such that keep-up sync in Substrate
85/// works even without archival nodes (initial sync will be done from DSN).
86///
87/// Ideally, we'd decouple pruning from finalization, but it may require invasive changes in
88/// Substrate and is not worth it right now.
89/// https://github.com/paritytech/substrate/discussions/14359
90pub(crate) const FINALIZATION_DEPTH_IN_SEGMENTS: SegmentIndex = SegmentIndex::new(5);
91
92#[derive(Debug)]
93struct SegmentHeadersStoreInner<AS> {
94    aux_store: Arc<AS>,
95    next_key_index: AtomicU16,
96    /// In-memory cache of segment headers
97    cache: RwLock<Vec<SegmentHeader>>,
98}
99
100/// Persistent storage of segment headers.
101///
102/// It maintains all known segment headers. During sync from DSN it is possible that this data structure contains
103/// segment headers that from the point of view of the tip of the current chain are "in the future". This is expected
104/// and must be accounted for in the archiver and other places.
105///
106/// Segment headers are stored in batches (which is more efficient to store and retrieve). Each next batch contains
107/// distinct segment headers with monotonically increasing segment indices. During instantiation all previously stored
108/// batches will be read and in-memory representation of the whole contents will be created such that queries to this
109/// data structure are quick and not involving any disk I/O.
110#[derive(Debug)]
111pub struct SegmentHeadersStore<AS> {
112    inner: Arc<SegmentHeadersStoreInner<AS>>,
113    confirmation_depth_k: BlockNumber,
114}
115
116impl<AS> Clone for SegmentHeadersStore<AS> {
117    fn clone(&self) -> Self {
118        Self {
119            inner: Arc::clone(&self.inner),
120            confirmation_depth_k: self.confirmation_depth_k,
121        }
122    }
123}
124
125impl<AS> SegmentHeadersStore<AS>
126where
127    AS: AuxStore,
128{
129    const KEY_PREFIX: &'static [u8] = b"segment-headers";
130    const INITIAL_CACHE_CAPACITY: usize = 1_000;
131
132    /// Create new instance
133    pub fn new(
134        aux_store: Arc<AS>,
135        confirmation_depth_k: BlockNumber,
136    ) -> sp_blockchain::Result<Self> {
137        let mut cache = Vec::with_capacity(Self::INITIAL_CACHE_CAPACITY);
138
139        debug!("Started loading segment headers into cache");
140        // Segment headers are stored in batches (which is more efficient to store and retrieve), this is why code deals
141        // with key indices here rather that segment indices. Essentially this iterates over keys from 0 until missing
142        // entry is hit, which becomes the next key index where additional segment headers will be stored.
143        let mut next_key_index = 0;
144        while let Some(segment_headers) =
145            aux_store
146                .get_aux(&Self::key(next_key_index))?
147                .map(|segment_header| {
148                    Vec::<SegmentHeader>::decode(&mut segment_header.as_slice())
149                        .expect("Always correct segment header unless DB is corrupted; qed")
150                })
151        {
152            cache.extend(segment_headers);
153            next_key_index += 1;
154        }
155        debug!("Finished loading segment headers into cache");
156
157        Ok(Self {
158            inner: Arc::new(SegmentHeadersStoreInner {
159                aux_store,
160                next_key_index: AtomicU16::new(next_key_index),
161                cache: RwLock::new(cache),
162            }),
163            confirmation_depth_k,
164        })
165    }
166
167    /// Returns last observed segment header
168    pub fn last_segment_header(&self) -> Option<SegmentHeader> {
169        self.inner.cache.read().last().cloned()
170    }
171
172    /// Returns last observed segment index
173    pub fn max_segment_index(&self) -> Option<SegmentIndex> {
174        let segment_index = self.inner.cache.read().len().checked_sub(1)? as u64;
175        Some(SegmentIndex::from(segment_index))
176    }
177
178    /// Add segment headers.
179    ///
180    /// Multiple can be inserted for efficiency purposes.
181    pub fn add_segment_headers(
182        &self,
183        segment_headers: &[SegmentHeader],
184    ) -> sp_blockchain::Result<()> {
185        let mut maybe_last_segment_index = self.max_segment_index();
186        let mut segment_headers_to_store = Vec::with_capacity(segment_headers.len());
187        // Check all input segment headers to see which ones are not stored yet and verifying that segment indices are
188        // monotonically increasing
189        for segment_header in segment_headers {
190            let segment_index = segment_header.segment_index();
191            match maybe_last_segment_index {
192                Some(last_segment_index) => {
193                    if segment_index <= last_segment_index {
194                        // Skip already stored segment headers
195                        continue;
196                    }
197
198                    if segment_index != last_segment_index + SegmentIndex::ONE {
199                        let error = format!(
200                            "Segment index {segment_index} must strictly follow {last_segment_index}, can't store segment header"
201                        );
202                        return Err(sp_blockchain::Error::Application(error.into()));
203                    }
204
205                    segment_headers_to_store.push(segment_header);
206                    maybe_last_segment_index.replace(segment_index);
207                }
208                None => {
209                    if segment_index != SegmentIndex::ZERO {
210                        let error = format!(
211                            "First segment header index must be zero, found index {segment_index}"
212                        );
213                        return Err(sp_blockchain::Error::Application(error.into()));
214                    }
215
216                    segment_headers_to_store.push(segment_header);
217                    maybe_last_segment_index.replace(segment_index);
218                }
219            }
220        }
221
222        if segment_headers_to_store.is_empty() {
223            return Ok(());
224        }
225
226        // Insert all new segment headers into vacant key index for efficiency purposes
227        // TODO: Do compaction when we have too many keys: combine multiple segment headers into a
228        //  single entry for faster retrievals and more compact storage
229        {
230            let key_index = self.inner.next_key_index.fetch_add(1, Ordering::SeqCst);
231            let key = Self::key(key_index);
232            let value = segment_headers_to_store.encode();
233            let insert_data = vec![(key.as_slice(), value.as_slice())];
234
235            self.inner.aux_store.insert_aux(&insert_data, &[])?;
236        }
237        self.inner.cache.write().extend(segment_headers_to_store);
238
239        Ok(())
240    }
241
242    /// Get a single segment header
243    pub fn get_segment_header(&self, segment_index: SegmentIndex) -> Option<SegmentHeader> {
244        self.inner
245            .cache
246            .read()
247            .get(u64::from(segment_index) as usize)
248            .copied()
249    }
250
251    fn key(key_index: u16) -> Vec<u8> {
252        (Self::KEY_PREFIX, key_index.to_le_bytes()).encode()
253    }
254
255    /// Get segment headers that are expected to be included at specified block number.
256    pub fn segment_headers_for_block(&self, block_number: BlockNumber) -> Vec<SegmentHeader> {
257        let Some(last_segment_index) = self.max_segment_index() else {
258            // Not initialized
259            return Vec::new();
260        };
261
262        // Special case for the initial segment (for genesis block).
263        if block_number == 1 {
264            // If there is a segment index present, and we store monotonically increasing segment
265            // headers, then the first header exists.
266            return vec![
267                self.get_segment_header(SegmentIndex::ZERO)
268                    .expect("Segment headers are stored in monotonically increasing order; qed"),
269            ];
270        }
271
272        if last_segment_index == SegmentIndex::ZERO {
273            // Genesis segment already included in block #1
274            return Vec::new();
275        }
276
277        let mut current_segment_index = last_segment_index;
278        loop {
279            // If the current segment index present, and we store monotonically increasing segment
280            // headers, then the current segment header exists as well.
281            let current_segment_header = self
282                .get_segment_header(current_segment_index)
283                .expect("Segment headers are stored in monotonically increasing order; qed");
284
285            // The block immediately after the archived segment adding the confirmation depth
286            let target_block_number =
287                current_segment_header.last_archived_block().number + 1 + self.confirmation_depth_k;
288            if target_block_number == block_number {
289                let mut headers_for_block = vec![current_segment_header];
290
291                // Check block spanning multiple segments
292                let last_archived_block_number =
293                    current_segment_header.last_archived_block().number;
294                let mut segment_index = current_segment_index - SegmentIndex::ONE;
295
296                while let Some(segment_header) = self.get_segment_header(segment_index) {
297                    if segment_header.last_archived_block().number == last_archived_block_number {
298                        headers_for_block.insert(0, segment_header);
299                        segment_index -= SegmentIndex::ONE;
300                    } else {
301                        break;
302                    }
303                }
304
305                return headers_for_block;
306            }
307
308            // iterate segments further
309            if target_block_number > block_number {
310                // no need to check the initial segment
311                if current_segment_index > SegmentIndex::ONE {
312                    current_segment_index -= SegmentIndex::ONE
313                } else {
314                    break;
315                }
316            } else {
317                // No segment headers required
318                return Vec::new();
319            }
320        }
321
322        // No segment headers required
323        Vec::new()
324    }
325}
326
327/// Notification with block header hash that needs to be signed and sender for signature.
328#[derive(Debug, Clone)]
329pub struct ArchivedSegmentNotification {
330    /// Archived segment.
331    pub archived_segment: Arc<NewArchivedSegment>,
332    /// Sender that signified the fact of receiving archived segment by farmer.
333    ///
334    /// This must be used to send a message or else block import pipeline will get stuck.
335    pub acknowledgement_sender: TracingUnboundedSender<()>,
336}
337
338/// Notification with incrementally generated object mappings for a block (and any previous block
339/// continuation)
340#[derive(Debug, Clone)]
341pub struct ObjectMappingNotification {
342    /// Incremental object mappings for a block (and any previous block continuation).
343    ///
344    /// The archived data won't be available in pieces until the entire segment is full and archived.
345    pub object_mapping: Vec<GlobalObject>,
346    /// The block that these mappings are from.
347    pub block_number: BlockNumber,
348    // TODO: add an acknowledgement_sender for backpressure if needed
349}
350
351/// Whether to create object mappings.
352#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
353pub enum CreateObjectMappings {
354    /// Start creating object mappings from this block number.
355    ///
356    /// This can be lower than the latest archived block, but must be greater than genesis.
357    ///
358    /// The genesis block doesn't have mappings, so starting mappings at genesis is pointless.
359    /// The archiver will fail if it can't get the data for this block, but snap sync doesn't store
360    /// the genesis data on disk.  So avoiding genesis also avoids this error.
361    /// <https://github.com/paritytech/polkadot-sdk/issues/5366>
362    Block(NonZeroU32),
363
364    /// Create object mappings as archiving is happening.
365    Yes,
366
367    /// Don't create object mappings.
368    #[default]
369    No,
370}
371
372impl CreateObjectMappings {
373    /// The fixed block number to start creating object mappings from.
374    /// If there is no fixed block number, or mappings are disabled, returns None.
375    fn block(&self) -> Option<BlockNumber> {
376        match self {
377            CreateObjectMappings::Block(block) => Some(block.get()),
378            CreateObjectMappings::Yes => None,
379            CreateObjectMappings::No => None,
380        }
381    }
382
383    /// Returns true if object mappings will be created from a past or future block.
384    pub fn is_enabled(&self) -> bool {
385        !matches!(self, CreateObjectMappings::No)
386    }
387
388    /// Does the supplied block number need object mappings?
389    pub fn is_enabled_for_block(&self, block: BlockNumber) -> bool {
390        if !self.is_enabled() {
391            return false;
392        }
393
394        // The genesis block has no mappings, and its parent has no state to extract them at
395        if block == 0 {
396            return false;
397        }
398
399        if let Some(target_block) = self.block() {
400            return block >= target_block;
401        }
402
403        // We're continuing where we left off, so all blocks get mappings.
404        true
405    }
406}
407
408fn find_last_archived_block<Block, Client, AS>(
409    client: &Client,
410    segment_headers_store: &SegmentHeadersStore<AS>,
411    best_block_to_archive: NumberFor<Block>,
412    create_object_mappings: bool,
413) -> sp_blockchain::Result<Option<(SegmentHeader, SignedBlock<Block>, BlockObjectMapping)>>
414where
415    Block: BlockT,
416    Client: ProvideRuntimeApi<Block> + BlockBackend<Block> + HeaderBackend<Block>,
417    Client::Api: SubspaceApi<Block, PublicKey> + ObjectsApi<Block>,
418    AS: AuxStore,
419{
420    let Some(max_segment_index) = segment_headers_store.max_segment_index() else {
421        return Ok(None);
422    };
423
424    if max_segment_index == SegmentIndex::ZERO {
425        // Just genesis, nothing else to check
426        return Ok(None);
427    }
428
429    for segment_header in (SegmentIndex::ZERO..=max_segment_index)
430        .rev()
431        .filter_map(|segment_index| segment_headers_store.get_segment_header(segment_index))
432    {
433        let last_archived_block_number = segment_header.last_archived_block().number;
434
435        if NumberFor::<Block>::from(last_archived_block_number) > best_block_to_archive {
436            // Last archived block in segment header is too high for current state of the chain
437            // (segment headers store may know about more blocks in existence than is currently
438            // imported)
439            continue;
440        }
441        let Some(last_archived_block_hash) = client.hash(last_archived_block_number.into())? else {
442            // This block number is not in our chain yet (segment headers store may know about more
443            // blocks in existence than is currently imported)
444            continue;
445        };
446
447        let Some(last_archived_block) = client.block(last_archived_block_hash)? else {
448            // This block data was already pruned (but the headers weren't)
449            continue;
450        };
451
452        // If we're starting mapping creation at this block, return its mappings.
453        let block_object_mappings = if create_object_mappings {
454            client
455                .runtime_api()
456                .extract_block_object_mapping(
457                    *last_archived_block.block.header().parent_hash(),
458                    last_archived_block.block.clone(),
459                )
460                .unwrap_or_default()
461        } else {
462            BlockObjectMapping::default()
463        };
464
465        return Ok(Some((
466            segment_header,
467            last_archived_block,
468            block_object_mappings,
469        )));
470    }
471
472    Ok(None)
473}
474
475/// Derive genesis segment on demand, returns `Ok(None)` in case genesis block was already pruned
476pub fn recreate_genesis_segment<Block, Client>(
477    client: &Client,
478    kzg: Kzg,
479    erasure_coding: ErasureCoding,
480) -> Result<Option<NewArchivedSegment>, Box<dyn Error>>
481where
482    Block: BlockT,
483    Client: ProvideRuntimeApi<Block> + BlockBackend<Block> + HeaderBackend<Block>,
484    Client::Api: ObjectsApi<Block>,
485{
486    let genesis_hash = client.info().genesis_hash;
487    let Some(signed_block) = client.block(genesis_hash)? else {
488        return Ok(None);
489    };
490
491    let encoded_block = encode_block(signed_block);
492
493    // There are no mappings in the genesis block, so they can be ignored
494    let block_outcome = Archiver::new(kzg, erasure_coding).add_block(
495        encoded_block,
496        BlockObjectMapping::default(),
497        false,
498    );
499    let new_archived_segment = block_outcome
500        .archived_segments
501        .into_iter()
502        .next()
503        .expect("Genesis block always results in exactly one archived segment; qed");
504
505    Ok(Some(new_archived_segment))
506}
507
508struct InitializedArchiver<Block>
509where
510    Block: BlockT,
511{
512    archiver: Archiver,
513    best_archived_block: (Block::Hash, NumberFor<Block>),
514}
515
516/// Encode block for archiving purposes.
517///
518/// Only specific Subspace justifications are included in the encoding, determined by result of
519/// [`SubspaceJustification::must_be_archived`], other justifications are filtered-out.
520pub fn encode_block<Block>(mut signed_block: SignedBlock<Block>) -> Vec<u8>
521where
522    Block: BlockT,
523{
524    if signed_block.block.header().number().is_zero() {
525        let mut encoded_block = signed_block.encode();
526
527        let encoded_block_length = encoded_block.len();
528
529        // We extend encoding of genesis block with extra data such that the very first archived
530        // segment can be produced right away, bootstrapping the farming process.
531        //
532        // Note: we add it to the end of the encoded block, so during decoding it'll actually be
533        // ignored (unless `DecodeAll::decode_all()` is used) even though it is technically present
534        // in encoded form.
535        encoded_block.resize(RecordedHistorySegment::SIZE, 0);
536        let mut rng = ChaCha8Rng::from_seed(
537            signed_block
538                .block
539                .header()
540                .state_root()
541                .as_ref()
542                .try_into()
543                .expect("State root in Subspace must be 32 bytes, panic otherwise; qed"),
544        );
545        rng.fill(&mut encoded_block[encoded_block_length..]);
546
547        encoded_block
548    } else {
549        // Filter out non-canonical justifications
550        if let Some(justifications) = signed_block.justifications.take() {
551            let mut filtered_justifications = justifications.into_iter().filter(|justification| {
552                // Only Subspace justifications are to be archived
553                let Some(subspace_justification) =
554                    SubspaceJustification::try_from_justification(justification)
555                        .and_then(|subspace_justification| subspace_justification.ok())
556                else {
557                    return false;
558                };
559
560                subspace_justification.must_be_archived()
561            });
562
563            if let Some(first_justification) = filtered_justifications.next() {
564                let mut justifications = Justifications::from(first_justification);
565
566                for justification in filtered_justifications {
567                    justifications.append(justification);
568                }
569
570                signed_block.justifications = Some(justifications);
571            }
572        }
573
574        signed_block.encode()
575    }
576}
577
578/// Symmetrical to [`encode_block()`], used to decode previously encoded blocks
579pub fn decode_block<Block>(
580    mut encoded_block: &[u8],
581) -> Result<SignedBlock<Block>, parity_scale_codec::Error>
582where
583    Block: BlockT,
584{
585    SignedBlock::<Block>::decode(&mut encoded_block)
586}
587
588fn initialize_archiver<Block, Client, AS>(
589    segment_headers_store: &SegmentHeadersStore<AS>,
590    subspace_link: &SubspaceLink<Block>,
591    client: &Client,
592    create_object_mappings: CreateObjectMappings,
593) -> sp_blockchain::Result<InitializedArchiver<Block>>
594where
595    Block: BlockT,
596    Client: ProvideRuntimeApi<Block> + BlockBackend<Block> + HeaderBackend<Block> + AuxStore,
597    Client::Api: SubspaceApi<Block, PublicKey> + ObjectsApi<Block>,
598    AS: AuxStore,
599{
600    let client_info = client.info();
601    let best_block_number = TryInto::<BlockNumber>::try_into(client_info.best_number)
602        .unwrap_or_else(|_| {
603            unreachable!("sp_runtime::BlockNumber fits into subspace_primitives::BlockNumber; qed");
604        });
605
606    let confirmation_depth_k = subspace_link.chain_constants.confirmation_depth_k();
607
608    let mut best_block_to_archive = best_block_number.saturating_sub(confirmation_depth_k);
609    // Choose a lower block number if we want to get mappings from that specific block.
610    // If we are continuing from where we left off, we don't need to change the block number to archive.
611    // If there is no path to this block from the tip due to snap sync, we'll start archiving from
612    // an earlier segment, then start mapping again once archiving reaches this block.
613    if let Some(block_number) = create_object_mappings.block() {
614        // There aren't any mappings in the genesis block, so starting there is pointless.
615        // (And causes errors on restart, because genesis block data is never stored during snap sync.)
616        best_block_to_archive = best_block_to_archive.min(block_number);
617    }
618
619    if (best_block_to_archive..best_block_number)
620        .any(|block_number| client.hash(block_number.into()).ok().flatten().is_none())
621    {
622        // If there are blocks missing headers between best block to archive and best block of the
623        // blockchain it means newer block was inserted in some special way and as such is by
624        // definition valid, so we can simply assume that is our best block to archive instead
625        best_block_to_archive = best_block_number;
626    }
627
628    // If the user chooses an object mapping start block we don't have data or state for, we can't
629    // create mappings for it, so the node must exit with an error. We ignore genesis here, because
630    // it doesn't have mappings.
631    if create_object_mappings.is_enabled() && best_block_to_archive >= 1 {
632        let Some(best_block_to_archive_hash) = client.hash(best_block_to_archive.into())? else {
633            let error = format!(
634                "Missing hash for mapping block {best_block_to_archive}, \
635                try a higher block number, or wipe your node and restart with `--sync full`"
636            );
637            return Err(sp_blockchain::Error::Application(error.into()));
638        };
639
640        let Some(best_block_data) = client.block(best_block_to_archive_hash)? else {
641            let error = format!(
642                "Missing data for mapping block {best_block_to_archive} \
643                hash {best_block_to_archive_hash}, \
644                try a higher block number, or wipe your node and restart with `--sync full`"
645            );
646            return Err(sp_blockchain::Error::Application(error.into()));
647        };
648
649        // Similarly, state can be pruned, even if the data is present
650        client
651            .runtime_api()
652            .extract_block_object_mapping(
653                *best_block_data.block.header().parent_hash(),
654                best_block_data.block.clone(),
655            )
656            .map_err(|error| {
657                sp_blockchain::Error::Application(
658                    format!(
659                        "Missing state for mapping block {best_block_to_archive} \
660                        hash {best_block_to_archive_hash}: {error}, \
661                        try a higher block number, or wipe your node and restart with `--sync full`"
662                    )
663                    .into(),
664                )
665            })?;
666    }
667
668    let maybe_last_archived_block = find_last_archived_block(
669        client,
670        segment_headers_store,
671        best_block_to_archive.into(),
672        create_object_mappings.is_enabled(),
673    )?;
674
675    let have_last_segment_header = maybe_last_archived_block.is_some();
676    let mut best_archived_block = None;
677
678    let mut archiver =
679        if let Some((last_segment_header, last_archived_block, block_object_mappings)) =
680            maybe_last_archived_block
681        {
682            // Continuing from existing initial state
683            let last_archived_block_number = last_segment_header.last_archived_block().number;
684            info!(
685                %last_archived_block_number,
686                "Resuming archiver from last archived block",
687            );
688
689            // Set initial value, this is needed in case only genesis block was archived and there
690            // is nothing else available
691            best_archived_block.replace((
692                last_archived_block.block.hash(),
693                *last_archived_block.block.header().number(),
694            ));
695
696            let last_archived_block_encoded = encode_block(last_archived_block);
697
698            Archiver::with_initial_state(
699                subspace_link.kzg().clone(),
700                subspace_link.erasure_coding().clone(),
701                last_segment_header,
702                &last_archived_block_encoded,
703                block_object_mappings,
704            )
705            .map_err(|error| {
706                sp_blockchain::Error::Application(
707                    format!("Incorrect parameters for archiver: {error:?} {last_segment_header:?}")
708                        .into(),
709                )
710            })?
711        } else {
712            info!("Starting archiving from genesis");
713
714            Archiver::new(
715                subspace_link.kzg().clone(),
716                subspace_link.erasure_coding().clone(),
717            )
718        };
719
720    // Process blocks since last fully archived block up to the current head minus K
721    {
722        let blocks_to_archive_from = archiver
723            .last_archived_block_number()
724            .map(|n| n + 1)
725            .unwrap_or_default();
726        let blocks_to_archive_to = best_block_number
727            .checked_sub(confirmation_depth_k)
728            .filter(|&blocks_to_archive_to| blocks_to_archive_to >= blocks_to_archive_from)
729            .or({
730                if have_last_segment_header {
731                    None
732                } else {
733                    // If not continuation, archive genesis block
734                    Some(0)
735                }
736            });
737
738        if let Some(blocks_to_archive_to) = blocks_to_archive_to {
739            info!(
740                "Archiving already produced blocks {}..={}",
741                blocks_to_archive_from, blocks_to_archive_to,
742            );
743
744            let thread_pool = ThreadPoolBuilder::new()
745                .num_threads(BLOCKS_TO_ARCHIVE_CONCURRENCY)
746                .build()
747                .map_err(|error| {
748                    sp_blockchain::Error::Backend(format!(
749                        "Failed to create thread pool for archiver initialization: {error}"
750                    ))
751                })?;
752            // We need to limit number of threads to avoid running out of WASM instances
753            let blocks_to_archive = thread_pool.install(|| {
754                (blocks_to_archive_from..=blocks_to_archive_to)
755                    .into_par_iter()
756                    .map(|block_number| {
757                        let block_hash = client
758                            .hash(block_number.into())?
759                            .expect("All blocks since last archived must be present; qed");
760
761                        let block = client
762                            .block(block_hash)?
763                            .expect("All blocks since last archived must be present; qed");
764
765                        let block_object_mappings =
766                            if create_object_mappings.is_enabled_for_block(block_number) {
767                                // A runtime API instance only works for one block, reusing it
768                                // fails with `UsingSameInstanceForDifferentBlocks`
769                                client
770                                    .runtime_api()
771                                    .extract_block_object_mapping(
772                                        *block.block.header().parent_hash(),
773                                        block.block.clone(),
774                                    )
775                                    .map_err(|error| {
776                                        sp_blockchain::Error::Application(
777                                            format!(
778                                                "Failed to retrieve block object mappings for \
779                                                block {block_number}: {error}"
780                                            )
781                                            .into(),
782                                        )
783                                    })?
784                            } else {
785                                BlockObjectMapping::default()
786                            };
787
788                        Ok((block, block_object_mappings))
789                    })
790                    .collect::<sp_blockchain::Result<Vec<(SignedBlock<_>, _)>>>()
791            })?;
792
793            best_archived_block =
794                blocks_to_archive
795                    .last()
796                    .map(|(block, _block_object_mappings)| {
797                        (block.block.hash(), *block.block.header().number())
798                    });
799
800            for (signed_block, block_object_mappings) in blocks_to_archive {
801                let block_number_to_archive = *signed_block.block.header().number();
802                let encoded_block = encode_block(signed_block);
803
804                debug!(
805                    "Encoded block {} has size of {}",
806                    block_number_to_archive,
807                    bytesize::ByteSize::b(encoded_block.len() as u64)
808                        .display()
809                        .iec(),
810                );
811
812                let block_outcome = archiver.add_block(encoded_block, block_object_mappings, false);
813                send_object_mapping_notification(
814                    &subspace_link.object_mapping_notification_sender,
815                    block_outcome.object_mapping,
816                    block_number_to_archive,
817                );
818                let new_segment_headers: Vec<SegmentHeader> = block_outcome
819                    .archived_segments
820                    .iter()
821                    .map(|archived_segment| archived_segment.segment_header)
822                    .collect();
823
824                if !new_segment_headers.is_empty() {
825                    segment_headers_store.add_segment_headers(&new_segment_headers)?;
826                }
827            }
828        }
829    }
830
831    Ok(InitializedArchiver {
832        archiver,
833        best_archived_block: best_archived_block
834            .expect("Must always set if there is no logical error; qed"),
835    })
836}
837
838fn finalize_block<Block, Backend, Client>(
839    client: &Client,
840    backend: &Backend,
841    telemetry: Option<&TelemetryHandle>,
842    hash: Block::Hash,
843    number: NumberFor<Block>,
844) where
845    Block: BlockT,
846    Backend: BackendT<Block>,
847    Client: LockImportRun<Block, Backend> + Finalizer<Block, Backend> + HeaderBackend<Block>,
848{
849    if number.is_zero() {
850        // Block zero is finalized already and generates unnecessary warning if called again
851        return;
852    }
853
854    let displaced = match client.header(hash) {
855        Ok(Some(header)) => {
856            let parent_hash = *header.parent_hash();
857            match backend
858                .blockchain()
859                .displaced_leaves_after_finalizing(hash, number, parent_hash)
860            {
861                Ok(d) => Some(d),
862                Err(error) => {
863                    warn!(
864                        ?error,
865                        ?hash,
866                        ?parent_hash,
867                        ?number,
868                        "Failed to compute displaced leaves; their block_weight entries will leak"
869                    );
870                    None
871                }
872            }
873        }
874        Ok(None) => {
875            warn!(
876                ?hash,
877                ?number,
878                "Header missing for finalized hash; skipping displaced-fork cleanup"
879            );
880            None
881        }
882        Err(error) => {
883            warn!(
884                ?error,
885                ?hash,
886                ?number,
887                "Failed to load header for finalized hash; skipping displaced-fork cleanup"
888            );
889            None
890        }
891    };
892
893    // We don't have anything useful to do with this result yet, the only source of errors was
894    // logged already inside
895    let _result: sp_blockchain::Result<_> = client.lock_import_and_run(|import_op| {
896        // Ideally some handle to a synchronization oracle would be used to avoid unconditionally
897        // notifying.
898        client
899            .apply_finality(import_op, hash, None, true)
900            .map_err(|error| {
901                warn!(
902                    "Error applying finality to block {:?}: {}",
903                    (hash, number),
904                    error
905                );
906                error
907            })?;
908
909        if let Some(d) = &displaced
910            && !d.displaced_blocks.is_empty()
911        {
912            let count = d.displaced_blocks.len();
913            let tombstones = d
914                .displaced_blocks
915                .iter()
916                .map(|h| (crate::aux_schema::block_weight_key(h), None));
917            import_op.op.insert_aux(tombstones).map_err(|error| {
918                warn!(
919                    ?error,
920                    count, "Failed to queue displaced fork tombstones; rolling back finalization",
921                );
922                error
923            })?;
924        }
925
926        debug!("Finalizing blocks up to ({:?}, {})", number, hash);
927
928        telemetry!(
929            telemetry;
930            CONSENSUS_INFO;
931            "subspace.finalized_blocks_up_to";
932            "number" => ?number, "hash" => ?hash,
933        );
934
935        Ok(())
936    });
937}
938
939/// Create an archiver task.
940///
941/// Archiver task will listen for importing blocks and archive blocks at `K` depth, producing pieces
942/// and segment headers (segment headers are then added back to the blockchain as
943/// `store_segment_header` extrinsic).
944///
945/// NOTE: Archiver is doing blocking operations and must run in a dedicated task.
946///
947/// Archiver is only able to move forward and doesn't support reorgs. Upon restart it will check
948/// [`SegmentHeadersStore`] and chain history to reconstruct "current" state it was in before last
949/// shutdown and continue incrementally archiving blockchain history from there.
950///
951/// Archiving is triggered by block importing notification ([`SubspaceLink::block_importing_notification_stream`])
952/// and tries to archive the block at [`ChainConstants::confirmation_depth_k`](sp_consensus_subspace::ChainConstants::confirmation_depth_k)
953/// depth from the block being imported. Block import will then wait for archiver to acknowledge
954/// processing, which is necessary for ensuring that when the next block is imported, inherents will
955/// contain segment header of newly archived block (must happen exactly in the next block).
956///
957/// `create_object_mappings` controls when object mappings are created for archived blocks. When
958/// these mappings are created, a ([`SubspaceLink::object_mapping_notification_stream`])
959/// notification will be sent.
960///
961/// Once segment header is archived, notification ([`SubspaceLink::archived_segment_notification_stream`])
962/// will be sent and archiver will be paused until all receivers have provided an acknowledgement
963/// for it.
964///
965/// Archiving will be incremental during normal operation to decrease impact on block import and
966/// non-incremental heavily parallel during sync process since parallel implementation is more
967/// efficient overall and during sync only total sync time matters.
968pub fn create_subspace_archiver<Block, Backend, Client, AS, SO>(
969    segment_headers_store: SegmentHeadersStore<AS>,
970    subspace_link: SubspaceLink<Block>,
971    client: Arc<Client>,
972    backend: Arc<Backend>,
973    sync_oracle: SubspaceSyncOracle<SO>,
974    telemetry: Option<TelemetryHandle>,
975    create_object_mappings: CreateObjectMappings,
976) -> sp_blockchain::Result<impl Future<Output = sp_blockchain::Result<()>> + Send + 'static>
977where
978    Block: BlockT,
979    Backend: BackendT<Block> + 'static,
980    Client: ProvideRuntimeApi<Block>
981        + BlockBackend<Block>
982        + HeaderBackend<Block>
983        + LockImportRun<Block, Backend>
984        + Finalizer<Block, Backend>
985        + BlockchainEvents<Block>
986        + AuxStore
987        + Send
988        + Sync
989        + 'static,
990    Client::Api: SubspaceApi<Block, PublicKey> + ObjectsApi<Block>,
991    AS: AuxStore + Send + Sync + 'static,
992    SO: SyncOracle + Send + Sync + 'static,
993{
994    if create_object_mappings.is_enabled() {
995        info!(
996            ?create_object_mappings,
997            "Creating object mappings from the configured block onwards"
998        );
999    } else {
1000        info!("Not creating object mappings");
1001    }
1002
1003    let maybe_archiver = if segment_headers_store.max_segment_index().is_none() {
1004        Some(initialize_archiver(
1005            &segment_headers_store,
1006            &subspace_link,
1007            client.as_ref(),
1008            create_object_mappings,
1009        )?)
1010    } else {
1011        None
1012    };
1013
1014    // Subscribing synchronously before returning
1015    let mut block_importing_notification_stream = subspace_link
1016        .block_importing_notification_stream
1017        .subscribe();
1018
1019    Ok(async move {
1020        let archiver = match maybe_archiver {
1021            Some(archiver) => archiver,
1022            None => initialize_archiver(
1023                &segment_headers_store,
1024                &subspace_link,
1025                client.as_ref(),
1026                create_object_mappings,
1027            )?,
1028        };
1029        let confirmation_depth_k = subspace_link.chain_constants.confirmation_depth_k().into();
1030
1031        let InitializedArchiver {
1032            mut archiver,
1033            best_archived_block,
1034        } = archiver;
1035        let (mut best_archived_block_hash, mut best_archived_block_number) = best_archived_block;
1036
1037        while let Some(block_importing_notification) =
1038            block_importing_notification_stream.next().await
1039        {
1040            let importing_block_number = block_importing_notification.block_number;
1041            let block_number_to_archive =
1042                match importing_block_number.checked_sub(&confirmation_depth_k) {
1043                    Some(block_number_to_archive) => block_number_to_archive,
1044                    None => {
1045                        // Too early to archive blocks
1046                        continue;
1047                    }
1048                };
1049
1050            let last_archived_block_number = segment_headers_store
1051                .last_segment_header()
1052                .expect("Exists after archiver initialization; qed")
1053                .last_archived_block()
1054                .number;
1055            let create_mappings =
1056                create_object_mappings.is_enabled_for_block(last_archived_block_number);
1057            let last_archived_block_number = NumberFor::<Block>::from(last_archived_block_number);
1058            trace!(
1059                %importing_block_number,
1060                %block_number_to_archive,
1061                %best_archived_block_number,
1062                %last_archived_block_number,
1063                "Checking if block needs to be skipped"
1064            );
1065
1066            // Skip archived blocks, unless we're producing object mappings for them
1067            let skip_last_archived_blocks =
1068                last_archived_block_number > block_number_to_archive && !create_mappings;
1069            if best_archived_block_number >= block_number_to_archive || skip_last_archived_blocks {
1070                // This block was already archived, skip
1071                debug!(
1072                    %importing_block_number,
1073                    %block_number_to_archive,
1074                    %best_archived_block_number,
1075                    %last_archived_block_number,
1076                    "Skipping already archived block",
1077                );
1078                continue;
1079            }
1080
1081            // In case there was a block gap re-initialize archiver and continue with current
1082            // block number (rather than block number at some depth) to allow for special sync
1083            // modes where pre-verified blocks are inserted at some point in the future comparing to
1084            // previously existing blocks
1085            if best_archived_block_number + One::one() != block_number_to_archive {
1086                InitializedArchiver {
1087                    archiver,
1088                    best_archived_block: (best_archived_block_hash, best_archived_block_number),
1089                } = initialize_archiver(
1090                    &segment_headers_store,
1091                    &subspace_link,
1092                    client.as_ref(),
1093                    create_object_mappings,
1094                )?;
1095
1096                if best_archived_block_number + One::one() == block_number_to_archive {
1097                    // As expected, can archive this block
1098                } else if best_archived_block_number >= block_number_to_archive {
1099                    // Special sync mode where verified blocks were inserted into blockchain
1100                    // directly, archiving of this block will naturally happen later
1101                    continue;
1102                } else if client
1103                    .block_hash(importing_block_number - One::one())?
1104                    .is_none()
1105                {
1106                    // We may have imported some block using special sync mode and block we're about
1107                    // to import is the first one after the gap at which archiver is supposed to be
1108                    // initialized, but we are only about to import it, so wait for the next block
1109                    // for now
1110                    continue;
1111                } else {
1112                    let error = format!(
1113                        "There was a gap in blockchain history and the last contiguous series of \
1114                        blocks starting with doesn't start with archived segment (best archived \
1115                        block number {best_archived_block_number}, block number to archive \
1116                        {block_number_to_archive}), block about to be imported \
1117                        {importing_block_number}), archiver can't continue",
1118                    );
1119                    return Err(sp_blockchain::Error::Consensus(sp_consensus::Error::Other(
1120                        error.into(),
1121                    )));
1122                }
1123            }
1124
1125            let max_segment_index_before = segment_headers_store.max_segment_index();
1126            (best_archived_block_hash, best_archived_block_number) = archive_block(
1127                &mut archiver,
1128                segment_headers_store.clone(),
1129                &*client,
1130                &sync_oracle,
1131                subspace_link.object_mapping_notification_sender.clone(),
1132                subspace_link.archived_segment_notification_sender.clone(),
1133                best_archived_block_hash,
1134                block_number_to_archive,
1135                create_object_mappings,
1136            )
1137            .await?;
1138
1139            let max_segment_index = segment_headers_store.max_segment_index();
1140            if max_segment_index_before != max_segment_index {
1141                let maybe_block_number_to_finalize = max_segment_index
1142                    // Skip last `FINALIZATION_DEPTH_IN_SEGMENTS` archived segments
1143                    .and_then(|max_segment_index| {
1144                        max_segment_index.checked_sub(FINALIZATION_DEPTH_IN_SEGMENTS)
1145                    })
1146                    .and_then(|segment_index| {
1147                        segment_headers_store.get_segment_header(segment_index)
1148                    })
1149                    .map(|segment_header| segment_header.last_archived_block().number)
1150                    // Make sure not to finalize block number that does not yet exist (segment
1151                    // headers store may contain future blocks during initial sync)
1152                    .map(|block_number| block_number_to_archive.min(block_number.into()))
1153                    // Do not finalize blocks twice
1154                    .filter(|block_number| *block_number > client.info().finalized_number);
1155
1156                if let Some(block_number_to_finalize) = maybe_block_number_to_finalize {
1157                    {
1158                        let mut import_notification = client.every_import_notification_stream();
1159
1160                        // Drop notification to drop acknowledgement and allow block import to
1161                        // proceed
1162                        drop(block_importing_notification);
1163
1164                        while let Some(notification) = import_notification.next().await {
1165                            // Wait for importing block to finish importing
1166                            if notification.header.number() == &importing_block_number {
1167                                break;
1168                            }
1169                        }
1170                    }
1171
1172                    // Block is not guaranteed to be present this deep if we have only synced recent
1173                    // blocks.
1174                    if let Some(block_hash_to_finalize) =
1175                        client.block_hash(block_number_to_finalize)?
1176                    {
1177                        finalize_block(
1178                            &*client,
1179                            &*backend,
1180                            telemetry.as_ref(),
1181                            block_hash_to_finalize,
1182                            block_number_to_finalize,
1183                        );
1184                    }
1185                }
1186            }
1187        }
1188
1189        Ok(())
1190    })
1191}
1192
1193/// Tries to archive `block_number` and returns new (or old if not changed) best archived block
1194#[allow(clippy::too_many_arguments)]
1195async fn archive_block<Block, Backend, Client, AS, SO>(
1196    archiver: &mut Archiver,
1197    segment_headers_store: SegmentHeadersStore<AS>,
1198    client: &Client,
1199    sync_oracle: &SubspaceSyncOracle<SO>,
1200    object_mapping_notification_sender: SubspaceNotificationSender<ObjectMappingNotification>,
1201    archived_segment_notification_sender: SubspaceNotificationSender<ArchivedSegmentNotification>,
1202    best_archived_block_hash: Block::Hash,
1203    block_number_to_archive: NumberFor<Block>,
1204    create_object_mappings: CreateObjectMappings,
1205) -> sp_blockchain::Result<(Block::Hash, NumberFor<Block>)>
1206where
1207    Block: BlockT,
1208    Backend: BackendT<Block>,
1209    Client: ProvideRuntimeApi<Block>
1210        + BlockBackend<Block>
1211        + HeaderBackend<Block>
1212        + LockImportRun<Block, Backend>
1213        + Finalizer<Block, Backend>
1214        + AuxStore
1215        + Send
1216        + Sync
1217        + 'static,
1218    Client::Api: SubspaceApi<Block, PublicKey> + ObjectsApi<Block>,
1219    AS: AuxStore + Send + Sync + 'static,
1220    SO: SyncOracle + Send + Sync + 'static,
1221{
1222    let block = client
1223        .block(
1224            client
1225                .block_hash(block_number_to_archive)?
1226                .expect("Older block by number must always exist"),
1227        )?
1228        .expect("Older block by number must always exist");
1229
1230    let parent_block_hash = *block.block.header().parent_hash();
1231    let block_hash_to_archive = block.block.hash();
1232
1233    debug!(
1234        "Archiving block {:?} ({})",
1235        block_number_to_archive, block_hash_to_archive
1236    );
1237
1238    if parent_block_hash != best_archived_block_hash {
1239        let error = format!(
1240            "Attempt to switch to a different fork beyond archiving depth, \
1241            can't do it: parent block hash {parent_block_hash}, best archived block hash {best_archived_block_hash}"
1242        );
1243        return Err(sp_blockchain::Error::Consensus(sp_consensus::Error::Other(
1244            error.into(),
1245        )));
1246    }
1247
1248    let create_mappings = create_object_mappings.is_enabled_for_block(
1249        block_number_to_archive.try_into().unwrap_or_else(|_| {
1250            unreachable!("sp_runtime::BlockNumber fits into subspace_primitives::BlockNumber; qed")
1251        }),
1252    );
1253
1254    let block_object_mappings = if create_mappings {
1255        client
1256            .runtime_api()
1257            .extract_block_object_mapping(parent_block_hash, block.block.clone())
1258            .map_err(|error| {
1259                sp_blockchain::Error::Application(
1260                    format!("Failed to retrieve block object mappings: {error}").into(),
1261                )
1262            })?
1263    } else {
1264        BlockObjectMapping::default()
1265    };
1266
1267    let encoded_block = encode_block(block);
1268    debug!(
1269        "Encoded block {} has size of {}",
1270        block_number_to_archive,
1271        bytesize::ByteSize::b(encoded_block.len() as u64)
1272            .display()
1273            .iec(),
1274    );
1275
1276    let block_outcome = archiver.add_block(
1277        encoded_block,
1278        block_object_mappings,
1279        !sync_oracle.is_major_syncing(),
1280    );
1281    send_object_mapping_notification(
1282        &object_mapping_notification_sender,
1283        block_outcome.object_mapping,
1284        block_number_to_archive,
1285    );
1286    for archived_segment in block_outcome.archived_segments {
1287        let segment_header = archived_segment.segment_header;
1288
1289        segment_headers_store.add_segment_headers(slice::from_ref(&segment_header))?;
1290
1291        send_archived_segment_notification(&archived_segment_notification_sender, archived_segment)
1292            .await;
1293    }
1294
1295    Ok((block_hash_to_archive, block_number_to_archive))
1296}
1297
1298fn send_object_mapping_notification<BlockNum>(
1299    object_mapping_notification_sender: &SubspaceNotificationSender<ObjectMappingNotification>,
1300    object_mapping: Vec<GlobalObject>,
1301    block_number: BlockNum,
1302) where
1303    BlockNum: BlockNumberT,
1304{
1305    if object_mapping.is_empty() {
1306        return;
1307    }
1308
1309    let block_number = TryInto::<BlockNumber>::try_into(block_number).unwrap_or_else(|_| {
1310        unreachable!("sp_runtime::BlockNumber fits into subspace_primitives::BlockNumber; qed");
1311    });
1312
1313    let object_mapping_notification = ObjectMappingNotification {
1314        object_mapping,
1315        block_number,
1316    };
1317
1318    object_mapping_notification_sender.notify(move || object_mapping_notification);
1319}
1320
1321async fn send_archived_segment_notification(
1322    archived_segment_notification_sender: &SubspaceNotificationSender<ArchivedSegmentNotification>,
1323    archived_segment: NewArchivedSegment,
1324) {
1325    let segment_index = archived_segment.segment_header.segment_index();
1326    let (acknowledgement_sender, mut acknowledgement_receiver) =
1327        tracing_unbounded::<()>("subspace_acknowledgement", 1000);
1328    // Keep `archived_segment` around until all acknowledgements are received since some receivers
1329    // might use weak references
1330    let archived_segment = Arc::new(archived_segment);
1331    let archived_segment_notification = ArchivedSegmentNotification {
1332        archived_segment: Arc::clone(&archived_segment),
1333        acknowledgement_sender,
1334    };
1335
1336    archived_segment_notification_sender.notify(move || archived_segment_notification);
1337
1338    let wait_fut = async {
1339        while acknowledgement_receiver.next().await.is_some() {
1340            debug!(
1341                "Archived segment notification acknowledged: {}",
1342                segment_index
1343            );
1344        }
1345    };
1346
1347    if tokio::time::timeout(ACKNOWLEDGEMENT_TIMEOUT, wait_fut)
1348        .await
1349        .is_err()
1350    {
1351        warn!(
1352            "Archived segment notification was not acknowledged and reached timeout, continue \
1353            regardless"
1354        );
1355    }
1356}