darkirc.rs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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 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, PropertyPtr, PropertyType, PropertyValue, Role},
  42. scene::{MethodCallSub, Pimpl, SceneNode, SceneNodeType, SceneNodePtr, SceneNodeWeak},
  43. ui::{
  44. chatview::{MessageId, Timestamp},
  45. OnModify,
  46. },
  47. ExecutorPtr,
  48. };
  49. use super::{PluginObject, PluginSettings};
  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, get_external_storage_path};
  60. use std::path::PathBuf;
  61. pub fn get_evgrdb_path() -> PathBuf {
  62. get_external_storage_path().join("evgr")
  63. }
  64. pub fn get_use_tor_filename() -> PathBuf {
  65. get_external_storage_path().join("use_tor.txt")
  66. }
  67. pub fn nick_filename() -> PathBuf {
  68. get_appdata_path().join("/nick.txt")
  69. }
  70. pub fn p2p_datastore_path() -> PathBuf {
  71. get_appdata_path().join("darkirc_p2p")
  72. }
  73. pub fn hostlist_path() -> PathBuf {
  74. get_appdata_path().join("hostlist.tsv")
  75. }
  76. }
  77. #[cfg(not(target_os = "android"))]
  78. mod paths {
  79. use std::path::PathBuf;
  80. pub fn get_evgrdb_path() -> PathBuf {
  81. dirs::data_local_dir().unwrap().join("darkfi/app/evgr")
  82. }
  83. pub fn get_use_tor_filename() -> PathBuf {
  84. dirs::data_local_dir().unwrap().join("darkfi/app/use_tor.txt")
  85. }
  86. pub fn nick_filename() -> PathBuf {
  87. dirs::cache_dir().unwrap().join("darkfi/app/nick.txt")
  88. }
  89. pub fn p2p_datastore_path() -> PathBuf {
  90. dirs::cache_dir().unwrap().join("darkfi/app/darkirc_p2p")
  91. }
  92. pub fn hostlist_path() -> PathBuf {
  93. dirs::cache_dir().unwrap().join("darkfi/app/hostlist.tsv")
  94. }
  95. }
  96. use paths::*;
  97. macro_rules! t { ($($arg:tt)*) => { trace!(target: "plugin::darkirc", $($arg)*); } }
  98. macro_rules! d { ($($arg:tt)*) => { debug!(target: "plugin::darkirc", $($arg)*); } }
  99. macro_rules! i { ($($arg:tt)*) => { info!(target: "plugin::darkirc", $($arg)*); } }
  100. macro_rules! e { ($($arg:tt)*) => { error!(target: "plugin::darkirc", $($arg)*); } }
  101. macro_rules! w { ($($arg:tt)*) => { warn!(target: "plugin::darkirc", $($arg)*); } }
  102. #[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
  103. pub struct Privmsg {
  104. pub channel: String,
  105. pub nick: String,
  106. pub msg: String,
  107. }
  108. impl Privmsg {
  109. pub fn new(channel: String, nick: String, msg: String) -> Self {
  110. Self { channel, nick, msg }
  111. }
  112. pub fn msg_id(&self, timest: u64) -> MessageId {
  113. let mut hasher = blake3::Hasher::new();
  114. 0u8.encode(&mut hasher).unwrap();
  115. 0u8.encode(&mut hasher).unwrap();
  116. timest.encode(&mut hasher).unwrap();
  117. self.channel.encode(&mut hasher).unwrap();
  118. self.nick.encode(&mut hasher).unwrap();
  119. self.msg.encode(&mut hasher).unwrap();
  120. MessageId(hasher.finalize().into())
  121. }
  122. }
  123. struct SeenMsg {
  124. id: MessageId,
  125. is_self: bool,
  126. seen_times: usize,
  127. }
  128. struct SeenMessages {
  129. seen: Vec<SeenMsg>,
  130. }
  131. impl SeenMessages {
  132. fn new() -> Self {
  133. Self { seen: vec![] }
  134. }
  135. fn get_status(&self, id: &MessageId) -> Option<&SeenMsg> {
  136. self.seen.iter().find(|s| s.id == *id)
  137. }
  138. fn push(&mut self, id: MessageId, is_self: bool) {
  139. self.seen.push(SeenMsg { id, is_self, seen_times: 0 });
  140. }
  141. }
  142. pub type DarkIrcPtr = Arc<DarkIrc>;
  143. pub struct DarkIrc {
  144. node: SceneNodeWeak,
  145. tasks: OnceLock<Vec<smol::Task<()>>>,
  146. p2p: P2pPtr,
  147. event_graph: EventGraphPtr,
  148. db: sled::Db,
  149. seen_msgs: SyncMutex<SeenMessages>,
  150. nick: PropertyStr,
  151. settings: PluginSettings,
  152. }
  153. impl DarkIrc {
  154. pub async fn new(node: SceneNodeWeak, ex: ExecutorPtr) -> Result<Pimpl> {
  155. let node_ref = &node.upgrade().unwrap();
  156. let nick = PropertyStr::wrap(node_ref, Role::Internal, "nick", 0).unwrap();
  157. let mut setting_root = Arc::new(SceneNode::new("setting", SceneNodeType::SettingRoot));
  158. node_ref.clone().link(setting_root.clone());
  159. i!("Starting DarkIRC backend");
  160. let evgr_path = get_evgrdb_path();
  161. let db = match sled::open(&evgr_path) {
  162. Ok(db) => db,
  163. Err(err) => {
  164. e!("Sled database '{}' failed to open: {err}!", evgr_path.display());
  165. return Err(Error::SledDbErr);
  166. }
  167. };
  168. let setting_tree = db.open_tree("settings")?;
  169. let settings = PluginSettings {
  170. setting_root,
  171. sled_tree: setting_tree,
  172. };
  173. let mut p2p_settings: NetSettings = Default::default();
  174. p2p_settings.app_version = semver::Version::parse("0.5.0").unwrap();
  175. if get_use_tor_filename().exists() {
  176. i!("Setup P2P network [tor]");
  177. p2p_settings.outbound_connect_timeout = 60;
  178. p2p_settings.channel_handshake_timeout = 55;
  179. p2p_settings.channel_heartbeat_interval = 90;
  180. p2p_settings.outbound_peer_discovery_cooloff_time = 60;
  181. p2p_settings.seeds.push(
  182. url::Url::parse(
  183. "tor://czzulj66rr5kq3uhidzn7fh4qvt3vaxaoldukuxnl5vipayuj7obo7id.onion:5263",
  184. )
  185. .unwrap(),
  186. );
  187. p2p_settings.seeds.push(
  188. url::Url::parse(
  189. "tor://vgbfkcu5hcnlnwd2lz26nfoa6g6quciyxwbftm6ivvrx74yvv5jnaoid.onion:5273",
  190. )
  191. .unwrap(),
  192. );
  193. } else {
  194. i!("Setup P2P network [clearnet]");
  195. p2p_settings.outbound_connect_timeout = 40;
  196. p2p_settings.channel_handshake_timeout = 30;
  197. p2p_settings.seeds.push(url::Url::parse("tcp+tls://lilith1.dark.fi:5262").unwrap());
  198. p2p_settings.seeds.push(url::Url::parse("tcp+tls://agorism.dev:26661").unwrap());
  199. p2p_settings.seeds.push(url::Url::parse("tcp+tls://agorism.dev:26671").unwrap());
  200. }
  201. p2p_settings.p2p_datastore = p2p_datastore_path().into_os_string().into_string().ok();
  202. p2p_settings.hostlist = hostlist_path().into_os_string().into_string().ok();
  203. let node_outbound_connect_timeout = settings.add_setting("net.outbound_connect_timeout", PropertyValue::Uint32(p2p_settings.outbound_connect_timeout as u32)).unwrap();
  204. let node_channel_handshake_timeout = settings.add_setting("net.channel_handshake_timeout", PropertyValue::Uint32(p2p_settings.channel_handshake_timeout as u32)).unwrap();
  205. let node_channel_heartbeat_interval = settings.add_setting("net.channel_heartbeat_interval", PropertyValue::Uint32(p2p_settings.channel_heartbeat_interval as u32)).unwrap();
  206. let node_outbound_peer_discovery_cooloff_time = settings.add_setting("net.outbound_peer_discovery_cooloff_time", PropertyValue::Uint32(p2p_settings.outbound_peer_discovery_cooloff_time as u32)).unwrap();
  207. let node_slot_preference_strict = settings.add_setting("net.slot_preference_strict", PropertyValue::Bool(p2p_settings.slot_preference_strict)).unwrap();
  208. let node_transport_mixing = settings.add_setting("net.transport_mixing", PropertyValue::Bool(p2p_settings.transport_mixing)).unwrap();
  209. let node_localnet = settings.add_setting("net.localnet", PropertyValue::Bool(p2p_settings.localnet)).unwrap();
  210. settings.load_settings();
  211. p2p_settings.outbound_connect_timeout = node_outbound_connect_timeout.get_property_u32("value").unwrap() as u64;
  212. p2p_settings.channel_handshake_timeout = node_channel_handshake_timeout.get_property_u32("value").unwrap() as u64;
  213. p2p_settings.channel_heartbeat_interval = node_channel_heartbeat_interval.get_property_u32("value").unwrap() as u64;
  214. p2p_settings.outbound_peer_discovery_cooloff_time = node_outbound_peer_discovery_cooloff_time.get_property_u32("value").unwrap() as u64;
  215. p2p_settings.slot_preference_strict = node_slot_preference_strict.get_property_bool("value").unwrap();
  216. p2p_settings.transport_mixing = node_transport_mixing.get_property_bool("value").unwrap();
  217. p2p_settings.localnet = node_localnet.get_property_bool("value").unwrap();
  218. let p2p = match P2p::new(p2p_settings.clone(), ex.clone()).await {
  219. Ok(p2p) => p2p,
  220. Err(err) => {
  221. e!("Create p2p network failed: {err}!");
  222. return Err(Error::ServiceFailed);
  223. }
  224. };
  225. let event_graph = match EventGraph::new(
  226. p2p.clone(),
  227. db.clone(),
  228. std::path::PathBuf::new(),
  229. false,
  230. "darkirc_dag",
  231. 1,
  232. ex.clone(),
  233. )
  234. .await
  235. {
  236. Ok(evgr) => evgr,
  237. Err(err) => {
  238. e!("Create event graph failed: {err}!");
  239. return Err(Error::ServiceFailed);
  240. }
  241. };
  242. if let Ok(prev_nick) = std::fs::read_to_string(nick_filename()) {
  243. nick.set(&mut PropertyAtomicGuard::new(), prev_nick);
  244. }
  245. let self_ = Arc::new(Self {
  246. node: node.clone(),
  247. tasks: OnceLock::new(),
  248. p2p,
  249. event_graph,
  250. db,
  251. seen_msgs: SyncMutex::new(SeenMessages::new()),
  252. nick,
  253. settings,
  254. });
  255. Ok(Pimpl::DarkIrc(self_))
  256. }
  257. async fn dag_sync(self: Arc<Self>, channel_sub: Subscription<DarkFiResult<ChannelPtr>>) {
  258. i!("Starting p2p network");
  259. while let Err(err) = self.p2p.clone().start().await {
  260. // This usually means we cannot listen on the inbound ports
  261. e!("Failed to start p2p network: {err}!");
  262. e!("Usually this means there is another process listening on the same ports.");
  263. e!("Trying again in {P2P_RETRY_TIME} secs");
  264. sleep(P2P_RETRY_TIME).await;
  265. }
  266. i!("Waiting for some P2P connections...");
  267. let mut sync_attempt = 0;
  268. loop {
  269. // Wait for a channel
  270. if let Err(err) = channel_sub.receive().await {
  271. w!("There was an error listening for channels. The service closed unexpectedly with error: {err}");
  272. continue
  273. }
  274. let peers_count = self.p2p.peers_count();
  275. self.notify_connect(peers_count, false).await;
  276. // Wait until we have enough connections
  277. if peers_count < SYNC_MIN_PEERS {
  278. i!("Connected to {peers_count} peers. Waiting for more connections.");
  279. continue
  280. }
  281. sync_attempt += 1;
  282. // Cool off periodically
  283. if sync_attempt > COOLOFF_SYNC_ATTEMPTS {
  284. i!("Wasn't able to sync yet. Cooling off for {COOLOFF_SLEEP_TIME} then will try again.");
  285. sleep(COOLOFF_SLEEP_TIME).await;
  286. sync_attempt = 0;
  287. }
  288. i!("Syncing event DAG (attempt #{sync_attempt})");
  289. match self.event_graph.dag_sync().await {
  290. Ok(()) => break,
  291. Err(e) => {
  292. // TODO: Maybe at this point we should prune or something?
  293. // TODO: Or maybe just tell the user to delete the DAG from FS.
  294. w!("Failed DAG sync: ({e}). Waiting for more connections before retry.");
  295. }
  296. }
  297. }
  298. let peers_count = self.p2p.peers_count();
  299. self.notify_connect(peers_count, true).await;
  300. // Initial sync finished. Now just notify of connection changes
  301. loop {
  302. // Wait for a channel
  303. if let Err(err) = channel_sub.receive().await {
  304. w!("There was an error listening for channels. The service closed unexpectedly with error: {err}");
  305. continue
  306. }
  307. let peers_count = self.p2p.peers_count();
  308. self.notify_connect(peers_count, true).await;
  309. }
  310. }
  311. async fn notify_connect(&self, peers_count: usize, is_dag_synced: bool) {
  312. let node = self.node.upgrade().unwrap();
  313. node.trigger("connect", serialize(&(peers_count as u32, is_dag_synced))).await.unwrap();
  314. }
  315. async fn relay_events(self: Arc<Self>, ev_sub: Subscription<event_graph::Event>) {
  316. loop {
  317. let ev = ev_sub.receive().await;
  318. // Try to deserialize the `Event`'s content into a `Privmsg`
  319. let privmsg: Privmsg = match deserialize_async(ev.content()).await {
  320. Ok(v) => v,
  321. Err(e) => {
  322. e!("[IRC CLIENT] Failed deserializing incoming Privmsg event: {}", e);
  323. continue
  324. }
  325. };
  326. let mut timest = ev.timestamp;
  327. let msg_id = privmsg.msg_id(timest);
  328. t!(
  329. "Relaying ev_id={:?}, ev={ev:?}, msg_id={msg_id}, privmsg={privmsg:?}, timest={timest}",
  330. ev.id(),
  331. );
  332. let is_self = {
  333. let mut is_self = false;
  334. let mut seen = self.seen_msgs.lock().unwrap();
  335. match seen.get_status(&msg_id) {
  336. Some(msg) => {
  337. is_self = msg.is_self;
  338. if !msg.is_self || msg.seen_times > 1 {
  339. warn!(target: "plugin::darkirc", "Skipping duplicate seen message: {msg_id}");
  340. continue
  341. }
  342. }
  343. None => {
  344. seen.push(msg_id.clone(), false);
  345. }
  346. }
  347. is_self
  348. };
  349. // This is a hack to make messages appear sequentially in the UI
  350. let now_timest = UNIX_EPOCH.elapsed().unwrap().as_millis() as u64;
  351. if !is_self && timest.abs_diff(now_timest) < RECENT_TIME_DIST {
  352. d!("Applied timestamp correction: <{timest}> => <{now_timest}>");
  353. timest = now_timest;
  354. }
  355. // Strip off starting #
  356. let mut channel = privmsg.channel;
  357. if channel.is_empty() {
  358. warn!(target: "plugin::darkirc", "Received privmsg with empty channel!");
  359. continue
  360. }
  361. if channel.chars().next().unwrap() != '#' {
  362. warn!(target: "plugin::darkirc", "Skipping encrypted channel: {channel}");
  363. continue
  364. }
  365. channel.remove(0);
  366. // Workaround for the chatview hack. This nick is off limits!
  367. let mut nick = privmsg.nick;
  368. if nick == "NOTICE" {
  369. nick = "noticer".to_string();
  370. }
  371. let mut arg_data = vec![];
  372. channel.encode(&mut arg_data).unwrap();
  373. timest.encode(&mut arg_data).unwrap();
  374. msg_id.encode(&mut arg_data).unwrap();
  375. nick.encode(&mut arg_data).unwrap();
  376. privmsg.msg.encode(&mut arg_data).unwrap();
  377. let node = self.node.upgrade().unwrap();
  378. node.trigger("recv", arg_data).await.unwrap();
  379. }
  380. }
  381. async fn process_send(me: &Weak<Self>, sub: &MethodCallSub) -> bool {
  382. let Ok(method_call) = sub.receive().await else {
  383. d!("Event relayer closed");
  384. return false
  385. };
  386. t!("method called: send({method_call:?})");
  387. assert!(method_call.send_res.is_none());
  388. fn decode_data(data: &[u8]) -> std::io::Result<(Timestamp, String, String)> {
  389. let mut cur = Cursor::new(&data);
  390. let timest = Timestamp::decode(&mut cur).unwrap();
  391. let channel = String::decode(&mut cur)?;
  392. let msg = String::decode(&mut cur)?;
  393. Ok((timest, channel, msg))
  394. }
  395. let Ok((timest, channel, msg)) = decode_data(&method_call.data) else {
  396. e!("send() method invalid arg data");
  397. return true
  398. };
  399. let Some(self_) = me.upgrade() else {
  400. // Should not happen
  401. panic!("self destroyed before send_method_task was stopped!");
  402. };
  403. self_.handle_send(timest, channel, msg).await;
  404. true
  405. }
  406. async fn handle_send(&self, timest: Timestamp, channel: String, msg: String) {
  407. let nick = self.nick.get();
  408. // Send text to channel
  409. d!("Sending privmsg: {timest} {channel}: <{nick}> {msg}");
  410. let msg = Privmsg::new(channel, nick, msg);
  411. let evgr = self.event_graph.clone();
  412. let mut event = event_graph::Event::new(serialize_async(&msg).await, &evgr).await;
  413. event.timestamp = timest;
  414. let msg_id = msg.msg_id(timest);
  415. // Keep track of our own messages so we don't apply timestamp correction to them
  416. // which messes up the msg id.
  417. {
  418. let mut seen = self.seen_msgs.lock().unwrap();
  419. seen.push(msg_id.clone(), true);
  420. }
  421. let mut arg_data = vec![];
  422. timest.encode_async(&mut arg_data).await.unwrap();
  423. msg_id.encode_async(&mut arg_data).await.unwrap();
  424. msg.nick.encode_async(&mut arg_data).await.unwrap();
  425. msg.msg.encode_async(&mut arg_data).await.unwrap();
  426. // Broadcast the msg
  427. if let Err(e) = evgr.dag_insert(&[event.clone()]).await {
  428. error!(target: "darkirc", "Failed inserting new event to DAG: {}", e);
  429. }
  430. self.p2p.broadcast(&EventPut(event)).await;
  431. }
  432. async fn apply_settings(self_: Arc<Self>) {
  433. self_.settings.save_settings();
  434. i!("TODO: Apply darkirc settings");
  435. }
  436. }
  437. #[async_trait]
  438. impl PluginObject for DarkIrc {
  439. async fn start(self: Arc<Self>, ex: ExecutorPtr) {
  440. i!("Registering EventGraph P2P protocol");
  441. let event_graph_ = Arc::clone(&self.event_graph);
  442. let registry = self.p2p.protocol_registry();
  443. registry
  444. .register(SESSION_DEFAULT, move |channel, _| {
  445. let event_graph_ = event_graph_.clone();
  446. async move { ProtocolEventGraph::init(event_graph_, channel).await.unwrap() }
  447. })
  448. .await;
  449. let me = Arc::downgrade(&self);
  450. let node = &self.node.upgrade().unwrap();
  451. let method_sub = node.subscribe_method_call("send").unwrap();
  452. let me2 = me.clone();
  453. let send_method_task =
  454. ex.spawn(async move { while Self::process_send(&me2, &method_sub).await {} });
  455. let mut on_modify = OnModify::new(ex.clone(), self.node.clone(), me.clone());
  456. async fn save_nick(self_: Arc<DarkIrc>) {
  457. let _ = std::fs::write(nick_filename(), self_.nick.get());
  458. }
  459. on_modify.when_change(self.nick.prop(), save_nick);
  460. // `apply_settings` is triggered if any setting changes
  461. for setting_node in self.settings.setting_root.get_children().iter() {
  462. on_modify.when_change(setting_node.get_property("value").clone().unwrap(), Self::apply_settings);
  463. }
  464. let ev_sub = self.event_graph.event_pub.clone().subscribe().await;
  465. let ev_task = ex.spawn(self.clone().relay_events(ev_sub));
  466. // Sync the DAG
  467. let channel_sub = self.p2p.hosts().subscribe_channel().await;
  468. let dag_task = ex.spawn(self.clone().dag_sync(channel_sub));
  469. let mut tasks = vec![send_method_task, ev_task, dag_task];
  470. tasks.append(&mut on_modify.tasks);
  471. self.tasks.set(tasks);
  472. }
  473. }