mod.rs 32 KB

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