model.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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. /* THIS IS FAILING
  343. #[test]
  344. fn test_update_root() {
  345. let events_queue = EventsQueue::new();
  346. let mut model = Model::new(events_queue);
  347. let root_id = model.current_root;
  348. // event_node 1
  349. // Fill this node with MAX_HEIGHT events
  350. let mut id1 = root_id;
  351. for x in 0..MAX_HEIGHT {
  352. let timestamp = get_current_time() + 1;
  353. let node = create_message(id1, &format!("chain 1 msg {}", x), "message", timestamp);
  354. id1 = node.hash();
  355. model.add(node);
  356. }
  357. // event_node 2
  358. // Fill this node with MAX_HEIGHT + 10 events
  359. let mut id2 = root_id;
  360. for x in 0..(MAX_HEIGHT + 10) {
  361. let timestamp = get_current_time() + 1;
  362. let node = create_message(id2, &format!("chain 2 msg {}", x), "message", timestamp);
  363. id2 = node.hash();
  364. model.add(node);
  365. }
  366. // Fill id2 node with MAX_HEIGHT / 2
  367. let mut id3 = id2;
  368. for x in (MAX_HEIGHT + 10)..(MAX_HEIGHT * 2) {
  369. let timestamp = get_current_time() + 1;
  370. let node =
  371. create_message(id3, &format!("chain 2 branch 1 msg {}", x), "message", timestamp);
  372. id3 = node.hash();
  373. model.add(node);
  374. }
  375. // Fill id2 node with 9 events
  376. let mut id4 = id2;
  377. for x in (MAX_HEIGHT + 10)..(MAX_HEIGHT * 2 + 30) {
  378. let timestamp = get_current_time() + 1;
  379. let node =
  380. create_message(id4, &format!("chain 2 branch 2 msg {}", x), "message", timestamp);
  381. id4 = node.hash();
  382. model.add(node);
  383. }
  384. assert_eq!(model.find_height(&model.current_root, &id2).unwrap(), 0);
  385. assert_eq!(model.find_height(&model.current_root, &id3).unwrap(), (MAX_HEIGHT - 10));
  386. assert_eq!(model.find_height(&model.current_root, &id4).unwrap(), (MAX_HEIGHT + 20));
  387. assert_eq!(model.current_root, id2);
  388. }
  389. #[test]
  390. fn test_find_height() {
  391. let events_queue = EventsQueue::new();
  392. let mut model = Model::new(events_queue);
  393. let root_id = model.current_root;
  394. // event_node 1
  395. // Fill this node with 8 events
  396. let mut id1 = root_id;
  397. for x in 0..8 {
  398. let timestamp = get_current_time() + 1;
  399. let node = create_message(id1, &format!("chain 1 msg {}", x), "message", timestamp);
  400. id1 = node.hash();
  401. model.add(node);
  402. }
  403. // event_node 2
  404. // Fill this node with 14 events
  405. let mut id2 = root_id;
  406. for x in 0..14 {
  407. let timestamp = get_current_time() + 1;
  408. let node = create_message(id2, &format!("chain 2 msg {}", x), "message", timestamp);
  409. id2 = node.hash();
  410. model.add(node);
  411. }
  412. assert_eq!(model.find_height(&model.current_root, &id1).unwrap(), 8);
  413. assert_eq!(model.find_height(&model.current_root, &id2).unwrap(), 14);
  414. }
  415. #[test]
  416. fn test_prune_chains() {
  417. let events_queue = EventsQueue::new();
  418. let mut model = Model::new(events_queue);
  419. let root_id = model.current_root;
  420. // event_node 1
  421. // Fill this node with 3 events
  422. let mut event_node_1_ids = vec![];
  423. let mut id1 = root_id;
  424. for x in 0..3 {
  425. let timestamp = get_current_time() + 1;
  426. let node = create_message(id1, &format!("chain 1 msg {}", x), "message", timestamp);
  427. id1 = node.hash();
  428. model.add(node);
  429. event_node_1_ids.push(id1);
  430. }
  431. // event_node 2
  432. // Start from the root_id and fill the node with 14 events
  433. // All the events from event_node_1 should get removed from the tree
  434. let mut id2 = root_id;
  435. for x in 0..(MAX_DEPTH + 10) {
  436. let timestamp = get_current_time() + 1;
  437. let node = create_message(id2, &format!("chain 2 msg {}", x), "message", timestamp);
  438. id2 = node.hash();
  439. model.add(node);
  440. }
  441. assert_eq!(model.find_head(), id2);
  442. for id in event_node_1_ids {
  443. assert!(!model.event_map.contains_key(&id));
  444. }
  445. assert_eq!(model.event_map.len(), (MAX_DEPTH + 11) as usize);
  446. }
  447. #[test]
  448. fn test_diff_depth() {
  449. let events_queue = EventsQueue::new();
  450. let mut model = Model::new(events_queue);
  451. let root_id = model.current_root;
  452. // event_node 1
  453. // Fill this node with (MAX_DEPTH / 2) events
  454. let mut id1 = root_id;
  455. for x in 0..(MAX_DEPTH / 2) {
  456. let timestamp = get_current_time() + 1;
  457. let node = create_message(id1, &format!("chain 1 msg {}", x), "message", timestamp);
  458. id1 = node.hash();
  459. model.add(node);
  460. }
  461. // event_node 2
  462. // Start from the root_id and fill the node with (MAX_DEPTH + 10) events
  463. // all the events must be added since the depth between id1
  464. // and the last head is less than MAX_DEPTH
  465. let mut id2 = root_id;
  466. for x in 0..(MAX_DEPTH + 10) {
  467. let timestamp = get_current_time() + 1;
  468. let node = create_message(id2, &format!("chain 2 msg {}", x), "message", timestamp);
  469. id2 = node.hash();
  470. model.add(node);
  471. }
  472. assert_eq!(model.find_head(), id2);
  473. // event_node 3
  474. // This will start as new chain, but no events will be added
  475. // since the last event's depth is MAX_DEPTH + 10
  476. let mut id3 = root_id;
  477. for x in 0..30 {
  478. let timestamp = get_current_time() + 1;
  479. let node = create_message(id3, &format!("chain 3 msg {}", x), "message", timestamp);
  480. id3 = node.hash();
  481. model.add(node);
  482. // ensure events are not added
  483. assert!(!model.event_map.contains_key(&id3));
  484. }
  485. assert_eq!(model.find_head(), id2);
  486. // Add more events to the event_node 1
  487. // At the end this chain must overtake the event_node 2
  488. for x in (MAX_DEPTH / 2)..(MAX_DEPTH + 15) {
  489. let timestamp = get_current_time() + 1;
  490. let node = create_message(id1, &format!("chain 1 msg {}", x), "message", timestamp);
  491. id1 = node.hash();
  492. model.add(node);
  493. }
  494. assert_eq!(model.find_head(), id1);
  495. }
  496. */
  497. #[test]
  498. fn test_event_hash() {
  499. let events_queue = EventsQueue::new();
  500. let model = Model::new(events_queue);
  501. let root_id = model.current_root;
  502. let timestamp = get_current_time() + 1;
  503. let event = create_message(root_id, "msg", "message", timestamp);
  504. let mut event2 = event.clone();
  505. let event_hash = event.hash();
  506. event2.read_confirms += 3;
  507. let event2_hash = event2.hash();
  508. assert_eq!(event2_hash, event_hash);
  509. assert_ne!(event2.read_confirms, event.read_confirms);
  510. }
  511. }