rpc_wallet.rs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2022 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) => v,
  80. Err(e) => {
  81. error!("[RPC] wallet.query_row_single: Failed to execute SQL query: {}", e);
  82. return server_error(RpcError::NoRowsFoundInWallet, id, None)
  83. }
  84. };
  85. // Try to decode the row into what was requested
  86. let mut ret: Vec<Value> = vec![];
  87. for (typ, col) in types.iter().zip(names) {
  88. match typ {
  89. QueryType::Integer => {
  90. let value: i32 = match row.try_get(col) {
  91. Ok(v) => v,
  92. Err(e) => {
  93. error!("[RPC] wallet.query_row_single: {}", e);
  94. return JsonError::new(ParseError, None, id).into()
  95. }
  96. };
  97. ret.push(json!(value));
  98. }
  99. QueryType::Blob => {
  100. let value: Vec<u8> = match row.try_get(col) {
  101. Ok(v) => v,
  102. Err(e) => {
  103. error!("[RPC] wallet.query_row_single: {}", e);
  104. return JsonError::new(ParseError, None, id).into()
  105. }
  106. };
  107. ret.push(json!(value));
  108. }
  109. _ => unreachable!(),
  110. }
  111. }
  112. JsonResponse::new(json!(ret), id).into()
  113. }
  114. // RPCAPI:
  115. // Executes an arbitrary SQL query on the wallet, and returns `true` on success.
  116. // `params[1..]` can optionally be provided in pairs like in `wallet.query_row_single`.
  117. //
  118. // --> {"jsonrpc": "2.0", "method": "wallet.exec_sql", "params": ["CREATE TABLE ..."], "id": 1}
  119. // <-- {"jsonrpc": "2.0", "result": true, "id": 1}
  120. pub async fn wallet_exec_sql(&self, id: Value, params: &[Value]) -> JsonResult {
  121. if params.is_empty() || !params[0].is_string() {
  122. return JsonError::new(InvalidParams, None, id).into()
  123. }
  124. if params.len() > 1 && params[1..].len() % 2 != 0 {
  125. return JsonError::new(InvalidParams, None, id).into()
  126. }
  127. let query = params[0].as_str().unwrap();
  128. debug!("Executing SQL query: {}", query);
  129. let mut query = sqlx::query(query);
  130. for pair in params[1..].chunks(2) {
  131. if !pair[0].is_u64() || pair[0].as_u64().unwrap() >= QueryType::Last as u64 {
  132. return JsonError::new(InvalidParams, None, id).into()
  133. }
  134. let typ = (pair[0].as_u64().unwrap() as u8).into();
  135. match typ {
  136. QueryType::Integer => {
  137. let val: i32 = match serde_json::from_value(pair[1].clone()) {
  138. Ok(v) => v,
  139. Err(e) => {
  140. error!("[RPC] wallet.exec_sql: Failed casting value to i32: {}", e);
  141. return JsonError::new(ParseError, None, id).into()
  142. }
  143. };
  144. query = query.bind(val);
  145. }
  146. QueryType::Blob => {
  147. let val: Vec<u8> = match serde_json::from_value(pair[1].clone()) {
  148. Ok(v) => v,
  149. Err(e) => {
  150. error!("[RPC] wallet.exec_sql: Failed casting value to Vec<u8>: {}", e);
  151. return JsonError::new(ParseError, None, id).into()
  152. }
  153. };
  154. query = query.bind(val);
  155. }
  156. _ => return JsonError::new(InvalidParams, None, id).into(),
  157. }
  158. }
  159. // Get a wallet connection
  160. let mut conn = match self.wallet.conn.acquire().await {
  161. Ok(v) => v,
  162. Err(e) => {
  163. error!("[RPC] wallet.exec_sql: Failed to acquire wallet connection: {}", e);
  164. return JsonError::new(InternalError, None, id).into()
  165. }
  166. };
  167. if let Err(e) = query.execute(&mut conn).await {
  168. error!("[RPC] wallet.exec_sql: Failed to execute sql query: {}", e);
  169. return JsonError::new(InternalError, None, id).into()
  170. };
  171. JsonResponse::new(json!(true), id).into()
  172. }
  173. }