main.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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_std::sync::{Arc, Mutex};
  19. use libc::mkfifo;
  20. use std::{
  21. collections::HashMap,
  22. env,
  23. ffi::CString,
  24. fs::{create_dir_all, remove_dir_all},
  25. io::{stdin, Write},
  26. path::Path,
  27. };
  28. use crypto_box::{
  29. aead::{Aead, AeadCore},
  30. rand_core::OsRng,
  31. SalsaBox, SecretKey,
  32. };
  33. use darkfi_serial::{deserialize, serialize, SerialDecodable, SerialEncodable};
  34. use futures::{select, FutureExt};
  35. use log::{debug, error, info, warn};
  36. use structopt_toml::StructOptToml;
  37. use darkfi::{
  38. async_daemonize,
  39. event_graph::{
  40. events_queue::EventsQueue,
  41. model::{Event, EventId, Model, ModelPtr},
  42. protocol_event::{ProtocolEvent, Seen, SeenPtr},
  43. view::{View, ViewPtr},
  44. EventMsg,
  45. },
  46. net::{self, P2pPtr},
  47. rpc::server::listen_and_serve,
  48. util::{path::expand_path, time::Timestamp},
  49. Error, Result,
  50. };
  51. mod error;
  52. mod jsonrpc;
  53. mod month_tasks;
  54. mod settings;
  55. mod task_info;
  56. mod util;
  57. use crate::{
  58. error::TaudResult,
  59. jsonrpc::JsonRpcInterface,
  60. settings::{Args, CONFIG_FILE, CONFIG_FILE_CONTENTS},
  61. task_info::{TaskEvent, TaskInfo},
  62. util::pipe_write,
  63. };
  64. fn get_workspaces(settings: &Args) -> Result<HashMap<String, SalsaBox>> {
  65. let mut workspaces = HashMap::new();
  66. for workspace in settings.workspaces.iter() {
  67. let workspace: Vec<&str> = workspace.split(':').collect();
  68. let (workspace, secret) = (workspace[0], workspace[1]);
  69. let bytes: [u8; 32] = bs58::decode(secret)
  70. .into_vec()?
  71. .try_into()
  72. .map_err(|_| Error::ParseFailed("Parse secret key failed"))?;
  73. let secret = crypto_box::SecretKey::from(bytes);
  74. let public = secret.public_key();
  75. let salsa_box = crypto_box::SalsaBox::new(&public, &secret);
  76. workspaces.insert(workspace.to_string(), salsa_box);
  77. }
  78. Ok(workspaces)
  79. }
  80. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  81. pub struct EncryptedTask {
  82. nonce: Vec<u8>,
  83. payload: Vec<u8>,
  84. }
  85. impl EventMsg for EncryptedTask {
  86. fn new() -> Self {
  87. Self {
  88. nonce: [
  89. 19, 40, 199, 87, 248, 23, 187, 11, 119, 237, 214, 65, 5, 206, 187, 33, 222, 107,
  90. 140, 84, 114, 61, 205, 40,
  91. ]
  92. .to_vec(),
  93. payload: [
  94. 30, 66, 74, 74, 65, 78, 80, 120, 85, 66, 106, 119, 119, 81, 66, 55, 112, 80, 88,
  95. 85, 82, 97, 79, 108, 115, 83, 113, 78, 71, 116, 113, 4, 114, 111, 111, 116, 1, 0,
  96. 0, 0, 5, 116, 105, 116, 108, 101, 0, 4, 100, 101, 115, 99, 6, 100, 97, 114, 107,
  97. 102, 105, 0, 0, 0, 0, 42, 47, 14, 100, 0, 0, 0, 0, 4, 111, 112, 101, 110, 0, 0,
  98. ]
  99. .to_vec(),
  100. }
  101. }
  102. }
  103. fn encrypt_task(
  104. task: &TaskInfo,
  105. salsa_box: &SalsaBox,
  106. rng: &mut OsRng,
  107. ) -> TaudResult<EncryptedTask> {
  108. debug!("start encrypting task");
  109. let nonce = SalsaBox::generate_nonce(rng);
  110. let payload = &serialize(task)[..];
  111. let payload = salsa_box.encrypt(&nonce, payload)?;
  112. let nonce = nonce.to_vec();
  113. Ok(EncryptedTask { nonce, payload })
  114. }
  115. fn decrypt_task(encrypt_task: &EncryptedTask, salsa_box: &SalsaBox) -> TaudResult<TaskInfo> {
  116. debug!("start decrypting task");
  117. let nonce = encrypt_task.nonce.as_slice();
  118. let decrypted_task = salsa_box.decrypt(nonce.into(), &encrypt_task.payload[..])?;
  119. let task = deserialize(&decrypted_task)?;
  120. Ok(task)
  121. }
  122. #[allow(clippy::too_many_arguments)]
  123. async fn start_sync_loop(
  124. broadcast_rcv: smol::channel::Receiver<TaskInfo>,
  125. view: ViewPtr<EncryptedTask>,
  126. model: ModelPtr<EncryptedTask>,
  127. seen: SeenPtr<EventId>,
  128. workspaces: HashMap<String, SalsaBox>,
  129. datastore_path: std::path::PathBuf,
  130. missed_events: Arc<Mutex<Vec<Event<EncryptedTask>>>>,
  131. piped: bool,
  132. p2p: P2pPtr,
  133. ) -> TaudResult<()> {
  134. loop {
  135. let mut v = view.lock().await;
  136. select! {
  137. task_event = broadcast_rcv.recv().fuse() => {
  138. let tk = task_event.map_err(Error::from)?;
  139. if workspaces.contains_key(&tk.workspace) {
  140. let salsa_box = workspaces.get(&tk.workspace).unwrap();
  141. let encrypted_task = encrypt_task(&tk, salsa_box, &mut OsRng)?;
  142. info!(target: "tau", "Send the task: ref: {}", tk.ref_id);
  143. let event = Event {
  144. previous_event_hash: model.lock().await.get_head_hash(),
  145. action: encrypted_task,
  146. timestamp: Timestamp::current_time(),
  147. };
  148. p2p.broadcast(event).await?;
  149. }
  150. }
  151. task_event = v.process().fuse() => {
  152. let event = task_event.map_err(Error::from)?;
  153. if !seen.push(&event.hash()).await {
  154. continue
  155. }
  156. missed_events.lock().await.push(event.clone());
  157. on_receive_task(&event.action, &datastore_path, &workspaces, piped)
  158. .await?;
  159. }
  160. }
  161. }
  162. }
  163. async fn on_receive_task(
  164. task: &EncryptedTask,
  165. datastore_path: &Path,
  166. workspaces: &HashMap<String, SalsaBox>,
  167. piped: bool,
  168. ) -> TaudResult<()> {
  169. for (workspace, salsa_box) in workspaces.iter() {
  170. let task = decrypt_task(task, salsa_box);
  171. if let Err(e) = task {
  172. info!("unable to decrypt the task: {}", e);
  173. continue
  174. }
  175. let mut task = task.unwrap();
  176. info!(target: "tau", "Save the task: ref: {}", task.ref_id);
  177. task.workspace = workspace.clone();
  178. if piped {
  179. // if we can't load the task then it's a new task.
  180. // otherwise it's a modification.
  181. match TaskInfo::load(&task.ref_id, datastore_path) {
  182. Ok(loaded_task) => {
  183. let loaded_events = loaded_task.events.0;
  184. let mut events = task.events.0.clone();
  185. events.retain(|ev| !loaded_events.contains(ev));
  186. let file = "/tmp/tau_pipe";
  187. let mut pipe_write = pipe_write(file)?;
  188. let mut task_clone = task.clone();
  189. task_clone.events.0 = events;
  190. let json = serde_json::to_string(&task_clone).unwrap();
  191. pipe_write.write_all(json.as_bytes())?;
  192. }
  193. Err(_) => {
  194. let file = "/tmp/tau_pipe";
  195. let mut pipe_write = pipe_write(file)?;
  196. let mut task_clone = task.clone();
  197. task_clone.events.0.push(TaskEvent::new(
  198. "add_task".to_string(),
  199. task_clone.owner.clone(),
  200. "".to_string(),
  201. ));
  202. let json = serde_json::to_string(&task_clone).unwrap();
  203. pipe_write.write_all(json.as_bytes())?;
  204. }
  205. }
  206. }
  207. task.save(datastore_path)?;
  208. }
  209. Ok(())
  210. }
  211. async_daemonize!(realmain);
  212. async fn realmain(settings: Args, executor: Arc<smol::Executor<'_>>) -> Result<()> {
  213. let datastore_path = expand_path(&settings.datastore)?;
  214. let nickname =
  215. if settings.nickname.is_some() { settings.nickname.clone() } else { env::var("USER").ok() };
  216. if settings.refresh {
  217. println!("Removing local data in: {:?} (yes/no)? ", datastore_path);
  218. let mut confirm = String::new();
  219. stdin().read_line(&mut confirm).expect("Failed to read line");
  220. let confirm = confirm.to_lowercase();
  221. let confirm = confirm.trim();
  222. if confirm == "yes" || confirm == "y" {
  223. remove_dir_all(datastore_path).unwrap_or(());
  224. println!("Local data removed successfully.");
  225. } else {
  226. error!("Unexpected Value: {}", confirm);
  227. }
  228. return Ok(())
  229. }
  230. if nickname.is_none() {
  231. error!("Provide a nickname in config file");
  232. return Ok(())
  233. }
  234. if settings.piped {
  235. let file = "/tmp/tau_pipe";
  236. let path = CString::new(file).unwrap();
  237. unsafe { mkfifo(path.as_ptr(), 0o644) };
  238. }
  239. // mkdir datastore_path if not exists
  240. create_dir_all(datastore_path.clone())?;
  241. create_dir_all(datastore_path.join("month"))?;
  242. create_dir_all(datastore_path.join("task"))?;
  243. if settings.generate {
  244. println!("Generating a new workspace");
  245. loop {
  246. println!("Name for the new workspace: ");
  247. let mut workspace = String::new();
  248. stdin().read_line(&mut workspace).expect("Failed to read line");
  249. let workspace = workspace.to_lowercase();
  250. let workspace = workspace.trim();
  251. if workspace.is_empty() && workspace.len() < 3 {
  252. error!("Wrong workspace try again");
  253. continue
  254. }
  255. let secret_key = SecretKey::generate(&mut OsRng);
  256. let encoded = bs58::encode(secret_key.as_bytes());
  257. println!("workspace: {}:{}", workspace, encoded.into_string());
  258. println!("Please add it to the config file.");
  259. break
  260. }
  261. return Ok(())
  262. }
  263. let workspaces = get_workspaces(&settings)?;
  264. if workspaces.is_empty() {
  265. error!("Please add at least one workspace to the config file.");
  266. println!("Run `$ taud --generate` to generate new workspace.");
  267. return Ok(())
  268. }
  269. ////////////////////
  270. // Initialize the base structures
  271. ////////////////////
  272. let events_queue = EventsQueue::<EncryptedTask>::new();
  273. let model = Arc::new(Mutex::new(Model::new(events_queue.clone())));
  274. let view = Arc::new(Mutex::new(View::new(events_queue)));
  275. let model_clone = model.clone();
  276. ////////////////////
  277. // Buffers
  278. ////////////////////
  279. let seen_event = Seen::new();
  280. let seen_inv = Seen::new();
  281. let (broadcast_snd, broadcast_rcv) = smol::channel::unbounded::<TaskInfo>();
  282. //
  283. // P2p setup
  284. //
  285. let mut net_settings = settings.net.clone();
  286. net_settings.app_version = Some(option_env!("CARGO_PKG_VERSION").unwrap_or("").to_string());
  287. let p2p = net::P2p::new(net_settings.into()).await;
  288. let registry = p2p.protocol_registry();
  289. registry
  290. .register(net::SESSION_ALL, move |channel, p2p| {
  291. let seen_event = seen_event.clone();
  292. let seen_inv = seen_inv.clone();
  293. let model = model.clone();
  294. async move { ProtocolEvent::init(channel, p2p, model, seen_event, seen_inv).await }
  295. })
  296. .await;
  297. p2p.clone().start(executor.clone()).await?;
  298. executor.spawn(p2p.clone().run(executor.clone())).detach();
  299. ////////////////////
  300. // Listner
  301. ////////////////////
  302. let seen_ids = Seen::new();
  303. let missed_events = Arc::new(Mutex::new(vec![]));
  304. executor
  305. .spawn(start_sync_loop(
  306. broadcast_rcv,
  307. view,
  308. model_clone,
  309. seen_ids,
  310. workspaces.clone(),
  311. datastore_path.clone(),
  312. missed_events,
  313. settings.piped,
  314. p2p.clone(),
  315. ))
  316. .detach();
  317. //
  318. // RPC interface
  319. //
  320. let rpc_interface = Arc::new(JsonRpcInterface::new(
  321. datastore_path.clone(),
  322. broadcast_snd,
  323. nickname.unwrap(),
  324. workspaces.clone(),
  325. p2p.clone(),
  326. ));
  327. let _ex = executor.clone();
  328. executor.spawn(listen_and_serve(settings.rpc_listen.clone(), rpc_interface, _ex)).detach();
  329. //
  330. // Waiting Exit signal
  331. //
  332. let (signal, shutdown) = smol::channel::bounded::<()>(1);
  333. ctrlc::set_handler(move || {
  334. warn!(target: "tau", "Catch exit signal");
  335. // cleaning up tasks running in the background
  336. if let Err(e) = async_std::task::block_on(signal.send(())) {
  337. error!("Error on sending exit signal: {}", e);
  338. }
  339. })
  340. .unwrap();
  341. shutdown.recv().await?;
  342. print!("\r");
  343. info!("Caught termination signal, cleaning up and exiting...");
  344. Ok(())
  345. }