darkirc.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use async_trait::async_trait;
  19. use darkfi::{
  20. event_graph::{
  21. self,
  22. proto::{EventPut, ProtocolEventGraph},
  23. EventGraph, EventGraphPtr,
  24. },
  25. net::{session::SESSION_DEFAULT, settings::Settings as NetSettings, ChannelPtr, P2p, P2pPtr},
  26. system::{sleep, Subscription},
  27. Result as DarkFiResult,
  28. };
  29. use darkfi_serial::{
  30. deserialize_async, serialize, serialize_async, AsyncEncodable, Decodable, Encodable,
  31. SerialDecodable, SerialEncodable,
  32. };
  33. use sled_overlay::sled;
  34. use std::{
  35. io::Cursor,
  36. sync::{Arc, Mutex as SyncMutex, OnceLock, Weak},
  37. time::UNIX_EPOCH,
  38. };
  39. use crate::{
  40. error::{Error, Result},
  41. prop::{PropertyAtomicGuard, PropertyStr, Role},
  42. scene::{MethodCallSub, Pimpl, SceneNodePtr, SceneNodeWeak},
  43. ui::{
  44. chatview::{MessageId, Timestamp},
  45. OnModify,
  46. },
  47. ExecutorPtr,
  48. };
  49. use super::PluginObject;
  50. const P2P_RETRY_TIME: u64 = 20;
  51. const COOLOFF_SLEEP_TIME: u64 = 20;
  52. const COOLOFF_SYNC_ATTEMPTS: usize = 6;
  53. const SYNC_MIN_PEERS: usize = 2;
  54. /// Due to drift between different machine's clocks, if the message timestamp is recent
  55. /// then we will just correct it to the current time so messages appear sequential in the UI.
  56. const RECENT_TIME_DIST: u64 = 25_000;
  57. #[cfg(target_os = "android")]
  58. mod paths {
  59. use crate::android::get_appdata_path;
  60. use std::path::PathBuf;
  61. pub fn get_evgrdb_path() -> PathBuf {
  62. get_appdata_path().join("evgr")
  63. }
  64. pub fn nick_filename() -> PathBuf {
  65. get_appdata_path().join("/nick.txt")
  66. }
  67. pub fn p2p_datastore_path() -> PathBuf {
  68. get_appdata_path().join("darkirc_p2p")
  69. }
  70. pub fn hostlist_path() -> PathBuf {
  71. get_appdata_path().join("hostlist.tsv")
  72. }
  73. }
  74. #[cfg(not(target_os = "android"))]
  75. mod paths {
  76. use std::path::PathBuf;
  77. pub fn get_evgrdb_path() -> PathBuf {
  78. dirs::data_local_dir().unwrap().join("darkfi/evgr")
  79. }
  80. pub fn nick_filename() -> PathBuf {
  81. dirs::cache_dir().unwrap().join("darkfi/nick.txt")
  82. }
  83. pub fn p2p_datastore_path() -> PathBuf {
  84. dirs::cache_dir().unwrap().join("darkfi/wallet/darkirc_p2p")
  85. }
  86. pub fn hostlist_path() -> PathBuf {
  87. dirs::cache_dir().unwrap().join("darkfi/wallet/hostlist.tsv")
  88. }
  89. }
  90. use paths::*;
  91. macro_rules! t { ($($arg:tt)*) => { trace!(target: "plugin::darkirc", $($arg)*); } }
  92. macro_rules! d { ($($arg:tt)*) => { debug!(target: "plugin::darkirc", $($arg)*); } }
  93. macro_rules! i { ($($arg:tt)*) => { info!(target: "plugin::darkirc", $($arg)*); } }
  94. macro_rules! e { ($($arg:tt)*) => { error!(target: "plugin::darkirc", $($arg)*); } }
  95. #[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
  96. pub struct Privmsg {
  97. pub channel: String,
  98. pub nick: String,
  99. pub msg: String,
  100. }
  101. impl Privmsg {
  102. pub fn new(channel: String, nick: String, msg: String) -> Self {
  103. Self { channel, nick, msg }
  104. }
  105. pub fn msg_id(&self, timest: u64) -> MessageId {
  106. let mut hasher = blake3::Hasher::new();
  107. 0u8.encode(&mut hasher).unwrap();
  108. 0u8.encode(&mut hasher).unwrap();
  109. timest.encode(&mut hasher).unwrap();
  110. self.channel.encode(&mut hasher).unwrap();
  111. self.nick.encode(&mut hasher).unwrap();
  112. self.msg.encode(&mut hasher).unwrap();
  113. MessageId(hasher.finalize().into())
  114. }
  115. }
  116. struct SeenMsg {
  117. id: MessageId,
  118. is_self: bool,
  119. seen_times: usize,
  120. }
  121. struct SeenMessages {
  122. seen: Vec<SeenMsg>,
  123. }
  124. impl SeenMessages {
  125. fn new() -> Self {
  126. Self { seen: vec![] }
  127. }
  128. fn get_status(&self, id: &MessageId) -> Option<&SeenMsg> {
  129. self.seen.iter().find(|s| s.id == *id)
  130. }
  131. fn push(&mut self, id: MessageId, is_self: bool) {
  132. self.seen.push(SeenMsg { id, is_self, seen_times: 0 });
  133. }
  134. }
  135. pub type DarkIrcPtr = Arc<DarkIrc>;
  136. pub struct DarkIrc {
  137. node: SceneNodeWeak,
  138. tasks: OnceLock<Vec<smol::Task<()>>>,
  139. p2p: P2pPtr,
  140. event_graph: EventGraphPtr,
  141. db: sled::Db,
  142. seen_msgs: SyncMutex<SeenMessages>,
  143. nick: PropertyStr,
  144. }
  145. impl DarkIrc {
  146. pub async fn new(node: SceneNodeWeak, ex: ExecutorPtr) -> Result<Pimpl> {
  147. let node_ref = &node.upgrade().unwrap();
  148. let nick = PropertyStr::wrap(node_ref, Role::Internal, "nick", 0).unwrap();
  149. i!("Starting DarkIRC backend");
  150. let evgr_path = get_evgrdb_path();
  151. let db = match sled::open(&evgr_path) {
  152. Ok(db) => db,
  153. Err(err) => {
  154. e!("Sled database '{}' failed to open: {err}!", evgr_path.display());
  155. return Err(Error::SledDbErr);
  156. }
  157. };
  158. let mut p2p_settings: NetSettings = Default::default();
  159. p2p_settings.app_version = semver::Version::parse("0.5.0").unwrap();
  160. p2p_settings.seeds.push(url::Url::parse("tcp+tls://lilith1.dark.fi:5262").unwrap());
  161. p2p_settings.seeds.push(url::Url::parse("tcp+tls://agorism.dev:26661").unwrap());
  162. p2p_settings.seeds.push(url::Url::parse("tcp+tls://agorism.dev:26671").unwrap());
  163. p2p_settings.outbound_connect_timeout = 40;
  164. p2p_settings.channel_handshake_timeout = 30;
  165. p2p_settings.p2p_datastore = p2p_datastore_path().into_os_string().into_string().ok();
  166. p2p_settings.hostlist = hostlist_path().into_os_string().into_string().ok();
  167. let p2p = match P2p::new(p2p_settings, ex.clone()).await {
  168. Ok(p2p) => p2p,
  169. Err(err) => {
  170. e!("Create p2p network failed: {err}!");
  171. return Err(Error::ServiceFailed);
  172. }
  173. };
  174. let event_graph = match EventGraph::new(
  175. p2p.clone(),
  176. db.clone(),
  177. std::path::PathBuf::new(),
  178. false,
  179. "darkirc_dag",
  180. 1,
  181. ex.clone(),
  182. )
  183. .await
  184. {
  185. Ok(evgr) => evgr,
  186. Err(err) => {
  187. e!("Create event graph failed: {err}!");
  188. return Err(Error::ServiceFailed);
  189. }
  190. };
  191. if let Ok(prev_nick) = std::fs::read_to_string(nick_filename()) {
  192. nick.set(&mut PropertyAtomicGuard::new(), prev_nick);
  193. }
  194. let self_ = Arc::new(Self {
  195. node,
  196. tasks: OnceLock::new(),
  197. p2p,
  198. event_graph,
  199. db,
  200. seen_msgs: SyncMutex::new(SeenMessages::new()),
  201. nick,
  202. });
  203. Ok(Pimpl::DarkIrc(self_))
  204. }
  205. async fn dag_sync(self: Arc<Self>, channel_sub: Subscription<DarkFiResult<ChannelPtr>>) {
  206. i!("Starting p2p network");
  207. while let Err(err) = self.p2p.clone().start().await {
  208. // This usually means we cannot listen on the inbound ports
  209. e!("Failed to start p2p network: {err}!");
  210. e!("Usually this means there is another process listening on the same ports.");
  211. e!("Trying again in {P2P_RETRY_TIME} secs");
  212. sleep(P2P_RETRY_TIME).await;
  213. }
  214. i!("Waiting for some P2P connections...");
  215. let mut sync_attempt = 0;
  216. loop {
  217. // Wait for a channel
  218. if let Err(_) = channel_sub.receive().await {
  219. e!("There was an error listening for channels. The service closed unexpectedly.");
  220. // Not sure what to do here
  221. return
  222. }
  223. // Wait until we have enough connections
  224. if self.p2p.hosts().peers().len() < SYNC_MIN_PEERS {
  225. continue
  226. }
  227. sync_attempt += 1;
  228. // Cool off periodically
  229. if sync_attempt > COOLOFF_SYNC_ATTEMPTS {
  230. i!("Wasn't able to sync yet. Cooling off for {COOLOFF_SLEEP_TIME} then will try again.");
  231. sleep(COOLOFF_SLEEP_TIME).await;
  232. sync_attempt = 0;
  233. }
  234. i!("Syncing event DAG (attempt #{sync_attempt})");
  235. match self.event_graph.dag_sync().await {
  236. Ok(()) => break,
  237. Err(e) => {
  238. // TODO: Maybe at this point we should prune or something?
  239. // TODO: Or maybe just tell the user to delete the DAG from FS.
  240. warn!("Failed DAG sync: ({e}). Waiting for more connections before retry.");
  241. }
  242. }
  243. }
  244. }
  245. async fn relay_events(self: Arc<Self>, ev_sub: Subscription<event_graph::Event>) {
  246. loop {
  247. let ev = ev_sub.receive().await;
  248. // Try to deserialize the `Event`'s content into a `Privmsg`
  249. let privmsg: Privmsg = match deserialize_async(ev.content()).await {
  250. Ok(v) => v,
  251. Err(e) => {
  252. e!("[IRC CLIENT] Failed deserializing incoming Privmsg event: {}", e);
  253. continue
  254. }
  255. };
  256. let mut timest = ev.timestamp;
  257. let msg_id = privmsg.msg_id(timest);
  258. t!(
  259. "Relaying ev_id={:?}, ev={ev:?}, msg_id={msg_id}, privmsg={privmsg:?}, timest={timest}",
  260. ev.id(),
  261. );
  262. let is_self = {
  263. let mut is_self = false;
  264. let mut seen = self.seen_msgs.lock().unwrap();
  265. match seen.get_status(&msg_id) {
  266. Some(msg) => {
  267. is_self = msg.is_self;
  268. if !msg.is_self || msg.seen_times > 1 {
  269. warn!(target: "plugin::darkirc", "Skipping duplicate seen message: {msg_id}");
  270. continue
  271. }
  272. }
  273. None => {
  274. seen.push(msg_id.clone(), false);
  275. }
  276. }
  277. is_self
  278. };
  279. // This is a hack to make messages appear sequentially in the UI
  280. let now_timest = UNIX_EPOCH.elapsed().unwrap().as_millis() as u64;
  281. if !is_self && timest.abs_diff(now_timest) < RECENT_TIME_DIST {
  282. d!("Applied timestamp correction: <{timest}> => <{now_timest}>");
  283. timest = now_timest;
  284. }
  285. // Strip off starting #
  286. let mut channel = privmsg.channel;
  287. if channel.is_empty() {
  288. warn!(target: "plugin::darkirc", "Received privmsg with empty channel!");
  289. continue
  290. }
  291. if channel.chars().next().unwrap() != '#' {
  292. warn!(target: "plugin::darkirc", "Skipping encrypted channel: {channel}");
  293. continue
  294. }
  295. channel.remove(0);
  296. // Workaround for the chatview hack. This nick is off limits!
  297. let mut nick = privmsg.nick;
  298. if nick == "NOTICE" {
  299. nick = "noticer".to_string();
  300. }
  301. let mut arg_data = vec![];
  302. channel.encode(&mut arg_data).unwrap();
  303. timest.encode(&mut arg_data).unwrap();
  304. msg_id.encode(&mut arg_data).unwrap();
  305. nick.encode(&mut arg_data).unwrap();
  306. privmsg.msg.encode(&mut arg_data).unwrap();
  307. let node = self.node.upgrade().unwrap();
  308. node.trigger("recv", arg_data).await.unwrap();
  309. }
  310. }
  311. async fn process_send(me: &Weak<Self>, sub: &MethodCallSub) -> bool {
  312. let Ok(method_call) = sub.receive().await else {
  313. d!("Event relayer closed");
  314. return false
  315. };
  316. t!("method called: send({method_call:?})");
  317. assert!(method_call.send_res.is_none());
  318. fn decode_data(data: &[u8]) -> std::io::Result<(Timestamp, String, String)> {
  319. let mut cur = Cursor::new(&data);
  320. let timest = Timestamp::decode(&mut cur).unwrap();
  321. let channel = String::decode(&mut cur)?;
  322. let msg = String::decode(&mut cur)?;
  323. Ok((timest, channel, msg))
  324. }
  325. let Ok((timest, channel, msg)) = decode_data(&method_call.data) else {
  326. e!("send() method invalid arg data");
  327. return true
  328. };
  329. let Some(self_) = me.upgrade() else {
  330. // Should not happen
  331. panic!("self destroyed before send_method_task was stopped!");
  332. };
  333. self_.handle_send(timest, channel, msg).await;
  334. true
  335. }
  336. async fn handle_send(&self, timest: Timestamp, channel: String, msg: String) {
  337. let nick = self.nick.get();
  338. // Send text to channel
  339. d!("Sending privmsg: {timest} {channel}: <{nick}> {msg}");
  340. let msg = Privmsg::new(channel, nick, msg);
  341. let evgr = self.event_graph.clone();
  342. let mut event = event_graph::Event::new(serialize_async(&msg).await, &evgr).await;
  343. event.timestamp = timest;
  344. let msg_id = msg.msg_id(timest);
  345. // Keep track of our own messages so we don't apply timestamp correction to them
  346. // which messes up the msg id.
  347. {
  348. let mut seen = self.seen_msgs.lock().unwrap();
  349. seen.push(msg_id.clone(), true);
  350. }
  351. let mut arg_data = vec![];
  352. timest.encode_async(&mut arg_data).await.unwrap();
  353. msg_id.encode_async(&mut arg_data).await.unwrap();
  354. msg.nick.encode_async(&mut arg_data).await.unwrap();
  355. msg.msg.encode_async(&mut arg_data).await.unwrap();
  356. // Broadcast the msg
  357. if let Err(e) = evgr.dag_insert(&[event.clone()]).await {
  358. error!(target: "darkirc", "Failed inserting new event to DAG: {}", e);
  359. }
  360. self.p2p.broadcast(&EventPut(event)).await;
  361. }
  362. async fn connect_notify(self: Arc<Self>, channel_sub: Subscription<DarkFiResult<ChannelPtr>>) {
  363. loop {
  364. // Wait for a channel
  365. if let Err(_) = channel_sub.receive().await {
  366. e!("There was an error listening for channels. The service closed unexpectedly.");
  367. return
  368. }
  369. let peers_count = self.p2p.hosts().peers().len() as u32;
  370. let node = self.node.upgrade().unwrap();
  371. node.trigger("connect", serialize(&peers_count)).await.unwrap();
  372. }
  373. }
  374. }
  375. #[async_trait]
  376. impl PluginObject for DarkIrc {
  377. async fn start(self: Arc<Self>, ex: ExecutorPtr) {
  378. i!("Registering EventGraph P2P protocol");
  379. let event_graph_ = Arc::clone(&self.event_graph);
  380. let registry = self.p2p.protocol_registry();
  381. registry
  382. .register(SESSION_DEFAULT, move |channel, _| {
  383. let event_graph_ = event_graph_.clone();
  384. async move { ProtocolEventGraph::init(event_graph_, channel).await.unwrap() }
  385. })
  386. .await;
  387. let me = Arc::downgrade(&self);
  388. let node = &self.node.upgrade().unwrap();
  389. let method_sub = node.subscribe_method_call("send").unwrap();
  390. let me2 = me.clone();
  391. let send_method_task =
  392. ex.spawn(async move { while Self::process_send(&me2, &method_sub).await {} });
  393. let mut on_modify = OnModify::new(ex.clone(), self.node.clone(), me.clone());
  394. async fn save_nick(self_: Arc<DarkIrc>) {
  395. let _ = std::fs::write(nick_filename(), self_.nick.get());
  396. }
  397. on_modify.when_change(self.nick.prop(), save_nick);
  398. let ev_sub = self.event_graph.event_pub.clone().subscribe().await;
  399. let ev_task = ex.spawn(self.clone().relay_events(ev_sub));
  400. // Sync the DAG
  401. let channel_sub = self.p2p.hosts().subscribe_channel().await;
  402. let dag_task = ex.spawn(self.clone().dag_sync(channel_sub));
  403. let channel_sub = self.p2p.hosts().subscribe_channel().await;
  404. let connect_notify_task = ex.spawn(self.clone().connect_notify(channel_sub));
  405. let mut tasks = vec![send_method_task, ev_task, dag_task, connect_notify_task];
  406. tasks.append(&mut on_modify.tasks);
  407. self.tasks.set(tasks);
  408. }
  409. }