darkirc.rs 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 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. io::Cursor,
  21. sync::{Arc, OnceLock, Weak},
  22. time::UNIX_EPOCH,
  23. };
  24. use async_lock::RwLock;
  25. use crypto_box::{ChaChaBox, PublicKey, SecretKey};
  26. use darkfi::{
  27. event_graph::{
  28. self,
  29. proto::{EventPut, ProtocolEventGraph},
  30. EventGraph, EventGraphConfig, EventGraphPtr,
  31. },
  32. net::{
  33. dnet::DnetEvent,
  34. session::SESSION_DEFAULT,
  35. settings::{MagicBytes, NetworkProfile, Settings as NetSettings},
  36. ChannelPtr, P2p, P2pPtr,
  37. },
  38. system::{sleep, Subscription},
  39. Result as DarkFiResult,
  40. };
  41. use darkfi_serial::{
  42. deserialize_async, serialize, serialize_async, AsyncEncodable, Decodable, Encodable,
  43. };
  44. use irc2::{
  45. crypto::saltbox,
  46. irc::{server::MAX_NICK_LEN, IrcChannel, IrcContact},
  47. pad, unpad, Privmsg,
  48. };
  49. use parking_lot::Mutex as SyncMutex;
  50. use sled_overlay::sled;
  51. use crate::{
  52. app::schema::menu::{channel::Channel, contact::Contact},
  53. error::{Error, Result},
  54. prop::{BatchGuardPtr, PropertyAtomicGuard, PropertyPtr, PropertyStr, Role},
  55. scene::{MethodCallSub, Pimpl, SceneNode, SceneNodePtr, SceneNodeType, SceneNodeWeak, Slot},
  56. ui::{
  57. chatview::{MessageId, Timestamp},
  58. OnModify,
  59. },
  60. ExecutorPtr,
  61. };
  62. use super::PluginSettings;
  63. const P2P_RETRY_TIME: u64 = 20;
  64. const COOLOFF_SLEEP_TIME: u64 = 20;
  65. const COOLOFF_SYNC_ATTEMPTS: usize = 6;
  66. const SYNC_MIN_PEERS: usize = 2;
  67. pub(crate) const P2P_OUTBOUND_ACTIVE: usize = 6;
  68. const P2P_OUTBOUND_SLEEP: usize = 1;
  69. /// Update `outbound_peers` property useful for diagnostics
  70. const DNET_ENABLED: bool = true;
  71. /// Due to drift between different machine's clocks, if the message timestamp is recent
  72. /// then we will just correct it to the current time so messages appear sequential in the UI.
  73. const RECENT_TIME_DIST: u64 = 25_000;
  74. // NOTE: if `paths` already lives in a shared module (e.g. `super::paths` from
  75. // darkirc.rs's parent module), delete this block and add `use super::paths::*;`
  76. // instead. Duplicated here so this file compiles standalone.
  77. #[cfg(target_os = "android")]
  78. mod paths {
  79. use crate::android::{get_appdata_path, get_external_storage_path};
  80. use std::path::PathBuf;
  81. pub fn get_evgrdb_path() -> PathBuf {
  82. get_external_storage_path().join("evgr2")
  83. }
  84. pub fn get_chatdb_path() -> PathBuf {
  85. get_external_storage_path().join("chatdb")
  86. }
  87. pub fn get_use_tor_filename() -> PathBuf {
  88. get_external_storage_path().join("use_tor.txt")
  89. }
  90. pub fn nick_filename() -> PathBuf {
  91. get_appdata_path().join("/nick2.txt")
  92. }
  93. pub fn p2p_datastore_path() -> PathBuf {
  94. get_appdata_path().join("darkirc2_p2p")
  95. }
  96. pub fn hostlist_path() -> PathBuf {
  97. get_appdata_path().join("hostlist2.tsv")
  98. }
  99. }
  100. #[cfg(not(target_os = "android"))]
  101. mod paths {
  102. use std::path::PathBuf;
  103. pub fn get_evgrdb_path() -> PathBuf {
  104. dirs::data_local_dir().unwrap().join("darkfi/app/evgr2")
  105. }
  106. pub fn get_chatdb_path() -> PathBuf {
  107. dirs::data_local_dir().unwrap().join("darkfi/app/chatdb")
  108. }
  109. pub fn get_use_tor_filename() -> PathBuf {
  110. dirs::data_local_dir().unwrap().join("darkfi/app/use_tor.txt")
  111. }
  112. pub fn nick_filename() -> PathBuf {
  113. dirs::cache_dir().unwrap().join("darkfi/app/nick2.txt")
  114. }
  115. pub fn p2p_datastore_path() -> PathBuf {
  116. dirs::cache_dir().unwrap().join("darkfi/app/darkirc2_p2p")
  117. }
  118. pub fn hostlist_path() -> PathBuf {
  119. dirs::cache_dir().unwrap().join("darkfi/app/hostlist2.tsv")
  120. }
  121. }
  122. use paths::*;
  123. macro_rules! t { ($($arg:tt)*) => { trace!(target: "plugin::darkirc2", $($arg)*); } }
  124. macro_rules! d { ($($arg:tt)*) => { debug!(target: "plugin::darkirc2", $($arg)*); } }
  125. macro_rules! i { ($($arg:tt)*) => { info!(target: "plugin::darkirc2", $($arg)*); } }
  126. macro_rules! e { ($($arg:tt)*) => { error!(target: "plugin::darkirc2", $($arg)*); } }
  127. macro_rules! w { ($($arg:tt)*) => { warn!(target: "plugin::darkirc2", $($arg)*); } }
  128. struct SeenMsg {
  129. id: MessageId,
  130. is_self: bool,
  131. seen_times: usize,
  132. }
  133. struct SeenMessages {
  134. seen: Vec<SeenMsg>,
  135. }
  136. impl SeenMessages {
  137. fn new() -> Self {
  138. Self { seen: vec![] }
  139. }
  140. fn get_status(&self, id: &MessageId) -> Option<&SeenMsg> {
  141. self.seen.iter().find(|s| s.id == *id)
  142. }
  143. fn push(&mut self, id: MessageId, is_self: bool) {
  144. self.seen.push(SeenMsg { id, is_self, seen_times: 0 });
  145. }
  146. }
  147. pub type DarkIrcPtr = Arc<DarkIrc>;
  148. pub struct DarkIrc {
  149. node: SceneNodeWeak,
  150. tasks: SyncMutex<Vec<smol::Task<()>>>,
  151. p2p: P2pPtr,
  152. event_graph: EventGraphPtr,
  153. seen_msgs: SyncMutex<SeenMessages>,
  154. nick: PropertyStr,
  155. pub channels: RwLock<HashMap<String, IrcChannel>>,
  156. pub contacts: RwLock<HashMap<String, IrcContact>>,
  157. channels_tree: sled::Tree,
  158. contacts_tree: sled::Tree,
  159. dm_secret: SecretKey,
  160. settings: PluginSettings,
  161. ex: ExecutorPtr,
  162. }
  163. impl DarkIrc {
  164. pub async fn new(
  165. node: SceneNodeWeak,
  166. sg_root: SceneNodePtr,
  167. ex: ExecutorPtr,
  168. db: sled::Db,
  169. ) -> Result<Pimpl> {
  170. let node_ref = &node.upgrade().unwrap();
  171. let nick = PropertyStr::wrap(node_ref, Role::Internal, "nick", 0).unwrap();
  172. let setting_root = Arc::new(SceneNode::new("setting", SceneNodeType::SettingRoot));
  173. node_ref.link(setting_root.clone());
  174. i!("Starting DarkIRC backend");
  175. let evgr_path = get_evgrdb_path();
  176. let evgr_db = match sled::open(&evgr_path) {
  177. Ok(db) => db,
  178. Err(err) => {
  179. e!("Sled database '{}' failed to open: {err}!", evgr_path.display());
  180. return Err(Error::SledDbErr)
  181. }
  182. };
  183. let setting_tree = evgr_db.open_tree("settings")?;
  184. // Use the unified db for reading channels (UI stores channels there)
  185. let channels_tree = db.open_tree("channels")?;
  186. i!("Opened channels tree from unified db");
  187. let contacts_tree = db.open_tree("contacts")?;
  188. i!("Opened contacts tree from unified db");
  189. let dm_secret = Self::load_or_create_dm_identity(&db);
  190. let dm_public_b58 = bs58::encode(dm_secret.public_key().to_bytes()).into_string();
  191. // Expose our DM public key on the plugin node so it can be displayed/shared.
  192. node_ref
  193. .set_property_str(
  194. &mut PropertyAtomicGuard::none(),
  195. Role::Internal,
  196. "dm_public",
  197. &dm_public_b58,
  198. )
  199. .unwrap();
  200. i!("DM identity public key (share with contacts): {dm_public_b58}");
  201. let settings = PluginSettings { setting_root, sled_tree: setting_tree };
  202. let mut p2p_settings: NetSettings = Default::default();
  203. p2p_settings.magic_bytes = MagicBytes([251, 229, 199, 181]);
  204. p2p_settings.app_version = semver::Version::parse("0.5.0").unwrap();
  205. p2p_settings.app_name = "darkirc".to_string();
  206. if get_use_tor_filename().exists() {
  207. i!("Setup P2P network [tor]");
  208. let mut tor_profile = NetworkProfile::tor_default();
  209. tor_profile.outbound_connect_timeout = 60;
  210. p2p_settings.profiles.insert("tor".to_string(), tor_profile);
  211. p2p_settings.outbound_peer_discovery_cooloff_time = 60;
  212. p2p_settings.seeds.push(
  213. url::Url::parse(
  214. "tor://g7fxelebievvpr27w7gt24lflptpw3jeeuvafovgliq5utdst6xyruyd.onion:25552",
  215. )
  216. .unwrap(),
  217. );
  218. p2p_settings.seeds.push(
  219. url::Url::parse(
  220. "tor://yvklzjnfmwxhyodhrkpomawjcdvcaushsj6torjz2gyd7e25f3gfunyd.onion:25552",
  221. )
  222. .unwrap(),
  223. );
  224. p2p_settings.active_profiles = vec!["tor".to_string()];
  225. } else {
  226. i!("Setup P2P network [clearnet]");
  227. let mut profile = NetworkProfile::default();
  228. profile.outbound_connect_timeout = 40;
  229. profile.channel_handshake_timeout = 30;
  230. p2p_settings.profiles.insert("tcp+tls".to_string(), profile);
  231. p2p_settings.outbound_connections = 5;
  232. p2p_settings.inbound_connections = 2;
  233. p2p_settings.seeds.push(url::Url::parse("tcp+tls://lilith0.dark.fi:9600").unwrap());
  234. p2p_settings.seeds.push(url::Url::parse("tcp+tls://lilith1.dark.fi:9600").unwrap());
  235. p2p_settings.active_profiles = vec!["tcp+tls".to_string()];
  236. }
  237. p2p_settings.p2p_datastore = p2p_datastore_path().into_os_string().into_string().ok();
  238. p2p_settings.hostlist = hostlist_path().into_os_string().into_string().ok();
  239. settings.add_p2p_settings(&p2p_settings);
  240. settings.load_settings();
  241. settings.update_p2p_settings(&mut p2p_settings);
  242. let p2p = match P2p::new(p2p_settings.clone(), ex.clone()).await {
  243. Ok(p2p) => p2p,
  244. Err(err) => {
  245. e!("Create p2p network failed: {err}!");
  246. return Err(Error::ServiceFailed)
  247. }
  248. };
  249. if DNET_ENABLED {
  250. i!("Enabling dnet outbound-slot event stream for outbound_peers property");
  251. p2p.dnet_enable();
  252. }
  253. let event_graph = match EventGraph::new(
  254. p2p.clone(),
  255. db.clone(),
  256. std::path::PathBuf::new(),
  257. false,
  258. EventGraphConfig {
  259. initial_genesis: 1_704_067_200_000,
  260. hours_rotation: 1,
  261. genesis_contents: b"darkirc-v1".to_vec(),
  262. rln_enabled: false,
  263. pregenerated_identity_commitments: vec![],
  264. max_dags: Some(24),
  265. },
  266. ex.clone(),
  267. )
  268. .await
  269. {
  270. Ok(evgr) => evgr,
  271. Err(err) => {
  272. e!("Create event graph failed: {err}!");
  273. return Err(Error::ServiceFailed)
  274. }
  275. };
  276. if let Ok(prev_nick) = std::fs::read_to_string(nick_filename()) {
  277. nick.set(&mut PropertyAtomicGuard::none(), prev_nick);
  278. }
  279. let self_ = Arc::new(Self {
  280. node: node.clone(),
  281. tasks: SyncMutex::new(vec![]),
  282. p2p,
  283. event_graph,
  284. seen_msgs: SyncMutex::new(SeenMessages::new()),
  285. nick,
  286. channels: RwLock::new(HashMap::new()),
  287. contacts: RwLock::new(HashMap::new()),
  288. channels_tree,
  289. contacts_tree,
  290. dm_secret,
  291. settings,
  292. ex: ex.clone(),
  293. });
  294. self_.load_channels_from_db().await;
  295. self_.load_contacts_from_db().await;
  296. self_.clone().start(sg_root, ex).await;
  297. Ok(Pimpl::DarkIrc(self_))
  298. }
  299. async fn dag_sync(self: Arc<Self>, channel_sub: Subscription<DarkFiResult<ChannelPtr>>) {
  300. i!("Starting p2p network");
  301. while let Err(err) = self.p2p.clone().start().await {
  302. // This usually means we cannot listen on the inbound ports
  303. e!("Failed to start p2p network: {err}!");
  304. e!("Usually this means there is another process listening on the same ports.");
  305. e!("Trying again in {P2P_RETRY_TIME} secs");
  306. sleep(P2P_RETRY_TIME).await;
  307. }
  308. i!("Waiting for some P2P connections...");
  309. let mut sync_attempt = 0;
  310. // TODO: these should be configurable
  311. let fast_mode = false;
  312. let dags_count = 24;
  313. loop {
  314. if self.p2p.is_connected() {
  315. let peers_count = self.p2p.peers_count();
  316. self.notify_connect(peers_count, self.event_graph.is_synced()).await;
  317. // Wait until we have enough connections
  318. if peers_count < SYNC_MIN_PEERS {
  319. i!("Connected to {peers_count} peers. Waiting for more connections.");
  320. continue
  321. }
  322. i!("Got peer connection");
  323. sync_attempt += 1;
  324. // Cool off periodically
  325. if sync_attempt > COOLOFF_SYNC_ATTEMPTS {
  326. i!("Wasn't able to sync yet. Cooling off for {COOLOFF_SLEEP_TIME} then will try again.");
  327. sleep(COOLOFF_SLEEP_TIME).await;
  328. sync_attempt = 0;
  329. }
  330. i!("Syncing static DAG");
  331. match self.event_graph.static_sync().await {
  332. Ok(()) => {
  333. i!("Static synced successfully");
  334. // log_memory("after static sync");
  335. }
  336. Err(e) => {
  337. e!("Failed syncing static graph: {e}");
  338. self.p2p.stop().await;
  339. break
  340. }
  341. }
  342. i!("Syncing event DAG (attempt #{sync_attempt})");
  343. // Sync mode is now per-call: full sync replays
  344. // every event (heavy, used by archival nodes), fast
  345. // sync only fetches headers (light, used by clients
  346. // that don't need to re-verify history).
  347. let sync_result = if fast_mode {
  348. self.event_graph.sync_selected_headers(dags_count).await
  349. } else {
  350. self.event_graph.sync_selected(dags_count).await
  351. };
  352. match sync_result {
  353. Ok(()) => {
  354. i!(
  355. "Event DAG synced successfully ({} mode, {} dag(s))",
  356. if fast_mode { "fast" } else { "full" },
  357. dags_count,
  358. );
  359. break
  360. }
  361. Err(e) => {
  362. // TODO: Maybe at this point we should prune or something?
  363. // TODO: Or maybe just tell the user to delete the DAG from FS.
  364. e!("Failed syncing DAG ({e}), retrying...");
  365. }
  366. }
  367. } else {
  368. i!("Waiting for some P2P connections...");
  369. sleep(COOLOFF_SLEEP_TIME).await;
  370. }
  371. }
  372. let peers_count = self.p2p.peers_count();
  373. self.notify_connect(peers_count, self.event_graph.is_synced()).await;
  374. // Initial sync finished. Now just notify of connection changes
  375. loop {
  376. // Wait for a channel
  377. if let Err(err) = channel_sub.receive().await {
  378. w!("There was an error listening for channels. The service closed unexpectedly with error: {err}");
  379. continue
  380. }
  381. let peers_count = self.p2p.peers_count();
  382. self.notify_connect(peers_count, self.event_graph.is_synced()).await;
  383. }
  384. }
  385. /// Send a notification when there's a change in number of peers or the DAG sync status
  386. pub async fn notify_connect(&self, peers_count: usize, is_dag_synced: bool) {
  387. let node = self.node.upgrade().unwrap();
  388. node.trigger("connect", serialize(&(peers_count as u32, is_dag_synced))).await.unwrap();
  389. }
  390. /// Update the `outbound_peers` property with the outgoing connection slots addrs.
  391. /// Allows us to monitor the network state of our p2p node.
  392. async fn relay_outbound_slots(dnet_sub: Subscription<DnetEvent>, prop: PropertyPtr) {
  393. loop {
  394. let event = dnet_sub.receive().await;
  395. let (slot, kind, addr) = match event {
  396. DnetEvent::OutboundSlotConnected(info) => {
  397. (info.slot, "connected", Some(info.addr.to_string()))
  398. }
  399. DnetEvent::OutboundSlotConnecting(info) => (info.slot, "connecting", None),
  400. DnetEvent::OutboundSlotDisconnected(info) => (info.slot, "disconnected", None),
  401. DnetEvent::OutboundSlotSleeping(info) => (info.slot, "sleeping", None),
  402. _ => continue,
  403. };
  404. let mut atom = PropertyAtomicGuard::none();
  405. let idx = slot as usize;
  406. assert!(idx < prop.get_len());
  407. match addr {
  408. Some(addr) => prop.set_str(&mut atom, Role::Internal, idx, addr).unwrap(),
  409. None => prop.set_null(&mut atom, Role::Internal, idx).unwrap(),
  410. }
  411. }
  412. }
  413. async fn relay_events(self: Arc<Self>, ev_sub: Subscription<event_graph::Event>) {
  414. loop {
  415. let ev = ev_sub.receive().await;
  416. // Try to deserialize the `Event`'s content into a `Privmsg`
  417. let privmsg: Privmsg = match deserialize_async(ev.content()).await {
  418. Ok(v) => v,
  419. Err(e) => {
  420. e!("[IRC CLIENT] Failed deserializing incoming Privmsg event: {}", e);
  421. continue
  422. }
  423. };
  424. // Route the message. An already-decrypted (plaintext) message names a
  425. // channel we hold directly: encrypted channels arrive as base58
  426. // ciphertext, so a channel key we recognise is plaintext by definition
  427. // and is accepted as-is. Anything else must decrypt as a channel or DM;
  428. // undecryptable traffic (base58 garbage in neither map) is silently dropped.
  429. let mut privmsg = privmsg;
  430. // Is this a plaintext channel?
  431. let is_plaintext = self.channels.read().await.contains_key(&privmsg.channel);
  432. if !is_plaintext && !self.try_decrypt(&mut privmsg, &self.nick.get()).await {
  433. continue;
  434. }
  435. let mut timest = ev.header.timestamp;
  436. let msg_id = msg_id(&privmsg, timest);
  437. t!(
  438. "Relaying ev_id={:?}, ev={ev:?}, msg_id={msg_id}, privmsg={privmsg:?}, timest={timest}",
  439. ev.id(),
  440. );
  441. let is_self = {
  442. let mut is_self = false;
  443. let mut seen = self.seen_msgs.lock();
  444. match seen.get_status(&msg_id) {
  445. Some(msg) => {
  446. is_self = msg.is_self;
  447. if !msg.is_self || msg.seen_times > 1 {
  448. w!("Skipping duplicate seen message: {msg_id}");
  449. continue
  450. }
  451. }
  452. None => {
  453. seen.push(msg_id.clone(), false);
  454. }
  455. }
  456. is_self
  457. };
  458. // This is a hack to make messages appear sequentially in the UI
  459. let now_timest = UNIX_EPOCH.elapsed().unwrap().as_millis() as u64;
  460. if !is_self && timest.abs_diff(now_timest) < RECENT_TIME_DIST {
  461. d!("Applied timestamp correction: <{timest}> => <{now_timest}>");
  462. timest = now_timest;
  463. }
  464. // Workaround for the chatview hack. This nick is off limits!
  465. let mut nick = privmsg.nick;
  466. if nick == "NOTICE" {
  467. nick = "noticer".to_string();
  468. }
  469. self.notify_recv(privmsg.channel, timest, msg_id, nick, privmsg.msg).await;
  470. }
  471. }
  472. /// Send a notification about a new received message
  473. pub async fn notify_recv(
  474. &self,
  475. channel: String,
  476. timestamp: Timestamp,
  477. id: MessageId,
  478. nick: String,
  479. msg: String,
  480. ) {
  481. assert!(
  482. channel.starts_with('#') || channel.starts_with('@'),
  483. "notify_recv channel must be a \"#name\" channel or \"@name\" DM, got: {channel}"
  484. );
  485. let mut arg_data = vec![];
  486. channel.encode(&mut arg_data).unwrap();
  487. timestamp.encode(&mut arg_data).unwrap();
  488. id.encode(&mut arg_data).unwrap();
  489. nick.encode(&mut arg_data).unwrap();
  490. msg.encode(&mut arg_data).unwrap();
  491. let node = self.node.upgrade().unwrap();
  492. node.trigger("recv", arg_data).await.unwrap();
  493. }
  494. async fn process_send(me: &Weak<Self>, sub: &MethodCallSub) -> bool {
  495. let Ok(method_call) = sub.receive().await else {
  496. d!("Event relayer closed");
  497. return false
  498. };
  499. t!("method called: send({method_call:?})");
  500. assert!(method_call.send_res.is_none());
  501. fn decode_data(data: &[u8]) -> std::io::Result<(Timestamp, String, String)> {
  502. let mut cur = Cursor::new(&data);
  503. let timest = Timestamp::decode(&mut cur).unwrap();
  504. let channel = String::decode(&mut cur)?;
  505. let msg = String::decode(&mut cur)?;
  506. Ok((timest, channel, msg))
  507. }
  508. let Ok((timest, channel, msg)) = decode_data(&method_call.data) else {
  509. e!("send() method invalid arg data");
  510. return true
  511. };
  512. let Some(self_) = me.upgrade() else {
  513. // Should not happen
  514. panic!("self destroyed before send_method_task was stopped!");
  515. };
  516. self_.handle_send(timest, channel, msg).await;
  517. true
  518. }
  519. /// User wants to send a msg
  520. async fn handle_send(&self, timest: Timestamp, channel: String, msg: String) {
  521. let nick = self.nick.get();
  522. // Send text to channel
  523. d!("Sending privmsg: {timest} {channel}: <{nick}> {msg}");
  524. let mut msg = Privmsg { version: 0, msg_type: 0, channel, nick, msg };
  525. // DM layers use the "@name" UI id; strip it to the bare contact key and
  526. // require the contact to exist, else refuse to broadcast.
  527. if let Some(bare) = msg.channel.strip_prefix('@').map(str::to_string) {
  528. msg.channel = bare;
  529. if self.try_encrypt_dm(&mut msg).await.is_err() {
  530. e!("Refusing to send DM to unknown contact");
  531. return;
  532. }
  533. } else {
  534. assert!(msg.channel.starts_with('#'), "channel name must start with #");
  535. self.try_encrypt_channel(&mut msg).await;
  536. }
  537. let evgr = self.event_graph.clone();
  538. let event = event_graph::Event::with_timestamp(timest, serialize_async(&msg).await, &evgr)
  539. .await
  540. .unwrap();
  541. let msg_id = msg_id(&msg, timest);
  542. // Keep track of our own messages so we don't apply timestamp correction to them
  543. // which messes up the msg id.
  544. {
  545. let mut seen = self.seen_msgs.lock();
  546. seen.push(msg_id.clone(), true);
  547. }
  548. // Broadcast the msg
  549. let current_genesis = self.event_graph.current_genesis.read().await;
  550. let dag_name = current_genesis.header.timestamp.to_string();
  551. if let Err(e) = evgr.insert_signal_with_blob(&event, &[], &dag_name).await {
  552. e!("Failed inserting new event to DAG: {}", e);
  553. }
  554. if let Err(e) = self.p2p.broadcast(&EventPut(event, vec![])).await {
  555. e!("Event broadcast was not admitted: {e}");
  556. }
  557. }
  558. /// Load channels from UI database and populate encryption keys
  559. pub async fn load_channels_from_db(&self) {
  560. let mut channels = self.channels.write().await;
  561. for item in self.channels_tree.iter() {
  562. let (key, val) = item.unwrap();
  563. let channel_name = String::from_utf8_lossy(&key).to_string();
  564. let ui_channel = deserialize_async::<Channel>(&val).await.unwrap();
  565. // Convert to IrcChannel with encryption
  566. let full_name = format!("#{}", channel_name);
  567. let mut irc_channel =
  568. IrcChannel { topic: String::new(), nicks: HashSet::new(), saltbox: None };
  569. if let Some(secret) = ui_channel.secret {
  570. // Convert secret array to SecretKey first, then derive PublicKey
  571. let secret_key = SecretKey::from_bytes(secret);
  572. let public = secret_key.public_key();
  573. let saltbox = ChaChaBox::new(&public, &secret_key);
  574. // Log the secret in base58 for debugging
  575. let secret_b58 = bs58::encode(secret).into_string();
  576. irc_channel.saltbox = Some(Arc::new(saltbox));
  577. }
  578. let is_encrypted = irc_channel.saltbox.is_some();
  579. channels.insert(full_name, irc_channel);
  580. i!("Loaded channel: #{} (encrypted: {})", channel_name, is_encrypted);
  581. }
  582. }
  583. /// Load (or generate on first run) the single global DM identity key.
  584. fn load_or_create_dm_identity(db: &sled::Db) -> SecretKey {
  585. let tree = db.open_tree("dm_identity").expect("cannot open dm_identity tree");
  586. if let Ok(Some(stored)) = tree.get(b"secret") {
  587. if stored.len() == 32 {
  588. let arr: [u8; 32] = stored.as_ref().try_into().unwrap();
  589. return SecretKey::from_bytes(arr);
  590. }
  591. }
  592. let bytes: [u8; 32] = rand::random();
  593. let _ = tree.insert(b"secret", bytes.to_vec());
  594. let _ = tree.flush();
  595. SecretKey::from_bytes(bytes)
  596. }
  597. /// Load contacts from the UI database and build their encryption boxes.
  598. pub async fn load_contacts_from_db(&self) {
  599. let mut contacts = self.contacts.write().await;
  600. contacts.clear();
  601. for item in self.contacts_tree.iter() {
  602. let (key, val) = item.unwrap();
  603. let name = String::from_utf8_lossy(&key).to_string();
  604. let contact = deserialize_async::<Contact>(&val).await.unwrap();
  605. let their_public = PublicKey::from(contact.public);
  606. let saltbox = Arc::new(ChaChaBox::new(&their_public, &self.dm_secret));
  607. let self_saltbox =
  608. Arc::new(ChaChaBox::new(&self.dm_secret.public_key(), &self.dm_secret));
  609. contacts.insert(name.clone(), IrcContact { saltbox, self_saltbox });
  610. i!("Loaded contact: {name}");
  611. }
  612. }
  613. async fn rescan_channel_history(self: Arc<Self>, channel: String) {
  614. i!("Starting background rescan for channel: {channel}");
  615. // Fetch and order all events from the DAG (like darkirc does)
  616. let Ok(dag_events) = self.event_graph.order_events().await else {
  617. e!("Failed to fetch events from DAG");
  618. return;
  619. };
  620. let mut found_count = 0;
  621. for event in dag_events.iter() {
  622. // Deserialize Privmsg
  623. let mut privmsg = match deserialize_async::<Privmsg>(event.content()).await {
  624. Ok(pm) => pm,
  625. Err(e) => {
  626. t!("Not a Privmsg event, skipping");
  627. continue;
  628. }
  629. };
  630. // Try to decrypt (handles encrypted channels)
  631. self.try_decrypt(&mut privmsg, &self.nick.get()).await;
  632. // Check if message belongs to target channel
  633. if privmsg.channel != channel {
  634. continue;
  635. }
  636. found_count += 1;
  637. // Calculate message ID
  638. let timest = event.header.timestamp;
  639. let msg_id = msg_id(&privmsg, timest);
  640. // Send to ChatView via notify_recv (handles DB storage and duplicates)
  641. self.notify_recv(
  642. channel.clone(),
  643. timest,
  644. msg_id,
  645. privmsg.nick.clone(),
  646. privmsg.msg.clone(),
  647. )
  648. .await;
  649. }
  650. i!("Rescan complete for {channel}: found {found_count} messages");
  651. }
  652. async fn process_rescan(me: &Weak<Self>, sub: &MethodCallSub) -> bool {
  653. let Ok(method_call) = sub.receive().await else {
  654. d!("Rescan method closed");
  655. return false
  656. };
  657. t!("method called: rescan({method_call:?})");
  658. let Some(self_) = me.upgrade() else {
  659. e!("DarkIrc destroyed before rescan completed");
  660. return false
  661. };
  662. // Decode channel name from method data
  663. let mut cur = std::io::Cursor::new(&method_call.data);
  664. let Ok(channel) = String::decode(&mut cur) else {
  665. e!("Rescan method called with invalid channel data");
  666. return false
  667. };
  668. self_.load_channels_from_db().await;
  669. self_.load_contacts_from_db().await;
  670. let task = self_.ex.clone().spawn(self_.clone().rescan_channel_history(channel));
  671. self_.tasks.lock().push(task);
  672. true
  673. }
  674. async fn apply_settings(self_: Arc<Self>, _: BatchGuardPtr) {
  675. self_.settings.save_settings();
  676. let p2p_settings = self_.p2p.settings();
  677. let mut write_guard = p2p_settings.write().await;
  678. self_.settings.update_p2p_settings(&mut write_guard);
  679. }
  680. async fn process_reconnect(me: &Weak<Self>, sub: &MethodCallSub) -> bool {
  681. let Ok(method_call) = sub.receive().await else {
  682. d!("Reconnect method closed");
  683. return false
  684. };
  685. t!("method called: reconnect({method_call:?})");
  686. let Some(self_) = me.upgrade() else {
  687. e!("DarkIrc destroyed before reconnect completed");
  688. return false
  689. };
  690. self_.handle_reconnect().await;
  691. true
  692. }
  693. /// User requested to reconnect
  694. async fn handle_reconnect(&self) {
  695. i!("Manual P2P reconnection triggered");
  696. self.p2p.clone().stop().await;
  697. while let Err(err) = self.p2p.clone().start().await {
  698. e!("Failed to start P2P network: {err}!");
  699. e!("Retrying in {P2P_RETRY_TIME} secs");
  700. sleep(P2P_RETRY_TIME).await;
  701. }
  702. i!("P2P reconnection completed");
  703. }
  704. async fn start(self: Arc<Self>, sg_root: SceneNodePtr, ex: ExecutorPtr) {
  705. i!("Registering EventGraph P2P protocol");
  706. let event_graph_ = Arc::clone(&self.event_graph);
  707. let registry = self.p2p.protocol_registry();
  708. registry
  709. .register(SESSION_DEFAULT, move |channel, _| {
  710. let event_graph_ = event_graph_.clone();
  711. async move { ProtocolEventGraph::init(event_graph_, channel).await.unwrap() }
  712. })
  713. .await;
  714. let me = Arc::downgrade(&self);
  715. let node = &self.node.upgrade().unwrap();
  716. let method_sub = node.subscribe_method_call("send").unwrap();
  717. let me2 = me.clone();
  718. let send_method_task =
  719. ex.spawn(async move { while Self::process_send(&me2, &method_sub).await {} });
  720. let reconnect_method_sub = node.subscribe_method_call("reconnect").unwrap();
  721. let me2 = me.clone();
  722. let reconnect_method_task =
  723. ex.spawn(
  724. async move { while Self::process_reconnect(&me2, &reconnect_method_sub).await {} },
  725. );
  726. let rescan_method_sub = node.subscribe_method_call("rescan").unwrap();
  727. let me2 = me.clone();
  728. let rescan_method_task =
  729. ex.spawn(async move { while Self::process_rescan(&me2, &rescan_method_sub).await {} });
  730. let mut on_modify = OnModify::new(ex.clone(), self.node.clone(), me.clone());
  731. async fn save_nick(self_: Arc<DarkIrc>, _batch: BatchGuardPtr) {
  732. let _ = std::fs::write(nick_filename(), self_.nick.get());
  733. }
  734. on_modify.when_change(self.nick.prop(), save_nick);
  735. // `apply_settings` is triggered if any setting changes
  736. for setting_node in self.settings.setting_root.get_children().iter() {
  737. on_modify.when_change(
  738. setting_node.get_property("value").clone().unwrap(),
  739. Self::apply_settings,
  740. );
  741. }
  742. let ev_sub = self.event_graph.event_subscribe().await;
  743. let ev_task = ex.spawn(self.clone().relay_events(ev_sub));
  744. // Sync the DAG / check sync status
  745. let channel_sub = self.p2p.hosts().subscribe_channel().await;
  746. let dag_task = ex.spawn(self.clone().dag_sync(channel_sub));
  747. // Subscribe to window start/stop signals for dynamic outbound connections
  748. let window_node = sg_root.lookup_node("/window").unwrap();
  749. let (start_slot, start_recv) = Slot::new("app_start");
  750. window_node.register("start", start_slot).unwrap();
  751. let p2p = self.p2p.clone();
  752. let start_task = ex.spawn(async move {
  753. while let Ok(_) = start_recv.recv().await {
  754. i!("App started: set outbound connections to {P2P_OUTBOUND_ACTIVE}");
  755. p2p.settings().write().await.outbound_connections = P2P_OUTBOUND_ACTIVE;
  756. p2p.clone().reload().await;
  757. }
  758. });
  759. let (stop_slot, stop_recv) = Slot::new("app_stop");
  760. window_node.register("stop", stop_slot).unwrap();
  761. let p2p = self.p2p.clone();
  762. let stop_task = ex.spawn(async move {
  763. while let Ok(_) = stop_recv.recv().await {
  764. i!("App stopped: set outbound connections to {P2P_OUTBOUND_SLEEP}");
  765. p2p.settings().write().await.outbound_connections = P2P_OUTBOUND_SLEEP;
  766. p2p.clone().reload().await;
  767. }
  768. });
  769. let mut tasks = vec![
  770. send_method_task,
  771. reconnect_method_task,
  772. rescan_method_task,
  773. ev_task,
  774. dag_task,
  775. start_task,
  776. stop_task,
  777. ];
  778. if DNET_ENABLED {
  779. let dnet_sub = self.p2p.dnet_subscribe().await;
  780. let node = self.node.upgrade().unwrap();
  781. let prop = node.get_property("outbound_peers").unwrap();
  782. let dnet_task = ex.spawn(Self::relay_outbound_slots(dnet_sub, prop));
  783. tasks.push(dnet_task);
  784. }
  785. tasks.append(&mut on_modify.tasks);
  786. *self.tasks.lock() = tasks;
  787. }
  788. /// Encrypt a channel `Privmsg` in place if the channel has a shared key.
  789. /// Open channels with no key are left plaintext.
  790. pub async fn try_encrypt_channel(&self, privmsg: &mut Privmsg) {
  791. let guard = self.channels.read().await;
  792. let Some((name, channel)) = guard.get_key_value(&privmsg.channel) else {
  793. return;
  794. };
  795. let Some(saltbox) = &channel.saltbox else {
  796. return;
  797. };
  798. privmsg.channel = saltbox::encrypt(saltbox, &[0x00; MAX_NICK_LEN]);
  799. privmsg.nick = saltbox::encrypt(saltbox, &pad(&privmsg.nick));
  800. privmsg.msg = saltbox::encrypt(saltbox, privmsg.msg.as_bytes());
  801. d!("Successfully encrypted message for {name}");
  802. }
  803. /// Encrypt a DM `Privmsg` in place for the contact named by `privmsg.channel`
  804. /// (the bare key, with no leading "@"). Fails if the contact is unknown so
  805. /// the caller can refuse to broadcast a message no one could decrypt.
  806. pub async fn try_encrypt_dm(&self, privmsg: &mut Privmsg) -> Result<()> {
  807. let guard = self.contacts.read().await;
  808. let Some((name, contact)) = guard.get_key_value(&privmsg.channel) else {
  809. return Err(Error::ContactNotFound);
  810. };
  811. privmsg.channel = saltbox::encrypt(&contact.saltbox, &[0x00; MAX_NICK_LEN]);
  812. privmsg.nick = saltbox::encrypt(&contact.self_saltbox, &[0x00; MAX_NICK_LEN]);
  813. privmsg.msg = saltbox::encrypt(&contact.saltbox, privmsg.msg.as_bytes());
  814. d!("Successfully encrypted DM for {name}");
  815. Ok(())
  816. }
  817. /// Try decrypting a `Privmsg` as a channel message in place. Returns true on
  818. /// success. Plaintext messages for a known keyless channel are accepted
  819. /// as-is; everything else returns false.
  820. pub async fn try_decrypt_channel(&self, privmsg: &mut Privmsg) -> bool {
  821. let Ok(channel_ciphertext) = bs58::decode(&privmsg.channel).into_vec() else {
  822. // Not encrypted: accept only if it names a channel we hold.
  823. return self.channels.read().await.contains_key(&privmsg.channel);
  824. };
  825. let Ok(nick_ciphertext) = bs58::decode(&privmsg.nick).into_vec() else { return false };
  826. let Ok(msg_ciphertext) = bs58::decode(&privmsg.msg).into_vec() else { return false };
  827. for (name, channel) in self.channels.read().await.iter() {
  828. let Some(saltbox) = &channel.saltbox else { continue };
  829. if saltbox::try_decrypt(saltbox, &channel_ciphertext).is_none() {
  830. continue
  831. };
  832. let Some(mut nick_dec) = saltbox::try_decrypt(saltbox, &nick_ciphertext) else {
  833. w!("Could not decrypt nick ciphertext for channel: {name}");
  834. continue
  835. };
  836. let Some(msg_dec) = saltbox::try_decrypt(saltbox, &msg_ciphertext) else {
  837. w!("Could not decrypt message ciphertext for channel: {name}");
  838. continue
  839. };
  840. unpad(&mut nick_dec);
  841. privmsg.channel = name.to_string();
  842. privmsg.nick = String::from_utf8_lossy(&nick_dec).into();
  843. privmsg.msg = String::from_utf8_lossy(&msg_dec).into();
  844. d!("Successfully decrypted message for {name}");
  845. return true
  846. }
  847. false
  848. }
  849. /// Try decrypting a `Privmsg` as a DM in place. Returns true on success.
  850. pub async fn try_decrypt_contact(&self, privmsg: &mut Privmsg, self_nickname: &str) -> bool {
  851. let Ok(channel_ciphertext) = bs58::decode(&privmsg.channel).into_vec() else {
  852. return false
  853. };
  854. let Ok(nick_ciphertext) = bs58::decode(&privmsg.nick).into_vec() else { return false };
  855. let Ok(msg_ciphertext) = bs58::decode(&privmsg.msg).into_vec() else { return false };
  856. for (name, contact) in self.contacts.read().await.iter() {
  857. if saltbox::try_decrypt(&contact.saltbox, &channel_ciphertext).is_none() {
  858. continue
  859. };
  860. let nick = if saltbox::try_decrypt(&contact.self_saltbox, &nick_ciphertext).is_some() {
  861. String::from(self_nickname)
  862. } else {
  863. name.to_string()
  864. };
  865. let Some(msg_dec) = saltbox::try_decrypt(&contact.saltbox, &msg_ciphertext) else {
  866. w!("Could not decrypt message ciphertext for contact: {name}");
  867. continue
  868. };
  869. privmsg.channel = format!("@{}", name);
  870. privmsg.nick = nick;
  871. privmsg.msg = String::from_utf8_lossy(&msg_dec).into();
  872. return true
  873. }
  874. false
  875. }
  876. /// Try decrypting a given potentially encrypted `Privmsg` object as a channel
  877. /// and then as a DM. Returns true if either succeeded.
  878. pub async fn try_decrypt(&self, privmsg: &mut Privmsg, self_nickname: &str) -> bool {
  879. self.try_decrypt_channel(privmsg).await ||
  880. self.try_decrypt_contact(privmsg, self_nickname).await
  881. }
  882. }
  883. pub fn msg_id(privmsg: &Privmsg, timest: u64) -> MessageId {
  884. let mut hasher = blake3::Hasher::new();
  885. 0u8.encode(&mut hasher).unwrap();
  886. 0u8.encode(&mut hasher).unwrap();
  887. timest.encode(&mut hasher).unwrap();
  888. privmsg.channel.encode(&mut hasher).unwrap();
  889. privmsg.nick.encode(&mut hasher).unwrap();
  890. privmsg.msg.encode(&mut hasher).unwrap();
  891. MessageId(hasher.finalize().into())
  892. }