smoldot-light 0.4.0

Browser bindings to a light 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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
// Smoldot
// 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/>.

//! This module contains useful features built on top of the [`RuntimeService`] that are only used
//! by the JSON-RPC service.

use crate::{
    platform::PlatformRef,
    runtime_service::{Notification, RuntimeError, RuntimeService},
};

use alloc::{sync::Arc, vec::Vec};
use core::num::NonZeroUsize;
use futures_util::{future, stream, StreamExt as _};
use smoldot::{executor, header};

/// Returns the current runtime version, plus an unlimited stream that produces one item every
/// time the specs of the runtime of the best block are changed.
///
/// The future returned by this function waits until the runtime is available. This can take
/// a long time.
///
/// The stream can generate an `Err` if the runtime in the best block is invalid.
///
/// The stream is infinite. In other words it is guaranteed to never return `None`.
pub async fn subscribe_runtime_version<TPlat: PlatformRef>(
    runtime_service: &Arc<RuntimeService<TPlat>>,
) -> (
    Result<executor::CoreVersion, RuntimeError>,
    stream::BoxStream<'static, Result<executor::CoreVersion, RuntimeError>>,
) {
    let mut master_stream = stream::unfold(runtime_service.clone(), |runtime_service| async move {
        let subscribe_all = runtime_service
            .subscribe_all("subscribe-runtime-version", 16, NonZeroUsize::new(24).unwrap())
            .await;

        // Map of runtimes by hash. Contains all non-finalized blocks, plus the current finalized
        // block.
        let mut headers = hashbrown::HashMap::<
            [u8; 32],
            Arc<Result<executor::CoreVersion, RuntimeError>>,
            fnv::FnvBuildHasher,
        >::with_capacity_and_hasher(16, Default::default());

        let current_finalized_hash = header::hash_from_scale_encoded_header(
            &subscribe_all.finalized_block_scale_encoded_header,
        );
        subscribe_all
            .new_blocks
            .unpin_block(&current_finalized_hash)
            .await;

        headers.insert(
            current_finalized_hash,
            Arc::new(subscribe_all.finalized_block_runtime),
        );

        let mut current_best = None;
        for block in subscribe_all.non_finalized_blocks_ancestry_order {
            let hash = header::hash_from_scale_encoded_header(&block.scale_encoded_header);
            subscribe_all.new_blocks.unpin_block(&hash).await;

            if let Some(new_runtime) = block.new_runtime {
                headers.insert(hash, Arc::new(new_runtime));
            } else {
                let parent_runtime = headers
                    .get(&block.parent_hash)
                    .unwrap()
                    .clone();
                headers.insert(hash, parent_runtime);
            }

            if block.is_new_best {
                debug_assert!(current_best.is_none());
                current_best = Some(hash);
            }
        }
        let current_best = current_best.unwrap_or(current_finalized_hash);
        let current_best_runtime = (**headers.get(&current_best).unwrap()).clone();

        // Turns `subscribe_all.new_blocks` into a stream of headers.
        let substream = stream::unfold(
            (
                subscribe_all.new_blocks,
                headers,
                current_finalized_hash,
                current_best,
            ),
            |(
                mut new_blocks,
                mut headers,
                mut current_finalized_hash,
                mut current_best,
            )| async move {
                loop {
                    match new_blocks.next().await? {
                        Notification::Block(block) => {
                            let hash =
                                header::hash_from_scale_encoded_header(&block.scale_encoded_header);
                            new_blocks.unpin_block(&hash).await;

                            if let Some(new_runtime) = block.new_runtime {
                                headers.insert(hash, Arc::new(new_runtime));
                            } else {
                                let parent_runtime = headers
                                    .get(&block.parent_hash)
                                    .unwrap()
                                    .clone();
                                headers.insert(hash, parent_runtime);
                            }

                            if block.is_new_best {
                                let current_best_runtime =
                                    headers.get(&current_best).unwrap();
                                let new_best_runtime = headers.get(&hash).unwrap();
                                current_best = hash;

                                if !Arc::ptr_eq(current_best_runtime, new_best_runtime) {
                                    let runtime = (**new_best_runtime).clone();
                                    break Some((
                                        runtime,
                                        (
                                            new_blocks,
                                            headers,
                                            current_finalized_hash,
                                            current_best,
                                        ),
                                    ));
                                }
                            }
                        }
                        Notification::Finalized {
                            hash,
                            pruned_blocks,
                            best_block_hash,
                        } => {
                            let current_best_runtime =
                                headers.get(&current_best).unwrap().clone();
                            let new_best_runtime =
                                headers.get(&best_block_hash).unwrap().clone();

                            // Clean up the headers we won't need anymore.
                            for pruned_block in pruned_blocks {
                                let _was_in = headers.remove(&pruned_block);
                                debug_assert!(_was_in.is_some());
                            }

                            let _ = headers
                                .remove(&current_finalized_hash)
                                .unwrap();
                            current_finalized_hash = hash;
                            current_best = best_block_hash;

                            if !Arc::ptr_eq(&current_best_runtime, &new_best_runtime) {
                                let runtime = (*new_best_runtime).clone();
                                break Some((
                                    runtime,
                                    (
                                        new_blocks,
                                        headers,
                                        current_finalized_hash,
                                        current_best,
                                    ),
                                ));
                            }
                        }
                        Notification::BestBlockChanged { hash } => {
                            let current_best_runtime =
                                headers.get(&current_best).unwrap().clone();
                            let new_best_runtime =
                                headers.get(&hash).unwrap().clone();

                            current_best = hash;

                            if !Arc::ptr_eq(&current_best_runtime, &new_best_runtime) {
                                let runtime = (*new_best_runtime).clone();
                                break Some((
                                    runtime,
                                    (
                                        new_blocks,
                                        headers,
                                        current_finalized_hash,
                                        current_best,
                                    ),
                                ));
                            }
                        }
                    }
                }
            },
        );

        // Prepend the current best block to the stream.
        let substream = stream::once(future::ready(current_best_runtime)).chain(substream);
        Some((substream, runtime_service))
    })
    .flatten()
    .boxed();

    // TODO: we don't dedup blocks; in other words the stream can produce the same block twice if the inner subscription drops

    // Now that we have a stream, extract the first element to be the first value.
    let first_value = master_stream.next().await.unwrap();
    (first_value, master_stream)
}

