protocol_privmsg.rs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. use async_std::sync::Arc;
  2. use async_executor::Executor;
  3. use async_trait::async_trait;
  4. use chrono::Utc;
  5. use log::debug;
  6. use ripemd::{Digest, Ripemd160};
  7. use darkfi::{
  8. net,
  9. util::{
  10. serial::{SerialDecodable, SerialEncodable},
  11. sleep,
  12. },
  13. Result,
  14. };
  15. use crate::{
  16. buffers::{ArcPrivmsgsBuffer, SeenIds},
  17. Privmsg, UnreadMsgs,
  18. };
  19. const MAX_CONFIRM: u8 = 4;
  20. const SLEEP_TIME_FOR_RESEND: u64 = 1200;
  21. const UNREAD_MSG_EXPIRE_TIME: i64 = 259200;
  22. #[derive(SerialDecodable, SerialEncodable, Clone)]
  23. struct Inv {
  24. invs: Vec<InvObject>,
  25. }
  26. impl Inv {
  27. fn new(invs: Vec<InvObject>) -> Self {
  28. Self { invs }
  29. }
  30. }
  31. #[derive(SerialDecodable, SerialEncodable, Clone)]
  32. struct GetData {
  33. invs: Vec<InvObject>,
  34. }
  35. impl GetData {
  36. fn new(invs: Vec<InvObject>) -> Self {
  37. Self { invs }
  38. }
  39. }
  40. #[derive(SerialDecodable, SerialEncodable, Clone)]
  41. struct InvObject(String);
  42. pub struct ProtocolPrivmsg {
  43. jobsman: net::ProtocolJobsManagerPtr,
  44. notify: async_channel::Sender<Privmsg>,
  45. msg_sub: net::MessageSubscription<Privmsg>,
  46. inv_sub: net::MessageSubscription<Inv>,
  47. getdata_sub: net::MessageSubscription<GetData>,
  48. p2p: net::P2pPtr,
  49. msg_ids: SeenIds,
  50. msgs: ArcPrivmsgsBuffer,
  51. unread_msgs: UnreadMsgs,
  52. channel: net::ChannelPtr,
  53. }
  54. impl ProtocolPrivmsg {
  55. pub async fn init(
  56. channel: net::ChannelPtr,
  57. notify: async_channel::Sender<Privmsg>,
  58. p2p: net::P2pPtr,
  59. msg_ids: SeenIds,
  60. msgs: ArcPrivmsgsBuffer,
  61. unread_msgs: UnreadMsgs,
  62. ) -> net::ProtocolBasePtr {
  63. let message_subsytem = channel.get_message_subsystem();
  64. message_subsytem.add_dispatch::<Privmsg>().await;
  65. let msg_sub =
  66. channel.subscribe_msg::<Privmsg>().await.expect("Missing Privmsg dispatcher!");
  67. let inv_sub = channel.subscribe_msg::<Inv>().await.expect("Missing Inv dispatcher!");
  68. let getdata_sub =
  69. channel.subscribe_msg::<GetData>().await.expect("Missing Inv dispatcher!");
  70. Arc::new(Self {
  71. notify,
  72. msg_sub,
  73. inv_sub,
  74. jobsman: net::ProtocolJobsManager::new("ProtocolPrivmsg", channel.clone()),
  75. p2p,
  76. msg_ids,
  77. getdata_sub,
  78. msgs,
  79. unread_msgs,
  80. channel,
  81. })
  82. }
  83. async fn handle_receive_inv(self: Arc<Self>) -> Result<()> {
  84. debug!(target: "ircd", "ProtocolPrivmsg::handle_receive_inv() [START]");
  85. let exclude_list = vec![self.channel.address()];
  86. loop {
  87. let inv = self.inv_sub.receive().await?;
  88. let inv = (*inv).to_owned();
  89. let mut inv_requested = vec![];
  90. for inv_object in inv.invs.iter() {
  91. let mut msgs = self.unread_msgs.lock().await;
  92. if let Some(msg) = msgs.get_mut(&inv_object.0) {
  93. msg.read_confirms += 1;
  94. } else {
  95. inv_requested.push(inv_object.clone());
  96. }
  97. }
  98. if !inv_requested.is_empty() {
  99. self.channel.send(GetData::new(inv_requested)).await;
  100. }
  101. self.update_unread_msgs().await;
  102. }
  103. }
  104. async fn handle_receive_msg(self: Arc<Self>) -> Result<()> {
  105. debug!(target: "ircd", "ProtocolPrivmsg::handle_receive_msg() [START]");
  106. let exclude_list = vec![self.channel.address()];
  107. loop {
  108. let msg = self.msg_sub.receive().await?;
  109. let msg = (*msg).to_owned();
  110. let mut msg_ids = self.msg_ids.lock().await;
  111. if msg_ids.contains(&msg.id) {
  112. continue
  113. }
  114. msg_ids.push(msg.id);
  115. drop(msg_ids);
  116. if msg.read_confirms > MAX_CONFIRM {
  117. self.add_to_msgs(&msg).await?;
  118. } else {
  119. let hash = self.add_to_unread_msgs(&msg).await;
  120. self.channel.send(Inv::new(vec![InvObject(hash)])).await;
  121. }
  122. self.p2p.broadcast_with_exclude(msg, &exclude_list).await?;
  123. }
  124. }
  125. async fn handle_receive_getdata(self: Arc<Self>) -> Result<()> {
  126. debug!(target: "ircd", "ProtocolPrivmsg::handle_receive_getdata() [START]");
  127. let exclude_list = vec![self.channel.address()];
  128. loop {
  129. let getdata = self.getdata_sub.receive().await?;
  130. let getdata = (*getdata).to_owned();
  131. let msgs = self.unread_msgs.lock().await;
  132. for inv in getdata.invs {
  133. if let Some(msg) = msgs.get(&inv.0) {
  134. self.channel.send(msg.clone()).await?;
  135. }
  136. }
  137. }
  138. }
  139. async fn add_to_unread_msgs(&self, msg: &Privmsg) -> String {
  140. let mut msgs = self.unread_msgs.lock().await;
  141. let mut hasher = Ripemd160::new();
  142. hasher.update(msg.to_string());
  143. let key = hex::encode(hasher.finalize());
  144. msgs.insert(key.clone(), msg.clone());
  145. key
  146. }
  147. async fn update_unread_msgs(&self) -> Result<()> {
  148. let mut msgs = self.unread_msgs.lock().await;
  149. for (hash, msg) in msgs.clone() {
  150. if msg.timestamp + UNREAD_MSG_EXPIRE_TIME < Utc::now().timestamp() {
  151. msgs.remove(&hash);
  152. continue
  153. }
  154. if msg.read_confirms > MAX_CONFIRM {
  155. self.add_to_msgs(&msg).await?;
  156. msgs.remove(&hash);
  157. }
  158. }
  159. Ok(())
  160. }
  161. async fn add_to_msgs(&self, msg: &Privmsg) -> Result<()> {
  162. self.msgs.lock().await.push(msg);
  163. self.notify.send(msg.clone()).await?;
  164. Ok(())
  165. }
  166. async fn resend_loop(self: Arc<Self>) -> Result<()> {
  167. sleep(SLEEP_TIME_FOR_RESEND).await;
  168. self.update_unread_msgs().await?;
  169. for msg in self.unread_msgs.lock().await.values() {
  170. self.channel.send(msg.clone()).await?;
  171. }
  172. Ok(())
  173. }
  174. }
  175. #[async_trait]
  176. impl net::ProtocolBase for ProtocolPrivmsg {
  177. /// Starts ping-pong keep-alive messages exchange. Runs ping-pong in the
  178. /// protocol task manager, then queues the reply. Sends out a ping and
  179. /// waits for pong reply. Waits for ping and replies with a pong.
  180. async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
  181. // once a channel get started
  182. let msgs_buffer = self.msgs.lock().await;
  183. for m in msgs_buffer.iter() {
  184. self.channel.send(m.clone()).await?;
  185. }
  186. drop(msgs_buffer);
  187. debug!(target: "ircd", "ProtocolPrivmsg::start() [START]");
  188. self.jobsman.clone().start(executor.clone());
  189. self.jobsman.clone().spawn(self.clone().handle_receive_msg(), executor.clone()).await;
  190. self.jobsman.clone().spawn(self.clone().handle_receive_inv(), executor.clone()).await;
  191. self.jobsman.clone().spawn(self.clone().handle_receive_getdata(), executor.clone()).await;
  192. self.jobsman.clone().spawn(self.clone().resend_loop(), executor.clone()).await;
  193. debug!(target: "ircd", "ProtocolPrivmsg::start() [END]");
  194. Ok(())
  195. }
  196. fn name(&self) -> &'static str {
  197. "ProtocolPrivmsg"
  198. }
  199. }
  200. impl net::Message for Privmsg {
  201. fn name() -> &'static str {
  202. "privmsg"
  203. }
  204. }
  205. impl net::Message for Inv {
  206. fn name() -> &'static str {
  207. "inv"
  208. }
  209. }
  210. impl net::Message for GetData {
  211. fn name() -> &'static str {
  212. "getdata"
  213. }
  214. }