model.rs 21 KB

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