p2panda-net 0.6.0

Data-type-agnostic p2p networking, discovery, gossip and local-first sync
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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Types representing node information and transport addresses.
//!
//! ## Example
//!
//! Create new bootstrap node with attached transport information for iroh:
//!
//! ```rust
//! use p2panda_net::addrs::NodeInfo;
//!
//! let node_id = "c0f3ce745cee96e1e9c01a20746cd503bb2199c2459d8ff8697f5edb30569101"
//!     .parse()
//!     .expect("valid hex-encoded Ed25519 public key");
//! let relay_url = "https://my.relay.org".parse().expect("valid relay url");
//!
//! let endpoint_addr = iroh_base::EndpointAddr::new(node_id)
//!    .with_relay_url(relay_url);
//! let bootstrap_node = NodeInfo::from(endpoint_addr).bootstrap();
//! ```
use std::fmt::Display;
use std::hash::Hash as StdHash;
use std::mem;
#[cfg(any(test, feature = "test_utils"))]
use std::net::SocketAddr;

use p2panda_core::cbor::encode_cbor;
use p2panda_core::timestamp::{HybridTimestamp, Timestamp};
use p2panda_core::{Signature, SigningKey};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::NodeId;
use crate::utils::to_verifying_key;

/// Record of a node we store locally in the address book.
///
/// Node information associates configuration, metrics and transport information with a node id.
/// Since the associated information is mostly for our own local use, we can consider `NodeInfo` to
/// be private data.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct NodeInfo {
    /// Unique identifier (Ed25519 public key) of this node.
    pub node_id: NodeId,

    /// Use node as a "bootstrap".
    ///
    /// Bootstraps are prioritized during discovery as they are considered "more reliable" and
    /// faster to reach than other nodes. Usually they are behind a static IP address and are
    /// always online.
    ///
    /// This is a local configuration and is not exchanged during discovery. Every node can decide
    /// themselves which other node they consider a bootstrap or not.
    pub bootstrap: bool,

    /// Records of successful or failed connection attempts with this node.
    ///
    /// This is useful to understand if we can consider this node as "stale" or not.
    pub metrics: NodeMetrics,

    /// Transport protocols we can use to connect to this node.
    ///
    /// If `None` then no information was received and we can't connect yet.
    pub transports: Option<TransportInfo>,
}

impl NodeInfo {
    /// Returns new `NodeInfo` with default values.
    pub fn new(node_id: NodeId) -> Self {
        Self {
            node_id,
            bootstrap: false,
            transports: None,
            metrics: NodeMetrics::default(),
        }
    }

    /// Use this node as a "bootstrap".
    pub fn bootstrap(mut self) -> Self {
        self.bootstrap = true;
        self
    }

    /// Updates transport info for a node if it is newer ("last-write wins" principle).
    ///
    /// Returns true if given transport info is newer than the current one.
    pub fn update_transports(&mut self, other: TransportInfo) -> Result<bool, NodeInfoError> {
        other.verify(&self.node_id)?;

        // Choose "latest" info by checking timestamp if given.
        let mut is_newer = false;
        match self.transports.as_ref() {
            None => {
                is_newer = true;
                self.transports = Some(other)
            }
            Some(current) => {
                if other.timestamp() > current.timestamp() {
                    self.transports = Some(other);
                    is_newer = true;
                }
            }
        }

        Ok(is_newer)
    }

    /// Checks authenticity of associated transport information.
    pub fn verify(&self) -> Result<(), NodeInfoError> {
        match self.transports {
            Some(ref transports) => transports.verify(&self.node_id),
            None => Ok(()),
        }
    }
}

impl TryFrom<NodeInfo> for iroh_base::EndpointAddr {
    type Error = NodeInfoError;

    fn try_from(node_info: NodeInfo) -> Result<Self, Self::Error> {
        let Some(transports) = node_info.transports else {
            return Err(NodeInfoError::MissingTransportAddresses);
        };

        transports
            .addresses()
            .iter()
            .find_map(|address| match address {
                TransportAddress::Iroh(endpoint_addr) => Some(endpoint_addr),
                #[allow(unreachable_patterns)]
                _ => None,
            })
            .cloned()
            .ok_or(NodeInfoError::MissingTransportAddresses)
    }
}

