mvc.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. use async_std::sync::{Arc, Mutex};
  2. use std::{
  3. collections::{HashMap, HashSet},
  4. fmt, io,
  5. };
  6. use async_executor::Executor;
  7. use async_recursion::async_recursion;
  8. use ripemd::{Digest, Ripemd256};
  9. use smol::future;
  10. use structopt::StructOpt;
  11. use structopt_toml::StructOptToml;
  12. use darkfi::{
  13. async_daemonize,
  14. util::{
  15. cli::{get_log_config, get_log_level, spawn_config},
  16. expand_path,
  17. path::get_config_path,
  18. serial::{Decodable, Encodable, ReadExt, SerialDecodable, SerialEncodable},
  19. },
  20. Result,
  21. };
  22. type EventId = [u8; 32];
  23. const MAX_DEPTH: u32 = 10;
  24. #[derive(SerialEncodable, SerialDecodable)]
  25. struct Event {
  26. previous_event_hash: EventId,
  27. action: EventAction,
  28. timestamp: u64,
  29. }
  30. impl Event {
  31. fn hash(&self) -> EventId {
  32. let mut bytes = Vec::new();
  33. self.encode(&mut bytes).expect("serialize failed!");
  34. let mut hasher = Ripemd256::new();
  35. hasher.update(bytes);
  36. let bytes = hasher.finalize().to_vec();
  37. let mut result = [0u8; 32];
  38. result.copy_from_slice(bytes.as_slice());
  39. result
  40. }
  41. }
  42. impl fmt::Debug for Event {
  43. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  44. match &self.action {
  45. EventAction::PrivMsg(event) => {
  46. write!(f, "PRIVMSG {}: {} ({})", event.nick, event.msg, self.timestamp)
  47. }
  48. }
  49. }
  50. }
  51. enum EventAction {
  52. PrivMsg(PrivMsgEvent),
  53. }
  54. impl Encodable for EventAction {
  55. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  56. match self {
  57. Self::PrivMsg(event) => {
  58. let mut len = 0;
  59. len += 0u8.encode(&mut s)?;
  60. len += event.encode(s)?;
  61. Ok(len)
  62. }
  63. }
  64. }
  65. }
  66. impl Decodable for EventAction {
  67. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  68. let type_id = d.read_u8()?;
  69. match type_id {
  70. 0 => Ok(Self::PrivMsg(PrivMsgEvent::decode(d)?)),
  71. _ => Err(darkfi::Error::ParseFailed("Bad type ID byte for Event")),
  72. }
  73. }
  74. }
  75. #[derive(SerialEncodable, SerialDecodable)]
  76. struct PrivMsgEvent {
  77. nick: String,
  78. msg: String,
  79. }
  80. #[derive(Debug)]
  81. struct EventNode {
  82. // Only current root has this set to None
  83. parent: Option<EventNodePtr>,
  84. event: Event,
  85. children: Mutex<Vec<EventNodePtr>>,
  86. }
  87. type EventNodePtr = Arc<EventNode>;
  88. #[derive(Debug)]
  89. struct Model {
  90. // This is periodically updated so we discard old nodes
  91. current_root: EventId,
  92. orphans: Vec<Event>,
  93. event_map: HashMap<EventId, EventNodePtr>,
  94. }
  95. impl Model {
  96. fn new() -> Self {
  97. let root_node = Arc::new(EventNode {
  98. parent: None,
  99. event: Event {
  100. previous_event_hash: [0u8; 32],
  101. action: EventAction::PrivMsg(PrivMsgEvent {
  102. nick: "root".to_string(),
  103. msg: "Let there be dark".to_string(),
  104. }),
  105. timestamp: get_current_time(),
  106. },
  107. children: Mutex::new(Vec::new()),
  108. });
  109. let root_node_id = root_node.event.hash();
  110. let event_map = HashMap::from([(root_node_id.clone(), root_node)]);
  111. Self { current_root: root_node_id, orphans: Vec::new(), event_map }
  112. }
  113. async fn add(&mut self, event: Event) {
  114. self.orphans.push(event);
  115. self.reorganize().await;
  116. }
  117. // TODO: Update root only after some time
  118. // Recursively free nodes climbing up from old root to new root
  119. // Also remove entries from event_map
  120. async fn reorganize(&mut self) {
  121. let mut remaining_orphans = Vec::new();
  122. for orphan in std::mem::take(&mut self.orphans) {
  123. let prev_event = orphan.previous_event_hash.clone();
  124. // clean up the tree from old eventnodes
  125. self.prune_forks().await;
  126. // Parent does not yet exist
  127. if !self.event_map.contains_key(&prev_event) {
  128. remaining_orphans.push(orphan);
  129. // BIGTODO #1:
  130. // TODO: We need to fetch missing ancestors from the network
  131. // Trigger get_blocks() request
  132. continue
  133. }
  134. let parent = self.event_map.get(&prev_event).expect("logic error").clone();
  135. let node = Arc::new(EventNode {
  136. parent: Some(parent.clone()),
  137. event: orphan,
  138. children: Mutex::new(Vec::new()),
  139. });
  140. // Reject events which attach to forks too low in the chain
  141. // At some point we ignore all events from old branches
  142. let depth = self.diff_depth(node.clone(), self.find_head().await);
  143. if depth > MAX_DEPTH {
  144. continue
  145. }
  146. parent.children.lock().await.push(node.clone());
  147. // Add node to the table
  148. self.event_map.insert(node.event.hash(), node);
  149. }
  150. }
  151. async fn prune_forks(&mut self) {
  152. let head = self.find_head().await;
  153. let head_event_hash = head.event.hash();
  154. for (event_hash, node) in self.event_map.clone() {
  155. // to prevent running through the same node twice
  156. if !self.event_map.contains_key(&event_hash) {
  157. continue
  158. }
  159. // skip the head event
  160. if event_hash == head_event_hash {
  161. continue
  162. }
  163. let empty_children = node.children.lock().await.is_empty();
  164. if empty_children {
  165. let depth = self.diff_depth(node.clone(), self.find_head().await);
  166. if depth > MAX_DEPTH {
  167. self.remove_node(node.clone()).await;
  168. }
  169. }
  170. }
  171. }
  172. async fn remove_node(&mut self, mut node: EventNodePtr) {
  173. loop {
  174. let event_id = node.event.hash();
  175. let parent_event_id = node.parent.as_ref().unwrap().event.hash();
  176. self.event_map.remove(&event_id);
  177. let parent_node = self.event_map.get_mut(&parent_event_id).unwrap();
  178. let children = &mut parent_node.children.lock().await;
  179. let index = children.iter().position(|n| n.event.hash() == event_id).unwrap();
  180. children.remove(index);
  181. if !children.is_empty() {
  182. return
  183. }
  184. node = parent_node.clone()
  185. }
  186. }
  187. fn get_root(&self) -> EventNodePtr {
  188. let root_id = &self.current_root;
  189. return self.event_map.get(root_id).expect("root ID is not in the event map!").clone()
  190. }
  191. // find_head
  192. // -> recursively call itself
  193. // -> + 1 for every recursion, return self if no children
  194. // -> select max from returned values
  195. // Gets the lead node with the maximal number of events counting from root
  196. async fn find_head(&self) -> EventNodePtr {
  197. let root = self.get_root();
  198. Self::find_longest_chain(root, 0).await.0
  199. }
  200. #[async_recursion]
  201. async fn find_longest_chain(parent_node: EventNodePtr, i: u32) -> (EventNodePtr, u32) {
  202. let children = parent_node.children.lock().await;
  203. if children.is_empty() {
  204. return (parent_node.clone(), i)
  205. }
  206. let mut current_max = 0;
  207. let mut current_node = None;
  208. for node in &*children {
  209. let (grandchild_node, grandchild_i) =
  210. Self::find_longest_chain(node.clone(), i + 1).await;
  211. if grandchild_i > current_max {
  212. current_max = grandchild_i;
  213. current_node = Some(grandchild_node.clone());
  214. } else if grandchild_i == current_max {
  215. // Break ties using the timestamp
  216. if grandchild_node.event.timestamp >
  217. current_node.as_ref().expect("current_node should be set!").event.timestamp
  218. {
  219. current_max = grandchild_i;
  220. current_node = Some(grandchild_node.clone());
  221. }
  222. }
  223. }
  224. assert_ne!(current_max, 0);
  225. (current_node.expect("internal logic error"), current_max)
  226. }
  227. // TODO change this to count from bottom
  228. fn find_depth(&self, mut node: EventNodePtr, ancestor_id: EventId) -> u32 {
  229. let mut depth = 0;
  230. while node.event.hash() != ancestor_id {
  231. depth += 1;
  232. node = node.parent.as_ref().expect("non-root nodes should have a parent set").clone();
  233. }
  234. depth
  235. }
  236. fn find_ancestor(&self, mut node_a: EventNodePtr, mut node_b: EventNodePtr) -> EventId {
  237. // node_a is a child of node_b
  238. let is_child = node_b.event.hash() == node_a.parent.as_ref().unwrap().event.hash();
  239. if is_child {
  240. return node_b.event.hash()
  241. }
  242. while node_a.event.hash() != node_b.event.hash() {
  243. let node_a_parent =
  244. node_a.parent.as_ref().expect("non-root nodes should have a parent set");
  245. let node_b_parent =
  246. node_b.parent.as_ref().expect("non-root nodes should have a parent set");
  247. if node_a_parent.event.hash() == self.current_root ||
  248. node_b_parent.event.hash() == self.current_root
  249. {
  250. return self.current_root
  251. }
  252. node_a = node_a_parent.clone();
  253. node_b = node_b_parent.clone();
  254. }
  255. node_a.event.hash().clone()
  256. }
  257. fn diff_depth(&self, node_a: EventNodePtr, node_b: EventNodePtr) -> u32 {
  258. let ancestor = self.find_ancestor(node_a.clone(), node_b.clone());
  259. let node_a_depth = self.find_depth(node_a, ancestor);
  260. let node_b_depth = self.find_depth(node_b, ancestor);
  261. (node_b_depth + 1) - node_a_depth
  262. }
  263. async fn debug(&self) {
  264. for (event_id, event_node) in &self.event_map {
  265. let depth = self.find_depth(event_node.clone(), self.current_root);
  266. println!("{}: {:?} [depth={}]", hex::encode(&event_id), event_node.event, depth);
  267. }
  268. println!("root: {}", hex::encode(&self.get_root().event.hash()));
  269. println!("head: {}", hex::encode(&self.find_head().await.event.hash()));
  270. }
  271. }
  272. pub const CONFIG_FILE: &str = "ircd_config.toml";
  273. pub const CONFIG_FILE_CONTENTS: &str = include_str!("../ircd_config.toml");
  274. #[derive(Clone, Debug, serde::Deserialize, StructOpt, StructOptToml)]
  275. #[serde(default)]
  276. #[structopt(name = "ircd")]
  277. pub struct Args {
  278. #[structopt(long)]
  279. pub config: Option<String>,
  280. /// Increase verbosity
  281. #[structopt(short, parse(from_occurrences))]
  282. pub verbose: u8,
  283. }
  284. fn get_current_time() -> u64 {
  285. let start = std::time::SystemTime::now();
  286. start
  287. .duration_since(std::time::UNIX_EPOCH)
  288. .expect("Time went backwards")
  289. .as_millis()
  290. .try_into()
  291. .unwrap()
  292. }
  293. fn create_message(previous_event_hash: EventId, nick: &str, msg: &str, timestamp: u64) -> Event {
  294. Event {
  295. previous_event_hash,
  296. action: EventAction::PrivMsg(PrivMsgEvent { nick: nick.to_string(), msg: msg.to_string() }),
  297. timestamp,
  298. }
  299. }
  300. struct View {
  301. seen: HashSet<EventId>,
  302. }
  303. impl View {
  304. pub fn new() -> Self {
  305. Self { seen: HashSet::new() }
  306. }
  307. fn process(_model: &Model) {
  308. // This does 2 passes:
  309. // 1. Walk down all chains and get unseen events
  310. // 2. Order those events according to timestamp
  311. // Then the events are replayed to the IRC client
  312. }
  313. }
  314. async_daemonize!(realmain);
  315. async fn realmain(_settings: Args, _executor: Arc<Executor<'_>>) -> Result<()> {
  316. let mut model = Model::new();
  317. let root_id = model.get_root().event.hash();
  318. let timestamp = get_current_time() + 1;
  319. let node1 = create_message(root_id, "alice", "alice message", timestamp);
  320. model.add(node1).await;
  321. let node2 = create_message(root_id, "bob", "bob message", timestamp);
  322. let node2_id = node2.hash();
  323. model.add(node2).await;
  324. let node3 = create_message(root_id, "charlie", "charlie message", timestamp);
  325. let node3_id = node3.hash();
  326. model.add(node3).await;
  327. let node4 = create_message(node2_id, "delta", "delta message", timestamp);
  328. let node4_id = node4.hash();
  329. model.add(node4).await;
  330. assert_eq!(model.find_head().await.event.hash(), node4_id);
  331. // Now lets extend another chain
  332. let node5 = create_message(node3_id, "epsilon", "epsilon message", timestamp);
  333. let node5_id = node5.hash();
  334. model.add(node5).await;
  335. let node6 = create_message(node5_id, "phi", "phi message", timestamp);
  336. let node6_id = node6.hash();
  337. model.add(node6).await;
  338. assert_eq!(model.find_head().await.event.hash(), node6_id);
  339. model.debug().await;
  340. Ok(())
  341. }
  342. #[cfg(test)]
  343. mod tests {
  344. use super::*;
  345. #[async_std::test]
  346. async fn test_prune_forks() {
  347. let mut model = Model::new();
  348. let root_id = model.get_root().event.hash();
  349. // event_node 1
  350. // Fill this node with 3 events
  351. let mut event_node_1_ids = vec![];
  352. let mut id1 = root_id;
  353. for x in 0..3 {
  354. let timestamp = get_current_time() + 1;
  355. let node = create_message(id1, &format!("alice {}", x), "alice message", timestamp);
  356. id1 = node.hash();
  357. model.add(node).await;
  358. event_node_1_ids.push(id1);
  359. }
  360. // event_node 2
  361. // Start from the root_id and fill the node with 14 events
  362. // All the events from event_node_1 should get removed from the tree
  363. let mut id2 = root_id;
  364. for x in 0..14 {
  365. let timestamp = get_current_time() + 1;
  366. let node = create_message(id2, &format!("bob {}", x), "bob message", timestamp);
  367. id2 = node.hash();
  368. model.add(node).await;
  369. }
  370. assert_eq!(model.find_head().await.event.hash(), id2);
  371. for id in event_node_1_ids {
  372. assert!(!model.event_map.contains_key(&id));
  373. }
  374. assert_eq!(model.event_map.len(), 15);
  375. }
  376. #[async_std::test]
  377. async fn test_diff_depth() {
  378. let mut model = Model::new();
  379. let root_id = model.get_root().event.hash();
  380. // event_node 1
  381. // Fill this node with 7 events
  382. let mut id1 = root_id;
  383. for x in 0..7 {
  384. let timestamp = get_current_time() + 1;
  385. let node = create_message(id1, &format!("alice {}", x), "alice message", timestamp);
  386. id1 = node.hash();
  387. model.add(node).await;
  388. }
  389. // event_node 2
  390. // Start from the root_id and fill the node with 14 events
  391. // all the events must be added since the depth between id1
  392. // and the last head is less than 9
  393. let mut id2 = root_id;
  394. for x in 0..14 {
  395. let timestamp = get_current_time() + 1;
  396. let node = create_message(id2, &format!("bob {}", x), "bob message", timestamp);
  397. id2 = node.hash();
  398. model.add(node).await;
  399. }
  400. assert_eq!(model.find_head().await.event.hash(), id2);
  401. // event_node 3
  402. // This will start as new fork, but no events will be added
  403. // since the last event's depth is 14
  404. let mut id3 = root_id;
  405. for x in 0..3 {
  406. let timestamp = get_current_time() + 1;
  407. let node = create_message(id3, &format!("phi {}", x), "phi message", timestamp);
  408. id3 = node.hash();
  409. model.add(node).await;
  410. // ensure events are not added
  411. assert!(!model.event_map.contains_key(&id3));
  412. }
  413. assert_eq!(model.find_head().await.event.hash(), id2);
  414. // Add more events to the event_node 1
  415. // At the end this fork must overtake the event_node 2
  416. for x in 7..14 {
  417. let timestamp = get_current_time() + 1;
  418. let node = create_message(id1, &format!("alice {}", x), "alice message", timestamp);
  419. id1 = node.hash();
  420. model.add(node).await;
  421. }
  422. assert_eq!(model.find_head().await.event.hash(), id1);
  423. }
  424. }