event.rs 9.4 KB

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