model.rs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  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, path::Path};
  19. use async_std::sync::{Arc, Mutex};
  20. use blake3;
  21. use darkfi_serial::{
  22. deserialize, serialize, Decodable, Encodable, SerialDecodable, SerialEncodable,
  23. };
  24. use log::{error, info};
  25. use tinyjson::JsonValue;
  26. use crate::{
  27. event_graph::events_queue::EventsQueuePtr,
  28. util::{
  29. encoding::base64,
  30. file::{load_json_file, save_json_file},
  31. time::Timestamp,
  32. },
  33. };
  34. use super::EventMsg;
  35. //pub type EventId = [u8; blake3::OUT_LEN];
  36. pub type EventId = blake3::Hash;
  37. const MAX_DEPTH: u32 = 300;
  38. #[derive(SerialEncodable, SerialDecodable, Clone, Debug)]
  39. pub struct Event<T: Send + Sync> {
  40. pub previous_event_hash: EventId,
  41. pub action: T,
  42. pub timestamp: Timestamp,
  43. }
  44. impl<T> Event<T>
  45. where
  46. T: Send + Sync + Encodable + Decodable + Clone + EventMsg,
  47. {
  48. pub fn hash(&self) -> EventId {
  49. blake3::hash(&serialize(self))
  50. }
  51. }
  52. #[derive(SerialEncodable, SerialDecodable, Clone, Debug)]
  53. struct EventNode<T: Send + Sync> {
  54. // Only current root has this set to None
  55. parent: Option<EventId>,
  56. event: Event<T>,
  57. children: Vec<EventId>,
  58. }
  59. pub type ModelPtr<T> = Arc<Mutex<Model<T>>>;
  60. pub struct Model<T: Send + Sync + Debug> {
  61. // This is up to the application to reset or keep
  62. current_root: EventId,
  63. orphans: HashMap<EventId, Event<T>>,
  64. event_map: HashMap<EventId, EventNode<T>>,
  65. events_queue: EventsQueuePtr<T>,
  66. }
  67. impl<T> Model<T>
  68. where
  69. T: Send + Sync + Encodable + Decodable + Clone + EventMsg + Debug,
  70. {
  71. pub fn new(events_queue: EventsQueuePtr<T>) -> Self {
  72. let root_node = EventNode {
  73. parent: None,
  74. event: Event {
  75. previous_event_hash: blake3::hash(b""), // This is a blake3 hash of NULL
  76. action: T::new(),
  77. timestamp: Timestamp(1674512021323),
  78. },
  79. children: Vec::new(),
  80. };
  81. let root_node_id = root_node.event.hash();
  82. let mut event_map = HashMap::new();
  83. event_map.insert(root_node_id, root_node);
  84. Self { current_root: root_node_id, orphans: HashMap::new(), event_map, events_queue }
  85. }
  86. pub fn save_tree(&self, path: &Path) -> crate::Result<()> {
  87. let path = path.join("tree");
  88. let tree = self.event_map.clone();
  89. let ser_tree = base64::encode(&serialize(&tree));
  90. save_json_file(&path, &JsonValue::String(ser_tree), false)?;
  91. info!("Tree is saved to disk");
  92. Ok(())
  93. }
  94. pub fn load_tree(&mut self, path: &Path) -> crate::Result<()> {
  95. let path = path.join("tree");
  96. if !path.exists() {
  97. return Ok(())
  98. }
  99. let loaded_tree_obj = load_json_file(&path)?;
  100. let loaded_tree_obj: &String = loaded_tree_obj.get::<String>().unwrap();
  101. let loaded_tree_bytes = base64::decode(loaded_tree_obj.as_str()).unwrap();
  102. let dser_tree: HashMap<blake3::Hash, EventNode<T>> = deserialize(&loaded_tree_bytes)?;
  103. self.event_map = dser_tree;
  104. info!("Tree is loaded from disk");
  105. Ok(())
  106. }
  107. pub fn reset_root(&mut self, timestamp: Timestamp) {
  108. let root_node = EventNode {
  109. parent: None,
  110. event: Event {
  111. previous_event_hash: blake3::hash(b""), // This is a blake3 hash of NULL
  112. action: T::new(),
  113. timestamp,
  114. },
  115. children: Vec::new(),
  116. };
  117. let root_node_id = root_node.event.hash();
  118. let mut event_map = HashMap::new();
  119. event_map.insert(root_node_id, root_node);
  120. self.current_root = root_node_id;
  121. self.orphans = HashMap::new();
  122. self.event_map = event_map;
  123. info!("reset current root to: {:?}", self.current_root);
  124. }
  125. pub fn remove_old_events(&mut self, timestamp: Timestamp) -> crate::Result<()> {
  126. let tree = self.event_map.clone();
  127. let mut is_tree_changed = false;
  128. for (event_hash, node) in tree {
  129. if node.event.timestamp < timestamp {
  130. if self.event_map.remove(&event_hash).is_none() {
  131. continue
  132. }
  133. is_tree_changed = true;
  134. let parent = self.event_map.get_mut(&self.current_root).unwrap();
  135. if parent.children.contains(&event_hash) {
  136. let index = parent.children.iter().position(|&n| n == event_hash).unwrap();
  137. parent.children.remove(index);
  138. }
  139. }
  140. }
  141. if is_tree_changed {
  142. let binding = self.event_map.clone();
  143. let min_hash = binding.iter().min_by_key(|entry| entry.1.event.timestamp.0).unwrap().0;
  144. println!("min hash: {}", min_hash);
  145. self.event_map.get_mut(min_hash).unwrap().parent = Some(self.current_root);
  146. self.event_map.get_mut(min_hash).unwrap().event.previous_event_hash = self.current_root;
  147. let parent = self.event_map.get_mut(&self.current_root).unwrap();
  148. parent.children.push(*min_hash);
  149. }
  150. Ok(())
  151. }
  152. pub fn get_head_hash(&self) -> EventId {
  153. self.find_head()
  154. }
  155. pub async fn add(&mut self, event: Event<T>) {
  156. self.orphans.insert(event.hash(), event);
  157. self.reorganize().await;
  158. }
  159. pub fn is_orphan(&self, event: &Event<T>) -> bool {
  160. !self.event_map.contains_key(&event.previous_event_hash)
  161. }
  162. pub fn find_leaves(&self) -> Vec<EventId> {
  163. // collect the leaves in the tree
  164. let mut leaves = vec![];
  165. for (event_hash, node) in self.event_map.iter() {
  166. // check if the node is a leaf
  167. if node.children.is_empty() {
  168. leaves.push(*event_hash);
  169. }
  170. }
  171. leaves
  172. }
  173. pub fn get_event(&self, event: &EventId) -> Option<Event<T>> {
  174. self.event_map.get(event).map(|en| en.event.clone())
  175. }
  176. pub fn get_offspring(&self, event: &EventId) -> Vec<Event<T>> {
  177. let mut offspring = vec![];
  178. let mut event = *event;
  179. let head = self.find_head();
  180. loop {
  181. if event == head {
  182. break
  183. }
  184. if let Some(ev) = self.event_map.get(&event) {
  185. for child in ev.children.iter() {
  186. let child = self.event_map.get(child).unwrap();
  187. offspring.push(child.event.clone());
  188. event = child.event.hash();
  189. }
  190. } else {
  191. break
  192. }
  193. }
  194. offspring
  195. }
  196. async fn reorganize(&mut self) {
  197. for (_, orphan) in std::mem::take(&mut self.orphans) {
  198. // if self.is_orphan(&orphan) {
  199. // // TODO should we remove orphan if it's too old
  200. // continue
  201. // }
  202. let prev_event = orphan.previous_event_hash;
  203. let node =
  204. EventNode { parent: Some(prev_event), event: orphan.clone(), children: Vec::new() };
  205. let node_hash = node.event.hash();
  206. let parent = match self.event_map.get_mut(&prev_event) {
  207. Some(parent) => parent,
  208. None => {
  209. error!("No parent found, Orphan is not relinked");
  210. self.orphans.insert(orphan.hash(), orphan);
  211. continue
  212. }
  213. };
  214. parent.children.push(node_hash);
  215. self.event_map.insert(node_hash, node.clone());
  216. self.events_queue.dispatch(&node.event).await.ok();
  217. // clean up the tree from old eventnodes
  218. self.prune_chains();
  219. }
  220. }
  221. fn prune_chains(&mut self) {
  222. let head = self.find_head();
  223. let leaves = self.find_leaves();
  224. // Reject events which attach to chains too low in the chain
  225. // At some point we ignore all events from old branches
  226. for leaf in leaves {
  227. // skip the head event
  228. if leaf == head {
  229. continue
  230. }
  231. let depth = self.diff_depth(leaf, head);
  232. if depth > MAX_DEPTH {
  233. self.remove_node(leaf);
  234. }
  235. }
  236. }
  237. fn remove_node(&mut self, mut event_id: EventId) {
  238. loop {
  239. if !self.event_map.contains_key(&event_id) {
  240. break
  241. }
  242. if event_id == self.current_root {
  243. break
  244. }
  245. let node = self.event_map.get(&event_id).unwrap().clone();
  246. self.event_map.remove(&event_id);
  247. let parent = self.event_map.get_mut(&node.parent.unwrap()).unwrap();
  248. if parent.children.is_empty() {
  249. event_id = parent.event.hash();
  250. continue
  251. }
  252. let index = parent.children.iter().position(|&n| n == event_id).unwrap();
  253. parent.children.remove(index);
  254. event_id = parent.event.hash();
  255. }
  256. }
  257. // find_head
  258. // -> recursively call itself
  259. // -> + 1 for every recursion, return self if no children
  260. // -> select max from returned values
  261. // Gets the lead node with the maximal number of events counting from root
  262. fn find_head(&self) -> EventId {
  263. self.find_longest_chain(&self.current_root, 0).0
  264. }
  265. fn find_longest_chain(&self, parent_node: &EventId, i: u32) -> (EventId, u32) {
  266. let children = &self.event_map.get(parent_node).unwrap().children;
  267. if children.is_empty() {
  268. return (*parent_node, i)
  269. }
  270. let mut current_max = 0;
  271. let mut current_node = None;
  272. for node in children.iter() {
  273. let (grandchild_node, grandchild_i) = self.find_longest_chain(node, i + 1);
  274. match &grandchild_i.cmp(&current_max) {
  275. Ordering::Greater => {
  276. current_max = grandchild_i;
  277. current_node = Some(grandchild_node);
  278. }
  279. Ordering::Equal => {
  280. // Break ties using the timestamp
  281. let grandchild_node_timestamp =
  282. self.event_map.get(&grandchild_node).unwrap().event.timestamp;
  283. let current_node_timestamp =
  284. self.event_map.get(&current_node.unwrap()).unwrap().event.timestamp;
  285. if grandchild_node_timestamp > current_node_timestamp {
  286. current_max = grandchild_i;
  287. current_node = Some(grandchild_node);
  288. }
  289. }
  290. Ordering::Less => {
  291. // Left a todo here, not sure if it should be handled
  292. continue
  293. }
  294. }
  295. }
  296. assert_ne!(current_max, 0);
  297. (current_node.expect("internal logic error"), current_max)
  298. }
  299. fn find_depth(&self, mut node: EventId, ancestor_id: &EventId) -> u32 {
  300. let mut depth = 0;
  301. while &node != ancestor_id {
  302. depth += 1;
  303. if let Some(parent) = self.event_map.get(&node).unwrap().parent {
  304. node = parent
  305. } else {
  306. break
  307. }
  308. }
  309. depth
  310. }
  311. // Find common ancestor between two events
  312. fn find_ancestor(&self, mut node_a: EventId, node_b: EventId) -> EventId {
  313. // node_a is a child of node_b
  314. let is_child = node_b == self.event_map.get(&node_a).unwrap().parent.unwrap();
  315. if is_child {
  316. return node_b
  317. }
  318. loop {
  319. let node_a_parent = self.event_map.get(&node_a).unwrap().parent.unwrap();
  320. node_a = node_a_parent;
  321. if node_a == self.current_root {
  322. return self.current_root
  323. }
  324. if self.event_map.get(&node_a).unwrap().children.len() > 1 {
  325. let offsprings = self
  326. .get_offspring(&node_a)
  327. .iter()
  328. .map(|event| event.hash())
  329. .collect::<Vec<EventId>>();
  330. if offsprings.contains(&node_b) {
  331. return node_a
  332. }
  333. }
  334. }
  335. }
  336. // Find the length between two events
  337. fn diff_depth(&self, node_a: EventId, node_b: EventId) -> u32 {
  338. let ancestor = self.find_ancestor(node_a, node_b);
  339. let node_a_depth = self.find_depth(node_a, &ancestor);
  340. let node_b_depth = self.find_depth(node_b, &ancestor);
  341. (node_b_depth + 1).abs_diff(node_a_depth)
  342. }
  343. fn _debug(&self) {
  344. for (event_id, event_node) in &self.event_map {
  345. let depth = self.find_depth(*event_id, &self.current_root);
  346. println!("{}: {:?} [depth={}]", event_id, event_node.event, depth);
  347. }
  348. println!("root: {}", self.current_root);
  349. println!("head: {}", self.find_head());
  350. }
  351. }
  352. #[cfg(test)]
  353. mod tests {
  354. use std::{
  355. fs::{create_dir_all, remove_dir_all},
  356. path::PathBuf,
  357. };
  358. use super::*;
  359. use crate::{event_graph::events_queue::EventsQueue, util::async_util::sleep, Result};
  360. #[derive(SerialEncodable, SerialDecodable, Clone, Debug)]
  361. pub struct PrivMsgEvent {
  362. pub nick: String,
  363. pub msg: String,
  364. pub target: String,
  365. }
  366. impl std::string::ToString for PrivMsgEvent {
  367. fn to_string(&self) -> String {
  368. format!(":{}!anon@dark.fi PRIVMSG {} :{}\r\n", self.nick, self.target, self.msg)
  369. }
  370. }
  371. impl EventMsg for PrivMsgEvent {
  372. fn new() -> Self {
  373. Self {
  374. nick: "root".to_string(),
  375. msg: "Let there be dark".to_string(),
  376. target: "root".to_string(),
  377. }
  378. }
  379. }
  380. fn create_message(previous_event_hash: EventId, timestamp: Timestamp) -> Event<PrivMsgEvent> {
  381. Event { previous_event_hash, action: PrivMsgEvent::new(), timestamp }
  382. }
  383. #[async_std::test]
  384. async fn test_remove_old_events() {
  385. let events_queue = EventsQueue::new();
  386. let mut model = Model::new(events_queue);
  387. let root_id = model.current_root;
  388. // event_node 1
  389. // Fill this node with 10 events
  390. // These are considered old events from 10 days ago
  391. let mut event_node_1_ids = vec![];
  392. let mut id1 = root_id;
  393. let timestamp = Timestamp::current_time().0 - 864000; // 864000 is 10 days in seconds
  394. for i in 0..10 {
  395. let node = create_message(id1, Timestamp(timestamp + i));
  396. id1 = node.hash();
  397. model.add(node).await;
  398. event_node_1_ids.push(id1);
  399. }
  400. sleep(1).await;
  401. // event_node 2
  402. // Fill this node with 10 events
  403. // These are considered new events at current time
  404. let timestamp = Timestamp::current_time().0;
  405. for i in 0..150 {
  406. let node = create_message(id1, Timestamp(timestamp + i));
  407. id1 = node.hash();
  408. model.add(node).await;
  409. }
  410. sleep(1).await;
  411. // every event older than one week gets removed
  412. let ts = Timestamp::current_time().0 - 604800; // one week in seconds
  413. let _ = model.remove_old_events(Timestamp(ts));
  414. // ensure the 10 events from event_node 1 are not in the tree anymore
  415. for event in event_node_1_ids {
  416. assert!(!model.event_map.contains_key(&event));
  417. }
  418. // event_node 2 events (150) + root event = 151 events
  419. assert_eq!(model.event_map.len(), 151_usize);
  420. }
  421. #[async_std::test]
  422. async 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 10 events
  428. let mut event_node_1_ids = vec![];
  429. let mut id1 = root_id;
  430. for _ in 0..10 {
  431. let node = create_message(id1, Timestamp::current_time());
  432. id1 = node.hash();
  433. model.add(node).await;
  434. event_node_1_ids.push(id1);
  435. }
  436. sleep(1).await;
  437. // event_node 2
  438. // Start from the root_id and fill the node with (MAX_DEPTH + 10) events.
  439. // All the events from event_node_1 should get removed from the tree
  440. let mut id2 = root_id;
  441. for _ in 0..(MAX_DEPTH + 10) {
  442. let node = create_message(id2, Timestamp::current_time());
  443. id2 = node.hash();
  444. model.add(node).await;
  445. }
  446. assert_eq!(model.find_head(), id2);
  447. // Ensure events from node 1 are removed in favor of node 2's longer chain
  448. for id in event_node_1_ids {
  449. assert!(!model.event_map.contains_key(&id));
  450. }
  451. // node1: (10 leaves) + node2: (MAX_DEPTH + 10) events + root event = (MAX_DEPTH + 11)
  452. // these ^^^^^^^^^^^ are pruned
  453. assert_eq!(model.event_map.len(), (MAX_DEPTH + 11) as usize);
  454. }
  455. #[async_std::test]
  456. async fn test_diff_depth() {
  457. let events_queue = EventsQueue::new();
  458. let mut model = Model::new(events_queue);
  459. let root_id = model.current_root;
  460. // event_node 1
  461. // Fill this node with (MAX_DEPTH / 2) events
  462. let mut id1 = root_id;
  463. for _ in 0..(MAX_DEPTH / 2) {
  464. let node = create_message(id1, Timestamp::current_time());
  465. id1 = node.hash();
  466. model.add(node).await;
  467. }
  468. sleep(1).await;
  469. // event_node 2
  470. // Start from the root_id and fill the node with (MAX_DEPTH + 10) events
  471. // all the events must be added since the depth between id1
  472. // and the last head is less than MAX_DEPTH
  473. let mut id2 = root_id;
  474. for _ in 0..(MAX_DEPTH + 10) {
  475. let node = create_message(id2, Timestamp::current_time());
  476. id2 = node.hash();
  477. model.add(node).await;
  478. }
  479. assert_eq!(model.find_head(), id2);
  480. sleep(1).await;
  481. // event_node 3
  482. // This will start as new chain, but no events will be added
  483. // since the last event's depth is MAX_DEPTH + 10
  484. let mut id3 = root_id;
  485. for _ in 0..30 {
  486. let node = create_message(id3, Timestamp::current_time());
  487. id3 = node.hash();
  488. model.add(node).await;
  489. // ensure events are not added
  490. assert!(!model.event_map.contains_key(&id3));
  491. }
  492. sleep(1).await;
  493. assert_eq!(model.find_head(), id2);
  494. // Add more events to the event_node 1
  495. // At the end this chain must overtake the event_node 2
  496. for _ in (MAX_DEPTH / 2)..(MAX_DEPTH + 15) {
  497. let node = create_message(id1, Timestamp::current_time());
  498. id1 = node.hash();
  499. model.add(node).await;
  500. }
  501. assert_eq!(model.find_head(), id1);
  502. }
  503. #[async_std::test]
  504. async fn save_load_model() -> Result<()> {
  505. // Setup directories
  506. let path = "/tmp/test_model";
  507. remove_dir_all(path).ok();
  508. let path = PathBuf::from(path);
  509. create_dir_all(&path)?;
  510. // First model
  511. let events_queue = EventsQueue::<PrivMsgEvent>::new();
  512. let mut model1 = Model::new(events_queue);
  513. let root_id = model1.current_root;
  514. // Create an event
  515. let event = create_message(root_id, Timestamp::current_time());
  516. // Add event to first model
  517. model1.add(event).await;
  518. // Save first model
  519. model1.save_tree(&path)?;
  520. // Second model
  521. let events_queue = EventsQueue::<PrivMsgEvent>::new();
  522. let mut model2 = Model::new(events_queue);
  523. // Load into second model
  524. model2.load_tree(&path)?;
  525. // Test equality
  526. let res = model1.event_map.len() == model2.event_map.len() &&
  527. model1.event_map.keys().all(|k| model2.event_map.contains_key(k));
  528. assert!(res);
  529. remove_dir_all(path).ok();
  530. Ok(())
  531. }
  532. #[test]
  533. fn test_event_hash() {
  534. let events_queue = EventsQueue::<PrivMsgEvent>::new();
  535. let model = Model::new(events_queue);
  536. let root_id = model.current_root;
  537. let event = create_message(root_id, Timestamp::current_time());
  538. let event2 = event.clone();
  539. let event_hash = event.hash();
  540. let event2_hash = event2.hash();
  541. assert_eq!(event2_hash, event_hash);
  542. }
  543. }