mod.rs 31 KB

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