mod.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::collections::{HashMap, HashSet};
  19. use async_std::sync::{Arc, RwLock};
  20. use chrono::Utc;
  21. use darkfi_serial::serialize;
  22. use futures::{select, FutureExt};
  23. use log::{debug, error, warn};
  24. use rand::{rngs::OsRng, Rng};
  25. use smol::Executor;
  26. use crate::{
  27. net,
  28. net::P2pPtr,
  29. util::async_util::sleep,
  30. Error::{NetworkNotConnected, UnknownKey},
  31. Result,
  32. };
  33. mod messages;
  34. use messages::{KeyRequest, KeyResponse, LookupMapRequest, LookupMapResponse, LookupRequest};
  35. mod protocol;
  36. use protocol::Protocol;
  37. // Constants configuration
  38. const SEEN_DURATION: i64 = 120;
  39. /// Atomic pointer to DHT state
  40. pub type DhtPtr = Arc<RwLock<Dht>>;
  41. // TODO: proper errors
  42. // TODO: lookup table to be based on directly connected peers, not broadcast based
  43. // Using string in structures because we are at an external crate
  44. // and cant use blake3 serialization. To be replaced once merged with core src.
  45. /// Struct representing DHT state.
  46. pub struct Dht {
  47. /// Daemon id
  48. pub id: blake3::Hash,
  49. /// Daemon hasmap
  50. pub map: HashMap<blake3::Hash, Vec<u8>>,
  51. /// Network lookup map, containing nodes that holds each key
  52. pub lookup: HashMap<blake3::Hash, HashSet<blake3::Hash>>,
  53. /// P2P network pointer
  54. pub p2p: P2pPtr,
  55. /// Channel to receive responses from P2P
  56. p2p_recv_channel: smol::channel::Receiver<KeyResponse>,
  57. /// Stop signal channel to terminate background processes
  58. stop_signal: smol::channel::Receiver<()>,
  59. /// Daemon seen requests/responses ids and timestamp,
  60. /// to prevent rebroadcasting and loops
  61. pub seen: HashMap<blake3::Hash, i64>,
  62. }
  63. impl Dht {
  64. pub async fn new(
  65. initial: Option<HashMap<blake3::Hash, HashSet<blake3::Hash>>>,
  66. p2p_ptr: P2pPtr,
  67. stop_signal: smol::channel::Receiver<()>,
  68. ex: Arc<Executor<'_>>,
  69. ) -> Result<DhtPtr> {
  70. // Generate a random id
  71. let n: u16 = OsRng.gen();
  72. let id = blake3::hash(&serialize(&n));
  73. let map = HashMap::default();
  74. let lookup = match initial {
  75. Some(l) => l,
  76. None => HashMap::default(),
  77. };
  78. let p2p = p2p_ptr.clone();
  79. let (p2p_send_channel, p2p_recv_channel) = smol::channel::unbounded::<KeyResponse>();
  80. let seen = HashMap::default();
  81. let dht = Arc::new(RwLock::new(Dht {
  82. id,
  83. map,
  84. lookup,
  85. p2p,
  86. p2p_recv_channel,
  87. stop_signal,
  88. seen,
  89. }));
  90. // Registering P2P protocols
  91. let registry = p2p_ptr.protocol_registry();
  92. let _dht = dht.clone();
  93. registry
  94. .register(net::SESSION_ALL, move |channel, p2p_ptr| {
  95. let sender = p2p_send_channel.clone();
  96. let dht = _dht.clone();
  97. async move { Protocol::init(channel, sender, dht, p2p_ptr).await.unwrap() }
  98. })
  99. .await;
  100. // Task to periodically clean up daemon seen messages
  101. ex.spawn(prune_seen_messages(dht.clone())).detach();
  102. Ok(dht)
  103. }
  104. /// Store provided key value pair, update lookup map and broadcast new insert to network
  105. pub async fn insert(
  106. &mut self,
  107. key: blake3::Hash,
  108. value: Vec<u8>,
  109. ) -> Result<Option<blake3::Hash>> {
  110. self.map.insert(key, value);
  111. if let Err(e) = self.lookup_insert(key, self.id) {
  112. error!(target: "dht", "Failed to insert record to lookup map: {}", e);
  113. return Err(e)
  114. };
  115. let request = LookupRequest::new(self.id, key, 0);
  116. self.p2p.broadcast(&request).await;
  117. Ok(Some(key))
  118. }
  119. /// Remove provided key value pair and update lookup map
  120. pub async fn remove(&mut self, key: blake3::Hash) -> Result<Option<blake3::Hash>> {
  121. // Check if key value pair existed and act accordingly
  122. match self.map.remove(&key) {
  123. Some(_) => {
  124. debug!(target: "dht", "Key removed: {}", key);
  125. let request = LookupRequest::new(self.id, key, 1);
  126. self.p2p.broadcast(&request).await;
  127. self.lookup_remove(key, self.id)
  128. }
  129. None => Ok(None),
  130. }
  131. }
  132. /// Store provided key node pair in lookup map and update network
  133. pub fn lookup_insert(
  134. &mut self,
  135. key: blake3::Hash,
  136. node_id: blake3::Hash,
  137. ) -> Result<Option<blake3::Hash>> {
  138. let mut lookup_set = match self.lookup.get(&key) {
  139. Some(s) => s.clone(),
  140. None => HashSet::new(),
  141. };
  142. lookup_set.insert(node_id);
  143. self.lookup.insert(key, lookup_set);
  144. Ok(Some(key))
  145. }
  146. /// Remove provided node id from keys set in local lookup map
  147. pub fn lookup_remove(
  148. &mut self,
  149. key: blake3::Hash,
  150. node_id: blake3::Hash,
  151. ) -> Result<Option<blake3::Hash>> {
  152. if let Some(s) = self.lookup.get(&key) {
  153. let mut lookup_set = s.clone();
  154. lookup_set.remove(&node_id);
  155. if lookup_set.is_empty() {
  156. self.lookup.remove(&key);
  157. } else {
  158. self.lookup.insert(key, lookup_set);
  159. }
  160. }
  161. Ok(Some(key))
  162. }
  163. /// Verify if provided key exists and return flag if local or in network
  164. pub fn contains_key(&self, key: blake3::Hash) -> Option<bool> {
  165. match self.lookup.contains_key(&key) {
  166. true => Some(self.map.contains_key(&key)),
  167. false => None,
  168. }
  169. }
  170. /// Get key from local map, acting as daemon cache
  171. pub fn get(&self, key: blake3::Hash) -> Option<&Vec<u8>> {
  172. self.map.get(&key)
  173. }
  174. /// Generate key request and broadcast it to the network
  175. pub async fn request_key(&self, key: blake3::Hash) -> Result<()> {
  176. // Verify the key exist in the lookup map.
  177. let peers = match self.lookup.get(&key) {
  178. Some(v) => v.clone(),
  179. None => return Err(UnknownKey),
  180. };
  181. debug!(target: "dht", "Key is in peers: {:?}", peers);
  182. // We retrieve p2p network connected channels, to verify if we
  183. // are connected to a network.
  184. // Using len here because is_empty() uses unstable library feature
  185. // called 'exact_size_is_empty'.
  186. if self.p2p.channels().lock().await.values().len() == 0 {
  187. return Err(NetworkNotConnected)
  188. }
  189. // We create a key request, and broadcast it to the network
  190. // We choose last known peer as request recipient
  191. let peer = *peers.iter().last().unwrap();
  192. let request = KeyRequest::new(self.id, peer, key);
  193. // TODO: ask connected peers directly, not broadcast
  194. self.p2p.broadcast(&request).await;
  195. Ok(())
  196. }
  197. /// Auxilary function to sync lookup map with network
  198. pub async fn sync_lookup_map(&mut self) -> Result<()> {
  199. debug!(target: "dht", "Starting lookup map sync...");
  200. let channels_map = self.p2p.channels().lock().await.clone();
  201. let values = channels_map.values();
  202. // Using len here because is_empty() uses unstable library feature
  203. // called 'exact_size_is_empty'.
  204. if values.len() != 0 {
  205. // Node iterates the channel peers to ask for their lookup map
  206. for channel in values {
  207. // Communication setup
  208. let msg_subsystem = channel.message_subsystem();
  209. msg_subsystem.add_dispatch::<LookupMapResponse>().await;
  210. let response_sub = channel.subscribe_msg::<LookupMapResponse>().await?;
  211. // Node creates a `LookupMapRequest` and sends it
  212. let order = LookupMapRequest::new(self.id);
  213. channel.send(&order).await?;
  214. // Node stores response data.
  215. let resp = response_sub.receive().await?;
  216. if resp.lookup.is_empty() {
  217. warn!(target: "dht", "Retrieved empty lookup map from an unsynced node, retrying...");
  218. continue
  219. }
  220. // Store retrieved records
  221. debug!(target: "dht", "Processing received records");
  222. for (k, v) in &resp.lookup {
  223. for node in v {
  224. self.lookup_insert(*k, *node)?;
  225. }
  226. }
  227. break
  228. }
  229. } else {
  230. warn!(target: "dht", "Node is not connected to other nodes");
  231. }
  232. debug!(target: "dht", "Lookup map synced!");
  233. Ok(())
  234. }
  235. }
  236. // Auxilary function to wait for a key response from the P2P network.
  237. pub async fn waiting_for_response(dht: DhtPtr) -> Result<Option<KeyResponse>> {
  238. let (p2p_recv_channel, stop_signal, timeout) = {
  239. let _dht = dht.read().await;
  240. (_dht.p2p_recv_channel.clone(), _dht.stop_signal.clone(), 666)
  241. };
  242. let ex = Arc::new(Executor::new());
  243. let (timeout_s, timeout_r) = smol::channel::unbounded::<()>();
  244. ex.spawn(async move {
  245. sleep(timeout).await;
  246. timeout_s.send(()).await.unwrap_or(());
  247. })
  248. .detach();
  249. select! {
  250. msg = p2p_recv_channel.recv().fuse() => {
  251. let response = msg?;
  252. return Ok(Some(response))
  253. },
  254. _ = stop_signal.recv().fuse() => {},
  255. _ = timeout_r.recv().fuse() => {},
  256. }
  257. Ok(None)
  258. }
  259. // Auxilary function to periodically prun seen messages, based on when they were received.
  260. // This helps us to prevent broadcasting loops.
  261. async fn prune_seen_messages(dht: DhtPtr) {
  262. loop {
  263. sleep(SEEN_DURATION as u64).await;
  264. debug!(target: "dht", "Pruning seen messages");
  265. let now = Utc::now().timestamp();
  266. let mut prune = vec![];
  267. let map = dht.read().await.seen.clone();
  268. for (k, v) in map.iter() {
  269. if now - v > SEEN_DURATION {
  270. prune.push(k);
  271. }
  272. }
  273. let mut map = map.clone();
  274. for i in prune {
  275. map.remove(i);
  276. }
  277. dht.write().await.seen = map;
  278. }
  279. }