rpc_wallet.rs 15 KB

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