mostro 0.17.4

Lightning Network peer-to-peer nostr platform
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
//! Main application module for the P2P trading system.
//! Handles message routing, action processing, and event loop management.

// Application context (dependency injection)
pub mod context;

// 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 bond; // Anti-abuse bond data + helpers (issue #711)
pub mod cancel; // User order cancellation
pub mod dev_fee; // Dev fee payment lifecycle
pub mod dispute; // User dispute handling
pub mod fiat_sent; // Fiat payment confirmation
pub mod last_trade_index;
pub mod order; // Order creation and management
pub mod orders; // Orders action
pub mod rate_user; // User reputation system
pub mod release; // Release of held funds
pub mod restore_session; // Restore session action
pub mod take_buy; // Taking buy orders
pub mod take_sell; // Taking sell orders
pub mod trade_pubkey; // Trade pubkey action // Sync user trade index 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;
use crate::app::admin_settle::admin_settle_action;
use crate::app::admin_take_dispute::admin_take_dispute_action;
use crate::app::bond::add_bond_invoice_action;
use crate::app::cancel::cancel_action;
use crate::app::context::AppContext;
use crate::app::dispute::dispute_action;
use crate::app::fiat_sent::fiat_sent_action;
use crate::app::last_trade_index::last_trade_index;
use crate::app::order::order_action;
use crate::app::orders::orders_action;
use crate::app::rate_user::update_user_reputation_action;
use crate::app::release::release_action;
use crate::app::restore_session::restore_session_action;
use crate::app::take_buy::take_buy_action;
use crate::app::take_sell::take_sell_action;
use crate::app::trade_pubkey::trade_pubkey_action;
// Core functionality imports
use crate::db::add_new_user;
use crate::db::is_user_present;
use crate::lightning::LndConnector;
use crate::util::enqueue_cant_do_msg;

// External dependencies
use mostro_core::error::CantDoReason;
use mostro_core::error::MostroError;
use mostro_core::error::ServiceError;
use mostro_core::message::{Action, Message};
use mostro_core::nip59::{unwrap_message, UnwrappedMessage};
use mostro_core::user::User;
use nostr_sdk::prelude::*;

/// Helper function to log warning messages for action errors
fn warning_msg(action: &Action, err: ServiceError) {
    let message = match &err {
        ServiceError::EnvVarError(message) => message.to_string(),
        ServiceError::EncryptionError(message) => message.to_string(),
        ServiceError::DecryptionError(message) => message.to_string(),
        ServiceError::IOError(message) => message.to_string(),
        ServiceError::UnexpectedError(message) => message.to_string(),
        ServiceError::LnNodeError(message) => message.to_string(),
        ServiceError::LnPaymentError(message) => message.to_string(),
        ServiceError::DbAccessError(message) => message.to_string(),
        ServiceError::NostrError(message) => message.to_string(),
        ServiceError::HoldInvoiceError(message) => message.to_string(),
        _ => "No message".to_string(),
    };

    tracing::warn!(
        "Error in {} with context {} - inner message {}",
        action,
        err,
        message
    );
}

/// Function to manage errors and send appropriate messages
async fn manage_errors(
    e: MostroError,
    inner_message: Message,
    event: UnwrappedMessage,
    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,
                // Reply to the trade key that authored the rumor.
                event.sender,
            )
            .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:
