protocol.rs 10 KB

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