proto.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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::{HashMap, HashSet},
  20. sync::{
  21. atomic::{AtomicUsize, Ordering::SeqCst},
  22. Arc,
  23. },
  24. time::Duration,
  25. };
  26. use darkfi_serial::{async_trait, deserialize_async, SerialDecodable, SerialEncodable};
  27. use log::{debug, error};
  28. use smol::Executor;
  29. use super::{Event, EventGraphPtr, NULL_ID};
  30. use crate::{impl_p2p_message, net::*, system::timeout::timeout, Error, Result};
  31. /// Malicious behaviour threshold. If the threshold is reached, we will
  32. /// drop the peer from our P2P connection.
  33. const MALICIOUS_THRESHOLD: usize = 5;
  34. /// Time to wait for a parent ID reply
  35. const REPLY_TIMEOUT: Duration = Duration::from_secs(5);
  36. /// P2P protocol implementation for the Event Graph.
  37. pub struct ProtocolEventGraph {
  38. /// Pointer to the connected peer
  39. channel: ChannelPtr,
  40. /// Pointer to the Event Graph instance
  41. event_graph: EventGraphPtr,
  42. /// `MessageSubscriber` for `EventPut`
  43. ev_put_sub: MessageSubscription<EventPut>,
  44. /// `MessageSubscriber` for `EventReq`
  45. ev_req_sub: MessageSubscription<EventReq>,
  46. /// `MessageSubscriber` for `EventRep`
  47. ev_rep_sub: MessageSubscription<EventRep>,
  48. /// Peer malicious message count
  49. malicious_count: AtomicUsize,
  50. /// P2P jobs manager pointer
  51. jobsman: ProtocolJobsManagerPtr,
  52. }
  53. /// A P2P message representing publishing an event on the network
  54. #[derive(Clone, SerialEncodable, SerialDecodable)]
  55. pub struct EventPut(pub Event);
  56. impl_p2p_message!(EventPut, "EventGraph::EventPut");
  57. /// A P2P message representing an event request
  58. #[derive(Clone, SerialEncodable, SerialDecodable)]
  59. pub struct EventReq(pub blake3::Hash);
  60. impl_p2p_message!(EventReq, "EventGraph::EventReq");
  61. /// A P2P message representing an event reply
  62. #[derive(Clone, SerialEncodable, SerialDecodable)]
  63. pub struct EventRep(pub Event);
  64. impl_p2p_message!(EventRep, "EventGraph::EventRep");
  65. #[async_trait]
  66. impl ProtocolBase for ProtocolEventGraph {
  67. async fn start(self: Arc<Self>, ex: Arc<Executor<'_>>) -> Result<()> {
  68. self.jobsman.clone().start(ex.clone());
  69. self.jobsman.clone().spawn(self.clone().handle_event_put(), ex.clone()).await;
  70. self.jobsman.clone().spawn(self.clone().handle_event_req(), ex.clone()).await;
  71. Ok(())
  72. }
  73. fn name(&self) -> &'static str {
  74. "ProtocolEventGraph"
  75. }
  76. }
  77. impl ProtocolEventGraph {
  78. pub async fn init(event_graph: EventGraphPtr, channel: ChannelPtr) -> Result<ProtocolBasePtr> {
  79. let msg_subsystem = channel.message_subsystem();
  80. msg_subsystem.add_dispatch::<EventPut>().await;
  81. msg_subsystem.add_dispatch::<EventReq>().await;
  82. msg_subsystem.add_dispatch::<EventRep>().await;
  83. let ev_put_sub = channel.subscribe_msg::<EventPut>().await?;
  84. let ev_req_sub = channel.subscribe_msg::<EventReq>().await?;
  85. let ev_rep_sub = channel.subscribe_msg::<EventRep>().await?;
  86. Ok(Arc::new(Self {
  87. channel: channel.clone(),
  88. event_graph,
  89. ev_put_sub,
  90. ev_req_sub,
  91. ev_rep_sub,
  92. malicious_count: AtomicUsize::new(0),
  93. jobsman: ProtocolJobsManager::new("ProtocolEventGraph", channel.clone()),
  94. }))
  95. }
  96. async fn handle_event_put(self: Arc<Self>) -> Result<()> {
  97. loop {
  98. let event = match self.ev_put_sub.receive().await {
  99. Ok(v) => v.0.clone(),
  100. Err(e) => {
  101. error!(
  102. target: "event_graph::handle_event_put()",
  103. "[EVENTGRAPH] handle_event_put() recv fail: {}", e,
  104. );
  105. continue
  106. }
  107. };
  108. // We received an event. Check if we already have it in our DAG.
  109. // Also check if we have the event's parents. In the case we do
  110. // not have the parents, we'll request them from the peer that has
  111. // sent this event to us. In case they do not reply in time, we drop
  112. // the event.
  113. // Validate the event first. If we do not consider it valid, we
  114. // will just drop it and stay quiet. If the malicious threshold
  115. // is reached, we will stop the connection.
  116. if !event.validate() {
  117. let malicious_count = self.malicious_count.fetch_add(1, SeqCst);
  118. if malicious_count + 1 == MALICIOUS_THRESHOLD {
  119. error!(
  120. target: "event_graph::handle_event_put()",
  121. "[EVENTGRAPH] Peer {} reached malicious threshold. Dropping connection.",
  122. self.channel.address(),
  123. );
  124. self.channel.stop().await;
  125. return Err(Error::ChannelStopped)
  126. }
  127. continue
  128. }
  129. // If we have already seen the event, we'll stay quiet.
  130. let event_id = event.id();
  131. if self.event_graph.dag.contains_key(event_id.as_bytes()).unwrap() {
  132. debug!(target: "event_graph::handle_event_put()", "Got known event");
  133. continue
  134. }
  135. // At this point, this is a new event to us. Let's see if we
  136. // have all of its parents.
  137. /*
  138. info!(
  139. target: "event_graph::handle_event_put()",
  140. "[EVENTGRAPH] Got new event"
  141. );
  142. */
  143. let mut missing_parents = HashSet::new();
  144. for parent_id in event.parents.iter() {
  145. // `event.validate()` should have already made sure that
  146. // not all parents are NULL.
  147. if parent_id == &NULL_ID {
  148. continue
  149. }
  150. if !self.event_graph.dag.contains_key(parent_id.as_bytes()).unwrap() {
  151. missing_parents.insert(*parent_id);
  152. }
  153. }
  154. // If we have missing parents, then we have to attempt to
  155. // fetch them from this peer.
  156. if !missing_parents.is_empty() {
  157. debug!(
  158. target: "event_graph::handle_event_put()",
  159. "Event has {} missing parents. Requesting...", missing_parents.len(),
  160. );
  161. let mut received_events = HashMap::new();
  162. for parent_id in missing_parents.iter() {
  163. debug!(
  164. target: "event_graph::handle_event_put()",
  165. "Requesting {}", parent_id,
  166. );
  167. self.channel.send(&EventReq(*parent_id)).await?;
  168. let parent = match timeout(REPLY_TIMEOUT, self.ev_rep_sub.receive()).await {
  169. Ok(parent) => parent?,
  170. Err(_) => {
  171. error!(
  172. target: "event_graph::handle_event_put()",
  173. "[EVENTGRAPH] Timeout while waiting for parent {} from {}",
  174. parent_id, self.channel.address(),
  175. );
  176. self.channel.stop().await;
  177. return Err(Error::ChannelStopped)
  178. }
  179. };
  180. let parent = parent.0.clone();
  181. if &parent.id() != parent_id {
  182. error!(
  183. target: "event_graph::handle_event_put()",
  184. "[EVENTGRAPH] Peer {} replied with a wrong event: {}",
  185. self.channel.address(), parent.id(),
  186. );
  187. self.channel.stop().await;
  188. return Err(Error::ChannelStopped)
  189. }
  190. debug!(
  191. target: "event_graph::handle_event_put()",
  192. "Got correct parent event {}", parent.id(),
  193. );
  194. received_events.insert(parent.id(), parent);
  195. }
  196. // At this point we should've got all the events.
  197. // We should add them to the DAG.
  198. // TODO: FIXME: Also validate these events.
  199. for event in received_events.values() {
  200. self.event_graph.dag_insert(event).await.unwrap();
  201. }
  202. } // <-- !missing_parents.is_empty()
  203. // If we're here, we have all the parents, and we can now
  204. // add the actual event to the DAG.
  205. self.event_graph.dag_insert(&event).await.unwrap();
  206. // Relay the event to other peers
  207. self.event_graph
  208. .p2p
  209. .broadcast_with_exclude(&EventPut(event), &[self.channel.address().clone()])
  210. .await;
  211. }
  212. }
  213. async fn handle_event_req(self: Arc<Self>) -> Result<()> {
  214. loop {
  215. let event_id = match self.ev_req_sub.receive().await {
  216. Ok(v) => v.0,
  217. Err(e) => {
  218. error!(
  219. target: "event_graph::handle_event_req()",
  220. "[EVENTGRAPH] handle_event_req() recv fail: {}", e,
  221. );
  222. continue
  223. }
  224. };
  225. // We received an event request from somebody.
  226. // If we do have ti, we will send it back to them as `EventRep`.
  227. // Otherwise, we'll stay quiet. An honest node should always have
  228. // something to reply with provided that the request is legitimate,
  229. // i.e. we've sent something to them and they did not have some of
  230. // the parents.
  231. // Check if we expected this request to come around.
  232. // I dunno if this is a good idea, but it seems it will help
  233. // against malicious event requests where they want us to keep
  234. // reading our db and steal our bandwidth.
  235. if !self.event_graph.broadcasted_ids.read().await.contains(&event_id) {
  236. let malicious_count = self.malicious_count.fetch_add(1, SeqCst);
  237. if malicious_count + 1 == MALICIOUS_THRESHOLD {
  238. error!(
  239. target: "event_graph::handle_event_req()",
  240. "[EVENTGRAPH] Peer {} reached malicious threshold. Dropping connection.",
  241. self.channel.address(),
  242. );
  243. self.channel.stop().await;
  244. return Err(Error::ChannelStopped)
  245. }
  246. continue
  247. }
  248. // At this point we should have it in our DAG.
  249. // This code panics if this is not the case.
  250. let event = self.event_graph.dag.get(event_id.as_bytes()).unwrap().unwrap();
  251. let event: Event = deserialize_async(&event).await.unwrap();
  252. // Now let's get the upper level of event IDs. When we reply, we could
  253. // get requests for those IDs as well.
  254. let mut bcast_ids = self.event_graph.broadcasted_ids.write().await;
  255. for parent_id in event.parents.iter() {
  256. if parent_id != &NULL_ID {
  257. bcast_ids.insert(event_id);
  258. }
  259. }
  260. drop(bcast_ids);
  261. // Reply with the event
  262. self.channel.send(&EventRep(event)).await?;
  263. }
  264. }
  265. }