ndn-protocol 0.4.1

Named Data Networking - main protocol parsing and encoding
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
//! [`Interest`], the packet used to request [`Data`](crate::Data) by name.
//!
//! An `Interest` is a [`Name`] plus a handful of optional selectors and,
//! for signed Interests, application parameters and a signature. It's
//! generic over its application parameters type, so a payload can be
//! carried either as raw [`Bytes`] or as a concrete type that implements
//! [`ndn_tlv::TlvEncode`]/[`ndn_tlv::TlvDecode`].

use bytes::{Buf, BufMut, Bytes, BytesMut};
use derive_more::{AsMut, AsRef, Constructor, From, Into};
use ndn_tlv::{find_tlv, NonNegativeInteger, Tlv, TlvDecode, TlvEncode, VarNum};
use rand::{Rng, SeedableRng};
use sha2::{Digest, Sha256};

use crate::{
    error::{SignError, VerifyError},
    name::ParametersSha256DigestComponent,
    signature::{
        InterestSignatureInfo, InterestSignatureValue, SignMethod, SignatureNonce, SignatureSeqNum,
        SignatureVerifier,
    },
    Name, NameComponent, SignatureType,
};

/// A marker element allowing the Interest to match Data whose name has this
/// Interest's name as a prefix, rather than requiring an exact match.
#[derive(Debug, Tlv, PartialEq, Eq, Clone, Copy, Constructor, Hash, Default)]
#[tlv(33)]
pub struct CanBePrefix;

/// A marker element requiring the forwarder to return only Data that isn't
/// stale, i.e. still within its [`FreshnessPeriod`](crate::FreshnessPeriod).
#[derive(Debug, Tlv, PartialEq, Eq, Clone, Copy, Constructor, Hash, Default)]
#[tlv(18)]
pub struct MustBeFresh;

/// Suggests a name for the forwarder to use when deciding where to forward
/// this Interest, as a hint rather than a hard requirement.
#[derive(Debug, Tlv, PartialEq, Eq, Clone, PartialOrd, Ord, Hash, Constructor)]
#[tlv(30)]
pub struct ForwardingHint {
    name: Name,
}

/// A random value that lets a forwarder detect duplicate/looping Interests.
#[derive(Debug, Tlv, PartialEq, Eq, Clone, Copy, Constructor, From, Into, AsRef, AsMut, Hash)]
#[tlv(10)]
pub struct Nonce {
    nonce: [u8; 4],
}

/// How long, in milliseconds, the Interest stays pending at a forwarder
/// while it waits for matching Data.
#[derive(
    Debug,
    Tlv,
    PartialEq,
    Eq,
    Clone,
    Copy,
    Constructor,
    From,
    Into,
    AsRef,
    AsMut,
    Hash,
    PartialOrd,
    Ord,
)]
#[tlv(12)]
pub struct InterestLifetime {
    lifetime: NonNegativeInteger,
}

/// The maximum number of forwarder hops this Interest may still travel,
/// decremented by each forwarder it passes through.
#[derive(
    Debug,
    Tlv,
    PartialEq,
    Eq,
    Clone,
    Copy,
    Constructor,
    From,
    Into,
    AsRef,
    AsMut,
    Hash,
    PartialOrd,
    Ord,
)]
#[tlv(34)]
pub struct HopLimit {
    limit: u8,
}

/// The Interest's application-defined payload.
///
/// Present only on signed Interests (or Interests that will be signed):
/// its encoding is what [`Interest::make_parameters_digest`] hashes into
/// the name's `ParametersSha256DigestComponent`.
#[derive(Debug, Tlv, PartialEq, Eq, Hash, From, AsRef, AsMut, Constructor, Clone)]
#[tlv(36)]
pub struct ApplicationParameters<T> {
    data: T,
}