impl From<iroh_base::EndpointAddr> for NodeInfo {
    fn from(addr: iroh_base::EndpointAddr) -> Self {
        let node_id = to_verifying_key(addr.id);
        let transports = TransportInfo::from(TrustedTransportInfo::from(addr));

        Self {
            node_id,
            bootstrap: false,
            transports: Some(transports),
            metrics: NodeMetrics::default(),
        }
    }
}

impl p2panda_store::address_book::NodeInfo<NodeId> for NodeInfo {
    type Transports = AuthenticatedTransportInfo;

    fn id(&self) -> NodeId {
        self.node_id
    }

    fn is_bootstrap(&self) -> bool {
        self.bootstrap
    }

    fn is_stale(&self) -> bool {
        if self.bootstrap {
            // Bootstrap nodes can never be marked as stale.
            false
        } else {
            self.metrics.is_stale()
        }
    }

    fn transports(&self) -> Option<Self::Transports> {
        match &self.transports {
            Some(TransportInfo::Authenticated(info)) => Some(info.clone()),
            Some(TransportInfo::Trusted(_)) => {
                // "Trusted" information is _not_ authenticated and can not be used for discovery
                // services as the origin of the data can't be verified by other parties.
                None
            }
            None => None,
        }
    }
}

pub trait NodeTransportInfo {
    /// Returns logical timestamp from when this information was created.
    fn timestamp(&self) -> HybridTimestamp;

    /// Returns all associated transport addresses.
    fn addresses(&self) -> Vec<TransportAddress>;

    /// Returns number of associated transports for this node.
    fn len(&self) -> usize;

    /// Returns `false` if no transports are given.
    fn is_empty(&self) -> bool;

    /// Check authenticity integrity of this information when possible.
    fn verify(&self, node_id: &NodeId) -> Result<(), NodeInfoError>;
}

/// Transport protocols information we can use to connect to a node.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum TransportInfo {
    /// Unauthenticated transport info we "trust" to be correct since it came to us via an verified
    /// side-channel (scanning QR code, sharing in a trusted chat group etc.).
    ///
    /// This info is never shared across the network services and is only used _locally_ by our own
    /// node. See `AuthenticatedTransportInfo` for an alternative which can be automatically
    /// distributed.
    Trusted(TrustedTransportInfo),

    /// Signed transport info which can be automatically shared across the network by discovery
    /// services and "untrusted" intermediaries since the original author is verifiable.
    Authenticated(AuthenticatedTransportInfo),
}

impl TransportInfo {
    pub fn new_trusted() -> TrustedTransportInfo {
        TrustedTransportInfo::new()
    }

    pub fn new_unsigned() -> UnsignedTransportInfo {
        UnsignedTransportInfo::new()
    }
}

impl NodeTransportInfo for TransportInfo {
    fn timestamp(&self) -> HybridTimestamp {
        match self {
            TransportInfo::Trusted(info) => info.timestamp(),
            TransportInfo::Authenticated(info) => info.timestamp(),
        }
    }

    fn addresses(&self) -> Vec<TransportAddress> {
        match self {
            TransportInfo::Trusted(info) => info.addresses(),
            TransportInfo::Authenticated(info) => info.addresses(),
        }
    }

    fn len(&self) -> usize {
        match self {
            TransportInfo::Trusted(info) => info.addresses.len(),
            TransportInfo::Authenticated(info) => info.addresses.len(),
        }
    }

    fn is_empty(&self) -> bool {
        match self {
            TransportInfo::Trusted(info) => info.addresses.is_empty(),
            TransportInfo::Authenticated(info) => info.addresses.is_empty(),
        }
    }

    fn verify(&self, node_id: &NodeId) -> Result<(), NodeInfoError> {
        match self {
            TransportInfo::Trusted(info) => info.verify(node_id),
            TransportInfo::Authenticated(info) => info.verify(node_id),
        }
    }
}

impl Display for TransportInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TransportInfo::Trusted(info) => write!(f, "{info}"),
            TransportInfo::Authenticated(info) => write!(f, "{info}"),
        }
    }
}

impl From<iroh_base::EndpointAddr> for TransportInfo {
    fn from(addr: iroh_base::EndpointAddr) -> Self {
        Self::from(TrustedTransportInfo::from(addr))
    }
}

