model.rs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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::Debug};
  19. use async_std::sync::{Arc, Mutex};
  20. use blake3;
  21. use darkfi_serial::{serialize, Decodable, Encodable, SerialDecodable, SerialEncodable};
  22. use log::error;
  23. use crate::{event_graph::events_queue::EventsQueuePtr, util::time::Timestamp};
  24. use super::EventMsg;
  25. //pub type EventId = [u8; blake3::OUT_LEN];
  26. pub type EventId = blake3::Hash;
  27. const MAX_DEPTH: u32 = 300;
  28. const MAX_HEIGHT: u32 = 300;
  29. #[derive(SerialEncodable, SerialDecodable, Clone, Debug)]
  30. pub struct Event<T: Send + Sync> {
  31. pub previous_event_hash: EventId,
  32. pub action: T,
  33. pub timestamp: Timestamp,
  34. }
  35. impl<T> Event<T>
  36. where
  37. T: Send + Sync + Encodable + Decodable + Clone + EventMsg,
  38. {
  39. pub fn hash(&self) -> EventId {
  40. blake3::hash(&serialize(self))
  41. }
  42. }
  43. #[derive(Debug, Clone)]
  44. struct EventNode<T: Send + Sync> {
  45. // Only current root has this set to None
  46. parent: Option<EventId>,
  47. event: Event<T>,
  48. children: Vec<EventId>,
  49. }
  50. pub type ModelPtr<T> = Arc<Mutex<Model<T>>>;
  51. pub struct Model<T: Send + Sync + Debug> {
  52. // This is periodically updated so we discard old nodes
  53. current_root: EventId,
  54. orphans: HashMap<EventId, Event<T>>,
  55. event_map: HashMap<EventId, EventNode<T>>,
  56. events_queue: EventsQueuePtr<T>,
  57. }
  58. impl<T> Model<T>
  59. where
  60. T: Send + Sync + Encodable + Decodable + Clone + EventMsg + Debug,
  61. {
  62. pub fn new(events_queue: EventsQueuePtr<T>) -> Self {
  63. let root_node = EventNode {
  64. parent: None,
  65. event: Event {
  66. previous_event_hash: blake3::hash(b""), // This is a blake3 hash of NULL
  67. action: T::new(),
  68. timestamp: Timestamp(1674512021323),
  69. },
  70. children: Vec::new(),
  71. };
  72. let root_node_id = root_node.event.hash();
  73. let mut event_map = HashMap::new();
  74. event_map.insert(root_node_id, root_node);
  75. Self { current_root: root_node_id, orphans: HashMap::new(), event_map, events_queue }
  76. }
  77. pub fn get_head_hash(&self) -> EventId {
  78. self.find_head()
  79. }
  80. pub async fn add(&mut self, event: Event<T>) {
  81. self.orphans.insert(event.hash(), event);
  82. self.reorganize().await;
  83. }
  84. pub fn is_orphan(&self, event: &Event<T>) -> bool {
  85. !self.event_map.contains_key(&event.previous_event_hash)
  86. }
  87. pub fn find_leaves(&self) -> Vec<EventId> {
  88. // collect the leaves in the tree
  89. let mut leaves = vec![];
  90. for (event_hash, node) in self.event_map.iter() {
  91. // check if the node is a leaf
  92. if node.children.is_empty() {
  93. leaves.push(*event_hash);
  94. }
  95. }
  96. leaves
  97. }
  98. pub fn get_event(&self, event: &EventId) -> Option<Event<T>> {
  99. self.event_map.get(event).map(|en| en.event.clone())
  100. }
  101. pub fn get_offspring(&self, event: &EventId) -> Vec<Event<T>> {
  102. let mut offspring = vec![];
  103. let mut event = *event;
  104. let head = self.find_head();
  105. loop {
  106. if event == head {
  107. break
  108. }
  109. if let Some(ev) = self.event_map.get(&event) {
  110. for child in ev.children.iter() {
  111. let child = self.event_map.get(child).unwrap();
  112. offspring.push(child.event.clone());
  113. event = child.event.hash();
  114. }
  115. } else {
  116. break
  117. }
  118. }
  119. offspring
  120. }
  121. async fn reorganize(&mut self) {
  122. for (_, orphan) in std::mem::take(&mut self.orphans) {
  123. // if self.is_orphan(&orphan) {
  124. // // TODO should we remove orphan if it's too old
  125. // continue
  126. // }
  127. let prev_event = orphan.previous_event_hash;
  128. let node =
  129. EventNode { parent: Some(prev_event), event: orphan.clone(), children: Vec::new() };
  130. let node_hash = node.event.hash();
  131. let parent = match self.event_map.get_mut(&prev_event) {
  132. Some(parent) => parent,
  133. None => {
  134. error!("No parent found, Orphan is not relinked");
  135. self.orphans.insert(orphan.hash(), orphan);
  136. continue
  137. }
  138. };
  139. parent.children.push(node_hash);
  140. self.event_map.insert(node_hash, node.clone());
  141. self.events_queue.dispatch(&node.event).await.expect("error dispatching the event");
  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. continue
  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={}]", event_id, event_node.event, depth);
  316. }
  317. println!("root: {}", self.current_root);
  318. println!("head: {}", self.find_head());
  319. }
  320. }
  321. #[cfg(test)]
  322. mod tests {
  323. use super::*;
  324. use crate::event_graph::events_queue::EventsQueue;
  325. #[derive(SerialEncodable, SerialDecodable, Clone, Debug)]
  326. pub struct PrivMsgEvent {
  327. pub nick: String,
  328. pub msg: String,
  329. pub target: String,
  330. }
  331. impl std::string::ToString for PrivMsgEvent {
  332. fn to_string(&self) -> String {
  333. format!(":{}!anon@dark.fi PRIVMSG {} :{}\r\n", self.nick, self.target, self.msg)
  334. }
  335. }
  336. impl EventMsg for PrivMsgEvent {
  337. fn new() -> Self {
  338. Self {
  339. nick: "root".to_string(),
  340. msg: "Let there be dark".to_string(),
  341. target: "root".to_string(),
  342. }
  343. }
  344. }
  345. fn create_message(previous_event_hash: EventId, timestamp: u64) -> Event<PrivMsgEvent> {
  346. Event { previous_event_hash, action: PrivMsgEvent::new(), timestamp: Timestamp(timestamp) }
  347. }
  348. /* THIS IS FAILING
  349. #[test]
  350. fn test_update_root() {
  351. let events_queue = EventsQueue::new();
  352. let mut model = Model::new(events_queue);
  353. let root_id = model.current_root;
  354. // event_node 1
  355. // Fill this node with MAX_HEIGHT events
  356. let mut id1 = root_id;
  357. for x in 0..MAX_HEIGHT {
  358. let timestamp = get_current_time() + 1;
  359. let node = create_message(id1, &format!("chain 1 msg {}", x), "message", timestamp);
  360. id1 = node.hash();
  361. model.add(node);
  362. }
  363. // event_node 2
  364. // Fill this node with MAX_HEIGHT + 10 events
  365. let mut id2 = root_id;
  366. for x in 0..(MAX_HEIGHT + 10) {
  367. let timestamp = get_current_time() + 1;
  368. let node = create_message(id2, &format!("chain 2 msg {}", x), "message", timestamp);
  369. id2 = node.hash();
  370. model.add(node);
  371. }
  372. // Fill id2 node with MAX_HEIGHT / 2
  373. let mut id3 = id2;
  374. for x in (MAX_HEIGHT + 10)..(MAX_HEIGHT * 2) {
  375. let timestamp = get_current_time() + 1;
  376. let node =
  377. create_message(id3, &format!("chain 2 branch 1 msg {}", x), "message", timestamp);
  378. id3 = node.hash();
  379. model.add(node);
  380. }
  381. // Fill id2 node with 9 events
  382. let mut id4 = id2;
  383. for x in (MAX_HEIGHT + 10)..(MAX_HEIGHT * 2 + 30) {
  384. let timestamp = get_current_time() + 1;
  385. let node =
  386. create_message(id4, &format!("chain 2 branch 2 msg {}", x), "message", timestamp);
  387. id4 = node.hash();
  388. model.add(node);
  389. }
  390. assert_eq!(model.find_height(&model.current_root, &id2).unwrap(), 0);
  391. assert_eq!(model.find_height(&model.current_root, &id3).unwrap(), (MAX_HEIGHT - 10));
  392. assert_eq!(model.find_height(&model.current_root, &id4).unwrap(), (MAX_HEIGHT + 20));
  393. assert_eq!(model.current_root, id2);
  394. }
  395. #[test]
  396. fn test_find_height() {
  397. let events_queue = EventsQueue::new();
  398. let mut model = Model::new(events_queue);
  399. let root_id = model.current_root;
  400. // event_node 1
  401. // Fill this node with 8 events
  402. let mut id1 = root_id;
  403. for x in 0..8 {
  404. let timestamp = get_current_time() + 1;
  405. let node = create_message(id1, &format!("chain 1 msg {}", x), "message", timestamp);
  406. id1 = node.hash();
  407. model.add(node);
  408. }
  409. // event_node 2
  410. // Fill this node with 14 events
  411. let mut id2 = root_id;
  412. for x in 0..14 {
  413. let timestamp = get_current_time() + 1;
  414. let node = create_message(id2, &format!("chain 2 msg {}", x), "message", timestamp);
  415. id2 = node.hash();
  416. model.add(node);
  417. }
  418. assert_eq!(model.find_height(&model.current_root, &id1).unwrap(), 8);
  419. assert_eq!(model.find_height(&model.current_root, &id2).unwrap(), 14);
  420. }
  421. #[test]
  422. fn test_prune_chains() {
  423. let events_queue = EventsQueue::new();
  424. let mut model = Model::new(events_queue);
  425. let root_id = model.current_root;
  426. // event_node 1
  427. // Fill this node with 3 events
  428. let mut event_node_1_ids = vec![];
  429. let mut id1 = root_id;
  430. for x in 0..3 {
  431. let timestamp = get_current_time() + 1;
  432. let node = create_message(id1, &format!("chain 1 msg {}", x), "message", timestamp);
  433. id1 = node.hash();
  434. model.add(node);
  435. event_node_1_ids.push(id1);
  436. }
  437. // event_node 2
  438. // Start from the root_id and fill the node with 14 events
  439. // All the events from event_node_1 should get removed from the tree
  440. let mut id2 = root_id;
  441. for x in 0..(MAX_DEPTH + 10) {
  442. let timestamp = get_current_time() + 1;
  443. let node = create_message(id2, &format!("chain 2 msg {}", x), "message", timestamp);
  444. id2 = node.hash();
  445. model.add(node);
  446. }
  447. assert_eq!(model.find_head(), id2);
  448. for id in event_node_1_ids {
  449. assert!(!model.event_map.contains_key(&id));
  450. }
  451. assert_eq!(model.event_map.len(), (MAX_DEPTH + 11) as usize);
  452. }
  453. #[test]
  454. fn test_diff_depth() {
  455. let events_queue = EventsQueue::new();
  456. let mut model = Model::new(events_queue);
  457. let root_id = model.current_root;
  458. // event_node 1
  459. // Fill this node with (MAX_DEPTH / 2) events
  460. let mut id1 = root_id;
  461. for x in 0..(MAX_DEPTH / 2) {
  462. let timestamp = get_current_time() + 1;
  463. let node = create_message(id1, &format!("chain 1 msg {}", x), "message", timestamp);
  464. id1 = node.hash();
  465. model.add(node);
  466. }
  467. // event_node 2
  468. // Start from the root_id and fill the node with (MAX_DEPTH + 10) events
  469. // all the events must be added since the depth between id1
  470. // and the last head is less than MAX_DEPTH
  471. let mut id2 = root_id;
  472. for x in 0..(MAX_DEPTH + 10) {
  473. let timestamp = get_current_time() + 1;
  474. let node = create_message(id2, &format!("chain 2 msg {}", x), "message", timestamp);
  475. id2 = node.hash();
  476. model.add(node);
  477. }
  478. assert_eq!(model.find_head(), id2);
  479. // event_node 3
  480. // This will start as new chain, but no events will be added
  481. // since the last event's depth is MAX_DEPTH + 10
  482. let mut id3 = root_id;
  483. for x in 0..30 {
  484. let timestamp = get_current_time() + 1;
  485. let node = create_message(id3, &format!("chain 3 msg {}", x), "message", timestamp);
  486. id3 = node.hash();
  487. model.add(node);
  488. // ensure events are not added
  489. assert!(!model.event_map.contains_key(&id3));
  490. }
  491. assert_eq!(model.find_head(), id2);
  492. // Add more events to the event_node 1
  493. // At the end this chain must overtake the event_node 2
  494. for x in (MAX_DEPTH / 2)..(MAX_DEPTH + 15) {
  495. let timestamp = get_current_time() + 1;
  496. let node = create_message(id1, &format!("chain 1 msg {}", x), "message", timestamp);
  497. id1 = node.hash();
  498. model.add(node);
  499. }
  500. assert_eq!(model.find_head(), id1);
  501. }
  502. */
  503. #[test]
  504. fn test_event_hash() {
  505. let events_queue = EventsQueue::<PrivMsgEvent>::new();
  506. let model = Model::new(events_queue);
  507. let root_id = model.current_root;
  508. let timestamp = Timestamp::current_time().0 + 1;
  509. let event = create_message(root_id, timestamp);
  510. let event2 = event.clone();
  511. let event_hash = event.hash();
  512. let event2_hash = event2.hash();
  513. assert_eq!(event2_hash, event_hash);
  514. }
  515. }