model.rs 19 KB

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