/// Returns the SCALE-encoded header of the current finalized block, plus an unlimited stream
/// that produces one item every time the finalized block is changed.
///
/// This function only returns once the runtime of the current finalized block is known. This
/// might take a long time.
pub async fn subscribe_finalized<TPlat: PlatformRef>(
    runtime_service: &Arc<RuntimeService<TPlat>>,
) -> (Vec<u8>, stream::BoxStream<'static, Vec<u8>>) {
    let mut master_stream = stream::unfold(runtime_service.clone(), |runtime_service| async move {
        let subscribe_all = runtime_service
            .subscribe_all("subscribe-finalized", 16, NonZeroUsize::new(32).unwrap())
            .await;

        // Map of block headers by hash. Contains all non-finalized blocks headers.
        let mut non_finalized_headers =
            hashbrown::HashMap::<[u8; 32], Vec<u8>, fnv::FnvBuildHasher>::with_capacity_and_hasher(
                16,
                Default::default(),
            );

        subscribe_all
            .new_blocks
            .unpin_block(&header::hash_from_scale_encoded_header(
                &subscribe_all.finalized_block_scale_encoded_header,
            ))
            .await;

        for block in subscribe_all.non_finalized_blocks_ancestry_order {
            let hash = header::hash_from_scale_encoded_header(&block.scale_encoded_header);
            subscribe_all.new_blocks.unpin_block(&hash).await;
            non_finalized_headers.insert(hash, block.scale_encoded_header);
        }

        // Turns `subscribe_all.new_blocks` into a stream of headers.
        let substream = stream::unfold(
            (subscribe_all.new_blocks, non_finalized_headers),
            |(mut new_blocks, mut non_finalized_headers)| async {
                loop {
                    match new_blocks.next().await? {
                        Notification::Block(block) => {
                            let hash =
                                header::hash_from_scale_encoded_header(&block.scale_encoded_header);
                            new_blocks.unpin_block(&hash).await;
                            non_finalized_headers.insert(hash, block.scale_encoded_header);
                        }
                        Notification::Finalized {
                            hash,
                            pruned_blocks,
                            ..
                        } => {
                            // Clean up the headers we won't need anymore.
                            for pruned_block in pruned_blocks {
                                let _was_in = non_finalized_headers.remove(&pruned_block);
                                debug_assert!(_was_in.is_some());
                            }

                            let header = non_finalized_headers.remove(&hash).unwrap();
                            break Some((header, (new_blocks, non_finalized_headers)));
                        }
                        Notification::BestBlockChanged { .. } => {}
                    }
                }
            },
        );

        // Prepend the current finalized block to the stream.
        let substream = stream::once(future::ready(
            subscribe_all.finalized_block_scale_encoded_header,
        ))
        .chain(substream);

        Some((substream, runtime_service))
    })
    .flatten()
    .boxed();

    // TODO: we don't dedup blocks; in other words the stream can produce the same block twice if the inner subscription drops

    // Now that we have a stream, extract the first element to be the first value.
    let first_value = master_stream.next().await.unwrap();
    (first_value, master_stream)
}

