mod.rs 32 KB

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