smoldot 1.0.0

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

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

//! Collection of sources used for the `all_forks` syncing.
//!
//! Each source stored in the [`AllForksSources`] is associated to:
//!
//! - A [`SourceId`].
//! - A best block.
//! - A list of non-finalized blocks known by this source.
//! - An opaque user data, of type `TSrc`.
//!

use alloc::{collections::BTreeSet, vec::Vec};
use core::{fmt, ops};

/// Identifier for a source in the [`AllForksSources`].
//
// Implementation note: the `u64` values are never re-used, making it possible to avoid clearing
// obsolete SourceIds in the `AllForksSources` state machine.
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct SourceId(u64);

/// Collection of sources and which blocks they know about.
pub struct AllForksSources<TSrc> {
    /// Actual list of sources.
    sources: hashbrown::HashMap<SourceId, Source<TSrc>, fnv::FnvBuildHasher>,

    /// Identifier to allocate to the next source. Identifiers are never reused, which allows
    /// keeping obsolete identifiers in the internal state.
    next_source_id: SourceId,

    /// Stores `(source, block hash)` tuples. Each tuple is an information about the fact that
    /// this source knows about the given block. Only contains blocks whose height is strictly
    /// superior to [`AllForksSources::finalized_block_height`].
    known_blocks1: BTreeSet<(SourceId, u64, [u8; 32])>,

    /// Contains the same entries as [`AllForksSources::known_blocks1`], but in reverse.
    known_blocks2: BTreeSet<(u64, [u8; 32], SourceId)>,

    /// Height of the finalized block. All sources whose best block number is superior to this
    /// value is expected to know the entire finalized chain.
    finalized_block_height: u64,
}

/// Extra fields specific to each blocks source.
///
/// `best_block_number`/`best_block_hash` must be present in the known blocks.
#[derive(Debug)]
struct Source<TSrc> {
    best_block_number: u64,
    best_block_hash: [u8; 32],
    user_data: TSrc,
}

impl<TSrc> AllForksSources<TSrc> {
    /// Creates a new container. Must be passed the height of the known finalized block.
    pub fn new(sources_capacity: usize, finalized_block_height: u64) -> Self {
        AllForksSources {
            sources: hashbrown::HashMap::with_capacity_and_hasher(
                sources_capacity,
                Default::default(),
            ),
            next_source_id: SourceId(0),
            known_blocks1: Default::default(),
            known_blocks2: Default::default(),
            finalized_block_height,
        }
    }

    /// Returns the list of all [`SourceId`]s.
    pub fn keys(&self) -> impl ExactSizeIterator<Item = SourceId> {
        self.sources.keys().copied()
    }

    /// Returns true if the data structure is empty.
    pub fn is_empty(&self) -> bool {
        self.sources.is_empty()
    }

    /// Returns the number of sources in the data structure.
    pub fn len(&self) -> usize {
        self.sources.len()
    }

    /// Remove all the sources.
    pub fn clear(&mut self) {
        self.sources.clear();
        self.known_blocks1.clear();
        self.known_blocks2.clear();
    }

    /// Returns the list of all user datas of all sources.
    pub fn user_data_iter_mut(&mut self) -> impl ExactSizeIterator<Item = &mut TSrc> {
        self.sources.values_mut().map(|s| &mut s.user_data)
    }

    /// Returns the number of unique blocks in the data structure.
    // TODO: is this method needed at all?
    pub fn num_blocks(&self) -> usize {
        // TODO: optimize; shouldn't be O(n)
        self.known_blocks2
            .iter()
            .fold((0, None), |(uniques, prev), next| match (prev, next) {
                (Some((pn, ph)), (nn, nh, _)) if pn == *nn && ph == *nh => {
                    (uniques, Some((pn, ph)))
                }
                (_, (nn, nh, _)) => (uniques + 1, Some((*nn, *nh))),
            })
            .0
    }

    /// Returns the finalized block height this state machine knows about.
    pub fn finalized_block_height(&self) -> u64 {
        self.finalized_block_height
    }

    /// Add a new source to the container.
    ///
    /// The `user_data` parameter is opaque and decided entirely by the user. It can later be
    /// retrieved using the `Index` trait implementation of this container.
    ///
    /// Returns the newly-created source entry.
    pub fn add_source(
        &mut self,
        best_block_number: u64,
        best_block_hash: [u8; 32],
        user_data: TSrc,
    ) -> SourceId {
        let new_id = {
            let id = self.next_source_id;
            self.next_source_id.0 += 1;
            id
        };

        self.sources.insert(
            new_id,
            Source {
                best_block_number,
                best_block_hash,
                user_data,
            },
        );

        if best_block_number > self.finalized_block_height {
            self.known_blocks1
                .insert((new_id, best_block_number, best_block_hash));
            self.known_blocks2
                .insert((best_block_number, best_block_hash, new_id));
        }

        new_id
    }

