walletdb.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 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::{convert::From, path::PathBuf, sync::Arc};
  19. use smol::lock::Mutex as AsyncMutex;
  20. use tracing::{debug, error};
  21. pub use turso::{Builder, Connection, EncryptionOpts, Value};
  22. use crate::error::{WalletDbError, WalletDbResult};
  23. pub type WalletPtr = Arc<WalletDb>;
  24. const ENCRYPTION_ALGO: &str = "aegis256";
  25. /// Structure representing base wallet database operations.
  26. pub struct WalletDb {
  27. /// Connection to the turso database.
  28. pub conn: AsyncMutex<Connection>,
  29. }
  30. impl WalletDb {
  31. /// Create a new wallet database handler. If `path` is `None`, create it in memory.
  32. pub async fn new(path: Option<PathBuf>, password: Option<&str>) -> WalletDbResult<WalletPtr> {
  33. // Parse database path
  34. let path = match path {
  35. Some(p) => {
  36. let Some(p) = p.to_str() else {
  37. return Err(WalletDbError::ConnectionFailed);
  38. };
  39. String::from(p)
  40. }
  41. None => String::from(":memory:"),
  42. };
  43. // Set encryption. We have to manually devire the key since
  44. // turso doesn't support it yet.
  45. let builder = match password {
  46. Some(password) => {
  47. let opts = EncryptionOpts {
  48. cipher: String::from(ENCRYPTION_ALGO),
  49. hexkey: blake3::hash(password.as_bytes()).to_hex().to_string(),
  50. };
  51. Builder::new_local(&path).experimental_encryption(true).with_encryption(opts)
  52. }
  53. None => Builder::new_local(&path),
  54. };
  55. // Initialize connection builder
  56. let Ok(builder) = builder.build().await else {
  57. return Err(WalletDbError::ConnectionFailed);
  58. };
  59. // Connect to database
  60. let Ok(conn) = builder.connect() else {
  61. return Err(WalletDbError::ConnectionFailed);
  62. };
  63. // Set foreign keys pragma
  64. if let Err(e) = conn.pragma_update("foreign_keys", "ON").await {
  65. error!(target: "walletdb::new", "[WalletDb] Foreign keys pragma update failed: {e}");
  66. return Err(WalletDbError::PragmaUpdateError);
  67. };
  68. debug!(target: "walletdb::new", "[WalletDb] Opened Sqlite connection at \"{path:?}\"");
  69. Ok(Arc::new(Self { conn: AsyncMutex::new(conn) }))
  70. }
  71. /// This function executes a given SQL query that contains multiple SQL statements,
  72. /// that don't contain any parameters.
  73. pub async fn exec_batch_sql(&self, query: &str) -> WalletDbResult<()> {
  74. debug!(target: "walletdb::exec_batch_sql", "[WalletDb] Executing batch SQL query:\n{query}");
  75. if let Err(e) = self.conn.lock().await.execute_batch(query).await {
  76. error!(target: "walletdb::exec_batch_sql", "[WalletDb] Query failed: {e}");
  77. return Err(WalletDbError::QueryExecutionFailed)
  78. };
  79. Ok(())
  80. }
  81. /// This function executes a given SQL query, but isn't able to return anything.
  82. /// Therefore it's best to use it for initializing a table or similar things.
  83. pub async fn exec_sql(&self, query: &str, params: Vec<Value>) -> WalletDbResult<()> {
  84. debug!(target: "walletdb::exec_sql", "[WalletDb] Executing SQL query:\n{query}");
  85. let conn = self.conn.lock().await;
  86. // If no params are provided, execute directly
  87. if params.is_empty() {
  88. if let Err(e) = conn.execute(query, ()).await {
  89. error!(target: "walletdb::exec_sql", "[WalletDb] Query failed: {e}");
  90. return Err(WalletDbError::QueryExecutionFailed)
  91. };
  92. return Ok(())
  93. }
  94. // First we prepare the query
  95. let Ok(mut stmt) = conn.prepare(query).await else {
  96. return Err(WalletDbError::QueryPreparationFailed)
  97. };
  98. // Execute the query using provided params
  99. if let Err(e) = stmt.execute(params).await {
  100. error!(target: "walletdb::exec_sql", "[WalletDb] Query failed: {e}");
  101. return Err(WalletDbError::QueryExecutionFailed)
  102. };
  103. drop(conn);
  104. Ok(())
  105. }
  106. /// Generate a `SELECT` query for provided table from selected column names and
  107. /// provided `WHERE` clauses. Named parameters are supported in the `WHERE` clauses,
  108. /// assuming they follow the normal formatting ":{column_name}".
  109. fn generate_select_query(
  110. &self,
  111. table: &str,
  112. col_names: &[&str],
  113. params: &[(String, Value)],
  114. ) -> String {
  115. let mut query = if col_names.is_empty() {
  116. format!("SELECT * FROM {table}")
  117. } else {
  118. format!("SELECT {} FROM {table}", col_names.join(", "))
  119. };
  120. if params.is_empty() {
  121. return query
  122. }
  123. let mut where_str = Vec::with_capacity(params.len());
  124. for (k, _) in params {
  125. let col = &k[1..];
  126. where_str.push(format!("{col} = {k}"));
  127. }
  128. query.push_str(&format!(" WHERE {}", where_str.join(" AND ")));
  129. query
  130. }
  131. /// Query provided table from selected column names and provided `WHERE` clauses,
  132. /// for a single row.
  133. pub async fn query_single(
  134. &self,
  135. table: &str,
  136. col_names: &[&str],
  137. params: Vec<(String, Value)>,
  138. ) -> WalletDbResult<Vec<Value>> {
  139. // Generate `SELECT` query
  140. let query = self.generate_select_query(table, col_names, &params);
  141. debug!(target: "walletdb::query_single", "[WalletDb] Executing SQL query:\n{query}");
  142. // First we prepare the query
  143. let conn = self.conn.lock().await;
  144. let Ok(mut stmt) = conn.prepare(&query).await else {
  145. return Err(WalletDbError::QueryPreparationFailed)
  146. };
  147. // Execute the query using provided params
  148. let Ok(mut rows) = stmt.query(params).await else {
  149. return Err(WalletDbError::QueryExecutionFailed)
  150. };
  151. // Check if row exists
  152. let Ok(next) = rows.next().await else { return Err(WalletDbError::QueryExecutionFailed) };
  153. let row = match next {
  154. Some(row_result) => row_result,
  155. None => return Err(WalletDbError::RowNotFound),
  156. };
  157. // Grab returned values
  158. let mut result = vec![];
  159. if col_names.is_empty() {
  160. let mut idx = 0;
  161. loop {
  162. let Ok(value) = row.get_value(idx) else { break };
  163. result.push(value);
  164. idx += 1;
  165. }
  166. } else {
  167. for col in col_names {
  168. let Ok(idx) = rows.column_index(col) else {
  169. return Err(WalletDbError::ParseColumnValueError)
  170. };
  171. let Ok(value) = row.get_value(idx) else {
  172. return Err(WalletDbError::ParseColumnValueError)
  173. };
  174. result.push(value);
  175. }
  176. }
  177. Ok(result)
  178. }
  179. /// Query provided table from selected column names and provided `WHERE` clauses,
  180. /// for multiple rows.
  181. pub async fn query_multiple(
  182. &self,
  183. table: &str,
  184. col_names: &[&str],
  185. params: Vec<(String, Value)>,
  186. ) -> WalletDbResult<Vec<Vec<Value>>> {
  187. // Generate `SELECT` query
  188. let query = self.generate_select_query(table, col_names, &params);
  189. debug!(target: "walletdb::query_multiple", "[WalletDb] Executing SQL query:\n{query}");
  190. // First we prepare the query
  191. let conn = self.conn.lock().await;
  192. let Ok(mut stmt) = conn.prepare(&query).await else {
  193. return Err(WalletDbError::QueryPreparationFailed)
  194. };
  195. // Execute the query using provided converted params
  196. let Ok(mut rows) = stmt.query(params).await else {
  197. return Err(WalletDbError::QueryExecutionFailed)
  198. };
  199. // Loop over returned rows and parse them
  200. let mut result = vec![];
  201. loop {
  202. // Check if an error occured
  203. let row = match rows.next().await {
  204. Ok(r) => r,
  205. Err(_) => return Err(WalletDbError::QueryExecutionFailed),
  206. };
  207. // Check if no row was returned
  208. let row = match row {
  209. Some(r) => r,
  210. None => break,
  211. };
  212. // Grab row returned values
  213. let mut row_values = vec![];
  214. if col_names.is_empty() {
  215. let mut idx = 0;
  216. loop {
  217. let Ok(value) = row.get_value(idx) else { break };
  218. row_values.push(value);
  219. idx += 1;
  220. }
  221. } else {
  222. for col in col_names {
  223. let Ok(idx) = rows.column_index(col) else {
  224. return Err(WalletDbError::ParseColumnValueError)
  225. };
  226. let Ok(value) = row.get_value(idx) else {
  227. return Err(WalletDbError::ParseColumnValueError)
  228. };
  229. row_values.push(value);
  230. }
  231. }
  232. result.push(row_values);
  233. }
  234. Ok(result)
  235. }
  236. /// Query provided table using provided query for multiple rows.
  237. pub async fn query_custom(
  238. &self,
  239. query: &str,
  240. params: Vec<Value>,
  241. ) -> WalletDbResult<Vec<Vec<Value>>> {
  242. debug!(target: "walletdb::query_custom", "[WalletDb] Executing SQL query:\n{query}");
  243. // First we prepare the query
  244. let conn = self.conn.lock().await;
  245. let Ok(mut stmt) = conn.prepare(query).await else {
  246. return Err(WalletDbError::QueryPreparationFailed)
  247. };
  248. // Execute the query using provided converted params
  249. let Ok(mut rows) = stmt.query(params).await else {
  250. return Err(WalletDbError::QueryExecutionFailed)
  251. };
  252. // Loop over returned rows and parse them
  253. let mut result = vec![];
  254. loop {
  255. // Check if an error occured
  256. let row = match rows.next().await {
  257. Ok(r) => r,
  258. Err(_) => return Err(WalletDbError::QueryExecutionFailed),
  259. };
  260. // Check if no row was returned
  261. let row = match row {
  262. Some(r) => r,
  263. None => break,
  264. };
  265. // Grab row returned values
  266. let mut row_values = vec![];
  267. let mut idx = 0;
  268. loop {
  269. let Ok(value) = row.get_value(idx) else { break };
  270. row_values.push(value);
  271. idx += 1;
  272. }
  273. result.push(row_values);
  274. }
  275. Ok(result)
  276. }
  277. }
  278. /// Custom implementation of `turso::params!` to construct positional
  279. /// params from a heterogeneous set of params types as a vec.
  280. #[macro_export]
  281. macro_rules! params {
  282. () => {
  283. ()
  284. };
  285. ($($value:expr),* $(,)?) => {
  286. [$(turso::Value::from($value)),*].to_vec()
  287. };
  288. }
  289. /// Custom implementation of `turso::named_params!` to construct named
  290. /// params from a heterogeneous set of params types as a vec.
  291. #[macro_export]
  292. macro_rules! named_params {
  293. () => {
  294. ()
  295. };
  296. ($($param_name:literal: $value:expr),* $(,)?) => {
  297. [$((String::from($param_name), turso::Value::from($value))),*].to_vec()
  298. };
  299. }
  300. /// Custom implementation of `turso::named_params!` to use `expr`
  301. /// instead of `literal` as `$param_name`, and append the ":" named
  302. /// parameters prefix.
  303. #[macro_export]
  304. macro_rules! convert_named_params {
  305. () => {
  306. ()
  307. };
  308. ($(($param_name:expr, $value:expr)),* $(,)?) => {
  309. [$((format!(":{}", $param_name), turso::Value::from($value))),*].to_vec()
  310. };
  311. }
  312. #[cfg(test)]
  313. mod tests {
  314. use crate::walletdb::{Value, WalletDb};
  315. #[test]
  316. fn test_mem_wallet() {
  317. smol::block_on(async {
  318. let wallet = WalletDb::new(None, Some("foobar")).await.unwrap();
  319. wallet
  320. .exec_batch_sql(
  321. "CREATE TABLE mista ( numba INTEGER ); INSERT INTO mista ( numba ) VALUES ( 42 );",
  322. ).await
  323. .unwrap();
  324. let ret = wallet.query_single("mista", &["numba"], vec![]).await.unwrap();
  325. assert_eq!(ret.len(), 1);
  326. let numba: i64 = if let Value::Integer(numba) = ret[0] { numba } else { -1 };
  327. assert_eq!(numba, 42);
  328. let ret = wallet.query_custom("SELECT numba FROM mista;", vec![]).await.unwrap();
  329. assert_eq!(ret.len(), 1);
  330. assert_eq!(ret[0].len(), 1);
  331. let numba: i64 = if let Value::Integer(numba) = ret[0][0] { numba } else { -1 };
  332. assert_eq!(numba, 42);
  333. })
  334. }
  335. #[test]
  336. fn test_query_single() {
  337. smol::block_on(async {
  338. let wallet = WalletDb::new(None, None).await.unwrap();
  339. wallet
  340. .exec_batch_sql(
  341. "CREATE TABLE mista ( why INTEGER, are TEXT, you INTEGER, gae BLOB );",
  342. )
  343. .await
  344. .unwrap();
  345. let why = 42;
  346. let are = "are".to_string();
  347. let you = 69;
  348. let gae = vec![42u8; 32];
  349. wallet
  350. .exec_sql(
  351. "INSERT INTO mista ( why, are, you, gae ) VALUES (?1, ?2, ?3, ?4);",
  352. params![why, are.clone(), you, gae.clone()],
  353. )
  354. .await
  355. .unwrap();
  356. let ret =
  357. wallet.query_single("mista", &["why", "are", "you", "gae"], vec![]).await.unwrap();
  358. assert_eq!(ret.len(), 4);
  359. assert_eq!(ret[0], Value::Integer(why));
  360. assert_eq!(ret[1], Value::Text(are.clone()));
  361. assert_eq!(ret[2], Value::Integer(you));
  362. assert_eq!(ret[3], Value::Blob(gae.clone()));
  363. let ret =
  364. wallet.query_custom("SELECT why, are, you, gae FROM mista;", vec![]).await.unwrap();
  365. assert_eq!(ret.len(), 1);
  366. assert_eq!(ret[0].len(), 4);
  367. assert_eq!(ret[0][0], Value::Integer(why));
  368. assert_eq!(ret[0][1], Value::Text(are.clone()));
  369. assert_eq!(ret[0][2], Value::Integer(you));
  370. assert_eq!(ret[0][3], Value::Blob(gae.clone()));
  371. let ret = wallet
  372. .query_single(
  373. "mista",
  374. &["gae"],
  375. named_params! {":why": why, ":are": are.clone(), ":you": you},
  376. )
  377. .await
  378. .unwrap();
  379. assert_eq!(ret.len(), 1);
  380. assert_eq!(ret[0], Value::Blob(gae.clone()));
  381. let ret = wallet
  382. .query_custom(
  383. "SELECT gae FROM mista WHERE why = ?1 AND are = ?2 AND you = ?3;",
  384. params![why, are, you],
  385. )
  386. .await
  387. .unwrap();
  388. assert_eq!(ret.len(), 1);
  389. assert_eq!(ret[0].len(), 1);
  390. assert_eq!(ret[0][0], Value::Blob(gae));
  391. })
  392. }
  393. #[test]
  394. fn test_query_multi() {
  395. smol::block_on(async {
  396. let wallet = WalletDb::new(None, None).await.unwrap();
  397. wallet
  398. .exec_batch_sql(
  399. "CREATE TABLE mista ( why INTEGER, are TEXT, you INTEGER, gae BLOB );",
  400. )
  401. .await
  402. .unwrap();
  403. let why = 42;
  404. let are = "are".to_string();
  405. let you = 69;
  406. let gae = vec![42u8; 32];
  407. wallet
  408. .exec_sql(
  409. "INSERT INTO mista ( why, are, you, gae ) VALUES (?1, ?2, ?3, ?4);",
  410. params![why, are.clone(), you, gae.clone()],
  411. )
  412. .await
  413. .unwrap();
  414. wallet
  415. .exec_sql(
  416. "INSERT INTO mista ( why, are, you, gae ) VALUES (?1, ?2, ?3, ?4);",
  417. params![why, are.clone(), you, gae.clone()],
  418. )
  419. .await
  420. .unwrap();
  421. let ret = wallet.query_multiple("mista", &[], vec![]).await.unwrap();
  422. assert_eq!(ret.len(), 2);
  423. for row in ret {
  424. assert_eq!(row.len(), 4);
  425. assert_eq!(row[0], Value::Integer(why));
  426. assert_eq!(row[1], Value::Text(are.clone()));
  427. assert_eq!(row[2], Value::Integer(you));
  428. assert_eq!(row[3], Value::Blob(gae.clone()));
  429. }
  430. let ret = wallet.query_custom("SELECT * FROM mista;", vec![]).await.unwrap();
  431. assert_eq!(ret.len(), 2);
  432. for row in ret {
  433. assert_eq!(row.len(), 4);
  434. assert_eq!(row[0], Value::Integer(why));
  435. assert_eq!(row[1], Value::Text(are.clone()));
  436. assert_eq!(row[2], Value::Integer(you));
  437. assert_eq!(row[3], Value::Blob(gae.clone()));
  438. }
  439. let ret = wallet
  440. .query_multiple(
  441. "mista",
  442. &["gae"],
  443. convert_named_params! {("why", why), ("are", are.clone()), ("you", you)},
  444. )
  445. .await
  446. .unwrap();
  447. assert_eq!(ret.len(), 2);
  448. for row in ret {
  449. assert_eq!(row.len(), 1);
  450. assert_eq!(row[0], Value::Blob(gae.clone()));
  451. }
  452. let ret = wallet
  453. .query_custom(
  454. "SELECT gae FROM mista WHERE why = ?1 AND are = ?2 AND you = ?3;",
  455. params![why, are, you],
  456. )
  457. .await
  458. .unwrap();
  459. assert_eq!(ret.len(), 2);
  460. for row in ret {
  461. assert_eq!(row.len(), 1);
  462. assert_eq!(row[0], Value::Blob(gae.clone()));
  463. }
  464. })
  465. }
  466. }