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
use crate::app::context::AppContext;
use crate::db::{is_user_present, update_user_rating};
use crate::util::{enqueue_order_msg, get_order, update_user_rating_event};
use mostro_core::prelude::*;
use nostr_sdk::prelude::*;

pub fn prepare_variables_for_vote(
    message_sender: &str,
    order: &Order,
) -> Result<(String, bool, bool), MostroError> {
    let mut counterpart_trade_pubkey: String = String::new();
    let mut buyer_rating: bool = false;
    let mut seller_rating: bool = false;

    // Get needed info about users
    let (seller, buyer) = match (&order.seller_pubkey, &order.buyer_pubkey) {
        (Some(seller), Some(buyer)) => (seller.to_owned(), buyer.to_owned()),
        (None, _) => return Err(MostroInternalErr(ServiceError::InvalidPubkey)),
        (_, None) => return Err(MostroInternalErr(ServiceError::InvalidPubkey)),
    };

    // Find the counterpart public key
    if message_sender == buyer {
        buyer_rating = true;
        counterpart_trade_pubkey = order
            .get_buyer_pubkey()
            .map_err(MostroInternalErr)?
            .to_string();
    } else if message_sender == seller {
        seller_rating = true;
        counterpart_trade_pubkey = order
            .get_seller_pubkey()
            .map_err(MostroInternalErr)?
            .to_string();
    };

    Ok((counterpart_trade_pubkey, buyer_rating, seller_rating))
}

