proto.rs 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 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, HashSet, VecDeque},
  20. slice,
  21. str::FromStr,
  22. sync::{
  23. atomic::{AtomicUsize, Ordering::SeqCst},
  24. Arc,
  25. },
  26. };
  27. use darkfi_sdk::{
  28. crypto::{poseidon_hash, util::FieldElemAsStr},
  29. pasta::pallas,
  30. };
  31. use darkfi_serial::{
  32. async_trait, deserialize_async, deserialize_async_partial, serialize_async, SerialDecodable,
  33. SerialEncodable,
  34. };
  35. use smol::Executor;
  36. use tracing::{debug, error, info, trace, warn};
  37. use super::{
  38. event::Header,
  39. rln::{closest_epoch, create_slash_proof, hash_event, sss_recover, MessageMetadata, RLNNode},
  40. Event, EventGraphPtr, LayerUTips, NULL_ID, NULL_PARENTS,
  41. };
  42. use crate::{
  43. event_graph::rln::{read_register_vk, read_signal_vk, read_slash_pk, read_slash_vk, Blob},
  44. impl_p2p_message,
  45. net::{
  46. metering::{MeteringConfiguration, DEFAULT_METERING_CONFIGURATION},
  47. ChannelPtr, Message, MessageSubscription, ProtocolBase, ProtocolBasePtr,
  48. ProtocolJobsManager, ProtocolJobsManagerPtr,
  49. },
  50. system::msleep,
  51. util::time::NanoTimestamp,
  52. zk::Proof,
  53. Error, Result,
  54. };
  55. /// Malicious behaviour threshold. If the threshold is reached, we will
  56. /// drop the peer from our P2P connection.
  57. const MALICIOUS_THRESHOLD: usize = 5;
  58. /// Global limit of messages per window
  59. const WINDOW_MAXSIZE: usize = 200;
  60. /// Rolling length of the window
  61. const WINDOW_EXPIRY_TIME: NanoTimestamp = NanoTimestamp::from_secs(60);
  62. /// Rolling length of the window
  63. const RATELIMIT_EXPIRY_TIME: NanoTimestamp = NanoTimestamp::from_secs(10);
  64. /// Ratelimit kicks in above this count
  65. const RATELIMIT_MIN_COUNT: usize = 6;
  66. /// Sample point used to calculate sleep time when ratelimit is active
  67. const RATELIMIT_SAMPLE_IDX: usize = 10;
  68. /// Sleep for this amount of time when `count == RATE_LIMIT_SAMPLE_IDX`.
  69. const RATELIMIT_SAMPLE_SLEEP: usize = 1000;
  70. struct MovingWindow {
  71. times: VecDeque<NanoTimestamp>,
  72. expiry_time: NanoTimestamp,
  73. }
  74. impl MovingWindow {
  75. fn new(expiry_time: NanoTimestamp) -> Self {
  76. Self { times: VecDeque::new(), expiry_time }
  77. }
  78. /// Clean out expired timestamps from the window.
  79. fn clean(&mut self) {
  80. while let Some(ts) = self.times.front() {
  81. let Ok(elapsed) = ts.elapsed() else {
  82. debug!(target: "event_graph::protocol::MovingWindow::clean", "Timestamp [{ts}] is in future. Removing...");
  83. let _ = self.times.pop_front();
  84. continue
  85. };
  86. if elapsed < self.expiry_time {
  87. break
  88. }
  89. let _ = self.times.pop_front();
  90. }
  91. }
  92. /// Add new timestamp
  93. fn ticktock(&mut self) {
  94. self.clean();
  95. self.times.push_back(NanoTimestamp::current_time());
  96. }
  97. #[inline]
  98. fn count(&self) -> usize {
  99. self.times.len()
  100. }
  101. }
  102. /// P2P protocol implementation for the Event Graph.
  103. pub struct ProtocolEventGraph {
  104. /// Pointer to the connected peer
  105. channel: ChannelPtr,
  106. /// Pointer to the Event Graph instance
  107. event_graph: EventGraphPtr,
  108. /// `MessageSubscriber` for `EventPut`
  109. ev_put_sub: MessageSubscription<EventPut>,
  110. /// `MessageSubscriber` for `StaticPut`
  111. st_put_sub: MessageSubscription<StaticPut>,
  112. /// `MessageSubscriber` for `EventReq`
  113. ev_req_sub: MessageSubscription<EventReq>,
  114. /// `MessageSubscriber` for `EventRep`
  115. ev_rep_sub: MessageSubscription<EventRep>,
  116. /// `MessageSubscriber` for `HeaderPut`
  117. _hdr_put_sub: MessageSubscription<HeaderPut>,
  118. /// `MessageSubscriber` for `HeaderReq`
  119. hdr_req_sub: MessageSubscription<HeaderReq>,
  120. /// `MessageSubscriber` for `HeaderRep`
  121. _hdr_rep_sub: MessageSubscription<HeaderRep>,
  122. /// `MessageSubscriber` for `TipReq`
  123. tip_req_sub: MessageSubscription<TipReq>,
  124. /// `MessageSubscriber` for `TipRep`
  125. _tip_rep_sub: MessageSubscription<TipRep>,
  126. /// Peer malicious message count
  127. malicious_count: AtomicUsize,
  128. /// P2P jobs manager pointer
  129. jobsman: ProtocolJobsManagerPtr,
  130. /// To apply the rate-limit, we don't broadcast directly but instead send into the
  131. /// sending queue.
  132. broadcaster_push: smol::channel::Sender<EventPut>,
  133. /// Receive send requests and rate-limit broadcasting them.
  134. broadcaster_pull: smol::channel::Receiver<EventPut>,
  135. }
  136. /// A P2P message representing publishing an event on the network
  137. #[derive(Clone, SerialEncodable, SerialDecodable)]
  138. pub struct EventPut(pub Event, pub Vec<u8>);
  139. impl_p2p_message!(EventPut, "EventGraph::EventPut", 0, 0, DEFAULT_METERING_CONFIGURATION);
  140. /// A P2P message representing publishing an event of a static graph
  141. /// (most likely RLN_identities) on the network
  142. #[derive(Clone, SerialEncodable, SerialDecodable)]
  143. pub struct StaticPut(pub Event, pub Vec<u8>);
  144. impl_p2p_message!(StaticPut, "EventGraph::StaticPut", 0, 0, DEFAULT_METERING_CONFIGURATION);
  145. /// A P2P message representing an event request
  146. #[derive(Clone, SerialEncodable, SerialDecodable)]
  147. pub struct EventReq(pub Vec<blake3::Hash>);
  148. impl_p2p_message!(EventReq, "EventGraph::EventReq", 0, 0, DEFAULT_METERING_CONFIGURATION);
  149. /// A P2P message representing an event reply
  150. #[derive(Clone, SerialEncodable, SerialDecodable)]
  151. pub struct EventRep(pub Vec<Event>);
  152. impl_p2p_message!(EventRep, "EventGraph::EventRep", 0, 0, DEFAULT_METERING_CONFIGURATION);
  153. /// A P2P message representing publishing an event's header on the network
  154. #[derive(Clone, SerialEncodable, SerialDecodable)]
  155. pub struct HeaderPut(pub Header);
  156. impl_p2p_message!(HeaderPut, "EventGraph::HeaderPut", 0, 0, DEFAULT_METERING_CONFIGURATION);
  157. /// A P2P message representing a header request
  158. #[derive(Clone, SerialEncodable, SerialDecodable)]
  159. pub struct HeaderReq(pub String, pub LayerUTips);
  160. impl_p2p_message!(HeaderReq, "EventGraph::HeaderReq", 0, 0, DEFAULT_METERING_CONFIGURATION);
  161. /// A P2P message representing a header reply
  162. #[derive(Clone, SerialEncodable, SerialDecodable)]
  163. pub struct HeaderRep(pub Vec<Header>);
  164. impl_p2p_message!(HeaderRep, "EventGraph::HeaderRep", 0, 0, DEFAULT_METERING_CONFIGURATION);
  165. /// A P2P message representing a request for a peer's DAG tips
  166. #[derive(Clone, SerialEncodable, SerialDecodable)]
  167. pub struct TipReq(pub String);
  168. impl_p2p_message!(TipReq, "EventGraph::TipReq", 0, 0, DEFAULT_METERING_CONFIGURATION);
  169. /// A P2P message representing a reply for the peer's DAG tips
  170. #[derive(Clone, SerialEncodable, SerialDecodable)]
  171. pub struct TipRep(pub LayerUTips);
  172. impl_p2p_message!(TipRep, "EventGraph::TipRep", 0, 0, DEFAULT_METERING_CONFIGURATION);
  173. #[async_trait]
  174. impl ProtocolBase for ProtocolEventGraph {
  175. async fn start(self: Arc<Self>, ex: Arc<Executor<'_>>) -> Result<()> {
  176. self.jobsman.clone().start(ex.clone());
  177. self.jobsman.clone().spawn(self.clone().handle_event_put(), ex.clone()).await;
  178. self.jobsman.clone().spawn(self.clone().handle_static_put(), ex.clone()).await;
  179. self.jobsman.clone().spawn(self.clone().handle_event_req(), ex.clone()).await;
  180. // self.jobsman.clone().spawn(self.clone().handle_header_put(), ex.clone()).await;
  181. // self.jobsman.clone().spawn(self.clone().handle_header_req(), ex.clone()).await;
  182. self.jobsman.clone().spawn(self.clone().handle_header_req(), ex.clone()).await;
  183. self.jobsman.clone().spawn(self.clone().handle_tip_req(), ex.clone()).await;
  184. self.jobsman.clone().spawn(self.clone().broadcast_rate_limiter(), ex.clone()).await;
  185. Ok(())
  186. }
  187. fn name(&self) -> &'static str {
  188. "ProtocolEventGraph"
  189. }
  190. }
  191. impl ProtocolEventGraph {
  192. pub async fn init(event_graph: EventGraphPtr, channel: ChannelPtr) -> Result<ProtocolBasePtr> {
  193. let msg_subsystem = channel.message_subsystem();
  194. msg_subsystem.add_dispatch::<EventPut>().await;
  195. msg_subsystem.add_dispatch::<StaticPut>().await;
  196. msg_subsystem.add_dispatch::<EventReq>().await;
  197. msg_subsystem.add_dispatch::<EventRep>().await;
  198. msg_subsystem.add_dispatch::<HeaderPut>().await;
  199. msg_subsystem.add_dispatch::<HeaderReq>().await;
  200. msg_subsystem.add_dispatch::<HeaderRep>().await;
  201. msg_subsystem.add_dispatch::<TipReq>().await;
  202. msg_subsystem.add_dispatch::<TipRep>().await;
  203. let ev_put_sub = channel.subscribe_msg::<EventPut>().await?;
  204. let st_put_sub = channel.subscribe_msg::<StaticPut>().await?;
  205. let ev_req_sub = channel.subscribe_msg::<EventReq>().await?;
  206. let ev_rep_sub = channel.subscribe_msg::<EventRep>().await?;
  207. let _hdr_put_sub = channel.subscribe_msg::<HeaderPut>().await?;
  208. let hdr_req_sub = channel.subscribe_msg::<HeaderReq>().await?;
  209. let _hdr_rep_sub = channel.subscribe_msg::<HeaderRep>().await?;
  210. let tip_req_sub = channel.subscribe_msg::<TipReq>().await?;
  211. let _tip_rep_sub = channel.subscribe_msg::<TipRep>().await?;
  212. let (broadcaster_push, broadcaster_pull) = smol::channel::unbounded();
  213. Ok(Arc::new(Self {
  214. channel: channel.clone(),
  215. event_graph,
  216. ev_put_sub,
  217. st_put_sub,
  218. ev_req_sub,
  219. ev_rep_sub,
  220. _hdr_put_sub,
  221. hdr_req_sub,
  222. _hdr_rep_sub,
  223. tip_req_sub,
  224. _tip_rep_sub,
  225. malicious_count: AtomicUsize::new(0),
  226. jobsman: ProtocolJobsManager::new("ProtocolEventGraph", channel.clone()),
  227. broadcaster_push,
  228. broadcaster_pull,
  229. }))
  230. }
  231. async fn increase_malicious_count(self: Arc<Self>) -> Result<()> {
  232. let malicious_count = self.malicious_count.fetch_add(1, SeqCst);
  233. if malicious_count + 1 == MALICIOUS_THRESHOLD {
  234. error!(
  235. target: "event_graph::protocol::handle_event_put",
  236. "[EVENTGRAPH] Peer {} reached malicious threshold. Dropping connection.",
  237. self.channel.display_address(),
  238. );
  239. self.channel.stop().await;
  240. return Err(Error::ChannelStopped)
  241. }
  242. warn!(
  243. target: "event_graph::protocol::handle_event_put",
  244. "[EVENTGRAPH] Peer {} sent us a malicious event", self.channel.display_address(),
  245. );
  246. Ok(())
  247. }
  248. /// Protocol function handling `EventPut`.
  249. /// This is triggered whenever someone broadcasts (or relays) a new
  250. /// event on the network.
  251. async fn handle_event_put(self: Arc<Self>) -> Result<()> {
  252. // Rolling window of event timestamps on this channel
  253. let mut bantimes = MovingWindow::new(WINDOW_EXPIRY_TIME);
  254. let mut metadata = MessageMetadata::new();
  255. let mut current_epoch = 0;
  256. loop {
  257. let (event, blob) = match self.ev_put_sub.receive().await {
  258. Ok(v) => (v.0.clone(), v.1.clone()),
  259. Err(_) => continue,
  260. };
  261. trace!(
  262. target: "event_graph::protocol::handle_event_put",
  263. "Got EventPut: {} [{}]", event.id(), self.channel.display_address(),
  264. );
  265. // Check if node has finished syncing its DAG
  266. if !*self.event_graph.synced.read().await {
  267. debug!(
  268. target: "event_graph::protocol::handle_event_put",
  269. "DAG is still syncing, skipping..."
  270. );
  271. continue
  272. }
  273. let mut verification_failed = false;
  274. #[allow(clippy::never_loop)]
  275. loop {
  276. if blob.is_empty() {
  277. break
  278. }
  279. let rcvd_blob: Blob = match deserialize_async_partial(&blob).await {
  280. Ok((v, _)) => v,
  281. Err(e) => {
  282. error!(target: "event_graph::protocol::handle_event_put()","[EVENTGRAPH] Failed deserializing event ephemeral data: {}", e);
  283. break
  284. }
  285. };
  286. // If the current epoch is different, we reset the stored shares
  287. if current_epoch != closest_epoch(event.header.timestamp) {
  288. metadata = MessageMetadata::new()
  289. }
  290. let rln_app_identifier = pallas::Base::from(1000);
  291. current_epoch = closest_epoch(event.header.timestamp);
  292. let epoch = pallas::Base::from(current_epoch);
  293. let external_nullifier = poseidon_hash([epoch, rln_app_identifier]);
  294. let x = hash_event(&event);
  295. let identity_root = self.event_graph.rln_identity_tree.read().await.root();
  296. let public_inputs = vec![
  297. identity_root,
  298. external_nullifier,
  299. x,
  300. rcvd_blob.y,
  301. rcvd_blob.internal_nullifier,
  302. ];
  303. if metadata.is_duplicate(
  304. &external_nullifier,
  305. &rcvd_blob.internal_nullifier,
  306. &x,
  307. &rcvd_blob.y,
  308. ) {
  309. error!(target: "event_graph::protocol::handle_event_put()", "[RLN] Duplicate Message!");
  310. verification_failed = true;
  311. break
  312. }
  313. if metadata.is_reused(&external_nullifier, &rcvd_blob.internal_nullifier) {
  314. info!(target: "event_graph::protocol::handle_event_put()", "[RLN] Metadata is reused.. slashing..");
  315. let shares =
  316. metadata.get_shares(&external_nullifier, &rcvd_blob.internal_nullifier);
  317. let secret = sss_recover(&shares);
  318. // Broadcast slashing event
  319. let slash_pk = read_slash_pk(&self.event_graph.sled_db)?;
  320. // let slash_pk = &self.event_graph.slash_pk;
  321. let mut identity_tree = self.event_graph.rln_identity_tree.write().await;
  322. info!("[RLN] Creating slashing proof");
  323. let (proof, identity_root) = match create_slash_proof(
  324. secret,
  325. rcvd_blob.user_msg_limit,
  326. &mut identity_tree,
  327. &slash_pk,
  328. ) {
  329. Ok(v) => v,
  330. Err(e) => {
  331. error!("[RLN] Failed creating RLN slash proof: {}", e);
  332. // Just use an empty "proof"
  333. (Proof::new(vec![]), pallas::Base::from(0))
  334. }
  335. };
  336. drop(identity_tree);
  337. let blob =
  338. serialize_async(&(proof, secret, rcvd_blob.user_msg_limit, identity_root))
  339. .await;
  340. let evgr = &self.event_graph;
  341. let identity_secret_hash =
  342. poseidon_hash([secret, rcvd_blob.user_msg_limit.into()]);
  343. let identity_commitment = poseidon_hash([identity_secret_hash]);
  344. let rln_commitment = RLNNode::Slashing(identity_commitment);
  345. let st_event =
  346. Event::new_static(serialize_async(&rln_commitment).await, evgr).await;
  347. evgr.static_insert(&st_event).await?;
  348. evgr.static_broadcast(st_event, blob).await?;
  349. verification_failed = true;
  350. break
  351. }
  352. // At this point we can safely add the shares
  353. metadata.add_share(
  354. external_nullifier,
  355. rcvd_blob.internal_nullifier,
  356. x,
  357. rcvd_blob.y,
  358. )?;
  359. info!(target: "event_graph::protocol::handle_event_put()", "[RLN] Verifying incoming Event RLN proof");
  360. let signal_vk = read_signal_vk(&self.event_graph.sled_db)?;
  361. verification_failed = rcvd_blob.proof.verify(&signal_vk, &public_inputs).is_err();
  362. break
  363. }
  364. if verification_failed {
  365. error!(target: "event_graph::protocol::handle_event_put()", "[RLN] Incoming Event RLN Signaling proof verification failed");
  366. continue
  367. }
  368. // Remove lingering messages from dag_sync event request response
  369. _ = self.ev_rep_sub.clean().await;
  370. // If we have already seen the event, we'll stay quiet.
  371. let current_genesis = self.event_graph.current_genesis.read().await;
  372. let genesis_timestamp = current_genesis.header.timestamp;
  373. let dag_name = genesis_timestamp.to_string();
  374. let hdr_tree_name = format!("headers_{dag_name}");
  375. let event_id = event.id();
  376. if self
  377. .event_graph
  378. .dag_store
  379. .read()
  380. .await
  381. .get_dag(&hdr_tree_name)
  382. .contains_key(event_id.as_bytes())
  383. .unwrap()
  384. {
  385. debug!(
  386. target: "event_graph::protocol::handle_event_put",
  387. "Event {event_id} is already known"
  388. );
  389. continue
  390. }
  391. // There's a new unique event.
  392. // Apply ban logic to stop network floods.
  393. bantimes.ticktock();
  394. if bantimes.count() > WINDOW_MAXSIZE {
  395. self.channel.ban().await;
  396. // This error is actually unused. We could return Ok here too.
  397. return Err(Error::MaliciousFlood)
  398. }
  399. // We received an event. Check if we already have it in our DAG.
  400. // Check event is not older that current genesis event timestamp.
  401. // Also check if we have the event's parents. In the case we do
  402. // not have the parents, we'll request them from the peer that has
  403. // sent this event to us. In case they do not reply in time, we drop
  404. // the event.
  405. // Check if the event is older than the genesis event. If so, we should
  406. // not include it in our Dag.
  407. // The genesis event marks the last time the Dag has been pruned of old
  408. // events. The pruning interval is defined by the days_rotation field
  409. // of [`EventGraph`].
  410. if event.header.timestamp < genesis_timestamp {
  411. debug!(
  412. target: "event_graph::protocol::handle_event_put",
  413. "Event {} is older than genesis. Event timestamp: `{}`. Genesis timestamp: `{genesis_timestamp}`",
  414. event.id(), event.header.timestamp
  415. );
  416. }
  417. // Validate the new event first. If we do not consider it valid, we
  418. // will just drop it and stay quiet. If the malicious threshold
  419. // is reached, we will stop the connection.
  420. if !event.validate_new() {
  421. self.clone().increase_malicious_count().await?;
  422. continue
  423. }
  424. // At this point, this is a new event to us. Let's see if we
  425. // have all of its parents.
  426. debug!(
  427. target: "event_graph::protocol::handle_event_put",
  428. "Event {event_id} is new"
  429. );
  430. let mut missing_parents = HashSet::new();
  431. for parent_id in event.header.parents.iter() {
  432. // `event.validate_new()` should have already made sure that
  433. // not all parents are NULL, and that there are no duplicates.
  434. if parent_id == &NULL_ID {
  435. continue
  436. }
  437. if !self
  438. .event_graph
  439. .dag_store
  440. .read()
  441. .await
  442. .get_dag(&hdr_tree_name)
  443. .contains_key(parent_id.as_bytes())
  444. .unwrap()
  445. {
  446. missing_parents.insert(*parent_id);
  447. }
  448. }
  449. // If we have missing parents, then we have to attempt to
  450. // fetch them from this peer. Do this recursively until we
  451. // find all of them.
  452. if !missing_parents.is_empty() {
  453. // We track the received events mapped by their layer.
  454. // If/when we get all of them, we need to insert them in order so
  455. // the DAG state stays correct and unreferenced tips represent the
  456. // actual thing they should. If we insert them out of order, then
  457. // we might have wrong unreferenced tips.
  458. let mut received_events: BTreeMap<u64, Vec<Event>> = BTreeMap::new();
  459. let mut received_events_hashes = HashSet::new();
  460. debug!(
  461. target: "event_graph::protocol::handle_event_put",
  462. "Event has {} missing parents. Requesting...", missing_parents.len(),
  463. );
  464. let current_genesis = self.event_graph.current_genesis.read().await;
  465. let dag_name = current_genesis.header.timestamp.to_string();
  466. let hdr_tree_name = format!("headers_{dag_name}");
  467. while !missing_parents.is_empty() {
  468. // for parent_id in missing_parents.clone().iter() {
  469. debug!(
  470. target: "event_graph::protocol::handle_event_put",
  471. "Requesting {missing_parents:?}..."
  472. );
  473. self.channel
  474. .send(&EventReq(missing_parents.clone().into_iter().collect()))
  475. .await?;
  476. // Node waits for response
  477. let Ok(parents) = self
  478. .ev_rep_sub
  479. .receive_with_timeout(
  480. self.event_graph
  481. .p2p
  482. .settings()
  483. .read()
  484. .await
  485. .outbound_connect_timeout_max(),
  486. )
  487. .await
  488. else {
  489. error!(
  490. target: "event_graph::protocol::handle_event_put",
  491. "[EVENTGRAPH] Timeout while waiting for parents {missing_parents:?} from {}",
  492. self.channel.display_address(),
  493. );
  494. self.channel.stop().await;
  495. return Err(Error::ChannelStopped)
  496. };
  497. let parents = parents.0.clone();
  498. for parent in parents {
  499. let parent_id = parent.id();
  500. if !missing_parents.contains(&parent_id) {
  501. error!(
  502. target: "event_graph::protocol::handle_event_put",
  503. "[EVENTGRAPH] Peer {} replied with a wrong event: {}",
  504. self.channel.display_address(), parent.id(),
  505. );
  506. self.channel.stop().await;
  507. return Err(Error::ChannelStopped)
  508. }
  509. debug!(
  510. target: "event_graph::protocol::handle_event_put",
  511. "Got correct parent event {}", parent.id(),
  512. );
  513. if let Some(layer_events) = received_events.get_mut(&parent.header.layer) {
  514. layer_events.push(parent.clone());
  515. } else {
  516. let layer_events = vec![parent.clone()];
  517. received_events.insert(parent.header.layer, layer_events);
  518. }
  519. received_events_hashes.insert(parent_id);
  520. missing_parents.remove(&parent_id);
  521. // See if we have the upper parents
  522. for upper_parent in parent.header.parents.iter() {
  523. if upper_parent == &NULL_ID {
  524. continue
  525. }
  526. if !missing_parents.contains(upper_parent) &&
  527. !received_events_hashes.contains(upper_parent) &&
  528. !self
  529. .event_graph
  530. .dag_store
  531. .read()
  532. .await
  533. .get_dag(&hdr_tree_name)
  534. .contains_key(upper_parent.as_bytes())
  535. .unwrap()
  536. {
  537. debug!(
  538. target: "event_graph::protocol::handle_event_put",
  539. "Found upper missing parent event {upper_parent}"
  540. );
  541. missing_parents.insert(*upper_parent);
  542. }
  543. }
  544. }
  545. } // <-- while !missing_parents.is_empty()
  546. // At this point we should've got all the events.
  547. // We should add them to the DAG.
  548. let mut events = vec![];
  549. for (_, tips) in received_events {
  550. for tip in tips {
  551. events.push(tip);
  552. }
  553. }
  554. let headers = events.iter().map(|x| x.header.clone()).collect();
  555. if self.event_graph.header_dag_insert(headers, &dag_name).await.is_err() {
  556. self.clone().increase_malicious_count().await?;
  557. continue
  558. }
  559. // FIXME
  560. if !self.event_graph.fast_mode &&
  561. self.event_graph.dag_insert(&events, &dag_name).await.is_err()
  562. {
  563. self.clone().increase_malicious_count().await?;
  564. continue
  565. }
  566. } // <-- !missing_parents.is_empty()
  567. // If we're here, we have all the parents, and we can now
  568. // perform a full validation and add the actual event to
  569. // the DAG.
  570. debug!(
  571. target: "event_graph::protocol::handle_event_put",
  572. "Got all parents necessary for insertion",
  573. );
  574. if self
  575. .event_graph
  576. .header_dag_insert(vec![event.header.clone()], &dag_name)
  577. .await
  578. .is_err()
  579. {
  580. self.clone().increase_malicious_count().await?;
  581. continue
  582. }
  583. if self.event_graph.dag_insert(slice::from_ref(&event), &dag_name).await.is_err() {
  584. self.clone().increase_malicious_count().await?;
  585. continue
  586. }
  587. self.broadcaster_push
  588. .send(EventPut(event, blob))
  589. .await
  590. .expect("push broadcaster closed");
  591. }
  592. }
  593. async fn handle_static_put(self: Arc<Self>) -> Result<()> {
  594. // Rolling window of event timestamps on this channel
  595. let mut bantimes = MovingWindow::new(WINDOW_EXPIRY_TIME);
  596. loop {
  597. let (event, blob) = match self.st_put_sub.receive().await {
  598. Ok(v) => (v.0.clone(), v.1.clone()),
  599. Err(_) => continue,
  600. };
  601. trace!(
  602. target: "event_graph::protocol::handle_static_put()",
  603. "Got StaticPut: {} [{}]", event.id(), self.channel.address(),
  604. );
  605. // Check if node has finished syncing its DAG
  606. if !*self.event_graph.synced.read().await {
  607. debug!(
  608. target: "event_graph::protocol::handle_static_put",
  609. "DAG is still syncing, skipping..."
  610. );
  611. continue
  612. }
  613. let event_id = event.id();
  614. if self.event_graph.static_dag.contains_key(event_id.as_bytes())? {
  615. debug!(
  616. target: "event_graph::protocol::handle_static_put()",
  617. "Event {} is already known", event_id,
  618. );
  619. continue
  620. }
  621. let rln_account: RLNNode = match deserialize_async_partial(&event.content()).await {
  622. Ok((v, _)) => v,
  623. Err(e) => {
  624. error!(target: "event_graph::protocol::handle_static_put()","[RLN] Failed deserializing event ephemeral data: {}", e);
  625. continue
  626. }
  627. };
  628. if blob.is_empty() {
  629. error!(target: "event_graph::protocol::handle_static_put()","[RLN] Failed to register/slash: Not enough data provided");
  630. continue
  631. }
  632. match rln_account {
  633. RLNNode::Registration(commitment) => {
  634. let (proof, user_msg_limit): (Proof, u64) = match deserialize_async_partial(
  635. &blob,
  636. )
  637. .await
  638. {
  639. Ok((v, _)) => v,
  640. Err(e) => {
  641. error!(target: "event_graph::protocol::handle_static_put()","[RLN] Failed deserializing event ephemeral data: {}", e);
  642. continue
  643. }
  644. };
  645. info!("registering account: {:?}", commitment);
  646. let public_inputs = vec![commitment, user_msg_limit.into()];
  647. let register_vk = read_register_vk(&self.event_graph.sled_db)?;
  648. if proof.verify(&register_vk, &public_inputs).is_err() {
  649. error!(target: "event_graph::protocol::handle_static_put()", "[RLN] Incoming Event RLN Registration proof verification failed");
  650. continue
  651. }
  652. }
  653. RLNNode::Slashing(commitment) => {
  654. let (proof, secret, user_msg_limit, identity_root): (
  655. Proof,
  656. pallas::Base,
  657. u64,
  658. pallas::Base,
  659. ) = match deserialize_async_partial(&blob).await {
  660. Ok((v, _)) => v,
  661. Err(e) => {
  662. error!(target: "event_graph::protocol::handle_static_put()","[RLN] Failed deserializing event ephemeral data: {}", e);
  663. continue
  664. }
  665. };
  666. let public_inputs =
  667. vec![secret, pallas::Base::from(user_msg_limit), identity_root];
  668. let slash_vk = read_slash_vk(&self.event_graph.sled_db)?;
  669. if proof.verify(&slash_vk, &public_inputs).is_err() {
  670. error!(target: "event_graph::protocol::handle_static_put()", "[RLN] Incoming Event RLN Slashing proof verification failed");
  671. continue
  672. }
  673. let identity_secret_hash = poseidon_hash([secret, user_msg_limit.into()]);
  674. let rebuilt_commitment = poseidon_hash([identity_secret_hash]);
  675. assert_eq!(commitment, rebuilt_commitment);
  676. info!("slashing account: {}", rebuilt_commitment.to_string());
  677. let commitment = vec![rebuilt_commitment];
  678. let commitment: Vec<_> = commitment.into_iter().map(|l| (l, l)).collect();
  679. let mut rln_id_tree = self.event_graph.rln_identity_tree.write().await;
  680. rln_id_tree.remove_leaves(commitment)?;
  681. }
  682. }
  683. // Check if event's parents are in the static DAG
  684. for parent in event.header.parents.iter() {
  685. if *parent == NULL_ID {
  686. continue
  687. }
  688. if !self.event_graph.static_dag.contains_key(parent.as_bytes())? {
  689. debug!(
  690. target: "event_graph::protocol::handle_static_put()",
  691. "Event {} is orphan", event_id,
  692. );
  693. return Err(Error::EventNotFound("Event is orphan".to_owned()))
  694. }
  695. }
  696. // There's a new unique event.
  697. // Apply ban logic to stop network floods.
  698. bantimes.ticktock();
  699. if bantimes.count() > WINDOW_MAXSIZE {
  700. self.channel.ban().await;
  701. // This error is actually unused. We could return Ok here too.
  702. return Err(Error::MaliciousFlood)
  703. }
  704. // Validate the new event first. If we do not consider it valid, we
  705. // will just drop it and stay quiet. If the malicious threshold
  706. // is reached, we will stop the connection.
  707. if !event.validate_new() {
  708. self.clone().increase_malicious_count().await?;
  709. continue
  710. }
  711. // At this point, this is a new event to us. Let's see if we
  712. // have all of its parents.
  713. debug!(
  714. target: "event_graph::protocol::handle_event_put()",
  715. "Event {} is new", event_id,
  716. );
  717. self.event_graph.static_insert(&event).await?;
  718. self.event_graph.static_broadcast(event, blob).await?
  719. }
  720. }
  721. /// Protocol function handling `EventReq`.
  722. /// This is triggered whenever someone requests an event from us.
  723. async fn handle_event_req(self: Arc<Self>) -> Result<()> {
  724. loop {
  725. let event_ids = match self.ev_req_sub.receive().await {
  726. Ok(v) => v.0.clone(),
  727. Err(_) => continue,
  728. };
  729. trace!(
  730. target: "event_graph::protocol::handle_event_req",
  731. "Got EventReq: {event_ids:?} [{}]", self.channel.display_address(),
  732. );
  733. // Check if node has finished syncing its DAG
  734. if !*self.event_graph.synced.read().await {
  735. debug!(
  736. target: "event_graph::protocol::handle_event_req",
  737. "DAG is still syncing, skipping..."
  738. );
  739. continue
  740. }
  741. // We received an event request from somebody.
  742. // If we do have it, we will send it back to them as `EventRep`.
  743. // Otherwise, we'll stay quiet. An honest node should always have
  744. // something to reply with provided that the request is legitimate,
  745. // i.e. we've sent something to them and they did not haveinfo some of
  746. // the parents.
  747. // Check if we expected this request to come around.
  748. // I dunno if this is a good idea, but it seems it will help
  749. // against malicious event requests where they want us to keep
  750. // reading our db and steal our bandwidth.
  751. let mut events = vec![];
  752. for event_id in event_ids.iter() {
  753. if let Ok(event) = self
  754. .event_graph
  755. .fetch_event_from_dags(event_id)
  756. .await?
  757. .ok_or(Error::EventNotFound("The requested event is not found".to_owned()))
  758. {
  759. // At this point we should have it in our DAG.
  760. // This code panics if this is not the case.
  761. debug!(
  762. target: "event_graph::protocol::handle_event_req()",
  763. "Fetching event {:?} from DAG", event_id,
  764. );
  765. events.push(event);
  766. } else {
  767. let malicious_count = self.malicious_count.fetch_add(1, SeqCst);
  768. if malicious_count + 1 == MALICIOUS_THRESHOLD {
  769. error!(
  770. target: "event_graph::protocol::handle_event_req",
  771. "[EVENTGRAPH] Peer {} reached malicious threshold. Dropping connection.",
  772. self.channel.display_address(),
  773. );
  774. self.channel.stop().await;
  775. return Err(Error::ChannelStopped)
  776. }
  777. warn!(
  778. target: "event_graph::protocol::handle_event_req",
  779. "[EVENTGRAPH] Peer {} requested an unexpected event {event_id:?}",
  780. self.channel.display_address()
  781. );
  782. continue
  783. }
  784. }
  785. // Check if the incoming event is older than the genesis event. If so, something
  786. // has gone wrong. The event should have been pruned during the last
  787. // rotation.
  788. let genesis_timestamp = self.event_graph.current_genesis.read().await.header.timestamp;
  789. let mut bcast_ids = self.event_graph.broadcasted_ids.write().await;
  790. for event in events.iter() {
  791. if event.header.timestamp < genesis_timestamp {
  792. error!(
  793. target: "event_graph::protocol::handle_event_req",
  794. "Requested event by peer {} is older than previous rotation period. It should have been pruned.
  795. Event timestamp: `{}`. Genesis timestamp: `{genesis_timestamp}`",
  796. event.id(), event.header.timestamp
  797. );
  798. }
  799. // Now let's get the upper level of event IDs. When we reply, we could
  800. // get requests for those IDs as well.
  801. for parent_id in event.header.parents.iter() {
  802. if parent_id != &NULL_ID {
  803. bcast_ids.insert(*parent_id);
  804. }
  805. }
  806. }
  807. // TODO: We should remove the reply from the bcast IDs for this specific channel.
  808. // We can't remove them for everyone.
  809. //bcast_ids.remove(&event_id);
  810. drop(bcast_ids);
  811. // Reply with the event
  812. self.channel.send(&EventRep(events)).await?;
  813. }
  814. }
  815. /// Protocol function handling `HeaderReq`.
  816. /// This is triggered whenever someone requests syncing headers by
  817. /// sending their current headers.
  818. async fn handle_header_req(self: Arc<Self>) -> Result<()> {
  819. loop {
  820. let Ok(v) = self.hdr_req_sub.receive().await else { continue };
  821. let (dag_name, tips) = (&v.0, &v.1);
  822. trace!(
  823. target: "event_graph::protocol::handle_tip_req",
  824. "Got TipReq [{}]", self.channel.display_address(),
  825. );
  826. // Check if node has finished syncing its DAG
  827. if !*self.event_graph.synced.read().await {
  828. debug!(
  829. target: "event_graph::protocol::handle_tip_req",
  830. "DAG is still syncing, skipping..."
  831. );
  832. continue
  833. }
  834. // TODO: Rate limit
  835. // We received header request. Let's find them, add them to
  836. // our bcast ids list, and reply with them.
  837. let dag_timestamp = u64::from_str(dag_name)?;
  838. let store = self.event_graph.dag_store.read().await;
  839. if !store.header_dags.contains_key(&dag_timestamp) {
  840. continue
  841. }
  842. let headers = self.event_graph.fetch_headers_with_tips(dag_name, tips).await?;
  843. // let mut bcast_ids = self.event_graph.broadcasted_ids.write().await;
  844. // for (_, tips) in layers.iter() {
  845. // for tip in tips {
  846. // bcast_ids.insert(*tip);
  847. // }
  848. // }
  849. // drop(bcast_ids);
  850. self.channel.send(&HeaderRep(headers)).await?;
  851. }
  852. // Ok(())
  853. }
  854. /// Protocol function handling `TipReq`.
  855. /// This is triggered when someone requests the current unreferenced
  856. /// tips of our DAG.
  857. async fn handle_tip_req(self: Arc<Self>) -> Result<()> {
  858. loop {
  859. let dag_name = match self.tip_req_sub.receive().await {
  860. Ok(v) => v.0.clone(),
  861. Err(_) => continue,
  862. };
  863. trace!(
  864. target: "event_graph::protocol::handle_tip_req",
  865. "Got TipReq [{}]", self.channel.display_address(),
  866. );
  867. // Check if node has finished syncing its DAG
  868. if !*self.event_graph.synced.read().await {
  869. debug!(
  870. target: "event_graph::protocol::handle_tip_req",
  871. "DAG is still syncing, skipping..."
  872. );
  873. continue
  874. }
  875. // TODO: Rate limit
  876. // We received a tip request. Let's find them, add them to
  877. // our bcast ids list, and reply with them.
  878. let layers = match dag_name.as_str() {
  879. "static-dag" => {
  880. let tips = self.event_graph.static_unreferenced_tips().await;
  881. &tips.clone()
  882. }
  883. _ => {
  884. let dag_timestamp = u64::from_str(&dag_name)?;
  885. let store = self.event_graph.dag_store.read().await;
  886. let (_, layers) = match store.header_dags.get(&dag_timestamp) {
  887. Some(v) => v,
  888. None => continue,
  889. };
  890. &layers.clone()
  891. }
  892. };
  893. // let layers = self.event_graph.dag_store.read().await.find_unreferenced_tips(&dag_name).await;
  894. let mut bcast_ids = self.event_graph.broadcasted_ids.write().await;
  895. for (_, tips) in layers.iter() {
  896. for tip in tips {
  897. bcast_ids.insert(*tip);
  898. }
  899. }
  900. drop(bcast_ids);
  901. self.channel.send(&TipRep(layers.clone())).await?;
  902. }
  903. }
  904. /// We need to rate limit message propagation so malicious nodes don't get us banned
  905. /// for flooding. We do that by aggregating messages here into a queue then apply
  906. /// rate limit logic before broadcasting.
  907. ///
  908. /// The rate limit logic is this:
  909. ///
  910. /// * If the count is less then RATELIMIT_MIN_COUNT then do nothing.
  911. /// * Otherwise sleep for `sleep_time` ms.
  912. ///
  913. /// To calculate the sleep time, we use the RATELIMIT_SAMPLE_* values.
  914. /// For example RATELIMIT_SAMPLE_IDX = 10, RATELIMIT_SAMPLE_SLEEP = 1000
  915. /// means that when N = 10, then sleep for 1000 ms.
  916. ///
  917. /// Let RATELIMIT_MIN_COUNT = 6, then here's a table of sleep times:
  918. ///
  919. /// | Count | Sleep Time / ms |
  920. /// |-------|-----------------|
  921. /// | 0 | 0 |
  922. /// | 4 | 0 |
  923. /// | 6 | 0 |
  924. /// | 10 | 1000 |
  925. /// | 14 | 2000 |
  926. /// | 18 | 3000 |
  927. ///
  928. /// So we use the sample to calculate a straight line from RATELIMIT_MIN_COUNT.
  929. async fn broadcast_rate_limiter(self: Arc<Self>) -> Result<()> {
  930. let mut ratelimit = MovingWindow::new(RATELIMIT_EXPIRY_TIME);
  931. loop {
  932. let event_put = self.broadcaster_pull.recv().await.expect("pull broadcaster closed");
  933. ratelimit.ticktock();
  934. if ratelimit.count() > RATELIMIT_MIN_COUNT {
  935. let sleep_time =
  936. ((ratelimit.count() - RATELIMIT_MIN_COUNT) * RATELIMIT_SAMPLE_SLEEP /
  937. (RATELIMIT_SAMPLE_IDX - RATELIMIT_MIN_COUNT)) as u64;
  938. debug!(
  939. target: "event_graph::protocol::broadcast_rate_limiter",
  940. "Activated rate limit: sleeping {sleep_time} ms [count={}]",
  941. ratelimit.count()
  942. );
  943. // Apply the ratelimit
  944. msleep(sleep_time).await;
  945. }
  946. // Relay the event to other peers.
  947. self.event_graph
  948. .p2p
  949. .broadcast_with_exclude(&event_put, &[self.channel.address().clone()])
  950. .await;
  951. }
  952. }
  953. }
  954. #[cfg(test)]
  955. mod test {
  956. use super::*;
  957. use std::time::UNIX_EPOCH;
  958. #[test]
  959. fn test_eventgraph_moving_window_clean_future() {
  960. let mut window = MovingWindow::new(NanoTimestamp::from_secs(60));
  961. let future = UNIX_EPOCH.elapsed().unwrap().as_secs() + 100;
  962. window.times.push_back(NanoTimestamp::from_secs(future.into()));
  963. window.clean();
  964. assert_eq!(window.count(), 0);
  965. }
  966. }