proto.rs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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::HashSet;
  19. use async_std::sync::Arc;
  20. use async_trait::async_trait;
  21. use darkfi::{
  22. dht2::net_hashmap::{NetHashMapInsert, NetHashMapRemove},
  23. net::{
  24. self, ChannelPtr, MessageSubscription, P2pPtr, ProtocolBase, ProtocolBasePtr,
  25. ProtocolJobsManager, ProtocolJobsManagerPtr,
  26. },
  27. Result,
  28. };
  29. use darkfi_serial::{SerialDecodable, SerialEncodable};
  30. use log::debug;
  31. use smol::Executor;
  32. use super::DhtdPtr;
  33. pub struct ProtocolDht {
  34. jobsman: ProtocolJobsManagerPtr,
  35. channel: ChannelPtr,
  36. _p2p: P2pPtr,
  37. state: DhtdPtr,
  38. insert_sub: MessageSubscription<NetHashMapInsert<blake3::Hash, Vec<blake3::Hash>>>,
  39. remove_sub: MessageSubscription<NetHashMapRemove<blake3::Hash>>,
  40. chunk_request_sub: MessageSubscription<ChunkRequest>,
  41. chunk_reply_sub: MessageSubscription<ChunkReply>,
  42. file_request_sub: MessageSubscription<FileRequest>,
  43. file_reply_sub: MessageSubscription<FileReply>,
  44. }
  45. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  46. pub struct ChunkRequest {
  47. pub hash: blake3::Hash,
  48. }
  49. impl net::Message for ChunkRequest {
  50. fn name() -> &'static str {
  51. "dhtchunkrequest"
  52. }
  53. }
  54. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  55. pub struct ChunkReply {
  56. pub hash: blake3::Hash,
  57. pub data: Vec<u8>,
  58. }
  59. impl net::Message for ChunkReply {
  60. fn name() -> &'static str {
  61. "dhtchunkreply"
  62. }
  63. }
  64. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  65. pub struct FileRequest {
  66. pub hash: blake3::Hash,
  67. }
  68. impl net::Message for FileRequest {
  69. fn name() -> &'static str {
  70. "dhtfilerequest"
  71. }
  72. }
  73. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  74. pub struct FileReply {
  75. pub hash: blake3::Hash,
  76. pub chunks: Vec<blake3::Hash>,
  77. }
  78. impl net::Message for FileReply {
  79. fn name() -> &'static str {
  80. "dhtfilereply"
  81. }
  82. }
  83. impl ProtocolDht {
  84. pub async fn init(channel: ChannelPtr, p2p: P2pPtr, state: DhtdPtr) -> Result<ProtocolBasePtr> {
  85. let msg_subsystem = channel.get_message_subsystem();
  86. msg_subsystem.add_dispatch::<NetHashMapInsert<blake3::Hash, Vec<blake3::Hash>>>().await;
  87. msg_subsystem.add_dispatch::<NetHashMapRemove<blake3::Hash>>().await;
  88. msg_subsystem.add_dispatch::<ChunkRequest>().await;
  89. msg_subsystem.add_dispatch::<ChunkReply>().await;
  90. msg_subsystem.add_dispatch::<FileRequest>().await;
  91. msg_subsystem.add_dispatch::<FileReply>().await;
  92. let insert_sub = channel.subscribe_msg().await?;
  93. let remove_sub = channel.subscribe_msg().await?;
  94. let chunk_request_sub = channel.subscribe_msg().await?;
  95. let chunk_reply_sub = channel.subscribe_msg().await?;
  96. let file_request_sub = channel.subscribe_msg().await?;
  97. let file_reply_sub = channel.subscribe_msg().await?;
  98. Ok(Arc::new(Self {
  99. jobsman: ProtocolJobsManager::new("DHTProto", channel.clone()),
  100. channel,
  101. _p2p: p2p,
  102. state,
  103. insert_sub,
  104. remove_sub,
  105. chunk_request_sub,
  106. chunk_reply_sub,
  107. file_request_sub,
  108. file_reply_sub,
  109. }))
  110. }
  111. async fn handle_insert(self: Arc<Self>) -> Result<()> {
  112. debug!("ProtocolDht::handle_insert START");
  113. loop {
  114. let Ok(msg) = self.insert_sub.receive().await else {
  115. continue
  116. };
  117. let mut state = self.state.write().await;
  118. if !state.routing_table.contains_key(&msg.k) {
  119. state.routing_table.insert(msg.k, HashSet::new());
  120. }
  121. let hashset = state.routing_table.get_mut(&msg.k).unwrap();
  122. hashset.insert(self.channel.address());
  123. }
  124. }
  125. async fn handle_remove(self: Arc<Self>) -> Result<()> {
  126. debug!("ProtocolDht::handle_remove START");
  127. loop {
  128. let Ok(msg) = self.remove_sub.receive().await else {
  129. continue
  130. };
  131. let mut state = self.state.write().await;
  132. if !state.routing_table.contains_key(&msg.k) {
  133. continue
  134. }
  135. let hashset = state.routing_table.get_mut(&msg.k).unwrap();
  136. hashset.remove(&self.channel.address());
  137. }
  138. }
  139. async fn handle_chunk_request(self: Arc<Self>) -> Result<()> {
  140. debug!("ProtocolDht::handle_chunk_request START");
  141. loop {
  142. let Ok(msg) = self.chunk_request_sub.receive().await else {
  143. continue
  144. };
  145. println!("{:?}", msg);
  146. }
  147. }
  148. async fn handle_chunk_reply(self: Arc<Self>) -> Result<()> {
  149. debug!("ProtocolDht::handle_chunk_reply START");
  150. loop {
  151. let Ok(msg) = self.chunk_reply_sub.receive().await else {
  152. continue
  153. };
  154. println!("{:?}", msg);
  155. }
  156. }
  157. async fn handle_file_request(self: Arc<Self>) -> Result<()> {
  158. debug!("ProtocolDht::handle_file_request START");
  159. loop {
  160. let Ok(msg) = self.file_request_sub.receive().await else {
  161. continue
  162. };
  163. println!("{:?}", msg);
  164. }
  165. }
  166. async fn handle_file_reply(self: Arc<Self>) -> Result<()> {
  167. debug!("ProtocolDht::handle_file_reply START");
  168. loop {
  169. let Ok(msg) = self.file_reply_sub.receive().await else {
  170. continue
  171. };
  172. println!("{:?}", msg);
  173. }
  174. }
  175. }
  176. #[async_trait]
  177. impl ProtocolBase for ProtocolDht {
  178. async fn start(self: Arc<Self>, ex: Arc<Executor<'_>>) -> Result<()> {
  179. debug!("ProtocolDht::start()");
  180. self.jobsman.clone().start(ex.clone());
  181. self.jobsman.clone().spawn(self.clone().handle_insert(), ex.clone()).await;
  182. self.jobsman.clone().spawn(self.clone().handle_remove(), ex.clone()).await;
  183. self.jobsman.clone().spawn(self.clone().handle_chunk_request(), ex.clone()).await;
  184. self.jobsman.clone().spawn(self.clone().handle_chunk_reply(), ex.clone()).await;
  185. self.jobsman.clone().spawn(self.clone().handle_file_request(), ex.clone()).await;
  186. self.jobsman.clone().spawn(self.clone().handle_file_reply(), ex.clone()).await;
  187. Ok(())
  188. }
  189. fn name(&self) -> &'static str {
  190. "ProtoDHT"
  191. }
  192. }