model.rs 21 KB

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