protocol.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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 async_std::sync::Arc;
  19. use async_trait::async_trait;
  20. use chrono::Utc;
  21. use log::{debug, error};
  22. use smol::Executor;
  23. use crate::{
  24. net::{
  25. ChannelPtr, MessageSubscription, P2pPtr, ProtocolBase, ProtocolBasePtr,
  26. ProtocolJobsManager, ProtocolJobsManagerPtr,
  27. },
  28. Result,
  29. };
  30. use super::{
  31. messages::{KeyRequest, KeyResponse, LookupMapRequest, LookupMapResponse, LookupRequest},
  32. DhtPtr,
  33. };
  34. pub struct Protocol {
  35. channel: ChannelPtr,
  36. notify_queue_sender: smol::channel::Sender<KeyResponse>,
  37. req_sub: MessageSubscription<KeyRequest>,
  38. resp_sub: MessageSubscription<KeyResponse>,
  39. lookup_sub: MessageSubscription<LookupRequest>,
  40. lookup_map_sub: MessageSubscription<LookupMapRequest>,
  41. jobsman: ProtocolJobsManagerPtr,
  42. dht: DhtPtr,
  43. p2p: P2pPtr,
  44. }
  45. impl Protocol {
  46. pub async fn init(
  47. channel: ChannelPtr,
  48. notify_queue_sender: smol::channel::Sender<KeyResponse>,
  49. dht: DhtPtr,
  50. p2p: P2pPtr,
  51. ) -> Result<ProtocolBasePtr> {
  52. debug!(target: "dht::protocol", "Adding Protocol to the protocol registry");
  53. let msg_subsystem = channel.get_message_subsystem();
  54. msg_subsystem.add_dispatch::<KeyRequest>().await;
  55. msg_subsystem.add_dispatch::<KeyResponse>().await;
  56. msg_subsystem.add_dispatch::<LookupRequest>().await;
  57. msg_subsystem.add_dispatch::<LookupMapRequest>().await;
  58. let req_sub = channel.subscribe_msg::<KeyRequest>().await?;
  59. let resp_sub = channel.subscribe_msg::<KeyResponse>().await?;
  60. let lookup_sub = channel.subscribe_msg::<LookupRequest>().await?;
  61. let lookup_map_sub = channel.subscribe_msg::<LookupMapRequest>().await?;
  62. Ok(Arc::new(Self {
  63. channel: channel.clone(),
  64. notify_queue_sender,
  65. req_sub,
  66. resp_sub,
  67. lookup_sub,
  68. lookup_map_sub,
  69. jobsman: ProtocolJobsManager::new("Protocol", channel),
  70. dht,
  71. p2p,
  72. }))
  73. }
  74. async fn handle_receive_request(self: Arc<Self>) -> Result<()> {
  75. debug!(target: "dht::protocol", "Protocol::handle_receive_request() [START]");
  76. let exclude_list = vec![self.channel.address()];
  77. loop {
  78. let req = match self.req_sub.receive().await {
  79. Ok(v) => v,
  80. Err(e) => {
  81. error!(target: "dht::protocol", "Protocol::handle_receive_request(): recv fail: {}", e);
  82. continue
  83. }
  84. };
  85. let req_copy = (*req).clone();
  86. debug!(target: "dht::protocol", "Protocol::handle_receive_request(): req: {:?}", req_copy);
  87. {
  88. let dht = &mut self.dht.write().await;
  89. if dht.seen.contains_key(&req_copy.id) {
  90. debug!(
  91. target: "dht::protocol",
  92. "Protocol::handle_receive_request(): We have already seen this request."
  93. );
  94. continue
  95. }
  96. dht.seen.insert(req_copy.id, Utc::now().timestamp());
  97. }
  98. let daemon = self.dht.read().await.id;
  99. if daemon != req_copy.to {
  100. if let Err(e) =
  101. self.p2p.broadcast_with_exclude(req_copy.clone(), &exclude_list).await
  102. {
  103. error!(target: "dht::protocol", "Protocol::handle_receive_response(): p2p broadcast fail: {}", e);
  104. };
  105. continue
  106. }
  107. match self.dht.read().await.map.get(&req_copy.key) {
  108. Some(value) => {
  109. let response =
  110. KeyResponse::new(daemon, req_copy.from, req_copy.key, value.clone());
  111. debug!(target: "dht::protocol", "Protocol::handle_receive_request(): sending response: {:?}", response);
  112. if let Err(e) = self.channel.send(response).await {
  113. error!(target: "dht::protocol", "Protocol::handle_receive_request(): p2p broadcast of response failed: {}", e);
  114. };
  115. }
  116. None => {
  117. error!(target: "dht::protocol", "Protocol::handle_receive_request(): Requested key doesn't exist locally: {}", req_copy.key);
  118. }
  119. }
  120. }
  121. }
  122. async fn handle_receive_response(self: Arc<Self>) -> Result<()> {
  123. debug!(target: "dht::protocol", "Protocol::handle_receive_response() [START]");
  124. let exclude_list = vec![self.channel.address()];
  125. loop {
  126. let resp = match self.resp_sub.receive().await {
  127. Ok(v) => v,
  128. Err(e) => {
  129. error!(target: "dht::protocol", "Protocol::handle_receive_response(): recv fail: {}", e);
  130. continue
  131. }
  132. };
  133. let resp_copy = (*resp).clone();
  134. debug!(target: "dht::protocol", "Protocol::handle_receive_response(): resp: {:?}", resp_copy);
  135. {
  136. let dht = &mut self.dht.write().await;
  137. if dht.seen.contains_key(&resp_copy.id) {
  138. debug!(
  139. target: "dht::protocol",
  140. "Protocol::handle_receive_request(): We have already seen this request."
  141. );
  142. continue
  143. }
  144. dht.seen.insert(resp_copy.id, Utc::now().timestamp());
  145. }
  146. if self.dht.read().await.id != resp_copy.to {
  147. if let Err(e) =
  148. self.p2p.broadcast_with_exclude(resp_copy.clone(), &exclude_list).await
  149. {
  150. error!(target: "dht::protocol", "Protocol::handle_receive_response(): p2p broadcast fail: {}", e);
  151. };
  152. continue
  153. }
  154. self.notify_queue_sender.send(resp_copy.clone()).await?;
  155. }
  156. }
  157. async fn handle_receive_lookup_request(self: Arc<Self>) -> Result<()> {
  158. debug!(target: "dht::protocol", "Protocol::handle_receive_lookup_request() [START]");
  159. let exclude_list = vec![self.channel.address()];
  160. loop {
  161. let req = match self.lookup_sub.receive().await {
  162. Ok(v) => v,
  163. Err(e) => {
  164. error!(target: "dht::protocol", "Protocol::handle_receive_lookup_request(): recv fail: {}", e);
  165. continue
  166. }
  167. };
  168. let req_copy = (*req).clone();
  169. debug!(target: "dht::protocol", "Protocol::handle_receive_lookup_request(): req: {:?}", req_copy);
  170. if !(0..=1).contains(&req_copy.req_type) {
  171. debug!(target: "dht::protocol", "Protocol::handle_receive_lookup_request(): Unknown request type.");
  172. continue
  173. }
  174. {
  175. let dht = &mut self.dht.write().await;
  176. if dht.seen.contains_key(&req_copy.id) {
  177. debug!(
  178. target: "dht::protocol",
  179. "Protocol::handle_receive_request(): We have already seen this request."
  180. );
  181. continue
  182. }
  183. dht.seen.insert(req_copy.id, Utc::now().timestamp());
  184. }
  185. let result = match req_copy.req_type {
  186. 0 => self.dht.write().await.lookup_insert(req_copy.key, req_copy.daemon),
  187. _ => self.dht.write().await.lookup_remove(req_copy.key, req_copy.daemon),
  188. };
  189. if let Err(e) = result {
  190. error!(target: "dht::protocol", "Protocol::handle_receive_lookup_request(): request action failed: {}", e);
  191. continue
  192. };
  193. if let Err(e) = self.p2p.broadcast_with_exclude(req_copy, &exclude_list).await {
  194. error!(target: "dht::protocol", "Protocol::handle_receive_lookup_request(): p2p broadcast fail: {}", e);
  195. };
  196. }
  197. }
  198. async fn handle_receive_lookup_map_request(self: Arc<Self>) -> Result<()> {
  199. debug!(target: "dht::protocol", "Protocol::handle_receive_lookup_map_request() [START]");
  200. loop {
  201. let req = match self.lookup_map_sub.receive().await {
  202. Ok(v) => v,
  203. Err(e) => {
  204. error!(target: "dht::protocol", "Protocol::handle_receive_lookup_map_request(): recv fail: {}", e);
  205. continue
  206. }
  207. };
  208. debug!(target: "dht::protocol", "Protocol::handle_receive_lookup_map_request(): req: {:?}", req);
  209. {
  210. let dht = &mut self.dht.write().await;
  211. if dht.seen.contains_key(&req.id) {
  212. debug!(
  213. target: "dht::protocol",
  214. "Protocol::handle_receive_lookup_map_request(): We have already seen this request."
  215. );
  216. continue
  217. }
  218. dht.seen.insert(req.id, Utc::now().timestamp());
  219. }
  220. // Extra validations can be added here.
  221. let lookup = self.dht.read().await.lookup.clone();
  222. let response = LookupMapResponse::new(lookup);
  223. if let Err(e) = self.channel.send(response).await {
  224. error!(target: "dht::protocol", "Protocol::handle_receive_lookup_map_request() channel send fail: {}", e);
  225. };
  226. }
  227. }
  228. }
  229. #[async_trait]
  230. impl ProtocolBase for Protocol {
  231. async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
  232. debug!(target: "dht::protocol", "Protocol::start() [START]");
  233. self.jobsman.clone().start(executor.clone());
  234. self.jobsman.clone().spawn(self.clone().handle_receive_request(), executor.clone()).await;
  235. self.jobsman.clone().spawn(self.clone().handle_receive_response(), executor.clone()).await;
  236. self.jobsman
  237. .clone()
  238. .spawn(self.clone().handle_receive_lookup_request(), executor.clone())
  239. .await;
  240. self.jobsman
  241. .clone()
  242. .spawn(self.clone().handle_receive_lookup_map_request(), executor.clone())
  243. .await;
  244. debug!(target: "dht::protocol", "Protocol::start() [END]");
  245. Ok(())
  246. }
  247. fn name(&self) -> &'static str {
  248. "Protocol"
  249. }
  250. }