From 5bb33fe35d7955f2583b4d0eb9b5883b142d7aec Mon Sep 17 00:00:00 2001 From: binarybaron <86064887+binarybaron@users.noreply.github.com> Date: Tue, 17 Sep 2024 17:32:21 +0200 Subject: [PATCH] fix(asb): Allow history command to be run while asb is running (#82) This applies the following PRs from upstream to our fork: * fix(asb): Allow history command to be run while asb is running (#1724) * Allow history command to be executed while asb is running by opening database in read-only mode (#1722) --------- Co-authored-by: einliterflasche Co-authored-by: Einliterflasche <81313171+Einliterflasche@users.noreply.github.com> --- CHANGELOG.md | 1 + swap/src/bin/asb.rs | 18 +++++++++++++++--- swap/src/cli/api.rs | 8 +++----- swap/src/database.rs | 15 ++++++++++++--- swap/src/database/sqlite.rs | 19 ++++++++++++------- swap/tests/harness/mod.rs | 12 ++++++++---- 6 files changed, 51 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bd4cec221..f2fc78333 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - ASB + CLI: You can now use the `logs` command to retrieve logs stored in the past, redacting addresses and id's using `logs --redact`. - ASB: The `--disable-timestamp` flag has been removed +- ASB: The `history` command can now be used while the asb is running. - Introduced a cooperative Monero redeem feature for Bob to request from Alice if Bob is punished for not refunding in time. Alice can choose to cooperate but is not obligated to do so. This change is backwards compatible. To attempt recovery, resume a swap in the "Bitcoin punished" state. Success depends on Alice being active and still having a record of the swap. Note that Alice's cooperation is voluntary and recovery is not guaranteed - CLI: `--change-address` can now be omitted. In that case, any change is refunded to the internal bitcoin wallet. diff --git a/swap/src/bin/asb.rs b/swap/src/bin/asb.rs index 3216adeeb..84fefc661 100644 --- a/swap/src/bin/asb.rs +++ b/swap/src/bin/asb.rs @@ -31,7 +31,7 @@ use swap::asb::config::{ use swap::asb::{cancel, punish, redeem, refund, safely_abort, EventLoop, Finality, KrakenRate}; use swap::common::tracing_util::Format; use swap::common::{self, check_latest_version, get_logs}; -use swap::database::open_db; +use swap::database::{open_db, AccessMode}; use swap::network::rendezvous::XmrBtcNamespace; use swap::network::swarm; use swap::protocol::alice::{run, AliceState}; @@ -97,13 +97,13 @@ pub async fn main() -> Result<()> { )); } - let db = open_db(config.data.dir.join("sqlite")).await?; - let seed = Seed::from_file_or_generate(&config.data.dir).expect("Could not retrieve/initialize seed"); match cmd { Command::Start { resume_only } => { + let db = open_db(config.data.dir.join("sqlite"), AccessMode::ReadWrite).await?; + // check and warn for duplicate rendezvous points let mut rendezvous_addrs = config.network.rendezvous_point.clone(); let prev_len = rendezvous_addrs.len(); @@ -232,6 +232,8 @@ pub async fn main() -> Result<()> { event_loop.run().await; } Command::History => { + let db = open_db(config.data.dir.join("sqlite"), AccessMode::ReadOnly).await?; + let mut table = Table::new(); table.set_header(vec!["SWAP ID", "STATE"]); @@ -290,6 +292,8 @@ pub async fn main() -> Result<()> { tracing::info!(%bitcoin_balance, %monero_balance, "Current balance"); } Command::Cancel { swap_id } => { + let db = open_db(config.data.dir.join("sqlite"), AccessMode::ReadWrite).await?; + let bitcoin_wallet = init_bitcoin_wallet(&config, &seed, env_config).await?; let (txid, _) = cancel(swap_id, Arc::new(bitcoin_wallet), db).await?; @@ -297,6 +301,8 @@ pub async fn main() -> Result<()> { tracing::info!("Cancel transaction successfully published with id {}", txid); } Command::Refund { swap_id } => { + let db = open_db(config.data.dir.join("sqlite"), AccessMode::ReadWrite).await?; + let bitcoin_wallet = init_bitcoin_wallet(&config, &seed, env_config).await?; let monero_wallet = init_monero_wallet(&config, env_config).await?; @@ -311,6 +317,8 @@ pub async fn main() -> Result<()> { tracing::info!("Monero successfully refunded"); } Command::Punish { swap_id } => { + let db = open_db(config.data.dir.join("sqlite"), AccessMode::ReadWrite).await?; + let bitcoin_wallet = init_bitcoin_wallet(&config, &seed, env_config).await?; let (txid, _) = punish(swap_id, Arc::new(bitcoin_wallet), db).await?; @@ -318,6 +326,8 @@ pub async fn main() -> Result<()> { tracing::info!("Punish transaction successfully published with id {}", txid); } Command::SafelyAbort { swap_id } => { + let db = open_db(config.data.dir.join("sqlite"), AccessMode::ReadWrite).await?; + safely_abort(swap_id, db).await?; tracing::info!("Swap safely aborted"); @@ -326,6 +336,8 @@ pub async fn main() -> Result<()> { swap_id, do_not_await_finality, } => { + let db = open_db(config.data.dir.join("sqlite"), AccessMode::ReadWrite).await?; + let bitcoin_wallet = init_bitcoin_wallet(&config, &seed, env_config).await?; let (txid, _) = redeem( diff --git a/swap/src/cli/api.rs b/swap/src/cli/api.rs index 3a2da19b5..e32764ebc 100644 --- a/swap/src/cli/api.rs +++ b/swap/src/cli/api.rs @@ -3,7 +3,7 @@ pub mod tauri_bindings; use crate::cli::command::{Bitcoin, Monero, Tor}; use crate::common::tracing_util::Format; -use crate::database::open_db; +use crate::database::{open_db, AccessMode}; use crate::env::{Config as EnvConfig, GetConfig, Mainnet, Testnet}; use crate::fs::system_data_dir; use crate::network::rendezvous::XmrBtcNamespace; @@ -345,12 +345,10 @@ impl ContextBuilder { TauriContextInitializationProgress::OpeningDatabase, )); - let db = open_db(data_dir.join("sqlite")).await?; - let tor_socks5_port = self.tor.map_or(9050, |tor| tor.tor_socks5_port); let context = Context { - db, + db: open_db(data_dir.join("sqlite"), AccessMode::ReadWrite).await?, bitcoin_wallet, monero_wallet, monero_rpc_process, @@ -393,7 +391,7 @@ impl Context { bitcoin_wallet: Some(bob_bitcoin_wallet), monero_wallet: Some(bob_monero_wallet), config, - db: open_db(db_path) + db: open_db(db_path, AccessMode::ReadWrite) .await .expect("Could not open sqlite database"), monero_rpc_process: None, diff --git a/swap/src/database.rs b/swap/src/database.rs index 7af161961..7c6185f7f 100644 --- a/swap/src/database.rs +++ b/swap/src/database.rs @@ -83,16 +83,25 @@ impl Swap { } } -pub async fn open_db(sqlite_path: impl AsRef) -> Result> { +#[derive(Debug, Clone, Copy, Serialize, Deserialize, Hash, PartialEq)] +pub enum AccessMode { + ReadWrite, + ReadOnly, +} + +pub async fn open_db( + sqlite_path: impl AsRef, + access_mode: AccessMode, +) -> Result> { if sqlite_path.as_ref().exists() { tracing::debug!("Using existing sqlite database."); - let sqlite = SqliteDatabase::open(sqlite_path).await?; + let sqlite = SqliteDatabase::open(sqlite_path, access_mode).await?; Ok(Arc::new(sqlite)) } else { tracing::debug!("Creating and using new sqlite database."); ensure_directory_exists(sqlite_path.as_ref())?; tokio::fs::File::create(&sqlite_path).await?; - let sqlite = SqliteDatabase::open(sqlite_path).await?; + let sqlite = SqliteDatabase::open(sqlite_path, access_mode).await?; Ok(Arc::new(sqlite)) } } diff --git a/swap/src/database/sqlite.rs b/swap/src/database/sqlite.rs index 1fb6ed1ab..5800bd837 100644 --- a/swap/src/database/sqlite.rs +++ b/swap/src/database/sqlite.rs @@ -11,25 +11,30 @@ use std::str::FromStr; use time::OffsetDateTime; use uuid::Uuid; +use super::AccessMode; + pub struct SqliteDatabase { pool: Pool, } impl SqliteDatabase { - pub async fn open(path: impl AsRef) -> Result + pub async fn open(path: impl AsRef, access_mode: AccessMode) -> Result where Self: std::marker::Sized, { - let path_str = format!("sqlite:{}", path.as_ref().display()); + let read_only = matches!(access_mode, AccessMode::ReadOnly); - let mut options = SqliteConnectOptions::from_str(&path_str)?; + let path_str = format!("sqlite:{}", path.as_ref().display()); - options.disable_statement_logging(); + let mut options = SqliteConnectOptions::from_str(&path_str)?.read_only(read_only); + let options = options.disable_statement_logging(); - let pool = SqlitePool::connect_with(options).await?; + let pool = SqlitePool::connect_with(options.to_owned()).await?; let mut sqlite = Self { pool }; - sqlite.run_migrations().await?; + if !read_only { + sqlite.run_migrations().await?; + } Ok(sqlite) } @@ -480,7 +485,7 @@ mod tests { // file has to exist in order to connect with sqlite File::create(temp_db.clone()).unwrap(); - let db = SqliteDatabase::open(temp_db).await?; + let db = SqliteDatabase::open(temp_db, AccessMode::ReadWrite).await?; Ok(db) } diff --git a/swap/tests/harness/mod.rs b/swap/tests/harness/mod.rs index 75991b36b..ef0803587 100644 --- a/swap/tests/harness/mod.rs +++ b/swap/tests/harness/mod.rs @@ -17,7 +17,7 @@ use std::time::Duration; use swap::asb::FixedRate; use swap::bitcoin::{CancelTimelock, PunishTimelock, TxCancel, TxPunish, TxRedeem, TxRefund}; use swap::cli::api; -use swap::database::SqliteDatabase; +use swap::database::{AccessMode, SqliteDatabase}; use swap::env::{Config, GetConfig}; use swap::fs::ensure_directory_exists; use swap::network::rendezvous::XmrBtcNamespace; @@ -232,7 +232,11 @@ async fn start_alice( if !&db_path.exists() { tokio::fs::File::create(&db_path).await.unwrap(); } - let db = Arc::new(SqliteDatabase::open(db_path.as_path()).await.unwrap()); + let db = Arc::new( + SqliteDatabase::open(db_path.as_path(), AccessMode::ReadWrite) + .await + .unwrap(), + ); let min_buy = bitcoin::Amount::from_sat(u64::MIN); let max_buy = bitcoin::Amount::from_sat(u64::MAX); @@ -434,7 +438,7 @@ impl BobParams { if !self.db_path.exists() { tokio::fs::File::create(&self.db_path).await?; } - let db = Arc::new(SqliteDatabase::open(&self.db_path).await?); + let db = Arc::new(SqliteDatabase::open(&self.db_path, AccessMode::ReadWrite).await?); let (event_loop, handle) = self.new_eventloop(swap_id, db.clone()).await?; @@ -464,7 +468,7 @@ impl BobParams { if !self.db_path.exists() { tokio::fs::File::create(&self.db_path).await?; } - let db = Arc::new(SqliteDatabase::open(&self.db_path).await?); + let db = Arc::new(SqliteDatabase::open(&self.db_path, AccessMode::ReadWrite).await?); let (event_loop, handle) = self.new_eventloop(swap_id, db.clone()).await?;