proto.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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. // TODO: FIXME: Some of the protocols should block operations until DAG is synced.
  19. use std::{
  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, trace, warn};
  28. use smol::Executor;
  29. use super::{Event, EventGraph, 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. pub(super) 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. /// `MessageSubscriber` for `TipReq`
  49. tip_req_sub: MessageSubscription<TipReq>,
  50. /// `MessageSubscriber` for `TipRep`
  51. _tip_rep_sub: MessageSubscription<TipRep>,
  52. /// Peer malicious message count
  53. malicious_count: AtomicUsize,
  54. /// P2P jobs manager pointer
  55. jobsman: ProtocolJobsManagerPtr,
  56. }
  57. /// A P2P message representing publishing an event on the network
  58. #[derive(Clone, SerialEncodable, SerialDecodable)]
  59. pub struct EventPut(pub Event);
  60. impl_p2p_message!(EventPut, "EventGraph::EventPut");
  61. /// A P2P message representing an event request
  62. #[derive(Clone, SerialEncodable, SerialDecodable)]
  63. pub struct EventReq(pub blake3::Hash);
  64. impl_p2p_message!(EventReq, "EventGraph::EventReq");
  65. /// A P2P message representing an event reply
  66. #[derive(Clone, SerialEncodable, SerialDecodable)]
  67. pub struct EventRep(pub Event);
  68. impl_p2p_message!(EventRep, "EventGraph::EventRep");
  69. /// A P2P message representing a request for a peer's DAG tips
  70. #[derive(Clone, SerialEncodable, SerialDecodable)]
  71. pub struct TipReq {}
  72. impl_p2p_message!(TipReq, "EventGraph::TipReq");
  73. /// A P2P message representing a reply for the peer's DAG tips
  74. #[derive(Clone, SerialEncodable, SerialDecodable)]
  75. pub struct TipRep(pub Vec<blake3::Hash>);
  76. impl_p2p_message!(TipRep, "EventGraph::TipRep");
  77. #[async_trait]
  78. impl ProtocolBase for ProtocolEventGraph {
  79. async fn start(self: Arc<Self>, ex: Arc<Executor<'_>>) -> Result<()> {
  80. self.jobsman.clone().start(ex.clone());
  81. self.jobsman.clone().spawn(self.clone().handle_event_put(), ex.clone()).await;
  82. self.jobsman.clone().spawn(self.clone().handle_event_req(), ex.clone()).await;
  83. self.jobsman.clone().spawn(self.clone().handle_tip_req(), ex.clone()).await;
  84. Ok(())
  85. }
  86. fn name(&self) -> &'static str {
  87. "ProtocolEventGraph"
  88. }
  89. }
  90. impl ProtocolEventGraph {
  91. pub async fn init(event_graph: EventGraphPtr, channel: ChannelPtr) -> Result<ProtocolBasePtr> {
  92. let msg_subsystem = channel.message_subsystem();
  93. msg_subsystem.add_dispatch::<EventPut>().await;
  94. msg_subsystem.add_dispatch::<EventReq>().await;
  95. msg_subsystem.add_dispatch::<EventRep>().await;
  96. msg_subsystem.add_dispatch::<TipReq>().await;
  97. msg_subsystem.add_dispatch::<TipRep>().await;
  98. let ev_put_sub = channel.subscribe_msg::<EventPut>().await?;
  99. let ev_req_sub = channel.subscribe_msg::<EventReq>().await?;
  100. let ev_rep_sub = channel.subscribe_msg::<EventRep>().await?;
  101. let tip_req_sub = channel.subscribe_msg::<TipReq>().await?;
  102. let _tip_rep_sub = channel.subscribe_msg::<TipRep>().await?;
  103. Ok(Arc::new(Self {
  104. channel: channel.clone(),
  105. event_graph,
  106. ev_put_sub,
  107. ev_req_sub,
  108. ev_rep_sub,
  109. tip_req_sub,
  110. _tip_rep_sub,
  111. malicious_count: AtomicUsize::new(0),
  112. jobsman: ProtocolJobsManager::new("ProtocolEventGraph", channel.clone()),
  113. }))
  114. }
  115. /// Protocol function handling `EventPut`.
  116. /// This is triggered whenever someone broadcasts (or relays) a new
  117. /// event on the network.
  118. async fn handle_event_put(self: Arc<Self>) -> Result<()> {
  119. loop {
  120. let event = match self.ev_put_sub.receive().await {
  121. Ok(v) => v.0.clone(),
  122. Err(_) => continue,
  123. };
  124. trace!(
  125. target: "event_graph::protocol::handle_event_put()",
  126. "Got EventPut: {} [{}]", event.id(), self.channel.address(),
  127. );
  128. // Check if the event is older than the genesis event. If so, we should
  129. // not include it in our Dag.
  130. // The genesis event marks the last time the Dag has been pruned of old
  131. // events. The pruning interval is defined by the days_rotation field
  132. // of [`EventGraph`].
  133. // TODO it would be better to store/cache this instead of calculating
  134. // on every broadcast/relay.
  135. let genesis_timestamp =
  136. EventGraph::generate_genesis(self.event_graph.days_rotation()).timestamp;
  137. if event.timestamp < genesis_timestamp {
  138. debug!(
  139. target: "event_graph::protocol::handle_event_put()",
  140. "Event {} is older than genesis. Event timestamp: `{}`. Genesis timestamp: `{}`",
  141. event.id(), event.timestamp, genesis_timestamp
  142. );
  143. }
  144. // We received an event. Check if we already have it in our DAG.
  145. // Also check if we have the event's parents. In the case we do
  146. // not have the parents, we'll request them from the peer that has
  147. // sent this event to us. In case they do not reply in time, we drop
  148. // the event.
  149. // Validate the event first. If we do not consider it valid, we
  150. // will just drop it and stay quiet. If the malicious threshold
  151. // is reached, we will stop the connection.
  152. if !event.validate() {
  153. let malicious_count = self.malicious_count.fetch_add(1, SeqCst);
  154. if malicious_count + 1 == MALICIOUS_THRESHOLD {
  155. error!(
  156. target: "event_graph::protocol::handle_event_put()",
  157. "[EVENTGRAPH] Peer {} reached malicious threshold. Dropping connection.",
  158. self.channel.address(),
  159. );
  160. self.channel.stop().await;
  161. return Err(Error::ChannelStopped)
  162. }
  163. warn!(
  164. target: "event_graph::protocol::handle_event_put()",
  165. "[EVENTGRAPH] Peer {} sent us a malicious event", self.channel.address(),
  166. );
  167. continue
  168. }
  169. // If we have already seen the event, we'll stay quiet.
  170. let event_id = event.id();
  171. if self.event_graph.dag.contains_key(event_id.as_bytes()).unwrap() {
  172. debug!(
  173. target: "event_graph::protocol::handle_event_put()",
  174. "Event {} is already known", event_id,
  175. );
  176. continue
  177. }
  178. // At this point, this is a new event to us. Let's see if we
  179. // have all of its parents.
  180. debug!(
  181. target: "event_graph::protocol::handle_event_put()",
  182. "Event {} is new", event_id,
  183. );
  184. let mut missing_parents = vec![];
  185. for parent_id in event.parents.iter() {
  186. // `event.validate()` should have already made sure that
  187. // not all parents are NULL, and that there are no duplicates.
  188. if parent_id == &NULL_ID {
  189. continue
  190. }
  191. if !self.event_graph.dag.contains_key(parent_id.as_bytes()).unwrap() {
  192. missing_parents.push(*parent_id);
  193. }
  194. }
  195. // If we have missing parents, then we have to attempt to
  196. // fetch them from this peer. Do this recursively until we
  197. // find all of them.
  198. if !missing_parents.is_empty() {
  199. // We track the received events in a vec. If/when we get all
  200. // of them, we need to insert them in reverse so the DAG state
  201. // stays correct and unreferenced tips represent the actual thing
  202. // they should. If we insert them out of order, then we might have
  203. // wrong unreferenced tips.
  204. // TODO: What should we do if at some point the events become too old?
  205. let mut received_events = vec![];
  206. debug!(
  207. target: "event_graph::protocol::handle_event_put()",
  208. "Event has {} missing parents. Requesting...", missing_parents.len(),
  209. );
  210. while !missing_parents.is_empty() {
  211. for parent_id in missing_parents.clone().iter() {
  212. debug!(
  213. target: "event_graph::protocol::handle_event_put()",
  214. "Requesting {}...", parent_id,
  215. );
  216. self.channel.send(&EventReq(*parent_id)).await?;
  217. let parent = match timeout(REPLY_TIMEOUT, self.ev_rep_sub.receive()).await {
  218. Ok(parent) => parent?,
  219. Err(_) => {
  220. error!(
  221. target: "event_graph::protocol::handle_event_put()",
  222. "[EVENTGRAPH] Timeout while waiting for parent {} from {}",
  223. parent_id, self.channel.address(),
  224. );
  225. self.channel.stop().await;
  226. return Err(Error::ChannelStopped)
  227. }
  228. };
  229. let parent = parent.0.clone();
  230. if &parent.id() != parent_id {
  231. error!(
  232. target: "event_graph::protocol::handle_event_put()",
  233. "[EVENTGRAPH] Peer {} replied with a wrong event: {}",
  234. self.channel.address(), parent.id(),
  235. );
  236. self.channel.stop().await;
  237. return Err(Error::ChannelStopped)
  238. }
  239. debug!(
  240. target: "event_graph::protocol::handle_event_put()",
  241. "Got correct parent event {}", parent.id(),
  242. );
  243. received_events.push(parent.clone());
  244. let pos = missing_parents.iter().position(|id| id == &parent.id()).unwrap();
  245. missing_parents.remove(pos);
  246. // See if we have the upper parents
  247. for upper_parent in parent.parents.iter() {
  248. if upper_parent == &NULL_ID {
  249. continue
  250. }
  251. if !self.event_graph.dag.contains_key(upper_parent.as_bytes()).unwrap()
  252. {
  253. debug!(
  254. target: "event_graph::protocol::handle_event_put()",
  255. "Found upper missing parent event{}", upper_parent,
  256. );
  257. missing_parents.push(*upper_parent);
  258. }
  259. }
  260. }
  261. } // <-- while !missing_parents.is_empty()
  262. // At this point we should've got all the events.
  263. // We should add them to the DAG.
  264. // TODO: FIXME: Also validate these events.
  265. let received_events_rev: Vec<Event> =
  266. received_events.iter().rev().cloned().collect();
  267. self.event_graph.dag_insert(&received_events_rev).await.unwrap();
  268. } // <-- !missing_parents.is_empty()
  269. // If we're here, we have all the parents, and we can now
  270. // add the actual event to the DAG.
  271. debug!(
  272. target: "event_graph::protocol::handle_event_put()",
  273. "Got all parents necessary for insertion",
  274. );
  275. self.event_graph.dag_insert(&[event.clone()]).await.unwrap();
  276. // Relay the event to other peers.
  277. self.event_graph
  278. .p2p
  279. .broadcast_with_exclude(&EventPut(event), &[self.channel.address().clone()])
  280. .await;
  281. }
  282. }
  283. /// Protocol function handling `EventReq`.
  284. /// This is triggered whenever someone requests an event from us.
  285. async fn handle_event_req(self: Arc<Self>) -> Result<()> {
  286. loop {
  287. let event_id = match self.ev_req_sub.receive().await {
  288. Ok(v) => v.0,
  289. Err(_) => continue,
  290. };
  291. trace!(
  292. target: "event_graph::protocol::handle_event_req()",
  293. "Got EventReq: {} [{}]", event_id, self.channel.address(),
  294. );
  295. // We received an event request from somebody.
  296. // If we do have it, we will send it back to them as `EventRep`.
  297. // Otherwise, we'll stay quiet. An honest node should always have
  298. // something to reply with provided that the request is legitimate,
  299. // i.e. we've sent something to them and they did not have some of
  300. // the parents.
  301. // Check if we expected this request to come around.
  302. // I dunno if this is a good idea, but it seems it will help
  303. // against malicious event requests where they want us to keep
  304. // reading our db and steal our bandwidth.
  305. if !self.event_graph.broadcasted_ids.read().await.contains(&event_id) {
  306. let malicious_count = self.malicious_count.fetch_add(1, SeqCst);
  307. if malicious_count + 1 == MALICIOUS_THRESHOLD {
  308. error!(
  309. target: "event_graph::protocol::handle_event_req()",
  310. "[EVENTGRAPH] Peer {} reached malicious threshold. Dropping connection.",
  311. self.channel.address(),
  312. );
  313. self.channel.stop().await;
  314. return Err(Error::ChannelStopped)
  315. }
  316. warn!(
  317. target: "event_graph::protocol::handle_event_req()",
  318. "[EVENTGRAPH] Peer {} requested an unexpected event {}",
  319. self.channel.address(), event_id,
  320. );
  321. continue
  322. }
  323. // At this point we should have it in our DAG.
  324. // This code panics if this is not the case.
  325. debug!(
  326. target: "event_graph::protocol::handle_event_req()",
  327. "Fetching event {} from DAG", event_id,
  328. );
  329. let event = self.event_graph.dag.get(event_id.as_bytes()).unwrap().unwrap();
  330. let event: Event = deserialize_async(&event).await.unwrap();
  331. // Check if the event is older than the genesis event. If so, something
  332. // has gone wrong. The event should have been pruned during the last
  333. // rotation.
  334. // TODO it would be better to store/cache this instead of calculating
  335. // on every broadcast/relay.
  336. let genesis_timestamp =
  337. EventGraph::generate_genesis(self.event_graph.days_rotation()).timestamp;
  338. if event.timestamp < genesis_timestamp {
  339. error!(
  340. target: "event_graph::protocol::handle_event_req()",
  341. "Requested event {} is older than previous rotation period. It should have been pruned.
  342. Event timestamp: `{}`. Genesis timestamp: `{}`",
  343. event.id(), event.timestamp, genesis_timestamp
  344. );
  345. }
  346. // Now let's get the upper level of event IDs. When we reply, we could
  347. // get requests for those IDs as well.
  348. let mut bcast_ids = self.event_graph.broadcasted_ids.write().await;
  349. for parent_id in event.parents.iter() {
  350. if parent_id != &NULL_ID {
  351. bcast_ids.insert(*parent_id);
  352. }
  353. }
  354. // TODO: We should remove the reply from the bcast IDs for this specific channel.
  355. // We can't remove them for everyone.
  356. //bcast_ids.remove(&event_id);
  357. drop(bcast_ids);
  358. // Reply with the event
  359. self.channel.send(&EventRep(event)).await?;
  360. }
  361. }
  362. /// Protocol function handling `TipReq`.
  363. /// This is triggered when someone requests the current unreferenced
  364. /// tips of our DAG.
  365. async fn handle_tip_req(self: Arc<Self>) -> Result<()> {
  366. loop {
  367. self.tip_req_sub.receive().await?;
  368. trace!(
  369. target: "event_graph::protocol::handle_tip_req()",
  370. "Got TipReq [{}]", self.channel.address(),
  371. );
  372. // TODO: Rate limit
  373. // We received a tip request. Let's find them, add them to
  374. // our bcast ids list, and reply with them.
  375. let mut tips = self.event_graph.get_unreferenced_tips().await.to_vec();
  376. tips.retain(|x| x != &NULL_ID);
  377. let mut bcast_ids = self.event_graph.broadcasted_ids.write().await;
  378. for tip in tips.iter() {
  379. bcast_ids.insert(*tip);
  380. }
  381. drop(bcast_ids);
  382. self.channel.send(&TipRep(tips)).await?;
  383. }
  384. }
  385. }