mod.rs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  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::{
  19. collections::{BTreeMap, HashMap, HashSet, VecDeque},
  20. path::PathBuf,
  21. sync::Arc,
  22. time::Duration,
  23. };
  24. use darkfi_serial::{deserialize_async, serialize_async};
  25. use log::{debug, error, info, warn};
  26. use num_bigint::BigUint;
  27. use sled_overlay::SledTreeOverlay;
  28. use smol::{
  29. lock::{OnceCell, RwLock},
  30. Executor,
  31. };
  32. use tinyjson::JsonValue::{self};
  33. use crate::{
  34. event_graph::util::{replayer_log, seconds_until_next_rotation},
  35. net::P2pPtr,
  36. rpc::{
  37. jsonrpc::{JsonResponse, JsonResult},
  38. util::json_map,
  39. },
  40. system::{
  41. sleep, timeout::timeout, Publisher, PublisherPtr, StoppableTask, StoppableTaskPtr,
  42. Subscription,
  43. },
  44. Error, Result,
  45. };
  46. /// An event graph event
  47. pub mod event;
  48. pub use event::Event;
  49. /// P2P protocol implementation for the Event Graph
  50. pub mod proto;
  51. use proto::{EventRep, EventReq, TipRep, TipReq};
  52. /// Utility functions
  53. pub mod util;
  54. use util::{generate_genesis, next_rotation_timestamp};
  55. // Debugging event graph
  56. pub(crate) mod deg;
  57. use deg::DegEvent;
  58. #[cfg(test)]
  59. mod tests;
  60. /// Initial genesis timestamp (07 Sep 2023, 00:00:00 UTC)
  61. /// Must always be UTC midnight.
  62. const INITIAL_GENESIS: u64 = 1694044800;
  63. /// Genesis event contents
  64. const GENESIS_CONTENTS: &[u8] = &[0x47, 0x45, 0x4e, 0x45, 0x53, 0x49, 0x53];
  65. /// The number of parents an event is supposed to have.
  66. const N_EVENT_PARENTS: usize = 5;
  67. /// Allowed timestamp drift in seconds
  68. const EVENT_TIME_DRIFT: u64 = 60;
  69. /// Null event ID
  70. pub const NULL_ID: blake3::Hash = blake3::Hash::from_bytes([0x00; blake3::OUT_LEN]);
  71. /// Atomic pointer to an [`EventGraph`] instance.
  72. pub type EventGraphPtr = Arc<EventGraph>;
  73. /// An Event Graph instance
  74. pub struct EventGraph {
  75. /// Pointer to the P2P network instance
  76. p2p: P2pPtr,
  77. /// Sled tree containing the DAG
  78. dag: sled::Tree,
  79. datastore: PathBuf,
  80. replay_mode: bool,
  81. /// The set of unreferenced DAG tips
  82. unreferenced_tips: RwLock<BTreeMap<u64, HashSet<blake3::Hash>>>,
  83. /// A `HashSet` containg event IDs and their 1-level parents.
  84. /// These come from the events we've sent out using `EventPut`.
  85. /// They are used with `EventReq` to decide if we should reply
  86. /// or not. Additionally it is also used when we broadcast the
  87. /// `TipRep` message telling peers about our unreferenced tips.
  88. broadcasted_ids: RwLock<HashSet<blake3::Hash>>,
  89. /// DAG Pruning Task
  90. pub prune_task: OnceCell<StoppableTaskPtr>,
  91. /// Event publisher, this notifies whenever an event is
  92. /// inserted into the DAG
  93. pub event_pub: PublisherPtr<Event>,
  94. /// Current genesis event
  95. current_genesis: RwLock<Event>,
  96. /// Currently configured DAG rotation, in days
  97. days_rotation: u64,
  98. /// Flag signalling DAG has finished initial sync
  99. pub synced: RwLock<bool>,
  100. /// Enable graph debugging
  101. pub deg_enabled: RwLock<bool>,
  102. /// The publisher for which we can give deg info over
  103. deg_publisher: PublisherPtr<DegEvent>,
  104. }
  105. impl EventGraph {
  106. /// Create a new [`EventGraph`] instance.
  107. /// * `days_rotation` marks the lifetime of the DAG before it's pruned.
  108. pub async fn new(
  109. p2p: P2pPtr,
  110. sled_db: sled::Db,
  111. datastore: PathBuf,
  112. replay_mode: bool,
  113. dag_tree_name: &str,
  114. days_rotation: u64,
  115. ex: Arc<Executor<'_>>,
  116. ) -> Result<EventGraphPtr> {
  117. let dag = sled_db.open_tree(dag_tree_name)?;
  118. let unreferenced_tips = RwLock::new(BTreeMap::new());
  119. let broadcasted_ids = RwLock::new(HashSet::new());
  120. let event_pub = Publisher::new();
  121. // Create the current genesis event based on the `days_rotation`
  122. let current_genesis = generate_genesis(days_rotation);
  123. let self_ = Arc::new(Self {
  124. p2p,
  125. dag: dag.clone(),
  126. datastore,
  127. replay_mode,
  128. unreferenced_tips,
  129. broadcasted_ids,
  130. prune_task: OnceCell::new(),
  131. event_pub,
  132. current_genesis: RwLock::new(current_genesis.clone()),
  133. days_rotation,
  134. synced: RwLock::new(false),
  135. deg_enabled: RwLock::new(false),
  136. deg_publisher: Publisher::new(),
  137. });
  138. // Check if we have it in our DAG.
  139. // If not, we can prune the DAG and insert this new genesis event.
  140. if !dag.contains_key(current_genesis.id().as_bytes())? {
  141. info!(
  142. target: "event_graph::new()",
  143. "[EVENTGRAPH] DAG does not contain current genesis, pruning existing data",
  144. );
  145. self_.dag_prune(current_genesis).await?;
  146. }
  147. // Find the unreferenced tips in the current DAG state.
  148. *self_.unreferenced_tips.write().await = self_.find_unreferenced_tips().await;
  149. // Spawn the DAG pruning task
  150. if days_rotation > 0 {
  151. let prune_task = StoppableTask::new();
  152. let _ = self_.prune_task.set(prune_task.clone()).await;
  153. prune_task.clone().start(
  154. self_.clone().dag_prune_task(days_rotation),
  155. |_| async move {
  156. info!(target: "event_graph::_handle_stop()", "[EVENTGRAPH] Prune task stopped, flushing sled")
  157. },
  158. Error::DetachedTaskStopped,
  159. ex.clone(),
  160. );
  161. }
  162. Ok(self_)
  163. }
  164. pub fn days_rotation(&self) -> u64 {
  165. self.days_rotation
  166. }
  167. /// Sync the DAG from connected peers
  168. pub async fn dag_sync(&self) -> Result<()> {
  169. // We do an optimistic sync where we ask all our connected peers for
  170. // the latest layer DAG tips (unreferenced events) and then we accept
  171. // the ones we see the most times.
  172. // * Compare received tips with local ones, identify which we are missing.
  173. // * Request these from peers
  174. // * Recursively request these backward
  175. //
  176. // Verification:
  177. // * Timestamps should go backwards
  178. // * Cross-check with multiple peers, this means we should request the
  179. // same event from multiple peers and make sure it is the same.
  180. // * Since we should be pruning, if we're not synced after some reasonable
  181. // amount of iterations, these could be faulty peers and we can try again
  182. // from the beginning
  183. // Get references to all our peers.
  184. let channels = self.p2p.hosts().peers();
  185. let mut communicated_peers = channels.len();
  186. info!(
  187. target: "event_graph::dag_sync()",
  188. "[EVENTGRAPH] Syncing DAG from {} peers...", communicated_peers,
  189. );
  190. // Here we keep track of the tips, their layers and how many time we've seen them.
  191. let mut tips: HashMap<blake3::Hash, (u64, usize)> = HashMap::new();
  192. // Let's first ask all of our peers for their tips and collect them
  193. // in our hashmap above.
  194. for channel in channels.iter() {
  195. let url = channel.address();
  196. let tip_rep_sub = match channel.subscribe_msg::<TipRep>().await {
  197. Ok(v) => v,
  198. Err(e) => {
  199. error!(
  200. target: "event_graph::dag_sync()",
  201. "[EVENTGRAPH] Sync: Couldn't subscribe TipReq for peer {}, skipping ({})",
  202. url, e,
  203. );
  204. communicated_peers -= 1;
  205. continue
  206. }
  207. };
  208. if let Err(e) = channel.send(&TipReq {}).await {
  209. error!(
  210. target: "event_graph::dag_sync()",
  211. "[EVENTGRAPH] Sync: Couldn't contact peer {}, skipping ({})", url, e,
  212. );
  213. communicated_peers -= 1;
  214. continue
  215. };
  216. let peer_tips = match timeout(
  217. Duration::from_secs(self.p2p.settings().read().await.outbound_connect_timeout),
  218. tip_rep_sub.receive(),
  219. )
  220. .await
  221. {
  222. Ok(peer_tips) => peer_tips?,
  223. Err(_) => {
  224. error!(
  225. target: "event_graph::dag_sync()",
  226. "[EVENTGRAPH] Sync: Peer {} didn't reply with tips in time, skipping", url,
  227. );
  228. communicated_peers -= 1;
  229. continue
  230. }
  231. };
  232. let peer_tips = &peer_tips.0;
  233. // Note down the seen tips
  234. for (layer, layer_tips) in peer_tips {
  235. for tip in layer_tips {
  236. if let Some(seen_tip) = tips.get_mut(tip) {
  237. seen_tip.1 += 1;
  238. } else {
  239. tips.insert(*tip, (*layer, 1));
  240. }
  241. }
  242. }
  243. }
  244. // After we've communicated all the peers, let's see what happened.
  245. if tips.is_empty() {
  246. error!(
  247. target: "event_graph::dag_sync()",
  248. "[EVENTGRAPH] Sync: Could not find any DAG tips",
  249. );
  250. return Err(Error::DagSyncFailed)
  251. }
  252. // We know the number of peers we've communicated with,
  253. // so we will consider events we saw at more than 2/3 of
  254. // those peers.
  255. let consideration_threshold = communicated_peers * 2 / 3;
  256. let mut considered_tips = HashSet::new();
  257. for (tip, (_, amount)) in tips.iter() {
  258. if amount > &consideration_threshold {
  259. considered_tips.insert(*tip);
  260. }
  261. }
  262. drop(tips);
  263. // Now begin fetching the events backwards.
  264. let mut missing_parents = HashSet::new();
  265. for tip in considered_tips.iter() {
  266. assert!(tip != &NULL_ID);
  267. if !self.dag.contains_key(tip.as_bytes()).unwrap() {
  268. missing_parents.insert(*tip);
  269. }
  270. }
  271. if missing_parents.is_empty() {
  272. *self.synced.write().await = true;
  273. info!(target: "event_graph::dag_sync()", "[EVENTGRAPH] DAG synced successfully!");
  274. return Ok(())
  275. }
  276. info!(target: "event_graph::dag_sync()", "[EVENTGRAPH] Fetching events");
  277. let mut received_events: BTreeMap<u64, Vec<Event>> = BTreeMap::new();
  278. let mut received_events_hashes = HashSet::new();
  279. while !missing_parents.is_empty() {
  280. let mut found_event = false;
  281. for channel in channels.iter() {
  282. let url = channel.address();
  283. debug!(
  284. target: "event_graph::dag_sync()",
  285. "Requesting {:?} from {}...", missing_parents, url,
  286. );
  287. let ev_rep_sub = match channel.subscribe_msg::<EventRep>().await {
  288. Ok(v) => v,
  289. Err(e) => {
  290. error!(
  291. target: "event_graph::dag_sync()",
  292. "[EVENTGRAPH] Sync: Couldn't subscribe EventRep for peer {}, skipping ({})",
  293. url, e,
  294. );
  295. continue
  296. }
  297. };
  298. let request_missing_events = missing_parents.clone().into_iter().collect();
  299. if let Err(e) = channel.send(&EventReq(request_missing_events)).await {
  300. error!(
  301. target: "event_graph::dag_sync()",
  302. "[EVENTGRAPH] Sync: Failed communicating EventReq({:?}) to {}: {}",
  303. missing_parents, url, e,
  304. );
  305. continue
  306. }
  307. let parent = match timeout(
  308. Duration::from_secs(self.p2p.settings().read().await.outbound_connect_timeout),
  309. ev_rep_sub.receive(),
  310. )
  311. .await
  312. {
  313. Ok(parent) => parent,
  314. Err(_) => {
  315. error!(
  316. target: "event_graph::dag_sync()",
  317. "[EVENTGRAPH] Sync: Timeout waiting for parents {:?} from {}",
  318. missing_parents, url,
  319. );
  320. continue
  321. }
  322. };
  323. let parents = match parent {
  324. Ok(v) => v.0.clone(),
  325. Err(e) => {
  326. error!(
  327. target: "event_graph::dag_sync()",
  328. "[EVENTGRAPH] Sync: Failed receiving parents {:?}: {}",
  329. missing_parents, e,
  330. );
  331. continue
  332. }
  333. };
  334. for parent in parents {
  335. let parent_id = parent.id();
  336. if !missing_parents.contains(&parent_id) {
  337. error!(
  338. target: "event_graph::dag_sync()",
  339. "[EVENTGRAPH] Sync: Peer {} replied with a wrong event: {}",
  340. url, parent.id(),
  341. );
  342. continue
  343. }
  344. debug!(
  345. target: "event_graph::dag_sync()",
  346. "Got correct parent event {}", parent_id,
  347. );
  348. if let Some(layer_events) = received_events.get_mut(&parent.layer) {
  349. layer_events.push(parent.clone());
  350. } else {
  351. let layer_events = vec![parent.clone()];
  352. received_events.insert(parent.layer, layer_events);
  353. }
  354. received_events_hashes.insert(parent_id);
  355. missing_parents.remove(&parent_id);
  356. found_event = true;
  357. // See if we have the upper parents
  358. for upper_parent in parent.parents.iter() {
  359. if upper_parent == &NULL_ID {
  360. continue
  361. }
  362. if !missing_parents.contains(upper_parent) &&
  363. !received_events_hashes.contains(upper_parent) &&
  364. !self.dag.contains_key(upper_parent.as_bytes()).unwrap()
  365. {
  366. debug!(
  367. target: "event_graph::dag_sync()",
  368. "Found upper missing parent event{}", upper_parent,
  369. );
  370. missing_parents.insert(*upper_parent);
  371. }
  372. }
  373. }
  374. break
  375. }
  376. if !found_event {
  377. error!(
  378. target: "event_graph::dag_sync()",
  379. "[EVENTGRAPH] Sync: Failed to get all events",
  380. );
  381. return Err(Error::DagSyncFailed)
  382. }
  383. } // <-- while !missing_parents.is_empty
  384. // At this point we should've got all the events.
  385. // We should add them to the DAG.
  386. let mut events = vec![];
  387. for (_, tips) in received_events {
  388. for tip in tips {
  389. events.push(tip);
  390. }
  391. }
  392. self.dag_insert(&events).await?;
  393. *self.synced.write().await = true;
  394. info!(target: "event_graph::dag_sync()", "[EVENTGRAPH] DAG synced successfully!");
  395. Ok(())
  396. }
  397. /// Atomically prune the DAG and insert the given event as genesis.
  398. async fn dag_prune(&self, genesis_event: Event) -> Result<()> {
  399. debug!(target: "event_graph::dag_prune()", "Pruning DAG...");
  400. // Acquire exclusive locks to unreferenced_tips, broadcasted_ids and
  401. // current_genesis while this operation is happening. We do this to
  402. // ensure that during the pruning operation, no other operations are
  403. // able to access the intermediate state which could lead to producing
  404. // the wrong state after pruning.
  405. let mut unreferenced_tips = self.unreferenced_tips.write().await;
  406. let mut broadcasted_ids = self.broadcasted_ids.write().await;
  407. let mut current_genesis = self.current_genesis.write().await;
  408. // Atomically clear the DAG and write the new genesis event.
  409. let mut batch = sled::Batch::default();
  410. for key in self.dag.iter().keys() {
  411. batch.remove(key.unwrap());
  412. }
  413. batch.insert(genesis_event.id().as_bytes(), serialize_async(&genesis_event).await);
  414. debug!(target: "event_graph::dag_prune()", "Applying batch...");
  415. if let Err(e) = self.dag.apply_batch(batch) {
  416. panic!("Failed pruning DAG, sled apply_batch error: {}", e);
  417. }
  418. // Clear unreferenced tips and bcast ids
  419. *unreferenced_tips = BTreeMap::new();
  420. unreferenced_tips.insert(0, HashSet::from([genesis_event.id()]));
  421. *current_genesis = genesis_event;
  422. *broadcasted_ids = HashSet::new();
  423. drop(unreferenced_tips);
  424. drop(broadcasted_ids);
  425. drop(current_genesis);
  426. debug!(target: "event_graph::dag_prune()", "DAG pruned successfully");
  427. Ok(())
  428. }
  429. /// Background task periodically pruning the DAG.
  430. async fn dag_prune_task(self: Arc<Self>, days_rotation: u64) -> Result<()> {
  431. // The DAG should periodically be pruned. This can be a configurable
  432. // parameter. By pruning, we should deterministically replace the
  433. // genesis event (can use a deterministic timestamp) and drop everything
  434. // in the DAG, leaving just the new genesis event.
  435. debug!(target: "event_graph::dag_prune_task()", "Spawned background DAG pruning task");
  436. loop {
  437. // Find the next rotation timestamp:
  438. let next_rotation = next_rotation_timestamp(INITIAL_GENESIS, days_rotation);
  439. // Prepare the new genesis event
  440. let current_genesis = Event {
  441. timestamp: next_rotation,
  442. content: GENESIS_CONTENTS.to_vec(),
  443. parents: [NULL_ID; N_EVENT_PARENTS],
  444. layer: 0,
  445. };
  446. // Sleep until it's time to rotate.
  447. let s = seconds_until_next_rotation(next_rotation);
  448. debug!(target: "event_graph::dag_prune_task()", "Sleeping {}s until next DAG prune", s);
  449. sleep(s).await;
  450. debug!(target: "event_graph::dag_prune_task()", "Rotation period reached");
  451. // Trigger DAG prune
  452. self.dag_prune(current_genesis).await?;
  453. }
  454. }
  455. /// Atomically insert given events into the DAG and return the event IDs.
  456. /// All provided events must be valid. An overlay is used over the DAG tree,
  457. /// temporary writting each event in order. After all events have been
  458. /// validated and inserted successfully, we write the overlay to sled.
  459. /// This will append the new events into the unreferenced tips set, and
  460. /// remove the events' parents from it. It will also append the events'
  461. /// level-1 parents to the `broadcasted_ids` set, so the P2P protocol
  462. /// knows that any requests for them are actually legitimate.
  463. /// TODO: The `broadcasted_ids` set should periodically be pruned, when
  464. /// some sensible time has passed after broadcasting the event.
  465. pub async fn dag_insert(&self, events: &[Event]) -> Result<Vec<blake3::Hash>> {
  466. // Sanity check
  467. if events.is_empty() {
  468. return Ok(vec![])
  469. }
  470. // Acquire exclusive locks to `unreferenced_tips and broadcasted_ids`
  471. let mut unreferenced_tips = self.unreferenced_tips.write().await;
  472. let mut broadcasted_ids = self.broadcasted_ids.write().await;
  473. // Here we keep the IDs to return
  474. let mut ids = Vec::with_capacity(events.len());
  475. // Create an overlay over the DAG tree
  476. let mut overlay = SledTreeOverlay::new(&self.dag);
  477. // Grab genesis timestamp
  478. let genesis_timestamp = self.current_genesis.read().await.timestamp;
  479. // Iterate over given events to validate them and
  480. // write them to the overlay
  481. for event in events {
  482. let event_id = event.id();
  483. debug!(
  484. target: "event_graph::dag_insert()",
  485. "Inserting event {} into the DAG", event_id,
  486. );
  487. if !event
  488. .validate(&self.dag, genesis_timestamp, self.days_rotation, Some(&overlay))
  489. .await?
  490. {
  491. error!(target: "event_graph::dag_insert()", "Event {} is invalid!", event_id);
  492. return Err(Error::EventIsInvalid)
  493. }
  494. let event_se = serialize_async(event).await;
  495. // Add the event to the overlay
  496. overlay.insert(event_id.as_bytes(), &event_se)?;
  497. if self.replay_mode {
  498. replayer_log(&self.datastore, "insert".to_owned(), event_se)?;
  499. }
  500. // Note down the event ID to return
  501. ids.push(event_id);
  502. }
  503. // Aggregate changes into a single batch
  504. let batch = overlay.aggregate().unwrap();
  505. // Atomically apply the batch.
  506. // Panic if something is corrupted.
  507. if let Err(e) = self.dag.apply_batch(batch) {
  508. panic!("Failed applying dag_insert batch to sled: {}", e);
  509. }
  510. // Iterate over given events to update references and
  511. // send out notifications about them
  512. for event in events {
  513. let event_id = event.id();
  514. // Update the unreferenced DAG tips set
  515. debug!(
  516. target: "event_graph::dag_insert()",
  517. "Event {} parents {:#?}", event_id, event.parents,
  518. );
  519. for parent_id in event.parents.iter() {
  520. if parent_id != &NULL_ID {
  521. debug!(
  522. target: "event_graph::dag_insert()",
  523. "Removing {} from unreferenced_tips", parent_id,
  524. );
  525. // Iterate over unreferenced tips in previous layers
  526. // and remove the parent
  527. // NOTE: this might be too exhaustive, but the
  528. // assumption is that previous layers unreferenced
  529. // tips will be few.
  530. for (layer, tips) in unreferenced_tips.iter_mut() {
  531. if layer >= &event.layer {
  532. continue
  533. }
  534. tips.remove(parent_id);
  535. }
  536. broadcasted_ids.insert(*parent_id);
  537. }
  538. }
  539. unreferenced_tips.retain(|_, tips| !tips.is_empty());
  540. debug!(
  541. target: "event_graph::dag_insert()",
  542. "Adding {} to unreferenced tips", event_id,
  543. );
  544. if let Some(layer_tips) = unreferenced_tips.get_mut(&event.layer) {
  545. layer_tips.insert(event_id);
  546. } else {
  547. let mut layer_tips = HashSet::new();
  548. layer_tips.insert(event_id);
  549. unreferenced_tips.insert(event.layer, layer_tips);
  550. }
  551. // Send out notifications about the new event
  552. self.event_pub.notify(event.clone()).await;
  553. }
  554. // Drop the exclusive locks
  555. drop(unreferenced_tips);
  556. drop(broadcasted_ids);
  557. Ok(ids)
  558. }
  559. /// Fetch an event from the DAG
  560. pub async fn dag_get(&self, event_id: &blake3::Hash) -> Result<Option<Event>> {
  561. let Some(bytes) = self.dag.get(event_id.as_bytes())? else { return Ok(None) };
  562. let event: Event = deserialize_async(&bytes).await?;
  563. Ok(Some(event))
  564. }
  565. /// Get next layer along with its N_EVENT_PARENTS from the unreferenced
  566. /// tips of the DAG. Since tips are mapped by their layer, we go backwards
  567. /// until we fill the vector, ensuring we always use latest layers tips as
  568. /// parents.
  569. async fn get_next_layer_with_parents(&self) -> (u64, [blake3::Hash; N_EVENT_PARENTS]) {
  570. let unreferenced_tips = self.unreferenced_tips.read().await;
  571. let mut parents = [NULL_ID; N_EVENT_PARENTS];
  572. let mut index = 0;
  573. 'outer: for (_, tips) in unreferenced_tips.iter().rev() {
  574. for tip in tips.iter() {
  575. parents[index] = *tip;
  576. index += 1;
  577. if index >= N_EVENT_PARENTS {
  578. break 'outer
  579. }
  580. }
  581. }
  582. let next_layer = unreferenced_tips.last_key_value().unwrap().0 + 1;
  583. assert!(parents.iter().any(|x| x != &NULL_ID));
  584. (next_layer, parents)
  585. }
  586. /// Find the unreferenced tips in the current DAG state, mapped by their layers.
  587. async fn find_unreferenced_tips(&self) -> BTreeMap<u64, HashSet<blake3::Hash>> {
  588. // First get all the event IDs
  589. let mut tips = HashSet::new();
  590. for iter_elem in self.dag.iter() {
  591. let (id, _) = iter_elem.unwrap();
  592. let id = blake3::Hash::from_bytes((&id as &[u8]).try_into().unwrap());
  593. tips.insert(id);
  594. }
  595. // Iterate again to find unreferenced IDs
  596. for iter_elem in self.dag.iter() {
  597. let (_, event) = iter_elem.unwrap();
  598. let event: Event = deserialize_async(&event).await.unwrap();
  599. for parent in event.parents.iter() {
  600. tips.remove(parent);
  601. }
  602. }
  603. // Build the layers map
  604. let mut map: BTreeMap<u64, HashSet<blake3::Hash>> = BTreeMap::new();
  605. for tip in tips {
  606. let event = self.dag_get(&tip).await.unwrap().unwrap();
  607. if let Some(layer_tips) = map.get_mut(&event.layer) {
  608. layer_tips.insert(tip);
  609. } else {
  610. let mut layer_tips = HashSet::new();
  611. layer_tips.insert(tip);
  612. map.insert(event.layer, layer_tips);
  613. }
  614. }
  615. map
  616. }
  617. /// Internal function used for DAG sorting.
  618. async fn get_unreferenced_tips_sorted(&self) -> [blake3::Hash; N_EVENT_PARENTS] {
  619. let (_, tips) = self.get_next_layer_with_parents().await;
  620. // Convert the hash to BigUint for sorting
  621. let mut sorted: Vec<_> =
  622. tips.iter().map(|x| BigUint::from_bytes_be(x.as_bytes())).collect();
  623. sorted.sort_unstable();
  624. // Convert back to blake3
  625. let mut tips_sorted = [NULL_ID; N_EVENT_PARENTS];
  626. for (i, id) in sorted.iter().enumerate() {
  627. let mut bytes = id.to_bytes_be();
  628. // Ensure we have 32 bytes
  629. while bytes.len() < blake3::OUT_LEN {
  630. bytes.insert(0, 0);
  631. }
  632. tips_sorted[i] = blake3::Hash::from_bytes(bytes.try_into().unwrap());
  633. }
  634. tips_sorted
  635. }
  636. /// Perform a topological sort of the DAG.
  637. pub async fn order_events(&self) -> Vec<Event> {
  638. let mut ordered_events = VecDeque::new();
  639. let mut visited = HashSet::new();
  640. for tip in self.get_unreferenced_tips_sorted().await {
  641. if !visited.contains(&tip) && tip != NULL_ID {
  642. let tip = self.dag_get(&tip).await.unwrap().unwrap();
  643. ordered_events.extend(self.dfs_topological_sort(tip, &mut visited).await);
  644. }
  645. }
  646. let mut ord_events_vec = ordered_events.make_contiguous().to_vec();
  647. // Order events based on thier layer numbers, or based on timestamp if they are equal
  648. ord_events_vec
  649. .sort_unstable_by(|a, b| a.0.cmp(&b.0).then(b.1.timestamp.cmp(&a.1.timestamp)));
  650. ord_events_vec.iter().map(|a| a.1.clone()).collect::<Vec<Event>>()
  651. }
  652. /// We do a non-recursive DFS (<https://en.wikipedia.org/wiki/Depth-first_search>),
  653. /// and additionally we consider the timestamps.
  654. async fn dfs_topological_sort(
  655. &self,
  656. event: Event,
  657. visited: &mut HashSet<blake3::Hash>,
  658. ) -> VecDeque<(u64, Event)> {
  659. let mut ordered_events = VecDeque::new();
  660. let mut stack = VecDeque::new();
  661. let event_id = event.id();
  662. stack.push_back(event_id);
  663. while let Some(event_id) = stack.pop_front() {
  664. if !visited.contains(&event_id) && event_id != NULL_ID {
  665. visited.insert(event_id);
  666. if let Some(event) = self.dag_get(&event_id).await.unwrap() {
  667. for parent in event.parents.iter() {
  668. stack.push_back(*parent);
  669. }
  670. ordered_events.push_back((event.layer, event))
  671. }
  672. }
  673. }
  674. ordered_events
  675. }
  676. /// Enable graph debugging
  677. pub async fn deg_enable(&self) {
  678. *self.deg_enabled.write().await = true;
  679. warn!("[EVENTGRAPH] Graph debugging enabled!");
  680. }
  681. /// Disable graph debugging
  682. pub async fn deg_disable(&self) {
  683. *self.deg_enabled.write().await = false;
  684. warn!("[EVENTGRAPH] Graph debugging disabled!");
  685. }
  686. /// Subscribe to deg events
  687. pub async fn deg_subscribe(&self) -> Subscription<DegEvent> {
  688. self.deg_publisher.clone().subscribe().await
  689. }
  690. /// Send a deg notification over the publisher
  691. pub async fn deg_notify(&self, event: DegEvent) {
  692. self.deg_publisher.notify(event).await;
  693. }
  694. pub async fn eventgraph_info(&self, id: u16, _params: JsonValue) -> JsonResult {
  695. let mut graph = HashMap::new();
  696. for iter_elem in self.dag.iter() {
  697. let (id, val) = iter_elem.unwrap();
  698. let id = blake3::Hash::from_bytes((&id as &[u8]).try_into().unwrap());
  699. let val: Event = deserialize_async(&val).await.unwrap();
  700. graph.insert(id, val);
  701. }
  702. let json_graph = graph
  703. .into_iter()
  704. .map(|(k, v)| {
  705. let key = k.to_string();
  706. let value = JsonValue::from(v);
  707. (key, value)
  708. })
  709. .collect();
  710. let values = json_map([("dag", JsonValue::Object(json_graph))]);
  711. let result = JsonValue::Object(HashMap::from([("eventgraph_info".to_string(), values)]));
  712. JsonResponse::new(result, id).into()
  713. }
  714. }