lib.rs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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 rusqlite::types::Value;
  20. use url::Url;
  21. use darkfi::{rpc::client::RpcClient, util::path::expand_path, Error, Result};
  22. /// Error codes
  23. pub mod error;
  24. use error::{WalletDbError, WalletDbResult};
  25. /// darkfid JSON-RPC related methods
  26. pub mod rpc;
  27. /// Payment methods
  28. pub mod transfer;
  29. /// Swap methods
  30. pub mod swap;
  31. /// Token methods
  32. pub mod token;
  33. /// CLI utility functions
  34. pub mod cli_util;
  35. /// Wallet functionality related to Money
  36. pub mod money;
  37. /// Wallet functionality related to Dao
  38. pub mod dao;
  39. /// Wallet functionality related to Deployooor
  40. pub mod deploy;
  41. /// Wallet functionality related to transactions history
  42. pub mod txs_history;
  43. /// Wallet database operations handler
  44. pub mod walletdb;
  45. use walletdb::{WalletDb, WalletPtr};
  46. // Wallet SQL table constant names. These have to represent the `wallet.sql`
  47. // SQL schema.
  48. const WALLET_INFO_TABLE: &str = "wallet_info";
  49. const WALLET_INFO_COL_LAST_SCANNED_BLOCK_HEIGHT: &str = "last_scanned_block_height";
  50. const WALLET_INFO_COL_LAST_SCANNED_BLOCK_HASH: &str = "last_scanned_block_hash";
  51. /// CLI-util structure
  52. pub struct Drk {
  53. /// Wallet database operations handler
  54. pub wallet: WalletPtr,
  55. /// JSON-RPC client to execute requests to darkfid daemon
  56. pub rpc_client: Option<RpcClient>,
  57. /// Flag indicating if fun stuff are enabled
  58. pub fun: bool,
  59. }
  60. impl Drk {
  61. pub async fn new(
  62. wallet_path: String,
  63. wallet_pass: String,
  64. endpoint: Option<Url>,
  65. ex: Arc<smol::Executor<'static>>,
  66. fun: bool,
  67. ) -> Result<Self> {
  68. // Initialize wallet
  69. let wallet_path = expand_path(&wallet_path)?;
  70. if !wallet_path.exists() {
  71. if let Some(parent) = wallet_path.parent() {
  72. fs::create_dir_all(parent)?;
  73. }
  74. }
  75. let Ok(wallet) = WalletDb::new(Some(wallet_path), Some(&wallet_pass)) else {
  76. return Err(Error::DatabaseError(format!("{}", WalletDbError::InitializationFailed)));
  77. };
  78. // Initialize rpc client
  79. let rpc_client = if let Some(endpoint) = endpoint {
  80. Some(RpcClient::new(endpoint, ex).await?)
  81. } else {
  82. None
  83. };
  84. Ok(Self { wallet, rpc_client, fun })
  85. }
  86. /// Initialize wallet with tables for `Drk`.
  87. pub async fn initialize_wallet(&self) -> WalletDbResult<()> {
  88. // Initialize wallet schema
  89. self.wallet.exec_batch_sql(include_str!("../wallet.sql"))?;
  90. // We maintain the last scanned block as part of the wallet
  91. // info table.
  92. if self.last_scanned_block().await.is_err() {
  93. let query = format!(
  94. "INSERT INTO {} ({}, {}) VALUES (?1, ?2);",
  95. WALLET_INFO_TABLE,
  96. WALLET_INFO_COL_LAST_SCANNED_BLOCK_HEIGHT,
  97. WALLET_INFO_COL_LAST_SCANNED_BLOCK_HASH
  98. );
  99. self.wallet.exec_sql(&query, rusqlite::params![0, "-"])?;
  100. }
  101. Ok(())
  102. }
  103. /// Update the last scanned block height and hash in the wallet.
  104. pub fn update_last_scanned_block(&self, height: u32, hash: &str) -> WalletDbResult<()> {
  105. let query = format!(
  106. "UPDATE {} SET {} = ?1, {} = ?2;",
  107. WALLET_INFO_TABLE,
  108. WALLET_INFO_COL_LAST_SCANNED_BLOCK_HEIGHT,
  109. WALLET_INFO_COL_LAST_SCANNED_BLOCK_HASH
  110. );
  111. self.wallet.exec_sql(&query, rusqlite::params![height, hash])
  112. }
  113. /// Get the last scanned block height and hash from the wallet.
  114. pub async fn last_scanned_block(&self) -> WalletDbResult<(u32, String)> {
  115. let ret = self.wallet.query_single(WALLET_INFO_TABLE, &[], &[])?;
  116. let Value::Integer(height) = ret[0] else {
  117. return Err(WalletDbError::ParseColumnValueError);
  118. };
  119. let Ok(height) = u32::try_from(height) else {
  120. return Err(WalletDbError::ParseColumnValueError);
  121. };
  122. let Value::Text(ref hash) = ret[1] else {
  123. return Err(WalletDbError::ParseColumnValueError);
  124. };
  125. Ok((height, hash.clone()))
  126. }
  127. }