/// A request for [`Data`](crate::Data) matching a [`Name`], optionally
/// carrying application parameters and a signature.
///
/// `T` is the type application parameters decode/encode as; use `()` for
/// Interests that don't carry any, [`Bytes`] to work with the raw payload,
/// or a type implementing [`ndn_tlv::TlvEncode`]/[`ndn_tlv::TlvDecode`] to
/// work with it directly.
#[derive(Debug, Tlv, PartialEq, Eq, Hash, Clone)]
#[tlv(5)]
pub struct Interest<T> {
    pub(crate) name: Name,
    can_be_prefix: Option<CanBePrefix>,
    must_be_fresh: Option<MustBeFresh>,
    forwarding_hint: Option<ForwardingHint>,
    nonce: Option<Nonce>,
    interest_lifetime: Option<InterestLifetime>,
    hop_limit: Option<HopLimit>,
    application_parameters: Option<ApplicationParameters<T>>,
    signature_info: Option<InterestSignatureInfo>,
    signature_value: Option<InterestSignatureValue>,
}

/// Options controlling what [`Interest::sign`]/[`Interest::sign_checked`] include
/// in the signature.
#[derive(Debug, PartialEq, Eq, Clone, Copy, Constructor, Hash)]
pub struct SignSettings {
    /// Whether to include a signing timestamp.
    pub include_time: bool,
    /// Whether to include a signing sequence number.
    pub include_seq_num: bool,
    /// The length, in bytes, of the random signing nonce. `0` omits the nonce.
    pub nonce_length: usize,
}

impl Default for SignSettings {
    fn default() -> Self {
        Self {
            include_time: true,
            include_seq_num: false,
            nonce_length: 8,
        }
    }
}

impl Interest<Bytes> {
    /// Decodes the raw application parameters into a concrete type `T`, converting an
    /// `Interest<Bytes>` into the curresponding `Interest<T>`.
    ///
    /// If decoding fails, or there were no application parameters to begin
    /// with, the returned Interest simply has none.
    pub fn decode_application_parameters<T>(self) -> Interest<T>
    where
        T: TlvDecode,
    {
        Interest {
            application_parameters: self
                .application_parameters
                .and_then(|mut x| T::decode(&mut x.data).ok())
                .map(ApplicationParameters::new),
            name: self.name,
            can_be_prefix: self.can_be_prefix,
            must_be_fresh: self.must_be_fresh,
            forwarding_hint: self.forwarding_hint,
            nonce: self.nonce,
            interest_lifetime: self.interest_lifetime,
            hop_limit: self.hop_limit,
            signature_info: self.signature_info,
            signature_value: self.signature_value,
        }
    }
}

impl<AppParamTy> Interest<AppParamTy> {
    /// Drops the application parameters, returning an `Interest<()>`.
    pub fn remove_application_parameters(self) -> Interest<()> {
        Interest {
            application_parameters: None,
            name: self.name,
            can_be_prefix: self.can_be_prefix,
            must_be_fresh: self.must_be_fresh,
            forwarding_hint: self.forwarding_hint,
            nonce: self.nonce,
            interest_lifetime: self.interest_lifetime,
            hop_limit: self.hop_limit,
            signature_info: self.signature_info,
            signature_value: self.signature_value,
        }
    }
}

