event.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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::{collections::HashSet, time::UNIX_EPOCH};
  19. use darkfi_serial::{async_trait, deserialize_async, Encodable, SerialDecodable, SerialEncodable};
  20. use sled_overlay::{sled, SledTreeOverlay};
  21. use crate::Result;
  22. use super::{
  23. util::next_rotation_timestamp, EventGraph, EVENT_TIME_DRIFT, INITIAL_GENESIS, NULL_ID,
  24. N_EVENT_PARENTS,
  25. };
  26. /// Representation of an event in the Event Graph
  27. #[derive(Debug, Clone, PartialEq, SerialEncodable, SerialDecodable)]
  28. pub struct Event {
  29. /// Timestamp of the event in whole seconds
  30. pub timestamp: u64,
  31. /// Content of the event
  32. pub(crate) content: Vec<u8>,
  33. /// Parent nodes in the event DAG
  34. pub(crate) parents: [blake3::Hash; N_EVENT_PARENTS],
  35. /// DAG layer index of the event
  36. pub(crate) layer: u64,
  37. }
  38. impl Event {
  39. /// Create a new event with the given data and an [`EventGraph`] reference.
  40. /// The timestamp of the event will be the current time, and the parents
  41. /// will be `N_EVENT_PARENTS` from the current event graph unreferenced tips.
  42. /// The parents can also include NULL, but this should be handled by the rest
  43. /// of the codebase.
  44. pub async fn new(data: Vec<u8>, event_graph: &EventGraph) -> Self {
  45. let (layer, parents) = event_graph.get_next_layer_with_parents().await;
  46. Self {
  47. timestamp: UNIX_EPOCH.elapsed().unwrap().as_millis() as u64,
  48. content: data,
  49. parents,
  50. layer,
  51. }
  52. }
  53. /// Hash the [`Event`] to retrieve its ID
  54. pub fn id(&self) -> blake3::Hash {
  55. let mut hasher = blake3::Hasher::new();
  56. let timestamp =
  57. if self.timestamp > 1e10 as u64 { self.timestamp / 1000 } else { self.timestamp };
  58. timestamp.encode(&mut hasher).unwrap();
  59. self.content.encode(&mut hasher).unwrap();
  60. self.parents.encode(&mut hasher).unwrap();
  61. self.layer.encode(&mut hasher).unwrap();
  62. hasher.finalize()
  63. }
  64. /// Return a reference to the event's content
  65. pub fn content(&self) -> &[u8] {
  66. &self.content
  67. }
  68. /*
  69. /// Check if an [`Event`] is considered too old.
  70. fn is_too_old(&self) -> bool {
  71. self.timestamp < UNIX_EPOCH.elapsed().unwrap().as_secs() - ORPHAN_AGE_LIMIT
  72. }
  73. */
  74. /// Fully validate an event for the correct layout against provided
  75. /// DAG [`sled::Tree`] reference and enforce relevant age, assuming
  76. /// some possibility for a time drift. Optionally, provide an overlay
  77. /// to use that instead of actual referenced DAG.
  78. pub async fn validate(
  79. &self,
  80. dag: &sled::Tree,
  81. genesis_timestamp: u64,
  82. days_rotation: u64,
  83. overlay: Option<&SledTreeOverlay>,
  84. ) -> Result<bool> {
  85. // Let's not bother with empty events
  86. if self.content.is_empty() {
  87. return Ok(false)
  88. }
  89. // Check if the event timestamp is after genesis timestamp
  90. if self.timestamp < genesis_timestamp - EVENT_TIME_DRIFT / 1000 {
  91. return Ok(false)
  92. }
  93. // If a rotation has been set, check if the event timestamp
  94. // is after the next genesis timestamp
  95. if days_rotation > 0 {
  96. let next_genesis_timestamp = next_rotation_timestamp(INITIAL_GENESIS, days_rotation);
  97. if self.timestamp > next_genesis_timestamp + EVENT_TIME_DRIFT / 1000 {
  98. return Ok(false)
  99. }
  100. }
  101. // Validate the parents. We have to check that at least one parent
  102. // is not NULL, that the parents exist, that no two parents are the
  103. // same, and that the parent exists in previous layers, to prevent
  104. // recursive references(circles).
  105. let mut seen = HashSet::new();
  106. let self_id = self.id();
  107. for parent_id in self.parents.iter() {
  108. if parent_id == &NULL_ID {
  109. continue
  110. }
  111. if parent_id == &self_id {
  112. return Ok(false)
  113. }
  114. if seen.contains(parent_id) {
  115. return Ok(false)
  116. }
  117. let parent_bytes = if let Some(overlay) = overlay {
  118. overlay.get(parent_id.as_bytes())?
  119. } else {
  120. dag.get(parent_id.as_bytes())?
  121. };
  122. if parent_bytes.is_none() {
  123. return Ok(false)
  124. }
  125. let parent: Event = deserialize_async(&parent_bytes.unwrap()).await?;
  126. if self.layer <= parent.layer {
  127. return Ok(false)
  128. }
  129. seen.insert(parent_id);
  130. }
  131. Ok(!seen.is_empty())
  132. }
  133. /// Fully validate an event for the correct layout against provided
  134. /// [`EventGraph`] reference and enforce relevant age, assuming some
  135. /// possibility for a time drift.
  136. pub async fn dag_validate(&self, event_graph: &EventGraph) -> Result<bool> {
  137. // Grab genesis timestamp
  138. let genesis_timestamp = event_graph.current_genesis.read().await.timestamp;
  139. // Perform validation
  140. self.validate(&event_graph.dag, genesis_timestamp, event_graph.days_rotation, None).await
  141. }
  142. /// Validate a new event for the correct layout and enforce relevant age,
  143. /// assuming some possibility for a time drift.
  144. /// Note: This validation does *NOT* check for recursive references(circles),
  145. /// and should be used as a first quick check.
  146. pub fn validate_new(&self, is_ver_match: bool) -> bool {
  147. // Let's not bother with empty events
  148. if self.content.is_empty() {
  149. return false
  150. }
  151. if is_ver_match {
  152. // Check if the event is too old or too new
  153. let now = UNIX_EPOCH.elapsed().unwrap().as_millis() as u64;
  154. let too_old = self.timestamp < now - EVENT_TIME_DRIFT;
  155. let too_new = self.timestamp > now + EVENT_TIME_DRIFT;
  156. if too_old || too_new {
  157. return false
  158. }
  159. } else {
  160. // Check if the event is too old or too new
  161. let now = UNIX_EPOCH.elapsed().unwrap().as_secs();
  162. let too_old = self.timestamp < (now - (EVENT_TIME_DRIFT / 1000));
  163. let too_new = self.timestamp > (now + (EVENT_TIME_DRIFT / 1000));
  164. if too_old || too_new {
  165. return false
  166. }
  167. }
  168. // Validate the parents. We have to check that at least one parent
  169. // is not NULL and that no two parents are the same.
  170. let mut seen = HashSet::new();
  171. let self_id = self.id();
  172. for parent_id in self.parents.iter() {
  173. if parent_id == &NULL_ID {
  174. continue
  175. }
  176. if parent_id == &self_id {
  177. return false
  178. }
  179. if seen.contains(parent_id) {
  180. return false
  181. }
  182. seen.insert(parent_id);
  183. }
  184. !seen.is_empty()
  185. }
  186. }
  187. #[cfg(test)]
  188. mod tests {
  189. use std::sync::Arc;
  190. use smol::Executor;
  191. use crate::{
  192. event_graph::{EventGraph, EventGraphPtr},
  193. net::{P2p, Settings},
  194. };
  195. use super::*;
  196. async fn make_event_graph() -> Result<EventGraphPtr> {
  197. let ex = Arc::new(Executor::new());
  198. let p2p = P2p::new(Settings::default(), ex.clone()).await?;
  199. let sled_db = sled::Config::new().temporary(true).open().unwrap();
  200. EventGraph::new(p2p, sled_db, "/tmp".into(), false, "dag", 1, ex).await
  201. }
  202. #[test]
  203. fn event_is_valid() -> Result<()> {
  204. smol::block_on(async {
  205. // Generate a dummy event graph
  206. let event_graph = make_event_graph().await?;
  207. // Create a new valid event
  208. let valid_event = Event::new(vec![1u8], &event_graph).await;
  209. // Validate our test Event struct
  210. assert!(valid_event.dag_validate(&event_graph).await?);
  211. // Thanks for reading
  212. Ok(())
  213. })
  214. }
  215. #[test]
  216. fn invalid_events() -> Result<()> {
  217. smol::block_on(async {
  218. // Generate a dummy event graph
  219. let event_graph = make_event_graph().await?;
  220. // Create a new valid event
  221. let valid_event = Event::new(vec![1u8], &event_graph).await;
  222. let mut event_empty_content = valid_event.clone();
  223. event_empty_content.content = vec![];
  224. assert!(!event_empty_content.dag_validate(&event_graph).await?);
  225. let mut event_timestamp_too_old = valid_event.clone();
  226. event_timestamp_too_old.timestamp = 0;
  227. assert!(!event_timestamp_too_old.dag_validate(&event_graph).await?);
  228. let mut event_timestamp_too_new = valid_event.clone();
  229. event_timestamp_too_new.timestamp = u64::MAX;
  230. assert!(!event_timestamp_too_new.dag_validate(&event_graph).await?);
  231. let mut event_duplicated_parents = valid_event.clone();
  232. event_duplicated_parents.parents[1] = valid_event.parents[0];
  233. assert!(!event_duplicated_parents.dag_validate(&event_graph).await?);
  234. let mut event_null_parents = valid_event.clone();
  235. let all_null_parents = [NULL_ID, NULL_ID, NULL_ID, NULL_ID, NULL_ID];
  236. event_null_parents.parents = all_null_parents;
  237. assert!(!event_null_parents.dag_validate(&event_graph).await?);
  238. let mut event_same_layer_as_parents = valid_event.clone();
  239. event_same_layer_as_parents.layer = 0;
  240. assert!(!event_same_layer_as_parents.dag_validate(&event_graph).await?);
  241. // Thanks for reading
  242. Ok(())
  243. })
  244. }
  245. }