/// Returns the SCALE-encoded header of the current best block, plus an unlimited stream that
/// produces one item every time the best block is changed.
///
/// This function only returns once the runtime of the current best block is known. This might
/// take a long time.
pub async fn subscribe_best<TPlat: PlatformRef>(
    runtime_service: &Arc<RuntimeService<TPlat>>,
) -> (Vec<u8>, stream::BoxStream<'static, Vec<u8>>) {
    let mut master_stream = stream::unfold(runtime_service.clone(), |runtime_service| async move {
        let subscribe_all = runtime_service
            .subscribe_all("subscribe-best", 16, NonZeroUsize::new(32).unwrap())
            .await;

        // Map of block headers by hash. Contains all non-finalized blocks headers, plus the
        // current finalized block header.
        let mut headers =
            hashbrown::HashMap::<[u8; 32], Vec<u8>, fnv::FnvBuildHasher>::with_capacity_and_hasher(
                16,
                Default::default(),
            );

        let current_finalized_hash = header::hash_from_scale_encoded_header(
            &subscribe_all.finalized_block_scale_encoded_header,
        );

        subscribe_all
            .new_blocks
            .unpin_block(&current_finalized_hash)
            .await;

        headers.insert(
            current_finalized_hash,
            subscribe_all.finalized_block_scale_encoded_header,
        );

        let mut current_best = None;
        for block in subscribe_all.non_finalized_blocks_ancestry_order {
            let hash = header::hash_from_scale_encoded_header(&block.scale_encoded_header);
            subscribe_all.new_blocks.unpin_block(&hash).await;
            headers.insert(hash, block.scale_encoded_header);

            if block.is_new_best {
                debug_assert!(current_best.is_none());
                current_best = Some(hash);
            }
        }
        let current_best = current_best.unwrap_or(current_finalized_hash);
        let current_best_header = headers.get(&current_best).unwrap().clone();

        // Turns `subscribe_all.new_blocks` into a stream of headers.
        let substream = stream::unfold(
            (
                subscribe_all.new_blocks,
                headers,
                current_finalized_hash,
                current_best,
            ),
            |(
                mut new_blocks,
                mut headers,
                mut current_finalized_hash,
                mut current_best,
            )| async move {
                loop {
                    match new_blocks.next().await? {
                        Notification::Block(block) => {
                            let hash =
                                header::hash_from_scale_encoded_header(&block.scale_encoded_header);
                            new_blocks.unpin_block(&hash).await;
                            headers.insert(hash, block.scale_encoded_header);

                            if block.is_new_best {
                                current_best = hash;
                                let header =
                                    headers.get(&current_best).unwrap().clone();
                                break Some((
                                    header,
                                    (
                                        new_blocks,
                                        headers,
                                        current_finalized_hash,
                                        current_best,
                                    ),
                                ));
                            }
                        }
                        Notification::Finalized {
                            hash,
                            pruned_blocks,
                            best_block_hash,
                        } => {
                            // Clean up the headers we won't need anymore.
                            for pruned_block in pruned_blocks {
                                let _was_in = headers.remove(&pruned_block);
                                debug_assert!(_was_in.is_some());
                            }

                            let _ = headers
                                .remove(&current_finalized_hash)
                                .unwrap();
                            current_finalized_hash = hash;

                            if best_block_hash != current_best {
                                current_best = best_block_hash;
                                let header =
                                    headers.get(&current_best).unwrap().clone();
                                break Some((
                                    header,
                                    (
                                        new_blocks,
                                        headers,
                                        current_finalized_hash,
                                        current_best,
                                    ),
                                ));
                            }
                        }
                        Notification::BestBlockChanged { hash } => {
                            if hash != current_best {
                                current_best = hash;
                                let header =
                                    headers.get(&current_best).unwrap().clone();
                                break Some((
                                    header,
                                    (
                                        new_blocks,
                                        headers,
                                        current_finalized_hash,
                                        current_best,
                                    ),
                                ));
                            }
                        }
                    }
                }
            },
        );

        // Prepend the current best block to the stream.
        let substream = stream::once(future::ready(current_best_header)).chain(substream);
        Some((substream, runtime_service))
    })
    .flatten()
    .boxed();

    // TODO: we don't dedup blocks; in other words the stream can produce the same block twice if the inner subscription drops

    // Now that we have a stream, extract the first element to be the first value.
    let first_value = master_stream.next().await.unwrap();
    (first_value, master_stream)
}