hopr_chain_actions/
redeem.rs

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
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
//! This module contains the [TicketRedeemActions] trait defining actions regarding
//! ticket redemption.
//!
//! An implementation of this trait is added to [ChainActions] which realizes the redemption
//! operations via [ActionQueue](crate::action_queue::ActionQueue).
//!
//! There are 4 functions that can be used to redeem tickets in the [TicketRedeemActions] trait:
//! - [redeem_all_tickets](TicketRedeemActions::redeem_all_tickets)
//! - [redeem_tickets_in_channel](TicketRedeemActions::redeem_tickets_in_channel)
//! - [redeem_tickets_with_counterparty](TicketRedeemActions::redeem_tickets_with_counterparty)
//! - [redeem_ticket](TicketRedeemActions::redeem_ticket)
//!
//! Each method first checks if the tickets are redeemable.
//! (= they are not marked as [BeingRedeemed](hopr_internal_types::tickets::AcknowledgedTicketStatus::BeingRedeemed) or
//! [BeingAggregated](hopr_internal_types::tickets::AcknowledgedTicketStatus::BeingAggregated) in the DB),
//! If they are redeemable, their state is changed to
//! [BeingRedeemed](hopr_internal_types::tickets::AcknowledgedTicketStatus::BeingRedeemed) (while having acquired the exclusive DB write lock).
//! Subsequently, the ticket in such a state is transmitted into the [ActionQueue](crate::action_queue::ActionQueue) so the redemption is soon executed on-chain.
//! The functions return immediately but provide futures that can be awaited in case the callers wish to await the on-chain
//! confirmation of each ticket redemption.
//!
//! See the details in [ActionQueue](crate::action_queue::ActionQueue) on how the confirmation is realized by awaiting the respective [SignificantChainEvent](hopr_chain_types::chain_events::SignificantChainEvent).
//! by the Indexer.
use async_trait::async_trait;
use futures::StreamExt;
use hopr_chain_types::actions::Action;
use hopr_crypto_types::types::Hash;
use hopr_db_sql::api::info::DomainSeparator;
use hopr_db_sql::api::tickets::{HoprDbTicketOperations, TicketSelector};
use hopr_db_sql::channels::HoprDbChannelOperations;
use hopr_db_sql::prelude::HoprDbInfoOperations;
use hopr_internal_types::prelude::*;
use hopr_primitive_types::prelude::*;
use tracing::{debug, error, info, warn};

use crate::action_queue::PendingAction;
use crate::errors::ChainActionsError::{ChannelDoesNotExist, InvalidState, OldTicket};
use crate::errors::{ChainActionsError::WrongTicketState, Result};
use crate::ChainActions;

lazy_static::lazy_static! {
    /// Used as a placeholder when the redeem transaction has not yet been published on-chain
    static ref EMPTY_TX_HASH: Hash = Hash::default();
}

/// Gathers all the ticket redemption-related on-chain calls.
#[async_trait]
pub trait TicketRedeemActions {
    /// Redeems all redeemable tickets in all channels.
    async fn redeem_all_tickets(&self, only_aggregated: bool) -> Result<Vec<PendingAction>>;

    /// Redeems all redeemable tickets in the incoming channel from the given counterparty.
    async fn redeem_tickets_with_counterparty(
        &self,
        counterparty: &Address,
        only_aggregated: bool,
    ) -> Result<Vec<PendingAction>>;

    /// Redeems all redeemable tickets in the given channel.
    async fn redeem_tickets_in_channel(
        &self,
        channel: &ChannelEntry,
        only_aggregated: bool,
    ) -> Result<Vec<PendingAction>>;

    /// Redeems all tickets based on the given [`TicketSelector`].
    async fn redeem_tickets(&self, selector: TicketSelector) -> Result<Vec<PendingAction>>;

    /// Tries to redeem the given ticket. If the ticket is not redeemable, returns an error.
    /// Otherwise, the transaction hash of the on-chain redemption is returned.
    async fn redeem_ticket(&self, ack: AcknowledgedTicket) -> Result<PendingAction>;
}

