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

Refactoring #431

Merged
merged 55 commits into from
Feb 14, 2025
Merged
Show file tree
Hide file tree
Changes from 45 commits
Commits
Show all changes
55 commits
Select commit Hold shift + click to select a range
b446cd7
Feat: new error management
arkanoider Jan 6, 2025
b88b4c5
Doing improvements on messages sending
arkanoider Jan 7, 2025
32de93c
Working on queues for sending messages
arkanoider Jan 7, 2025
d293d01
Start alignment of all files - stil not usable
arkanoider Jan 8, 2025
896e735
Start alignment of all files - stil not usable
arkanoider Jan 8, 2025
8d82b9e
Working on refactoring all files...
arkanoider Jan 8, 2025
63003f9
going on with refactor
arkanoider Jan 16, 2025
db80d82
Going on with file refactor: fiat_sent, release
arkanoider Jan 17, 2025
b601b79
fixing and polishing
arkanoider Jan 19, 2025
ea07c12
continue fixing
arkanoider Jan 20, 2025
42b56f9
polishing all my shit
arkanoider Jan 20, 2025
a856834
first compiling release - starting tests
arkanoider Jan 21, 2025
e3a6e99
small fix on cancel.rs
arkanoider Jan 23, 2025
79f86c6
merged latest main on refactored branch
arkanoider Jan 23, 2025
afb132d
starting fix to compile
arkanoider Jan 23, 2025
dee8cd9
fix: fixing latest commits with refactoring
arkanoider Jan 31, 2025
49e679c
compiling with latest modifications ready for testing
arkanoider Feb 1, 2025
c6ebafa
Fix: removed elements from queues after sending
arkanoider Feb 2, 2025
77791fd
Fix: did first takesell order with successful result
arkanoider Feb 2, 2025
f41b521
fix: fixed a fiatsent update of db
arkanoider Feb 3, 2025
e8de8a8
improvement on release.rs
arkanoider Feb 3, 2025
0596e27
new get_next_trade_key function calls
arkanoider Feb 4, 2025
b2db8bf
removed redundant check
arkanoider Feb 4, 2025
098e7fd
polishing scheduler
arkanoider Feb 6, 2025
9b243a6
going to compile with new scheduler
arkanoider Feb 7, 2025
14b8a7a
Mostrod compile -just fixing one test
arkanoider Feb 7, 2025
a1641fd
Merge branch 'polishing-scheduler' into error-manage
arkanoider Feb 7, 2025
1f99cd3
fix on cargo.toml and used specific core commit to compile - in case …
arkanoider Feb 7, 2025
1b2f248
Merge branch 'main' into error-manage
arkanoider Feb 7, 2025
e8ea8f6
fix on test_send_dm to work - previously error was discarded so alway…
arkanoider Feb 8, 2025
5faf275
ready to test release with refactoring
arkanoider Feb 9, 2025
55739e5
Update src/app.rs
arkanoider Feb 9, 2025
28f44ba
Add an error in mostro-core suggested by rabbit
arkanoider Feb 9, 2025
b80d068
Fix: coderabbit issue #434
arkanoider Feb 9, 2025
291ebef
add: rabbit advice on atomic database operations
arkanoider Feb 9, 2025
ac7abe3
reverted rabbit transactions sqlx impl - not useful in my case
arkanoider Feb 9, 2025
145e728
Fix: bad checks on cancel fixed - accelerated scheduler dequeue to 25…
arkanoider Feb 10, 2025
cbaff8c
Fix: improved some part of code
arkanoider Feb 11, 2025
add5ce6
Fix: wrong amount message sent back to taker - also trade index cantD…
arkanoider Feb 11, 2025
566e6f1
Reverted a wrong check on cancel.rs
arkanoider Feb 11, 2025
d46e680
Test a fix for trade keys errors
arkanoider Feb 12, 2025
a65cc29
Fix: testing trade keys error
arkanoider Feb 12, 2025
5fa099f
Merge branch 'trade-keys-test' into error-manage
arkanoider Feb 12, 2025
de63e4f
Fix: out of sats limits fix in take-buy
arkanoider Feb 12, 2025
e848a9f
Fix: order cancelled is cancel come from maker and is pending
arkanoider Feb 12, 2025
d15d4d7
Removed unused code from cancel.rs
arkanoider Feb 12, 2025
e7588b1
Added error management
arkanoider Feb 12, 2025
4db974e
Fix: invalid invoice cantDo message sent in addInvoce command
arkanoider Feb 13, 2025
900c9a4
Fix: correct cancel from taker implementation
arkanoider Feb 13, 2025
360d807
Typo: uncommented openssl from cargo.toml
arkanoider Feb 13, 2025
aadc17a
Fix taker message issue
arkanoider Feb 13, 2025
ca175a6
Fix cooperative cancel
arkanoider Feb 13, 2025
001c2e0
Fix: cancel cooperative split fns to improve readability - tested cat…
arkanoider Feb 14, 2025
2ac345b
Merge branch 'message-cancel-fix' into error-manage
arkanoider Feb 14, 2025
dfc1f65
bumped some deps
arkanoider Feb 14, 2025
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
473 changes: 275 additions & 198 deletions Cargo.lock