impl From<AuthenticatedTransportInfo> for TransportInfo {
    fn from(value: AuthenticatedTransportInfo) -> Self {
        Self::Authenticated(value)
    }
}

impl From<TrustedTransportInfo> for TransportInfo {
    fn from(value: TrustedTransportInfo) -> Self {
        Self::Trusted(value)
    }
}

/// Signed transport info which can be automatically shared across the network by discovery
/// services and "untrusted" intermediaries since the original author is verifiable.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AuthenticatedTransportInfo {
    /// Logical timestamp from when this transport information was published.
    ///
    /// This can be used to find out which information is the "latest".
    pub timestamp: HybridTimestamp,

    /// Signature to prove authenticity of this transport information.
    ///
    /// Other nodes can validate the authenticity by checking this signature against the associated
    /// node id and info.
    ///
    /// This protects against attacks where nodes maliciously publish wrong information about other
    /// nodes, for example to make them unreachable due to invalid addresses.
    pub signature: Signature,

    /// Associated transport addresses to aid establishing a connection to this node.
    pub addresses: Vec<TransportAddress>,
}

impl AuthenticatedTransportInfo {
    pub fn new_unsigned() -> UnsignedTransportInfo {
        UnsignedTransportInfo::new()
    }

    fn to_unsigned(&self) -> UnsignedTransportInfo {
        UnsignedTransportInfo {
            timestamp: self.timestamp,
            addresses: self.addresses.clone(),
        }
    }
}

impl NodeTransportInfo for AuthenticatedTransportInfo {
    fn timestamp(&self) -> HybridTimestamp {
        self.timestamp
    }

    fn addresses(&self) -> Vec<TransportAddress> {
        self.addresses.clone()
    }

    fn len(&self) -> usize {
        self.addresses.len()
    }

    fn is_empty(&self) -> bool {
        self.addresses.is_empty()
    }

    fn verify(&self, node_id: &NodeId) -> Result<(), NodeInfoError> {
        let bytes = self.to_unsigned().to_bytes()?;

        if !node_id.verify(&bytes, &self.signature) {
            Err(NodeInfoError::InvalidSignature)
        } else {
            Ok(())
        }
    }
}

impl Display for AuthenticatedTransportInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let addresses = if self.addresses.is_empty() {
            "[]".to_string()
        } else {
            self.addresses.iter().map(|addr| addr.to_string()).collect()
        };

        write!(
            f,
            "[authenticated] timestamp={}, addresses={}",
            self.timestamp, addresses
        )
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct UnsignedTransportInfo {
    /// Logical timestamp from when this transport information was published.
    ///
    /// This can be used to find out which information is the "latest".
    pub timestamp: HybridTimestamp,

    /// Associated transport addresses to aid establishing a connection to this node.
    pub addresses: Vec<TransportAddress>,
}

impl Default for UnsignedTransportInfo {
    fn default() -> Self {
        Self::new()
    }
}

impl UnsignedTransportInfo {
    pub fn new() -> Self {
        Self {
            timestamp: HybridTimestamp::now(),
            addresses: vec![],
        }
    }

    pub fn from_addrs(addrs: impl IntoIterator<Item = TransportAddress>) -> Self {
        let mut info = Self::new();
        for addr in addrs {
            info.add_addr(addr);
        }
        info
    }

    /// Add transport address for this node.
    ///
    /// This method automatically de-duplicates transports per type and chooses the last-inserted
    /// one.
    pub fn add_addr(&mut self, addr: TransportAddress) {
        let existing_transport_index =
            self.addresses
                .iter()
                .enumerate()
                .find_map(|(index, existing_addr)| {
                    if mem::discriminant(&addr) == mem::discriminant(existing_addr) {
                        Some(index)
                    } else {
                        None
                    }
                });

        if let Some(index) = existing_transport_index {
            self.addresses.remove(index);
        }

        self.addresses.push(addr);
    }

    fn to_bytes(&self) -> Result<Vec<u8>, NodeInfoError> {
        let bytes = encode_cbor(&self)?;
        Ok(bytes)
    }

    /// Returns number of associated transports for this node.
    pub fn len(&self) -> usize {
        self.addresses.len()
    }

    pub fn is_empty(&self) -> bool {
        self.addresses.is_empty()
    }