impl<AppParamTy> Interest<AppParamTy>
where
    AppParamTy: TlvEncode,
{
    /// Creates the `ParametersSha256DigestComponent` part of the name.
    ///
    /// The component will be automatically added to the name when signing the interest, so this is
    /// only useful for unsigned interests.
    pub fn make_parameters_digest(data: AppParamTy) -> ParametersSha256DigestComponent {
        let mut hasher = Sha256::new();
        hasher.update(VarNum::from(ApplicationParameters::<AppParamTy>::TYP).encode());
        hasher.update(VarNum::from(data.size()).encode());
        hasher.update(&data.encode());
        ParametersSha256DigestComponent {
            name: hasher.finalize().into(),
        }
    }

    /// Adds a `ParametersSha256DigestComponent` to the end of the name
    ///
    /// The component will be automatically added to the name when signing the interest, so this is
    /// only useful for unsigned interests.
    ///
    /// Empty application parameters will be set if none are set currently.
    /// Any existing `ParametersSha256DigestComponent` will be removed.
    pub fn add_parameters_digest(&mut self) -> &mut Self
    where
        AppParamTy: Default,
        AppParamTy: Clone,
    {
        if self.application_parameters.is_none() {
            self.application_parameters = Some(ApplicationParameters {
                data: AppParamTy::default(),
            });
        }

        self.add_parameters_digest_unchecked()
    }

    /// Adds a `ParametersSha256DigestComponent` to the end of the name, assuming application
    /// parameters already exist
    ///
    /// The component will be automatically added to the name when signing the interest, so this is
    /// only useful for unsigned interests.
    ///
    /// Any existing `ParametersSha256DigestComponent` will be removed.
    pub fn add_parameters_digest_unchecked(&mut self) -> &mut Self
    where
        AppParamTy: Clone,
    {
        self.name
            .components
            .retain(|x| !matches!(x, NameComponent::ParametersSha256DigestComponent(_)));

        self.name
            .components
            .push(NameComponent::ParametersSha256DigestComponent(
                Self::make_parameters_digest(
                    self.application_parameters.as_ref().unwrap().data.clone(),
                ),
            ));
        self
    }

    fn signable_portion(&self) -> Bytes {
        let mut bytes = self.encode();
        let _ = VarNum::decode(&mut bytes);
        let _ = VarNum::decode(&mut bytes);
        let _ = find_tlv::<ApplicationParameters<AppParamTy>>(&mut bytes, false);

        let mut end = bytes.clone();
        let _ = find_tlv::<InterestSignatureValue>(&mut end, false);
        bytes.truncate(bytes.remaining() - end.remaining());

        let mut signature_buffer =
            BytesMut::with_capacity(self.name.inner_size() + bytes.remaining());
        for component in &self.name.components {
            if !matches!(component, NameComponent::ParametersSha256DigestComponent(_)) {
                signature_buffer.put(component.encode());
            }
        }
        signature_buffer.put(&mut bytes);
        signature_buffer.freeze()
    }

    fn parameters_digest(&self) -> [u8; 32] {
        let mut data = self.encode();
        let _ = VarNum::decode(&mut data);
        let _ = VarNum::decode(&mut data);
        let _ = find_tlv::<ApplicationParameters<AppParamTy>>(&mut data, false);
        let mut hasher = Sha256::new();
        hasher.update(&data);
        hasher.finalize().into()
    }

    /// Signs the Interest with `sign_method`, setting empty application
    /// parameters first if none are set yet.
    pub fn sign<T>(&mut self, sign_method: &mut T, settings: SignSettings)
    where
        T: SignMethod,
        AppParamTy: Default,
    {
        if self.application_parameters.is_none() {
            self.set_application_parameters(Some(AppParamTy::default()));
        }

        self.sign_checked(sign_method, settings)
            .expect("sign_checked failed from sign")
    }

    /// Signs the Interest with `sign_method`, adding a signature info,
    /// signature value, and `ParametersSha256DigestComponent` to the name.
    ///
    /// Fails if the Interest has no application parameters set --
    /// signed Interests are required to carry some, even if empty. see
    /// [`Interest::sign`] for a version that sets empty ones automatically.
    pub fn sign_checked<T>(
        &mut self,
        sign_method: &mut T,
        settings: SignSettings,
    ) -> Result<(), SignError>
    where
        T: SignMethod,
    {
        // Delete existing params-sha256
        self.name
            .components
            .retain(|x| !matches!(x, NameComponent::ParametersSha256DigestComponent(_)));
        if self.application_parameters.is_none() {
            return Err(SignError::MissingApplicationParameters);
        }

        // Generate nonce
        let nonce = if settings.nonce_length > 0 {
            let mut rng = rand::rngs::StdRng::from_entropy();
            let mut data = BytesMut::with_capacity(settings.nonce_length);
            for _ in 0..settings.nonce_length {
                data.put_u8(rng.gen());
            }
            Some(SignatureNonce::new(data.freeze()))
        } else {
            None
        };

        // Generate sequence number
        let seq_num = sign_method.next_seq_num();

        self.signature_info = Some(InterestSignatureInfo {
            signature_type: SignatureType::new(sign_method.signature_type().into()),
            key_locator: sign_method.certificate().map(|x| x.name_locator()),
            nonce,
            time: settings.include_time.then(|| sign_method.time()),
            seq_num: settings
                .include_seq_num
                .then(|| SignatureSeqNum::new(seq_num.into())),
        });

        // Create signature
        self.signature_value = Some(InterestSignatureValue::new(
            sign_method.sign(&self.signable_portion()),
        ));

        // Add new params-sha256
        self.name
            .components
            .push(NameComponent::ParametersSha256DigestComponent(
                ParametersSha256DigestComponent {
                    name: self.parameters_digest(),
                },
            ));
        Ok(())
    }

    fn verify_param_digest(&self) -> Result<(), VerifyError> {
        if self.is_signed() {
            if self.application_parameters.is_none() {
                return Err(VerifyError::MissingApplicationParameters);
            }

            let Some(NameComponent::ParametersSha256DigestComponent(param_digest)) =
                self.name.components.last()
            else {
                return Err(VerifyError::InvalidParameterDigest);
            };

            if param_digest.name != self.parameters_digest() {
                return Err(VerifyError::InvalidParameterDigest);
            }
            Ok(())
        } else {
            if self.application_parameters.is_some() {
                // Not signed, application parameters present - check parameter digest
                for component in &self.name.components {
                    if let NameComponent::ParametersSha256DigestComponent(component) = component {
                        if component.name == self.parameters_digest() {
                            return Ok(());
                        } else {
                            return Err(VerifyError::InvalidParameterDigest);
                        }
                    }
                }
                // No digest present
                Err(VerifyError::InvalidParameterDigest)
            } else {
                // Not signed, no application parameters - nothing to check
                Ok(())
            }
        }
    }

    /// Verify the interest with a given signature verifier
    ///
    /// Returns `Ok(())` if the signature and the `ParametersSha256DigestComponent` of the name are
    /// valid
    pub fn verify<T>(&self, verifier: &T) -> Result<(), VerifyError>
    where
        T: SignatureVerifier,
        T: ?Sized,
    {
        self.verify_param_digest()?;

        if self.signature_info.is_none() {
            // Not signed
            return Ok(());
        }

        let Some(ref sig_value) = self.signature_value else {
            // Signature missing
            return Err(VerifyError::InvalidSignature);
        };

        verifier
            .verify(&self.signable_portion(), sig_value.as_ref())
            .then_some(())
            .ok_or(VerifyError::InvalidSignature)
    }

    /// Encodes the application parameters to their raw TLV bytes, the
    /// inverse of [`Interest::decode_application_parameters`].
    pub fn encode_application_parameters(self) -> Interest<Bytes> {
        Interest {
            name: self.name,
            can_be_prefix: self.can_be_prefix,
            must_be_fresh: self.must_be_fresh,
            forwarding_hint: self.forwarding_hint,
            nonce: self.nonce,
            interest_lifetime: self.interest_lifetime,
            hop_limit: self.hop_limit,
            application_parameters: self.application_parameters.map(|params| {
                ApplicationParameters {
                    data: params.data.encode(),
                }
            }),
            signature_info: self.signature_info,
            signature_value: self.signature_value,
        }
    }
}