    /// Removes the source from the [`AllForksSources`].
    ///
    /// Returns the user data that was originally passed to [`AllForksSources::add_source`].
    ///
    /// # Panic
    ///
    /// Panics if the [`SourceId`] is out of range.
    ///
    #[track_caller]
    pub fn remove(&mut self, source_id: SourceId) -> TSrc {
        let source = self.sources.remove(&source_id).unwrap();

        // Purge `known_blocks1` and `known_blocks2`.
        let known_blocks = self
            .known_blocks1
            .range((source_id, 0, [0; 32])..=(source_id, u64::MAX, [0xff; 32]))
            .map(|(_, n, h)| (*n, *h))
            .collect::<Vec<_>>();
        for (height, hash) in known_blocks {
            let _was_in1 = self.known_blocks1.remove(&(source_id, height, hash));
            let _was_in2 = self.known_blocks2.remove(&(height, hash, source_id));
            debug_assert!(_was_in1);
            debug_assert!(_was_in2);
        }

        source.user_data
    }

    /// Updates the height of the finalized block.
    ///
    /// This removes from the collection, and will ignore in the future, all blocks whose height
    /// is inferior or equal to this value.
    ///
    /// # Panic
    ///
    /// Panics if the new height is inferior to the previous value.
    ///
    pub fn set_finalized_block_height(&mut self, height: u64) {
        assert!(height >= self.finalized_block_height);

        debug_assert_eq!(
            self.known_blocks2
                .range(
                    (0, [0; 32], SourceId(u64::MIN))
                        ..=(self.finalized_block_height, [0xff; 32], SourceId(u64::MAX)),
                )
                .count(),
            0
        );

        let entries = self
            .known_blocks2
            .range((0, [0; 32], SourceId(u64::MIN))..=(height, [0xff; 32], SourceId(u64::MAX)))
            .cloned()
            .collect::<Vec<_>>();

        for (height, hash, source_id) in entries {
            self.known_blocks2.remove(&(height, hash, source_id));
            let _was_in = self.known_blocks1.remove(&(source_id, height, hash));
            debug_assert!(_was_in);
        }

        self.finalized_block_height = height;
    }

    /// Registers a new block that the source is aware of.
    ///
    /// Has no effect if `height` is inferior or equal to the finalized block height.
    ///
    /// # Panic
    ///
    /// Panics if the [`SourceId`] is out of range.
    ///
    pub fn add_known_block(&mut self, source_id: SourceId, height: u64, hash: [u8; 32]) {
        if height > self.finalized_block_height {
            self.known_blocks1.insert((source_id, height, hash));
            self.known_blocks2.insert((height, hash, source_id));
        }
    }

    /// Removes a block from the list of blocks the sources are aware of.
    ///
    /// > **Note**: Alongside with [`AllForksSources::set_finalized_block_height`], this method
    /// >           can be used to prevent the data structure from growing indefinitely.
    pub fn remove_known_block(&mut self, height: u64, hash: &[u8; 32]) {
        let sources = self
            .known_blocks2
            .range((height, *hash, SourceId(u64::MIN))..=(height, *hash, SourceId(u64::MAX)))
            .map(|(_, _, source)| *source)
            .collect::<Vec<_>>();

        for source_id in sources {
            self.known_blocks2.remove(&(height, *hash, source_id));
            let _was_in = self.known_blocks1.remove(&(source_id, height, *hash));
            debug_assert!(_was_in);
        }
    }

    /// Removes a block from the list of blocks the source is aware of.
    ///
    /// Has no effect if the source didn't know this block.
    ///
    /// > **Note**: Can be used when a request is sent to a node, and the node answers that it
    /// >           doesn't know about the requested block contrary to previously believed.
    ///
    /// # Panic
    ///
    /// Panics if the [`SourceId`] is out of range.
    ///
    pub fn source_remove_known_block(&mut self, source_id: SourceId, height: u64, hash: &[u8; 32]) {
        let _was_in1 = self.known_blocks1.remove(&(source_id, height, *hash));
        let _was_in2 = self.known_blocks2.remove(&(height, *hash, source_id));
        debug_assert_eq!(_was_in1, _was_in2);
    }

    /// Registers a new block that the source is aware of and sets it as its best block.
    ///
    /// If the block height is inferior or equal to the finalized block height, the block itself
    /// isn't kept in memory but is still set as the source's best block.
    ///
    /// # Panic
    ///
    /// Panics if the [`SourceId`] is out of range.
    ///
    #[track_caller]
    pub fn add_known_block_and_set_best(
        &mut self,
        source_id: SourceId,
        height: u64,
        hash: [u8; 32],
    ) {
        self.add_known_block(source_id, height, hash);

        let source = self.sources.get_mut(&source_id).unwrap();
        source.best_block_number = height;
        source.best_block_hash = hash;
    }

