Skip to content

Commit

Permalink
Merge pull request #8 from comit-network/master
Browse files Browse the repository at this point in the history
Merge parent repository
  • Loading branch information
binarybaron authored Jul 25, 2024
2 parents cf87f19 + ce8d3af commit aaa52e9
Show file tree
Hide file tree
Showing 10 changed files with 111 additions and 51 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

- ASB: The `history` command can now be used while the asb is running.

## [0.13.3] - 2024-07-22

- 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
Expand Down
8 changes: 4 additions & 4 deletions swap/src/api.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pub mod request;
use crate::cli::command::{Bitcoin, Monero, Tor};
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;
Expand Down Expand Up @@ -224,7 +224,7 @@ impl Context {
let tor_socks5_port = tor.map_or(9050, |tor| tor.tor_socks5_port);

let context = Context {
db: open_db(data_dir.join("sqlite")).await?,
db: open_db(data_dir.join("sqlite"), AccessMode::ReadWrite).await?,
bitcoin_wallet,
monero_wallet,
monero_rpc_process,
Expand Down Expand Up @@ -259,7 +259,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,
Expand Down Expand Up @@ -437,7 +437,7 @@ pub mod api_test {

Request::new(Method::BuyXmr {
seller,
bitcoin_change_address,
bitcoin_change_address: Some(bitcoin_change_address),
monero_receive_address,
swap_id: Uuid::new_v4(),
})
Expand Down
21 changes: 20 additions & 1 deletion swap/src/api/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ pub struct Request {
pub enum Method {
BuyXmr {
seller: Multiaddr,
bitcoin_change_address: bitcoin::Address,
bitcoin_change_address: Option<bitcoin::Address>,
monero_receive_address: monero::Address,
swap_id: Uuid,
},
Expand Down Expand Up @@ -335,6 +335,25 @@ impl Request {
let env_config = context.config.env_config;
let seed = context.config.seed.clone().context("Could not get seed")?;

// When no change address was provided we default to the internal wallet
let bitcoin_change_address = match bitcoin_change_address {
Some(addr) => addr,
None => {
let internal_wallet_address = context
.bitcoin_wallet()
.expect("bitcoin wallet should exist")
.new_address()
.await?;

tracing::info!(
internal_wallet_address=%internal_wallet_address,
"No --change-address supplied. Any change will be received to the internal wallet."
);

internal_wallet_address
}
};

let seller_peer_id = seller
.extract_peer_id()
.context("Seller address must contain peer ID")?;
Expand Down
18 changes: 15 additions & 3 deletions swap/src/bin/asb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use swap::asb::config::{
};
use swap::asb::{cancel, punish, redeem, refund, safely_abort, EventLoop, Finality, KrakenRate};
use swap::common::check_latest_version;
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};
Expand Down Expand Up @@ -95,13 +95,13 @@ 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();
Expand Down Expand Up @@ -225,6 +225,8 @@ 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"]);
Expand Down Expand Up @@ -270,13 +272,17 @@ 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?;

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?;

Expand All @@ -291,13 +297,17 @@ 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?;

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");
Expand All @@ -306,6 +316,8 @@ 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(
Expand Down
24 changes: 3 additions & 21 deletions swap/src/cli/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,29 +81,11 @@ where
)
.await?;

// when no refund address was provided we default to the internal wallet
let bitcoin_change_address = match bitcoin_change_address {
Some(addr) => addr,
None => {
let internal_wallet_address = context
.bitcoin_wallet()
.expect("bitcoin wallet should exist")
.new_address()
.await?;

tracing::info!(
internal_wallet_address=%internal_wallet_address,
"No --change-address supplied. Any change will be received to the internal wallet."
);

internal_wallet_address
}
};

let monero_receive_address =
monero_address::validate_is_testnet(monero_receive_address, is_testnet)?;
let bitcoin_change_address =
bitcoin_address::validate_is_testnet(bitcoin_change_address, is_testnet)?;
let bitcoin_change_address = bitcoin_change_address
.map(|address| bitcoin_address::validate_is_testnet(address, is_testnet))
.transpose()?;

let request = Request::new(Method::BuyXmr {
seller,
Expand Down
15 changes: 12 additions & 3 deletions swap/src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,16 +83,25 @@ impl Swap {
}
}

pub async fn open_db(sqlite_path: impl AsRef<Path>) -> Result<Arc<dyn Database + Send + Sync>> {
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Hash, PartialEq)]
pub enum AccessMode {
ReadWrite,
ReadOnly,
}

pub async fn open_db(
sqlite_path: impl AsRef<Path>,
access_mode: AccessMode,
) -> Result<Arc<dyn Database + Send + Sync>> {
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))
}
}
20 changes: 15 additions & 5 deletions swap/src/database/sqlite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,37 @@ use crate::protocol::{Database, State};
use anyhow::{anyhow, Context, Result};
use async_trait::async_trait;
use libp2p::{Multiaddr, PeerId};
use sqlx::sqlite::Sqlite;
use sqlx::sqlite::{Sqlite, SqliteConnectOptions};
use sqlx::{Pool, SqlitePool};
use std::collections::HashMap;
use std::path::Path;
use std::str::FromStr;
use time::OffsetDateTime;
use uuid::Uuid;

use super::AccessMode;

pub struct SqliteDatabase {
pool: Pool<Sqlite>,
}

impl SqliteDatabase {
pub async fn open(path: impl AsRef<Path>) -> Result<Self>
pub async fn open(path: impl AsRef<Path>, access_mode: AccessMode) -> Result<Self>
where
Self: std::marker::Sized,
{
let read_only = matches!(access_mode, AccessMode::ReadOnly);

let path_str = format!("sqlite:{}", path.as_ref().display());
let pool = SqlitePool::connect(&path_str).await?;
let options = SqliteConnectOptions::from_str(&path_str)?.read_only(read_only);

let pool = SqlitePool::connect_with(options).await?;
let mut sqlite = Self { pool };
sqlite.run_migrations().await?;

if !read_only {
sqlite.run_migrations().await?;
}

Ok(sqlite)
}

Expand Down Expand Up @@ -504,7 +514,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)
}
Expand Down
29 changes: 19 additions & 10 deletions swap/src/rpc/methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,16 +135,25 @@ pub fn register_modules(context: Arc<Context>) -> Result<RpcModule<Arc<Context>>
module.register_async_method("buy_xmr", |params_raw, context| async move {
let params: HashMap<String, String> = params_raw.parse()?;

let bitcoin_change_address =
bitcoin::Address::from_str(params.get("bitcoin_change_address").ok_or_else(|| {
jsonrpsee_core::Error::Custom("Does not contain bitcoin_change_address".to_string())
})?)
.map_err(|err| jsonrpsee_core::Error::Custom(err.to_string()))?;

let bitcoin_change_address = bitcoin_address::validate(
bitcoin_change_address,
context.config.env_config.bitcoin_network,
)?;
let bitcoin_change_address = params
.get("bitcoin_change_address")
.map(|addr_str| {
bitcoin::Address::from_str(addr_str)
.map_err(|err| {
jsonrpsee_core::Error::Custom(format!(
"Could not parse bitcoin address: {}",
err
))
})
.and_then(|address| {
bitcoin_address::validate(
address,
context.config.env_config.bitcoin_network,
)
.map_err(|err| jsonrpsee_core::Error::Custom(err.to_string()))
})
})
.transpose()?;

let monero_receive_address =
monero::Address::from_str(params.get("monero_receive_address").ok_or_else(|| {
Expand Down
12 changes: 8 additions & 4 deletions swap/tests/harness/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use std::sync::Arc;
use std::time::Duration;
use swap::asb::FixedRate;
use swap::bitcoin::{CancelTimelock, PunishTimelock, TxCancel, TxPunish, TxRedeem, TxRefund};
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;
Expand Down Expand Up @@ -231,7 +231,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);
Expand Down Expand Up @@ -433,7 +437,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?;

Expand Down Expand Up @@ -463,7 +467,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?;

Expand Down
13 changes: 13 additions & 0 deletions utils/gpg_keys/binarybaron.asc
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
-----BEGIN PGP PUBLIC KEY BLOCK-----

mDMEZp+avRYJKwYBBAHaRw8BAQdAD99LhR+cHlXDsYPjRJr0Ag7BXsjGZKfdWCtx
CPA0fwG0LWJpbmFyeWJhcm9uIDxiaW5hcnliYXJvbkB1bnN0b3BwYWJsZXN3YXAu
bmV0PoiTBBMWCgA7FiEENahE1/S1W8ROGA/xmbddPhR2om4FAmafmr0CGwMFCwkI
BwICIgIGFQoJCAsCBBYCAwECHgcCF4AACgkQmbddPhR2om5IQQD/d/EmD/yKMKRl
Hw9RSP4bhcALmrZPri8sYkPteus8OhIA+wWTaIxXZJgydpXv95yECTfUXZ0UhuJq
6UH0FQL8mosJuDgEZp+avRIKKwYBBAGXVQEFAQEHQOd1tQ46YVKxyUKluPAvGJLY
LQ+3UWFWQJavLblkrYE2AwEIB4h4BBgWCgAgFiEENahE1/S1W8ROGA/xmbddPhR2
om4FAmafmr0CGwwACgkQmbddPhR2om6mmQEAn7vufrOp/HSYgn9l5tmJxMkyxJ3W
2WNo9u+JdnSik1IBAMsNcc4zm5ewfFr/qAnTHzHRId7dWR2+hs1oH7JOlf8L
=Rxij
-----END PGP PUBLIC KEY BLOCK-----

0 comments on commit aaa52e9

Please sign in to comment.