walletdb.rs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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::{
  19. path::PathBuf,
  20. sync::{Arc, Mutex},
  21. };
  22. use darkfi_sdk::{
  23. crypto::{
  24. pasta_prelude::PrimeField,
  25. smt::{PoseidonFp, SparseMerkleTree, StorageAdapter, SMT_FP_DEPTH},
  26. },
  27. error::{ContractError, ContractResult},
  28. pasta::pallas,
  29. };
  30. use log::{debug, error};
  31. use num_bigint::BigUint;
  32. use rusqlite::{
  33. types::{ToSql, Value},
  34. Connection,
  35. };
  36. use crate::error::{WalletDbError, WalletDbResult};
  37. pub type WalletPtr = Arc<WalletDb>;
  38. /// Structure representing base wallet database operations.
  39. pub struct WalletDb {
  40. /// Connection to the SQLite database.
  41. pub conn: Mutex<Connection>,
  42. /// Inverse queries cache, in case we want to rollback
  43. /// executed queries, stored as raw SQL strings.
  44. inverse_cache: Mutex<Vec<String>>,
  45. }
  46. impl WalletDb {
  47. /// Create a new wallet database handler. If `path` is `None`, create it in memory.
  48. pub fn new(path: Option<PathBuf>, password: Option<&str>) -> WalletDbResult<WalletPtr> {
  49. let Ok(conn) = (match path.clone() {
  50. Some(p) => Connection::open(p),
  51. None => Connection::open_in_memory(),
  52. }) else {
  53. return Err(WalletDbError::ConnectionFailed);
  54. };
  55. if let Some(password) = password {
  56. if let Err(e) = conn.pragma_update(None, "key", password) {
  57. error!(target: "walletdb::new", "[WalletDb] Pragma update failed: {e}");
  58. return Err(WalletDbError::PragmaUpdateError);
  59. };
  60. }
  61. if let Err(e) = conn.pragma_update(None, "foreign_keys", "ON") {
  62. error!(target: "walletdb::new", "[WalletDb] Pragma update failed: {e}");
  63. return Err(WalletDbError::PragmaUpdateError);
  64. };
  65. debug!(target: "walletdb::new", "[WalletDb] Opened Sqlite connection at \"{path:?}\"");
  66. Ok(Arc::new(Self { conn: Mutex::new(conn), inverse_cache: Mutex::new(vec![]) }))
  67. }
  68. /// This function executes a given SQL query that contains multiple SQL statements,
  69. /// that don't contain any parameters.
  70. pub fn exec_batch_sql(&self, query: &str) -> WalletDbResult<()> {
  71. debug!(target: "walletdb::exec_batch_sql", "[WalletDb] Executing batch SQL query:\n{query}");
  72. let Ok(conn) = self.conn.lock() else { return Err(WalletDbError::FailedToAquireLock) };
  73. if let Err(e) = conn.execute_batch(query) {
  74. error!(target: "walletdb::exec_batch_sql", "[WalletDb] Query failed: {e}");
  75. return Err(WalletDbError::QueryExecutionFailed)
  76. };
  77. Ok(())
  78. }
  79. /// This function executes a given SQL query, but isn't able to return anything.
  80. /// Therefore it's best to use it for initializing a table or similar things.
  81. pub fn exec_sql(&self, query: &str, params: &[&dyn ToSql]) -> WalletDbResult<()> {
  82. debug!(target: "walletdb::exec_sql", "[WalletDb] Executing SQL query:\n{query}");
  83. let Ok(conn) = self.conn.lock() else { return Err(WalletDbError::FailedToAquireLock) };
  84. // If no params are provided, execute directly
  85. if params.is_empty() {
  86. if let Err(e) = conn.execute(query, ()) {
  87. error!(target: "walletdb::exec_sql", "[WalletDb] Query failed: {e}");
  88. return Err(WalletDbError::QueryExecutionFailed)
  89. };
  90. return Ok(())
  91. }
  92. // First we prepare the query
  93. let Ok(mut stmt) = conn.prepare(query) else {
  94. return Err(WalletDbError::QueryPreparationFailed)
  95. };
  96. // Execute the query using provided params
  97. if let Err(e) = stmt.execute(params) {
  98. error!(target: "walletdb::exec_sql", "[WalletDb] Query failed: {e}");
  99. return Err(WalletDbError::QueryExecutionFailed)
  100. };
  101. // Finalize query and drop connection lock
  102. if let Err(e) = stmt.finalize() {
  103. error!(target: "walletdb::exec_sql", "[WalletDb] Query finalization failed: {e}");
  104. return Err(WalletDbError::QueryFinalizationFailed)
  105. };
  106. drop(conn);
  107. Ok(())
  108. }
  109. /// Generate a new statement for provided query and bind the provided params,
  110. /// returning the raw SQL query as a string.
  111. pub fn create_prepared_statement(
  112. &self,
  113. query: &str,
  114. params: &[&dyn ToSql],
  115. ) -> WalletDbResult<String> {
  116. debug!(target: "walletdb::create_prepared_statement", "[WalletDb] Preparing statement for SQL query:\n{query}");
  117. let Ok(conn) = self.conn.lock() else { return Err(WalletDbError::FailedToAquireLock) };
  118. // First we prepare the query
  119. let Ok(mut stmt) = conn.prepare(query) else {
  120. return Err(WalletDbError::QueryPreparationFailed)
  121. };
  122. // Bind all provided params
  123. for (index, param) in params.iter().enumerate() {
  124. if stmt.raw_bind_parameter(index + 1, param).is_err() {
  125. return Err(WalletDbError::QueryPreparationFailed)
  126. };
  127. }
  128. // Grab the raw SQL
  129. let query = stmt.expanded_sql().unwrap();
  130. // Drop statement and the connection lock
  131. drop(stmt);
  132. drop(conn);
  133. Ok(query)
  134. }
  135. /// Generate a `SELECT` query for provided table from selected column names and
  136. /// provided `WHERE` clauses. Named parameters are supported in the `WHERE` clauses,
  137. /// assuming they follow the normal formatting ":{column_name}".
  138. fn generate_select_query(
  139. &self,
  140. table: &str,
  141. col_names: &[&str],
  142. params: &[(&str, &dyn ToSql)],
  143. ) -> String {
  144. let mut query = if col_names.is_empty() {
  145. format!("SELECT * FROM {}", table)
  146. } else {
  147. format!("SELECT {} FROM {}", col_names.join(", "), table)
  148. };
  149. if params.is_empty() {
  150. return query
  151. }
  152. let mut where_str = Vec::with_capacity(params.len());
  153. for (k, _) in params {
  154. let col = &k[1..];
  155. where_str.push(format!("{col} = {k}"));
  156. }
  157. query.push_str(&format!(" WHERE {}", where_str.join(" AND ")));
  158. query
  159. }
  160. /// Query provided table from selected column names and provided `WHERE` clauses,
  161. /// for a single row.
  162. pub fn query_single(
  163. &self,
  164. table: &str,
  165. col_names: &[&str],
  166. params: &[(&str, &dyn ToSql)],
  167. ) -> WalletDbResult<Vec<Value>> {
  168. // Generate `SELECT` query
  169. let query = self.generate_select_query(table, col_names, params);
  170. debug!(target: "walletdb::query_single", "[WalletDb] Executing SQL query:\n{query}");
  171. // First we prepare the query
  172. let Ok(conn) = self.conn.lock() else { return Err(WalletDbError::FailedToAquireLock) };
  173. let Ok(mut stmt) = conn.prepare(&query) else {
  174. return Err(WalletDbError::QueryPreparationFailed)
  175. };
  176. // Execute the query using provided params
  177. let Ok(mut rows) = stmt.query(params) else {
  178. return Err(WalletDbError::QueryExecutionFailed)
  179. };
  180. // Check if row exists
  181. let Ok(next) = rows.next() else { return Err(WalletDbError::QueryExecutionFailed) };
  182. let row = match next {
  183. Some(row_result) => row_result,
  184. None => return Err(WalletDbError::RowNotFound),
  185. };
  186. // Grab returned values
  187. let mut result = vec![];
  188. if col_names.is_empty() {
  189. let mut idx = 0;
  190. loop {
  191. let Ok(value) = row.get(idx) else { break };
  192. result.push(value);
  193. idx += 1;
  194. }
  195. } else {
  196. for col in col_names {
  197. let Ok(value) = row.get(*col) else {
  198. return Err(WalletDbError::ParseColumnValueError)
  199. };
  200. result.push(value);
  201. }
  202. }
  203. Ok(result)
  204. }
  205. /// Query provided table from selected column names and provided `WHERE` clauses,
  206. /// for multiple rows.
  207. pub fn query_multiple(
  208. &self,
  209. table: &str,
  210. col_names: &[&str],
  211. params: &[(&str, &dyn ToSql)],
  212. ) -> WalletDbResult<Vec<Vec<Value>>> {
  213. // Generate `SELECT` query
  214. let query = self.generate_select_query(table, col_names, params);
  215. debug!(target: "walletdb::query_multiple", "[WalletDb] Executing SQL query:\n{query}");
  216. // First we prepare the query
  217. let Ok(conn) = self.conn.lock() else { return Err(WalletDbError::FailedToAquireLock) };
  218. let Ok(mut stmt) = conn.prepare(&query) else {
  219. return Err(WalletDbError::QueryPreparationFailed)
  220. };
  221. // Execute the query using provided converted params
  222. let Ok(mut rows) = stmt.query(params) else {
  223. return Err(WalletDbError::QueryExecutionFailed)
  224. };
  225. // Loop over returned rows and parse them
  226. let mut result = vec![];
  227. loop {
  228. // Check if an error occured
  229. let row = match rows.next() {
  230. Ok(r) => r,
  231. Err(_) => return Err(WalletDbError::QueryExecutionFailed),
  232. };
  233. // Check if no row was returned
  234. let row = match row {
  235. Some(r) => r,
  236. None => break,
  237. };
  238. // Grab row returned values
  239. let mut row_values = vec![];
  240. if col_names.is_empty() {
  241. let mut idx = 0;
  242. loop {
  243. let Ok(value) = row.get(idx) else { break };
  244. row_values.push(value);
  245. idx += 1;
  246. }
  247. } else {
  248. for col in col_names {
  249. let Ok(value) = row.get(*col) else {
  250. return Err(WalletDbError::ParseColumnValueError)
  251. };
  252. row_values.push(value);
  253. }
  254. }
  255. result.push(row_values);
  256. }
  257. Ok(result)
  258. }
  259. /// Query provided table using provided query for multiple rows.
  260. pub fn query_custom(
  261. &self,
  262. query: &str,
  263. params: &[&dyn ToSql],
  264. ) -> WalletDbResult<Vec<Vec<Value>>> {
  265. debug!(target: "walletdb::query_custom", "[WalletDb] Executing SQL query:\n{query}");
  266. // First we prepare the query
  267. let Ok(conn) = self.conn.lock() else { return Err(WalletDbError::FailedToAquireLock) };
  268. let Ok(mut stmt) = conn.prepare(query) else {
  269. return Err(WalletDbError::QueryPreparationFailed)
  270. };
  271. // Execute the query using provided converted params
  272. let Ok(mut rows) = stmt.query(params) else {
  273. return Err(WalletDbError::QueryExecutionFailed)
  274. };
  275. // Loop over returned rows and parse them
  276. let mut result = vec![];
  277. loop {
  278. // Check if an error occured
  279. let row = match rows.next() {
  280. Ok(r) => r,
  281. Err(_) => return Err(WalletDbError::QueryExecutionFailed),
  282. };
  283. // Check if no row was returned
  284. let row = match row {
  285. Some(r) => r,
  286. None => break,
  287. };
  288. // Grab row returned values
  289. let mut row_values = vec![];
  290. let mut idx = 0;
  291. loop {
  292. let Ok(value) = row.get(idx) else { break };
  293. row_values.push(value);
  294. idx += 1;
  295. }
  296. result.push(row_values);
  297. }
  298. Ok(result)
  299. }
  300. /// Auxiliary function to store provided inverse query into our cache.
  301. pub fn cache_inverse(&self, query: String) -> WalletDbResult<()> {
  302. debug!(target: "walletdb::cache_inverse", "[WalletDb] Storing query:\n{query}");
  303. let Ok(mut cache) = self.inverse_cache.lock() else {
  304. return Err(WalletDbError::FailedToAquireLock)
  305. };
  306. // Push the query into the cache
  307. cache.push(query);
  308. // Drop cache lock
  309. drop(cache);
  310. Ok(())
  311. }
  312. /// Auxiliary function to retrieve cached inverse queries into a single SQL execution block.
  313. /// The final query will contain the queries in reverse order, and cache is cleared afterwards.
  314. pub fn grab_inverse_cache_block(&self) -> WalletDbResult<String> {
  315. // Grab cache lock
  316. debug!(target: "walletdb::grab_inverse_block", "[WalletDb] Grabbing cached inverse queries");
  317. let Ok(cache) = self.inverse_cache.lock() else {
  318. return Err(WalletDbError::FailedToAquireLock)
  319. };
  320. // Build the full SQL block query
  321. let mut inverse_batch = String::from("BEGIN;");
  322. for query in cache.iter().rev() {
  323. inverse_batch += query;
  324. }
  325. inverse_batch += "END;";
  326. // Drop the lock
  327. drop(cache);
  328. Ok(inverse_batch)
  329. }
  330. /// Auxiliary function to clear inverse queries cache.
  331. pub fn clear_inverse_cache(&self) -> WalletDbResult<()> {
  332. // Grab cache lock
  333. let Ok(mut cache) = self.inverse_cache.lock() else {
  334. return Err(WalletDbError::FailedToAquireLock)
  335. };
  336. // Clear cache
  337. *cache = vec![];
  338. // Drop the lock
  339. drop(cache);
  340. Ok(())
  341. }
  342. }
  343. /// Custom implementation of rusqlite::named_params! to use `expr` instead of `literal` as `$param_name`,
  344. /// and append the ":" named parameters prefix.
  345. #[macro_export]
  346. macro_rules! convert_named_params {
  347. () => {
  348. &[] as &[(&str, &dyn rusqlite::types::ToSql)]
  349. };
  350. ($(($param_name:expr, $param_val:expr)),+ $(,)?) => {
  351. &[$((format!(":{}", $param_name).as_str(), &$param_val as &dyn rusqlite::types::ToSql)),+] as &[(&str, &dyn rusqlite::types::ToSql)]
  352. };
  353. }
  354. /// Wallet SMT definition
  355. pub type WalletSmt<'a> = SparseMerkleTree<
  356. 'static,
  357. SMT_FP_DEPTH,
  358. { SMT_FP_DEPTH + 1 },
  359. pallas::Base,
  360. PoseidonFp,
  361. WalletStorage<'a>,
  362. >;
  363. /// An SMT adapter for wallet SQLite database storage.
  364. pub struct WalletStorage<'a> {
  365. wallet: &'a WalletPtr,
  366. table: &'a str,
  367. key_col: &'a str,
  368. value_col: &'a str,
  369. }
  370. impl<'a> WalletStorage<'a> {
  371. pub fn new(
  372. wallet: &'a WalletPtr,
  373. table: &'a str,
  374. key_col: &'a str,
  375. value_col: &'a str,
  376. ) -> Self {
  377. Self { wallet, table, key_col, value_col }
  378. }
  379. }
  380. impl StorageAdapter for WalletStorage<'_> {
  381. type Value = pallas::Base;
  382. fn put(&mut self, key: BigUint, value: pallas::Base) -> ContractResult {
  383. // Check if record already exists to create the corresponding query,
  384. // its param and its inverse.
  385. let (query, params, inverse) = match self.get(&key) {
  386. Some(v) => {
  387. // Create an SQL `UPDATE` query
  388. let q = format!(
  389. "UPDATE {} SET {} = ?1 WHERE {} = ?2;",
  390. self.table, self.value_col, self.key_col
  391. );
  392. // Create its inverse query
  393. let i = match self.wallet.create_prepared_statement(
  394. &format!(
  395. "UPDATE {} SET {} = ?1 WHERE {} = ?2;",
  396. self.table, self.value_col, self.key_col
  397. ),
  398. rusqlite::params![v.to_repr(), key.to_bytes_le()],
  399. ) {
  400. Ok(i) => i,
  401. Err(e) => {
  402. error!(target: "walletdb::StorageAdapter::put", "Creating inverse query for key {key:?} failed: {e:?}");
  403. return Err(ContractError::SmtPutFailed)
  404. }
  405. };
  406. (q, rusqlite::params![value.to_repr(), key.to_bytes_le()], i)
  407. }
  408. None => {
  409. // Create an SQL `INSERT` query
  410. let q = format!(
  411. "INSERT INTO {} ({}, {}) VALUES (?1, ?2);",
  412. self.table, self.key_col, self.value_col
  413. );
  414. // Create its inverse query
  415. let i = match self.wallet.create_prepared_statement(
  416. &format!("DELETE FROM {} WHERE {} = ?1;", self.table, self.key_col),
  417. rusqlite::params![key.to_bytes_le()],
  418. ) {
  419. Ok(i) => i,
  420. Err(e) => {
  421. error!(target: "walletdb::StorageAdapter::put", "Creating inverse query for key {key:?} failed: {e:?}");
  422. return Err(ContractError::SmtPutFailed)
  423. }
  424. };
  425. (q, rusqlite::params![key.to_bytes_le(), value.to_repr()], i)
  426. }
  427. };
  428. // Execute the query
  429. if let Err(e) = self.wallet.exec_sql(&query, params) {
  430. error!(target: "walletdb::StorageAdapter::put", "Inserting key {key:?}, value {value:?} into DB failed: {e:?}");
  431. return Err(ContractError::SmtPutFailed)
  432. }
  433. // Store its inverse
  434. if let Err(e) = self.wallet.cache_inverse(inverse) {
  435. error!(target: "walletdb::StorageAdapter::put", "Inserting inverse query into cache failed: {e:?}");
  436. return Err(ContractError::SmtPutFailed)
  437. }
  438. Ok(())
  439. }
  440. fn get(&self, key: &BigUint) -> Option<pallas::Base> {
  441. let row = match self.wallet.query_single(
  442. self.table,
  443. &[self.value_col],
  444. convert_named_params! {(self.key_col, key.to_bytes_le())},
  445. ) {
  446. Ok(r) => r,
  447. Err(WalletDbError::RowNotFound) => return None,
  448. Err(e) => {
  449. error!(target: "walletdb::StorageAdapter::get", "Fetching key {key:?} from DB failed: {e:?}");
  450. return None
  451. }
  452. };
  453. let Value::Blob(ref value_bytes) = row[0] else {
  454. error!(target: "walletdb::StorageAdapter::get", "Parsing key {key:?} value bytes");
  455. return None
  456. };
  457. let mut repr = [0; 32];
  458. repr.copy_from_slice(value_bytes);
  459. pallas::Base::from_repr(repr).into()
  460. }
  461. fn del(&mut self, key: &BigUint) -> ContractResult {
  462. // Check if record already exists to create the corresponding query,
  463. // its param and its inverse.
  464. let (query, params, inverse) = match self.get(key) {
  465. Some(value) => {
  466. // Create an SQL `DELETE` query
  467. let q = format!("DELETE FROM {} WHERE {} = ?1;", self.table, self.key_col);
  468. // Create its inverse query
  469. let i = match self.wallet.create_prepared_statement(
  470. &format!(
  471. "INSERT INTO {} ({}, {}) VALUES (?1, ?2);",
  472. self.table, self.key_col, self.value_col
  473. ),
  474. rusqlite::params![key.to_bytes_le(), value.to_repr()],
  475. ) {
  476. Ok(i) => i,
  477. Err(e) => {
  478. error!(target: "walletdb::StorageAdapter::del", "Creating inverse query for key {key:?} failed: {e:?}");
  479. return Err(ContractError::SmtDelFailed)
  480. }
  481. };
  482. (q, rusqlite::params![key.to_bytes_le()], i)
  483. }
  484. None => {
  485. // If record doesn't exist do nothing
  486. return Ok(())
  487. }
  488. };
  489. // Execute the query
  490. if let Err(e) = self.wallet.exec_sql(&query, params) {
  491. error!(target: "walletdb::StorageAdapter::del", "Removing key {key:?} from DB failed: {e:?}");
  492. return Err(ContractError::SmtDelFailed)
  493. }
  494. // Store its inverse
  495. if let Err(e) = self.wallet.cache_inverse(inverse) {
  496. error!(target: "walletdb::StorageAdapter::del", "Inserting inverse query into cache failed: {e:?}");
  497. return Err(ContractError::SmtDelFailed)
  498. }
  499. Ok(())
  500. }
  501. }
  502. #[cfg(test)]
  503. mod tests {
  504. use darkfi::zk::halo2::Field;
  505. use darkfi_sdk::{
  506. crypto::smt::{gen_empty_nodes, util::FieldHasher, PoseidonFp, SparseMerkleTree},
  507. pasta::pallas,
  508. };
  509. use rand::rngs::OsRng;
  510. use rusqlite::types::Value;
  511. use crate::walletdb::{WalletDb, WalletStorage};
  512. #[test]
  513. fn test_mem_wallet() {
  514. let wallet = WalletDb::new(None, Some("foobar")).unwrap();
  515. wallet
  516. .exec_batch_sql(
  517. "CREATE TABLE mista ( numba INTEGER ); INSERT INTO mista ( numba ) VALUES ( 42 );",
  518. )
  519. .unwrap();
  520. let ret = wallet.query_single("mista", &["numba"], &[]).unwrap();
  521. assert_eq!(ret.len(), 1);
  522. let numba: i64 = if let Value::Integer(numba) = ret[0] { numba } else { -1 };
  523. assert_eq!(numba, 42);
  524. let ret = wallet.query_custom("SELECT numba FROM mista;", &[]).unwrap();
  525. assert_eq!(ret.len(), 1);
  526. assert_eq!(ret[0].len(), 1);
  527. let numba: i64 = if let Value::Integer(numba) = ret[0][0] { numba } else { -1 };
  528. assert_eq!(numba, 42);
  529. }
  530. #[test]
  531. fn test_query_single() {
  532. let wallet = WalletDb::new(None, None).unwrap();
  533. wallet
  534. .exec_batch_sql("CREATE TABLE mista ( why INTEGER, are TEXT, you INTEGER, gae BLOB );")
  535. .unwrap();
  536. let why = 42;
  537. let are = "are".to_string();
  538. let you = 69;
  539. let gae = vec![42u8; 32];
  540. wallet
  541. .exec_sql(
  542. "INSERT INTO mista ( why, are, you, gae ) VALUES (?1, ?2, ?3, ?4);",
  543. rusqlite::params![why, are, you, gae],
  544. )
  545. .unwrap();
  546. let ret = wallet.query_single("mista", &["why", "are", "you", "gae"], &[]).unwrap();
  547. assert_eq!(ret.len(), 4);
  548. assert_eq!(ret[0], Value::Integer(why));
  549. assert_eq!(ret[1], Value::Text(are.clone()));
  550. assert_eq!(ret[2], Value::Integer(you));
  551. assert_eq!(ret[3], Value::Blob(gae.clone()));
  552. let ret = wallet.query_custom("SELECT why, are, you, gae FROM mista;", &[]).unwrap();
  553. assert_eq!(ret.len(), 1);
  554. assert_eq!(ret[0].len(), 4);
  555. assert_eq!(ret[0][0], Value::Integer(why));
  556. assert_eq!(ret[0][1], Value::Text(are.clone()));
  557. assert_eq!(ret[0][2], Value::Integer(you));
  558. assert_eq!(ret[0][3], Value::Blob(gae.clone()));
  559. let ret = wallet
  560. .query_single(
  561. "mista",
  562. &["gae"],
  563. rusqlite::named_params! {":why": why, ":are": are, ":you": you},
  564. )
  565. .unwrap();
  566. assert_eq!(ret.len(), 1);
  567. assert_eq!(ret[0], Value::Blob(gae.clone()));
  568. let ret = wallet
  569. .query_custom(
  570. "SELECT gae FROM mista WHERE why = ?1 AND are = ?2 AND you = ?3;",
  571. rusqlite::params![why, are, you],
  572. )
  573. .unwrap();
  574. assert_eq!(ret.len(), 1);
  575. assert_eq!(ret[0].len(), 1);
  576. assert_eq!(ret[0][0], Value::Blob(gae));
  577. }
  578. #[test]
  579. fn test_query_multi() {
  580. let wallet = WalletDb::new(None, None).unwrap();
  581. wallet
  582. .exec_batch_sql("CREATE TABLE mista ( why INTEGER, are TEXT, you INTEGER, gae BLOB );")
  583. .unwrap();
  584. let why = 42;
  585. let are = "are".to_string();
  586. let you = 69;
  587. let gae = vec![42u8; 32];
  588. wallet
  589. .exec_sql(
  590. "INSERT INTO mista ( why, are, you, gae ) VALUES (?1, ?2, ?3, ?4);",
  591. rusqlite::params![why, are, you, gae],
  592. )
  593. .unwrap();
  594. wallet
  595. .exec_sql(
  596. "INSERT INTO mista ( why, are, you, gae ) VALUES (?1, ?2, ?3, ?4);",
  597. rusqlite::params![why, are, you, gae],
  598. )
  599. .unwrap();
  600. let ret = wallet.query_multiple("mista", &[], &[]).unwrap();
  601. assert_eq!(ret.len(), 2);
  602. for row in ret {
  603. assert_eq!(row.len(), 4);
  604. assert_eq!(row[0], Value::Integer(why));
  605. assert_eq!(row[1], Value::Text(are.clone()));
  606. assert_eq!(row[2], Value::Integer(you));
  607. assert_eq!(row[3], Value::Blob(gae.clone()));
  608. }
  609. let ret = wallet.query_custom("SELECT * FROM mista;", &[]).unwrap();
  610. assert_eq!(ret.len(), 2);
  611. for row in ret {
  612. assert_eq!(row.len(), 4);
  613. assert_eq!(row[0], Value::Integer(why));
  614. assert_eq!(row[1], Value::Text(are.clone()));
  615. assert_eq!(row[2], Value::Integer(you));
  616. assert_eq!(row[3], Value::Blob(gae.clone()));
  617. }
  618. let ret = wallet
  619. .query_multiple(
  620. "mista",
  621. &["gae"],
  622. convert_named_params! {("why", why), ("are", are), ("you", you)},
  623. )
  624. .unwrap();
  625. assert_eq!(ret.len(), 2);
  626. for row in ret {
  627. assert_eq!(row.len(), 1);
  628. assert_eq!(row[0], Value::Blob(gae.clone()));
  629. }
  630. let ret = wallet
  631. .query_custom(
  632. "SELECT gae FROM mista WHERE why = ?1 AND are = ?2 AND you = ?3;",
  633. rusqlite::params![why, are, you],
  634. )
  635. .unwrap();
  636. assert_eq!(ret.len(), 2);
  637. for row in ret {
  638. assert_eq!(row.len(), 1);
  639. assert_eq!(row[0], Value::Blob(gae.clone()));
  640. }
  641. }
  642. #[test]
  643. fn test_sqlite_smt() {
  644. // Setup SQLite database
  645. let table = &"smt";
  646. let key_col = &"smt_key";
  647. let value_col = &"smt_value";
  648. let wallet = WalletDb::new(None, None).unwrap();
  649. wallet.exec_batch_sql(&format!("CREATE TABLE {table} ( {key_col} BLOB INTEGER PRIMARY KEY NOT NULL, {value_col} BLOB NOT NULL);")).unwrap();
  650. // Setup SMT
  651. const HEIGHT: usize = 3;
  652. let hasher = PoseidonFp::new();
  653. let empty_leaf = pallas::Base::ZERO;
  654. let empty_nodes = gen_empty_nodes::<{ HEIGHT + 1 }, _, _>(&hasher, empty_leaf);
  655. let store = WalletStorage::new(&wallet, table, key_col, value_col);
  656. let mut smt = SparseMerkleTree::<HEIGHT, { HEIGHT + 1 }, _, _, _>::new(
  657. store,
  658. hasher.clone(),
  659. &empty_nodes,
  660. );
  661. // Verify database is empty
  662. let rows = wallet.query_multiple(table, &[key_col], &[]).unwrap();
  663. assert!(rows.is_empty());
  664. let leaves = vec![
  665. (pallas::Base::from(1), pallas::Base::random(&mut OsRng)),
  666. (pallas::Base::from(2), pallas::Base::random(&mut OsRng)),
  667. (pallas::Base::from(3), pallas::Base::random(&mut OsRng)),
  668. ];
  669. smt.insert_batch(leaves.clone()).unwrap();
  670. let hash1 = leaves[0].1;
  671. let hash2 = leaves[1].1;
  672. let hash3 = leaves[2].1;
  673. let hash = |l, r| hasher.hash([l, r]);
  674. let hash01 = hash(empty_nodes[3], hash1);
  675. let hash23 = hash(hash2, hash3);
  676. let hash0123 = hash(hash01, hash23);
  677. let root = hash(hash0123, empty_nodes[1]);
  678. assert_eq!(root, smt.root());
  679. // Now try to construct a membership proof for leaf 3
  680. let pos = leaves[2].0;
  681. let path = smt.prove_membership(&pos);
  682. assert_eq!(path.path[0], empty_nodes[1]);
  683. assert_eq!(path.path[1], hash01);
  684. assert_eq!(path.path[2], hash2);
  685. assert_eq!(hash23, hash(path.path[2], hash3));
  686. assert_eq!(hash0123, hash(path.path[1], hash(path.path[2], hash3)));
  687. assert_eq!(root, hash(hash(path.path[1], hash(path.path[2], hash3)), path.path[0]));
  688. assert!(path.verify(&root, &hash3, &pos));
  689. // Verify database contains keys
  690. let rows = wallet.query_multiple(table, &[key_col], &[]).unwrap();
  691. assert!(!rows.is_empty());
  692. // We are now going to rollback the wallet changes
  693. let rollback_query = wallet.grab_inverse_cache_block().unwrap();
  694. wallet.exec_batch_sql(&rollback_query).unwrap();
  695. // Clear cache
  696. wallet.clear_inverse_cache().unwrap();
  697. // Verify database is empty again
  698. let rows = wallet.query_multiple(table, &[key_col], &[]).unwrap();
  699. assert!(rows.is_empty());
  700. }
  701. }