Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(asb): Check for updates in background #215

Merged
merged 1 commit into from
Nov 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@
"appimage",
"dmg",
"nsis",
"app",
"deb"
"app"
],
"icon": [
"icons/32x32.png",
Expand Down Expand Up @@ -58,4 +57,4 @@
]
}
}
}
}
22 changes: 10 additions & 12 deletions swap/src/bin/asb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,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::common::{self, get_logs, warn_if_outdated};
use swap::database::{open_db, AccessMode};
use swap::network::rendezvous::XmrBtcNamespace;
use swap::network::swarm;
Expand Down Expand Up @@ -63,12 +63,10 @@ pub async fn main() -> Result<()> {
}
};

// warn if we're not on the latest version
if let Err(e) = check_latest_version(env!("CARGO_PKG_VERSION")).await {
eprintln!("{}", e);
}
// Check in the background if there's a new version available
tokio::spawn(async move { warn_if_outdated(env!("CARGO_PKG_VERSION")).await });

// read config from the specified path
// Read config from the specified path
let config = match read_config(config_path.clone())? {
Ok(config) => config,
Err(ConfigNotInitialized {}) => {
Expand All @@ -77,13 +75,13 @@ pub async fn main() -> Result<()> {
}
};

// initialize tracing
// Initialize tracing
let format = if json { Format::Json } else { Format::Raw };
let log_dir = config.data.dir.join("logs");
common::tracing_util::init(LevelFilter::DEBUG, format, log_dir, None)
.expect("initialize tracing");

// check for conflicting env / config values
// Check for conflicting env / config values
if config.monero.network != env_config.monero_network {
bail!(format!(
"Expected monero network in config file to be {:?} but was {:?}",
Expand Down Expand Up @@ -118,12 +116,12 @@ pub async fn main() -> Result<()> {
);
}

// initialize monero wallet
// Initialize Monero wallet
let monero_wallet = init_monero_wallet(&config, env_config).await?;
let monero_address = monero_wallet.get_main_address();
tracing::info!(%monero_address, "Monero wallet address");

// check monero balance
// Check Monero balance
let monero = monero_wallet.get_balance().await?;
match (monero.balance, monero.unlocked_balance) {
(0, _) => {
Expand All @@ -146,14 +144,14 @@ pub async fn main() -> Result<()> {
}
}

// init bitcoin wallet
// Initialize Bitcoin wallet
let bitcoin_wallet = init_bitcoin_wallet(&config, &seed, env_config).await?;
let bitcoin_balance = bitcoin_wallet.balance().await?;
tracing::info!(%bitcoin_balance, "Bitcoin wallet balance");

let kraken_price_updates = kraken::connect(config.maker.price_ticker_ws_url.clone())?;

// setup Tor hidden services
// Setup Tor hidden services
let tor_client =
tor::Client::new(config.tor.socks5_port).with_control_port(config.tor.control_port);
let _ac = match tor_client.assert_tor_running().await {
Expand Down
5 changes: 0 additions & 5 deletions swap/src/bin/swap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,9 @@
use anyhow::Result;
use std::env;
use swap::cli::command::{parse_args_and_apply_defaults, ParseResult};
use swap::common::check_latest_version;

#[tokio::main]
pub async fn main() -> Result<()> {
if let Err(e) = check_latest_version(env!("CARGO_PKG_VERSION")).await {
eprintln!("{}", e);
}

match parse_args_and_apply_defaults(env::args_os()).await? {
ParseResult::Success(context) => {
context.tasks.wait_for_tasks().await?;
Expand Down
3 changes: 1 addition & 2 deletions swap/src/cli/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -642,10 +642,9 @@ pub mod api_test {
json: bool,
) -> Self {
let data_dir = data::data_dir_from(data_dir, is_testnet).unwrap();

let seed = Seed::from_file_or_generate(data_dir.as_path()).unwrap();

let env_config = env_config_from(is_testnet);

Self {
namespace: XmrBtcNamespace::from_is_testnet(is_testnet),
env_config,
Expand Down
62 changes: 15 additions & 47 deletions swap/src/common/mod.rs
Original file line number Diff line number Diff line change
@@ -1,45 +1,35 @@
pub mod tracing_util;

use std::{collections::HashMap, path::PathBuf};

use anyhow::anyhow;
use std::{collections::HashMap, path::PathBuf};
use tokio::{
fs::{read_dir, File},
io::{AsyncBufReadExt, BufReader},
};
use uuid::Uuid;

const LATEST_RELEASE_URL: &str = "https://github.com/comit-network/xmr-btc-swap/releases/latest";

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Version {
Current,
Available,
}
const LATEST_RELEASE_URL: &str = "https://github.com/UnstoppableSwap/core/releases/latest";

/// Check the latest release from GitHub API.
pub async fn check_latest_version(current_version: &str) -> anyhow::Result<Version> {
/// Check the latest release from GitHub and warn if we are not on the latest version.
pub async fn warn_if_outdated(current_version: &str) -> anyhow::Result<()> {
// Visit the Github releases page and check which url we are redirected to
let response = reqwest::get(LATEST_RELEASE_URL).await?;
let e = "Failed to get latest release.";
let download_url = response.url();
let segments = download_url.path_segments().ok_or_else(|| anyhow!(e))?;
let latest_version = segments.last().ok_or_else(|| anyhow!(e))?;

let result = if is_latest_version(current_version, latest_version) {
Version::Current
} else {
let segments = download_url
.path_segments()
.ok_or_else(|| anyhow!("Cannot split Github release URL into segments"))?;
let latest_version = segments
.last()
.ok_or_else(|| anyhow!("Cannot extract latest version from Github release URL"))?;

if current_version != latest_version {
tracing::warn!(%current_version, %latest_version, %download_url,
"You are not on the latest version",
);
Version::Available
};

Ok(result)
}
}

// todo: naive implementation can be improved using semver
fn is_latest_version(current: &str, latest: &str) -> bool {
current == latest
Ok(())
}

/// helper macro for [`redact`]... eldrich sorcery
Expand Down Expand Up @@ -196,25 +186,3 @@ pub fn redact_with(input: &str, replacements: &mut HashMap<String, String>) -> S

redacted
}

#[cfg(test)]
mod test {
use super::*;

#[test]
fn it_compares_versions() {
assert!(is_latest_version("0.10.2", "0.10.2"));
assert!(!is_latest_version("0.10.2", "0.10.3"));
assert!(!is_latest_version("0.10.2", "0.11.0"));
}

#[tokio::test]
#[ignore = "For local testing, makes http requests to github."]
async fn it_compares_with_github() {
let result = check_latest_version("0.11.0").await.unwrap();
assert_eq!(result, Version::Available);

let result = check_latest_version("0.11.1").await.unwrap();
assert_eq!(result, Version::Current);
}
}
Loading