model.rs 20 KB

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