impl Interest<()> {
    /// Same as [`Interest::new`], for callers that need to spell out that
    /// `T` is `()` for type inference to work.
    pub fn new_u(name: Name) -> Self {
        Self::new(name)
    }
}

impl<AppParamTy> Interest<AppParamTy> {
    /// Creates a new, unsigned Interest for `name` with no selectors set.
    pub fn new(name: Name) -> Self {
        Self {
            name,
            can_be_prefix: None,
            must_be_fresh: None,
            forwarding_hint: None,
            nonce: None,
            interest_lifetime: None,
            hop_limit: None,
            application_parameters: None,
            signature_info: None,
            signature_value: None,
        }
    }

    /// Sets the Interest's name.
    pub fn set_name(&mut self, name: Name) -> &mut Self {
        self.name = name;
        self
    }

    /// The Interest's name.
    pub fn name(&self) -> &Name {
        &self.name
    }

    /// Sets whether the Interest can be satisfied by Data whose name has
    /// this Interest's name as a prefix (see [`CanBePrefix`]).
    pub fn set_can_be_prefix(&mut self, can_be_prefix: bool) -> &mut Self {
        self.can_be_prefix = can_be_prefix.then_some(CanBePrefix);
        self
    }

    /// Whether [`CanBePrefix`] is set.
    pub fn can_be_prefix(&self) -> bool {
        self.can_be_prefix.is_some()
    }