/// 1. It checks if the action associated with the incoming message is related to trading (NewOrder, TakeBuy, or TakeSell).
/// 2. If the user is found in the database, it verifies the trade index and the signature of the message.
///    - If valid, it updates the user's trade index.
///    - If invalid, it logs a warning and sends a message indicating the issue.
/// 3. If the user is not found, it creates a new user entry with the provided trade index if applicable.
///
/// # Arguments
/// * `ctx` - Application context providing database pool and other dependencies.
/// * `event` - The unwrapped NIP-59 message (`UnwrappedMessage`) containing
///   the sender's identity and trade keys.
/// * `msg` - The message containing action details and trade index information.
async fn check_trade_index(
    ctx: &AppContext,
    event: &UnwrappedMessage,
    msg: &Message,
) -> Result<(), MostroError> {
    let pool = ctx.pool();
    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 Ok(());
    }

    // If user is present, we check the trade index and signature
    match is_user_present(pool, event.identity.to_string()).await {
        Ok(user) => {
            if let index @ 1.. = message_kind.trade_index() {
                // Inner-tuple signature is already decoded by unwrap_message.
                let sig = event.signature.ok_or_else(|| {
                    tracing::error!("Trade-index message missing inner signature");
                    MostroError::MostroCantDo(CantDoReason::InvalidSignature)
                })?;

                if index <= user.last_trade_index {
                    tracing::info!("Invalid trade index");
                    manage_errors(
                        MostroError::MostroCantDo(CantDoReason::InvalidTradeIndex),
                        msg.clone(),
                        event.clone(),
                        &message_kind.action,
                    )
                    .await;
                    return Err(MostroError::MostroCantDo(CantDoReason::InvalidTradeIndex));
                }
                let msg_json = match msg.as_json() {
                    Ok(m) => m,
                    Err(e) => {
                        tracing::error!(
                            "Failed to serialize message for signature verification: {}",
                            e
                        );
                        return Err(MostroError::MostroInternalErr(
                            ServiceError::MessageSerializationError,
                        ));
                    }
                };
                if !Message::verify_signature(msg_json, event.sender, sig) {
                    tracing::info!("Invalid signature");
                    return Err(MostroError::MostroCantDo(CantDoReason::InvalidSignature));
                }
            }
            Ok(())
        }
        Err(_) => {
            if let Some(last_trade_index) = message_kind.trade_index {
                // Refuse case of index 0, means identikey key and new user cannot use it!
                if last_trade_index == 0 {
                    return Err(MostroError::MostroCantDo(CantDoReason::InvalidTradeIndex));
                }
                if event.identity != event.sender {
                    let new_user: User = User {
                        pubkey: event.identity.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);
                        return Err(MostroError::MostroCantDo(CantDoReason::CantCreateUser));
                    }
                }
            }
            Ok(())
        }
    }
}

async fn handle_message_action_no_ln(
    action: &Action,
    msg: Message,
    event: &UnwrappedMessage,
    my_keys: &Keys,
    ctx: &AppContext,
) -> Result<()> {
    match action {
        // Order-related actions
        Action::NewOrder => order_action(ctx, msg, event, my_keys)
            .await
            .map_err(|e| e.into()),
        Action::TakeSell => take_sell_action(ctx, msg, event, my_keys)
            .await
            .map_err(|e| e.into()),
        Action::TakeBuy => take_buy_action(ctx, msg, event, my_keys)
            .await
            .map_err(|e| e.into()),

        // Payment-related actions that do not require LN client
        Action::FiatSent => fiat_sent_action(ctx, msg, event, my_keys)
            .await
            .map_err(|e| e.into()),
        Action::AddInvoice => add_invoice_action(ctx, msg, event, my_keys)
            .await
            .map_err(|e| e.into()),
        Action::AddBondInvoice => add_bond_invoice_action(ctx, msg, event, my_keys)
            .await
            .map_err(|e| e.into()),
        Action::PayInvoice => Err(MostroError::MostroCantDo(CantDoReason::InvalidAction).into()),
        Action::LastTradeIndex => last_trade_index(ctx, msg, event, my_keys)
            .await
            .map_err(|e| e.into()),

        // Dispute and rating actions
        Action::Dispute => dispute_action(ctx, msg, event, my_keys)
            .await
            .map_err(|e| e.into()),
        Action::RateUser => update_user_reputation_action(ctx, msg, event, my_keys)
            .await
            .map_err(|e| e.into()),

        // Admin actions without LN
        Action::AdminAddSolver => admin_add_solver_action(ctx, msg, event, my_keys)
            .await
            .map_err(|e| e.into()),
        Action::AdminTakeDispute => admin_take_dispute_action(ctx, msg, event, my_keys)
            .await
            .map_err(|e| e.into()),
        Action::TradePubkey => trade_pubkey_action(ctx, msg, event)
            .await
            .map_err(|e| e.into()),
        Action::RestoreSession => restore_session_action(ctx, event)
            .await
            .map_err(|e| e.into()),
        Action::Orders => orders_action(ctx, msg, event).await.map_err(|e| e.into()),
        _ => {
            tracing::info!("Received message with action {:?}", action);
            Ok(())
        }
    }
}

/// 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.
async fn handle_message_action(
    action: &Action,
    msg: Message,
    event: &UnwrappedMessage,
    my_keys: &Keys,
    ln_client: &mut LndConnector,
    ctx: &AppContext,
) -> Result<()> {
    match action {
        Action::Release => release_action(ctx, msg, event, my_keys, ln_client)
            .await
            .map_err(|e| e.into()),
        Action::Cancel => cancel_action(ctx, msg, event, my_keys, ln_client)
            .await
            .map_err(|e| e.into()),
        Action::AdminCancel => admin_cancel_action(ctx, msg, event, my_keys, ln_client)
            .await
            .map_err(|e| e.into()),
        Action::AdminSettle => admin_settle_action(ctx, msg, event, my_keys, ln_client)
            .await
            .map_err(|e| e.into()),
        _ => handle_message_action_no_ln(action, msg, event, my_keys, ctx).await,
    }
}

