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
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
// 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/>.

// TODO: document all this

use crate::finality::{decode, decode::PrecommitRef}; // TODO: weird imports

use alloc::vec::Vec;
use core::{cmp, iter, mem};
use nom::Finish as _;

pub use crate::finality::decode::{CommitMessageRef, UnsignedPrecommitRef};

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GrandpaNotificationRef<'a> {
    Vote(VoteMessageRef<'a>),
    Commit(CommitMessageRef<'a>), // TODO: consider weaker type, since in different module
    Neighbor(NeighborPacket),
    CatchUpRequest(CatchUpRequest),
    CatchUp(CatchUpRef<'a>),
}

impl GrandpaNotificationRef<'_> {
    /// Returns an iterator to list of buffers which, when concatenated, produces the SCALE
    /// encoding of that object.
    pub fn scale_encoding(
        &self,
        block_number_bytes: usize,
    ) -> impl Iterator<Item = impl AsRef<[u8]> + Clone> + Clone {
        match self {
            GrandpaNotificationRef::Neighbor(n) => iter::once(either::Left(&[2u8]))
                .chain(n.scale_encoding(block_number_bytes).map(either::Right)),
            _ => todo!(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VoteMessageRef<'a> {
    pub round_number: u64,
    pub set_id: u64,
    pub message: MessageRef<'a>,
    pub signature: &'a [u8; 64],
    pub authority_public_key: &'a [u8; 32],
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MessageRef<'a> {
    Prevote(UnsignedPrevoteRef<'a>),
    Precommit(UnsignedPrecommitRef<'a>),
    PrimaryPropose(PrimaryProposeRef<'a>),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnsignedPrevoteRef<'a> {
    pub target_hash: &'a [u8; 32],
    pub target_number: u64,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrimaryProposeRef<'a> {
    pub target_hash: &'a [u8; 32],
    pub target_number: u64,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NeighborPacket {
    pub round_number: u64,
    pub set_id: u64,
    pub commit_finalized_height: u64,
}

impl NeighborPacket {
    /// Returns an iterator to list of buffers which, when concatenated, produces the SCALE
    /// encoding of that object.
    pub fn scale_encoding(
        &self,
        block_number_bytes: usize,
    ) -> impl Iterator<Item = impl AsRef<[u8]> + Clone> + Clone {
        let mut commit_finalized_height = Vec::with_capacity(cmp::max(
            block_number_bytes,
            mem::size_of_val(&self.commit_finalized_height),
        ));
        commit_finalized_height.extend(self.commit_finalized_height.to_le_bytes());
        // TODO: unclear what to do if the block number doesn't fit in `block_number_bytes`
        debug_assert!(
            !commit_finalized_height
                .iter()
                .skip(block_number_bytes)
                .any(|b| *b != 0)
        );
        commit_finalized_height.resize(block_number_bytes, 0);

        [
            either::Right(either::Left([1u8])),
            either::Left(self.round_number.to_le_bytes()),
            either::Left(self.set_id.to_le_bytes()),
            either::Right(either::Right(commit_finalized_height)),
        ]
        .into_iter()
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CatchUpRequest {
    pub round_number: u64,
    pub set_id: u64,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CatchUpRef<'a> {
    pub set_id: u64,
    pub round_number: u64,
    pub prevotes: Vec<PrevoteRef<'a>>,
    pub precommits: Vec<PrecommitRef<'a>>,
    pub base_hash: &'a [u8; 32],
    pub base_number: u64,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrevoteRef<'a> {
    /// Hash of the block concerned by the pre-vote.
    pub target_hash: &'a [u8; 32],
    /// Height of the block concerned by the pre-vote.
    pub target_number: u64,

    /// Ed25519 signature made with [`PrevoteRef::authority_public_key`].
    pub signature: &'a [u8; 64],

    /// Authority that signed the pre-vote. Must be part of the authority set for the
    /// justification to be valid.
    pub authority_public_key: &'a [u8; 32],
}

/// Attempt to decode the given SCALE-encoded Grandpa notification.
pub fn decode_grandpa_notification(
    scale_encoded: &'_ [u8],
    block_number_bytes: usize,
) -> Result<GrandpaNotificationRef<'_>, DecodeGrandpaNotificationError> {
    match nom::Parser::parse(
        &mut nom::combinator::all_consuming::<_, nom::error::Error<&[u8]>, _>(
            nom::combinator::complete(grandpa_notification(block_number_bytes)),
        ),
        scale_encoded,
    )
    .finish()
    {
        Ok((_, notif)) => Ok(notif),
        Err(err) => Err(DecodeGrandpaNotificationError(err.code)),
    }
}

/// Error potentially returned by [`decode_grandpa_notification`].
#[derive(Debug, derive_more::Display, derive_more::Error)]
#[display("Failed to decode a Grandpa notification")]
// TODO: nom doesn't implement the Error trait at the moment; remove error(not(source)) eventually
pub struct DecodeGrandpaNotificationError(#[error(not(source))] nom::error::ErrorKind);

// Nom combinators below.

fn grandpa_notification<
    'a,
    E: nom::error::ContextError<&'a [u8]> + nom::error::ParseError<&'a [u8]>,
>(
    block_number_bytes: usize,
) -> impl nom::Parser<&'a [u8], Output = GrandpaNotificationRef<'a>, Error = E> {
    nom::error::context(
        "grandpa_notification",
        nom::branch::alt((
            nom::combinator::map(
                nom::sequence::preceded(
                    nom::bytes::streaming::tag(&[0][..]),
                    vote_message(block_number_bytes),
                ),
                GrandpaNotificationRef::Vote,
            ),
            nom::combinator::map(
                nom::sequence::preceded(nom::bytes::streaming::tag(&[1][..]), move |s| {
                    decode::decode_partial_grandpa_commit(s, block_number_bytes)
                        .map(|(a, b)| (b, a))
                        .map_err(|_| {
                            nom::Err::Failure(nom::error::make_error(
                                s,
                                nom::error::ErrorKind::Verify,
                            ))
                        })
                }),
                GrandpaNotificationRef::Commit,
            ),
            nom::combinator::map(
                nom::sequence::preceded(
                    nom::bytes::streaming::tag(&[2][..]),
                    neighbor_packet(block_number_bytes),
                ),
                GrandpaNotificationRef::Neighbor,
            ),
            nom::combinator::map(
                nom::sequence::preceded(nom::bytes::streaming::tag(&[3][..]), catch_up_request),
                GrandpaNotificationRef::CatchUpRequest,
            ),
            nom::combinator::map(
                nom::sequence::preceded(
                    nom::bytes::streaming::tag(&[4][..]),
                    catch_up(block_number_bytes),
                ),
                GrandpaNotificationRef::CatchUp,
            ),
        )),
    )
}

fn vote_message<'a, E: nom::error::ContextError<&'a [u8]> + nom::error::ParseError<&'a [u8]>>(
    block_number_bytes: usize,
) -> impl nom::Parser<&'a [u8], Output = VoteMessageRef<'a>, Error = E> {
    nom::error::context(
        "vote_message",
        nom::combinator::map(
            (
                nom::number::streaming::le_u64,
                nom::number::streaming::le_u64,
                message(block_number_bytes),
                nom::bytes::streaming::take(64u32),
                nom::bytes::streaming::take(32u32),
            ),
            |(round_number, set_id, message, signature, authority_public_key)| VoteMessageRef {
                round_number,
                set_id,
                message,
                signature: <&[u8; 64]>::try_from(signature).unwrap(),
                authority_public_key: <&[u8; 32]>::try_from(authority_public_key).unwrap(),
            },
        ),
    )
}

fn message<'a, E: nom::error::ContextError<&'a [u8]> + nom::error::ParseError<&'a [u8]>>(
    block_number_bytes: usize,
) -> impl nom::Parser<&'a [u8], Output = MessageRef<'a>, Error = E> {
    nom::error::context(
        "message",
        nom::branch::alt((
            nom::combinator::map(
                nom::sequence::preceded(
                    nom::bytes::streaming::tag(&[0][..]),
                    unsigned_prevote(block_number_bytes),
                ),
                MessageRef::Prevote,
            ),
            nom::combinator::map(
                nom::sequence::preceded(
                    nom::bytes::streaming::tag(&[1][..]),
                    unsigned_precommit(block_number_bytes),
                ),
                MessageRef::Precommit,
            ),
            nom::combinator::map(
                nom::sequence::preceded(
                    nom::bytes::streaming::tag(&[2][..]),
                    primary_propose(block_number_bytes),
                ),
                MessageRef::PrimaryPropose,
            ),
        )),
    )
}

fn unsigned_prevote<
    'a,
    E: nom::error::ContextError<&'a [u8]> + nom::error::ParseError<&'a [u8]>,
>(
    block_number_bytes: usize,
) -> impl nom::Parser<&'a [u8], Output = UnsignedPrevoteRef<'a>, Error = E> {
    nom::error::context(
        "unsigned_prevote",
        nom::combinator::map(
            (
                nom::bytes::streaming::take(32u32),
                crate::util::nom_varsize_number_decode_u64(block_number_bytes),
            ),
            |(target_hash, target_number)| UnsignedPrevoteRef {
                target_hash: <&[u8; 32]>::try_from(target_hash).unwrap(),
                target_number,
            },
        ),
    )
}

fn unsigned_precommit<
    'a,
    E: nom::error::ContextError<&'a [u8]> + nom::error::ParseError<&'a [u8]>,
>(
    block_number_bytes: usize,
) -> impl nom::Parser<&'a [u8], Output = UnsignedPrecommitRef<'a>, Error = E> {
    nom::error::context(
        "unsigned_precommit",
        nom::combinator::map(
            (
                nom::bytes::streaming::take(32u32),
                crate::util::nom_varsize_number_decode_u64(block_number_bytes),
            ),
            |(target_hash, target_number)| UnsignedPrecommitRef {
                target_hash: <&[u8; 32]>::try_from(target_hash).unwrap(),
                target_number,
            },
        ),
    )
}

fn primary_propose<'a, E: nom::error::ContextError<&'a [u8]> + nom::error::ParseError<&'a [u8]>>(
    block_number_bytes: usize,
) -> impl nom::Parser<&'a [u8], Output = PrimaryProposeRef<'a>, Error = E> {
    nom::error::context(
        "primary_propose",
        nom::combinator::map(
            (
                nom::bytes::streaming::take(32u32),
                crate::util::nom_varsize_number_decode_u64(block_number_bytes),
            ),
            |(target_hash, target_number)| PrimaryProposeRef {
                target_hash: <&[u8; 32]>::try_from(target_hash).unwrap(),
                target_number,
            },
        ),
    )
}

fn neighbor_packet<'a, E: nom::error::ContextError<&'a [u8]> + nom::error::ParseError<&'a [u8]>>(
    block_number_bytes: usize,
) -> impl nom::Parser<&'a [u8], Output = NeighborPacket, Error = E> {
    nom::error::context(
        "neighbor_packet",
        nom::combinator::map(
            nom::sequence::preceded(
                nom::bytes::streaming::tag(&[1][..]),
                (
                    nom::number::streaming::le_u64,
                    nom::number::streaming::le_u64,
                    crate::util::nom_varsize_number_decode_u64(block_number_bytes),
                ),
            ),
            |(round_number, set_id, commit_finalized_height)| NeighborPacket {
                round_number,
                set_id,
                commit_finalized_height,
            },
        ),
    )
}

fn catch_up_request<
    'a,
    E: nom::error::ContextError<&'a [u8]> + nom::error::ParseError<&'a [u8]>,
>(
    bytes: &'a [u8],
) -> nom::IResult<&'a [u8], CatchUpRequest, E> {
    nom::Parser::parse(
        &mut nom::error::context(
            "catch_up_request",
            nom::combinator::map(
                (
                    nom::number::streaming::le_u64,
                    nom::number::streaming::le_u64,
                ),
                |(round_number, set_id)| CatchUpRequest {
                    round_number,
                    set_id,
                },
            ),
        ),
        bytes,
    )
}

fn catch_up<'a, E: nom::error::ContextError<&'a [u8]> + nom::error::ParseError<&'a [u8]>>(
    block_number_bytes: usize,
) -> impl nom::Parser<&'a [u8], Output = CatchUpRef<'a>, Error = E> {
    nom::error::context(
        "catch_up",
        nom::combinator::map(
            (
                nom::number::streaming::le_u64,
                nom::number::streaming::le_u64,
                nom::combinator::flat_map(crate::util::nom_scale_compact_usize, move |num_elems| {
                    nom::multi::many_m_n(num_elems, num_elems, prevote(block_number_bytes))
                }),
                nom::combinator::flat_map(crate::util::nom_scale_compact_usize, move |num_elems| {
                    nom::multi::many_m_n(num_elems, num_elems, move |s| {
                        crate::finality::decode::PrecommitRef::decode_partial(s, block_number_bytes)
                            .map(|(a, b)| (b, a))
                            .map_err(|_| {
                                nom::Err::Failure(nom::error::make_error(
                                    s,
                                    nom::error::ErrorKind::Verify,
                                ))
                            })
                    })
                }),
                nom::bytes::streaming::take(32u32),
                crate::util::nom_varsize_number_decode_u64(block_number_bytes),
            ),
            |(set_id, round_number, prevotes, precommits, base_hash, base_number)| CatchUpRef {
                set_id,
                round_number,
                prevotes,
                precommits,
                base_hash: <&[u8; 32]>::try_from(base_hash).unwrap(),
                base_number,
            },
        ),
    )
}

fn prevote<'a, E: nom::error::ContextError<&'a [u8]> + nom::error::ParseError<&'a [u8]>>(
    block_number_bytes: usize,
) -> impl nom::Parser<&'a [u8], Output = PrevoteRef<'a>, Error = E> {
    nom::error::context(
        "prevote",
        nom::combinator::map(
            (
                nom::bytes::streaming::take(32u32),
                crate::util::nom_varsize_number_decode_u64(block_number_bytes),
                nom::bytes::streaming::take(64u32),
                nom::bytes::streaming::take(32u32),
            ),
            |(target_hash, target_number, signature, authority_public_key)| PrevoteRef {
                target_hash: <&[u8; 32]>::try_from(target_hash).unwrap(),
                target_number,
                signature: <&[u8; 64]>::try_from(signature).unwrap(),
                authority_public_key: <&[u8; 32]>::try_from(authority_public_key).unwrap(),
            },
        ),
    )
}

#[cfg(test)]
mod tests {
    #[test]
    fn basic_decode_neighbor() {
        let actual = super::decode_grandpa_notification(
            &[
                2, 1, 87, 14, 0, 0, 0, 0, 0, 0, 162, 13, 0, 0, 0, 0, 0, 0, 49, 231, 77, 0,
            ],
            4,
        )
        .unwrap();

        let expected = super::GrandpaNotificationRef::Neighbor(super::NeighborPacket {
            round_number: 3671,
            set_id: 3490,
            commit_finalized_height: 5_105_457,
        });

        assert_eq!(actual, expected);
    }
}