protocol_event.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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::{HashMap, VecDeque};
  19. use async_std::sync::{Arc, Mutex};
  20. use async_trait::async_trait;
  21. use darkfi_serial::{SerialDecodable, SerialEncodable};
  22. use log::debug;
  23. use rand::{rngs::OsRng, RngCore};
  24. use darkfi::{net, util::async_util::sleep, Result};
  25. use crate::{
  26. model::{Event, EventId, ModelPtr},
  27. settings::get_current_time,
  28. };
  29. const UNREAD_EVENT_EXPIRE_TIME: u64 = 3600; // in seconds
  30. const SIZE_OF_SEEN_BUFFER: usize = 65536;
  31. const MAX_CONFIRM: u8 = 4;
  32. #[derive(Clone)]
  33. struct RingBuffer<T> {
  34. pub items: VecDeque<T>,
  35. }
  36. impl<T: Eq + PartialEq + Clone> RingBuffer<T> {
  37. pub fn new(capacity: usize) -> Self {
  38. let items = VecDeque::with_capacity(capacity);
  39. Self { items }
  40. }
  41. pub fn push(&mut self, val: T) {
  42. if self.items.len() == self.items.capacity() {
  43. self.items.pop_front();
  44. }
  45. self.items.push_back(val);
  46. }
  47. pub fn contains(&self, val: &T) -> bool {
  48. self.items.contains(val)
  49. }
  50. }
  51. type InvId = u64;
  52. #[derive(SerialEncodable, SerialDecodable, Clone, Debug, PartialEq, Eq, Hash)]
  53. struct InvItem {
  54. id: InvId,
  55. hash: EventId,
  56. }
  57. #[derive(SerialDecodable, SerialEncodable, Clone, Debug)]
  58. struct Inv {
  59. invs: Vec<InvItem>,
  60. }
  61. #[derive(SerialDecodable, SerialEncodable, Clone, Debug)]
  62. struct SyncEvent {
  63. leaves: Vec<EventId>,
  64. }
  65. #[derive(SerialDecodable, SerialEncodable, Clone, Debug)]
  66. struct GetData {
  67. events: Vec<EventId>,
  68. }
  69. pub type SeenPtr<T> = Arc<Seen<T>>;
  70. pub struct Seen<T> {
  71. seen: Mutex<RingBuffer<T>>,
  72. }
  73. impl<T: Eq + PartialEq + Clone> Seen<T> {
  74. pub fn new() -> SeenPtr<T> {
  75. Arc::new(Self { seen: Mutex::new(RingBuffer::new(SIZE_OF_SEEN_BUFFER)) })
  76. }
  77. pub async fn push(&self, item: &T) -> bool {
  78. let seen = &mut self.seen.lock().await;
  79. if !seen.contains(item) {
  80. seen.push(item.clone());
  81. return true
  82. }
  83. false
  84. }
  85. }
  86. pub type UnreadEventsPtr = Arc<Mutex<UnreadEvents>>;
  87. pub struct UnreadEvents {
  88. events: HashMap<EventId, Event>,
  89. }
  90. impl UnreadEvents {
  91. pub fn new() -> UnreadEventsPtr {
  92. Arc::new(Mutex::new(Self { events: HashMap::new() }))
  93. }
  94. fn contains(&self, key: &EventId) -> bool {
  95. self.events.contains_key(key)
  96. }
  97. fn get(&self, key: &EventId) -> Option<Event> {
  98. self.events.get(key).cloned()
  99. }
  100. // Increase the read_confirms for an event, if it has exceeded the MAX_CONFIRM
  101. // then remove it from the hash_map and return Some(event), otherwise return None
  102. fn inc_read_confirms(&mut self, key: &EventId) -> Option<Event> {
  103. let mut result = None;
  104. if let Some(event) = self.events.get_mut(key) {
  105. event.read_confirms += 1;
  106. if event.read_confirms >= MAX_CONFIRM {
  107. result = Some(event.clone())
  108. }
  109. }
  110. if result.is_some() {
  111. self.events.remove(key);
  112. }
  113. result
  114. }
  115. fn insert(&mut self, event: &Event) {
  116. // prune expired events
  117. let mut prune_ids = vec![];
  118. for (id, e) in self.events.iter() {
  119. if e.timestamp + (UNREAD_EVENT_EXPIRE_TIME * 1000) < get_current_time() {
  120. prune_ids.push(*id);
  121. }
  122. }
  123. for id in prune_ids {
  124. self.events.remove(&id);
  125. }
  126. self.events.insert(event.hash(), event.clone());
  127. }
  128. }
  129. pub struct ProtocolEvent {
  130. jobsman: net::ProtocolJobsManagerPtr,
  131. event_sub: net::MessageSubscription<Event>,
  132. inv_sub: net::MessageSubscription<Inv>,
  133. getdata_sub: net::MessageSubscription<GetData>,
  134. syncevent_sub: net::MessageSubscription<SyncEvent>,
  135. p2p: net::P2pPtr,
  136. channel: net::ChannelPtr,
  137. model: ModelPtr,
  138. seen_event: SeenPtr<EventId>,
  139. seen_inv: SeenPtr<InvId>,
  140. unread_events: UnreadEventsPtr,
  141. }
  142. impl ProtocolEvent {
  143. pub async fn init(
  144. channel: net::ChannelPtr,
  145. p2p: net::P2pPtr,
  146. model: ModelPtr,
  147. seen_event: SeenPtr<EventId>,
  148. seen_inv: SeenPtr<InvId>,
  149. unread_events: UnreadEventsPtr,
  150. ) -> net::ProtocolBasePtr {
  151. let message_subsytem = channel.get_message_subsystem();
  152. message_subsytem.add_dispatch::<Event>().await;
  153. message_subsytem.add_dispatch::<Inv>().await;
  154. message_subsytem.add_dispatch::<GetData>().await;
  155. message_subsytem.add_dispatch::<SyncEvent>().await;
  156. let event_sub =
  157. channel.clone().subscribe_msg::<Event>().await.expect("Missing Event dispatcher!");
  158. let inv_sub = channel.subscribe_msg::<Inv>().await.expect("Missing Inv dispatcher!");
  159. let getdata_sub =
  160. channel.clone().subscribe_msg::<GetData>().await.expect("Missing GetData dispatcher!");
  161. let syncevent_sub = channel
  162. .clone()
  163. .subscribe_msg::<SyncEvent>()
  164. .await
  165. .expect("Missing SyncEvent dispatcher!");
  166. Arc::new(Self {
  167. jobsman: net::ProtocolJobsManager::new("ProtocolEvent", channel.clone()),
  168. event_sub,
  169. inv_sub,
  170. getdata_sub,
  171. syncevent_sub,
  172. p2p,
  173. channel,
  174. model,
  175. seen_event,
  176. seen_inv,
  177. unread_events,
  178. })
  179. }
  180. async fn handle_receive_event(self: Arc<Self>) -> Result<()> {
  181. debug!(target: "ircd", "ProtocolEvent::handle_receive_event() [START]");
  182. let exclude_list = vec![self.channel.address()];
  183. loop {
  184. let event = self.event_sub.receive().await?;
  185. let mut event = (*event).to_owned();
  186. if !self.seen_event.push(&event.hash()).await {
  187. continue
  188. }
  189. event.read_confirms += 1;
  190. if event.read_confirms >= MAX_CONFIRM {
  191. self.new_event(&event).await?;
  192. } else {
  193. self.unread_events.lock().await.insert(&event);
  194. self.send_inv(&event).await?;
  195. }
  196. // Broadcast the msg
  197. self.p2p.broadcast_with_exclude(event, &exclude_list).await?;
  198. }
  199. }
  200. async fn handle_receive_inv(self: Arc<Self>) -> Result<()> {
  201. debug!(target: "ircd", "ProtocolEvent::handle_receive_inv() [START]");
  202. let exclude_list = vec![self.channel.address()];
  203. loop {
  204. let inv = self.inv_sub.receive().await?;
  205. let inv = (*inv).to_owned();
  206. for inv in inv.invs.iter() {
  207. if !self.seen_inv.push(&inv.id).await {
  208. continue
  209. }
  210. {
  211. let mut unread_events = self.unread_events.lock().await;
  212. if !unread_events.contains(&inv.hash) {
  213. self.send_getdata(vec![inv.hash]).await?;
  214. } else if let Some(event) = unread_events.inc_read_confirms(&inv.hash) {
  215. self.new_event(&event).await?;
  216. }
  217. }
  218. }
  219. // Broadcast the inv msg
  220. self.p2p.broadcast_with_exclude(inv, &exclude_list).await?;
  221. }
  222. }
  223. async fn handle_receive_getdata(self: Arc<Self>) -> Result<()> {
  224. debug!(target: "ircd", "ProtocolEvent::handle_receive_getdata() [START]");
  225. loop {
  226. let getdata = self.getdata_sub.receive().await?;
  227. let events = (*getdata).to_owned().events;
  228. for event_id in events {
  229. let unread_event = self.unread_events.lock().await.get(&event_id);
  230. if let Some(event) = unread_event {
  231. self.channel.send(event).await?;
  232. continue
  233. }
  234. let model_event = self.model.lock().await.get_event(&event_id);
  235. if let Some(event) = model_event {
  236. self.channel.send(event).await?;
  237. }
  238. }
  239. }
  240. }
  241. async fn handle_receive_syncevent(self: Arc<Self>) -> Result<()> {
  242. debug!(target: "ircd", "ProtocolEvent::handle_receive_syncevent() [START]");
  243. loop {
  244. let syncevent = self.syncevent_sub.receive().await?;
  245. let model = self.model.lock().await;
  246. let leaves = model.find_leaves();
  247. if leaves == syncevent.leaves {
  248. continue
  249. }
  250. for leaf in syncevent.leaves.iter() {
  251. if leaves.contains(leaf) {
  252. continue
  253. }
  254. let children = model.get_event_children(leaf);
  255. for child in children {
  256. self.channel.send(child).await?;
  257. }
  258. }
  259. }
  260. }
  261. // every 2 seconds send a SyncEvent msg
  262. async fn send_sync_hash_loop(self: Arc<Self>) -> Result<()> {
  263. loop {
  264. sleep(2).await;
  265. let leaves = self.model.lock().await.find_leaves();
  266. self.channel.send(SyncEvent { leaves }).await?;
  267. }
  268. }
  269. async fn new_event(&self, event: &Event) -> Result<()> {
  270. let mut model = self.model.lock().await;
  271. if model.is_orphan(event) {
  272. self.send_getdata(vec![event.hash()]).await?;
  273. } else {
  274. model.add(event.clone());
  275. }
  276. Ok(())
  277. }
  278. async fn send_inv(&self, event: &Event) -> Result<()> {
  279. let id = OsRng.next_u64();
  280. self.p2p.broadcast(Inv { invs: vec![InvItem { id, hash: event.hash() }] }).await?;
  281. Ok(())
  282. }
  283. async fn send_getdata(&self, events: Vec<EventId>) -> Result<()> {
  284. self.channel.send(GetData { events }).await?;
  285. Ok(())
  286. }
  287. }
  288. #[async_trait]
  289. impl net::ProtocolBase for ProtocolEvent {
  290. async fn start(self: Arc<Self>, executor: Arc<smol::Executor<'_>>) -> Result<()> {
  291. debug!(target: "ircd", "ProtocolEvent::start() [START]");
  292. self.jobsman.clone().start(executor.clone());
  293. self.jobsman.clone().spawn(self.clone().handle_receive_event(), executor.clone()).await;
  294. self.jobsman.clone().spawn(self.clone().handle_receive_inv(), executor.clone()).await;
  295. self.jobsman.clone().spawn(self.clone().handle_receive_getdata(), executor.clone()).await;
  296. self.jobsman.clone().spawn(self.clone().handle_receive_syncevent(), executor.clone()).await;
  297. self.jobsman.clone().spawn(self.clone().send_sync_hash_loop(), executor.clone()).await;
  298. debug!(target: "ircd", "ProtocolEvent::start() [END]");
  299. Ok(())
  300. }
  301. fn name(&self) -> &'static str {
  302. "ProtocolEvent"
  303. }
  304. }
  305. impl net::Message for Event {
  306. fn name() -> &'static str {
  307. "event"
  308. }
  309. }
  310. impl net::Message for Inv {
  311. fn name() -> &'static str {
  312. "inv"
  313. }
  314. }
  315. impl net::Message for SyncEvent {
  316. fn name() -> &'static str {
  317. "syncevent"
  318. }
  319. }
  320. impl net::Message for GetData {
  321. fn name() -> &'static str {
  322. "getdata"
  323. }
  324. }