protocol.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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.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().clone()];
  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. self.p2p.broadcast_with_exclude(&req_copy, &exclude_list).await;
  101. }
  102. match self.dht.read().await.map.get(&req_copy.key) {
  103. Some(value) => {
  104. let response =
  105. KeyResponse::new(daemon, req_copy.from, req_copy.key, value.clone());
  106. debug!(target: "dht::protocol", "Protocol::handle_receive_request(): sending response: {:?}", response);
  107. if let Err(e) = self.channel.send(&response).await {
  108. error!(target: "dht::protocol", "Protocol::handle_receive_request(): p2p broadcast of response failed: {}", e);
  109. };
  110. }
  111. None => {
  112. error!(target: "dht::protocol", "Protocol::handle_receive_request(): Requested key doesn't exist locally: {}", req_copy.key);
  113. }
  114. }
  115. }
  116. }
  117. async fn handle_receive_response(self: Arc<Self>) -> Result<()> {
  118. debug!(target: "dht::protocol", "Protocol::handle_receive_response() [START]");
  119. let exclude_list = vec![self.channel.address().clone()];
  120. loop {
  121. let resp = match self.resp_sub.receive().await {
  122. Ok(v) => v,
  123. Err(e) => {
  124. error!(target: "dht::protocol", "Protocol::handle_receive_response(): recv fail: {}", e);
  125. continue
  126. }
  127. };
  128. let resp_copy = (*resp).clone();
  129. debug!(target: "dht::protocol", "Protocol::handle_receive_response(): resp: {:?}", resp_copy);
  130. {
  131. let dht = &mut self.dht.write().await;
  132. if dht.seen.contains_key(&resp_copy.id) {
  133. debug!(
  134. target: "dht::protocol",
  135. "Protocol::handle_receive_request(): We have already seen this request."
  136. );
  137. continue
  138. }
  139. dht.seen.insert(resp_copy.id, Utc::now().timestamp());
  140. }
  141. if self.dht.read().await.id != resp_copy.to {
  142. self.p2p.broadcast_with_exclude(&resp_copy, &exclude_list).await;
  143. }
  144. self.notify_queue_sender.send(resp_copy.clone()).await?;
  145. }
  146. }
  147. async fn handle_receive_lookup_request(self: Arc<Self>) -> Result<()> {
  148. debug!(target: "dht::protocol", "Protocol::handle_receive_lookup_request() [START]");
  149. let exclude_list = vec![self.channel.address().clone()];
  150. loop {
  151. let req = match self.lookup_sub.receive().await {
  152. Ok(v) => v,
  153. Err(e) => {
  154. error!(target: "dht::protocol", "Protocol::handle_receive_lookup_request(): recv fail: {}", e);
  155. continue
  156. }
  157. };
  158. let req_copy = (*req).clone();
  159. debug!(target: "dht::protocol", "Protocol::handle_receive_lookup_request(): req: {:?}", req_copy);
  160. if !(0..=1).contains(&req_copy.req_type) {
  161. debug!(target: "dht::protocol", "Protocol::handle_receive_lookup_request(): Unknown request type.");
  162. continue
  163. }
  164. {
  165. let dht = &mut self.dht.write().await;
  166. if dht.seen.contains_key(&req_copy.id) {
  167. debug!(
  168. target: "dht::protocol",
  169. "Protocol::handle_receive_request(): We have already seen this request."
  170. );
  171. continue
  172. }
  173. dht.seen.insert(req_copy.id, Utc::now().timestamp());
  174. }
  175. let result = match req_copy.req_type {
  176. 0 => self.dht.write().await.lookup_insert(req_copy.key, req_copy.daemon),
  177. _ => self.dht.write().await.lookup_remove(req_copy.key, req_copy.daemon),
  178. };
  179. if let Err(e) = result {
  180. error!(target: "dht::protocol", "Protocol::handle_receive_lookup_request(): request action failed: {}", e);
  181. continue
  182. };
  183. self.p2p.broadcast_with_exclude(&req_copy, &exclude_list).await;
  184. }
  185. }
  186. async fn handle_receive_lookup_map_request(self: Arc<Self>) -> Result<()> {
  187. debug!(target: "dht::protocol", "Protocol::handle_receive_lookup_map_request() [START]");
  188. loop {
  189. let req = match self.lookup_map_sub.receive().await {
  190. Ok(v) => v,
  191. Err(e) => {
  192. error!(target: "dht::protocol", "Protocol::handle_receive_lookup_map_request(): recv fail: {}", e);
  193. continue
  194. }
  195. };
  196. debug!(target: "dht::protocol", "Protocol::handle_receive_lookup_map_request(): req: {:?}", req);
  197. {
  198. let dht = &mut self.dht.write().await;
  199. if dht.seen.contains_key(&req.id) {
  200. debug!(
  201. target: "dht::protocol",
  202. "Protocol::handle_receive_lookup_map_request(): We have already seen this request."
  203. );
  204. continue
  205. }
  206. dht.seen.insert(req.id, Utc::now().timestamp());
  207. }
  208. // Extra validations can be added here.
  209. let lookup = self.dht.read().await.lookup.clone();
  210. let response = LookupMapResponse::new(lookup);
  211. if let Err(e) = self.channel.send(&response).await {
  212. error!(target: "dht::protocol", "Protocol::handle_receive_lookup_map_request() channel send fail: {}", e);
  213. };
  214. }
  215. }
  216. }
  217. #[async_trait]
  218. impl ProtocolBase for Protocol {
  219. async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
  220. debug!(target: "dht::protocol", "Protocol::start() [START]");
  221. self.jobsman.clone().start(executor.clone());
  222. self.jobsman.clone().spawn(self.clone().handle_receive_request(), executor.clone()).await;
  223. self.jobsman.clone().spawn(self.clone().handle_receive_response(), executor.clone()).await;
  224. self.jobsman
  225. .clone()
  226. .spawn(self.clone().handle_receive_lookup_request(), executor.clone())
  227. .await;
  228. self.jobsman
  229. .clone()
  230. .spawn(self.clone().handle_receive_lookup_map_request(), executor.clone())
  231. .await;
  232. debug!(target: "dht::protocol", "Protocol::start() [END]");
  233. Ok(())
  234. }
  235. fn name(&self) -> &'static str {
  236. "Protocol"
  237. }
  238. }