    /// Increment logical timestamp based on previous clock state (if given).
    pub fn increment_timestamp(mut self, previous: Option<&AuthenticatedTransportInfo>) -> Self {
        match previous {
            Some(previous) => {
                // The underlying "hybrid" timestamp implementation guarantees to _always_ be
                // larger than the previous one.
                //
                // This is a locally created event and we want to make sure it is _after_ anything
                // which happened before.
                self.timestamp = previous.timestamp.increment();
                self
            }
            None => self,
        }
    }

    /// Authenticate transport info by signining it with our secret key.
    pub fn sign(
        self,
        signing_key: &SigningKey,
    ) -> Result<AuthenticatedTransportInfo, NodeInfoError> {
        Ok(AuthenticatedTransportInfo {
            timestamp: self.timestamp,
            signature: {
                let bytes = self.to_bytes()?;
                signing_key.sign(&bytes)
            },
            addresses: self.addresses,
        })
    }
}

impl From<iroh_base::EndpointAddr> for UnsignedTransportInfo {
    fn from(addr: iroh_base::EndpointAddr) -> Self {
        Self::from_addrs([addr.into()])
    }
}

/// Unauthenticated transport info we "trust" to be correct since it came to us via an verified
/// side-channel (scanning QR code, sharing in a trusted chat group etc.).
///
/// This info is never shared across the network services and is only used _locally_ by our own
/// node. See `AuthenticatedTransportInfo` for an alternative which can be automatically
/// distributed.
#[derive(Clone, Debug, PartialEq, Eq, StdHash, Serialize, Deserialize)]
pub struct TrustedTransportInfo {
    /// Logical timestamp from when this transport information was published.
    ///
    /// This can be used to find out which information is the "latest".
    pub timestamp: HybridTimestamp,

    /// Associated transport addresses to aid establishing a connection to this node.
    pub addresses: Vec<TransportAddress>,
}

impl Default for TrustedTransportInfo {
    fn default() -> Self {
        Self::new()
    }
}

impl TrustedTransportInfo {
    pub fn new() -> Self {
        Self {
            timestamp: HybridTimestamp::now(),
            addresses: vec![],
        }
    }

    pub fn from_addrs(addrs: impl IntoIterator<Item = TransportAddress>) -> Self {
        let mut info = Self::new();
        for addr in addrs {
            info.add_addr(addr);
        }
        info
    }

    /// Add transport address for this node.
    ///
    /// This method automatically de-duplicates transports per type and chooses the last-inserted
    /// one.
    pub fn add_addr(&mut self, addr: TransportAddress) {
        let existing_transport_index =
            self.addresses
                .iter()
                .enumerate()
                .find_map(|(index, existing_addr)| {
                    if mem::discriminant(&addr) == mem::discriminant(existing_addr) {
                        Some(index)
                    } else {
                        None
                    }
                });

        if let Some(index) = existing_transport_index {
            self.addresses.remove(index);
        }

        self.addresses.push(addr);
    }
}

impl NodeTransportInfo for TrustedTransportInfo {
    fn timestamp(&self) -> HybridTimestamp {
        self.timestamp
    }

    fn addresses(&self) -> Vec<TransportAddress> {
        self.addresses.clone()
    }

    fn len(&self) -> usize {
        self.addresses.len()
    }

    fn is_empty(&self) -> bool {
        self.addresses.is_empty()
    }

    fn verify(&self, node_id: &NodeId) -> Result<(), NodeInfoError> {
        for address in &self.addresses {
            address.verify(node_id)?;
        }

        Ok(())
    }
}

impl From<iroh_base::EndpointAddr> for TrustedTransportInfo {
    fn from(addr: iroh_base::EndpointAddr) -> Self {
        Self::from_addrs([addr.into()])
    }
}

impl Display for TrustedTransportInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let addresses = if self.addresses.is_empty() {
            "[]".to_string()
        } else {
            self.addresses.iter().map(|addr| addr.to_string()).collect()
        };

        write!(
            f,
            "[trusted] timestamp={}, addresses={}",
            self.timestamp, addresses
        )
    }
}

