message_publisher.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 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::{any::Any, collections::HashMap, sync::Arc, time::Duration};
  19. use async_trait::async_trait;
  20. use futures::stream::{FuturesUnordered, StreamExt};
  21. use rand::{rngs::OsRng, Rng};
  22. use smol::{io::AsyncReadExt, lock::Mutex};
  23. use tracing::{debug, error};
  24. use super::message::Message;
  25. use crate::{
  26. net::{metering::MeteringQueue, transport::PtStream},
  27. system::{msleep, timeout::timeout},
  28. Error, Result,
  29. };
  30. use darkfi_serial::{AsyncDecodable, VarInt};
  31. /// 64-bit identifier for message subscription.
  32. pub type MessageSubscriptionId = u64;
  33. type MessageResult<M> = Result<Arc<M>>;
  34. /// Dispatcher subscriptions HashMap type.
  35. type DispatcherSubscriptionsMap<M> =
  36. Mutex<HashMap<MessageSubscriptionId, smol::channel::Sender<(MessageResult<M>, Option<u64>)>>>;
  37. /// A dispatcher that is unique to every [`Message`].
  38. ///
  39. /// Maintains a list of subscriptions to a unique Message
  40. /// type and handles sending messages across these
  41. /// subscriptions.
  42. ///
  43. /// Additionally, holds a `MeteringQueue` using the
  44. /// [`Message`] configuration to perform rate limiting
  45. /// of propagation towards the subscriptions.
  46. #[derive(Debug)]
  47. struct MessageDispatcher<M: Message> {
  48. subs: DispatcherSubscriptionsMap<M>,
  49. metering_queue: Mutex<MeteringQueue>,
  50. }
  51. impl<M: Message> MessageDispatcher<M> {
  52. /// Create a new message dispatcher
  53. fn new() -> Self {
  54. Self {
  55. subs: Mutex::new(HashMap::new()),
  56. metering_queue: Mutex::new(MeteringQueue::new(M::METERING_CONFIGURATION)),
  57. }
  58. }
  59. /// Create a random ID.
  60. fn random_id() -> MessageSubscriptionId {
  61. OsRng.gen()
  62. }
  63. /// Subscribe to a channel.
  64. /// Assigns a new ID and adds it to the list of subscriptions.
  65. pub async fn subscribe(self: Arc<Self>) -> MessageSubscription<M> {
  66. let (sender, recv_queue) = smol::channel::unbounded();
  67. // Guard against overwriting
  68. let mut id = Self::random_id();
  69. let mut subs = self.subs.lock().await;
  70. loop {
  71. if subs.contains_key(&id) {
  72. id = Self::random_id();
  73. continue
  74. }
  75. subs.insert(id, sender);
  76. break
  77. }
  78. drop(subs);
  79. MessageSubscription { id, recv_queue, parent: self }
  80. }
  81. /// Unsubscribe from a channel.
  82. /// Removes the associated ID from the subscriber list.
  83. async fn unsubscribe(&self, sub_id: MessageSubscriptionId) {
  84. self.subs.lock().await.remove(&sub_id);
  85. }
  86. /// Private function to concurrently transmit a message to all subscriber channels.
  87. /// Automatically clear all inactive channels. Strictly used internally.
  88. async fn _trigger_all(&self, message: MessageResult<M>) {
  89. let mut subs = self.subs.lock().await;
  90. let msg_result_type = if message.is_ok() { "Ok" } else { "Err" };
  91. debug!(
  92. target: "net::message_publisher::_trigger_all", "START msg={msg_result_type}({}), subs={}",
  93. M::NAME, subs.len()
  94. );
  95. // Insert metering information and grab potential sleep time
  96. let mut queue = self.metering_queue.lock().await;
  97. queue.push(&M::METERING_SCORE);
  98. let sleep_time = queue.sleep_time();
  99. drop(queue);
  100. let mut futures = FuturesUnordered::new();
  101. let mut garbage_ids = vec![];
  102. // Prep the futures for concurrent execution
  103. for (sub_id, sub) in &*subs {
  104. let sub_id = *sub_id;
  105. let sub = sub.clone();
  106. let message = message.clone();
  107. futures.push(async move {
  108. match sub.send((message, sleep_time)).await {
  109. Ok(res) => Ok((sub_id, res)),
  110. Err(err) => Err((sub_id, err)),
  111. }
  112. });
  113. }
  114. // Start polling
  115. while let Some(r) = futures.next().await {
  116. if let Err((sub_id, _err)) = r {
  117. garbage_ids.push(sub_id);
  118. }
  119. }
  120. // Garbage cleanup
  121. for sub_id in garbage_ids {
  122. subs.remove(&sub_id);
  123. }
  124. debug!(
  125. target: "net::message_publisher::_trigger_all", "END msg={msg_result_type}({}), subs={}",
  126. M::NAME, subs.len(),
  127. );
  128. }
  129. }
  130. /// Handles message subscriptions through a subscription ID and
  131. /// a receiver channel.
  132. #[derive(Debug)]
  133. pub struct MessageSubscription<M: Message> {
  134. id: MessageSubscriptionId,
  135. recv_queue: smol::channel::Receiver<(MessageResult<M>, Option<u64>)>,
  136. parent: Arc<MessageDispatcher<M>>,
  137. }
  138. impl<M: Message> MessageSubscription<M> {
  139. /// Start receiving messages.
  140. /// Sender also provides with a sleep time,
  141. /// in case rate limit has started.
  142. pub async fn receive(&self) -> MessageResult<M> {
  143. let (message, sleep_time) = match self.recv_queue.recv().await {
  144. Ok(pair) => pair,
  145. Err(e) => panic!("MessageSubscription::receive(): recv_queue failed! {e}"),
  146. };
  147. // Check if we need to sleep
  148. if message.is_ok() {
  149. if let Some(sleep_time) = sleep_time {
  150. msleep(sleep_time).await;
  151. }
  152. }
  153. message
  154. }
  155. /// Start receiving messages with timeout.
  156. pub async fn receive_with_timeout(&self, seconds: u64) -> MessageResult<M> {
  157. let dur = Duration::from_secs(seconds);
  158. let Ok(res) = timeout(dur, self.recv_queue.recv()).await else {
  159. return Err(Error::ConnectTimeout)
  160. };
  161. let (message, sleep_time) = match res {
  162. Ok(pair) => pair,
  163. Err(e) => {
  164. panic!("MessageSubscription::receive_with_timeout(): recv_queue failed! {e}")
  165. }
  166. };
  167. // Check if we need to sleep
  168. if message.is_ok() {
  169. if let Some(sleep_time) = sleep_time {
  170. msleep(sleep_time).await;
  171. }
  172. }
  173. message
  174. }
  175. /// Cleans existing items from the receiver channel.
  176. pub async fn clean(&self) -> Result<()> {
  177. loop {
  178. match self.recv_queue.try_recv() {
  179. Ok(_) => continue,
  180. Err(smol::channel::TryRecvError::Empty) => return Ok(()),
  181. Err(e) => panic!("MessageSubscription::receive(): recv_queue failed! {e}"),
  182. }
  183. }
  184. }
  185. /// Unsubscribe from a message subscription. Must be called manually.
  186. pub async fn unsubscribe(&self) {
  187. self.parent.unsubscribe(self.id).await
  188. }
  189. }
  190. /// Generic interface for the message dispatcher.
  191. #[async_trait]
  192. trait MessageDispatcherInterface: Send + Sync {
  193. async fn trigger(
  194. &self,
  195. stream: &mut smol::io::ReadHalf<Box<dyn PtStream + 'static>>,
  196. ) -> Result<()>;
  197. async fn trigger_error(&self, err: Error);
  198. async fn metering_score(&self) -> u64;
  199. fn as_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync>;
  200. }
  201. /// Local implementation of the Message Dispatcher Interface
  202. #[async_trait]
  203. impl<M: Message> MessageDispatcherInterface for MessageDispatcher<M> {
  204. /// Internal function to deserialize data into a message type
  205. /// and dispatch it across subscriber channels. Reads directly
  206. /// from an inbound stream.
  207. ///
  208. /// We extract the message length from the stream and use `take()`
  209. /// to allocate an appropriately sized buffer as a basic DDOS protection.
  210. async fn trigger(
  211. &self,
  212. stream: &mut smol::io::ReadHalf<Box<dyn PtStream + 'static>>,
  213. ) -> Result<()> {
  214. // Parse message length
  215. let length = match VarInt::decode_async(stream).await {
  216. Ok(int) => int.0,
  217. Err(err) => {
  218. error!(
  219. target: "net::message_publisher::trigger",
  220. "Unable to decode VarInt. Dropping...: {err}"
  221. );
  222. return Err(Error::MessageInvalid)
  223. }
  224. };
  225. // Check the message length does not exceed set limit
  226. if M::MAX_BYTES > 0 && length > M::MAX_BYTES {
  227. error!(
  228. target: "net::message_publisher::trigger",
  229. "Message length ({length}) exceeds configured limit ({}). Dropping...",
  230. M::MAX_BYTES
  231. );
  232. return Err(Error::MessageInvalid)
  233. }
  234. // Deserialize stream into type
  235. let mut take = stream.take(length);
  236. let message = match M::decode_async(&mut take).await {
  237. Ok(payload) => Ok(Arc::new(payload)),
  238. Err(err) => {
  239. error!(
  240. target: "net::message_publisher::trigger",
  241. "Unable to decode data. Dropping...: {err}"
  242. );
  243. return Err(Error::MessageInvalid)
  244. }
  245. };
  246. // Send down the pipes
  247. self._trigger_all(message).await;
  248. Ok(())
  249. }
  250. /// Internal function that sends an error message to all subscriber channels.
  251. async fn trigger_error(&self, err: Error) {
  252. self._trigger_all(Err(err)).await;
  253. }
  254. /// Internal function to retrieve metering queue current total score,
  255. /// after prunning expired metering information.
  256. async fn metering_score(&self) -> u64 {
  257. let mut lock = self.metering_queue.lock().await;
  258. lock.clean();
  259. lock.total()
  260. }
  261. /// Converts to `Any` trait. Enables the dynamic modification of static types.
  262. fn as_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
  263. self
  264. }
  265. }
  266. /// Generic publish/subscribe class that maintains a list of dispatchers.
  267. ///
  268. /// Dispatchers transmit messages to subscribers and are specific to one
  269. /// message type.
  270. ///
  271. /// Additionally, holds a global metering limit, which is the sum of each
  272. /// dispatcher `MeteringQueue` threshold, to drop the connection if passed.
  273. #[derive(Default)]
  274. pub struct MessageSubsystem {
  275. dispatchers: Mutex<HashMap<&'static str, Arc<dyn MessageDispatcherInterface>>>,
  276. metering_limit: Mutex<u64>,
  277. }
  278. impl MessageSubsystem {
  279. /// Create a new message subsystem.
  280. pub fn new() -> Self {
  281. Self { dispatchers: Mutex::new(HashMap::new()), metering_limit: Mutex::new(0) }
  282. }
  283. /// Add a new dispatcher for specified [`Message`].
  284. pub async fn add_dispatch<M: Message>(&self) {
  285. // First lock the dispatchers
  286. let mut lock = self.dispatchers.lock().await;
  287. // Update the metering limit
  288. *self.metering_limit.lock().await += M::METERING_CONFIGURATION.threshold;
  289. // Insert the new dispatcher
  290. lock.insert(M::NAME, Arc::new(MessageDispatcher::<M>::new()));
  291. }
  292. /// Subscribes to a [`Message`]. Using the Message name, the method
  293. /// returns the associated `MessageDispatcher` from the list of
  294. /// dispatchers and calls `subscribe()`.
  295. pub async fn subscribe<M: Message>(&self) -> Result<MessageSubscription<M>> {
  296. let dispatcher = self.dispatchers.lock().await.get(M::NAME).cloned();
  297. let sub = match dispatcher {
  298. Some(dispatcher) => {
  299. let dispatcher: Arc<MessageDispatcher<M>> = dispatcher
  300. .as_any()
  301. .downcast::<MessageDispatcher<M>>()
  302. .expect("Multiple messages registered with different names");
  303. dispatcher.subscribe().await
  304. }
  305. None => {
  306. // Normal return failure here
  307. return Err(Error::NetworkOperationFailed)
  308. }
  309. };
  310. Ok(sub)
  311. }
  312. /// Transmits a payload to a dispatcher.
  313. /// Returns an error if the payload fails to transmit.
  314. pub async fn notify(
  315. &self,
  316. command: &str,
  317. reader: &mut smol::io::ReadHalf<Box<dyn PtStream + 'static>>,
  318. ) -> Result<()> {
  319. // Iterate over dispatchers and keep track of their current
  320. // metering score
  321. let mut found = false;
  322. let mut total_score = 0;
  323. for (name, dispatcher) in self.dispatchers.lock().await.iter() {
  324. // If dispatcher is the command one, trasmit the message
  325. if name == &command {
  326. dispatcher.trigger(reader).await?;
  327. found = true;
  328. }
  329. // Grab its total score
  330. total_score += dispatcher.metering_score().await;
  331. }
  332. // Check if dispatcher was found
  333. if !found {
  334. return Err(Error::MissingDispatcher)
  335. }
  336. // Check if we are over the global metering limit
  337. if total_score > *self.metering_limit.lock().await {
  338. return Err(Error::MeteringLimitExceeded)
  339. }
  340. Ok(())
  341. }
  342. /// Concurrently transmits an error message across dispatchers.
  343. pub async fn trigger_error(&self, err: Error) {
  344. let mut futures = FuturesUnordered::new();
  345. let dispatchers = self.dispatchers.lock().await;
  346. for dispatcher in dispatchers.values() {
  347. let dispatcher = dispatcher.clone();
  348. let error = err.clone();
  349. futures.push(async move { dispatcher.trigger_error(error).await });
  350. }
  351. drop(dispatchers);
  352. while let Some(_r) = futures.next().await {}
  353. }
  354. }