Skip to content

Commit

Permalink
Dispute readability (#390)
Browse files Browse the repository at this point in the history
* removed wrong request_id in messages

* playing a bit on a file with cursor AI

* improving readability in dispute.rs

* Update src/app/dispute.rs

Ok rabbit!

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update src/app/dispute.rs

Ok Rabbit

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* cursorAi is fucking good for commentsgit status

* Update src/app/dispute.rs

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* small fix on message error in dispute.rs

* Update src/app/dispute.rs

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* fixed test and build

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
  • Loading branch information
arkanoider and coderabbitai[bot] authored Nov 12, 2024
1 parent 8542920 commit 22d3a30
Show file tree
Hide file tree
Showing 3 changed files with 267 additions and 231 deletions.
236 changes: 104 additions & 132 deletions src/app.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
pub mod add_invoice;
pub mod admin_add_solver;
pub mod admin_cancel;
pub mod admin_settle;
pub mod admin_take_dispute;
pub mod cancel;
pub mod dispute;
pub mod fiat_sent;
pub mod order;
pub mod rate_user;
pub mod release;
pub mod take_buy;
pub mod take_sell;
//! Main application module for the P2P trading system.
//! Handles message routing, action processing, and event loop management.
// Submodules for different trading actions
pub mod add_invoice; // Handles invoice creation
pub mod admin_add_solver; // Admin functionality to add dispute solvers
pub mod admin_cancel; // Admin order cancellation
pub mod admin_settle; // Admin dispute settlement
pub mod admin_take_dispute; // Admin dispute handling
pub mod cancel; // User order cancellation
pub mod dispute; // User dispute handling
pub mod fiat_sent; // Fiat payment confirmation
pub mod order; // Order creation and management
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
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 @@ -25,23 +30,86 @@ 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;

// Core functionality imports
use crate::lightning::LndConnector;
use crate::nip59::unwrap_gift_wrap;
use crate::Settings;

// External dependencies
use anyhow::Result;
use mostro_core::message::{Action, Message};
use nostr_sdk::prelude::*;
use sqlx::{Pool, Sqlite};
use std::sync::Arc;
use tokio::sync::Mutex;
use tracing::error;
use tracing::info;

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

/// Handles the processing of a single message action by routing it to the appropriate handler
/// based on the action type. This is the core message routing logic of the application.
///
/// # Arguments
/// * `action` - The type of action to be performed
/// * `msg` - The message containing action details
/// * `event` - The unwrapped gift wrap event
/// * `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,

// 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::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,

// 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,

_ => {
tracing::info!("Received message with action {:?}", action);
Ok(())
}
}
}

