interactive.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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 std::{io::ErrorKind, str::FromStr};
  19. use futures::{select, FutureExt};
  20. use libc::{fcntl, F_GETFL, F_SETFL, O_NONBLOCK};
  21. use linenoise_rs::{
  22. linenoise_history_add, linenoise_history_load, linenoise_history_save,
  23. linenoise_set_completion_callback, linenoise_set_hints_callback, LinenoiseState,
  24. };
  25. use smol::channel::{unbounded, Receiver, Sender};
  26. use url::Url;
  27. use darkfi::{
  28. cli_desc,
  29. system::{msleep, ExecutorPtr, StoppableTask, StoppableTaskPtr},
  30. util::path::expand_path,
  31. Error,
  32. };
  33. use crate::{
  34. cli_util::{generate_completions, kaching},
  35. rpc::subscribe_blocks,
  36. DrkPtr,
  37. };
  38. // TODO:
  39. // 1. add rest commands handling, along with their completions, hints and help message.
  40. // 2. add input definitions, so you input from files not just stdin.
  41. // 3. add output definitions, so you can output to files not just stdout.
  42. // 4. create a transactions cache in the wallet db, so you can use it to handle them.
  43. /// Auxiliary function to print the help message.
  44. fn help() {
  45. println!("{}", cli_desc!());
  46. println!("Commands:");
  47. println!("\thelp: Prints the help message");
  48. println!("\tkaching: Fun");
  49. println!("\tping: Send a ping request to the darkfid RPC endpoint");
  50. println!("\tcompletions: Generate a SHELL completion script and print to stdout");
  51. println!(
  52. "\tsubscribe: Perform a scan and then subscribe to darkfid to listen for incoming blocks"
  53. );
  54. println!("\tunsubscribe: Stops the background subscription, if its active");
  55. println!("\tsnooze: Disables the background subscription messages printing");
  56. println!("\tunsnooze: Enables the background subscription messages printing");
  57. println!("\tscan: Scan the blockchain and parse relevant transactions");
  58. }
  59. /// Auxiliary function to define the interactive shell completions.
  60. fn completion(buf: &str, lc: &mut Vec<String>) {
  61. // First we define the specific commands prefixes
  62. if buf.starts_with("h") {
  63. lc.push("help".to_string());
  64. return
  65. }
  66. if buf.starts_with("k") {
  67. lc.push("kaching".to_string());
  68. return
  69. }
  70. if buf.starts_with("p") {
  71. lc.push("ping".to_string());
  72. return
  73. }
  74. if buf.starts_with("c") {
  75. lc.push("completions".to_string());
  76. return
  77. }
  78. if buf.starts_with("su") {
  79. lc.push("subscribe".to_string());
  80. return
  81. }
  82. if buf.starts_with("unsu") {
  83. lc.push("unsubscribe".to_string());
  84. return
  85. }
  86. if buf.starts_with("sn") {
  87. lc.push("snooze".to_string());
  88. return
  89. }
  90. if buf.starts_with("unsn") {
  91. lc.push("unsnooze".to_string());
  92. return
  93. }
  94. if buf.starts_with("sc") {
  95. lc.push("scan".to_string());
  96. return
  97. }
  98. // Now the catch alls
  99. if buf.starts_with("s") {
  100. lc.push("subscribe".to_string());
  101. lc.push("snooze".to_string());
  102. lc.push("scan".to_string());
  103. return
  104. }
  105. if buf.starts_with("u") {
  106. lc.push("unsubscribe".to_string());
  107. lc.push("unsnooze".to_string());
  108. }
  109. }
  110. /// Auxiliary function to define the interactive shell hints.
  111. fn hints(buf: &str) -> Option<(String, i32, bool)> {
  112. match buf {
  113. "completions " => Some(("{shell}".to_string(), 35, false)), // 35 = magenta
  114. "scan " => Some(("--reset {height}".to_string(), 35, false)), // 35 = magenta
  115. _ => None,
  116. }
  117. }
  118. /// Auxiliary function to start provided Drk as an interactive shell.
  119. /// Only sane/linenoise terminals are suported.
  120. pub async fn interactive(drk: &DrkPtr, endpoint: &Url, history_path: &str, ex: &ExecutorPtr) {
  121. // Expand the history file path
  122. let history_path = match expand_path(history_path) {
  123. Ok(p) => p,
  124. Err(e) => {
  125. eprintln!("Error while expanding history file path: {e}");
  126. return
  127. }
  128. };
  129. let history_path = history_path.into_os_string();
  130. let history_file = history_path.to_str().unwrap();
  131. // Set the completion callback. This will be called every time the
  132. // user uses the <tab> key.
  133. linenoise_set_completion_callback(completion);
  134. // Set the shell hints
  135. linenoise_set_hints_callback(hints);
  136. // Load history from file.The history file is just a plain text file
  137. // where entries are separated by newlines.
  138. let _ = linenoise_history_load(history_file);
  139. // Create a detached task to use for block subscription
  140. let mut subscription_active = false;
  141. let mut snooze_active = false;
  142. let subscription_task = StoppableTask::new();
  143. // Create an unbounded smol channel, so we can have a printing
  144. // queue the background task can submit messages to the shell.
  145. let (shell_sender, shell_receiver) = unbounded();
  146. // Start the interactive shell
  147. loop {
  148. // Wait for next line to process
  149. let line = listen_for_line(&snooze_active, &shell_receiver).await;
  150. // Grab input or end if Ctrl-D or Ctrl-C was pressed
  151. let Some(line) = line else { break };
  152. // Check if line is empty
  153. if line.is_empty() {
  154. continue
  155. }
  156. // Add line to history
  157. linenoise_history_add(&line);
  158. // Parse command parts
  159. let parts: Vec<&str> = line.split_whitespace().collect();
  160. if parts.is_empty() {
  161. continue
  162. }
  163. // Handle command
  164. match parts[0] {
  165. "help" => help(),
  166. "kaching" => kaching().await,
  167. "ping" => handle_ping(drk).await,
  168. "completions" => handle_completions(&parts),
  169. "subscribe" => {
  170. handle_subscribe(
  171. drk,
  172. endpoint,
  173. &mut subscription_active,
  174. &subscription_task,
  175. &shell_sender,
  176. ex,
  177. )
  178. .await
  179. }
  180. "unsubscribe" => handle_unsubscribe(&mut subscription_active, &subscription_task).await,
  181. "snooze" => snooze_active = true,
  182. "unsnooze" => snooze_active = false,
  183. "scan" => handle_scan(drk, &subscription_active, &parts).await,
  184. _ => println!("Unreconized command: {}", parts[0]),
  185. }
  186. }
  187. // Stop the subscription task if its active
  188. if subscription_active {
  189. subscription_task.stop().await;
  190. }
  191. // Write history file
  192. let _ = linenoise_history_save(history_file);
  193. }
  194. /// Auxiliary function to listen for linenoise input line and handle
  195. /// background task messages.
  196. async fn listen_for_line(
  197. snooze_active: &bool,
  198. shell_receiver: &Receiver<Vec<String>>,
  199. ) -> Option<String> {
  200. // Generate the linoise state structure
  201. let mut state = match LinenoiseState::edit_start(-1, -1, "drk> ") {
  202. Ok(s) => s,
  203. Err(e) => {
  204. eprintln!("Error while generating linenoise state: {e}");
  205. return None
  206. }
  207. };
  208. // Set stdin to non-blocking mode
  209. let fd = state.get_fd();
  210. unsafe {
  211. let flags = fcntl(fd, F_GETFL, 0);
  212. fcntl(fd, F_SETFL, flags | O_NONBLOCK);
  213. }
  214. // Read until we get a line to process
  215. let mut line = None;
  216. loop {
  217. // Future that polls stdin for input
  218. let input_future = async {
  219. loop {
  220. match state.edit_feed() {
  221. Ok(Some(l)) => {
  222. line = Some(l);
  223. break
  224. }
  225. Ok(None) => break,
  226. Err(e) if e.kind() == ErrorKind::Interrupted => break,
  227. Err(e) if e.kind() == ErrorKind::WouldBlock => {
  228. // No data available, yield and retry
  229. msleep(10).await;
  230. continue
  231. }
  232. Err(e) => {
  233. eprintln!("Error while reading linenoise feed: {e}");
  234. break
  235. }
  236. }
  237. }
  238. };
  239. // Future that polls the channel
  240. let channel_future = async {
  241. loop {
  242. if !shell_receiver.is_empty() {
  243. break
  244. }
  245. msleep(1000).await;
  246. }
  247. };
  248. // Manage the futures
  249. select! {
  250. // When input is ready we break out the loop
  251. _ = input_future.fuse() => break,
  252. // Manage filled channel
  253. _ = channel_future.fuse() => {
  254. while !shell_receiver.is_empty() {
  255. match shell_receiver.recv().await {
  256. Ok(msg) => {
  257. // We only print if snooze is inactive,
  258. // but have to consume the message regardless,
  259. // so the queue gets empty.
  260. if *snooze_active {
  261. continue
  262. }
  263. // Hide prompt, print output, show prompt again
  264. let _ = state.hide();
  265. for line in msg {
  266. println!("{}\r", line.replace("\n", "\n\r"));
  267. }
  268. let _ = state.show();
  269. }
  270. Err(e) => {
  271. eprintln!("Error while reading shell receiver channel: {e}");
  272. break
  273. }
  274. }
  275. }
  276. }
  277. }
  278. }
  279. // Restore blocking mode
  280. unsafe {
  281. let flags = fcntl(fd, F_GETFL, 0);
  282. fcntl(fd, F_SETFL, flags & !O_NONBLOCK);
  283. }
  284. let _ = state.edit_stop();
  285. line
  286. }
  287. /// Auxiliary function to define the ping command handling.
  288. async fn handle_ping(drk: &DrkPtr) {
  289. if let Err(e) = drk.read().await.ping().await {
  290. println!("Error while executing ping command: {e}")
  291. }
  292. }
  293. /// Auxiliary function to define the completions command handling.
  294. fn handle_completions(parts: &[&str]) {
  295. if parts.len() != 2 {
  296. println!("Malformed `completions` command");
  297. println!("Usage: completions {{shell}}");
  298. return
  299. }
  300. if let Err(e) = generate_completions(parts[1]) {
  301. println!("Error while executing completions command: {e}")
  302. }
  303. }
  304. /// Auxiliary function to define the subscribe command handling.
  305. async fn handle_subscribe(
  306. drk: &DrkPtr,
  307. endpoint: &Url,
  308. subscription_active: &mut bool,
  309. subscription_task: &StoppableTaskPtr,
  310. shell_sender: &Sender<Vec<String>>,
  311. ex: &ExecutorPtr,
  312. ) {
  313. if *subscription_active {
  314. println!("Subscription is already active!");
  315. return
  316. }
  317. if let Err(e) = drk.read().await.scan_blocks().await {
  318. println!("Failed during scanning: {e:?}");
  319. return
  320. }
  321. println!("Finished scanning blockchain");
  322. // Start the subcristion task
  323. let drk_ = drk.clone();
  324. let endpoint_ = endpoint.clone();
  325. let shell_sender_ = shell_sender.clone();
  326. let ex_ = ex.clone();
  327. subscription_task.clone().start(
  328. async move { subscribe_blocks(&drk_, shell_sender_, endpoint_, &ex_).await },
  329. |res| async {
  330. match res {
  331. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  332. Err(e) => println!("Failed starting subscription task: {e}"),
  333. }
  334. },
  335. Error::DetachedTaskStopped,
  336. ex.clone(),
  337. );
  338. *subscription_active = true;
  339. }
  340. /// Auxiliary function to define the unsubscribe command handling.
  341. async fn handle_unsubscribe(subscription_active: &mut bool, subscription_task: &StoppableTaskPtr) {
  342. if !*subscription_active {
  343. println!("Subscription is already inactive!");
  344. return
  345. }
  346. subscription_task.stop().await;
  347. *subscription_active = false;
  348. }
  349. /// Auxiliary function to define the scan command handling.
  350. async fn handle_scan(drk: &DrkPtr, subscription_active: &bool, parts: &[&str]) {
  351. if *subscription_active {
  352. println!("Subscription is already active!");
  353. return
  354. }
  355. // Check correct command structure
  356. if parts.len() != 1 && parts.len() != 3 {
  357. println!("Malformed `scan` command");
  358. return
  359. }
  360. // Check if reset was requested
  361. let lock = drk.read().await;
  362. if parts.len() == 3 {
  363. if parts[1] != "--reset" {
  364. println!("Malformed `scan` command");
  365. println!("Usage: scan --reset {{height}}");
  366. return
  367. }
  368. let height = match u32::from_str(parts[2]) {
  369. Ok(h) => h,
  370. Err(e) => {
  371. println!("Invalid reset height: {e:?}");
  372. return
  373. }
  374. };
  375. if let Err(e) = lock.reset_to_height(height) {
  376. println!("Failed during wallet reset: {e:?}");
  377. return
  378. }
  379. }
  380. if let Err(e) = lock.scan_blocks().await {
  381. println!("Failed during scanning: {e:?}");
  382. return
  383. }
  384. println!("Finished scanning blockchain");
  385. }