model.rs 20 KB

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