From 43de74145df1c26edc808d3f6509fcef267fd91c Mon Sep 17 00:00:00 2001 From: f321x Date: Tue, 9 Jul 2024 16:54:47 +0000 Subject: [PATCH] working on fixing bond validation --- .../coordinator/src/communication/mod.rs | 7 ++++--- .../coordinator/src/coordinator/monitoring.rs | 7 +++++-- taptrade-cli-demo/coordinator/src/wallet/mod.rs | 7 ++++++- taptrade-cli-demo/trader/src/wallet/bond.rs | 13 ++++++++----- 4 files changed, 23 insertions(+), 11 deletions(-) diff --git a/taptrade-cli-demo/coordinator/src/communication/mod.rs b/taptrade-cli-demo/coordinator/src/communication/mod.rs index 74c2f11..5917aef 100755 --- a/taptrade-cli-demo/coordinator/src/communication/mod.rs +++ b/taptrade-cli-demo/coordinator/src/communication/mod.rs @@ -25,10 +25,11 @@ async fn receive_order( Extension(database): Extension>, Extension(wallet): Extension>, Json(order): Json, -) -> Result, AppError> { +) -> Result { debug!("{:#?}", &order); if order.sanity_check().is_err() { - return Err(AppError(anyhow!("Invalid order request"))); + warn!("Received order failed sanity check"); + return Ok(StatusCode::NOT_ACCEPTABLE.into_response()); } let bond_requirements = BondRequirementResponse { bond_address: wallet.get_new_address().await?, @@ -39,7 +40,7 @@ async fn receive_order( .insert_new_maker_request(&order, &bond_requirements) .await?; debug!("Coordinator received new offer: {:?}", order); - Ok(Json(bond_requirements)) + Ok(Json(bond_requirements).into_response()) } /// receives the maker bond, verifies it and moves to offer to the active table (orderbook) diff --git a/taptrade-cli-demo/coordinator/src/coordinator/monitoring.rs b/taptrade-cli-demo/coordinator/src/coordinator/monitoring.rs index 835e44d..67b8bb3 100644 --- a/taptrade-cli-demo/coordinator/src/coordinator/monitoring.rs +++ b/taptrade-cli-demo/coordinator/src/coordinator/monitoring.rs @@ -4,11 +4,13 @@ // Also needs to implement punishment logic in case a fraud is detected. use super::*; +#[derive(Debug)] pub enum Table { Orderbook, ActiveTrades, } +#[derive(Debug)] pub struct MonitoringBond { pub bond_tx_hex: String, pub trade_id_hex: String, @@ -42,13 +44,14 @@ pub async fn monitor_bonds(coordinator: Arc) -> Result<()> { loop { // fetch all bonds let bonds = coordinator_db.fetch_all_bonds().await?; - + debug!("Monitoring active bonds: {}", bonds.len()); // verify all bonds and initiate punishment if necessary for bond in bonds { if let Err(e) = coordinator_wallet .validate_bond_tx_hex(&bond.1.bond_tx_hex, &bond.1.requirements) .await { + warn!("Bond validation failed: {:?}", e); match env::var("PUNISHMENT_ENABLED") .unwrap_or_else(|_| "0".to_string()) .as_str() @@ -67,6 +70,6 @@ pub async fn monitor_bonds(coordinator: Arc) -> Result<()> { } // sleep for a while - tokio::time::sleep(tokio::time::Duration::from_secs(30)).await; + tokio::time::sleep(tokio::time::Duration::from_secs(15)).await; } } diff --git a/taptrade-cli-demo/coordinator/src/wallet/mod.rs b/taptrade-cli-demo/coordinator/src/wallet/mod.rs index 11d6ce2..ea33b0f 100644 --- a/taptrade-cli-demo/coordinator/src/wallet/mod.rs +++ b/taptrade-cli-demo/coordinator/src/wallet/mod.rs @@ -75,7 +75,10 @@ impl CoordinatorWallet { let tx: Transaction = deserialize(&hex::decode(bond)?)?; { let wallet = self.wallet.lock().await; - + if let Err(e) = wallet.sync(blockchain, SyncOptions::default()) { + error!("Error syncing wallet: {:?}", e); + return Ok(()); // if the electrum server goes down all bonds will be considered valid. Maybe redundancy should be added. + }; // we need to test this with signed and invalid/unsigned transactions // checks signatures and inputs if let Err(e) = verify_tx(&tx, &*wallet.database(), blockchain) { @@ -111,10 +114,12 @@ impl CoordinatorWallet { if ((input_sum - output_sum) / tx.vsize() as u64) < 200 { return Err(anyhow!("Bond fee rate too low")); } + debug!("validate_bond_tx_hex(): Bond validation successful."); Ok(()) } pub fn publish_bond_tx_hex(&self, bond: &str) -> Result<()> { + warn!("publish_bond_tx_hex(): publishing cheating bond tx!"); let blockchain = &*self.backend; let tx: Transaction = deserialize(&hex::decode(bond)?)?; diff --git a/taptrade-cli-demo/trader/src/wallet/bond.rs b/taptrade-cli-demo/trader/src/wallet/bond.rs index 05bbae8..c37dd8a 100644 --- a/taptrade-cli-demo/trader/src/wallet/bond.rs +++ b/taptrade-cli-demo/trader/src/wallet/bond.rs @@ -7,6 +7,7 @@ use bdk::{ database::MemoryDatabase, wallet::coin_selection::BranchAndBoundCoinSelection, FeeRate, SignOptions, Wallet, }; +use log::debug; use serde::de::value; use std::str::FromStr; @@ -29,6 +30,7 @@ impl Bond { bond_target: &BondRequirementResponse, trader_input: &TraderSettings, ) -> Result { + debug!("Assembling bond transaction"); // parse bond locking address as Address struct and verify network is testnet let address: Address = Address::from_str(&bond_target.bond_address)?.require_network(Network::Testnet)?; @@ -45,15 +47,16 @@ impl Bond { builder .add_recipient(address.script_pubkey(), bond_target.locking_amount_sat) - .do_not_spend_change() + .do_not_spend_change() // reconsider if we need this? .fee_rate(FeeRate::from_sat_per_vb(201.0)); builder.finish()? }; - let finalized = wallet.sign(&mut psbt, SignOptions::default())?; - if !finalized { - return Err(anyhow!("Transaction could not be finalized")); - }; + debug!("Signing bond transaction."); + // let finalized = wallet.sign(&mut psbt, SignOptions::default())?; // deactivated to test bond validation + // if !finalized { + // return Err(anyhow!("Transaction could not be finalized")); + // }; Ok(psbt) } }