/// Main event loop that processes incoming Nostr events.
/// Handles message verification, POW checking, and routes valid messages to appropriate handlers.
///
/// # Arguments
/// * `my_keys` - The node's keypair
/// * `client` - Nostr client instance
/// * `ln_client` - Lightning network connector
/// * `pool` - SQLite connection pool
/// * `rate_list` - Shared list of rating events
pub async fn run(
my_keys: Keys,
client: &Client,
Expand All @@ -56,20 +124,20 @@ pub async fn run(
let pow = Settings::get_mostro().pow;
while let Ok(notification) = notifications.recv().await {
if let RelayPoolNotification::Event { event, .. } = notification {
// Verify pow
// Verify proof of work
if !event.check_pow(pow) {
// Discard
info!("Not POW verified event!");
// Discard events that don't meet POW requirements
tracing::info!("Not POW verified event!");
continue;
}
if let Kind::GiftWrap = event.kind {
// We validates if the event is correctly signed
// Validate event signature
if event.verify().is_err() {
tracing::warn!("Error in event verification")
};

let event = unwrap_gift_wrap(&my_keys, &event)?;
// We discard events older than 10 seconds
// Discard events older than 10 seconds to prevent replay attacks
let since_time = chrono::Utc::now()
.checked_sub_signed(chrono::Duration::seconds(10))
.unwrap()
Expand All @@ -78,127 +146,31 @@ pub async fn run(
continue;
}

// Parse and process the message
let message = Message::from_json(&event.rumor.content);
match message {
Ok(msg) => {
if msg.get_inner_message_kind().verify() {
if let Some(action) = msg.inner_action() {
match action {
Action::NewOrder => {
if let Err(e) =
order_action(msg, &event, &my_keys, &pool).await
{
warning_msg(&action, e)
}
}
Action::TakeSell => {
if let Err(e) =
take_sell_action(msg, &event, &my_keys, &pool).await
{
warning_msg(&action, e)
}
}
Action::TakeBuy => {
if let Err(e) =
take_buy_action(msg, &event, &my_keys, &pool).await
{
warning_msg(&action, e)
}
}
Action::FiatSent => {
if let Err(e) =
fiat_sent_action(msg, &event, &my_keys, &pool).await
{
warning_msg(&action, e)
}
}
Action::Release => {
if let Err(e) = release_action(
msg, &event, &my_keys, &pool, ln_client,
)
.await
{
warning_msg(&action, e)
}
}
Action::Cancel => {
if let Err(e) = cancel_action(
msg, &event, &my_keys, &pool, ln_client,
)
.await
{
warning_msg(&action, e)
}
}
Action::AddInvoice => {
if let Err(e) =
add_invoice_action(msg, &event, &my_keys, &pool)
.await
{
warning_msg(&action, e)
}
}
Action::PayInvoice => todo!(),
Action::RateUser => {
if let Err(e) = update_user_reputation_action(
msg,
&event,
&my_keys,
&pool,
rate_list.clone(),
)
.await
{
warning_msg(&action, e)
}
}
Action::Dispute => {
if let Err(e) =
dispute_action(msg, &event, &my_keys, &pool).await
{
warning_msg(&action, e)
}
}
Action::AdminCancel => {
if let Err(e) = admin_cancel_action(
msg, &event, &my_keys, &pool, ln_client,
)
.await
{
warning_msg(&action, e)
}
}
Action::AdminSettle => {
if let Err(e) = admin_settle_action(
msg, &event, &my_keys, &pool, ln_client,
)
.await
{
warning_msg(&action, e)
}
}
Action::AdminAddSolver => {
if let Err(e) = admin_add_solver_action(
msg, &event, &my_keys, &pool,
)
.await
{
warning_msg(&action, e)
}
}
Action::AdminTakeDispute => {
if let Err(e) =
admin_take_dispute_action(msg, &event, &pool).await
{
warning_msg(&action, e)
}
}
_ => info!("Received message with action {:?}", action),
if let Err(e) = handle_message_action(
&action,
msg,
&event,
&my_keys,
&pool,
ln_client,
rate_list.clone(),
)
.await
{
warning_msg(&action, e)
}
}
}
}
Err(e) => error!("Failed to parse message from JSON: {:?}", e),
Err(e) => {
tracing::warn!("Failed to parse event message from JSON: {:?}", e)
}
}
}
}
Expand Down
18 changes: 2 additions & 16 deletions src/app/cancel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,14 +214,7 @@ pub async fn cancel_add_invoice(
&event.sender,
)
.await;
send_new_order_msg(
None,
Some(order.id),
Action::Canceled,
None,
&seller_pubkey,
)
.await;
send_new_order_msg(None, Some(order.id), Action::Canceled, None, &seller_pubkey).await;
Ok(())
} else {
// We re-publish the event with Pending status
Expand Down Expand Up @@ -283,14 +276,7 @@ pub async fn cancel_pay_hold_invoice(
&event.sender,
)
.await;
send_new_order_msg(
None,
Some(order.id),
Action::Canceled,
None,
&seller_pubkey,
)
.await;
send_new_order_msg(None, Some(order.id), Action::Canceled, None, &seller_pubkey).await;
Ok(())
} else {
// We re-publish the event with Pending status
Expand Down
Loading

0 comments on commit 22d3a30

Please sign in to comment.