/// Updates a user's reputation based on a rating received from a trade counterpart.
///
/// This function handles the reputation update process for users after a successful trade.
/// It processes ratings from either the buyer or seller of a completed order and updates
/// the recipient's reputation metrics accordingly. The function also handles privacy mode
/// checks and ensures users can only rate their trade counterpart once.
///
/// # Arguments
///
/// * `ctx` - Application context containing the database pool and other dependencies
/// * `msg` - The message containing the rating information
/// * `event` - The unwrapped gift event containing the sender's information
/// * `my_keys` - The keys used for signing events
///
/// # Returns
///
/// * `Result<(), MostroError>` - Returns `Ok(())` if the reputation update was successful,
///   or an appropriate error if something went wrong during the process.
///
/// # Process Flow
///
/// 1. Retrieves the order information from the database
/// 2. Verifies the order status is "Success", or "SettledHoldInvoice" for seller-initiated ratings
/// 3. Determines if the rating is from buyer or seller
/// 4. Checks if the user has already rated their counterpart
/// 5. Validates privacy mode settings
/// 6. Updates the recipient's rating metrics
/// 7. Creates and saves a new rating event
/// 8. Updates the database with the new rating information
/// 9. Sends a confirmation message to the rating user
pub async fn update_user_reputation_action(
    ctx: &AppContext,
    msg: Message,
    event: &UnwrappedMessage,
    my_keys: &Keys,
) -> Result<(), MostroError> {
    let pool = ctx.pool();
    // Get order
    let order = get_order(&msg, pool).await?;

    // Prepare variables for vote
    let (counterpart_trade_pubkey, buyer_rating, seller_rating) =
        prepare_variables_for_vote(&event.sender.to_string(), &order)?;

    // Check if order is success, but sellers can rate in status settled-hold-invoice
    if !(order.check_status(Status::Success).is_ok()
        || (order.check_status(Status::SettledHoldInvoice).is_ok() && seller_rating))
    {
        return Err(MostroCantDo(CantDoReason::InvalidOrderStatus));
    }

    // Check if the order is not rated by the message sender
    // Check what rate status needs update
    let mut update_seller_rate = false;
    let mut update_buyer_rate = false;
    if seller_rating && !order.seller_sent_rate {
        update_seller_rate = true;
    } else if buyer_rating && !order.buyer_sent_rate {
        update_buyer_rate = true;
    };
    if !update_buyer_rate && !update_seller_rate {
        return Ok(());
    };

    // Get rating from message
    let new_rating = msg
        .get_inner_message_kind()
        .get_rating()
        .map_err(MostroInternalErr)?;

    // Check if users are in full privacy mode
    let (normal_buyer_idkey, normal_seller_idkey) = order
        .is_full_privacy_order()
        .map_err(|_| MostroInternalErr(ServiceError::InvalidPubkey))?;

    // Get counter to vote from db, but only if they're not in privacy mode
    let mut user_to_vote = if buyer_rating {
        // If buyer is rating seller, check if seller is in privacy mode
        if let Some(seller_key) = normal_seller_idkey {
            is_user_present(pool, seller_key).await.map_err(|cause| {
                MostroInternalErr(ServiceError::DbAccessError(cause.to_string()))
            })?
        } else {
            return Ok(());
        }
    } else {
        // If seller is rating buyer, check if buyer is in privacy mode
        if let Some(buyer_key) = normal_buyer_idkey {
            is_user_present(pool, buyer_key).await.map_err(|cause| {
                MostroInternalErr(ServiceError::DbAccessError(cause.to_string()))
            })?
        } else {
            return Ok(());
        }
    };

    // Calculate new rating
    user_to_vote.update_rating(new_rating);

    // Create new rating event
    let reputation_event = Rating::new(
        user_to_vote.total_reviews as u64,
        user_to_vote.total_rating as f64,
        user_to_vote.last_rating as u8,
        user_to_vote.min_rating as u8,
        user_to_vote.max_rating as u8,
    )
    .to_tags()
    .map_err(|cause| MostroInternalErr(ServiceError::NostrError(cause.to_string())))?;

    // Calculate days since user creation and add to rating tags
    let days = calculate_days_since_creation(user_to_vote.created_at);
    let mut tags: Vec<Tag> = reputation_event.into_iter().collect();
    tags.push(Tag::custom(
        TagKind::Custom(std::borrow::Cow::Borrowed("days")),
        vec![days.to_string()],
    ));
    let reputation_event = Tags::from_list(tags);

    // Save new rating to db
    if let Err(e) = update_user_rating(
        pool,
        user_to_vote.pubkey,
        user_to_vote.last_rating,
        user_to_vote.min_rating,
        user_to_vote.max_rating,
        user_to_vote.total_reviews,
        user_to_vote.total_rating,
    )
    .await
    {
        return Err(MostroInternalErr(ServiceError::DbAccessError(format!(
            "Error updating user rating : {}",
            e
        ))));
    }

    if buyer_rating || seller_rating {
        // Update db with rate flags
        update_user_rating_event(
            &counterpart_trade_pubkey,
            update_buyer_rate,
            update_seller_rate,
            reputation_event,
            &msg,
            my_keys,
            pool,
        )
        .await
        .map_err(|cause| {
            MostroInternalErr(ServiceError::DbAccessError(format!(
                "Error updating user rating event : {}",
                cause
            )))
        })?;

        // Send confirmation message to user that rated
        enqueue_order_msg(
            msg.get_inner_message_kind().request_id,
            Some(order.id),
            Action::RateReceived,
            Some(Payload::RatingUser(new_rating)),
            event.sender,
            None,
        )
        .await;
    }

    Ok(())
}

