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
use crate::behaviour::{ExternalAddrConfirmed, ExternalAddrExpired, FromSwarm};
use libp2p_core::Multiaddr;

/// The maximum number of local external addresses. When reached any
/// further externally reported addresses are ignored. The behaviour always
/// tracks all its listen addresses.
const MAX_LOCAL_EXTERNAL_ADDRS: usize = 20;

/// Utility struct for tracking the external addresses of a [`Swarm`](crate::Swarm).
#[derive(Debug, Clone, Default)]
pub struct ExternalAddresses {
    addresses: Vec<Multiaddr>,
}

impl ExternalAddresses {
    /// Returns an [`Iterator`] over all external addresses.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = &Multiaddr> {
        self.addresses.iter()
    }

    pub fn as_slice(&self) -> &[Multiaddr] {
        self.addresses.as_slice()
    }

    /// Feed a [`FromSwarm`] event to this struct.
    ///
    /// Returns whether the event changed our set of external addresses.
    pub fn on_swarm_event<THandler>(&mut self, event: &FromSwarm<THandler>) -> bool {
        match event {
            FromSwarm::ExternalAddrConfirmed(ExternalAddrConfirmed { addr }) => {
                if let Some(pos) = self
                    .addresses
                    .iter()
                    .position(|candidate| candidate == *addr)
                {
                    // Refresh the existing confirmed address.
                    self.addresses.remove(pos);
                    self.push_front(addr);

                    log::debug!("Refreshed external address {addr}");

                    return false; // No changes to our external addresses.
                }

                self.push_front(addr);

                if self.addresses.len() > MAX_LOCAL_EXTERNAL_ADDRS {
                    let expired = self.addresses.pop().expect("list to be not empty");

                    log::debug!("Removing previously confirmed external address {expired} because we reached the limit of {MAX_LOCAL_EXTERNAL_ADDRS} addresses");
                }

                return true;
            }
            FromSwarm::ExternalAddrExpired(ExternalAddrExpired {
                addr: expired_addr, ..
            }) => {
                let pos = match self
                    .addresses
                    .iter()
                    .position(|candidate| candidate == *expired_addr)
                {
                    None => return false,
                    Some(p) => p,
                };

                self.addresses.remove(pos);
                return true;
            }
            _ => {}
        }

        false
    }

    fn push_front(&mut self, addr: &Multiaddr) {
        self.addresses.insert(0, addr.clone()); // We have at most `MAX_LOCAL_EXTERNAL_ADDRS` so this isn't very expensive.
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dummy;
    use libp2p_core::multiaddr::Protocol;
    use once_cell::sync::Lazy;
    use rand::Rng;

    #[test]
    fn new_external_addr_returns_correct_changed_value() {
        let mut addresses = ExternalAddresses::default();

        let changed = addresses.on_swarm_event(&new_external_addr1());
        assert!(changed);

        let changed = addresses.on_swarm_event(&new_external_addr1());
        assert!(!changed)
    }

    #[test]
    fn expired_external_addr_returns_correct_changed_value() {
        let mut addresses = ExternalAddresses::default();
        addresses.on_swarm_event(&new_external_addr1());

        let changed = addresses.on_swarm_event(&expired_external_addr1());
        assert!(changed);

        let changed = addresses.on_swarm_event(&expired_external_addr1());
        assert!(!changed)
    }

    #[test]
    fn more_recent_external_addresses_are_prioritized() {
        let mut addresses = ExternalAddresses::default();

        addresses.on_swarm_event(&new_external_addr1());
        addresses.on_swarm_event(&new_external_addr2());

        assert_eq!(
            addresses.as_slice(),
            &[(*MEMORY_ADDR_2000).clone(), (*MEMORY_ADDR_1000).clone()]
        );
    }

    #[test]
    fn when_pushing_more_than_max_addresses_oldest_is_evicted() {
        let mut addresses = ExternalAddresses::default();

        while addresses.as_slice().len() < MAX_LOCAL_EXTERNAL_ADDRS {
            let random_address =
                Multiaddr::empty().with(Protocol::Memory(rand::thread_rng().gen_range(0..1000)));
            addresses.on_swarm_event(
                &FromSwarm::<'_, dummy::ConnectionHandler>::ExternalAddrConfirmed(
                    ExternalAddrConfirmed {
                        addr: &random_address,
                    },
                ),
            );
        }

        addresses.on_swarm_event(&new_external_addr2());

        assert_eq!(addresses.as_slice().len(), 20);
        assert_eq!(addresses.as_slice()[0], (*MEMORY_ADDR_2000).clone());
    }

    #[test]
    fn reporting_existing_external_address_moves_it_to_the_front() {
        let mut addresses = ExternalAddresses::default();

        addresses.on_swarm_event(&new_external_addr1());
        addresses.on_swarm_event(&new_external_addr2());
        addresses.on_swarm_event(&new_external_addr1());

        assert_eq!(
            addresses.as_slice(),
            &[(*MEMORY_ADDR_1000).clone(), (*MEMORY_ADDR_2000).clone()]
        );
    }

    fn new_external_addr1() -> FromSwarm<'static, dummy::ConnectionHandler> {
        FromSwarm::ExternalAddrConfirmed(ExternalAddrConfirmed {
            addr: &MEMORY_ADDR_1000,
        })
    }

    fn new_external_addr2() -> FromSwarm<'static, dummy::ConnectionHandler> {
        FromSwarm::ExternalAddrConfirmed(ExternalAddrConfirmed {
            addr: &MEMORY_ADDR_2000,
        })
    }

    fn expired_external_addr1() -> FromSwarm<'static, dummy::ConnectionHandler> {
        FromSwarm::ExternalAddrExpired(ExternalAddrExpired {
            addr: &MEMORY_ADDR_1000,
        })
    }

    static MEMORY_ADDR_1000: Lazy<Multiaddr> =
        Lazy::new(|| Multiaddr::empty().with(Protocol::Memory(1000)));
    static MEMORY_ADDR_2000: Lazy<Multiaddr> =
        Lazy::new(|| Multiaddr::empty().with(Protocol::Memory(2000)));
}