model.rs 20 KB

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