protocol_event.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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, info};
  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 = 3;
  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. #[derive(Debug)]
  88. pub struct UnreadEvents {
  89. pub events: HashMap<EventId, Event>,
  90. }
  91. impl UnreadEvents {
  92. pub fn new() -> UnreadEventsPtr {
  93. Arc::new(Mutex::new(Self { events: HashMap::new() }))
  94. }
  95. fn contains(&self, key: &EventId) -> bool {
  96. self.events.contains_key(key)
  97. }
  98. fn get(&self, key: &EventId) -> Option<Event> {
  99. self.events.get(key).cloned()
  100. }
  101. // Increase the read_confirms for an event, if it has exceeded the MAX_CONFIRM
  102. // then remove it from the hash_map and return Some(event), otherwise return None
  103. fn inc_read_confirms(&mut self, key: &EventId) -> Option<Event> {
  104. let mut result = None;
  105. if let Some(event) = self.events.get_mut(key) {
  106. event.read_confirms += 1;
  107. if event.read_confirms >= MAX_CONFIRM {
  108. info!("max confirm reached");
  109. result = Some(event.clone())
  110. }
  111. }
  112. if result.is_some() {
  113. self.events.remove(key);
  114. }
  115. result
  116. }
  117. pub fn insert(&mut self, event: &Event) {
  118. // prune expired events
  119. let mut prune_ids = vec![];
  120. for (id, e) in self.events.iter() {
  121. if e.timestamp + (UNREAD_EVENT_EXPIRE_TIME * 1000) < get_current_time() {
  122. prune_ids.push(*id);
  123. }
  124. }
  125. for id in prune_ids {
  126. self.events.remove(&id);
  127. }
  128. self.events.insert(event.hash(), event.clone());
  129. }
  130. }
  131. pub struct ProtocolEvent {
  132. jobsman: net::ProtocolJobsManagerPtr,
  133. event_sub: net::MessageSubscription<Event>,
  134. inv_sub: net::MessageSubscription<Inv>,
  135. getdata_sub: net::MessageSubscription<GetData>,
  136. syncevent_sub: net::MessageSubscription<SyncEvent>,
  137. p2p: net::P2pPtr,
  138. channel: net::ChannelPtr,
  139. model: ModelPtr,
  140. seen_event: SeenPtr<EventId>,
  141. seen_inv: SeenPtr<InvId>,
  142. unread_events: UnreadEventsPtr,
  143. }
  144. impl ProtocolEvent {
  145. pub async fn init(
  146. channel: net::ChannelPtr,
  147. p2p: net::P2pPtr,
  148. model: ModelPtr,
  149. seen_event: SeenPtr<EventId>,
  150. seen_inv: SeenPtr<InvId>,
  151. unread_events: UnreadEventsPtr,
  152. ) -> net::ProtocolBasePtr {
  153. let message_subsytem = channel.get_message_subsystem();
  154. message_subsytem.add_dispatch::<Event>().await;
  155. message_subsytem.add_dispatch::<Inv>().await;
  156. message_subsytem.add_dispatch::<GetData>().await;
  157. message_subsytem.add_dispatch::<SyncEvent>().await;
  158. let event_sub =
  159. channel.clone().subscribe_msg::<Event>().await.expect("Missing Event dispatcher!");
  160. let inv_sub = channel.subscribe_msg::<Inv>().await.expect("Missing Inv dispatcher!");
  161. let getdata_sub =
  162. channel.clone().subscribe_msg::<GetData>().await.expect("Missing GetData dispatcher!");
  163. let syncevent_sub = channel
  164. .clone()
  165. .subscribe_msg::<SyncEvent>()
  166. .await
  167. .expect("Missing SyncEvent dispatcher!");
  168. Arc::new(Self {
  169. jobsman: net::ProtocolJobsManager::new("ProtocolEvent", channel.clone()),
  170. event_sub,
  171. inv_sub,
  172. getdata_sub,
  173. syncevent_sub,
  174. p2p,
  175. channel,
  176. model,
  177. seen_event,
  178. seen_inv,
  179. unread_events,
  180. })
  181. }
  182. async fn handle_receive_event(self: Arc<Self>) -> Result<()> {
  183. debug!(target: "ircd", "ProtocolEvent::handle_receive_event() [START]");
  184. let exclude_list = vec![self.channel.address()];
  185. loop {
  186. let event = self.event_sub.receive().await?;
  187. let mut event = (*event).to_owned();
  188. // This could be better
  189. if !self.seen_event.push(&event.hash()).await {
  190. continue
  191. }
  192. event.read_confirms += 1;
  193. // if event.read_confirms >= MAX_CONFIRM {
  194. // self.new_event(&event).await?;
  195. // } else {
  196. info!("add to unread_events: {:?}", event);
  197. self.unread_events.lock().await.insert(&event);
  198. self.send_inv(&event).await?;
  199. // }
  200. // Broadcast the msg
  201. self.p2p.broadcast_with_exclude(event, &exclude_list).await?;
  202. }
  203. }
  204. async fn handle_receive_inv(self: Arc<Self>) -> Result<()> {
  205. debug!(target: "ircd", "ProtocolEvent::handle_receive_inv() [START]");
  206. let exclude_list = vec![self.channel.address()];
  207. loop {
  208. let inv = self.inv_sub.receive().await?;
  209. let inv = (*inv).to_owned();
  210. // info!("invs: {}", inv.invs.iter().len());
  211. let the_inv = inv.invs[0].clone();
  212. // for inv in inv.invs.iter() {
  213. if !self.seen_inv.push(&the_inv.id).await {
  214. continue
  215. }
  216. info!("received inv: id: {}", the_inv.id);
  217. {
  218. let mut unread_events = self.unread_events.lock().await;
  219. if !unread_events.contains(&the_inv.hash) &&
  220. self.model.lock().await.get_event(&the_inv.hash).is_none()
  221. {
  222. info!("send_getdata");
  223. self.send_getdata(vec![the_inv.hash]).await?;
  224. } else if let Some(event) = unread_events.inc_read_confirms(&the_inv.hash) {
  225. info!("new_event() in handle_receive_inv");
  226. self.new_event(&event).await?;
  227. }
  228. info!("unread events: {:?}", unread_events);
  229. }
  230. // }
  231. // Broadcast the inv msg
  232. self.p2p.broadcast_with_exclude(inv, &exclude_list).await?;
  233. }
  234. }
  235. async fn handle_receive_getdata(self: Arc<Self>) -> Result<()> {
  236. debug!(target: "ircd", "ProtocolEvent::handle_receive_getdata() [START]");
  237. loop {
  238. let getdata = self.getdata_sub.receive().await?;
  239. let events = (*getdata).to_owned().events;
  240. // info!("received getdata()");
  241. for event_id in events {
  242. // info!("requesting event with id: {:?}", event_id);
  243. let unread_event = self.unread_events.lock().await.get(&event_id);
  244. if let Some(event) = unread_event {
  245. self.channel.send(event).await?;
  246. // info!("[unread_events] send event");
  247. continue
  248. }
  249. let model_event = self.model.lock().await.get_event(&event_id);
  250. if let Some(event) = model_event {
  251. // info!("[model] send event");
  252. self.channel.send(event).await?;
  253. }
  254. }
  255. }
  256. }
  257. async fn handle_receive_syncevent(self: Arc<Self>) -> Result<()> {
  258. debug!(target: "ircd", "ProtocolEvent::handle_receive_syncevent() [START]");
  259. loop {
  260. let syncevent = self.syncevent_sub.receive().await?;
  261. let model = self.model.lock().await;
  262. let leaves = model.find_leaves();
  263. if leaves == syncevent.leaves {
  264. continue
  265. }
  266. for leaf in syncevent.leaves.iter() {
  267. if leaves.contains(leaf) {
  268. continue
  269. }
  270. let children = model.get_event_children(leaf);
  271. for child in children {
  272. self.channel.send(child).await?;
  273. }
  274. }
  275. }
  276. }
  277. // every 2 seconds send a SyncEvent msg
  278. async fn send_sync_hash_loop(self: Arc<Self>) -> Result<()> {
  279. loop {
  280. sleep(2).await;
  281. let leaves = self.model.lock().await.find_leaves();
  282. self.channel.send(SyncEvent { leaves }).await?;
  283. }
  284. }
  285. async fn new_event(&self, event: &Event) -> Result<()> {
  286. let mut model = self.model.lock().await;
  287. if model.is_orphan(event) {
  288. info!("orphan -> send_getdata()");
  289. self.send_getdata(vec![event.hash()]).await?;
  290. } else {
  291. info!("not orphan -> add()");
  292. model.add(event.clone()).await;
  293. }
  294. Ok(())
  295. }
  296. async fn send_inv(&self, event: &Event) -> Result<()> {
  297. let id = OsRng.next_u64();
  298. info!("send_inv() with id: {id}");
  299. // let exclude_list = vec![self.channel.address()];
  300. self.p2p.broadcast(Inv { invs: vec![InvItem { id, hash: event.hash() }] }).await?;
  301. // self.p2p
  302. // .broadcast_with_exclude(
  303. // Inv { invs: vec![InvItem { id, hash: event.hash() }] },
  304. // &exclude_list,
  305. // )
  306. // .await?;
  307. Ok(())
  308. }
  309. async fn send_getdata(&self, events: Vec<EventId>) -> Result<()> {
  310. self.channel.send(GetData { events }).await?;
  311. Ok(())
  312. }
  313. }
  314. #[async_trait]
  315. impl net::ProtocolBase for ProtocolEvent {
  316. async fn start(self: Arc<Self>, executor: Arc<smol::Executor<'_>>) -> Result<()> {
  317. debug!(target: "ircd", "ProtocolEvent::start() [START]");
  318. self.jobsman.clone().start(executor.clone());
  319. self.jobsman.clone().spawn(self.clone().handle_receive_event(), executor.clone()).await;
  320. self.jobsman.clone().spawn(self.clone().handle_receive_inv(), executor.clone()).await;
  321. self.jobsman.clone().spawn(self.clone().handle_receive_getdata(), executor.clone()).await;
  322. self.jobsman.clone().spawn(self.clone().handle_receive_syncevent(), executor.clone()).await;
  323. self.jobsman.clone().spawn(self.clone().send_sync_hash_loop(), executor.clone()).await;
  324. debug!(target: "ircd", "ProtocolEvent::start() [END]");
  325. Ok(())
  326. }
  327. fn name(&self) -> &'static str {
  328. "ProtocolEvent"
  329. }
  330. }
  331. impl net::Message for Event {
  332. fn name() -> &'static str {
  333. "event"
  334. }
  335. }
  336. impl net::Message for Inv {
  337. fn name() -> &'static str {
  338. "inv"
  339. }
  340. }
  341. impl net::Message for SyncEvent {
  342. fn name() -> &'static str {
  343. "syncevent"
  344. }
  345. }
  346. impl net::Message for GetData {
  347. fn name() -> &'static str {
  348. "getdata"
  349. }
  350. }