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
// Copyright 2019 Parity Technologies (UK) Ltd.
// Copyright 2021 Protocol Labs.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

use crate::ConnectionId;
use libp2p_core::connection::Endpoint;
use libp2p_core::multiaddr::Protocol;
use libp2p_core::multihash::Multihash;
use libp2p_core::Multiaddr;
use libp2p_identity::PeerId;
use std::num::NonZeroU8;

/// Options to configure a dial to a known or unknown peer.
///
/// Used in [`Swarm::dial`](crate::Swarm::dial) and
/// [`ToSwarm::Dial`](crate::behaviour::ToSwarm::Dial).
///
/// To construct use either of:
///
/// - [`DialOpts::peer_id`] dialing a known peer
///
/// - [`DialOpts::unknown_peer_id`] dialing an unknown peer
#[derive(Debug)]
pub struct DialOpts {
    peer_id: Option<PeerId>,
    condition: PeerCondition,
    addresses: Vec<Multiaddr>,
    extend_addresses_through_behaviour: bool,
    role_override: Endpoint,
    dial_concurrency_factor_override: Option<NonZeroU8>,
    connection_id: ConnectionId,
}

impl DialOpts {
    /// Dial a known peer.
    ///
    ///   ```
    ///   # use libp2p_swarm::dial_opts::{DialOpts, PeerCondition};
    ///   # use libp2p_identity::PeerId;
    ///   DialOpts::peer_id(PeerId::random())
    ///      .condition(PeerCondition::Disconnected)
    ///      .addresses(vec!["/ip6/::1/tcp/12345".parse().unwrap()])
    ///      .extend_addresses_through_behaviour()
    ///      .build();
    ///   ```
    pub fn peer_id(peer_id: PeerId) -> WithPeerId {
        WithPeerId {
            peer_id,
            condition: Default::default(),
            role_override: Endpoint::Dialer,
            dial_concurrency_factor_override: Default::default(),
        }
    }

    /// Dial an unknown peer.
    ///
    ///   ```
    ///   # use libp2p_swarm::dial_opts::DialOpts;
    ///   DialOpts::unknown_peer_id()
    ///      .address("/ip6/::1/tcp/12345".parse().unwrap())
    ///      .build();
    ///   ```
    pub fn unknown_peer_id() -> WithoutPeerId {
        WithoutPeerId {}
    }

    /// Get the [`PeerId`] specified in a [`DialOpts`] if any.
    pub fn get_peer_id(&self) -> Option<PeerId> {
        self.peer_id
    }

    /// Get the [`ConnectionId`] of this dial attempt.
    ///
    /// All future events of this dial will be associated with this ID.
    /// See [`DialFailure`](crate::DialFailure) and [`ConnectionEstablished`](crate::behaviour::ConnectionEstablished).
    pub fn connection_id(&self) -> ConnectionId {
        self.connection_id
    }

    /// Retrieves the [`PeerId`] from the [`DialOpts`] if specified or otherwise tries to parse it
    /// from the multihash in the `/p2p` part of the address, if present.
    ///
    /// Note: A [`Multiaddr`] with something else other than a [`PeerId`] within the `/p2p` protocol is invalid as per specification.
    /// Unfortunately, we are not making good use of the type system here.
    /// Really, this function should be merged with [`DialOpts::get_peer_id`] above.
    /// If it weren't for the parsing error, the function signatures would be the same.
    ///
    /// See <https://github.com/multiformats/rust-multiaddr/issues/73>.
    pub(crate) fn get_or_parse_peer_id(&self) -> Result<Option<PeerId>, Multihash> {
        if let Some(peer_id) = self.peer_id {
            return Ok(Some(peer_id));
        }

        let first_address = match self.addresses.first() {
            Some(first_address) => first_address,
            None => return Ok(None),
        };

        let maybe_peer_id = first_address
            .iter()
            .last()
            .and_then(|p| {
                if let Protocol::P2p(ma) = p {
                    Some(PeerId::try_from(ma))
                } else {
                    None
                }
            })
            .transpose()?;

        Ok(maybe_peer_id)
    }

    pub(crate) fn get_addresses(&self) -> Vec<Multiaddr> {
        self.addresses.clone()
    }

    pub(crate) fn extend_addresses_through_behaviour(&self) -> bool {
        self.extend_addresses_through_behaviour
    }

    pub(crate) fn peer_condition(&self) -> PeerCondition {
        self.condition
    }

    pub(crate) fn dial_concurrency_override(&self) -> Option<NonZeroU8> {
        self.dial_concurrency_factor_override
    }

    pub(crate) fn role_override(&self) -> Endpoint {
        self.role_override
    }
}

impl From<Multiaddr> for DialOpts {
    fn from(address: Multiaddr) -> Self {
        DialOpts::unknown_peer_id().address(address).build()
    }
}

impl From<PeerId> for DialOpts {
    fn from(peer_id: PeerId) -> Self {
        DialOpts::peer_id(peer_id).build()
    }
}

#[derive(Debug)]
pub struct WithPeerId {
    peer_id: PeerId,
    condition: PeerCondition,
    role_override: Endpoint,
    dial_concurrency_factor_override: Option<NonZeroU8>,
}

impl WithPeerId {
    /// Specify a [`PeerCondition`] for the dial.
    pub fn condition(mut self, condition: PeerCondition) -> Self {
        self.condition = condition;
        self
    }

    /// Override
    /// Number of addresses concurrently dialed for a single outbound connection attempt.
    pub fn override_dial_concurrency_factor(mut self, factor: NonZeroU8) -> Self {
        self.dial_concurrency_factor_override = Some(factor);
        self
    }

