event.rs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 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::HashSet};
  19. use darkfi_serial::{async_trait, deserialize_async, Encodable, SerialDecodable, SerialEncodable};
  20. use kvdb_overlay::{Tree, TreeOverlay};
  21. use super::{
  22. util::{unix_timestamp_millis, HOUR_MS},
  23. EventGraph, EventGraphConfig, EVENT_TIME_DRIFT, NULL_ID, N_EVENT_PARENTS,
  24. };
  25. use crate::Result;
  26. /// The fixed-size structural metadata of an event.
  27. ///
  28. /// Headers are lightweight and encode the full DAG topology without
  29. /// carrying the variable-length content. The content is committed
  30. /// to via `content_hash`, so peers can verify the integrity of an
  31. /// event body against the header that announced it.
  32. #[derive(Debug, Clone, PartialEq, SerialEncodable, SerialDecodable)]
  33. pub struct Header {
  34. /// UNIX timestamp of the event in milliseconds.
  35. pub timestamp: u64,
  36. /// Parent references. Unused slots are [`NULL_ID`].
  37. pub parents: [blake3::Hash; N_EVENT_PARENTS],
  38. /// Monotonically increasing layer index.
  39. pub layer: u64,
  40. /// blake3 hash of the event's content payload
  41. pub content_hash: blake3::Hash,
  42. }
  43. impl Header {
  44. pub async fn new(content: &[u8], eg: &EventGraph) -> Result<Self> {
  45. let dag_ts = eg.current_genesis.read().await.header.timestamp;
  46. let (layer, parents) = eg.get_next_layer_with_parents(&dag_ts).await?;
  47. Ok(Self {
  48. timestamp: unix_timestamp_millis()?,
  49. parents,
  50. layer,
  51. content_hash: blake3::hash(content),
  52. })
  53. }
  54. pub async fn new_static(content: &[u8], eg: &EventGraph) -> Result<Self> {
  55. let (layer, parents) = eg.get_next_layer_with_parents_static().await?;
  56. Ok(Self {
  57. timestamp: unix_timestamp_millis()?,
  58. parents,
  59. layer,
  60. content_hash: blake3::hash(content),
  61. })
  62. }
  63. pub async fn with_timestamp(timestamp: u64, content: &[u8], eg: &EventGraph) -> Result<Self> {
  64. let dag_ts = eg.current_genesis.read().await.header.timestamp;
  65. let (layer, parents) = eg.get_next_layer_with_parents(&dag_ts).await?;
  66. Ok(Self { timestamp, parents, layer, content_hash: blake3::hash(content) })
  67. }
  68. /// Blake3 hash of `(timestamp, parents, layer, content_hash)`.
  69. pub fn id(&self) -> blake3::Hash {
  70. let mut h = blake3::Hasher::new();
  71. let _ = self.timestamp.encode(&mut h);
  72. let _ = self.parents.encode(&mut h);
  73. let _ = self.layer.encode(&mut h);
  74. h.update(self.content_hash.as_bytes());
  75. h.finalize()
  76. }
  77. /// Full structural validation against a header DAG.
  78. ///
  79. /// `dag_genesis` is the timestamp/name of the target rotating DAG slot.
  80. pub async fn validate(
  81. &self,
  82. header_dag: &Tree,
  83. config: &EventGraphConfig,
  84. dag_genesis: u64,
  85. overlay: Option<&TreeOverlay>,
  86. ) -> Result<bool> {
  87. if !self.timestamp_fits_slot(config, dag_genesis) {
  88. return Ok(false)
  89. }
  90. let mut seen = HashSet::new();
  91. let mut max_parent_layer = None;
  92. let self_id = self.id();
  93. for pid in self.parents.iter() {
  94. if pid == &NULL_ID {
  95. continue
  96. }
  97. if pid == &self_id || seen.contains(pid) {
  98. return Ok(false)
  99. }
  100. let bytes = if let Some(ov) = overlay {
  101. ov.get(pid.as_bytes())?
  102. } else {
  103. header_dag.get(pid.as_bytes())?
  104. };
  105. let Some(bytes) = bytes else { return Ok(false) };
  106. let parent: Header = deserialize_async(&bytes).await?;
  107. max_parent_layer =
  108. Some(max_parent_layer.map_or(parent.layer, |m: u64| m.max(parent.layer)));
  109. seen.insert(pid);
  110. }
  111. let Some(max_parent_layer) = max_parent_layer else { return Ok(false) };
  112. let Some(expected_layer) = max_parent_layer.checked_add(1) else { return Ok(false) };
  113. Ok(self.layer == expected_layer)
  114. }
  115. /// Check whether this header timestamp belongs to the target DAG slot.
  116. fn timestamp_fits_slot(&self, config: &EventGraphConfig, dag_genesis: u64) -> bool {
  117. if self.timestamp < dag_genesis.saturating_sub(EVENT_TIME_DRIFT) {
  118. return false
  119. }
  120. if config.hours_rotation == 0 {
  121. let Ok(now) = unix_timestamp_millis() else { return false };
  122. return self.timestamp <= now.saturating_add(EVENT_TIME_DRIFT)
  123. }
  124. let Some(rotation_ms) = config.hours_rotation.checked_mul(HOUR_MS) else { return false };
  125. let Some(next_slot) = dag_genesis.checked_add(rotation_ms) else { return false };
  126. let Some(upper_bound) = next_slot.checked_add(EVENT_TIME_DRIFT) else { return false };
  127. self.timestamp < upper_bound
  128. }
  129. }
  130. /// A complete event: [`Header`] + application-defined content.
  131. #[derive(Debug, Clone, PartialEq, SerialEncodable, SerialDecodable)]
  132. pub struct Event {
  133. pub header: Header,
  134. /// Application payload. Must not be empty for non-genesis events.
  135. pub content: Vec<u8>,
  136. }
  137. impl Event {
  138. pub async fn new(data: Vec<u8>, eg: &EventGraph) -> Result<Self> {
  139. let header = Header::new(&data, eg).await?;
  140. Ok(Self { header, content: data })
  141. }
  142. pub async fn new_static(data: Vec<u8>, eg: &EventGraph) -> Result<Self> {
  143. let header = Header::new_static(&data, eg).await?;
  144. Ok(Self { header, content: data })
  145. }
  146. pub fn id(&self) -> blake3::Hash {
  147. self.header.id()
  148. }
  149. pub async fn with_timestamp(ts: u64, data: Vec<u8>, eg: &EventGraph) -> Result<Self> {
  150. let header = Header::with_timestamp(ts, &data, eg).await?;
  151. Ok(Self { header, content: data })
  152. }
  153. pub fn content(&self) -> &[u8] {
  154. &self.content
  155. }
  156. /// Check that the content matches the hash committed to in the header.
  157. pub fn content_matches_header(&self) -> bool {
  158. blake3::hash(&self.content) == self.header.content_hash
  159. }
  160. /// Validate for insertion into a DAG.
  161. ///
  162. /// `dag_genesis` is the timestamp/name of the target rotating DAG slot.
  163. pub async fn dag_validate(
  164. &self,
  165. hdr_dag: &Tree,
  166. config: &EventGraphConfig,
  167. dag_genesis: u64,
  168. ) -> Result<bool> {
  169. if self.content.is_empty() {
  170. return Ok(false)
  171. }
  172. if !self.content_matches_header() {
  173. return Ok(false)
  174. }
  175. self.header.validate(hdr_dag, config, dag_genesis, None).await
  176. }
  177. /// Quick validation (no DAG lookup).
  178. pub fn validate_new(&self) -> bool {
  179. if !self.validate_new_common() {
  180. return false
  181. }
  182. let Ok(now) = unix_timestamp_millis() else { return false };
  183. if self.header.timestamp < now.saturating_sub(EVENT_TIME_DRIFT) ||
  184. self.header.timestamp > now.saturating_add(EVENT_TIME_DRIFT)
  185. {
  186. return false
  187. }
  188. true
  189. }
  190. /// Quick validation for static-DAG events.
  191. ///
  192. /// Static-DAG events (RLN registrations and slashes) are
  193. /// persistent across rotation windows by design - they form
  194. /// the consensus identity tree and a node syncing for the
  195. /// first time may legitimately receive registrations that are
  196. /// hours, days, or longer old. Rejecting them on a 60-second
  197. /// time-drift window (as `validate_new` does for rotating
  198. /// events, where freshness IS part of the threat model)
  199. /// would prevent any late-joining node from ever syncing
  200. /// historical RLN state.
  201. ///
  202. /// This method runs the same structural checks as
  203. /// `validate_new` (non-empty content, content matches header,
  204. /// well-formed parent set) but omits the drift-window check.
  205. /// RLN proof verification of the static event itself happens
  206. /// separately in `EventGraph::rln_verify_static_event`.
  207. pub fn validate_new_static(&self) -> bool {
  208. self.validate_new_common()
  209. }
  210. /// Shared validation between `validate_new` and
  211. /// `validate_new_static`. Returns false if the event is
  212. /// structurally malformed in any time-independent way.
  213. fn validate_new_common(&self) -> bool {
  214. if self.content.is_empty() {
  215. return false
  216. }
  217. if !self.content_matches_header() {
  218. return false
  219. }
  220. let mut seen = HashSet::new();
  221. let sid = self.header.id();
  222. for pid in self.header.parents.iter() {
  223. if pid == &NULL_ID {
  224. continue
  225. }
  226. if pid == &sid || seen.contains(pid) {
  227. return false
  228. }
  229. seen.insert(pid);
  230. }
  231. !seen.is_empty()
  232. }
  233. }
  234. /// Chronological comparator with deterministic hash tie-breaking.
  235. pub fn display_order(a: &Event, b: &Event) -> Ordering {
  236. a.header
  237. .timestamp
  238. .cmp(&b.header.timestamp)
  239. .then_with(|| a.id().as_bytes().cmp(b.id().as_bytes()))
  240. }