/// Associated transport addresses to aid establishing a connection to this node.
///
/// Currently this only supports using iroh (Internet Protocol) to connect.
#[derive(Clone, Debug, PartialEq, Eq, StdHash, Serialize, Deserialize)]
pub enum TransportAddress {
    /// Information to connect to another node via QUIC / UDP / IP using iroh for holepunching and
    /// relayed connections as a fallback.
    ///
    /// To connect to another node either their "home relay" URL needs to be known (to coordinate
    /// holepunching or relayed connection fallback) or at least one reachable "direct address"
    /// (IPv4 or IPv6). If none of these are given, establishing a connection is not possible.
    Iroh(iroh_base::EndpointAddr),
}

impl TransportAddress {
    #[cfg(any(test, feature = "test_utils"))]
    pub fn from_iroh(
        node_id: NodeId,
        relay_url: Option<iroh_base::RelayUrl>,
        direct_addresses: impl IntoIterator<Item = SocketAddr>,
    ) -> Self {
        let transport_addrs = direct_addresses
            .into_iter()
            .map(iroh_base::TransportAddr::Ip);

        let mut endpoint_addr =
            iroh_base::EndpointAddr::new(crate::utils::from_verifying_key(node_id))
                .with_addrs(transport_addrs);

        if let Some(url) = relay_url {
            endpoint_addr = endpoint_addr.with_relay_url(url);
        }

        Self::Iroh(endpoint_addr)
    }

    pub fn verify(&self, node_id: &NodeId) -> Result<(), NodeInfoError> {
        #[allow(irrefutable_let_patterns)]
        // Make sure the given address matches the node id.
        if let TransportAddress::Iroh(endpoint_addr) = self
            && &to_verifying_key(endpoint_addr.id) != node_id
        {
            return Err(NodeInfoError::NodeIdMismatch);
        }

        Ok(())
    }
}

impl From<iroh_base::EndpointAddr> for TransportAddress {
    fn from(addr: iroh_base::EndpointAddr) -> Self {
        Self::Iroh(addr)
    }
}

impl Display for TransportAddress {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TransportAddress::Iroh(endpoint_addr) => {
                write!(f, "[iroh] {:?}", endpoint_addr.addrs)
            }
        }
    }
}

/// Metrics which are locally recorded for a node.
///
/// The recorded information can be used to indicate if a node is "stale" or not.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct NodeMetrics {
    failed_connections: usize,
    successful_connections: usize,
    last_failed_at: Option<Timestamp>,
    last_succeeded_at: Option<Timestamp>,
}

impl NodeMetrics {
    /// Records failed connection attempt (both incoming or outgoing).
    pub fn report_failed_connection(&mut self) {
        self.failed_connections += 1;
        self.last_failed_at = Some(Timestamp::now());
    }

    /// Records successful connection attempt (both incoming or outgoing).
    pub fn report_successful_connection(&mut self) {
        self.successful_connections += 1;
        self.last_succeeded_at = Some(Timestamp::now());
    }

    /// Returns true if last known connection attempt failed.
    pub fn is_stale(&self) -> bool {
        match (self.last_succeeded_at, self.last_failed_at) {
            (None, None) => false,
            (None, Some(_)) => true,
            (Some(_), None) => false,
            (Some(succeeded_at), Some(failed_at)) => succeeded_at < failed_at,
        }
    }
}

#[derive(Debug, Error)]
pub enum NodeInfoError {
    #[error("missing or invalid signature")]
    InvalidSignature,

    #[error("no addresses given for this transport")]
    MissingTransportAddresses,

    #[error("node id of given transport info does not match")]
    NodeIdMismatch,

