settings.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. sync::Arc,
  21. time::UNIX_EPOCH,
  22. };
  23. use crypto_box::PublicKey;
  24. use darkfi::{Error::ParseFailed, Result};
  25. use darkfi_sdk::{crypto::pasta_prelude::PrimeField, pasta::pallas};
  26. use tracing::info;
  27. use crate::{
  28. crypto::rln::{closest_epoch, RlnIdentity},
  29. irc::{IrcChannel, IrcContact},
  30. };
  31. /// Parse configured autojoin channels from a TOML map.
  32. ///
  33. /// ```toml
  34. /// autojoin = ["#dev", "#memes"]
  35. /// ```
  36. pub fn parse_autojoin_channels(data: &toml::Value) -> Result<Vec<String>> {
  37. let mut ret = vec![];
  38. let Some(autojoin) = data.get("autojoin") else { return Ok(ret) };
  39. let Some(autojoin) = autojoin.as_array() else {
  40. return Err(ParseFailed("autojoin not an array"))
  41. };
  42. for item in autojoin {
  43. let Some(channel) = item.as_str() else {
  44. return Err(ParseFailed("autojoin channel not a string"))
  45. };
  46. if !channel.starts_with('#') {
  47. return Err(ParseFailed("autojoin channel not a valid channel"))
  48. }
  49. if ret.contains(&channel.to_string()) {
  50. return Err(ParseFailed("Duplicate autojoin channel found"))
  51. }
  52. ret.push(channel.to_string());
  53. }
  54. Ok(ret)
  55. }
  56. pub fn list_configured_contacts(
  57. data: &toml::Value,
  58. ) -> Result<HashMap<String, (PublicKey, crypto_box::SecretKey)>> {
  59. let mut ret = HashMap::new();
  60. let Some(table) = data.as_table() else { return Err(ParseFailed("TOML not a map")) };
  61. let Some(contacts) = table.get("contact") else { return Ok(ret) };
  62. let Some(contacts) = contacts.as_table() else {
  63. return Err(ParseFailed("`contact` not a map"))
  64. };
  65. for (name, items) in contacts {
  66. let Some(public_str) = items.get("dm_chacha_public") else {
  67. return Err(ParseFailed("Invalid contact configuration dm_chacha_public missing"))
  68. };
  69. let Some(public_str) = public_str.as_str() else {
  70. return Err(ParseFailed("dm_chacha_public not a string"))
  71. };
  72. let Ok(public_bytes) = bs58::decode(public_str).into_vec() else {
  73. return Err(ParseFailed("Invalid base58 for contact pubkey"))
  74. };
  75. if public_bytes.len() != 32 {
  76. return Err(ParseFailed("Invalid contact pubkey (not 32 bytes)"))
  77. }
  78. let public_bytes: [u8; 32] = public_bytes.try_into().unwrap();
  79. let public = crypto_box::PublicKey::from(public_bytes);
  80. if ret.contains_key(name) {
  81. return Err(ParseFailed("Duplicate contact found"))
  82. }
  83. // Parse the secret key for that specific contact
  84. let Some(my_secret) = items.get("my_dm_chacha_secret") else {
  85. return Err(ParseFailed("Invalid contact configuration my_dm_chacha_secret missing. \
  86. You can generate a keypair with: 'darkirc --gen-chacha-keypair' and then add that keypair to your config toml file."))
  87. };
  88. let Some(my_secret_str) = my_secret.as_str() else {
  89. return Err(ParseFailed("my_dm_chacha_secret not a string"))
  90. };
  91. let Ok(my_secret_bytes) = bs58::decode(my_secret_str).into_vec() else {
  92. return Err(ParseFailed("my_dm_chacha_secret not valid base58"))
  93. };
  94. if my_secret_bytes.len() != 32 {
  95. return Err(ParseFailed("my_dm_chacha_secret not 32 bytes long"))
  96. }
  97. let my_secret_bytes: [u8; 32] = my_secret_bytes.try_into().unwrap();
  98. let my_secret = crypto_box::SecretKey::from(my_secret_bytes);
  99. ret.insert(name.to_string(), (public, my_secret));
  100. }
  101. Ok(ret)
  102. }
  103. /// Parse configured contacts from a TOML map.
  104. ///
  105. /// ```toml
  106. /// [contact."anon"]
  107. /// dm_chacha_public = "7CkVuFgwTUpJn5Sv67Q3fyEDpa28yrSeL5Hg2GqQ4jfM"
  108. /// my_dm_chacha_secret = "A3mLrq4aW9UkFVY4zCfR2aLdEEWVUdH4u8v4o2dgi4kC"
  109. /// ```
  110. #[allow(clippy::type_complexity)]
  111. pub fn parse_configured_contacts(data: &toml::Value) -> Result<HashMap<String, IrcContact>> {
  112. let mut ret = HashMap::new();
  113. let contacts = list_configured_contacts(data)?;
  114. if contacts.is_empty() {
  115. return Ok(ret);
  116. }
  117. for (name, (public, my_secret)) in contacts {
  118. let saltbox: Arc<crypto_box::ChaChaBox> =
  119. Arc::new(crypto_box::ChaChaBox::new(&public, &my_secret));
  120. let self_saltbox: Arc<crypto_box::ChaChaBox> =
  121. Arc::new(crypto_box::ChaChaBox::new(&my_secret.public_key(), &my_secret));
  122. if ret.contains_key(&name) {
  123. return Err(ParseFailed("Duplicate contact found"))
  124. }
  125. info!("Instantiated ChaChaBox for contact \"{name}\"");
  126. ret.insert(name.to_string(), IrcContact { saltbox, self_saltbox });
  127. }
  128. Ok(ret)
  129. }
  130. /// Parse configured RLN identity from a TOML map.
  131. ///
  132. /// ```toml
  133. /// [rln]
  134. /// nullifier = "6EGKCm3FdSK3fySbjY19pxG49aB34poXhaepsW5NMxFB"
  135. /// trapdoor = "dCbf5fD2w3K9eYHA2ppgio3ui12tSMZXnEGm8dHS5x6"
  136. /// user_message_limit = 100
  137. /// ```
  138. pub fn parse_rln_identity(data: &toml::Value) -> Result<Option<RlnIdentity>> {
  139. let Some(table) = data.as_table() else { return Err(ParseFailed("TOML not a map")) };
  140. let Some(rlninfo) = table.get("rln") else { return Ok(None) };
  141. let Some(nullifier) = rlninfo.get("nullifier") else {
  142. return Err(ParseFailed("RLN identity nullifier missing"))
  143. };
  144. let Some(trapdoor) = rlninfo.get("trapdoor") else {
  145. return Err(ParseFailed("RLN identity trapdoor missing"))
  146. };
  147. let Some(msglimit) = rlninfo.get("user_message_limit") else {
  148. return Err(ParseFailed("RLN user message limit missing"))
  149. };
  150. // Decode
  151. let identity_nullifier = if let Some(nullifier) = nullifier.as_str() {
  152. let Ok(nullifier_bytes) = bs58::decode(nullifier).into_vec() else {
  153. return Err(ParseFailed("RLN nullifier not valid base58"))
  154. };
  155. if nullifier_bytes.len() != 32 {
  156. return Err(ParseFailed("RLN nullifier not 32 bytes long"))
  157. }
  158. let Some(identity_nullifier) =
  159. pallas::Base::from_repr(nullifier_bytes.try_into().unwrap()).into()
  160. else {
  161. return Err(ParseFailed("RLN nullifier not a pallas base field element"))
  162. };
  163. identity_nullifier
  164. } else {
  165. return Err(ParseFailed("RLN nullifier not a string"))
  166. };
  167. let identity_trapdoor = if let Some(trapdoor) = trapdoor.as_str() {
  168. let Ok(trapdoor_bytes) = bs58::decode(trapdoor).into_vec() else {
  169. return Err(ParseFailed("RLN trapdoor not valid base58"))
  170. };
  171. if trapdoor_bytes.len() != 32 {
  172. return Err(ParseFailed("RLN trapdoor not 32 bytes long"))
  173. }
  174. let Some(identity_trapdoor) =
  175. pallas::Base::from_repr(trapdoor_bytes.try_into().unwrap()).into()
  176. else {
  177. return Err(ParseFailed("RLN trapdoor not a pallas base field element"))
  178. };
  179. identity_trapdoor
  180. } else {
  181. return Err(ParseFailed("RLN trapdoor not a string"))
  182. };
  183. let user_message_limit = if let Some(msglimit) = msglimit.as_float() {
  184. msglimit as u64
  185. } else {
  186. return Err(ParseFailed("RLN user message limit not a number"))
  187. };
  188. Ok(Some(RlnIdentity {
  189. nullifier: identity_nullifier,
  190. trapdoor: identity_trapdoor,
  191. user_message_limit,
  192. // TODO: FIXME: We should probably keep track of these rather than
  193. // resetting here
  194. message_id: 1,
  195. last_epoch: closest_epoch(UNIX_EPOCH.elapsed().unwrap().as_secs()),
  196. }))
  197. }
  198. /// Parse a TOML string for any configured channels and return
  199. /// a map containing said configurations.
  200. ///
  201. /// ```toml
  202. /// [channel."#memes"]
  203. /// secret = "7CkVuFgwTUpJn5Sv67Q3fyEDpa28yrSeL5Hg2GqQ4jfM"
  204. /// topic = "Dank Memes"
  205. /// ```
  206. pub fn parse_configured_channels(data: &toml::Value) -> Result<HashMap<String, IrcChannel>> {
  207. let mut ret = HashMap::new();
  208. let Some(table) = data.as_table() else { return Err(ParseFailed("TOML not a map")) };
  209. let Some(chans) = table.get("channel") else { return Ok(ret) };
  210. let Some(chans) = chans.as_table() else { return Err(ParseFailed("`channel` not a map")) };
  211. for (name, items) in chans {
  212. let mut chan = IrcChannel { topic: String::new(), nicks: HashSet::new(), saltbox: None };
  213. if let Some(topic) = items.get("topic") {
  214. if let Some(topic) = topic.as_str() {
  215. info!("Found configured topic for {name}: {topic}");
  216. chan.topic = topic.to_string();
  217. } else {
  218. return Err(ParseFailed("Channel topic not a string"))
  219. }
  220. }
  221. if let Some(secret) = items.get("secret") {
  222. if let Some(secret) = secret.as_str() {
  223. let Ok(secret_bytes) = bs58::decode(secret).into_vec() else {
  224. return Err(ParseFailed("Channel secret not valid base58"))
  225. };
  226. if secret_bytes.len() != 32 {
  227. return Err(ParseFailed("Channel secret not 32 bytes long"))
  228. }
  229. let secret_bytes: [u8; 32] = secret_bytes.try_into().unwrap();
  230. let secret = crypto_box::SecretKey::from(secret_bytes);
  231. let public = secret.public_key();
  232. chan.saltbox = Some(Arc::new(crypto_box::ChaChaBox::new(&public, &secret)));
  233. info!("Configured NaCl box for channel {name}");
  234. } else {
  235. return Err(ParseFailed("Channel secret not a string"))
  236. }
  237. }
  238. info!("Configured channel {name}");
  239. ret.insert(name.to_string(), chan);
  240. }
  241. Ok(ret)
  242. }