Skip to main content

everscale_network/dht/
mod.rs

1//! ## DHT - Kademlia-like Distributed Hash Table
2//!
3//! TODO
4
5use std::sync::Arc;
6
7use anyhow::Result;
8use frunk_core::hlist::{HCons, HList, IntoTuple2, Selector};
9use frunk_core::indices::There;
10
11pub use entry::Entry;
12pub use node::{Node, NodeMetrics, NodeOptions};
13
14use crate::adnl;
15use crate::util::{DeferredInitialization, NetworkBuilder};
16
17mod buckets;
18mod entry;
19mod node;
20mod peers_iter;
21mod storage;
22
23/// DHT helper futures
24pub mod futures;
25/// DHT helper streams
26pub mod streams;
27
28pub(crate) type Deferred = Result<(Arc<adnl::Node>, usize, NodeOptions)>;
29
30impl DeferredInitialization for Deferred {
31    type Initialized = Arc<Node>;
32
33    fn initialize(self) -> Result<Self::Initialized> {
34        let (adnl, key_tag, options) = self?;
35        Node::new(adnl, key_tag, options)
36    }
37}
38
39impl<L, A, R> NetworkBuilder<L, (A, R)>
40where
41    L: HList + Selector<adnl::Deferred, A>,
42    HCons<Deferred, L>: IntoTuple2,
43{
44    /// Creates DHT network layer
45    ///
46    /// # Examples
47    ///
48    /// ```
49    /// # use std::error::Error;
50    /// # use anyhow::Result;
51    /// # use everscale_network::{adnl, dht, NetworkBuilder};
52    ///
53    /// #[tokio::main]
54    /// async fn main() -> Result<()> {
55    ///     const DHT_KEY_TAG: usize = 0;
56    ///
57    ///     let keystore = adnl::Keystore::builder()
58    ///         .with_tagged_key([0; 32], DHT_KEY_TAG)?
59    ///         .build();
60    ///
61    ///     let adnl_options = adnl::NodeOptions::default();
62    ///     let dht_options = dht::NodeOptions::default();
63    ///
64    ///     let (adnl, dht) = NetworkBuilder::with_adnl("127.0.0.1:10000", keystore, adnl_options)
65    ///         .with_dht(DHT_KEY_TAG, dht_options)
66    ///         .build()?;
67    ///     Ok(())
68    /// }
69    /// ```
70    #[allow(clippy::type_complexity)]
71    pub fn with_dht(
72        self,
73        key_tag: usize,
74        options: NodeOptions,
75    ) -> NetworkBuilder<HCons<Deferred, L>, (There<A>, There<R>)> {
76        let deferred = match self.0.get() {
77            Ok(adnl) => Ok((adnl.clone(), key_tag, options)),
78            Err(_) => Err(anyhow::anyhow!("ADNL was not initialized")),
79        };
80        NetworkBuilder(self.0.prepend(deferred), Default::default())
81    }
82}
83
84/// DHT key name used for storing nodes socket address
85pub const KEY_ADDRESS: &str = "address";
86
87/// DHT key name used for storing overlay nodes
88pub const KEY_NODES: &str = "nodes";
89
90/// Max allowed DHT peers in the network
91pub const MAX_DHT_PEERS: u32 = 65536;