lib.rs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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::{fs, sync::Arc};
  19. use url::Url;
  20. use darkfi::{rpc::client::RpcClient, util::path::expand_path, Error, Result};
  21. /// Error codes
  22. pub mod error;
  23. use error::{WalletDbError, WalletDbResult};
  24. /// darkfid JSON-RPC related methods
  25. pub mod rpc;
  26. /// Payment methods
  27. pub mod transfer;
  28. /// Swap methods
  29. pub mod swap;
  30. /// Token methods
  31. pub mod token;
  32. /// CLI utility functions
  33. pub mod cli_util;
  34. /// Wallet functionality related to Money
  35. pub mod money;
  36. /// Wallet functionality related to Dao
  37. pub mod dao;
  38. /// Wallet functionality related to Deployooor
  39. pub mod deploy;
  40. /// Wallet functionality related to transactions history
  41. pub mod txs_history;
  42. /// Wallet functionality related to scanned blocks
  43. pub mod scanned_blocks;
  44. /// Wallet database operations handler
  45. pub mod walletdb;
  46. use walletdb::{WalletDb, WalletPtr};
  47. /// CLI-util structure
  48. pub struct Drk {
  49. /// Wallet database operations handler
  50. pub wallet: WalletPtr,
  51. /// JSON-RPC client to execute requests to darkfid daemon
  52. pub rpc_client: Option<RpcClient>,
  53. /// Flag indicating if fun stuff are enabled
  54. pub fun: bool,
  55. }
  56. impl Drk {
  57. pub async fn new(
  58. wallet_path: String,
  59. wallet_pass: String,
  60. endpoint: Option<Url>,
  61. ex: Arc<smol::Executor<'static>>,
  62. fun: bool,
  63. ) -> Result<Self> {
  64. // Initialize wallet
  65. let wallet_path = expand_path(&wallet_path)?;
  66. if !wallet_path.exists() {
  67. if let Some(parent) = wallet_path.parent() {
  68. fs::create_dir_all(parent)?;
  69. }
  70. }
  71. let Ok(wallet) = WalletDb::new(Some(wallet_path), Some(&wallet_pass)) else {
  72. return Err(Error::DatabaseError(format!("{}", WalletDbError::InitializationFailed)));
  73. };
  74. // Initialize rpc client
  75. let rpc_client = if let Some(endpoint) = endpoint {
  76. Some(RpcClient::new(endpoint, ex).await?)
  77. } else {
  78. None
  79. };
  80. Ok(Self { wallet, rpc_client, fun })
  81. }
  82. /// Initialize wallet with tables for `Drk`.
  83. pub async fn initialize_wallet(&self) -> WalletDbResult<()> {
  84. // Initialize wallet schema
  85. self.wallet.exec_batch_sql(include_str!("../wallet.sql"))?;
  86. Ok(())
  87. }
  88. /// Auxiliary function to completely reset wallet state.
  89. pub async fn reset(&self) -> WalletDbResult<()> {
  90. println!("Resetting full wallet state");
  91. self.reset_scanned_blocks()?;
  92. self.reset_money_tree().await?;
  93. self.reset_money_smt()?;
  94. self.reset_money_coins()?;
  95. self.reset_mint_authorities()?;
  96. self.reset_dao_trees().await?;
  97. self.reset_daos().await?;
  98. self.reset_dao_proposals().await?;
  99. self.reset_dao_votes()?;
  100. self.reset_tx_history()?;
  101. println!("Successfully reset full wallet state");
  102. Ok(())
  103. }
  104. /// Auxiliary function to reset `walletdb` inverse cache state.
  105. /// Additionally, set current trees state inverse queries.
  106. /// We keep the entire trees state as two distinct inverse queries,
  107. /// since we execute per transaction call, so we don't have to update
  108. /// them on each iteration.
  109. pub async fn reset_inverse_cache(&self) -> Result<()> {
  110. // Reset `walletdb` inverse cache
  111. if let Err(e) = self.wallet.clear_inverse_cache() {
  112. return Err(Error::DatabaseError(format!(
  113. "[reset_inverse_cache] Clearing wallet inverse cache failed: {e:?}"
  114. )))
  115. }
  116. // Grab current money tree state query and insert it into inverse cache
  117. let query = self.get_money_tree_state_query().await?;
  118. if let Err(e) = self.wallet.cache_inverse(query) {
  119. return Err(Error::DatabaseError(format!(
  120. "[reset_inverse_cache] Inserting money query into inverse cache failed: {e:?}"
  121. )))
  122. }
  123. // Grab current DAO trees state query and insert it into inverse cache
  124. let query = self.get_dao_trees_state_query().await?;
  125. if let Err(e) = self.wallet.cache_inverse(query) {
  126. return Err(Error::DatabaseError(format!(
  127. "[reset_inverse_cache] Inserting DAO query into inverse cache failed: {e:?}"
  128. )))
  129. }
  130. Ok(())
  131. }
  132. /// Auxiliary function to store current `walletdb` inverse cache
  133. /// in scanned blocks information for provided block height and hash.
  134. /// Additionally, clear `walletdb` inverse cache state.
  135. pub fn store_inverse_cache(&self, height: u32, hash: &str) -> Result<()> {
  136. // Grab current inverse state rollback query
  137. let rollback_query = match self.wallet.grab_inverse_cache_block() {
  138. Ok(q) => q,
  139. Err(e) => {
  140. return Err(Error::DatabaseError(format!(
  141. "[store_inverse_cache] Creating rollback query failed: {e:?}"
  142. )))
  143. }
  144. };
  145. // Store it as a scanned blocks information record
  146. if let Err(e) = self.put_scanned_block_record(height, hash, &rollback_query) {
  147. return Err(Error::DatabaseError(format!(
  148. "[store_inverse_cache] Inserting scanned blocks information record failed: {e:?}"
  149. )))
  150. };
  151. // Reset `walletdb` inverse cache
  152. if let Err(e) = self.wallet.clear_inverse_cache() {
  153. return Err(Error::DatabaseError(format!(
  154. "[store_inverse_cache] Clearing wallet inverse cache failed: {e:?}"
  155. )))
  156. };
  157. Ok(())
  158. }
  159. }