    /// Sets whether the Interest requires fresh Data (see [`MustBeFresh`]).
    pub fn set_must_be_fresh(&mut self, must_be_fresh: bool) -> &mut Self {
        self.must_be_fresh = must_be_fresh.then_some(MustBeFresh);
        self
    }

    /// Whether [`MustBeFresh`] is set.
    pub fn must_be_fresh(&self) -> bool {
        self.must_be_fresh.is_some()
    }

    /// Sets the forwarding hint, or clears it if `None` (see [`ForwardingHint`]).
    pub fn set_forwarding_hint(&mut self, forwarding_hint: Option<Name>) -> &mut Self {
        self.forwarding_hint = forwarding_hint.map(|name| ForwardingHint { name });
        self
    }

    /// The forwarding hint's name, if set.
    pub fn forwarding_hint(&self) -> Option<&Name> {
        self.forwarding_hint.as_ref().map(|x| &x.name)
    }

    /// Sets the nonce, or clears it if `None` (see [`Nonce`]).
    pub fn set_nonce(&mut self, nonce: Option<[u8; 4]>) -> &mut Self {
        self.nonce = nonce.map(|nonce| Nonce { nonce });
        self
    }

    /// The nonce, if set.
    pub fn nonce(&self) -> Option<&[u8; 4]> {
        self.nonce.as_ref().map(|x| &x.nonce)
    }

    /// Sets the interest lifetime in milliseconds, or clears it if `None`
    /// (see [`InterestLifetime`]).
    pub fn set_interest_lifetime(
        &mut self,
        interest_lifetime: Option<NonNegativeInteger>,
    ) -> &mut Self {
        self.interest_lifetime = interest_lifetime.map(|lifetime| InterestLifetime { lifetime });
        self
    }

    /// The interest lifetime in milliseconds, if set.
    pub fn interest_lifetime(&self) -> Option<NonNegativeInteger> {
        self.interest_lifetime.as_ref().map(|x| x.lifetime)
    }

    /// Sets the hop limit, or clears it if `None` (see [`HopLimit`]).
    pub fn set_hop_limit(&mut self, hop_limit: Option<u8>) -> &mut Self {
        self.hop_limit = hop_limit.map(|limit| HopLimit { limit });
        self
    }

    /// The hop limit, if set.
    pub fn hop_limit(&self) -> Option<u8> {
        self.hop_limit.as_ref().map(|x| x.limit)
    }

