model.rs 19 KB

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