mod.rs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  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 num_bigint::BigUint;
  25. use sled_overlay::{sled, SledTreeOverlay};
  26. use smol::{
  27. lock::{OnceCell, RwLock},
  28. Executor,
  29. };
  30. use tinyjson::JsonValue::{self};
  31. use tracing::{debug, error, info, warn};
  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 {communicated_peers} 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.display_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 {url}, skipping ({e})"
  215. );
  216. communicated_peers -= 1;
  217. continue
  218. }
  219. };
  220. if let Err(e) = channel.send(&TipReq {}).await {
  221. error!(
  222. target: "event_graph::dag_sync()",
  223. "[EVENTGRAPH] Sync: Couldn't contact peer {url}, skipping ({e})"
  224. );
  225. communicated_peers -= 1;
  226. continue
  227. };
  228. // Node waits for response
  229. let Ok(peer_tips) = tip_rep_sub
  230. .receive_with_timeout(self.p2p.settings().read().await.outbound_connect_timeout)
  231. .await
  232. else {
  233. error!(
  234. target: "event_graph::dag_sync()",
  235. "[EVENTGRAPH] Sync: Peer {url} didn't reply with tips in time, skipping"
  236. );
  237. communicated_peers -= 1;
  238. continue
  239. };
  240. let peer_tips = &peer_tips.0;
  241. // Note down the seen tips
  242. for (layer, layer_tips) in peer_tips {
  243. for tip in layer_tips {
  244. if let Some(seen_tip) = tips.get_mut(tip) {
  245. seen_tip.1 += 1;
  246. } else {
  247. tips.insert(*tip, (*layer, 1));
  248. }
  249. }
  250. }
  251. }
  252. // After we've communicated all the peers, let's see what happened.
  253. if tips.is_empty() {
  254. error!(
  255. target: "event_graph::dag_sync()",
  256. "[EVENTGRAPH] Sync: Could not find any DAG tips",
  257. );
  258. return Err(Error::DagSyncFailed)
  259. }
  260. // We know the number of peers we've communicated with,
  261. // so we will consider events we saw at more than 2/3 of
  262. // those peers.
  263. let consideration_threshold = communicated_peers * 2 / 3;
  264. let mut considered_tips = HashSet::new();
  265. for (tip, (_, amount)) in tips.iter() {
  266. if amount > &consideration_threshold {
  267. considered_tips.insert(*tip);
  268. }
  269. }
  270. drop(tips);
  271. // Now begin fetching the events backwards.
  272. let mut missing_parents = HashSet::new();
  273. for tip in considered_tips.iter() {
  274. assert!(tip != &NULL_ID);
  275. if !self.dag.contains_key(tip.as_bytes()).unwrap() {
  276. missing_parents.insert(*tip);
  277. }
  278. }
  279. if missing_parents.is_empty() {
  280. *self.synced.write().await = true;
  281. info!(target: "event_graph::dag_sync()", "[EVENTGRAPH] DAG synced successfully!");
  282. return Ok(())
  283. }
  284. info!(target: "event_graph::dag_sync()", "[EVENTGRAPH] Fetching events");
  285. let mut received_events: BTreeMap<u64, Vec<Event>> = BTreeMap::new();
  286. let mut received_events_hashes = HashSet::new();
  287. while !missing_parents.is_empty() {
  288. let mut found_event = false;
  289. for channel in channels.iter() {
  290. let url = channel.display_address();
  291. debug!(
  292. target: "event_graph::dag_sync()",
  293. "Requesting {missing_parents:?} from {url}..."
  294. );
  295. let ev_rep_sub = match channel.subscribe_msg::<EventRep>().await {
  296. Ok(v) => v,
  297. Err(e) => {
  298. error!(
  299. target: "event_graph::dag_sync()",
  300. "[EVENTGRAPH] Sync: Couldn't subscribe EventRep for peer {url}, skipping ({e})"
  301. );
  302. continue
  303. }
  304. };
  305. let request_missing_events = missing_parents.clone().into_iter().collect();
  306. if let Err(e) = channel.send(&EventReq(request_missing_events)).await {
  307. error!(
  308. target: "event_graph::dag_sync()",
  309. "[EVENTGRAPH] Sync: Failed communicating EventReq({missing_parents:?}) to {url}: {e}"
  310. );
  311. continue
  312. }
  313. // Node waits for response
  314. let Ok(parent) = ev_rep_sub
  315. .receive_with_timeout(self.p2p.settings().read().await.outbound_connect_timeout)
  316. .await
  317. else {
  318. error!(
  319. target: "event_graph::dag_sync()",
  320. "[EVENTGRAPH] Sync: Timeout waiting for parents {missing_parents:?} from {url}"
  321. );
  322. continue
  323. };
  324. let parents = parent.0.clone();
  325. for parent in parents {
  326. let parent_id = parent.id();
  327. if !missing_parents.contains(&parent_id) {
  328. error!(
  329. target: "event_graph::dag_sync()",
  330. "[EVENTGRAPH] Sync: Peer {url} replied with a wrong event: {}",
  331. parent.id()
  332. );
  333. continue
  334. }
  335. debug!(
  336. target: "event_graph::dag_sync()",
  337. "Got correct parent event {parent_id}"
  338. );
  339. if let Some(layer_events) = received_events.get_mut(&parent.layer) {
  340. layer_events.push(parent.clone());
  341. } else {
  342. let layer_events = vec![parent.clone()];
  343. received_events.insert(parent.layer, layer_events);
  344. }
  345. received_events_hashes.insert(parent_id);
  346. missing_parents.remove(&parent_id);
  347. found_event = true;
  348. // See if we have the upper parents
  349. for upper_parent in parent.parents.iter() {
  350. if upper_parent == &NULL_ID {
  351. continue
  352. }
  353. if !missing_parents.contains(upper_parent) &&
  354. !received_events_hashes.contains(upper_parent) &&
  355. !self.dag.contains_key(upper_parent.as_bytes()).unwrap()
  356. {
  357. debug!(
  358. target: "event_graph::dag_sync()",
  359. "Found upper missing parent event {upper_parent}"
  360. );
  361. missing_parents.insert(*upper_parent);
  362. }
  363. }
  364. }
  365. break
  366. }
  367. if !found_event {
  368. error!(
  369. target: "event_graph::dag_sync()",
  370. "[EVENTGRAPH] Sync: Failed to get all events",
  371. );
  372. return Err(Error::DagSyncFailed)
  373. }
  374. } // <-- while !missing_parents.is_empty
  375. // At this point we should've got all the events.
  376. // We should add them to the DAG.
  377. let mut events = vec![];
  378. for (_, tips) in received_events {
  379. for tip in tips {
  380. events.push(tip);
  381. }
  382. }
  383. self.dag_insert(&events).await?;
  384. *self.synced.write().await = true;
  385. info!(target: "event_graph::dag_sync()", "[EVENTGRAPH] DAG synced successfully!");
  386. Ok(())
  387. }
  388. /// Atomically prune the DAG and insert the given event as genesis.
  389. async fn dag_prune(&self, genesis_event: Event) -> Result<()> {
  390. debug!(target: "event_graph::dag_prune()", "Pruning DAG...");
  391. // Acquire exclusive locks to unreferenced_tips, broadcasted_ids and
  392. // current_genesis while this operation is happening. We do this to
  393. // ensure that during the pruning operation, no other operations are
  394. // able to access the intermediate state which could lead to producing
  395. // the wrong state after pruning.
  396. let mut unreferenced_tips = self.unreferenced_tips.write().await;
  397. let mut broadcasted_ids = self.broadcasted_ids.write().await;
  398. let mut current_genesis = self.current_genesis.write().await;
  399. // Atomically clear the DAG and write the new genesis event.
  400. let mut batch = sled::Batch::default();
  401. for key in self.dag.iter().keys() {
  402. batch.remove(key.unwrap());
  403. }
  404. batch.insert(genesis_event.id().as_bytes(), serialize_async(&genesis_event).await);
  405. debug!(target: "event_graph::dag_prune()", "Applying batch...");
  406. if let Err(e) = self.dag.apply_batch(batch) {
  407. panic!("Failed pruning DAG, sled apply_batch error: {e}");
  408. }
  409. // Clear unreferenced tips and bcast ids
  410. *unreferenced_tips = BTreeMap::new();
  411. unreferenced_tips.insert(0, HashSet::from([genesis_event.id()]));
  412. *current_genesis = genesis_event;
  413. *broadcasted_ids = HashSet::new();
  414. drop(unreferenced_tips);
  415. drop(broadcasted_ids);
  416. drop(current_genesis);
  417. debug!(target: "event_graph::dag_prune()", "DAG pruned successfully");
  418. Ok(())
  419. }
  420. /// Background task periodically pruning the DAG.
  421. async fn dag_prune_task(self: Arc<Self>, days_rotation: u64) -> Result<()> {
  422. // The DAG should periodically be pruned. This can be a configurable
  423. // parameter. By pruning, we should deterministically replace the
  424. // genesis event (can use a deterministic timestamp) and drop everything
  425. // in the DAG, leaving just the new genesis event.
  426. debug!(target: "event_graph::dag_prune_task()", "Spawned background DAG pruning task");
  427. loop {
  428. // Find the next rotation timestamp:
  429. let next_rotation = next_rotation_timestamp(INITIAL_GENESIS, days_rotation);
  430. // Prepare the new genesis event
  431. let current_genesis = Event {
  432. timestamp: next_rotation,
  433. content: GENESIS_CONTENTS.to_vec(),
  434. parents: [NULL_ID; N_EVENT_PARENTS],
  435. layer: 0,
  436. };
  437. // Sleep until it's time to rotate.
  438. let s = millis_until_next_rotation(next_rotation);
  439. debug!(target: "event_graph::dag_prune_task()", "Sleeping {s}ms until next DAG prune");
  440. msleep(s).await;
  441. debug!(target: "event_graph::dag_prune_task()", "Rotation period reached");
  442. // Trigger DAG prune
  443. self.dag_prune(current_genesis).await?;
  444. }
  445. }
  446. /// Atomically insert given events into the DAG and return the event IDs.
  447. /// All provided events must be valid. An overlay is used over the DAG tree,
  448. /// temporary writting each event in order. After all events have been
  449. /// validated and inserted successfully, we write the overlay to sled.
  450. /// This will append the new events into the unreferenced tips set, and
  451. /// remove the events' parents from it. It will also append the events'
  452. /// level-1 parents to the `broadcasted_ids` set, so the P2P protocol
  453. /// knows that any requests for them are actually legitimate.
  454. /// TODO: The `broadcasted_ids` set should periodically be pruned, when
  455. /// some sensible time has passed after broadcasting the event.
  456. pub async fn dag_insert(&self, events: &[Event]) -> Result<Vec<blake3::Hash>> {
  457. // Sanity check
  458. if events.is_empty() {
  459. return Ok(vec![])
  460. }
  461. // Acquire exclusive locks to `unreferenced_tips and broadcasted_ids`
  462. let mut unreferenced_tips = self.unreferenced_tips.write().await;
  463. let mut broadcasted_ids = self.broadcasted_ids.write().await;
  464. // Here we keep the IDs to return
  465. let mut ids = Vec::with_capacity(events.len());
  466. // Create an overlay over the DAG tree
  467. let mut overlay = SledTreeOverlay::new(&self.dag);
  468. // Grab genesis timestamp
  469. let genesis_timestamp = self.current_genesis.read().await.timestamp;
  470. // Iterate over given events to validate them and
  471. // write them to the overlay
  472. for event in events {
  473. let event_id = event.id();
  474. debug!(
  475. target: "event_graph::dag_insert()",
  476. "Inserting event {event_id} into the DAG"
  477. );
  478. if !event
  479. .validate(&self.dag, genesis_timestamp, self.days_rotation, Some(&overlay))
  480. .await?
  481. {
  482. error!(target: "event_graph::dag_insert()", "Event {event_id} is invalid!");
  483. return Err(Error::EventIsInvalid)
  484. }
  485. let event_se = serialize_async(event).await;
  486. // Add the event to the overlay
  487. overlay.insert(event_id.as_bytes(), &event_se)?;
  488. if self.replay_mode {
  489. replayer_log(&self.datastore, "insert".to_owned(), event_se)?;
  490. }
  491. // Note down the event ID to return
  492. ids.push(event_id);
  493. }
  494. // Aggregate changes into a single batch
  495. let batch = overlay.aggregate().unwrap();
  496. // Atomically apply the batch.
  497. // Panic if something is corrupted.
  498. if let Err(e) = self.dag.apply_batch(batch) {
  499. panic!("Failed applying dag_insert batch to sled: {e}");
  500. }
  501. // Iterate over given events to update references and
  502. // send out notifications about them
  503. for event in events {
  504. let event_id = event.id();
  505. // Update the unreferenced DAG tips set
  506. debug!(
  507. target: "event_graph::dag_insert()",
  508. "Event {event_id} parents {:#?}", event.parents,
  509. );
  510. for parent_id in event.parents.iter() {
  511. if parent_id != &NULL_ID {
  512. debug!(
  513. target: "event_graph::dag_insert()",
  514. "Removing {parent_id} from unreferenced_tips"
  515. );
  516. // Iterate over unreferenced tips in previous layers
  517. // and remove the parent
  518. // NOTE: this might be too exhaustive, but the
  519. // assumption is that previous layers unreferenced
  520. // tips will be few.
  521. for (layer, tips) in unreferenced_tips.iter_mut() {
  522. if layer >= &event.layer {
  523. continue
  524. }
  525. tips.remove(parent_id);
  526. }
  527. broadcasted_ids.insert(*parent_id);
  528. }
  529. }
  530. unreferenced_tips.retain(|_, tips| !tips.is_empty());
  531. debug!(
  532. target: "event_graph::dag_insert()",
  533. "Adding {event_id} to unreferenced tips"
  534. );
  535. if let Some(layer_tips) = unreferenced_tips.get_mut(&event.layer) {
  536. layer_tips.insert(event_id);
  537. } else {
  538. let mut layer_tips = HashSet::new();
  539. layer_tips.insert(event_id);
  540. unreferenced_tips.insert(event.layer, layer_tips);
  541. }
  542. // Send out notifications about the new event
  543. self.event_pub.notify(event.clone()).await;
  544. }
  545. // Drop the exclusive locks
  546. drop(unreferenced_tips);
  547. drop(broadcasted_ids);
  548. Ok(ids)
  549. }
  550. /// Fetch an event from the DAG
  551. pub async fn dag_get(&self, event_id: &blake3::Hash) -> Result<Option<Event>> {
  552. let Some(bytes) = self.dag.get(event_id.as_bytes())? else { return Ok(None) };
  553. let event: Event = deserialize_async(&bytes).await?;
  554. Ok(Some(event))
  555. }
  556. /// Get next layer along with its N_EVENT_PARENTS from the unreferenced
  557. /// tips of the DAG. Since tips are mapped by their layer, we go backwards
  558. /// until we fill the vector, ensuring we always use latest layers tips as
  559. /// parents.
  560. async fn get_next_layer_with_parents(&self) -> (u64, [blake3::Hash; N_EVENT_PARENTS]) {
  561. let unreferenced_tips = self.unreferenced_tips.read().await;
  562. let mut parents = [NULL_ID; N_EVENT_PARENTS];
  563. let mut index = 0;
  564. 'outer: for (_, tips) in unreferenced_tips.iter().rev() {
  565. for tip in tips.iter() {
  566. parents[index] = *tip;
  567. index += 1;
  568. if index >= N_EVENT_PARENTS {
  569. break 'outer
  570. }
  571. }
  572. }
  573. let next_layer = unreferenced_tips.last_key_value().unwrap().0 + 1;
  574. assert!(parents.iter().any(|x| x != &NULL_ID));
  575. (next_layer, parents)
  576. }
  577. /// Find the unreferenced tips in the current DAG state, mapped by their layers.
  578. async fn find_unreferenced_tips(&self) -> BTreeMap<u64, HashSet<blake3::Hash>> {
  579. // First get all the event IDs
  580. let mut tips = HashSet::new();
  581. for iter_elem in self.dag.iter() {
  582. let (id, _) = iter_elem.unwrap();
  583. let id = blake3::Hash::from_bytes((&id as &[u8]).try_into().unwrap());
  584. tips.insert(id);
  585. }
  586. // Iterate again to find unreferenced IDs
  587. for iter_elem in self.dag.iter() {
  588. let (_, event) = iter_elem.unwrap();
  589. let event: Event = deserialize_async(&event).await.unwrap();
  590. for parent in event.parents.iter() {
  591. tips.remove(parent);
  592. }
  593. }
  594. // Build the layers map
  595. let mut map: BTreeMap<u64, HashSet<blake3::Hash>> = BTreeMap::new();
  596. for tip in tips {
  597. let event = self.dag_get(&tip).await.unwrap().unwrap();
  598. if let Some(layer_tips) = map.get_mut(&event.layer) {
  599. layer_tips.insert(tip);
  600. } else {
  601. let mut layer_tips = HashSet::new();
  602. layer_tips.insert(tip);
  603. map.insert(event.layer, layer_tips);
  604. }
  605. }
  606. map
  607. }
  608. /// Internal function used for DAG sorting.
  609. async fn get_unreferenced_tips_sorted(&self) -> [blake3::Hash; N_EVENT_PARENTS] {
  610. let (_, tips) = self.get_next_layer_with_parents().await;
  611. // Convert the hash to BigUint for sorting
  612. let mut sorted: Vec<_> =
  613. tips.iter().map(|x| BigUint::from_bytes_be(x.as_bytes())).collect();
  614. sorted.sort_unstable();
  615. // Convert back to blake3
  616. let mut tips_sorted = [NULL_ID; N_EVENT_PARENTS];
  617. for (i, id) in sorted.iter().enumerate() {
  618. let mut bytes = id.to_bytes_be();
  619. // Ensure we have 32 bytes
  620. while bytes.len() < blake3::OUT_LEN {
  621. bytes.insert(0, 0);
  622. }
  623. tips_sorted[i] = blake3::Hash::from_bytes(bytes.try_into().unwrap());
  624. }
  625. tips_sorted
  626. }
  627. /// Perform a topological sort of the DAG.
  628. pub async fn order_events(&self) -> Vec<Event> {
  629. let mut ordered_events = VecDeque::new();
  630. let mut visited = HashSet::new();
  631. for tip in self.get_unreferenced_tips_sorted().await {
  632. if !visited.contains(&tip) && tip != NULL_ID {
  633. let tip = self.dag_get(&tip).await.unwrap().unwrap();
  634. ordered_events.extend(self.dfs_topological_sort(tip, &mut visited).await);
  635. }
  636. }
  637. let mut ord_events_vec = ordered_events.make_contiguous().to_vec();
  638. // Order events based on thier layer numbers, or based on timestamp if they are equal
  639. ord_events_vec
  640. .sort_unstable_by(|a, b| a.0.cmp(&b.0).then(b.1.timestamp.cmp(&a.1.timestamp)));
  641. ord_events_vec.iter().map(|a| a.1.clone()).collect::<Vec<Event>>()
  642. }
  643. /// We do a non-recursive DFS (<https://en.wikipedia.org/wiki/Depth-first_search>),
  644. /// and additionally we consider the timestamps.
  645. async fn dfs_topological_sort(
  646. &self,
  647. event: Event,
  648. visited: &mut HashSet<blake3::Hash>,
  649. ) -> VecDeque<(u64, Event)> {
  650. let mut ordered_events = VecDeque::new();
  651. let mut stack = VecDeque::new();
  652. let event_id = event.id();
  653. stack.push_back(event_id);
  654. while let Some(event_id) = stack.pop_front() {
  655. if !visited.contains(&event_id) && event_id != NULL_ID {
  656. visited.insert(event_id);
  657. if let Some(event) = self.dag_get(&event_id).await.unwrap() {
  658. for parent in event.parents.iter() {
  659. stack.push_back(*parent);
  660. }
  661. ordered_events.push_back((event.layer, event))
  662. }
  663. }
  664. }
  665. ordered_events
  666. }
  667. /// Enable graph debugging
  668. pub async fn deg_enable(&self) {
  669. *self.deg_enabled.write().await = true;
  670. warn!("[EVENTGRAPH] Graph debugging enabled!");
  671. }
  672. /// Disable graph debugging
  673. pub async fn deg_disable(&self) {
  674. *self.deg_enabled.write().await = false;
  675. warn!("[EVENTGRAPH] Graph debugging disabled!");
  676. }
  677. /// Subscribe to deg events
  678. pub async fn deg_subscribe(&self) -> Subscription<DegEvent> {
  679. self.deg_publisher.clone().subscribe().await
  680. }
  681. /// Send a deg notification over the publisher
  682. pub async fn deg_notify(&self, event: DegEvent) {
  683. self.deg_publisher.notify(event).await;
  684. }
  685. pub async fn eventgraph_info(&self, id: u16, _params: JsonValue) -> JsonResult {
  686. let mut graph = HashMap::new();
  687. for iter_elem in self.dag.iter() {
  688. let (id, val) = iter_elem.unwrap();
  689. let id = blake3::Hash::from_bytes((&id as &[u8]).try_into().unwrap());
  690. let val: Event = deserialize_async(&val).await.unwrap();
  691. graph.insert(id, val);
  692. }
  693. let json_graph = graph
  694. .into_iter()
  695. .map(|(k, v)| {
  696. let key = k.to_string();
  697. let value = JsonValue::from(v);
  698. (key, value)
  699. })
  700. .collect();
  701. let values = json_map([("dag", JsonValue::Object(json_graph))]);
  702. let result = JsonValue::Object(HashMap::from([("eventgraph_info".to_string(), values)]));
  703. JsonResponse::new(result, id).into()
  704. }
  705. /// Fetch all the events that are on a higher layers than the
  706. /// provided ones.
  707. pub async fn fetch_successors_of(
  708. &self,
  709. tips: BTreeMap<u64, HashSet<blake3::Hash>>,
  710. ) -> Result<Vec<Event>> {
  711. debug!(
  712. target: "event_graph::fetch_successors_of()",
  713. "fetching successors of {tips:?}"
  714. );
  715. let mut graph = HashMap::new();
  716. for iter_elem in self.dag.iter() {
  717. let (id, val) = iter_elem.unwrap();
  718. let hash = blake3::Hash::from_bytes((&id as &[u8]).try_into().unwrap());
  719. let event: Event = deserialize_async(&val).await.unwrap();
  720. graph.insert(hash, event);
  721. }
  722. let mut result = vec![];
  723. 'outer: for tip in tips.iter() {
  724. for i in tip.1.iter() {
  725. if !graph.contains_key(i) {
  726. continue 'outer;
  727. }
  728. }
  729. for (_, ev) in graph.iter() {
  730. if ev.layer > *tip.0 && !result.contains(ev) {
  731. result.push(ev.clone())
  732. }
  733. }
  734. }
  735. result.sort_by(|a, b| a.layer.cmp(&b.layer));
  736. Ok(result)
  737. }
  738. }