    /// Returns the current best block of the given source.
    ///
    /// This corresponds either to the latest call to
    /// [`AllForksSources::add_known_block_and_set_best`], or to the parameter passed to
    /// [`AllForksSources::add_source`].
    ///
    /// # Panic
    ///
    /// Panics if the [`SourceId`] is invalid.
    ///
    pub fn best_block(&self, source_id: SourceId) -> (u64, &[u8; 32]) {
        let source = self.sources.get(&source_id).unwrap();
        (source.best_block_number, &source.best_block_hash)
    }

    /// Returns the list of sources for which [`AllForksSources::knows_non_finalized_block`]
    /// would return `true`.
    ///
    /// # Panic
    ///
    /// Panics if `height` is inferior or equal to the finalized block height. Finalized blocks
    /// are intentionally not tracked by this data structure, and panicking when asking for a
    /// potentially-finalized block prevents potentially confusing or erroneous situations.
    ///
    pub fn knows_non_finalized_block<'a>(
        &'a self,
        height: u64,
        hash: &[u8; 32],
    ) -> impl Iterator<Item = SourceId> + use<'a, TSrc> {
        assert!(height > self.finalized_block_height);
        self.known_blocks2
            .range((height, *hash, SourceId(u64::MIN))..=(height, *hash, SourceId(u64::MAX)))
            .map(|(_, _, id)| *id)
    }

    /// Returns true if [`AllForksSources::add_known_block`] or
    /// [`AllForksSources::add_known_block_and_set_best`] has earlier been called on this source
    /// with this height and hash, or if the source was originally created (using
    /// [`AllForksSources::add_source`]) with this height and hash.
    ///
    /// # Panic
    ///
    /// Panics if the [`SourceId`] is out of range.
    ///
    /// Panics if `height` is inferior or equal to the finalized block height. Finalized blocks
    /// are intentionally not tracked by this data structure, and panicking when asking for a
    /// potentially-finalized block prevents potentially confusing or erroneous situations.
    ///
    pub fn source_knows_non_finalized_block(
        &self,
        source_id: SourceId,
        height: u64,
        hash: &[u8; 32],
    ) -> bool {
        assert!(height > self.finalized_block_height);
        self.known_blocks1.contains(&(source_id, height, *hash))
    }

    /// Returns `true` if the [`SourceId`] is present in the collection.
    pub fn contains(&self, source_id: SourceId) -> bool {
        self.sources.contains_key(&source_id)
    }
}

impl<TSrc> ops::Index<SourceId> for AllForksSources<TSrc> {
    type Output = TSrc;

    #[track_caller]
    fn index(&self, id: SourceId) -> &TSrc {
        let source = self.sources.get(&id).unwrap();
        &source.user_data
    }
}

impl<TSrc> ops::IndexMut<SourceId> for AllForksSources<TSrc> {
    #[track_caller]
    fn index_mut(&mut self, id: SourceId) -> &mut TSrc {
        let source = self.sources.get_mut(&id).unwrap();
        &mut source.user_data
    }
}

impl<TSrc: fmt::Debug> fmt::Debug for AllForksSources<TSrc> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("AllForksSources")
            .field("sources", &self.sources)
            .field("finalized_block_height", &self.finalized_block_height)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn basic_works() {
        let mut sources = super::AllForksSources::new(256, 10);
        assert!(sources.is_empty());
        assert_eq!(sources.num_blocks(), 0);

        let source1 = sources.add_source(12, [1; 32], ());
        assert!(!sources.is_empty());
        assert_eq!(sources.len(), 1);
        assert_eq!(sources.num_blocks(), 1);
        assert!(sources.source_knows_non_finalized_block(source1, 12, &[1; 32]));

        sources.add_known_block_and_set_best(source1, 13, [2; 32]);
        assert_eq!(sources.num_blocks(), 2);
        assert!(sources.source_knows_non_finalized_block(source1, 12, &[1; 32]));
        assert!(sources.source_knows_non_finalized_block(source1, 13, &[2; 32]));

        sources.remove_known_block(13, &[2; 32]);
        assert_eq!(sources.num_blocks(), 1);
        assert!(sources.source_knows_non_finalized_block(source1, 12, &[1; 32]));
        assert!(!sources.source_knows_non_finalized_block(source1, 13, &[2; 32]));

        sources.set_finalized_block_height(12);
        assert_eq!(sources.num_blocks(), 0);

        sources.remove(source1);
        assert!(sources.is_empty());
        assert_eq!(sources.len(), 0);
    }
}