rpc_wallet.rs 17 KB

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