    /// Specify a set of addresses to be used to dial the known peer.
    pub fn addresses(self, addresses: Vec<Multiaddr>) -> WithPeerIdWithAddresses {
        WithPeerIdWithAddresses {
            peer_id: self.peer_id,
            condition: self.condition,
            addresses,
            extend_addresses_through_behaviour: false,
            role_override: self.role_override,
            dial_concurrency_factor_override: self.dial_concurrency_factor_override,
        }
    }

    /// Override role of local node on connection. I.e. execute the dial _as a
    /// listener_.
    ///
    /// See
    /// [`ConnectedPoint::Dialer`](libp2p_core::connection::ConnectedPoint::Dialer)
    /// for details.
    pub fn override_role(mut self) -> Self {
        self.role_override = Endpoint::Listener;
        self
    }

    /// Build the final [`DialOpts`].
    ///
    /// Addresses to dial the peer are retrieved via
    /// [`NetworkBehaviour::addresses_of_peer`](crate::behaviour::NetworkBehaviour::addresses_of_peer).
    pub fn build(self) -> DialOpts {
        DialOpts {
            peer_id: Some(self.peer_id),
            condition: self.condition,
            addresses: vec![],
            extend_addresses_through_behaviour: true,
            role_override: self.role_override,
            dial_concurrency_factor_override: self.dial_concurrency_factor_override,
            connection_id: ConnectionId::next(),
        }
    }
}

#[derive(Debug)]
pub struct WithPeerIdWithAddresses {
    peer_id: PeerId,
    condition: PeerCondition,
    addresses: Vec<Multiaddr>,
    extend_addresses_through_behaviour: bool,
    role_override: Endpoint,
    dial_concurrency_factor_override: Option<NonZeroU8>,
}

impl WithPeerIdWithAddresses {
    /// Specify a [`PeerCondition`] for the dial.
    pub fn condition(mut self, condition: PeerCondition) -> Self {
        self.condition = condition;
        self
    }

    /// In addition to the provided addresses, extend the set via
    /// [`NetworkBehaviour::addresses_of_peer`](crate::behaviour::NetworkBehaviour::addresses_of_peer).
    pub fn extend_addresses_through_behaviour(mut self) -> Self {
        self.extend_addresses_through_behaviour = true;
        self
    }

    /// Override role of local node on connection. I.e. execute the dial _as a
    /// listener_.
    ///
    /// See
    /// [`ConnectedPoint::Dialer`](libp2p_core::connection::ConnectedPoint::Dialer)
    /// for details.
    pub fn override_role(mut self) -> Self {
        self.role_override = Endpoint::Listener;
        self
    }

    /// Override
    /// Number of addresses concurrently dialed for a single outbound connection attempt.
    pub fn override_dial_concurrency_factor(mut self, factor: NonZeroU8) -> Self {
        self.dial_concurrency_factor_override = Some(factor);
        self
    }

    /// Build the final [`DialOpts`].
    pub fn build(self) -> DialOpts {
        DialOpts {
            peer_id: Some(self.peer_id),
            condition: self.condition,
            addresses: self.addresses,
            extend_addresses_through_behaviour: self.extend_addresses_through_behaviour,
            role_override: self.role_override,
            dial_concurrency_factor_override: self.dial_concurrency_factor_override,
            connection_id: ConnectionId::next(),
        }
    }
}

#[derive(Debug)]
pub struct WithoutPeerId {}

impl WithoutPeerId {
    /// Specify a single address to dial the unknown peer.
    pub fn address(self, address: Multiaddr) -> WithoutPeerIdWithAddress {
        WithoutPeerIdWithAddress {
            address,
            role_override: Endpoint::Dialer,
        }
    }
}

#[derive(Debug)]
pub struct WithoutPeerIdWithAddress {
    address: Multiaddr,
    role_override: Endpoint,
}

impl WithoutPeerIdWithAddress {
    /// Override role of local node on connection. I.e. execute the dial _as a
    /// listener_.
    ///
    /// See
    /// [`ConnectedPoint::Dialer`](libp2p_core::connection::ConnectedPoint::Dialer)
    /// for details.
    pub fn override_role(mut self) -> Self {
        self.role_override = Endpoint::Listener;
        self
    }
    /// Build the final [`DialOpts`].
    pub fn build(self) -> DialOpts {
        DialOpts {
            peer_id: None,
            condition: PeerCondition::Always,
            addresses: vec![self.address],
            extend_addresses_through_behaviour: false,
            role_override: self.role_override,
            dial_concurrency_factor_override: None,
            connection_id: ConnectionId::next(),
        }
    }
}

/// The available conditions under which a new dialing attempt to
/// a known peer is initiated.
///
/// ```
/// # use libp2p_swarm::dial_opts::{DialOpts, PeerCondition};
/// # use libp2p_identity::PeerId;
/// #
/// DialOpts::peer_id(PeerId::random())
///    .condition(PeerCondition::Disconnected)
///    .build();
/// ```
#[derive(Debug, Copy, Clone, Default)]
pub enum PeerCondition {
    /// A new dialing attempt is initiated _only if_ the peer is currently
    /// considered disconnected, i.e. there is no established connection
    /// and no ongoing dialing attempt.
    #[default]
    Disconnected,
    /// A new dialing attempt is initiated _only if_ there is currently
    /// no ongoing dialing attempt, i.e. the peer is either considered
    /// disconnected or connected but without an ongoing dialing attempt.
    NotDialing,
    /// A new dialing attempt is always initiated, only subject to the
    /// configured connection limits.
    Always,
}