channel.rs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{
  19. collections::HashMap,
  20. fmt,
  21. sync::{
  22. atomic::{AtomicBool, Ordering::SeqCst},
  23. Arc,
  24. },
  25. time::UNIX_EPOCH,
  26. };
  27. use darkfi_serial::{
  28. async_trait, AsyncDecodable, AsyncEncodable, SerialDecodable, SerialEncodable, VarInt,
  29. };
  30. use log::{debug, error, info, trace, warn};
  31. use rand::{rngs::OsRng, Rng};
  32. use smol::{
  33. io::{self, AsyncRead, AsyncReadExt, AsyncWriteExt, ReadHalf, WriteHalf},
  34. lock::{Mutex as AsyncMutex, OnceCell},
  35. Executor,
  36. };
  37. use url::Url;
  38. use super::{
  39. dnet::{self, dnetev, DnetEvent},
  40. hosts::{HostColor, HostsPtr},
  41. message,
  42. message::{SerializedMessage, VersionMessage},
  43. message_publisher::{MessageSubscription, MessageSubsystem},
  44. metering::{MeteringConfiguration, MeteringQueue},
  45. p2p::P2pPtr,
  46. session::{
  47. Session, SessionBitFlag, SessionWeakPtr, SESSION_ALL, SESSION_INBOUND, SESSION_REFINE,
  48. },
  49. transport::PtStream,
  50. };
  51. use crate::{
  52. net::BanPolicy,
  53. system::{msleep, Publisher, PublisherPtr, StoppableTask, StoppableTaskPtr, Subscription},
  54. util::time::NanoTimestamp,
  55. Error, Result,
  56. };
  57. /// Atomic pointer to async channel
  58. pub type ChannelPtr = Arc<Channel>;
  59. /// Channel debug info
  60. #[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
  61. pub struct ChannelInfo {
  62. pub resolve_addr: Option<Url>,
  63. pub connect_addr: Url,
  64. pub start_time: u64,
  65. pub id: u32,
  66. }
  67. impl ChannelInfo {
  68. fn new(resolve_addr: Option<Url>, connect_addr: Url, start_time: u64) -> Self {
  69. Self { resolve_addr, connect_addr, start_time, id: OsRng.gen() }
  70. }
  71. }
  72. /// Async channel for communication between nodes.
  73. pub struct Channel {
  74. /// The reading half of the transport stream
  75. reader: AsyncMutex<ReadHalf<Box<dyn PtStream>>>,
  76. /// The writing half of the transport stream
  77. writer: AsyncMutex<WriteHalf<Box<dyn PtStream>>>,
  78. /// The message subsystem instance for this channel
  79. message_subsystem: MessageSubsystem,
  80. /// Publisher listening for stop signal for closing this channel
  81. stop_publisher: PublisherPtr<Error>,
  82. /// Task that is listening for the stop signal
  83. receive_task: StoppableTaskPtr,
  84. /// A boolean marking if this channel is stopped
  85. stopped: AtomicBool,
  86. /// Weak pointer to respective session
  87. pub(in crate::net) session: SessionWeakPtr,
  88. /// The version message of the node we are connected to.
  89. /// Some if the version exchange has already occurred, None
  90. /// otherwise.
  91. pub version: OnceCell<Arc<VersionMessage>>,
  92. /// Channel debug info
  93. pub info: ChannelInfo,
  94. /// Map holding a `MeteringQueue` for each [`Message`] to perform
  95. /// rate limiting of propagation towards the stream.
  96. metering_map: AsyncMutex<HashMap<String, MeteringQueue>>,
  97. }
  98. impl Channel {
  99. /// Sets up a new channel. Creates a reader and writer [`PtStream`] and
  100. /// the message publisher subsystem. Performs a network handshake on the
  101. /// subsystem dispatchers.
  102. pub async fn new(
  103. stream: Box<dyn PtStream>,
  104. resolve_addr: Option<Url>,
  105. connect_addr: Url,
  106. session: SessionWeakPtr,
  107. ) -> Arc<Self> {
  108. let (reader, writer) = io::split(stream);
  109. let reader = AsyncMutex::new(reader);
  110. let writer = AsyncMutex::new(writer);
  111. let message_subsystem = MessageSubsystem::new();
  112. Self::setup_dispatchers(&message_subsystem).await;
  113. let start_time = UNIX_EPOCH.elapsed().unwrap().as_secs();
  114. let info = ChannelInfo::new(resolve_addr, connect_addr.clone(), start_time);
  115. let metering_map = AsyncMutex::new(HashMap::new());
  116. Arc::new(Self {
  117. reader,
  118. writer,
  119. message_subsystem,
  120. stop_publisher: Publisher::new(),
  121. receive_task: StoppableTask::new(),
  122. stopped: AtomicBool::new(false),
  123. session,
  124. version: OnceCell::new(),
  125. info,
  126. metering_map,
  127. })
  128. }
  129. /// Perform network handshake for message subsystem dispatchers.
  130. async fn setup_dispatchers(subsystem: &MessageSubsystem) {
  131. subsystem.add_dispatch::<message::VersionMessage>().await;
  132. subsystem.add_dispatch::<message::VerackMessage>().await;
  133. subsystem.add_dispatch::<message::PingMessage>().await;
  134. subsystem.add_dispatch::<message::PongMessage>().await;
  135. subsystem.add_dispatch::<message::GetAddrsMessage>().await;
  136. subsystem.add_dispatch::<message::AddrsMessage>().await;
  137. }
  138. /// Starts the channel. Runs a receive loop to start receiving messages
  139. /// or handles a network failure.
  140. pub fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) {
  141. debug!(target: "net::channel::start()", "START {:?}", self);
  142. let self_ = self.clone();
  143. self.receive_task.clone().start(
  144. self.clone().main_receive_loop(),
  145. |result| self_.handle_stop(result),
  146. Error::ChannelStopped,
  147. executor,
  148. );
  149. debug!(target: "net::channel::start()", "END {:?}", self);
  150. }
  151. /// Stops the channel.
  152. /// Notifies all publishers that the channel has been closed in `handle_stop()`.
  153. pub async fn stop(&self) {
  154. debug!(target: "net::channel::stop()", "START {:?}", self);
  155. self.receive_task.stop().await;
  156. debug!(target: "net::channel::stop()", "END {:?}", self);
  157. }
  158. /// Creates a subscription to a stopped signal.
  159. /// If the channel is stopped then this will return a ChannelStopped error.
  160. pub async fn subscribe_stop(&self) -> Result<Subscription<Error>> {
  161. debug!(target: "net::channel::subscribe_stop()", "START {:?}", self);
  162. if self.is_stopped() {
  163. return Err(Error::ChannelStopped)
  164. }
  165. let sub = self.stop_publisher.clone().subscribe().await;
  166. debug!(target: "net::channel::subscribe_stop()", "END {:?}", self);
  167. Ok(sub)
  168. }
  169. pub fn is_stopped(&self) -> bool {
  170. self.stopped.load(SeqCst)
  171. }
  172. /// Sends a message across a channel. First it converts the message
  173. /// into a `SerializedMessage` and then calls `send_serialized` to send it.
  174. /// Returns an error if something goes wrong.
  175. pub async fn send<M: message::Message>(&self, message: &M) -> Result<()> {
  176. self.send_serialized(
  177. &SerializedMessage::new(message).await,
  178. &M::METERING_SCORE,
  179. &M::METERING_CONFIGURATION,
  180. )
  181. .await
  182. }
  183. /// Sends the encoded payload of provided `SerializedMessage` across the channel.
  184. ///
  185. /// We first check if we should apply some throttling, based on the provided
  186. /// `Message` configuration. We always sleep 2x times more that the exepted one,
  187. /// so we don't flood the peer.
  188. /// Then, calls `send_message` that creates a new payload and sends it over the
  189. /// network transport as a packet.
  190. /// Returns an error if something goes wrong.
  191. pub async fn send_serialized(
  192. &self,
  193. message: &SerializedMessage,
  194. metering_score: &u64,
  195. metering_config: &MeteringConfiguration,
  196. ) -> Result<()> {
  197. debug!(
  198. target: "net::channel::send()", "[START] command={} {:?}",
  199. message.command, self,
  200. );
  201. // Check if we need to initialize a `MeteringQueue`
  202. // for this specific `Message`.
  203. let mut lock = self.metering_map.lock().await;
  204. if !lock.contains_key(&message.command) {
  205. lock.insert(message.command.clone(), MeteringQueue::new(metering_config.clone()));
  206. }
  207. // Insert metering information and grab potential sleep time.
  208. // It's safe to unwrap here since we initialized the value
  209. // previously.
  210. let queue = lock.get_mut(&message.command).unwrap();
  211. queue.push(metering_score);
  212. let sleep_time = queue.sleep_time();
  213. drop(lock);
  214. // Check if we need to sleep
  215. if let Some(sleep_time) = sleep_time {
  216. let sleep_time = 2 * sleep_time;
  217. debug!(
  218. target: "net::channel::send()",
  219. "[P2P] Channel rate limit is active, sleeping before sending for: {} (ms)",
  220. sleep_time,
  221. );
  222. msleep(sleep_time).await;
  223. }
  224. // Check if the channel is stopped, so we can abort
  225. if self.is_stopped() {
  226. return Err(Error::ChannelStopped)
  227. }
  228. // Catch failure and stop channel, return a net error
  229. if let Err(e) = self.send_message(message).await {
  230. if self.session.upgrade().unwrap().type_id() & (SESSION_ALL & !SESSION_REFINE) != 0 {
  231. error!(
  232. target: "net::channel::send()", "[P2P] Channel send error for [{:?}]: {}",
  233. self, e
  234. );
  235. }
  236. self.stop().await;
  237. return Err(Error::ChannelStopped)
  238. }
  239. debug!(
  240. target: "net::channel::send()", "[END] command={} {:?}",
  241. message.command, self
  242. );
  243. Ok(())
  244. }
  245. /// Sends the encoded payload of provided `SerializedMessage` by writing
  246. /// the data to the channel async stream.
  247. async fn send_message(&self, message: &SerializedMessage) -> Result<()> {
  248. assert!(!message.command.is_empty());
  249. let stream = &mut *self.writer.lock().await;
  250. let mut written: usize = 0;
  251. dnetev!(self, SendMessage, {
  252. chan: self.info.clone(),
  253. cmd: message.command.clone(),
  254. time: NanoTimestamp::current_time(),
  255. });
  256. trace!(target: "net::channel::send_message()", "Sending magic...");
  257. let magic_bytes = self.p2p().settings().read().await.magic_bytes.0;
  258. written += magic_bytes.encode_async(stream).await?;
  259. trace!(target: "net::channel::send_message()", "Sent magic");
  260. trace!(target: "net::channel::send_message()", "Sending command...");
  261. written += message.command.encode_async(stream).await?;
  262. trace!(target: "net::channel::send_message()", "Sent command: {}", message.command);
  263. trace!(target: "net::channel::send_message()", "Sending payload...");
  264. // First extract the length of the payload as a VarInt and write it to the stream.
  265. written += VarInt(message.payload.len() as u64).encode_async(stream).await?;
  266. // Then write the encoded payload itself to the stream.
  267. stream.write_all(&message.payload).await?;
  268. written += message.payload.len();
  269. trace!(target: "net::channel::send_message()", "Sent payload {} bytes, total bytes {}",
  270. message.payload.len(), written);
  271. stream.flush().await?;
  272. Ok(())
  273. }
  274. /// Returns a decoded Message command. We start by extracting the length
  275. /// from the stream, then allocate the precise buffer for this length
  276. /// using stream.take(). This manual deserialization provides a basic
  277. /// DDOS protection, since it prevents nodes from sending an arbitarily
  278. /// large payload.
  279. pub async fn read_command<R: AsyncRead + Unpin + Send + Sized>(
  280. &self,
  281. stream: &mut R,
  282. ) -> Result<String> {
  283. // Messages should have a 4 byte header of magic digits.
  284. // This is used for network debugging.
  285. let mut magic = [0u8; 4];
  286. trace!(target: "net::channel::read_command()", "Reading magic...");
  287. stream.read_exact(&mut magic).await?;
  288. trace!(target: "net::channel::read_command()", "Read magic {:?}", magic);
  289. let magic_bytes = self.p2p().settings().read().await.magic_bytes.0;
  290. if magic != magic_bytes {
  291. error!(target: "net::channel::read_command", "Error: Magic bytes mismatch");
  292. return Err(Error::MalformedPacket)
  293. }
  294. // First extract the length from the stream
  295. let cmd_len = VarInt::decode_async(stream).await?.0;
  296. // Then extract precisely `cmd_len` items from the stream.
  297. let mut take = stream.take(cmd_len);
  298. // Deserialize into a vector of `cmd_len` size.
  299. let mut bytes = vec![0; cmd_len.try_into().unwrap()];
  300. take.read_exact(&mut bytes).await?;
  301. let command = String::from_utf8(bytes)?;
  302. Ok(command)
  303. }
  304. /// Subscribe to a message on the message subsystem.
  305. pub async fn subscribe_msg<M: message::Message>(&self) -> Result<MessageSubscription<M>> {
  306. debug!(
  307. target: "net::channel::subscribe_msg()", "[START] command={} {:?}",
  308. M::NAME, self
  309. );
  310. let sub = self.message_subsystem.subscribe::<M>().await;
  311. debug!(
  312. target: "net::channel::subscribe_msg()", "[END] command={} {:?}",
  313. M::NAME, self
  314. );
  315. sub
  316. }
  317. /// Handle network errors. Panic if error passes silently, otherwise
  318. /// broadcast the error.
  319. async fn handle_stop(self: Arc<Self>, result: Result<()>) {
  320. debug!(target: "net::channel::handle_stop()", "[START] {:?}", self);
  321. self.stopped.store(true, SeqCst);
  322. match result {
  323. Ok(()) => panic!("Channel task should never complete without error status"),
  324. // Send this error to all channel subscribers
  325. Err(e) => {
  326. self.stop_publisher.notify(Error::ChannelStopped).await;
  327. self.message_subsystem.trigger_error(e).await;
  328. }
  329. }
  330. debug!(target: "net::channel::handle_stop()", "[END] {:?}", self);
  331. }
  332. /// Run the receive loop. Start receiving messages or handle network failure.
  333. async fn main_receive_loop(self: Arc<Self>) -> Result<()> {
  334. debug!(target: "net::channel::main_receive_loop()", "[START] {:?}", self);
  335. // Acquire reader lock
  336. let reader = &mut *self.reader.lock().await;
  337. // Run loop
  338. loop {
  339. let command = match self.read_command(reader).await {
  340. Ok(command) => command,
  341. Err(err) => {
  342. if Self::is_eof_error(&err) {
  343. info!(
  344. target: "net::channel::main_receive_loop()",
  345. "[P2P] Channel {} disconnected",
  346. self.address(),
  347. );
  348. } else if self.session.upgrade().unwrap().type_id() &
  349. (SESSION_ALL & !SESSION_REFINE) !=
  350. 0
  351. {
  352. error!(
  353. target: "net::channel::main_receive_loop()",
  354. "[P2P] Read error on channel {}: {}",
  355. self.address(), err,
  356. );
  357. }
  358. debug!(
  359. target: "net::channel::main_receive_loop()",
  360. "Stopping channel {:?}", self
  361. );
  362. return Err(Error::ChannelStopped)
  363. }
  364. };
  365. dnetev!(self, RecvMessage, {
  366. chan: self.info.clone(),
  367. cmd: command.clone(),
  368. time: NanoTimestamp::current_time(),
  369. });
  370. // Send result to our publishers
  371. match self.message_subsystem.notify(&command, reader).await {
  372. Ok(()) => {}
  373. Err(Error::MissingDispatcher) |
  374. Err(Error::MessageInvalid) |
  375. Err(Error::MeteringLimitExceeded) => {
  376. // If we're getting messages without dispatchers or its invalid,
  377. // it's spam. We therefore ban this channel if:
  378. //
  379. // 1) This channel is NOT part of a refine session.
  380. //
  381. // It's possible that nodes can send messages without
  382. // dispatchers during the refinery process. If that happens
  383. // we simply ignore it. Otherwise, it's spam.
  384. //
  385. // 2) BanPolicy is set to Strict.
  386. //
  387. // We only ban if the BanPolicy is set to Strict, which is
  388. // the default setting for most nodes. The exception to
  389. // this is a seed node like Lilith which has BanPolicy::Relaxed
  390. // since it regularly forms connections with nodes sending
  391. // messages it does not have dispatchers for.
  392. if self.session.upgrade().unwrap().type_id() != SESSION_REFINE {
  393. warn!(
  394. target: "net::channel::main_receive_loop()",
  395. "MissingDispatcher|MessageInvalid|MeteringLimitExcheeded for command={}, channel={:?}",
  396. command, self
  397. );
  398. if let BanPolicy::Strict = self.p2p().settings().read().await.ban_policy {
  399. self.ban().await;
  400. }
  401. return Err(Error::ChannelStopped)
  402. }
  403. }
  404. Err(_) => unreachable!("You added a new error in notify()"),
  405. }
  406. }
  407. }
  408. /// Ban a malicious peer and stop the channel.
  409. pub async fn ban(&self) {
  410. debug!(target: "net::channel::ban()", "START {:?}", self);
  411. debug!(target: "net::channel::ban()", "Peer: {:?}", self.address());
  412. // Just store the hostname if this is an inbound session.
  413. // This will block all ports from this peer by setting
  414. // `hosts.block_all_ports()` to true.
  415. let peer = {
  416. if self.session_type_id() & SESSION_INBOUND != 0 {
  417. if self.address().host().is_none() {
  418. error!("[P2P] ban() caught Url without host: {:?}", self.address());
  419. return
  420. }
  421. // An inbound Tor connection can't really be banned :)
  422. #[cfg(feature = "p2p-tor")]
  423. if (self.address().scheme() == "tor" || self.address().scheme() == "tor+tls") &&
  424. self.p2p().hosts().is_local_host(self.address())
  425. {
  426. return
  427. }
  428. if self.address().scheme() == "unix" {
  429. return
  430. }
  431. let mut addr = self.address().clone();
  432. addr.set_port(None).unwrap();
  433. addr
  434. } else {
  435. self.address().clone()
  436. }
  437. };
  438. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  439. info!(target: "net::channel::ban()", "Blacklisting peer={}", peer);
  440. match self.p2p().hosts().move_host(&peer, last_seen, HostColor::Black) {
  441. Ok(()) => {
  442. info!(target: "net::channel::ban()", "Peer={} blacklisted successfully", peer);
  443. }
  444. Err(e) => {
  445. warn!(target: "net::channel::ban()", "Could not blacklisted peer={}, err={}", peer, e);
  446. }
  447. }
  448. self.stop().await;
  449. debug!(target: "net::channel::ban()", "STOP {:?}", self);
  450. }
  451. /// Returns the relevant socket address for this connection. If this is
  452. /// an outbound connection, the transport-processed resolve_addr will
  453. /// be returned. Otherwise for inbound connections it will default
  454. /// to connect_addr.
  455. pub fn address(&self) -> &Url {
  456. if self.info.resolve_addr.is_some() {
  457. self.info.resolve_addr.as_ref().unwrap()
  458. } else {
  459. &self.info.connect_addr
  460. }
  461. }
  462. /// Returns the socket address that has undergone transport
  463. /// processing, if it exists. Returns None otherwise.
  464. pub fn resolve_addr(&self) -> Option<Url> {
  465. self.info.resolve_addr.clone()
  466. }
  467. /// Return the socket address without transport processing.
  468. pub fn connect_addr(&self) -> &Url {
  469. &self.info.connect_addr
  470. }
  471. /// Set the VersionMessage of the node this channel is connected
  472. /// to. Called on receiving a version message in `ProtocolVersion`.
  473. pub(crate) async fn set_version(&self, version: Arc<VersionMessage>) {
  474. self.version.set(version).await.unwrap();
  475. }
  476. /// Should only be called after the version exchange has been completed.
  477. pub fn get_version(&self) -> Arc<VersionMessage> {
  478. self.version.get().unwrap().clone()
  479. }
  480. /// Returns the inner [`MessageSubsystem`] reference
  481. pub fn message_subsystem(&self) -> &MessageSubsystem {
  482. &self.message_subsystem
  483. }
  484. fn session(&self) -> Arc<dyn Session> {
  485. self.session.upgrade().unwrap()
  486. }
  487. pub fn session_type_id(&self) -> SessionBitFlag {
  488. let session = self.session();
  489. session.type_id()
  490. }
  491. #[inline]
  492. pub fn p2p(&self) -> P2pPtr {
  493. self.session().p2p()
  494. }
  495. #[inline]
  496. pub fn hosts(&self) -> HostsPtr {
  497. self.p2p().hosts()
  498. }
  499. fn is_eof_error(err: &Error) -> bool {
  500. match err {
  501. Error::Io(ioerr) => ioerr == &std::io::ErrorKind::UnexpectedEof,
  502. _ => false,
  503. }
  504. }
  505. }
  506. impl fmt::Debug for Channel {
  507. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  508. write!(f, "<Channel addr='{}' id={}>", self.address(), self.info.id)
  509. }
  510. }