event.rs 9.8 KB

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