Large diffs are not rendered by default.

7 changes: 4 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,16 @@ uuid = { version = "1.8.0", features = [
"serde",
] }
reqwest = { version = "0.12.1", features = ["json"] }
mostro-core = { version = "0.6.25", features = ["sqlx"] }
# mostro-core = { version = "0.6.25", features = ["sqlx"] }
mostro-core = { git = "https://github.com/MostroP2P/mostro-core", rev = "7e53875cc8370a8da4dcc80b243f9eae630ae345" , features = ["sqlx"] }
arkanoider marked this conversation as resolved.
Show resolved Hide resolved
tracing = "0.1.40"
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
config = "0.15.4"
clap = { version = "4.5.19", features = ["derive"] }
lnurl-rs = "0.9.0"
openssl = { version = "0.10.66", features = ["vendored"] }
# openssl = { version = "0.10.66", features = ["vendored"] }
arkanoider marked this conversation as resolved.
Show resolved Hide resolved
once_cell = "1.20.2"
bitcoin = "0.32.5"

[dev-dependencies]
tokio = { version = "1.40.0", features = ["full", "test-util", "macros"] }
tokio = { version = "1.40.0", features = ["full", "test-util", "macros"] }
175 changes: 115 additions & 60 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ pub mod rate_user; // User reputation system
pub mod release; // Release of held funds
pub mod take_buy; // Taking buy orders
pub mod take_sell; // Taking sell orders

// Import action handlers from submodules
pub mod trade_pubkey; // Trade pubkey action
// Import action handlers from submodules
use crate::app::add_invoice::add_invoice_action;
use crate::app::admin_add_solver::admin_add_solver_action;
use crate::app::admin_cancel::admin_cancel_action;
Expand All @@ -30,27 +30,51 @@ use crate::app::rate_user::update_user_reputation_action;
use crate::app::release::release_action;
use crate::app::take_buy::take_buy_action;
use crate::app::take_sell::take_sell_action;
use crate::db::update_user_trade_index;
use crate::app::trade_pubkey::trade_pubkey_action;
// use crate::db::update_user_trade_index;
// Core functionality imports
use crate::db::add_new_user;
use crate::db::is_user_present;
use crate::lightning::LndConnector;
use crate::util::send_cant_do_msg;
use crate::util::enqueue_cant_do_msg;
use crate::Settings;

// External dependencies
use anyhow::Result;
use mostro_core::message::{Action, CantDoReason, Message};
use mostro_core::error::CantDoReason;
use mostro_core::error::MostroError;
use mostro_core::error::ServiceError;
use mostro_core::message::{Action, Message};
use mostro_core::user::User;
use nostr_sdk::prelude::*;
use sqlx::{Pool, Sqlite};
use std::sync::Arc;
use tokio::sync::Mutex;