    /// Sets the application parameters, or clears them if `None`.
    pub fn set_application_parameters(&mut self, params: Option<AppParamTy>) -> &mut Self {
        self.application_parameters = params.map(|data| ApplicationParameters { data });
        self
    }

    /// The application parameters, if set.
    pub fn application_parameters(&self) -> Option<&AppParamTy> {
        self.application_parameters.as_ref().map(|x| &x.data)
    }

    /// The signature info added by [`Interest::sign`]/[`Interest::sign_checked`], if the Interest is signed.
    pub fn signature_info(&self) -> Option<&InterestSignatureInfo> {
        self.signature_info.as_ref()
    }

    /// Whether the Interest carries a signature.
    pub fn is_signed(&self) -> bool {
        self.signature_info.is_some()
    }
}

#[cfg(test)]
mod tests {
    use base64::Engine;

    use crate::{signature::DigestSha256, RsaCertificate, SafeBag, SignatureSha256WithRsa};

    use super::*;

    #[test]
    fn simple_usage() {
        let mut interest = Interest::<()>::new(Name::from_str("ndn:/hello/world").unwrap());
        interest
            .set_can_be_prefix(true)
            .set_hop_limit(Some(20))
            .set_interest_lifetime(Some(10_000u16.into()));

        assert_eq!(
            interest,
            Interest {
                name: Name::from_str("ndn:/hello/world").unwrap(),
                can_be_prefix: Some(CanBePrefix),
                must_be_fresh: None,
                forwarding_hint: None,
                nonce: None,
                interest_lifetime: Some(InterestLifetime {
                    lifetime: 10_000u16.into()
                }),
                hop_limit: Some(HopLimit { limit: 20 }),
                application_parameters: None,
                signature_info: None,
                signature_value: None,
            }
        );
    }

    #[test]
    fn sha256_interest() {
        let mut interest = Interest::<()>::new(Name::from_str("ndn:/hello/world").unwrap());
        let mut signer = DigestSha256::new();
        interest.sign(
            &mut signer,
            SignSettings {
                include_time: false,
                nonce_length: 0,
                include_seq_num: true,
            },
        );
        assert!(interest.verify(&mut signer).is_ok());

        let name_components = [
            8, 5, b'h', b'e', b'l', b'l', b'o', 8, 5, b'w', b'o', b'r', b'l', b'd', //
        ];

        let app_params_plus = [
            36, 0, // ApplicationParameters
            44, 6, // SignatureInfo
            27, 1, 0, // Signature Type
            42, 1, 0, // seq num
        ];

        let mut hasher = Sha256::new();
        hasher.update(name_components);
        hasher.update(app_params_plus);
        let signature = hasher.finalize();

        hasher = Sha256::new();
        hasher.update(app_params_plus);
        hasher.update([46, 32]);
        hasher.update(signature);
        let param_digest = hasher.finalize();

        let mut full_record = Vec::new();
        full_record.extend([5, 94]);
        full_record.extend([7, 48]);
        full_record.extend(name_components);
        full_record.extend([2, 32]);
        full_record.extend(param_digest);
        full_record.extend(app_params_plus);
        full_record.extend([46, 32]);
        full_record.extend(signature);

        assert_eq!(<Vec<u8>>::from(interest.encode()), full_record);
    }

    #[test]
    fn rsa_interest() {
        const SAFEBAG: &[u8] = b"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\
g==";

        let safebag_data = base64::engine::general_purpose::STANDARD
            .decode(SAFEBAG)
            .unwrap();
        let safebag = SafeBag::decode(&mut Bytes::from(safebag_data)).unwrap();

        let cert = RsaCertificate::from_safebag(safebag, "test").unwrap();
        let mut signer = SignatureSha256WithRsa::new(cert.clone());

        let mut interest = Interest::<()>::new(Name::from_str("ndn:/test/test/asd").unwrap());
        interest.sign(&mut signer, SignSettings::default());

        assert!(interest.verify(&signer).is_ok());
    }
}