/// Calculate the number of days since user creation.
fn calculate_days_since_creation(created_at: i64) -> u64 {
    const SECONDS_IN_DAY: u64 = 86_400;
    let now = Timestamp::now().as_secs();
    u64::try_from(created_at)
        .ok()
        .filter(|ts| *ts > 0)
        .map(|ts| now.saturating_sub(ts) / SECONDS_IN_DAY)
        .unwrap_or(0)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::settings::Settings;
    use crate::config::MOSTRO_CONFIG;
    use mostro_core::message::{MessageKind, Payload};
    use mostro_core::order::Order;
    use nostr_sdk::{Keys, Timestamp};
    use sqlx::SqlitePool;
    use sqlx_crud::Crud;
    use uuid::Uuid;

    fn init_test_settings() {
        let _ = MOSTRO_CONFIG.set(Settings {
            database: Default::default(),
            nostr: Default::default(),
            mostro: Default::default(),
            lightning: Default::default(),
            rpc: Default::default(),
            expiration: Some(Default::default()),
            anti_abuse_bond: None,
        });
    }

    async fn create_test_pool() -> SqlitePool {
        init_test_settings();
        let pool = SqlitePool::connect("sqlite::memory:").await.unwrap();
        sqlx::migrate!().run(&pool).await.unwrap();
        pool
    }

    fn create_test_keys() -> Keys {
        Keys::generate()
    }

    /// Build an `UnwrappedMessage` whose trade key (rumor author / `sender`)
    /// is `pubkey` — these tests gate on `event.sender` to identify
    /// buyer/seller — and whose identity key is generated separately so the
    /// fixture exercises the dual-key flow rather than full-privacy mode.
    fn create_unwrapped_message_with_pubkey(pubkey: PublicKey) -> UnwrappedMessage {
        UnwrappedMessage {
            message: Message::Order(MessageKind::new(
                Some(Uuid::new_v4()),
                Some(1),
                None,
                Action::RateUser,
                None,
            )),
            signature: None,
            sender: pubkey,
            identity: Keys::generate().public_key(),
            created_at: Timestamp::now(),
        }
    }

    fn create_rate_user_message(order_id: Uuid, rating: u8) -> Message {
        let kind = MessageKind::new(
            Some(order_id),
            Some(1),
            None,
            Action::RateUser,
            Some(Payload::RatingUser(rating)),
        );
        Message::Order(kind)
    }

    fn create_test_order(
        status: Status,
        seller_pubkey: PublicKey,
        buyer_pubkey: PublicKey,
    ) -> Order {
        Order {
            id: Uuid::new_v4(),
            status: status.to_string(),
            seller_pubkey: Some(seller_pubkey.to_string()),
            buyer_pubkey: Some(buyer_pubkey.to_string()),
            seller_sent_rate: false,
            buyer_sent_rate: false,
            ..Default::default()
        }
    }

    #[tokio::test]
    async fn test_update_user_reputation_allows_success_status() {
        let pool = create_test_pool().await;
        use crate::app::context::test_utils::{test_settings, TestContextBuilder};
        let ctx = TestContextBuilder::new()
            .with_pool(std::sync::Arc::new(pool.clone()))
            .with_settings(test_settings())
            .build();
        let keys = create_test_keys();

        let seller_keys = create_test_keys();
        let buyer_keys = create_test_keys();
        let seller_pk = seller_keys.public_key();
        let buyer_pk = buyer_keys.public_key();

        // Event where the sender is the seller (so seller_rating = true)
        let event = create_unwrapped_message_with_pubkey(seller_pk);

        // Insert Success order in DB
        let order = create_test_order(Status::Success, seller_pk, buyer_pk);
        let order = order.create(&pool).await.unwrap();

        // Message pointing to that order id with a valid rating payload
        let msg = create_rate_user_message(order.id, 5);

        let result = update_user_reputation_action(&ctx, msg, &event, &keys).await;

        // A Success order must not be rejected with InvalidOrderStatus
        if let Err(MostroCantDo(CantDoReason::InvalidOrderStatus)) = result {
            panic!("valid Success status must not be rejected");
        }
    }

    #[tokio::test]
    async fn test_update_user_reputation_rejects_settled_hold_invoice_buyer() {
        let pool = create_test_pool().await;
        use crate::app::context::test_utils::{test_settings, TestContextBuilder};
        let ctx = TestContextBuilder::new()
            .with_pool(std::sync::Arc::new(pool.clone()))
            .with_settings(test_settings())
            .build();
        let keys = create_test_keys();

        let seller_keys = create_test_keys();
        let buyer_keys = create_test_keys();
        let seller_pk = seller_keys.public_key();
        let buyer_pk = buyer_keys.public_key();

        // Event where the sender is the buyer (so buyer_rating = true)
        let event = create_unwrapped_message_with_pubkey(buyer_pk);

        // SettledHoldInvoice order in DB
        let order = create_test_order(Status::SettledHoldInvoice, seller_pk, buyer_pk);
        let order = order.create(&pool).await.unwrap();

        let msg = create_rate_user_message(order.id, 5);

        let result = update_user_reputation_action(&ctx, msg, &event, &keys).await;

        // Buyer must not be allowed to rate in SettledHoldInvoice status
        match result {
            Err(MostroCantDo(CantDoReason::InvalidOrderStatus)) => {}
            _ => panic!("buyer should not be able to rate SettledHoldInvoice order"),
        }
    }

    #[tokio::test]
    async fn test_update_user_reputation_updates_buyer_and_order_flags() {
        use crate::db::{add_new_user, is_user_present};

        let pool = create_test_pool().await;
        use crate::app::context::test_utils::{test_settings, TestContextBuilder};
        let ctx = TestContextBuilder::new()
            .with_pool(std::sync::Arc::new(pool.clone()))
            .with_settings(test_settings())
            .build();
        let keys = create_test_keys();

        // Trade keys (ephemeral per-trade)
        let seller_keys = create_test_keys();
        let buyer_keys = create_test_keys();
        let seller_pk = seller_keys.public_key();
        let buyer_pk = buyer_keys.public_key();

        // Identity keys (master keys, must differ from trade keys)
        let seller_id_keys = create_test_keys();
        let buyer_id_keys = create_test_keys();
        let seller_id = seller_id_keys.public_key().to_string();
        let buyer_id = buyer_id_keys.public_key().to_string();

        // Counterpart user (seller identity) exists in DB so rating can be applied
        let seller_user = User {
            pubkey: seller_id.clone(),
            ..Default::default()
        };
        add_new_user(&pool, seller_user).await.unwrap();

        // Success order with master keys set (not full-privacy)
        let mut order = create_test_order(Status::Success, seller_pk, buyer_pk);
        order.master_seller_pubkey = Some(seller_id.clone());
        order.master_buyer_pubkey = Some(buyer_id.clone());
        let order = order.create(&pool).await.unwrap();

        // Event where sender is the buyer (buyer_rating = true)
        let event = create_unwrapped_message_with_pubkey(buyer_pk);
        let msg = create_rate_user_message(order.id, 5);

        let result = update_user_reputation_action(&ctx, msg, &event, &keys).await;
        assert!(result.is_ok());

        // The seller (counterpart of buyer rating) must have updated reputation
        let seller_user = is_user_present(&pool, seller_id).await.unwrap();
        assert_eq!(seller_user.total_reviews, 1);
        assert_eq!(seller_user.last_rating, 5);
        assert_eq!(seller_user.min_rating, 5);
        assert_eq!(seller_user.max_rating, 5);
        // First vote uses weight 1/2: total_rating = rating / 2.0
        assert!((seller_user.total_rating - 2.5).abs() < f64::EPSILON);

        // Order buyer_sent_rate flag must be set via update_user_rating_event
        let updated_order = Order::by_id(&pool, order.id)
            .await
            .unwrap()
            .expect("order not found");
        assert!(updated_order.buyer_sent_rate);
    }

    #[tokio::test]
    async fn test_update_user_reputation_buyer_already_rated_is_noop() {
        use crate::db::{add_new_user, is_user_present};

        let pool = create_test_pool().await;
        use crate::app::context::test_utils::{test_settings, TestContextBuilder};
        let ctx = TestContextBuilder::new()
            .with_pool(std::sync::Arc::new(pool.clone()))
            .with_settings(test_settings())
            .build();
        let keys = create_test_keys();

        let seller_keys = create_test_keys();
        let buyer_keys = create_test_keys();
        let seller_pk = seller_keys.public_key();
        let buyer_pk = buyer_keys.public_key();

        let seller_id_keys = create_test_keys();
        let buyer_id_keys = create_test_keys();
        let seller_id = seller_id_keys.public_key().to_string();
        let buyer_id = buyer_id_keys.public_key().to_string();

        let seller_user = User {
            pubkey: seller_id.clone(),
            ..Default::default()
        };
        add_new_user(&pool, seller_user).await.unwrap();

        // Order where buyer has already rated
        let mut order = create_test_order(Status::Success, seller_pk, buyer_pk);
        order.master_seller_pubkey = Some(seller_id.clone());
        order.master_buyer_pubkey = Some(buyer_id.clone());
        order.buyer_sent_rate = true;
        let order = order.create(&pool).await.unwrap();

        // Buyer tries to rate again
        let event = create_unwrapped_message_with_pubkey(buyer_pk);
        let msg = create_rate_user_message(order.id, 5);

        let result = update_user_reputation_action(&ctx, msg, &event, &keys).await;
        assert!(result.is_ok());

        // Seller reputation must remain unchanged (no double-rating)
        let seller_user = is_user_present(&pool, seller_id).await.unwrap();
        assert_eq!(seller_user.total_reviews, 0);
        assert!((seller_user.total_rating - 0.0).abs() < f64::EPSILON);
    }

    #[tokio::test]
    async fn test_update_user_reputation_updates_seller_and_order_flags() {
        use crate::db::{add_new_user, is_user_present};

        let pool = create_test_pool().await;
        use crate::app::context::test_utils::{test_settings, TestContextBuilder};
        let ctx = TestContextBuilder::new()
            .with_pool(std::sync::Arc::new(pool.clone()))
            .with_settings(test_settings())
            .build();
        let keys = create_test_keys();

        // Trade keys (ephemeral per-trade)
        let seller_keys = create_test_keys();
        let buyer_keys = create_test_keys();
        let seller_pk = seller_keys.public_key();
        let buyer_pk = buyer_keys.public_key();

        // Identity keys (master keys, must differ from trade keys)
        let seller_id_keys = create_test_keys();
        let buyer_id_keys = create_test_keys();
        let seller_id = seller_id_keys.public_key().to_string();
        let buyer_id = buyer_id_keys.public_key().to_string();

        // Counterpart user (buyer identity) exists in DB so rating can be applied
        let buyer_user = User {
            pubkey: buyer_id.clone(),
            ..Default::default()
        };
        add_new_user(&pool, buyer_user).await.unwrap();

        // Success order with master keys set (not full-privacy)
        let mut order = create_test_order(Status::Success, seller_pk, buyer_pk);
        order.master_seller_pubkey = Some(seller_id.clone());
        order.master_buyer_pubkey = Some(buyer_id.clone());
        let order = order.create(&pool).await.unwrap();

        // Event where sender is the seller (seller_rating = true)
        let event = create_unwrapped_message_with_pubkey(seller_pk);
        let msg = create_rate_user_message(order.id, 4);

        let result = update_user_reputation_action(&ctx, msg, &event, &keys).await;
        assert!(result.is_ok());

        // The buyer (counterpart of seller rating) must have updated reputation
        let buyer_user = is_user_present(&pool, buyer_id).await.unwrap();
        assert_eq!(buyer_user.total_reviews, 1);
        assert_eq!(buyer_user.last_rating, 4);
        assert_eq!(buyer_user.min_rating, 4);
        assert_eq!(buyer_user.max_rating, 4);
        // First vote uses weight 1/2: total_rating = rating / 2.0
        assert!((buyer_user.total_rating - 2.0).abs() < f64::EPSILON);

        // Order seller_sent_rate flag must be set via update_user_rating_event
        let updated_order = Order::by_id(&pool, order.id)
            .await
            .unwrap()
            .expect("order not found");
        assert!(updated_order.seller_sent_rate);
    }

    #[test]
    fn test_prepare_variables_for_vote_buyer() {
        let seller_keys = create_test_keys();
        let buyer_keys = create_test_keys();
        let order = create_test_order(
            Status::Success,
            seller_keys.public_key(),
            buyer_keys.public_key(),
        );

        let result = prepare_variables_for_vote(&buyer_keys.public_key().to_string(), &order);

        assert!(result.is_ok());
        let (_, buyer_rating, seller_rating) = result.unwrap();
        assert!(buyer_rating);
        assert!(!seller_rating);
    }

    #[test]
    fn test_prepare_variables_for_vote_seller() {
        let seller_keys = create_test_keys();
        let buyer_keys = create_test_keys();
        let order = create_test_order(
            Status::Success,
            seller_keys.public_key(),
            buyer_keys.public_key(),
        );

        let result = prepare_variables_for_vote(&seller_keys.public_key().to_string(), &order);

        assert!(result.is_ok());
        let (_, buyer_rating, seller_rating) = result.unwrap();
        assert!(!buyer_rating);
        assert!(seller_rating);
    }

    #[test]
    fn test_rating_validation_success_status() {
        let seller_keys = create_test_keys();
        let buyer_keys = create_test_keys();
        let order = create_test_order(
            Status::Success,
            seller_keys.public_key(),
            buyer_keys.public_key(),
        );

        // Both buyer and seller should be able to rate in Success status
        assert!(order.check_status(Status::Success).is_ok());

        // Test seller rating validation
        let (_, _, seller_rating) =
            prepare_variables_for_vote(&seller_keys.public_key().to_string(), &order).unwrap();
        let can_rate_seller = order.check_status(Status::Success).is_ok()
            || (order.check_status(Status::SettledHoldInvoice).is_ok() && seller_rating);
        assert!(can_rate_seller);

        // Test buyer rating validation
        let (_, buyer_rating, _) =
            prepare_variables_for_vote(&buyer_keys.public_key().to_string(), &order).unwrap();
        let can_rate_buyer = order.check_status(Status::Success).is_ok()
            || (order.check_status(Status::SettledHoldInvoice).is_ok() && !buyer_rating);
        assert!(can_rate_buyer);
    }

    #[test]
    fn test_rating_validation_settled_hold_invoice_seller() {
        let seller_keys = create_test_keys();
        let buyer_keys = create_test_keys();
        let order = create_test_order(
            Status::SettledHoldInvoice,
            seller_keys.public_key(),
            buyer_keys.public_key(),
        );

        // Seller should be able to rate in SettledHoldInvoice status
        let (_, _, seller_rating) =
            prepare_variables_for_vote(&seller_keys.public_key().to_string(), &order).unwrap();
        let can_rate_seller = order.check_status(Status::Success).is_ok()
            || (order.check_status(Status::SettledHoldInvoice).is_ok() && seller_rating);
        assert!(can_rate_seller);
    }

    #[test]
    fn test_rating_validation_settled_hold_invoice_buyer_denied() {
        let seller_keys = create_test_keys();
        let buyer_keys = create_test_keys();
        let order = create_test_order(
            Status::SettledHoldInvoice,
            seller_keys.public_key(),
            buyer_keys.public_key(),
        );

        // Buyer should NOT be able to rate in SettledHoldInvoice status
        let (_, buyer_rating, _) =
            prepare_variables_for_vote(&buyer_keys.public_key().to_string(), &order).unwrap();
        let can_rate_buyer = order.check_status(Status::Success).is_ok()
            || (order.check_status(Status::SettledHoldInvoice).is_ok() && !buyer_rating);
        assert!(!can_rate_buyer);
    }

    #[test]
    fn test_rating_validation_invalid_status() {
        let seller_keys = create_test_keys();
        let buyer_keys = create_test_keys();
        let order = create_test_order(
            Status::Pending,
            seller_keys.public_key(),
            buyer_keys.public_key(),
        );

        // Neither buyer nor seller should be able to rate in Pending status
        let (_, buyer_rating, seller_rating) =
            prepare_variables_for_vote(&seller_keys.public_key().to_string(), &order).unwrap();

        let can_rate_seller = order.check_status(Status::Success).is_ok()
            || (order.check_status(Status::SettledHoldInvoice).is_ok() && seller_rating);
        assert!(!can_rate_seller);

        let can_rate_buyer = order.check_status(Status::Success).is_ok()
            || (order.check_status(Status::SettledHoldInvoice).is_ok() && !buyer_rating);
        assert!(!can_rate_buyer);
    }

    #[test]
    fn test_calculate_days_since_creation_normal() {
        let now = Timestamp::now().as_secs();
        // User created 10 days ago
        let created_at = (now - 10 * 86_400) as i64;
        let days = calculate_days_since_creation(created_at);
        assert_eq!(days, 10);
    }

    #[test]
    fn test_calculate_days_since_creation_zero() {
        // New user with created_at = 0 should return 0 days
        let days = calculate_days_since_creation(0);
        assert_eq!(days, 0);
    }

    #[test]
    fn test_calculate_days_since_creation_negative() {
        // Corrupted created_at should return 0 days
        let days = calculate_days_since_creation(-1);
        assert_eq!(days, 0);
    }

    #[test]
    fn test_calculate_days_since_creation_partial_day() {
        let now = Timestamp::now().as_secs();
        // Created 1.5 days ago - should truncate to 1
        let created_at = (now - 86_400 - 43_200) as i64;
        let days = calculate_days_since_creation(created_at);
        assert_eq!(days, 1);
    }
}