/// Helper function to log warning messages for action errors
fn warning_msg(action: &Action, e: anyhow::Error) {
fn warning_msg(action: &Action, e: ServiceError) {
tracing::warn!("Error in {} with context {}", action, e);
}

/// Function to manage errors and send appropriate messages
async fn manage_errors(
e: MostroError,
inner_message: Message,
event: UnwrappedGift,
action: &Action,
) {
match e {
MostroError::MostroCantDo(cause) => {
enqueue_cant_do_msg(
inner_message.get_inner_message_kind().request_id,
inner_message.get_inner_message_kind().id,
cause,
event.rumor.pubkey,
)
.await
}
MostroError::MostroInternalErr(e) => warning_msg(action, e),
}
}

/// Function to check if a user is present in the database and update or create their trade index.
///
/// This function performs the following tasks:
Expand All @@ -64,15 +88,19 @@ fn warning_msg(action: &Action, e: anyhow::Error) {
/// * `pool` - The database connection pool used to query and update user data.
/// * `event` - The unwrapped gift event containing the sender's information.
/// * `msg` - The message containing action details and trade index information.
async fn check_trade_index(pool: &Pool<Sqlite>, event: &UnwrappedGift, msg: &Message) {
async fn check_trade_index(
pool: &Pool<Sqlite>,
event: &UnwrappedGift,
msg: &Message,
) -> Result<(), MostroError> {
let message_kind = msg.get_inner_message_kind();

// Only process actions related to trading
if !matches!(
message_kind.action,
Action::NewOrder | Action::TakeBuy | Action::TakeSell
) {
return;
return Ok(());
}

// If user is present, we check the trade index and signature
Expand All @@ -87,60 +115,50 @@ async fn check_trade_index(pool: &Pool<Sqlite>, event: &UnwrappedGift, msg: &Mes
Ok(data) => data,
Err(e) => {
tracing::error!("Error deserializing content: {}", e);
return;
return Err(MostroError::MostroInternalErr(
ServiceError::MessageSerializationError,
));
}
};

let (_, sig) = content;

if index <= user.last_trade_index {
tracing::info!("Invalid trade index");
send_cant_do_msg(
None,
message_kind.id,
Some(CantDoReason::InvalidTradeIndex),
&event.rumor.pubkey,
manage_errors(
MostroError::MostroCantDo(CantDoReason::InvalidTradeIndex),
msg.clone(),
event.clone(),
&message_kind.action,
)
.await;
return;
return Err(MostroError::MostroCantDo(CantDoReason::InvalidTradeIndex));
}

if !message_kind.verify_signature(event.rumor.pubkey, sig) {
tracing::info!("Invalid signature");
send_cant_do_msg(
None,
message_kind.id,
Some(CantDoReason::InvalidSignature),
&event.rumor.pubkey,
)
.await;
return;
return Err(MostroError::MostroCantDo(CantDoReason::InvalidSignature));
}

if let Err(e) = update_user_trade_index(pool, event.sender.to_string(), index).await
{
tracing::error!("Error updating user trade index: {}", e);
}
// if let Err(e) = update_user_trade_index(pool, event.sender.to_string(), index).await
// {
// tracing::error!("Error updating user trade index: {}", e);
// }
}
Ok(())
}
Err(_) => {
if let (true, last_trade_index) = message_kind.has_trade_index() {
if let (true, _) = message_kind.has_trade_index() {
let new_user: User = User {
pubkey: event.sender.to_string(),
last_trade_index,
..Default::default()
};
if let Err(e) = add_new_user(pool, new_user).await {
tracing::error!("Error creating new user: {}", e);
send_cant_do_msg(
None,
msg.get_inner_message_kind().id,
Some(CantDoReason::CantCreateUser),
&event.rumor.pubkey,
)
.await;
return Err(MostroError::MostroCantDo(CantDoReason::CantCreateUser));
}
}
Ok(())
}
}
}
Expand All @@ -155,40 +173,65 @@ async fn check_trade_index(pool: &Pool<Sqlite>, event: &UnwrappedGift, msg: &Mes
/// * `my_keys` - Node keypair for signing/verification
/// * `pool` - Database connection pool
/// * `ln_client` - Lightning network connector
/// * `rate_list` - Shared list of rating events
async fn handle_message_action(
action: &Action,
msg: Message,
event: &UnwrappedGift,
my_keys: &Keys,
pool: &Pool<Sqlite>,
ln_client: &mut LndConnector,
rate_list: Arc<Mutex<Vec<Event>>>,
) -> Result<()> {
match action {
// Order-related actions
Action::NewOrder => order_action(msg, event, my_keys, pool).await,
Action::TakeSell => take_sell_action(msg, event, my_keys, pool).await,
Action::TakeBuy => take_buy_action(msg, event, my_keys, pool).await,
Action::NewOrder => order_action(msg, event, my_keys, pool)
.await
.map_err(|e| e.into()),
Action::TakeSell => take_sell_action(msg, event, my_keys, pool)
.await
.map_err(|e| e.into()),
Action::TakeBuy => take_buy_action(msg, event, my_keys, pool)
.await
.map_err(|e| e.into()),

// Payment-related actions
Action::FiatSent => fiat_sent_action(msg, event, my_keys, pool).await,
Action::Release => release_action(msg, event, my_keys, pool, ln_client).await,
Action::AddInvoice => add_invoice_action(msg, event, my_keys, pool).await,
Action::FiatSent => fiat_sent_action(msg, event, my_keys, pool)
.await
.map_err(|e| e.into()),
Action::Release => release_action(msg, event, my_keys, pool, ln_client)
.await
.map_err(|e| e.into()),
Action::AddInvoice => add_invoice_action(msg, event, my_keys, pool)
.await
.map_err(|e| e.into()),
Action::PayInvoice => todo!(),

// Dispute and rating actions
Action::Dispute => dispute_action(msg, event, my_keys, pool).await,
Action::RateUser => {
update_user_reputation_action(msg, event, my_keys, pool, rate_list).await
}
Action::Cancel => cancel_action(msg, event, my_keys, pool, ln_client).await,
Action::Dispute => dispute_action(msg, event, my_keys, pool)
.await
.map_err(|e| e.into()),
Action::RateUser => update_user_reputation_action(msg, event, my_keys, pool)
.await
.map_err(|e| e.into()),
Action::Cancel => cancel_action(msg, event, my_keys, pool, ln_client)
.await
.map_err(|e| e.into()),

// Admin actions
Action::AdminCancel => admin_cancel_action(msg, event, my_keys, pool, ln_client).await,
Action::AdminSettle => admin_settle_action(msg, event, my_keys, pool, ln_client).await,
Action::AdminAddSolver => admin_add_solver_action(msg, event, my_keys, pool).await,
Action::AdminTakeDispute => admin_take_dispute_action(msg, event, pool).await,
Action::AdminCancel => admin_cancel_action(msg, event, my_keys, pool, ln_client)
.await
.map_err(|e| e.into()),
Action::AdminSettle => admin_settle_action(msg, event, my_keys, pool, ln_client)
.await
.map_err(|e| e.into()),
Action::AdminAddSolver => admin_add_solver_action(msg, event, my_keys, pool)
.await
.map_err(|e| e.into()),
Action::AdminTakeDispute => admin_take_dispute_action(msg, event, pool)
.await
.map_err(|e| e.into()),
Action::TradePubkey => trade_pubkey_action(msg, event, pool)
.await
.map_err(|e| e.into()),

_ => {
tracing::info!("Received message with action {:?}", action);
Expand All @@ -211,7 +254,6 @@ pub async fn run(
client: &Client,
ln_client: &mut LndConnector,
pool: Pool<Sqlite>,
rate_list: Arc<Mutex<Vec<Event>>>,
) -> Result<()> {
loop {
let mut notifications = client.notifications();
Expand Down Expand Up @@ -275,22 +317,35 @@ pub async fn run(
}

// Check if message is message with trade index
check_trade_index(&pool, &event, &message).await;
if let Err(e) = check_trade_index(&pool, &event, &message).await {
tracing::error!("Error checking trade index: {}", e);
continue;
}

if inner_message.verify() {
if let Some(action) = message.inner_action() {
if let Err(e) = handle_message_action(
&action,
message,
message.clone(),
&event,
&my_keys,
&pool,
ln_client,
rate_list.clone(),
)
.await
{
warning_msg(&action, e)
match e.downcast::<MostroError>() {
Ok(err) => {
manage_errors(err, message, event, &action).await;
}
Err(e) => {
tracing::error!("Unexpected error type: {}", e);
warning_msg(
&action,
ServiceError::UnexpectedError(e.to_string()),
);
}
}
}
}
}
Expand Down
Loading