/// 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
pub async fn run(ctx: AppContext, ln_client: &mut LndConnector) -> Result<()> {
    let my_keys = ctx.keys();
    let client = ctx.nostr_client();
    let pow = ctx.settings().mostro.pow;

    loop {
        let mut notifications = client.notifications();

        while let Ok(notification) = notifications.recv().await {
            if let RelayPoolNotification::Event { event, .. } = notification {
                // Verify proof of work
                if !event.check_pow(pow) {
                    // Discard events that don't meet POW requirements
                    tracing::info!("Not POW verified event!");
                    continue;
                }
                if let Kind::GiftWrap = event.kind {
                    // Validate event signature
                    if event.verify().is_err() {
                        tracing::warn!("Error in event verification")
                    };

                    // Mostro-core's NIP-59 transport handles the dual-key layout
                    // (identity key signs seal, trade key authors rumor) plus inner
                    // tuple (message, signature) decoding and signature verification
                    // in one shot.
                    let unwrapped = match unwrap_message(&event, my_keys).await {
                        Ok(Some(u)) => u,
                        // Outer NIP-44 decrypt failed: not addressed to this node.
                        Ok(None) => continue,
                        Err(e) => {
                            tracing::warn!("Error unwrapping NIP-59 message: {}", e);
                            continue;
                        }
                    };
                    // Discard events older than 10 seconds to prevent replay attacks
                    let since_time = chrono::Utc::now()
                        .checked_sub_signed(chrono::Duration::seconds(10))
                        .unwrap()
                        .timestamp() as u64;
                    if unwrapped.created_at.as_secs() < since_time {
                        continue;
                    }
                    let message = unwrapped.message.clone();

                    // Full-privacy clients reuse the trade key as identity and send
                    // unsigned rumors. Any other shape must carry a valid inner
                    // signature — unwrap_message already verified it, so if identity
                    // and sender differ here without a signature we bail out.
                    if unwrapped.identity != unwrapped.sender && unwrapped.signature.is_none() {
                        tracing::warn!(
                            "Missing inner signature: identity {} differs from trade key {}",
                            unwrapped.identity,
                            unwrapped.sender
                        );
                        continue;
                    }

                    // Get inner message kind
                    let inner_message = message.get_inner_message_kind();
                    // Check if message is message with trade index
                    if let Err(e) = check_trade_index(&ctx, &unwrapped, &message).await {
                        tracing::warn!("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.clone(),
                                &unwrapped,
                                my_keys,
                                ln_client,
                                &ctx,
                            )
                            .await
                            {
                                match e.downcast::<MostroError>() {
                                    Ok(err) => {
                                        manage_errors(*err, message, unwrapped, &action).await;
                                    }
                                    Err(e) => {
                                        tracing::error!("Unexpected error type: {}", e);
                                        warning_msg(
                                            &action,
                                            ServiceError::UnexpectedError(e.to_string()),
                                        );
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use mostro_core::message::Action;

    use nostr_sdk::secp256k1::schnorr::Signature;
    use nostr_sdk::{Keys, Kind as NostrKind, Timestamp};

    // Helper function to create test keys
    fn create_test_keys() -> Keys {
        Keys::generate()
    }

    // Helper function to create test message
    fn create_test_message(action: Action, trade_index: Option<u32>) -> Message {
        Message::new_order(
            Some(uuid::Uuid::new_v4()),
            Some(1),
            trade_index.map(|i| i as i64),
            action,
            None, // We don't need payload for structure tests
        )
    }

    // Helper function to create an UnwrappedMessage for testing. Identity and
    // sender (trade key) are distinct to mirror the canonical Mostro flow.
    fn create_test_unwrapped_message() -> UnwrappedMessage {
        let identity = create_test_keys();
        let trade = create_test_keys();

        UnwrappedMessage {
            message: create_test_message(Action::NewOrder, None),
            signature: None,
            sender: trade.public_key(),
            identity: identity.public_key(),
            created_at: Timestamp::now(),
        }
    }

    #[test]
    fn test_warning_msg_all_error_types() {
        let action = Action::NewOrder;

        // Test all ServiceError variants
        warning_msg(&action, ServiceError::EnvVarError("env error".to_string()));
        warning_msg(
            &action,
            ServiceError::EncryptionError("encryption error".to_string()),
        );
        warning_msg(
            &action,
            ServiceError::DecryptionError("decryption error".to_string()),
        );
        warning_msg(&action, ServiceError::IOError("io error".to_string()));
        warning_msg(
            &action,
            ServiceError::UnexpectedError("unexpected error".to_string()),
        );
        warning_msg(
            &action,
            ServiceError::LnNodeError("ln node error".to_string()),
        );
        warning_msg(
            &action,
            ServiceError::LnPaymentError("ln payment error".to_string()),
        );
        warning_msg(
            &action,
            ServiceError::DbAccessError("db access error".to_string()),
        );
        warning_msg(&action, ServiceError::NostrError("nostr error".to_string()));
        warning_msg(
            &action,
            ServiceError::HoldInvoiceError("hold invoice error".to_string()),
        );

        // Test default case
        warning_msg(&action, ServiceError::MessageSerializationError);
    }

    #[tokio::test]
    async fn test_manage_errors_cant_do() {
        let message = create_test_message(Action::NewOrder, None);
        let event = create_test_unwrapped_message();
        let action = Action::NewOrder;

        let error = MostroError::MostroCantDo(CantDoReason::InvalidSignature);
        manage_errors(error, message, event, &action).await;

        // No-op: ensure no panic
    }

    #[tokio::test]
    async fn test_manage_errors_internal_error() {
        let message = create_test_message(Action::NewOrder, None);
        let event = create_test_unwrapped_message();
        let action = Action::NewOrder;

        let error =
            MostroError::MostroInternalErr(ServiceError::UnexpectedError("test error".to_string()));
        manage_errors(error, message, event, &action).await;

        // No-op: ensure no panic
    }

    mod check_trade_index_tests {
        use super::*;
        use crate::app::context::test_utils::{test_settings, TestContextBuilder};
        use sqlx::SqlitePool;
        use std::sync::Arc;

        async fn create_test_ctx() -> AppContext {
            let pool = Arc::new(SqlitePool::connect(":memory:").await.unwrap());
            TestContextBuilder::new()
                .with_pool(pool)
                .with_settings(test_settings())
                .build()
        }

        #[tokio::test]
        async fn test_check_trade_index_non_trading_action() {
            let ctx = create_test_ctx().await;
            let event = create_test_unwrapped_message();
            let message = create_test_message(Action::FiatSent, None);

            let result = check_trade_index(&ctx, &event, &message).await;
            assert!(result.is_ok());
        }

        #[tokio::test]
        async fn test_check_trade_index_trading_action_no_index() {
            let ctx = create_test_ctx().await;
            let event = create_test_unwrapped_message();
            let message = create_test_message(Action::NewOrder, None);

            let result = check_trade_index(&ctx, &event, &message).await;
            assert!(result.is_ok());
        }

        #[tokio::test]
        async fn test_check_trade_index_with_valid_index() {
            let ctx = create_test_ctx().await;
            let event = create_test_unwrapped_message();
            let message = create_test_message(Action::NewOrder, Some(1));

            // This test would require database setup and user creation
            // For now, we test the structure
            let result = check_trade_index(&ctx, &event, &message).await;
            // Result could be Ok or Err depending on database state
            assert!(result.is_ok() || result.is_err());
        }
    }

    mod handle_message_action_tests {
        use super::*;
        use crate::app::context::test_utils::{test_settings, TestContextBuilder};
        use sqlx::SqlitePool;
        use std::sync::Arc;

        fn create_restore_session_message() -> Message {
            Message::new_restore(None)
        }

        #[tokio::test]
        async fn routes_last_trade_index_to_handler_and_propagates_error() {
            let pool = Arc::new(SqlitePool::connect("sqlite::memory:").await.unwrap());
            sqlx::migrate!("./migrations")
                .run(pool.as_ref())
                .await
                .unwrap();

            let ctx = TestContextBuilder::new()
                .with_pool(pool)
                .with_settings(test_settings())
                .build();

            let my_keys = create_test_keys();
            let event = create_test_unwrapped_message();
            let msg = create_test_message(Action::LastTradeIndex, None);

            let result =
                handle_message_action_no_ln(&Action::LastTradeIndex, msg, &event, &my_keys, &ctx)
                    .await;

            // Routing assertion: we only require that the specific handler path is invoked
            // and its result is propagated; the exact business error is handler-owned.
            assert!(result.is_err());
        }

        #[tokio::test]
        async fn routes_restore_session_to_handler_and_returns_ok() {
            let pool = Arc::new(SqlitePool::connect("sqlite::memory:").await.unwrap());
            sqlx::migrate!("./migrations")
                .run(pool.as_ref())
                .await
                .unwrap();

            let ctx = TestContextBuilder::new()
                .with_pool(pool)
                .with_settings(test_settings())
                .build();

            let my_keys = create_test_keys();
            let event = create_test_unwrapped_message();
            let msg = create_restore_session_message();

            let result =
                handle_message_action_no_ln(&Action::RestoreSession, msg, &event, &my_keys, &ctx)
                    .await;

            assert!(result.is_ok());
        }

        #[tokio::test]
        async fn routes_orders_to_handler_and_propagates_error() {
            let pool = Arc::new(SqlitePool::connect("sqlite::memory:").await.unwrap());
            sqlx::migrate!("./migrations")
                .run(pool.as_ref())
                .await
                .unwrap();

            let ctx = TestContextBuilder::new()
                .with_pool(pool)
                .with_settings(test_settings())
                .build();

            let my_keys = create_test_keys();
            let event = create_test_unwrapped_message();
            let msg = create_test_message(Action::Orders, None);

            let result =
                handle_message_action_no_ln(&Action::Orders, msg, &event, &my_keys, &ctx).await;

            // Routing assertion: we only require that the specific handler path is invoked
            // and its result is propagated; the exact business error is handler-owned.
            assert!(result.is_err());
        }

        #[tokio::test]
        async fn routes_payinvoice_to_typed_invalid_action_error() {
            let pool = Arc::new(SqlitePool::connect("sqlite::memory:").await.unwrap());
            sqlx::migrate!("./migrations")
                .run(pool.as_ref())
                .await
                .unwrap();

            let ctx = TestContextBuilder::new()
                .with_pool(pool)
                .with_settings(test_settings())
                .build();

            let my_keys = create_test_keys();
            let event = create_test_unwrapped_message();
            let msg = create_test_message(Action::PayInvoice, None);

            let result =
                handle_message_action_no_ln(&Action::PayInvoice, msg, &event, &my_keys, &ctx).await;

            assert!(matches!(
                result,
                Err(e)
                    if e.downcast_ref::<MostroError>()
                        == Some(&MostroError::MostroCantDo(CantDoReason::InvalidAction))
            ));
        }
    }

    mod message_validation_tests {
        use super::*;

        #[test]
        fn test_signature_verification_logic() {
            let keys = create_test_keys();
            let sender_keys = create_test_keys();

            // Test sender matches rumor pubkey case
            let sender_matches_rumor = keys.public_key() == keys.public_key();
            assert!(sender_matches_rumor);

            // Test sender doesn't match rumor pubkey case
            let sender_differs = sender_keys.public_key() != keys.public_key();
            assert!(sender_differs);
        }

        #[test]
        fn test_timestamp_validation() {
            let current_time = chrono::Utc::now().timestamp() as u64;
            let old_time = current_time - 20; // 20 seconds ago
            let recent_time = current_time - 5; // 5 seconds ago

            let since_time = chrono::Utc::now()
                .checked_sub_signed(chrono::Duration::seconds(10))
                .unwrap()
                .timestamp() as u64;

            // Old event should be rejected
            assert!(old_time < since_time);

            // Recent event should be accepted
            assert!(recent_time >= since_time);
        }

        #[test]
        fn test_pow_verification_logic() {
            // Test POW validation logic structure
            // In a real implementation, we would test event.check_pow(pow)
            // This tests the logical flow
            let meets_pow = true; // Mock result
            let fails_pow = false; // Mock result

            assert!(meets_pow);
            assert!(!fails_pow);
        }
    }

    mod event_processing_tests {
        use super::*;

        #[test]
        fn test_gift_wrap_processing_structure() {
            // Test the structure of gift wrap event processing
            let kind = NostrKind::GiftWrap;

            match kind {
                NostrKind::GiftWrap => {
                    // This is the expected path for gift wrap events
                    // No-op
                }
                _ => unreachable!("Only GiftWrap events are considered in this test scope"),
            }
        }

        #[test]
        fn test_message_parsing_structure() {
            // Test message parsing logic structure
            let test_content = r#"[{"order":{"version":1,"request_id":1,"trade_index":null,"id":"550e8400-e29b-41d4-a716-446655440000","action":"new-order","payload":null}}, null]"#;

            let result = serde_json::from_str::<(Message, Option<Signature>)>(test_content);
            match result {
                Ok((message, signature)) => {
                    // Test the structure of message parsing
                    // Note: message.verify() may fail without proper payload setup
                    // We're testing the parsing structure, not the validation logic
                    assert!(signature.is_none());

                    // Test that we got a message of some kind
                    if let Message::Order(_) = message {}
                }
                Err(_) => {
                    // Parsing error is handled gracefully
                    // No-op
                }
            }
        }
    }
}