#[async_trait]
impl<Db> TicketRedeemActions for ChainActions<Db>
where
    Db: HoprDbChannelOperations + HoprDbTicketOperations + HoprDbInfoOperations + Clone + Send + Sync + std::fmt::Debug,
{
    #[tracing::instrument(level = "debug", skip(self))]
    async fn redeem_all_tickets(&self, only_aggregated: bool) -> Result<Vec<PendingAction>> {
        let incoming_channels = self
            .db
            .get_channels_via(None, ChannelDirection::Incoming, &self.self_address())
            .await?;
        debug!(
            channel_count = incoming_channels.len(),
            "starting to redeem all tickets in channels to self"
        );

        let mut receivers: Vec<PendingAction> = vec![];

        // Must be synchronous because underlying Ethereum transactions are sequential
        for incoming_channel in incoming_channels {
            match self.redeem_tickets_in_channel(&incoming_channel, only_aggregated).await {
                Ok(mut successful_txs) => {
                    receivers.append(&mut successful_txs);
                }
                Err(e) => {
                    warn!(
                        channel = %generate_channel_id(&incoming_channel.source, &incoming_channel.destination),
                        error = %e,
                        "Failed to redeem tickets in channel",
                    );
                }
            }
        }

        Ok(receivers)
    }

    #[tracing::instrument(level = "debug", skip(self))]
    async fn redeem_tickets_with_counterparty(
        &self,
        counterparty: &Address,
        only_aggregated: bool,
    ) -> Result<Vec<PendingAction>> {
        let maybe_channel = self
            .db
            .get_channel_by_parties(None, counterparty, &self.self_address(), false)
            .await?;
        if let Some(channel) = maybe_channel {
            self.redeem_tickets_in_channel(&channel, only_aggregated).await
        } else {
            Err(ChannelDoesNotExist)
        }
    }

    #[tracing::instrument(level = "debug", skip(self))]
    async fn redeem_tickets_in_channel(
        &self,
        channel: &ChannelEntry,
        only_aggregated: bool,
    ) -> Result<Vec<PendingAction>> {
        self.redeem_tickets(
            TicketSelector::from(channel)
                .with_aggregated_only(only_aggregated)
                .with_index_range(channel.ticket_index.as_u64()..)
                .with_state(AcknowledgedTicketStatus::Untouched),
        )
        .await
    }

    #[tracing::instrument(level = "debug", skip(self))]
    async fn redeem_tickets(&self, selector: TicketSelector) -> Result<Vec<PendingAction>> {
        let (count_redeemable_tickets, _) = self.db.get_tickets_value(selector.clone()).await?;

        info!(
            count_redeemable_tickets, %selector,
            "acknowledged tickets in channel that can be redeemed"
        );

        // Return fast if there are no redeemable tickets
        if count_redeemable_tickets == 0 {
            return Ok(vec![]);
        }

        let channel_dst = self
            .db
            .get_indexer_data(None)
            .await?
            .domain_separator(DomainSeparator::Channel)
            .ok_or(InvalidState("missing channel dst".into()))?;

        let selector_id = selector.to_string();

        // Collect here, so we don't hold-up the stream open for too long
        let redeem_stream = self
            .db
            .update_ticket_states_and_fetch(selector, AcknowledgedTicketStatus::BeingRedeemed)
            .await?
            .collect::<Vec<_>>()
            .await;

        let mut receivers: Vec<PendingAction> = vec![];
        for ack_ticket in redeem_stream {
            let ticket_id = ack_ticket.to_string();

            if let Ok(redeemable) = ack_ticket.into_redeemable(&self.chain_key, &channel_dst) {
                let action = self.tx_sender.send(Action::RedeemTicket(redeemable)).await;
                match action {
                    Ok(successful_tx) => {
                        receivers.push(successful_tx);
                    }
                    Err(e) => {
                        error!(ticket_id, error = %e, "Failed to submit transaction that redeems ticket",);
                    }
                }
            } else {
                error!("failed to extract redeemable ticket");
            }
        }

        info!(
            count = receivers.len(),
            selector = selector_id,
            "acknowledged tickets were submitted to redeem in channel",
        );

        Ok(receivers)
    }

    #[tracing::instrument(level = "debug", skip(self))]
    async fn redeem_ticket(&self, ack_ticket: AcknowledgedTicket) -> Result<PendingAction> {
        if let Some(channel) = self
            .db
            .get_channel_by_id(None, &ack_ticket.verified_ticket().channel_id)
            .await?
        {
            // Check if not trying to redeem a ticket that cannot be redeemed.
            // Such tickets are automatically cleaned up (neglected) after successful redemption.
            if ack_ticket.verified_ticket().index < channel.ticket_index.as_u64() {
                return Err(OldTicket);
            }

            debug!(%ack_ticket, %channel, "redeeming single ticket");

            let selector = TicketSelector::from(&channel)
                .with_index(ack_ticket.verified_ticket().index)
                .with_state(AcknowledgedTicketStatus::Untouched);

            // Do not hold up the stream open for too long
            let maybe_ticket = self
                .db
                .update_ticket_states_and_fetch(selector, AcknowledgedTicketStatus::BeingRedeemed)
                .await?
                .next()
                .await;

            if let Some(ticket) = maybe_ticket {
                let channel_dst = self
                    .db
                    .get_indexer_data(None)
                    .await?
                    .domain_separator(DomainSeparator::Channel)
                    .ok_or(InvalidState("missing channel dst".into()))?;

                let redeemable = ticket.into_redeemable(&self.chain_key, &channel_dst)?;

                debug!(%ack_ticket, "ticket is redeemable");
                Ok(self.tx_sender.send(Action::RedeemTicket(redeemable)).await?)
            } else {
                Err(WrongTicketState(ack_ticket.to_string()))
            }
        } else {
            Err(ChannelDoesNotExist)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures::FutureExt;
    use hex_literal::hex;
    use hopr_chain_types::chain_events::ChainEventType::TicketRedeemed;
    use hopr_chain_types::chain_events::SignificantChainEvent;
    use hopr_crypto_random::random_bytes;
    use hopr_crypto_types::prelude::*;
    use hopr_db_sql::api::info::DomainSeparator;
    use hopr_db_sql::db::HoprDb;
    use hopr_db_sql::errors::DbSqlError;
    use hopr_db_sql::info::HoprDbInfoOperations;
    use hopr_db_sql::{HoprDbGeneralModelOperations, TargetDb};

    use crate::action_queue::{ActionQueue, MockTransactionExecutor};
    use crate::action_state::MockActionState;

    lazy_static::lazy_static! {
        static ref ALICE: ChainKeypair = ChainKeypair::from_secret(&hex!("492057cf93e99b31d2a85bc5e98a9c3aa0021feec52c227cc8170e8f7d047775")).expect("lazy static keypair should be constructible");
        static ref BOB: ChainKeypair = ChainKeypair::from_secret(&hex!("48680484c6fc31bc881a0083e6e32b6dc789f9eaba0f8b981429fd346c697f8c")).expect("lazy static keypair should be constructible");
        static ref CHARLIE: ChainKeypair = ChainKeypair::from_secret(&hex!("d39a926980d6fa96a9eba8f8058b2beb774bc11866a386e9ddf9dc1152557c26")).expect("lazy static keypair should be constructible");
    }

    fn generate_random_ack_ticket(
        idx: u64,
        counterparty: &ChainKeypair,
        channel_epoch: u32,
    ) -> anyhow::Result<AcknowledgedTicket> {
        let hk1 = HalfKey::random();
        let hk2 = HalfKey::random();

        let cp1: CurvePoint = hk1.to_challenge().try_into()?;
        let cp2: CurvePoint = hk2.to_challenge().try_into()?;
        let cp_sum = CurvePoint::combine(&[&cp1, &cp2]);

        let price_per_packet: U256 = 10000000000000000u128.into(); // 0.01 HOPR

        Ok(TicketBuilder::default()
            .addresses(counterparty, &*ALICE)
            .amount(price_per_packet.div_f64(1.0f64)? * 5u32)
            .index(idx)
            .index_offset(1)
            .win_prob(1.0)
            .channel_epoch(channel_epoch)
            .challenge(Challenge::from(cp_sum).to_ethereum_challenge())
            .build_signed(counterparty, &Hash::default())?
            .into_acknowledged(Response::from_half_keys(&hk1, &hk2)?))
    }

    async fn create_channel_with_ack_tickets(
        db: HoprDb,
        ticket_count: usize,
        counterparty: &ChainKeypair,
        channel_epoch: u32,
    ) -> anyhow::Result<(ChannelEntry, Vec<AcknowledgedTicket>)> {
        let ckp = counterparty.clone();
        let db_clone = db.clone();
        let channel = db
            .begin_transaction()
            .await?
            .perform(|tx| {
                Box::pin(async move {
                    db_clone
                        .set_domain_separator(Some(tx), DomainSeparator::Channel, Default::default())
                        .await?;

                    let channel = ChannelEntry::new(
                        ckp.public().to_address(),
                        ALICE.public().to_address(),
                        Balance::zero(BalanceType::HOPR),
                        U256::zero(),
                        ChannelStatus::Open,
                        channel_epoch.into(),
                    );
                    db_clone.upsert_channel(Some(tx), channel).await?;
                    Ok::<_, DbSqlError>(channel)
                })
            })
            .await?;

        let ckp = counterparty.clone();
        let input_tickets = db
            .begin_transaction_in_db(TargetDb::Tickets)
            .await?
            .perform(|tx| {
                Box::pin(async move {
                    let mut input_tickets = Vec::new();
                    for i in 0..ticket_count {
                        let ack_ticket = generate_random_ack_ticket(i as u64, &ckp, channel_epoch)
                            .map_err(|e| hopr_db_sql::errors::DbSqlError::LogicalError(e.to_string()))?;
                        db.upsert_ticket(Some(tx), ack_ticket.clone()).await?;
                        input_tickets.push(ack_ticket);
                    }
                    Ok::<_, DbSqlError>(input_tickets)
                })
            })
            .await?;

        Ok((channel, input_tickets))
    }

    #[async_std::test]
    async fn test_ticket_redeem_flow() -> anyhow::Result<()> {
        let random_hash = Hash::from(random_bytes::<{ Hash::SIZE }>());

        let ticket_count = 5;
        let db = HoprDb::new_in_memory(ALICE.clone()).await?;

        // All the tickets can be redeemed because they are issued with the same channel epoch
        let (channel_from_bob, bob_tickets) =
            create_channel_with_ack_tickets(db.clone(), ticket_count, &BOB, 4u32).await?;
        let (channel_from_charlie, charlie_tickets) =
            create_channel_with_ack_tickets(db.clone(), ticket_count, &CHARLIE, 4u32).await?;

        let mut indexer_action_tracker = MockActionState::new();
        let mut seq2 = mockall::Sequence::new();

        for tkt in bob_tickets.iter().cloned() {
            indexer_action_tracker
                .expect_register_expectation()
                .once()
                .in_sequence(&mut seq2)
                .return_once(move |_| {
                    Ok(futures::future::ok(SignificantChainEvent {
                        tx_hash: random_hash,
                        event_type: TicketRedeemed(channel_from_bob, Some(tkt)),
                    })
                    .boxed())
                });
        }

        for tkt in charlie_tickets.iter().cloned() {
            indexer_action_tracker
                .expect_register_expectation()
                .once()
                .in_sequence(&mut seq2)
                .return_once(move |_| {
                    Ok(futures::future::ok(SignificantChainEvent {
                        tx_hash: random_hash,
                        event_type: TicketRedeemed(channel_from_charlie, Some(tkt)),
                    })
                    .boxed())
                });
        }

        let mut tx_exec = MockTransactionExecutor::new();
        let mut seq = mockall::Sequence::new();

        // Expect all Bob's tickets get redeemed first
        tx_exec
            .expect_redeem_ticket()
            .times(ticket_count)
            .in_sequence(&mut seq)
            .withf(move |t| bob_tickets.iter().any(|tk| tk.ticket.eq(&t.ticket)))
            .returning(move |_| Ok(random_hash));

        // and then all Charlie's tickets get redeemed
        tx_exec
            .expect_redeem_ticket()
            .times(ticket_count)
            .in_sequence(&mut seq)
            .withf(move |t| charlie_tickets.iter().any(|tk| tk.ticket.eq(&t.ticket)))
            .returning(move |_| Ok(random_hash));

        // Start the ActionQueue with the mock TransactionExecutor
        let tx_queue = ActionQueue::new(db.clone(), indexer_action_tracker, tx_exec, Default::default());
        let tx_sender = tx_queue.new_sender();
        async_std::task::spawn(async move {
            tx_queue.start().await;
        });

        let actions = ChainActions::new(&ALICE, db.clone(), tx_sender.clone());

        let confirmations = futures::future::try_join_all(actions.redeem_all_tickets(false).await?.into_iter()).await?;

        assert_eq!(2 * ticket_count, confirmations.len(), "must have all confirmations");
        assert!(
            confirmations.into_iter().all(|c| c.tx_hash == random_hash),
            "tx hashes must be equal"
        );

        let db_acks_bob = db.get_tickets((&channel_from_bob).into()).await?;

        let db_acks_charlie = db.get_tickets((&channel_from_charlie).into()).await?;

        assert!(
            db_acks_bob
                .into_iter()
                .all(|tkt| tkt.status == AcknowledgedTicketStatus::BeingRedeemed),
            "all bob's tickets must be in BeingRedeemed state"
        );
        assert!(
            db_acks_charlie
                .into_iter()
                .all(|tkt| tkt.status == AcknowledgedTicketStatus::BeingRedeemed),
            "all charlie's tickets must be in BeingRedeemed state"
        );

        Ok(())
    }

    #[async_std::test]
    async fn test_ticket_redeem_in_channel() -> anyhow::Result<()> {
        let random_hash = Hash::from(random_bytes::<{ Hash::SIZE }>());

        let ticket_count = 5;
        let db = HoprDb::new_in_memory(ALICE.clone()).await?;

        // All the tickets can be redeemed because they are issued with the same channel epoch
        let (mut channel_from_bob, bob_tickets) =
            create_channel_with_ack_tickets(db.clone(), ticket_count, &BOB, 4u32).await?;
        let (channel_from_charlie, _) =
            create_channel_with_ack_tickets(db.clone(), ticket_count, &CHARLIE, 4u32).await?;

        // Tickets with index 0 will be skipped, as that is already past
        channel_from_bob.ticket_index = 1_u32.into();
        db.upsert_channel(None, channel_from_bob.clone()).await?;

        let mut indexer_action_tracker = MockActionState::new();
        let mut seq2 = mockall::Sequence::new();

        for tkt in bob_tickets.iter().cloned() {
            indexer_action_tracker
                .expect_register_expectation()
                .once()
                .in_sequence(&mut seq2)
                .return_once(move |_| {
                    Ok(futures::future::ok(SignificantChainEvent {
                        tx_hash: random_hash,
                        event_type: TicketRedeemed(channel_from_bob, Some(tkt)),
                    })
                    .boxed())
                });
        }

        // Expect only Bob's tickets to get redeemed
        let mut tx_exec = MockTransactionExecutor::new();
        tx_exec
            .expect_redeem_ticket()
            .times(ticket_count - 1)
            .withf(move |t| bob_tickets.iter().any(|tk| tk.ticket.eq(&t.ticket)))
            .returning(move |_| Ok(random_hash));

        // Start the ActionQueue with the mock TransactionExecutor
        let tx_queue = ActionQueue::new(db.clone(), indexer_action_tracker, tx_exec, Default::default());
        let tx_sender = tx_queue.new_sender();
        async_std::task::spawn(async move {
            tx_queue.start().await;
        });

        let actions = ChainActions::new(&ALICE, db.clone(), tx_sender.clone());

        let confirmations = futures::future::try_join_all(
            actions
                .redeem_tickets_with_counterparty(&BOB.public().to_address(), false)
                .await?
                .into_iter(),
        )
        .await?;

        // First ticket is skipped, because its index is lower than the index on the channel entry
        assert_eq!(ticket_count - 1, confirmations.len(), "must have all confirmations");
        assert!(
            confirmations.into_iter().all(|c| c.tx_hash == random_hash),
            "tx hashes must be equal"
        );

        let db_acks_bob = db.get_tickets((&channel_from_bob).into()).await?;

        let db_acks_charlie = db.get_tickets((&channel_from_charlie).into()).await?;

        assert!(
            db_acks_bob
                .into_iter()
                .take_while(|tkt| tkt.verified_ticket().index != 0)
                .all(|tkt| tkt.status == AcknowledgedTicketStatus::BeingRedeemed),
            "all bob's tickets must be in BeingRedeemed state"
        );
        assert!(
            db_acks_charlie
                .into_iter()
                .all(|tkt| tkt.status == AcknowledgedTicketStatus::Untouched),
            "all charlie's tickets must be in Untouched state"
        );

        Ok(())
    }

    #[async_std::test]
    async fn test_redeem_must_not_work_for_tickets_being_aggregated_and_being_redeemed() -> anyhow::Result<()> {
        let random_hash = Hash::from(random_bytes::<{ Hash::SIZE }>());

        let ticket_count = 3;
        let db = HoprDb::new_in_memory(ALICE.clone()).await?;

        let (channel_from_bob, mut tickets) =
            create_channel_with_ack_tickets(db.clone(), ticket_count, &BOB, 4u32).await?;

        // Make the first ticket unredeemable
        tickets[0].status = AcknowledgedTicketStatus::BeingAggregated;
        let selector = TicketSelector::from(&tickets[0]).with_no_state();
        db.update_ticket_states(selector, AcknowledgedTicketStatus::BeingAggregated)
            .await?;

        // Make the second ticket unredeemable
        tickets[1].status = AcknowledgedTicketStatus::BeingRedeemed;
        let selector = TicketSelector::from(&tickets[1]).with_no_state();
        db.update_ticket_states(selector, AcknowledgedTicketStatus::BeingRedeemed)
            .await?;

        // Expect only the redeemable tickets get redeemed
        let tickets_clone = tickets.clone();
        let mut tx_exec = MockTransactionExecutor::new();
        tx_exec
            .expect_redeem_ticket()
            .times(ticket_count - 2)
            .withf(move |t| tickets_clone[2..].iter().any(|tk| tk.ticket.eq(&t.ticket)))
            .returning(move |_| Ok(random_hash));

        let mut indexer_action_tracker = MockActionState::new();
        for tkt in tickets.iter().skip(2).cloned() {
            indexer_action_tracker
                .expect_register_expectation()
                .once()
                .return_once(move |_| {
                    Ok(futures::future::ok(SignificantChainEvent {
                        tx_hash: random_hash,
                        event_type: TicketRedeemed(channel_from_bob, Some(tkt)),
                    })
                    .boxed())
                });
        }

        // Start the ActionQueue with the mock TransactionExecutor
        let tx_queue = ActionQueue::new(db.clone(), indexer_action_tracker, tx_exec, Default::default());
        let tx_sender = tx_queue.new_sender();
        async_std::task::spawn(async move {
            tx_queue.start().await;
        });

        let actions = ChainActions::new(&ALICE, db.clone(), tx_sender.clone());

        let confirmations = futures::future::try_join_all(
            actions
                .redeem_tickets_in_channel(&channel_from_bob, false)
                .await?
                .into_iter(),
        )
        .await?;

        assert_eq!(
            ticket_count - 2,
            confirmations.len(),
            "must redeem only redeemable tickets in channel"
        );

        assert!(
            actions.redeem_ticket(tickets[0].clone()).await.is_err(),
            "cannot redeem a ticket that's being aggregated"
        );

        assert!(
            actions.redeem_ticket(tickets[1].clone()).await.is_err(),
            "cannot redeem a ticket that's being redeemed"
        );

        Ok(())
    }

    #[async_std::test]
    async fn test_redeem_must_not_work_for_tickets_of_previous_epoch_being_aggregated_and_being_redeemed(
    ) -> anyhow::Result<()> {
        let ticket_count = 3;
        let ticket_from_previous_epoch_count = 2;
        let db = HoprDb::new_in_memory(ALICE.clone()).await?;
        let random_hash = Hash::from(random_bytes::<{ Hash::SIZE }>());

        // Create 1 ticket in Epoch 4
        let (channel_from_bob, mut tickets) = create_channel_with_ack_tickets(db.clone(), 1, &BOB, 4u32).await?;

        // Insert another 2 tickets in Epoch 3
        let ticket = generate_random_ack_ticket(0, &BOB, 3)?;
        db.upsert_ticket(None, ticket.clone()).await?;
        tickets.insert(0, ticket);

        let ticket = generate_random_ack_ticket(1, &BOB, 3)?;
        db.upsert_ticket(None, ticket.clone()).await?;
        tickets.insert(1, ticket);

        let tickets_clone = tickets.clone();
        let mut tx_exec = MockTransactionExecutor::new();
        tx_exec
            .expect_redeem_ticket()
            .times(ticket_count - ticket_from_previous_epoch_count)
            .withf(move |t| {
                tickets_clone[ticket_from_previous_epoch_count..]
                    .iter()
                    .any(|tk| tk.ticket.eq(&t.ticket))
            })
            .returning(move |_| Ok(random_hash));

        let mut indexer_action_tracker = MockActionState::new();
        for tkt in tickets.iter().skip(ticket_from_previous_epoch_count).cloned() {
            indexer_action_tracker
                .expect_register_expectation()
                .once()
                .return_once(move |_| {
                    Ok(futures::future::ok(SignificantChainEvent {
                        tx_hash: random_hash,
                        event_type: TicketRedeemed(channel_from_bob, Some(tkt)),
                    })
                    .boxed())
                });
        }

        // Start the ActionQueue with the mock TransactionExecutor
        let tx_queue = ActionQueue::new(db.clone(), indexer_action_tracker, tx_exec, Default::default());
        let tx_sender = tx_queue.new_sender();
        async_std::task::spawn(async move {
            tx_queue.start().await;
        });

        let actions = ChainActions::new(&ALICE, db.clone(), tx_sender.clone());

        futures::future::join_all(
            actions
                .redeem_tickets_in_channel(&channel_from_bob, false)
                .await?
                .into_iter(),
        )
        .await;

        assert!(
            actions.redeem_ticket(tickets[0].clone()).await.is_err(),
            "cannot redeem a ticket that's from the previous epoch"
        );

        Ok(())
    }

    #[async_std::test]
    async fn test_redeem_must_not_work_for_tickets_of_next_epoch_being_redeemed() -> anyhow::Result<()> {
        let ticket_count = 4;
        let ticket_from_next_epoch_count = 2;
        let db = HoprDb::new_in_memory(ALICE.clone()).await?;
        let random_hash = Hash::from(random_bytes::<{ Hash::SIZE }>());

        // Create 1 ticket in Epoch 4
        let (channel_from_bob, mut tickets) = create_channel_with_ack_tickets(db.clone(), 1, &BOB, 4u32).await?;

        // Insert another 2 tickets in Epoch 5
        let ticket = generate_random_ack_ticket(0, &BOB, 5)?;
        db.upsert_ticket(None, ticket.clone()).await?;
        tickets.insert(0, ticket);

        let ticket = generate_random_ack_ticket(1, &BOB, 5)?;
        db.upsert_ticket(None, ticket.clone()).await?;
        tickets.insert(1, ticket);

        let tickets_clone = tickets.clone();
        let mut tx_exec = MockTransactionExecutor::new();
        tx_exec
            .expect_redeem_ticket()
            .times(ticket_count - ticket_from_next_epoch_count)
            .withf(move |t| {
                tickets_clone[ticket_from_next_epoch_count..]
                    .iter()
                    .any(|tk| tk.ticket.eq(&t.ticket))
            })
            .returning(move |_| Ok(random_hash));

        let mut indexer_action_tracker = MockActionState::new();
        for tkt in tickets.iter().skip(ticket_from_next_epoch_count).cloned() {
            indexer_action_tracker
                .expect_register_expectation()
                .once()
                .return_once(move |_| {
                    Ok(futures::future::ok(SignificantChainEvent {
                        tx_hash: random_hash,
                        event_type: TicketRedeemed(channel_from_bob, Some(tkt)),
                    })
                    .boxed())
                });
        }

        // Start the ActionQueue with the mock TransactionExecutor
        let tx_queue = ActionQueue::new(db.clone(), indexer_action_tracker, tx_exec, Default::default());
        let tx_sender = tx_queue.new_sender();
        async_std::task::spawn(async move {
            tx_queue.start().await;
        });

        let actions = ChainActions::new(&ALICE, db.clone(), tx_sender.clone());

        futures::future::join_all(
            actions
                .redeem_tickets_in_channel(&channel_from_bob, false)
                .await?
                .into_iter(),
        )
        .await;

        for unredeemable_index in 0..ticket_from_next_epoch_count {
            assert!(
                actions
                    .redeem_ticket(tickets[unredeemable_index].clone())
                    .await
                    .is_err(),
                "cannot redeem a ticket that's from the next epoch"
            );
        }

        Ok(())
    }

    #[async_std::test]
    async fn test_should_redeem_single_ticket() -> anyhow::Result<()> {
        let db = HoprDb::new_in_memory(ALICE.clone()).await?;
        let random_hash = Hash::from(random_bytes::<{ Hash::SIZE }>());

        let (channel_from_bob, tickets) = create_channel_with_ack_tickets(db.clone(), 1, &BOB, 1u32).await?;

        let ticket = tickets.into_iter().next().unwrap();

        let mut tx_exec = MockTransactionExecutor::new();
        let ticket_clone = ticket.clone();
        tx_exec
            .expect_redeem_ticket()
            .once()
            .withf(move |t| ticket_clone.ticket.eq(&t.ticket))
            .returning(move |_| Ok(random_hash));

        let mut indexer_action_tracker = MockActionState::new();
        let ticket_clone = ticket.clone();
        indexer_action_tracker
            .expect_register_expectation()
            .once()
            .return_once(move |_| {
                Ok(futures::future::ok(SignificantChainEvent {
                    tx_hash: random_hash,
                    event_type: TicketRedeemed(channel_from_bob, Some(ticket_clone)),
                })
                .boxed())
            });

        // Start the ActionQueue with the mock TransactionExecutor
        let tx_queue = ActionQueue::new(db.clone(), indexer_action_tracker, tx_exec, Default::default());
        let tx_sender = tx_queue.new_sender();
        async_std::task::spawn(async move {
            tx_queue.start().await;
        });

        let actions = ChainActions::new(&ALICE, db.clone(), tx_sender.clone());

        let confirmation = actions.redeem_ticket(ticket).await?.await?;

        assert_eq!(confirmation.tx_hash, random_hash);

        assert!(
            db.get_tickets((&channel_from_bob).into())
                .await?
                .into_iter()
                .all(|tkt| tkt.status == AcknowledgedTicketStatus::BeingRedeemed),
            "all bob's tickets must be in BeingRedeemed state"
        );

        Ok(())
    }

    #[async_std::test]
    async fn test_should_not_redeem_single_ticket_with_lower_index_than_channel_index() -> anyhow::Result<()> {
        let db = HoprDb::new_in_memory(ALICE.clone()).await?;
        let random_hash = Hash::from(random_bytes::<{ Hash::SIZE }>());

        let (mut channel_from_bob, tickets) = create_channel_with_ack_tickets(db.clone(), 1, &BOB, 1u32).await?;

        channel_from_bob.ticket_index = 2_u32.into();
        db.upsert_channel(None, channel_from_bob.clone()).await?;

        let ticket = tickets.into_iter().next().unwrap();

        let mut tx_exec = MockTransactionExecutor::new();
        let ticket_clone = ticket.clone();
        tx_exec
            .expect_redeem_ticket()
            .never()
            .withf(move |t| ticket_clone.ticket.eq(&t.ticket))
            .returning(move |_| Ok(random_hash));

        let mut indexer_action_tracker = MockActionState::new();
        let ticket_clone = ticket.clone();
        indexer_action_tracker
            .expect_register_expectation()
            .never()
            .return_once(move |_| {
                Ok(futures::future::ok(SignificantChainEvent {
                    tx_hash: random_hash,
                    event_type: TicketRedeemed(channel_from_bob, Some(ticket_clone)),
                })
                .boxed())
            });

        // Start the ActionQueue with the mock TransactionExecutor
        let tx_queue = ActionQueue::new(db.clone(), indexer_action_tracker, tx_exec, Default::default());
        let tx_sender = tx_queue.new_sender();
        async_std::task::spawn(async move {
            tx_queue.start().await;
        });

        let actions = ChainActions::new(&ALICE, db.clone(), tx_sender.clone());

        assert!(matches!(actions.redeem_ticket(ticket).await, Err(OldTicket)));

        Ok(())
    }
}