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
// Copyright 2023 litep2p developers
//
// 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::{
    codec::ProtocolCodec,
    protocol::libp2p::kademlia::handle::{
        KademliaCommand, KademliaEvent, KademliaHandle, RoutingTableUpdateMode,
    },
    types::protocol::ProtocolName,
    PeerId, DEFAULT_CHANNEL_SIZE,
};

use multiaddr::Multiaddr;
use tokio::sync::mpsc::{channel, Receiver, Sender};

use std::collections::HashMap;

/// Protocol name.
const PROTOCOL_NAME: &str = "/ipfs/kad/1.0.0";

/// Kademlia replication factor.
const REPLICATION_FACTOR: usize = 20usize;

/// Kademlia configuration.
#[derive(Debug)]
pub struct Config {
    // Protocol name.
    // pub(crate) protocol: ProtocolName,
    /// Protocol names.
    pub(crate) protocol_names: Vec<ProtocolName>,

    /// Protocol codec.
    pub(crate) codec: ProtocolCodec,

    /// Replication factor.
    #[allow(unused)]
    pub(super) replication_factor: usize,

    /// Known peers.
    pub(super) known_peers: HashMap<PeerId, Vec<Multiaddr>>,

    /// Routing table update mode.
    pub(super) update_mode: RoutingTableUpdateMode,

    /// TX channel for sending events to `KademliaHandle`.
    pub(super) event_tx: Sender<KademliaEvent>,

    /// RX channel for receiving commands from `KademliaHandle`.
    pub(super) cmd_rx: Receiver<KademliaCommand>,
}

impl Config {
    fn new(
        replication_factor: usize,
        known_peers: HashMap<PeerId, Vec<Multiaddr>>,
        mut protocol_names: Vec<ProtocolName>,
        update_mode: RoutingTableUpdateMode,
    ) -> (Self, KademliaHandle) {
        let (cmd_tx, cmd_rx) = channel(DEFAULT_CHANNEL_SIZE);
        let (event_tx, event_rx) = channel(DEFAULT_CHANNEL_SIZE);

        // if no protocol names were provided, use the default protocol
        if protocol_names.is_empty() {
            protocol_names.push(ProtocolName::from(PROTOCOL_NAME));
        }

        (
            Config {
                protocol_names,
                update_mode,
                codec: ProtocolCodec::UnsignedVarint(None),
                replication_factor,
                known_peers,
                cmd_rx,
                event_tx,
            },
            KademliaHandle::new(cmd_tx, event_rx),
        )
    }

    /// Build default Kademlia configuration.
    pub fn default() -> (Self, KademliaHandle) {
        Self::new(
            REPLICATION_FACTOR,
            HashMap::new(),
            Vec::new(),
            RoutingTableUpdateMode::Automatic,
        )
    }
}

/// Configuration builder for Kademlia.
#[derive(Debug)]
pub struct ConfigBuilder {
    /// Replication factor.
    pub(super) replication_factor: usize,

    /// Routing table update mode.
    pub(super) update_mode: RoutingTableUpdateMode,

    /// Known peers.
    pub(super) known_peers: HashMap<PeerId, Vec<Multiaddr>>,

    /// Protocol names.
    pub(super) protocol_names: Vec<ProtocolName>,
}

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

impl ConfigBuilder {
    /// Create new [`ConfigBuilder`].
    pub fn new() -> Self {
        Self {
            replication_factor: REPLICATION_FACTOR,
            known_peers: HashMap::new(),
            protocol_names: Vec::new(),
            update_mode: RoutingTableUpdateMode::Automatic,
        }
    }

    /// Set replication factor.
    pub fn with_replication_factor(mut self, replication_factor: usize) -> Self {
        self.replication_factor = replication_factor;
        self
    }

    /// Seed Kademlia with one or more known peers.
    pub fn with_known_peers(mut self, peers: HashMap<PeerId, Vec<Multiaddr>>) -> Self {
        self.known_peers = peers;
        self
    }

    /// Set routing table update mode.
    pub fn with_routing_table_update_mode(mut self, mode: RoutingTableUpdateMode) -> Self {
        self.update_mode = mode;
        self
    }

    /// Set Kademlia protocol names, overriding the default protocol name.
    ///
    /// The order of the protocol names signifies preference so if, for example, there are two
    /// protocols:
    ///  * `/kad/2.0.0`
    ///  * `/kad/1.0.0`
    ///
    /// Where `/kad/2.0.0` is the preferred version, then that should be in `protocol_names` before
    /// `/kad/1.0.0`.
    pub fn with_protocol_names(mut self, protocol_names: Vec<ProtocolName>) -> Self {
        self.protocol_names = protocol_names;
        self
    }

    /// Build Kademlia [`Config`].
    pub fn build(self) -> (Config, KademliaHandle) {
        Config::new(
            self.replication_factor,
            self.known_peers,
            self.protocol_names,
            self.update_mode,
        )
    }
}