model.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2022 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::{cmp::Ordering, fmt};
  19. use async_std::sync::{Arc, Mutex};
  20. use darkfi_serial::{Encodable, SerialDecodable, SerialEncodable};
  21. use fxhash::FxHashMap;
  22. use ripemd::{Digest, Ripemd256};
  23. use crate::{
  24. events_queue::EventsQueuePtr,
  25. privmsg::{EventAction, PrivMsgEvent},
  26. settings::get_current_time,
  27. };
  28. pub type EventId = [u8; 32];
  29. const MAX_DEPTH: u32 = 300;
  30. const MAX_HEIGHT: u32 = 300;
  31. #[derive(SerialEncodable, SerialDecodable, Clone)]
  32. pub struct Event {
  33. previous_event_hash: EventId,
  34. action: EventAction,
  35. pub timestamp: u64,
  36. #[skip_serialize]
  37. pub read_confirms: u8,
  38. }
  39. impl Event {
  40. pub fn hash(&self) -> EventId {
  41. let mut bytes = Vec::new();
  42. self.encode(&mut bytes).expect("serialize failed!");
  43. let mut hasher = Ripemd256::new();
  44. hasher.update(bytes);
  45. let bytes = hasher.finalize().to_vec();
  46. let mut result = [0u8; 32];
  47. result.copy_from_slice(bytes.as_slice());
  48. result
  49. }
  50. }
  51. impl fmt::Debug for Event {
  52. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  53. match &self.action {
  54. EventAction::PrivMsg(event) => {
  55. write!(f, "PRIVMSG {}: {} ({})", event.nick, event.msg, self.timestamp)
  56. }
  57. }
  58. }
  59. }
  60. #[derive(Debug, Clone)]
  61. struct EventNode {
  62. // Only current root has this set to None
  63. parent: Option<EventId>,
  64. event: Event,
  65. children: Vec<EventId>,
  66. }
  67. pub type ModelPtr = Arc<Mutex<Model>>;
  68. pub struct Model {
  69. // This is periodically updated so we discard old nodes
  70. current_root: EventId,
  71. orphans: FxHashMap<EventId, Event>,
  72. event_map: FxHashMap<EventId, EventNode>,
  73. events_queue: EventsQueuePtr,
  74. }
  75. impl Model {
  76. pub fn new(events_queue: EventsQueuePtr) -> Self {
  77. let root_node = EventNode {
  78. parent: None,
  79. event: Event {
  80. previous_event_hash: [0u8; 32],
  81. action: EventAction::PrivMsg(PrivMsgEvent {
  82. nick: "root".to_string(),
  83. msg: "Let there be dark".to_string(),
  84. target: "root".to_string(),
  85. }),
  86. timestamp: get_current_time(),
  87. read_confirms: 0,
  88. },
  89. children: Vec::new(),
  90. };
  91. let root_node_id = root_node.event.hash();
  92. let mut event_map = FxHashMap::default();
  93. event_map.insert(root_node_id, root_node);
  94. Self { current_root: root_node_id, orphans: FxHashMap::default(), event_map, events_queue }
  95. }
  96. pub fn add(&mut self, event: Event) {
  97. self.orphans.insert(event.hash(), event);
  98. self.reorganize();
  99. }
  100. pub fn is_orphan(&self, event: &Event) -> bool {
  101. !self.event_map.contains_key(&event.previous_event_hash)
  102. }
  103. pub fn find_leaves(&self) -> Vec<EventId> {
  104. // collect the leaves in the tree
  105. let mut leaves = vec![];
  106. for (event_hash, node) in self.event_map.iter() {
  107. // check if the node is a leaf
  108. if node.children.is_empty() {
  109. leaves.push(*event_hash);
  110. }
  111. }
  112. leaves
  113. }
  114. pub fn get_event(&self, event: &EventId) -> Option<Event> {
  115. self.event_map.get(event).map(|en| en.event.clone())
  116. }
  117. pub fn get_event_children(&self, event: &EventId) -> Vec<Event> {
  118. let mut children = vec![];
  119. if let Some(ev) = self.event_map.get(event) {
  120. for child in ev.children.iter() {
  121. let child = self.event_map.get(child).unwrap();
  122. children.push(child.event.clone());
  123. }
  124. }
  125. children
  126. }
  127. fn reorganize(&mut self) {
  128. for (_, orphan) in std::mem::take(&mut self.orphans) {
  129. if self.is_orphan(&orphan) {
  130. // TODO should we remove orphan if it's too old
  131. continue
  132. }
  133. let prev_event = orphan.previous_event_hash;
  134. let node =
  135. EventNode { parent: Some(prev_event), event: orphan.clone(), children: Vec::new() };
  136. let node_hash = node.event.hash();
  137. let parent = self.event_map.get_mut(&prev_event).unwrap();
  138. parent.children.push(node_hash);
  139. self.event_map.insert(node_hash, node);
  140. // TODO dispatch to events_queue
  141. // to use events_queue here the add() and reorganize() functions should change to async
  142. // clean up the tree from old eventnodes
  143. self.prune_chains();
  144. self.update_root();
  145. }
  146. }
  147. fn prune_chains(&mut self) {
  148. let head = self.find_head();
  149. let leaves = self.find_leaves();
  150. // Reject events which attach to chains too low in the chain
  151. // At some point we ignore all events from old branches
  152. for leaf in leaves {
  153. // skip the head event
  154. if leaf == head {
  155. continue
  156. }
  157. let depth = self.diff_depth(leaf, head);
  158. if depth > MAX_DEPTH {
  159. self.remove_node(leaf);
  160. }
  161. }
  162. }
  163. fn update_root(&mut self) {
  164. let head = self.find_head();
  165. let leaves = self.find_leaves();
  166. // find the common ancestor for each leaf and the head event
  167. let mut ancestors = vec![];
  168. for leaf in leaves {
  169. if leaf == head {
  170. continue
  171. }
  172. let ancestor = self.find_ancestor(leaf, head);
  173. ancestors.push(ancestor);
  174. }
  175. // find the highest ancestor
  176. let highest_ancestor = ancestors
  177. .iter()
  178. .max_by(|&a, &b| self.find_depth(*a, &head).cmp(&self.find_depth(*b, &head)));
  179. // set the new root
  180. if let Some(ancestor) = highest_ancestor {
  181. // the ancestor must have at least height > MAX_HEIGHT
  182. let ancestor_height = self.find_height(&self.current_root, ancestor).unwrap();
  183. if ancestor_height < MAX_HEIGHT {
  184. return
  185. }
  186. // removing the parents of the new root node
  187. let mut root = self.event_map.get(&self.current_root).unwrap();
  188. loop {
  189. let root_hash = root.event.hash();
  190. if &root_hash == ancestor {
  191. break
  192. }
  193. let root_childs = &root.children;
  194. assert_eq!(root_childs.len(), 1);
  195. let child = *root_childs.first().unwrap();
  196. self.event_map.remove(&root_hash);
  197. root = self.event_map.get(&child).unwrap();
  198. }
  199. self.current_root = *ancestor;
  200. }
  201. }
  202. fn remove_node(&mut self, mut event_id: EventId) {
  203. loop {
  204. if !self.event_map.contains_key(&event_id) {
  205. break
  206. }
  207. let node = self.event_map.get(&event_id).unwrap().clone();
  208. self.event_map.remove(&event_id);
  209. let parent = self.event_map.get_mut(&node.parent.unwrap()).unwrap();
  210. let index = parent.children.iter().position(|&n| n == event_id).unwrap();
  211. parent.children.remove(index);
  212. if !parent.children.is_empty() {
  213. break
  214. }
  215. event_id = parent.event.hash();
  216. }
  217. }
  218. // find_head
  219. // -> recursively call itself
  220. // -> + 1 for every recursion, return self if no children
  221. // -> select max from returned values
  222. // Gets the lead node with the maximal number of events counting from root
  223. fn find_head(&self) -> EventId {
  224. self.find_longest_chain(&self.current_root, 0).0
  225. }
  226. fn find_longest_chain(&self, parent_node: &EventId, i: u32) -> (EventId, u32) {
  227. let children = &self.event_map.get(parent_node).unwrap().children;
  228. if children.is_empty() {
  229. return (*parent_node, i)
  230. }
  231. let mut current_max = 0;
  232. let mut current_node = None;
  233. for node in children.iter() {
  234. let (grandchild_node, grandchild_i) = self.find_longest_chain(node, i + 1);
  235. match &grandchild_i.cmp(&current_max) {
  236. Ordering::Greater => {
  237. current_max = grandchild_i;
  238. current_node = Some(grandchild_node);
  239. }
  240. Ordering::Equal => {
  241. // Break ties using the timestamp
  242. let grandchild_node_timestamp =
  243. self.event_map.get(&grandchild_node).unwrap().event.timestamp;
  244. let current_node_timestamp =
  245. self.event_map.get(&current_node.unwrap()).unwrap().event.timestamp;
  246. if grandchild_node_timestamp > current_node_timestamp {
  247. current_max = grandchild_i;
  248. current_node = Some(grandchild_node);
  249. }
  250. }
  251. Ordering::Less => {
  252. // Left a todo here, not sure if it should be handled
  253. todo!();
  254. }
  255. }
  256. }
  257. assert_ne!(current_max, 0);
  258. (current_node.expect("internal logic error"), current_max)
  259. }
  260. fn find_depth(&self, mut node: EventId, ancestor_id: &EventId) -> u32 {
  261. let mut depth = 0;
  262. while &node != ancestor_id {
  263. depth += 1;
  264. if let Some(parent) = self.event_map.get(&node).unwrap().parent {
  265. node = parent
  266. } else {
  267. break
  268. }
  269. }
  270. depth
  271. }
  272. fn find_height(&self, node: &EventId, child_id: &EventId) -> Option<u32> {
  273. let mut height = 0;
  274. if node == child_id {
  275. return Some(height)
  276. }
  277. height += 1;
  278. let children = &self.event_map.get(node).unwrap().children;
  279. if children.is_empty() {
  280. return None
  281. }
  282. for child in children.iter() {
  283. if let Some(h) = self.find_height(child, child_id) {
  284. return Some(height + h)
  285. }
  286. }
  287. None
  288. }
  289. fn find_ancestor(&self, mut node_a: EventId, mut node_b: EventId) -> EventId {
  290. // node_a is a child of node_b
  291. let is_child = node_b == self.event_map.get(&node_a).unwrap().parent.unwrap();
  292. if is_child {
  293. return node_b
  294. }
  295. while node_a != node_b {
  296. let node_a_parent = self.event_map.get(&node_a).unwrap().parent.unwrap();
  297. let node_b_parent = self.event_map.get(&node_b).unwrap().parent.unwrap();
  298. if node_a_parent == self.current_root || node_b_parent == self.current_root {
  299. return self.current_root
  300. }
  301. node_a = node_a_parent;
  302. node_b = node_b_parent;
  303. }
  304. node_a
  305. }
  306. fn diff_depth(&self, node_a: EventId, node_b: EventId) -> u32 {
  307. let ancestor = self.find_ancestor(node_a, node_b);
  308. let node_a_depth = self.find_depth(node_a, &ancestor);
  309. let node_b_depth = self.find_depth(node_b, &ancestor);
  310. (node_b_depth + 1) - node_a_depth
  311. }
  312. fn _debug(&self) {
  313. for (event_id, event_node) in &self.event_map {
  314. let depth = self.find_depth(*event_id, &self.current_root);
  315. println!("{}: {:?} [depth={}]", hex::encode(&event_id), event_node.event, depth);
  316. }
  317. println!("root: {}", hex::encode(&self.current_root));
  318. println!("head: {}", hex::encode(&self.find_head()));
  319. }
  320. }
  321. #[cfg(test)]
  322. mod tests {
  323. use super::*;
  324. use crate::events_queue::EventsQueue;
  325. fn create_message(
  326. previous_event_hash: EventId,
  327. nick: &str,
  328. msg: &str,
  329. timestamp: u64,
  330. ) -> Event {
  331. Event {
  332. previous_event_hash,
  333. action: EventAction::PrivMsg(PrivMsgEvent {
  334. nick: nick.to_string(),
  335. msg: msg.to_string(),
  336. target: "".to_string(),
  337. }),
  338. timestamp,
  339. read_confirms: 4,
  340. }
  341. }
  342. #[test]
  343. fn test_update_root() {
  344. let events_queue = EventsQueue::new();
  345. let mut model = Model::new(events_queue);
  346. let root_id = model.current_root;
  347. // event_node 1
  348. // Fill this node with MAX_HEIGHT events
  349. let mut id1 = root_id;
  350. for x in 0..MAX_HEIGHT {
  351. let timestamp = get_current_time() + 1;
  352. let node = create_message(id1, &format!("chain 1 msg {}", x), "message", timestamp);
  353. id1 = node.hash();
  354. model.add(node);
  355. }
  356. // event_node 2
  357. // Fill this node with MAX_HEIGHT + 10 events
  358. let mut id2 = root_id;
  359. for x in 0..(MAX_HEIGHT + 10) {
  360. let timestamp = get_current_time() + 1;
  361. let node = create_message(id2, &format!("chain 2 msg {}", x), "message", timestamp);
  362. id2 = node.hash();
  363. model.add(node);
  364. }
  365. // Fill id2 node with MAX_HEIGHT / 2
  366. let mut id3 = id2;
  367. for x in (MAX_HEIGHT + 10)..(MAX_HEIGHT * 2) {
  368. let timestamp = get_current_time() + 1;
  369. let node =
  370. create_message(id3, &format!("chain 2 branch 1 msg {}", x), "message", timestamp);
  371. id3 = node.hash();
  372. model.add(node);
  373. }
  374. // Fill id2 node with 9 events
  375. let mut id4 = id2;
  376. for x in (MAX_HEIGHT + 10)..(MAX_HEIGHT * 2 + 30) {
  377. let timestamp = get_current_time() + 1;
  378. let node =
  379. create_message(id4, &format!("chain 2 branch 2 msg {}", x), "message", timestamp);
  380. id4 = node.hash();
  381. model.add(node);
  382. }
  383. assert_eq!(model.find_height(&model.current_root, &id2).unwrap(), 0);
  384. assert_eq!(model.find_height(&model.current_root, &id3).unwrap(), (MAX_HEIGHT - 10));
  385. assert_eq!(model.find_height(&model.current_root, &id4).unwrap(), (MAX_HEIGHT + 20));
  386. assert_eq!(model.current_root, id2);
  387. }
  388. #[test]
  389. fn test_find_height() {
  390. let events_queue = EventsQueue::new();
  391. let mut model = Model::new(events_queue);
  392. let root_id = model.current_root;
  393. // event_node 1
  394. // Fill this node with 8 events
  395. let mut id1 = root_id;
  396. for x in 0..8 {
  397. let timestamp = get_current_time() + 1;
  398. let node = create_message(id1, &format!("chain 1 msg {}", x), "message", timestamp);
  399. id1 = node.hash();
  400. model.add(node);
  401. }
  402. // event_node 2
  403. // Fill this node with 14 events
  404. let mut id2 = root_id;
  405. for x in 0..14 {
  406. let timestamp = get_current_time() + 1;
  407. let node = create_message(id2, &format!("chain 2 msg {}", x), "message", timestamp);
  408. id2 = node.hash();
  409. model.add(node);
  410. }
  411. assert_eq!(model.find_height(&model.current_root, &id1).unwrap(), 8);
  412. assert_eq!(model.find_height(&model.current_root, &id2).unwrap(), 14);
  413. }
  414. #[test]
  415. fn test_prune_chains() {
  416. let events_queue = EventsQueue::new();
  417. let mut model = Model::new(events_queue);
  418. let root_id = model.current_root;
  419. // event_node 1
  420. // Fill this node with 3 events
  421. let mut event_node_1_ids = vec![];
  422. let mut id1 = root_id;
  423. for x in 0..3 {
  424. let timestamp = get_current_time() + 1;
  425. let node = create_message(id1, &format!("chain 1 msg {}", x), "message", timestamp);
  426. id1 = node.hash();
  427. model.add(node);
  428. event_node_1_ids.push(id1);
  429. }
  430. // event_node 2
  431. // Start from the root_id and fill the node with 14 events
  432. // All the events from event_node_1 should get removed from the tree
  433. let mut id2 = root_id;
  434. for x in 0..(MAX_DEPTH + 10) {
  435. let timestamp = get_current_time() + 1;
  436. let node = create_message(id2, &format!("chain 2 msg {}", x), "message", timestamp);
  437. id2 = node.hash();
  438. model.add(node);
  439. }
  440. assert_eq!(model.find_head(), id2);
  441. for id in event_node_1_ids {
  442. assert!(!model.event_map.contains_key(&id));
  443. }
  444. assert_eq!(model.event_map.len(), (MAX_DEPTH + 11) as usize);
  445. }
  446. #[test]
  447. fn test_diff_depth() {
  448. let events_queue = EventsQueue::new();
  449. let mut model = Model::new(events_queue);
  450. let root_id = model.current_root;
  451. // event_node 1
  452. // Fill this node with (MAX_DEPTH / 2) events
  453. let mut id1 = root_id;
  454. for x in 0..(MAX_DEPTH / 2) {
  455. let timestamp = get_current_time() + 1;
  456. let node = create_message(id1, &format!("chain 1 msg {}", x), "message", timestamp);
  457. id1 = node.hash();
  458. model.add(node);
  459. }
  460. // event_node 2
  461. // Start from the root_id and fill the node with (MAX_DEPTH + 10) events
  462. // all the events must be added since the depth between id1
  463. // and the last head is less than MAX_DEPTH
  464. let mut id2 = root_id;
  465. for x in 0..(MAX_DEPTH + 10) {
  466. let timestamp = get_current_time() + 1;
  467. let node = create_message(id2, &format!("chain 2 msg {}", x), "message", timestamp);
  468. id2 = node.hash();
  469. model.add(node);
  470. }
  471. assert_eq!(model.find_head(), id2);
  472. // event_node 3
  473. // This will start as new chain, but no events will be added
  474. // since the last event's depth is MAX_DEPTH + 10
  475. let mut id3 = root_id;
  476. for x in 0..30 {
  477. let timestamp = get_current_time() + 1;
  478. let node = create_message(id3, &format!("chain 3 msg {}", x), "message", timestamp);
  479. id3 = node.hash();
  480. model.add(node);
  481. // ensure events are not added
  482. assert!(!model.event_map.contains_key(&id3));
  483. }
  484. assert_eq!(model.find_head(), id2);
  485. // Add more events to the event_node 1
  486. // At the end this chain must overtake the event_node 2
  487. for x in (MAX_DEPTH / 2)..(MAX_DEPTH + 15) {
  488. let timestamp = get_current_time() + 1;
  489. let node = create_message(id1, &format!("chain 1 msg {}", x), "message", timestamp);
  490. id1 = node.hash();
  491. model.add(node);
  492. }
  493. assert_eq!(model.find_head(), id1);
  494. }
  495. #[test]
  496. fn test_event_hash() {
  497. let events_queue = EventsQueue::new();
  498. let model = Model::new(events_queue);
  499. let root_id = model.current_root;
  500. let timestamp = get_current_time() + 1;
  501. let event = create_message(root_id, "msg", "message", timestamp);
  502. let mut event2 = event.clone();
  503. let event_hash = event.hash();
  504. event2.read_confirms += 3;
  505. let event2_hash = event2.hash();
  506. assert_eq!(event2_hash, event_hash);
  507. assert_ne!(event2.read_confirms, event.read_confirms);
  508. }
  509. }