    #[error(transparent)]
    Encode(#[from] p2panda_core::cbor::EncodeError),
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use mock_instant::thread_local::MockClock;
    use p2panda_core::SigningKey;

    use crate::addrs::NodeTransportInfo;

    use super::{
        AuthenticatedTransportInfo, NodeInfo, NodeMetrics, TransportAddress, UnsignedTransportInfo,
    };

    #[test]
    fn deduplicate_transport_address() {
        let signing_key_1 = SigningKey::generate();
        let node_id_1 = signing_key_1.verifying_key();

        // De-duplicate addresses when transport is the same.
        let mut info = AuthenticatedTransportInfo::new_unsigned();
        info.add_addr(TransportAddress::from_iroh(node_id_1, None, []));
        info.add_addr(TransportAddress::from_iroh(
            node_id_1,
            Some("https://my.relay.net".parse().unwrap()),
            [],
        ));

        assert_eq!(info.len(), 1);
    }

    #[test]
    fn authenticate_address_infos() {
        let signing_key_1 = SigningKey::generate();
        let node_id_1 = signing_key_1.verifying_key();

        let mut unsigned = UnsignedTransportInfo::new();
        unsigned.add_addr(TransportAddress::from_iroh(
            node_id_1,
            Some("https://my.relay.net".parse().unwrap()),
            [],
        ));

        let info = unsigned.sign(&signing_key_1).unwrap();
        assert!(info.verify(&node_id_1).is_ok());

        // Fails when node id does not match.
        let signing_key_2 = SigningKey::generate();
        let node_id_2 = signing_key_2.verifying_key();
        assert!(info.verify(&node_id_2).is_err());

        // Fails when information got changed.
        let mut info = info;
        info.addresses.pop().unwrap();
        assert!(info.verify(&node_id_1).is_err());
    }

    #[test]
    fn node_id_mismatch() {
        let signing_key_1 = SigningKey::generate();
        let node_id_1 = signing_key_1.verifying_key();

        let signing_key_2 = SigningKey::generate();
        let node_id_2 = signing_key_2.verifying_key();

        // Create transport info for node 1.
        let mut unsigned = UnsignedTransportInfo::new();
        unsigned.add_addr(TransportAddress::from_iroh(
            node_id_1,
            Some("https://my.relay.net".parse().unwrap()),
            [],
        ));
        let transport_info = unsigned.sign(&signing_key_1).unwrap();

        // Create info for node 2 and try to add unrelated transport info.
        let mut node_info = NodeInfo {
            node_id: node_id_2,
            bootstrap: false,
            transports: None,
            metrics: NodeMetrics::default(),
        };
        assert!(node_info.verify().is_ok());
        assert!(node_info.update_transports(transport_info.into()).is_err());
    }

    #[test]
    fn latest_transport_info_wins() {
        let signing_key_1 = SigningKey::generate();
        let node_id_1 = signing_key_1.verifying_key();

        // Create "newer" transport info.
        let transport_info_1 = {
            let mut unsigned = UnsignedTransportInfo::new();
            unsigned.add_addr(TransportAddress::from_iroh(
                node_id_1,
                Some("https://my.relay.net".parse().unwrap()),
                [],
            ));
            unsigned.timestamp = 2.into(); // Force "newer" timestamp.
            unsigned.sign(&signing_key_1).unwrap()
        };

        // Create "older" transport info.
        let transport_info_2 = {
            let mut unsigned = UnsignedTransportInfo::new();
            unsigned.add_addr(TransportAddress::from_iroh(
                node_id_1,
                Some("https://my.relay.net".parse().unwrap()),
                [],
            ));
            unsigned.timestamp = 1.into(); // Force "older" timestamp.
            unsigned.sign(&signing_key_1).unwrap()
        };

        // Register both transport infos with node.
        let mut node_info = NodeInfo {
            node_id: node_id_1,
            bootstrap: true,
            transports: None,
            metrics: NodeMetrics::default(),
        };
        assert!(node_info.verify().is_ok());
        assert!(node_info.update_transports(transport_info_1.into()).is_ok());
        assert!(node_info.update_transports(transport_info_2.into()).is_ok());

        // The "newer" transport info is the only one registered.
        assert_eq!(node_info.transports.as_ref().unwrap().len(), 1);
        assert_eq!(node_info.transports.unwrap().timestamp(), 2.into());
    }

    #[test]
    fn stale_nodes() {
        let signing_key = SigningKey::generate();
        let node_id = signing_key.verifying_key();

        let mut node_info = NodeInfo {
            node_id,
            bootstrap: true,
            transports: None,
            metrics: NodeMetrics::default(),
        };

        // Node is not stale by default.
        assert!(!node_info.metrics.is_stale());

        // Node is not stale after reporting successful connection attempt.
        node_info.metrics.report_successful_connection();
        assert!(!node_info.metrics.is_stale());

        MockClock::advance_system_time(Duration::from_secs(1));

        // Node is stale after reporting failed connection attempt.
        node_info.metrics.report_failed_connection();
        assert!(node_info.metrics.is_stale());

        MockClock::advance_system_time(Duration::from_secs(1));

        // After a successful connection was reported, it is not stale again.
        node_info.metrics.report_successful_connection();
        assert!(!node_info.metrics.is_stale());
    }
}