rpc_wallet.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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. /*
  19. use log::{debug, error};
  20. use serde_json::{json, Value};
  21. use darkfi::{
  22. rpc::jsonrpc::{
  23. ErrorCode::{InternalError, InvalidParams, ParseError},
  24. JsonError, JsonResponse, JsonResult,
  25. },
  26. wallet::walletdb::QueryType,
  27. };
  28. use super::{error::RpcError, server_error, Darkfid};
  29. */
  30. use darkfi::rpc::jsonrpc::JsonResult;
  31. use tinyjson::JsonValue;
  32. use super::Darkfid;
  33. impl Darkfid {
  34. // RPCAPI:
  35. // Attempts to query for a single row in a given table.
  36. // The parameters given contain paired metadata so we know how to decode the SQL data.
  37. // An example of `params` is as such:
  38. // ```
  39. // params[0] -> "sql query"
  40. // params[1] -> column_type
  41. // params[2] -> "column_name"
  42. // ...
  43. // params[n-1] -> column_type
  44. // params[n] -> "column_name"
  45. // ```
  46. // This function will fetch the first row it finds, if any. The `column_type` field
  47. // is a type available in the `WalletDb` API as an enum called `QueryType`. If a row
  48. // is not found, the returned result will be a JSON-RPC error.
  49. // NOTE: This is obviously vulnerable to SQL injection. Open to interesting solutions.
  50. //
  51. // --> {"jsonrpc": "2.0", "method": "wallet.query_row_single", "params": [...], "id": 1}
  52. // <-- {"jsonrpc": "2.0", "result": ["va", "lu", "es", ...], "id": 1}
  53. pub async fn wallet_query_row_single(&self, _id: u16, _params: JsonValue) -> JsonResult {
  54. todo!();
  55. /* TODO: This will be abstracted away
  56. // We need at least 3 params for something we want to fetch, and we want them in pairs.
  57. // Also the first param should be a String
  58. if params.len() < 3 || params[1..].len() % 2 != 0 || !params[0].is_string() {
  59. return JsonError::new(InvalidParams, None, id).into()
  60. }
  61. // The remaining pairs should be typed properly too
  62. let mut types: Vec<QueryType> = vec![];
  63. let mut names: Vec<&str> = vec![];
  64. for pair in params[1..].chunks(2) {
  65. if !pair[0].is_u64() || !pair[1].is_string() {
  66. return JsonError::new(InvalidParams, None, id).into()
  67. }
  68. let typ = pair[0].as_u64().unwrap();
  69. if typ >= QueryType::Last as u64 {
  70. return JsonError::new(InvalidParams, None, id).into()
  71. }
  72. types.push((typ as u8).into());
  73. names.push(pair[1].as_str().unwrap());
  74. }
  75. // Get a wallet connection
  76. let mut conn = match self.wallet.conn.acquire().await {
  77. Ok(v) => v,
  78. Err(e) => {
  79. error!("[RPC] wallet.query_row_single: Failed to acquire wallet connection: {}", e);
  80. return JsonError::new(InternalError, None, id).into()
  81. }
  82. };
  83. // Execute the query and see if we find a row
  84. let row = match sqlx::query(params[0].as_str().unwrap()).fetch_one(&mut conn).await {
  85. Ok(v) => Some(v),
  86. Err(_) => None,
  87. };
  88. // Try to decode the row into what was requested
  89. let mut ret: Vec<Value> = vec![];
  90. for (typ, col) in types.iter().zip(names) {
  91. match typ {
  92. QueryType::Integer => {
  93. let Some(ref row) = row else {
  94. error!("[RPC] wallet.query_row_single: Got None for QueryType::Integer");
  95. return server_error(RpcError::NoRowsFoundInWallet, id, None)
  96. };
  97. let value: i32 = match row.try_get(col) {
  98. Ok(v) => v,
  99. Err(e) => {
  100. error!("[RPC] wallet.query_row_single: {}", e);
  101. return JsonError::new(ParseError, None, id).into()
  102. }
  103. };
  104. ret.push(json!(value));
  105. continue
  106. }
  107. QueryType::Blob => {
  108. let Some(ref row) = row else {
  109. error!("[RPC] wallet.query_row_single: Got None for QueryType::Blob");
  110. return server_error(RpcError::NoRowsFoundInWallet, id, None)
  111. };
  112. let value: Vec<u8> = match row.try_get(col) {
  113. Ok(v) => v,
  114. Err(e) => {
  115. error!("[RPC] wallet.query_row_single: {}", e);
  116. return JsonError::new(ParseError, None, id).into()
  117. }
  118. };
  119. ret.push(json!(value));
  120. continue
  121. }
  122. QueryType::OptionInteger => {
  123. let Some(ref row) = row else {
  124. ret.push(json!(None::<i32>));
  125. continue
  126. };
  127. let value: i32 = match row.try_get(col) {
  128. Ok(v) => v,
  129. Err(e) => {
  130. error!("[RPC] wallet.query_row_single: {}", e);
  131. return JsonError::new(ParseError, None, id).into()
  132. }
  133. };
  134. ret.push(json!(value));
  135. continue
  136. }
  137. QueryType::OptionBlob => {
  138. let Some(ref row) = row else {
  139. ret.push(json!(None::<Vec<u8>>));
  140. continue
  141. };
  142. let value: Vec<u8> = match row.try_get(col) {
  143. Ok(v) => v,
  144. Err(e) => {
  145. error!("[RPC] wallet.query_row_single: {}", e);
  146. return JsonError::new(ParseError, None, id).into()
  147. }
  148. };
  149. ret.push(json!(value));
  150. continue
  151. }
  152. QueryType::Text => {
  153. let Some(ref row) = row else {
  154. error!("[RPC] wallet.query_row_single: Got None for QueryType::Text");
  155. return server_error(RpcError::NoRowsFoundInWallet, id, None)
  156. };
  157. let value: String = match row.try_get(col) {
  158. Ok(v) => v,
  159. Err(e) => {
  160. error!("[RPC] wallet.query_row_single: {}", e);
  161. return JsonError::new(ParseError, None, id).into()
  162. }
  163. };
  164. ret.push(json!(value));
  165. continue
  166. }
  167. _ => unreachable!(),
  168. }
  169. }
  170. JsonResponse::new(json!(ret), id).into()
  171. */
  172. }
  173. // RPCAPI:
  174. // Attempts to query for all available rows in a given table.
  175. // The parameters given contain paired metadata so we know how to decode the SQL data.
  176. // They're the same as above in `wallet.query_row_single`.
  177. // If there are any values found, they will be returned in a paired array. If not, an
  178. // empty array will be returned.
  179. //
  180. // --> {"jsonrpc": "2.0", "method": "wallet.query_row_multi", "params": [...], "id": 1}
  181. // <-- {"jsonrpc": "2.0", "result": [["va", "lu"], ["es", "es"], ...], "id": 1}
  182. pub async fn wallet_query_row_multi(&self, _id: u16, _params: JsonValue) -> JsonResult {
  183. todo!();
  184. /* TODO: This will be abstracted away
  185. // We need at least 3 params for something we want to fetch, and we want them in pairs.
  186. // Also the first param (the query) should be a String.
  187. if params.len() < 3 || params[1..].len() % 2 != 0 || !params[0].is_string() {
  188. return JsonError::new(InvalidParams, None, id).into()
  189. }
  190. // The remaining pairs should be typed properly too
  191. let mut types: Vec<QueryType> = vec![];
  192. let mut names: Vec<&str> = vec![];
  193. for pair in params[1..].chunks(2) {
  194. if !pair[0].is_u64() || !pair[1].is_string() {
  195. return JsonError::new(InvalidParams, None, id).into()
  196. }
  197. let typ = pair[0].as_u64().unwrap();
  198. if typ >= QueryType::Last as u64 {
  199. return JsonError::new(InvalidParams, None, id).into()
  200. }
  201. types.push((typ as u8).into());
  202. names.push(pair[1].as_str().unwrap());
  203. }
  204. // Get a wallet connection
  205. let mut conn = match self.wallet.conn.acquire().await {
  206. Ok(v) => v,
  207. Err(e) => {
  208. error!("[RPC] wallet.query_row_multi: Failed to acquire wallet connection: {}", e);
  209. return JsonError::new(InternalError, None, id).into()
  210. }
  211. };
  212. // Execute the query and see if we find any rows
  213. let rows = match sqlx::query(params[0].as_str().unwrap()).fetch_all(&mut conn).await {
  214. Ok(v) => v,
  215. Err(e) => {
  216. error!("[RPC] wallet.query_row_multi: Failed to execute SQL query: {}", e);
  217. return JsonError::new(InternalError, None, id).into()
  218. }
  219. };
  220. debug!("[RPC] wallet.query_row_multi: Found {} rows", rows.len());
  221. // Try to decode whatever we've found
  222. let mut ret: Vec<Vec<Value>> = vec![];
  223. for row in rows {
  224. let mut row_ret: Vec<Value> = vec![];
  225. for (typ, col) in types.iter().zip(names.clone()) {
  226. match typ {
  227. QueryType::Integer => {
  228. let value: i32 = match row.try_get(col) {
  229. Ok(v) => v,
  230. Err(e) => {
  231. error!("[RPC] wallet.query_row_multi: {}", e);
  232. return JsonError::new(ParseError, None, id).into()
  233. }
  234. };
  235. row_ret.push(json!(value));
  236. }
  237. QueryType::Blob => {
  238. let value: Vec<u8> = match row.try_get(col) {
  239. Ok(v) => v,
  240. Err(e) => {
  241. error!("[RPC] wallet.query_row_multi: {}", e);
  242. return JsonError::new(ParseError, None, id).into()
  243. }
  244. };
  245. row_ret.push(json!(value));
  246. }
  247. QueryType::OptionInteger => {
  248. let value: Option<i32> = match row.try_get(col) {
  249. Ok(v) => Some(v),
  250. Err(_) => None,
  251. };
  252. row_ret.push(json!(value));
  253. }
  254. QueryType::OptionBlob => {
  255. let value: Option<Vec<u8>> = match row.try_get(col) {
  256. Ok(v) => Some(v),
  257. Err(_) => None,
  258. };
  259. row_ret.push(json!(value));
  260. }
  261. QueryType::Text => {
  262. let value: String = match row.try_get(col) {
  263. Ok(v) => v,
  264. Err(e) => {
  265. error!("[RPC] wallet.query_row_multi: {}", e);
  266. return JsonError::new(ParseError, None, id).into()
  267. }
  268. };
  269. row_ret.push(json!(value));
  270. }
  271. _ => unreachable!(),
  272. }
  273. }
  274. ret.push(row_ret);
  275. }
  276. JsonResponse::new(json!(ret), id).into()
  277. */
  278. }
  279. // RPCAPI:
  280. // Executes an arbitrary SQL query on the wallet, and returns `true` on success.
  281. // `params[1..]` can optionally be provided in pairs like in `wallet.query_row_single`.
  282. //
  283. // --> {"jsonrpc": "2.0", "method": "wallet.exec_sql", "params": ["CREATE TABLE ..."], "id": 1}
  284. // <-- {"jsonrpc": "2.0", "result": true, "id": 1}
  285. pub async fn wallet_exec_sql(&self, _id: u16, _params: JsonValue) -> JsonResult {
  286. todo!();
  287. /* TODO: This will be abstracted away
  288. if params.is_empty() || !params[0].is_string() {
  289. return JsonError::new(InvalidParams, None, id).into()
  290. }
  291. if params.len() > 1 && params[1..].len() % 2 != 0 {
  292. return JsonError::new(InvalidParams, None, id).into()
  293. }
  294. let query = params[0].as_str().unwrap();
  295. debug!("Executing SQL query: {}", query);
  296. let mut query = sqlx::query(query);
  297. for pair in params[1..].chunks(2) {
  298. if !pair[0].is_u64() || pair[0].as_u64().unwrap() >= QueryType::Last as u64 {
  299. return JsonError::new(InvalidParams, None, id).into()
  300. }
  301. let typ = (pair[0].as_u64().unwrap() as u8).into();
  302. match typ {
  303. QueryType::Integer => {
  304. let val: i32 = match serde_json::from_value(pair[1].clone()) {
  305. Ok(v) => v,
  306. Err(e) => {
  307. error!("[RPC] wallet.exec_sql: Failed casting value to i32: {}", e);
  308. return JsonError::new(ParseError, None, id).into()
  309. }
  310. };
  311. query = query.bind(val);
  312. }
  313. QueryType::Blob => {
  314. let val: Vec<u8> = match serde_json::from_value(pair[1].clone()) {
  315. Ok(v) => v,
  316. Err(e) => {
  317. error!("[RPC] wallet.exec_sql: Failed casting value to Vec<u8>: {}", e);
  318. return JsonError::new(ParseError, None, id).into()
  319. }
  320. };
  321. query = query.bind(val);
  322. }
  323. QueryType::OptionInteger => {
  324. let val: Option<i32> = match serde_json::from_value(pair[1].clone()) {
  325. Ok(v) => v,
  326. Err(e) => {
  327. error!(
  328. "[RPC] wallet.exec_sql: Failed casting value to Option<i32>: {}",
  329. e
  330. );
  331. return JsonError::new(ParseError, None, id).into()
  332. }
  333. };
  334. query = query.bind(val);
  335. }
  336. QueryType::OptionBlob => {
  337. let val: Option<Vec<u8>> = match serde_json::from_value(pair[1].clone()) {
  338. Ok(v) => v,
  339. Err(e) => {
  340. error!("[RPC] wallet.exec_sql: Failed casting value to Option<Vec<u8>>: {}", e);
  341. return JsonError::new(ParseError, None, id).into()
  342. }
  343. };
  344. query = query.bind(val);
  345. }
  346. QueryType::Text => {
  347. let val: String = match serde_json::from_value(pair[1].clone()) {
  348. Ok(v) => v,
  349. Err(e) => {
  350. error!("[RPC] wallet.exec_sql: Failed casting value to String: {}", e);
  351. return JsonError::new(ParseError, None, id).into()
  352. }
  353. };
  354. query = query.bind(val);
  355. }
  356. _ => return JsonError::new(InvalidParams, None, id).into(),
  357. }
  358. }
  359. // Get a wallet connection
  360. let mut conn = match self.wallet.conn.acquire().await {
  361. Ok(v) => v,
  362. Err(e) => {
  363. error!("[RPC] wallet.exec_sql: Failed to acquire wallet connection: {}", e);
  364. return JsonError::new(InternalError, None, id).into()
  365. }
  366. };
  367. if let Err(e) = query.execute(&mut conn).await {
  368. error!("[RPC] wallet.exec_sql: Failed to execute sql query: {}", e);
  369. return JsonError::new(InternalError, None, id).into()
  370. };
  371. JsonResponse::new(json!(true), id).into()
  372. */
  373. }
  374. }