hopr-types 1.8.0

Complete collection of Rust types used in Hoprnet and other related projects
Documentation
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
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
use std::{
    cmp::Ordering,
    fmt::{Display, Formatter},
    str::FromStr,
};

use crate::crypto::prelude::*;
use crate::primitive::prelude::*;
use hex_literal::hex;
use tracing::{error, instrument};

use crate::internal::prelude::ChannelBuilder;
use crate::internal::{
    errors,
    errors::CoreTypesError,
    prelude::{ChannelId, CoreTypesError::InvalidInputData, generate_channel_id},
};

/// Custom float to integer encoding used in the integer-only
/// Ethereum Virtual Machine (EVM). Chosen to be easily
/// convertible to IEEE754 double-precision and vice versa
const ENCODED_WIN_PROB_LENGTH: usize = 7;

/// Define the selector for the redeemTicketCall to avoid importing
/// the entire hopr-bindings crate for one single constant.
/// This value should be updated with the function interface changes.
pub const REDEEM_CALL_SELECTOR: [u8; 4] = [101, 227, 250, 114];

/// Winning probability encoded in 7-byte representation
pub type EncodedWinProb = [u8; ENCODED_WIN_PROB_LENGTH];

/// Represents a ticket-winning probability.
///
/// It holds the modified IEEE-754 representation but behaves like a reduced precision float.
/// It intentionally does not implement `Ord` or `Eq`, as
/// it can be either [approximately compared](WinningProbability::approx_cmp) or
/// [lexicographically compared](WinningProbability::lex_cmp).
#[derive(Clone, Copy, Debug, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct WinningProbability(
    #[cfg_attr(feature = "serde", serde(with = "serde_bytes"))] EncodedWinProb,
);

impl WinningProbability {
    /// 100% winning probability
    pub const ALWAYS: Self = Self([0xff; ENCODED_WIN_PROB_LENGTH]);
    /// Tolerance threshold for approximate floating-point probability comparisons.
    ///
    /// Two probabilities whose absolute difference is below this value are treated
    /// as equal by [`Self::approx_cmp`]/[`Self::approx_eq`], and values within
    /// this tolerance of `0.0` or `1.0` are snapped to [`Self::NEVER`] / [`Self::ALWAYS`]
    /// by [`Self::try_from_f64`].
    pub const EPSILON: f64 = 0.00000001;
    /// 0% winning probability.
    pub const NEVER: Self = Self([0u8; ENCODED_WIN_PROB_LENGTH]);

    /// Converts winning probability to an unsigned integer (luck).
    pub fn as_luck(&self) -> u64 {
        let mut tmp = [0u8; 8];
        tmp[1..].copy_from_slice(&self.0);
        u64::from_be_bytes(tmp)
    }

    /// Convenience function to convert to internal probability representation.
    pub fn as_encoded(&self) -> EncodedWinProb {
        self.0
    }

    /// Convert probability to a float.
    pub fn as_f64(&self) -> f64 {
        if self.0.eq(&Self::NEVER.0) {
            return 0.0;
        }

        if self.0.eq(&Self::ALWAYS.0) {
            return 1.0;
        }

        let mut tmp = [0u8; 8];
        tmp[1..].copy_from_slice(&self.0);

        let tmp = u64::from_be_bytes(tmp);

        // project interval [0x0fffffffffffff, 0x0000000000000f] to [0x00000000000010, 0x10000000000000]
        let significand: u64 = tmp + 1;

        f64::from_bits((1023u64 << 52) | (significand >> 4)) - 1.0
    }

    /// Tries to get probability from a float.
    pub fn try_from_f64(win_prob: f64) -> errors::Result<Self> {
        // Also makes sure the input value is not NaN or infinite.
        if !(0.0..=1.0).contains(&win_prob) {
            return Err(InvalidInputData(
                "winning probability must be in [0.0, 1.0]".into(),
            ));
        }

        if f64_approx_eq(0.0, win_prob, Self::EPSILON) {
            return Ok(Self::NEVER);
        }

        if f64_approx_eq(1.0, win_prob, Self::EPSILON) {
            return Ok(Self::ALWAYS);
        }

        let tmp: u64 = (win_prob + 1.0).to_bits();

        // // clear sign and exponent
        let significand: u64 = tmp & 0x000fffffffffffffu64;

        // project interval [0x10000000000000, 0x00000000000010] to [0x0000000000000f, 0x0fffffffffffff]
        let encoded = ((significand - 1) << 4) | 0x000000000000000fu64;

        let mut res = [0u8; 7];
        res.copy_from_slice(&encoded.to_be_bytes()[1..]);

        Ok(Self(res))
    }

    /// Performs approximate comparison up to [`Self::EPSILON`].
    pub fn approx_cmp(&self, other: &Self) -> Ordering {
        let a = self.as_f64();
        let b = other.as_f64();
        if !f64_approx_eq(a, b, Self::EPSILON) {
            a.partial_cmp(&b)
                .expect("finite non-NaN f64 comparison cannot fail")
        } else {
            Ordering::Equal
        }
    }

    /// Performs approximate equality comparison up to [`Self::EPSILON`].
    pub fn approx_eq(&self, other: &Self) -> bool {
        self.approx_cmp(other).is_eq()
    }

    /// Performs lexicographical comparison of the [luck values](Self::as_luck).
    pub fn lex_cmp(&self, other: &Self) -> Ordering {
        self.as_luck().cmp(&other.as_luck())
    }

    /// Performs lexicographical equality comparison of the [luck values](Self::as_luck).
    pub fn lex_eq(&self, other: &Self) -> bool {
        self.lex_cmp(other).is_eq()
    }

    /// Gets the minimum of two winning probabilities.
    pub fn min(&self, other: &Self) -> Self {
        if self.approx_cmp(other) == Ordering::Less {
            *self
        } else {
            *other
        }
    }

    /// Gets the maximum of two winning probabilities.
    pub fn max(&self, other: &Self) -> Self {
        if self.approx_cmp(other) == Ordering::Greater {
            *self
        } else {
            *other
        }
    }
}

impl Default for WinningProbability {
    fn default() -> Self {
        Self::ALWAYS
    }
}

impl Display for WinningProbability {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:.8}", self.as_f64())
    }
}

impl FromStr for WinningProbability {
    type Err = CoreTypesError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        f64::from_str(s)
            .map_err(|e| {
                CoreTypesError::ParseError(format!("failed to parse winning probability: {e}"))
            })
            .and_then(|v| v.try_into())
    }
}

impl From<EncodedWinProb> for WinningProbability {
    fn from(value: EncodedWinProb) -> Self {
        Self(value)
    }
}

impl<'a> From<&'a EncodedWinProb> for WinningProbability {
    fn from(value: &'a EncodedWinProb) -> Self {
        Self(*value)
    }
}

impl From<WinningProbability> for EncodedWinProb {
    fn from(value: WinningProbability) -> Self {
        value.0
    }
}

impl From<u64> for WinningProbability {
    fn from(value: u64) -> Self {
        let mut ret = Self::default();
        ret.0.copy_from_slice(&value.to_be_bytes()[1..]);
        ret
    }
}

impl TryFrom<f64> for WinningProbability {
    type Error = CoreTypesError;

    fn try_from(value: f64) -> Result<Self, Self::Error> {
        Self::try_from_f64(value)
    }
}

impl From<WinningProbability> for f64 {
    fn from(value: WinningProbability) -> Self {
        value.as_f64()
    }
}

impl PartialEq<f64> for WinningProbability {
    fn eq(&self, other: &f64) -> bool {
        f64_approx_eq(self.as_f64(), *other, Self::EPSILON)
    }
}

impl PartialEq<WinningProbability> for f64 {
    fn eq(&self, other: &WinningProbability) -> bool {
        f64_approx_eq(*self, other.as_f64(), WinningProbability::EPSILON)
    }
}

impl PartialEq<EncodedWinProb> for WinningProbability {
    fn eq(&self, other: &EncodedWinProb) -> bool {
        self.0.eq(other)
    }
}

impl AsRef<[u8]> for WinningProbability {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl<'a> TryFrom<&'a [u8]> for WinningProbability {
    type Error = GeneralError;

    fn try_from(value: &'a [u8]) -> Result<Self, Self::Error> {
        value
            .try_into()
            .map(Self)
            .map_err(|_| GeneralError::ParseError("WinningProbability".into()))
    }
}

impl BytesRepresentable for WinningProbability {
    const SIZE: usize = ENCODED_WIN_PROB_LENGTH;
}

/// Helper function checks if the given ticket values belong to a winning ticket.
///
/// This function is inexpensive to compute.
pub(crate) fn check_ticket_win(
    ticket_hash: &Hash,
    ticket_signature: &Signature,
    win_prob: &WinningProbability,
    response: &Response,
    vrf_params: &VrfParameters,
) -> bool {
    // Computed winning probability
    let mut computed_ticket_luck = [0u8; 8];
    computed_ticket_luck[1..].copy_from_slice(
        &Hash::create(&[
            ticket_hash.as_ref(),
            &vrf_params.get_v_encoded_point().as_bytes()[1..], // skip prefix
            response.as_ref(),
            ticket_signature.as_ref(),
        ])
        .as_ref()[0..7],
    );

    u64::from_be_bytes(computed_ticket_luck) <= win_prob.as_luck()
}

/// A ticket is uniquely identified by its channel id, ticket index and epoch.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TicketId {
    pub id: ChannelId,
    pub epoch: u32,
    pub index: u64,
}

impl Display for TicketId {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "ticket #{}, epoch {} in channel {}",
            self.index, self.epoch, self.id
        )
    }
}

impl From<&VerifiedTicket> for TicketId {
    fn from(value: &VerifiedTicket) -> Self {
        Self {
            id: value.channel_id,
            epoch: value.ticket.channel_epoch,
            index: value.ticket.index,
        }
    }
}

/// Builder for the [`Ticket`] and [`VerifiedTicket`].
///
/// A new builder is created via [`TicketBuilder::default`] or [`TicketBuilder::zero_hop`].
///
/// Input validation is performed upon calling [`TicketBuilder::build`], [`TicketBuilder::build_signed`]
/// and [`TicketBuilder::build_verified`].
#[derive(Debug, Copy, Clone, smart_default::SmartDefault)]
pub struct TicketBuilder {
    counterparty: Option<Address>,
    amount: Option<U256>,
    balance: Option<HoprBalance>,
    #[default = 0]
    index: u64,
    #[default = 1]
    channel_epoch: u32,
    win_prob: WinningProbability,
    challenge: Option<EthereumChallenge>,
    signature: Option<Signature>,
}

impl TicketBuilder {
    /// Maximum number of tokens that can be transferred in a single ticket: 10^25 wxHOPR.
    pub const MAX_TICKET_AMOUNT: u128 = ChannelBuilder::MAX_FUNDING_AMOUNT;
    /// Maximum ticket index in a single channel epoch: 2^48 - 1.
    pub const MAX_TICKET_INDEX: u64 = (1_u64 << 48) - 1;
    /// Maximum channel epoch: 2^24 - 1.
    pub const MAX_CHANNEL_EPOCH: u32 = (1_u32 << 24) - 1;

    /// Initializes the builder for a zero-hop ticket.
    #[must_use]
    pub fn zero_hop() -> Self {
        Self {
            index: 0,
            amount: Some(U256::zero()),
            win_prob: WinningProbability::NEVER,
            channel_epoch: 0,
            ..Default::default()
        }
    }

    /// Sets the counterparty (recipient) of the ticket.
    #[must_use]
    pub fn counterparty<A: Into<Address>>(mut self, counterparty: A) -> Self {
        self.counterparty = Some(counterparty.into());
        self
    }

    /// Sets the ticket amount in wei wxHOPR.
    ///
    /// This or [`TicketBuilder::balance`] must be set and be less or equal to 10^25 - 1.
    #[must_use]
    pub fn amount<T: Into<U256>>(mut self, amount: T) -> Self {
        self.amount = Some(amount.into());
        self.balance = None;
        self
    }

    /// Sets the ticket amount as HOPR balance.
    ///
    /// This or [`TicketBuilder::amount`] must be set and be less or equal to 10^25 - 1.
    #[must_use]
    pub fn balance(mut self, balance: HoprBalance) -> Self {
        self.balance = Some(balance);
        self.amount = None;
        self
    }

    /// Sets the ticket index.
    ///
    /// Must be less or equal to 2^48 - 1.
    ///
    /// Defaults to 0.
    #[must_use]
    pub fn index(mut self, index: u64) -> Self {
        self.index = index;
        self
    }

    /// Sets the channel epoch.
    ///
    /// Must be less or equal to 2^24 - 1.
    ///
    /// Defaults to 1.
    #[must_use]
    pub fn channel_epoch(mut self, channel_epoch: u32) -> Self {
        self.channel_epoch = channel_epoch;
        self
    }

    /// Sets the ticket winning probability.
    ///
    /// Defaults to 1.0
    #[must_use]
    pub fn win_prob(mut self, win_prob: WinningProbability) -> Self {
        self.win_prob = win_prob;
        self
    }

    /// Sets the [`Challenge`] for the Proof of Relay, converting it to [`EthereumChallenge`] first.
    ///
    /// Either this method or [`TicketBuilder::eth_challenge`] must be called.
    #[must_use]
    pub fn challenge(mut self, challenge: Challenge) -> Self {
        self.challenge = Some(challenge.to_ethereum_challenge());
        self
    }

    /// Sets the [`EthereumChallenge`] for the Proof of Relay.
    ///
    /// Either this method or [`Ticket::challenge`] must be called.
    pub fn eth_challenge(mut self, challenge: EthereumChallenge) -> Self {
        self.challenge = Some(challenge);
        self
    }

    /// Set the signature of this ticket.
    ///
    /// Defaults to `None`.
    #[must_use]
    pub fn signature(mut self, signature: Signature) -> Self {
        self.signature = Some(signature);
        self
    }

    /// Verifies all inputs and builds the [`Ticket`].
    ///
    /// This **does not** perform signature verification if a [signature](TicketBuilder::signature)
    /// was set.
    pub fn build(self) -> errors::Result<Ticket> {
        let amount = match (self.amount, self.balance) {
            (Some(amount), None) if amount.lt(&Self::MAX_TICKET_AMOUNT.into()) => {
                HoprBalance::from(amount)
            }
            (None, Some(balance)) if balance.amount().lt(&Self::MAX_TICKET_AMOUNT.into()) => {
                balance
            }
            (None, None) => return Err(InvalidInputData("missing ticket amount".into())),
            (Some(_), Some(_)) => {
                return Err(InvalidInputData(
                    "either amount or balance must be set but not both".into(),
                ));
            }
            _ => {
                return Err(InvalidInputData(
                    "tickets may not have more than 1% of total supply".into(),
                ));
            }
        };

        if self.index > Self::MAX_TICKET_INDEX {
            return Err(InvalidInputData(
                "cannot hold ticket indices larger than 2^48 - 1".into(),
            ));
        }

        if self.channel_epoch > Self::MAX_CHANNEL_EPOCH {
            return Err(InvalidInputData(
                "cannot hold channel epoch larger than 2^24 - 1".into(),
            ));
        }

        Ok(Ticket {
            counterparty: self
                .counterparty
                .ok_or(InvalidInputData("missing channel id".into()))?,
            amount,
            index: self.index,
            encoded_win_prob: self.win_prob.into(),
            channel_epoch: self.channel_epoch,
            challenge: self
                .challenge
                .ok_or(InvalidInputData("missing ticket challenge".into()))?,
            signature: self.signature,
        })
    }

    /// Validates all inputs and builds the [VerifiedTicket] by signing the ticket data
    /// with the given key. Fails if [signature](TicketBuilder::signature) was previously set.
    pub fn build_signed(
        self,
        signer: &ChainKeypair,
        domain_separator: &Hash,
    ) -> errors::Result<VerifiedTicket> {
        if self.signature.is_none() {
            Ok(self.build()?.sign(signer, domain_separator))
        } else {
            Err(InvalidInputData("signature already set".into()))
        }
    }

    /// Validates all inputs and builds the [`VerifiedTicket`] by **assuming** the previously
    /// set [signature](TicketBuilder::signature) is valid and belongs to the given ticket `hash`.
    ///
    /// It does **not** check whether `hash` matches the input data nor that the signature verifies
    /// the given hash.
    pub fn build_verified(self, hash: Hash) -> errors::Result<VerifiedTicket> {
        if let Some(signature) = self.signature {
            let issuer = signature.recover_from_hash(&hash)?.to_address();
            let ticket = self.build()?;
            Ok(VerifiedTicket {
                hash,
                issuer,
                channel_id: generate_channel_id(&issuer, &ticket.counterparty),
                ticket,
            })
        } else {
            Err(InvalidInputData("signature is missing".into()))
        }
    }
}

impl From<&Ticket> for TicketBuilder {
    fn from(value: &Ticket) -> Self {
        Self {
            counterparty: Some(value.counterparty),
            amount: None,
            balance: Some(value.amount),
            index: value.index,
            channel_epoch: value.channel_epoch,
            win_prob: value.encoded_win_prob.into(),
            challenge: Some(value.challenge),
            signature: None,
        }
    }
}

impl From<Ticket> for TicketBuilder {
    fn from(value: Ticket) -> Self {
        Self::from(&value)
    }
}

#[cfg_attr(doc, aquamarine::aquamarine)]
/// Contains the overall description of a ticket with a signature.
///
/// This structure is not considered [verified](VerifiedTicket), unless
/// the [`Ticket::verify`] or [`Ticket::sign`] methods are called.
///
/// # Ticket state machine
/// See the entire state machine describing the relations of the different ticket types below:
/// ```mermaid
/// flowchart TB
///     A[Ticket] -->|verify| B(VerifiedTicket)
///     B --> |leak| A
///     A --> |sign| B
///     B --> |into_unacknowledged| C(UnacknowledgedTicket)
///     B --> |into_acknowledged| D(AcknowledgedTicket)
///     C --> |acknowledge| D
///     D --> |into_redeemable| E(RedeemableTicket)
///     D --> |into_transferable| F(TransferableWinningTicket)
///     E --> |into_transferable| F
///     F --> |into_redeemable| E
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Ticket {
    /// Counterparty (recipient) of the ticket.
    pub counterparty: Address,
    /// Amount of HOPR tokens this ticket is worth.
    ///
    /// Always between 0 and 2^92.
    pub amount: HoprBalance, // 92 bits
    /// Ticket index.
    ///
    /// Always between 0 and 2^48.
    pub index: u64, // 48 bits
    /// Encoded winning probability represented via 56-bit number.
    pub encoded_win_prob: EncodedWinProb, // 56 bits
    /// Epoch of the channel this ticket belongs to.
    ///
    /// Always between 0 and 2^24.
    pub channel_epoch: u32, // 24 bits
    /// Represent the Proof of Relay challenge encoded as an Ethereum address.
    pub challenge: EthereumChallenge,
    /// ECDSA secp256k1 signature of all the above values.
    pub signature: Option<Signature>,
}

impl Display for Ticket {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "ticket #{}, amount {}, epoch {} with {}",
            self.index, self.amount, self.channel_epoch, self.counterparty
        )
    }
}

impl Ticket {
    /// Creates a new [`TicketBuilder`].
    #[must_use]
    pub fn builder() -> TicketBuilder {
        TicketBuilder::default()
    }

    fn encode_tail_without_signature(&self) -> [u8; Self::SIZE - Address::SIZE - Signature::SIZE] {
        let mut ret = [0u8; Self::SIZE - Address::SIZE - Signature::SIZE];
        let mut offset = 0;
        // There are only 2^96 HOPR tokens
        ret[offset..offset + 12].copy_from_slice(&self.amount.amount().to_be_bytes()[20..32]);
        offset += 12;

        // Ticket index can go only up to 2^48
        ret[offset..offset + 6].copy_from_slice(&self.index.to_be_bytes()[2..8]);
        offset += 6;

        // Channel epoch can go only up to 2^24
        ret[offset..offset + 3].copy_from_slice(&self.channel_epoch.to_be_bytes()[1..4]);
        offset += 3;

        ret[offset..offset + ENCODED_WIN_PROB_LENGTH].copy_from_slice(&self.encoded_win_prob);
        offset += ENCODED_WIN_PROB_LENGTH;

        ret[offset..offset + EthereumChallenge::SIZE].copy_from_slice(self.challenge.as_ref());

        ret
    }

    fn encode_for_transfer(&self) -> [u8; Self::SIZE - Signature::SIZE] {
        let mut ret = [0u8; Self::SIZE - Signature::SIZE];
        let mut offset = 0;

        ret[offset..offset + Address::SIZE].copy_from_slice(self.counterparty.as_ref());
        offset += Address::SIZE;

        ret[offset..].copy_from_slice(&self.encode_tail_without_signature());
        ret
    }

    fn encode_for_signing(
        &self,
        issuer: &Address,
    ) -> (ChannelId, [u8; ON_CHAIN_TICKET_SIZE - Signature::SIZE]) {
        let mut ret = [0u8; ON_CHAIN_TICKET_SIZE - Signature::SIZE];
        let mut offset = 0;

        let channel_id = generate_channel_id(issuer, &self.counterparty);
        ret[offset..offset + Hash::SIZE].copy_from_slice(channel_id.as_ref());
        offset += Hash::SIZE;

        ret[offset..].copy_from_slice(&self.encode_tail_without_signature());
        (channel_id, ret)
    }

    /// Computes Ethereum signature hash of the ticket,
    /// must be equal to on-chain computation
    fn get_hash(&self, issuer: &Address, domain_separator: &Hash) -> (ChannelId, Hash) {
        let (channel_id, hash_struct) = self.encode_for_signing(issuer);
        let ticket_hash = Hash::create(&[hash_struct.as_ref()]); // cannot fail
        let hash_struct = Hash::create(&[&REDEEM_CALL_SELECTOR, &[0u8; 28], ticket_hash.as_ref()]);
        (
            channel_id,
            Hash::create(&[
                &hex!("1901"),
                domain_separator.as_ref(),
                hash_struct.as_ref(),
            ]),
        )
    }

    /// Signs the ticket using the given private key, turning this ticket into [VerifiedTicket].
    /// If a signature was already present, it will be replaced.
    pub fn sign(mut self, signing_key: &ChainKeypair, domain_separator: &Hash) -> VerifiedTicket {
        let (channel_id, ticket_hash) =
            self.get_hash(signing_key.public().as_ref(), domain_separator);
        self.signature = Some(Signature::sign_hash(&ticket_hash, signing_key));
        VerifiedTicket {
            ticket: self,
            hash: ticket_hash,
            issuer: signing_key.public().to_address(),
            channel_id,
        }
    }

    /// Verifies the signature of this ticket, turning this ticket into `VerifiedTicket`.
    /// If the verification fails, `Self` is returned in the error.
    ///
    /// This is done by recovering the signer from the signature and verifying that it matches
    /// the given `issuer` argument. This is possible due this specific instantiation of the ECDSA
    /// over the secp256k1 curve.
    /// The operation can fail if a public key cannot be recovered from the ticket signature.
    #[instrument(level = "trace", skip_all, err)]
    pub fn verify(
        self,
        issuer: &Address,
        domain_separator: &Hash,
    ) -> Result<VerifiedTicket, Box<Ticket>> {
        let (channel_id, ticket_hash) = self.get_hash(issuer, domain_separator);

        if let Some(signature) = &self.signature {
            match signature.recover_from_hash(&ticket_hash) {
                Ok(pk) if pk.to_address().eq(issuer) => Ok(VerifiedTicket {
                    ticket: self,
                    hash: ticket_hash,
                    issuer: *issuer,
                    channel_id,
                }),
                Err(e) => {
                    error!("failed to verify ticket signature: {e}");
                    Err(self.into())
                }
                _ => Err(self.into()),
            }
        } else {
            Err(self.into())
        }
    }

    /// Returns the decoded winning probability of the ticket
    #[inline]
    pub fn win_prob(&self) -> WinningProbability {
        WinningProbability(self.encoded_win_prob)
    }
}

impl From<Ticket> for [u8; TICKET_SIZE] {
    fn from(value: Ticket) -> Self {
        let mut ret = [0u8; TICKET_SIZE];
        ret[0..Ticket::SIZE - Signature::SIZE]
            .copy_from_slice(value.encode_for_transfer().as_ref());
        ret[Ticket::SIZE - Signature::SIZE..].copy_from_slice(
            value
                .signature
                .expect("cannot serialize ticket without signature")
                .as_ref(),
        );
        ret
    }
}

impl TryFrom<&[u8]> for Ticket {
    type Error = GeneralError;

    fn try_from(value: &[u8]) -> std::result::Result<Self, Self::Error> {
        if value.len() == Self::SIZE {
            let mut offset = 0;

            let counterparty = Address::try_from(&value[offset..offset + Address::SIZE])?;
            offset += Address::SIZE;

            let mut amount = [0u8; 32];
            amount[20..32].copy_from_slice(&value[offset..offset + 12]);
            offset += 12;

            let mut index = [0u8; 8];
            index[2..8].copy_from_slice(&value[offset..offset + 6]);
            offset += 6;

            let mut channel_epoch = [0u8; 4];
            channel_epoch[1..4].copy_from_slice(&value[offset..offset + 3]);
            offset += 3;

            let win_prob =
                WinningProbability::try_from(&value[offset..offset + WinningProbability::SIZE])?;
            offset += WinningProbability::SIZE;

            let challenge =
                EthereumChallenge::try_from(&value[offset..offset + EthereumChallenge::SIZE])?;
            offset += EthereumChallenge::SIZE;

            let signature = Signature::try_from(&value[offset..offset + Signature::SIZE])?;

            // Validate the boundaries of the parsed values
            TicketBuilder::default()
                .counterparty(counterparty)
                .amount(U256::from_big_endian(&amount))
                .index(u64::from_be_bytes(index))
                .channel_epoch(u32::from_be_bytes(channel_epoch))
                .win_prob(win_prob)
                .eth_challenge(challenge)
                .signature(signature)
                .build()
                .map_err(|e| GeneralError::ParseError(format!("ticket build failed: {e}")))
        } else {
            Err(GeneralError::ParseError("Ticket".into()))
        }
    }
}

const TICKET_SIZE: usize = 48 + EthereumChallenge::SIZE + Signature::SIZE;

const ON_CHAIN_TICKET_SIZE: usize = 60 + EthereumChallenge::SIZE + Signature::SIZE;

impl BytesEncodable<TICKET_SIZE> for Ticket {}

/// Holds a ticket that has been already verified.
/// This structure guarantees that `Ticket::get_hash()` of [`VerifiedTicket::verified_ticket()`]
/// is always equal to [`VerifiedTicket::verified_hash`]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct VerifiedTicket {
    ticket: Ticket,
    hash: Hash,
    issuer: Address,
    channel_id: ChannelId,
}

impl VerifiedTicket {
    /// Returns the verified encoded winning probability of the ticket
    #[inline]
    pub fn win_prob(&self) -> WinningProbability {
        self.ticket.win_prob()
    }

    /// Checks if this ticket is considered a win.
    /// Requires access to the private key to compute the VRF values.
    ///
    /// Computes the ticket's luck value and compares it against the
    /// ticket's probability. If luck <= probability, the ticket is
    /// considered a win.
    ///
    /// ## Ticket luck value
    /// This ticket's `luck value` is the first 7 bytes of Keccak256 hash
    /// where the input is the concatenation of ticket's hash, VRF's encoded `v` value,
    /// PoR response and the ticket's signature.
    ///
    /// ## Winning probability
    /// Each ticket specifies a probability, given as an integer in
    /// `[0, 2^56-1]` where 0 -> 0% and 2^56 - 1 -> 100% win
    /// probability. If the ticket's luck value is greater than
    /// the stated probability, it is considered a winning ticket.
    pub fn is_winning(
        &self,
        response: &Response,
        chain_keypair: &ChainKeypair,
        domain_separator: &Hash,
    ) -> bool {
        if let Ok(vrf_params) =
            derive_vrf_parameters(self.hash, chain_keypair, domain_separator.as_ref())
        {
            check_ticket_win(
                &self.hash,
                self.ticket
                    .signature
                    .as_ref()
                    .expect("verified ticket have always a signature"),
                &self.ticket.win_prob(),
                response,
                &vrf_params,
            )
        } else {
            error!("cannot derive vrf parameters for {self}");
            false
        }
    }

    /// Ticket with already verified signature.
    #[inline]
    pub fn verified_ticket(&self) -> &Ticket {
        &self.ticket
    }

    /// Fixed ticket hash that is guaranteed to be equal to
    /// `Ticket::get_hash` of [`VerifiedTicket::verified_ticket`].
    #[inline]
    pub fn verified_hash(&self) -> &Hash {
        &self.hash
    }

    /// Verified issuer of the ticket.
    ///
    /// The returned address is guaranteed to be equal to the signer
    /// recovered from the [`VerifiedTicket::verified_ticket`]'s signature.
    #[inline]
    pub fn verified_issuer(&self) -> &Address {
        &self.issuer
    }

    /// Channel ID of the ticket.
    ///
    /// The ticket is guaranteed to belong to the channel with the returned [`ChannelId`].
    #[inline]
    pub fn channel_id(&self) -> &ChannelId {
        &self.channel_id
    }

    /// Shorthand to retrieve reference to the verified ticket signature
    pub fn verified_signature(&self) -> &Signature {
        self.ticket
            .signature
            .as_ref()
            .expect("verified ticket always has a signature")
    }

    /// Deconstructs self back into the unverified [`Ticket`].
    #[inline]
    pub fn leak(self) -> Ticket {
        self.ticket
    }

    /// Creates a new unacknowledged ticket from the [`VerifiedTicket`],
    /// given our own part of the PoR challenge.
    pub fn into_unacknowledged(self, own_key: HalfKey) -> UnacknowledgedTicket {
        UnacknowledgedTicket {
            ticket: self,
            own_key,
        }
    }

    /// Shorthand to acknowledge the ticket if the matching response is already known.
    pub fn into_acknowledged(self, response: Response) -> AcknowledgedTicket {
        AcknowledgedTicket {
            status: AcknowledgedTicketStatus::Untouched,
            ticket: self,
            response,
        }
    }
}

impl Display for VerifiedTicket {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "verified {} in channel {}", self.ticket, self.channel_id)
    }
}

impl PartialOrd for VerifiedTicket {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for VerifiedTicket {
    fn cmp(&self, other: &Self) -> Ordering {
        TicketId::from(self).cmp(&TicketId::from(other))
    }
}

/// Represents a [`VerifiedTicket`] with an unknown other part of the [`HalfKey`].
/// Once the other [`HalfKey`] is known (forming a [`Response`]),
/// it can be [acknowledged](UnacknowledgedTicket::acknowledge).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct UnacknowledgedTicket {
    pub ticket: VerifiedTicket,
    pub(crate) own_key: HalfKey,
}

impl UnacknowledgedTicket {
    /// Convenience method to retrieve a reference to the underlying verified [Ticket].
    #[inline]
    pub fn verified_ticket(&self) -> &Ticket {
        self.ticket.verified_ticket()
    }

    /// Verifies that the given acknowledgement solves this ticket's challenge and then
    /// turns this unacknowledged ticket into an acknowledged ticket by adding
    /// the received acknowledgement of the forwarded packet.
    pub fn acknowledge(
        self,
        acknowledgement: &HalfKey,
    ) -> crate::internal::errors::Result<AcknowledgedTicket> {
        let response = Response::from_half_keys(&self.own_key, acknowledgement)?;
        tracing::trace!(ticket = %self.ticket, response = response.to_hex(), "acknowledging ticket using response");

        if self.ticket.verified_ticket().challenge
            == response.to_challenge()?.to_ethereum_challenge()
        {
            Ok(self.ticket.into_acknowledged(response))
        } else {
            Err(CryptoError::InvalidChallenge.into())
        }
    }
}

impl Display for UnacknowledgedTicket {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "unacknowledged {}", self.ticket)
    }
}

/// Status of the acknowledged ticket.
#[repr(u8)]
#[derive(
    Clone,
    Copy,
    Debug,
    Default,
    Eq,
    PartialEq,
    strum::Display,
    strum::EnumString,
    num_enum::IntoPrimitive,
    num_enum::TryFromPrimitive,
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[strum(serialize_all = "PascalCase")]
pub enum AcknowledgedTicketStatus {
    /// The ticket is available for redeeming or aggregating
    #[default]
    Untouched = 0,
    /// Ticket is currently being redeemed in and ongoing redemption process
    BeingRedeemed = 1,
}

/// Contains acknowledgment information and the respective ticket
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AcknowledgedTicket {
    #[cfg_attr(feature = "serde", serde(default))]
    pub status: AcknowledgedTicketStatus,
    pub ticket: VerifiedTicket,
    pub response: Response,
}

impl PartialOrd for AcknowledgedTicket {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for AcknowledgedTicket {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.ticket.cmp(&other.ticket)
    }
}

impl AcknowledgedTicket {
    /// Convenience method to retrieve a reference to the underlying verified [Ticket].
    #[inline]
    pub fn verified_ticket(&self) -> &Ticket {
        self.ticket.verified_ticket()
    }

    /// Checks if this acknowledged ticket is winning.
    pub fn is_winning(&self, chain_keypair: &ChainKeypair, domain_separator: &Hash) -> bool {
        self.ticket
            .is_winning(&self.response, chain_keypair, domain_separator)
    }

    /// Transforms this ticket into [`RedeemableTicket`] that can be redeemed on-chain
    /// or transformed into [`TransferableWinningTicket`] that can be sent for aggregation.
    ///
    /// The `chain_keypair` must not be of the ticket's issuer.
    /// This ticket MUST be winning, otherwise the function fails with [`CoreTypesError::TicketNotWinning`].
    pub fn into_redeemable(
        self,
        chain_keypair: &ChainKeypair,
        domain_separator: &Hash,
    ) -> errors::Result<RedeemableTicket> {
        // This function must be called by the ticket recipient and not the issuer
        if chain_keypair
            .public()
            .to_address()
            .eq(self.ticket.verified_issuer())
        {
            return Err(errors::CoreTypesError::LoopbackTicket);
        }

        let vrf_params = derive_vrf_parameters(
            self.ticket.verified_hash(),
            chain_keypair,
            domain_separator.as_ref(),
        )?;

        if !check_ticket_win(
            self.ticket.verified_hash(),
            self.ticket.verified_signature(),
            &self.ticket.win_prob(),
            &self.response,
            &vrf_params,
        ) {
            return Err(CoreTypesError::TicketNotWinning);
        }

        Ok(RedeemableTicket {
            ticket: self.ticket,
            response: self.response,
            vrf_params,
            channel_dst: *domain_separator,
        })
    }

    /// Shorthand for transforming this ticket into [TransferableWinningTicket].
    /// See [`AcknowledgedTicket::into_redeemable`] for details.
    pub fn into_transferable(
        self,
        chain_keypair: &ChainKeypair,
        domain_separator: &Hash,
    ) -> errors::Result<TransferableWinningTicket> {
        self.into_redeemable(chain_keypair, domain_separator)
            .map(TransferableWinningTicket::from)
    }
}

impl Display for AcknowledgedTicket {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "acknowledged {} in state '{}'", self.ticket, self.status)
    }
}

/// Represents a winning ticket that can be successfully redeemed on-chain.
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RedeemableTicket {
    /// Verified ticket that can be redeemed.
    pub ticket: VerifiedTicket,
    /// Solution to the PoR challenge in the ticket.
    pub response: Response,
    /// VRF parameters required for redeeming.
    pub vrf_params: VrfParameters,
    /// Channel domain separator used to compute the VRF parameters.
    pub channel_dst: Hash,
}

impl RedeemableTicket {
    /// Convenience method to retrieve a reference to the underlying verified [Ticket].
    #[inline]
    pub fn verified_ticket(&self) -> &Ticket {
        self.ticket.verified_ticket()
    }

    /// Gets the [`TicketId`] of the ticket.
    #[inline]
    pub fn ticket_id(&self) -> TicketId {
        TicketId::from(&self.ticket)
    }
}

impl PartialEq for RedeemableTicket {
    fn eq(&self, other: &Self) -> bool {
        self.ticket == other.ticket
            && self.channel_dst == other.channel_dst
            && self.response == other.response
    }
}

impl Eq for RedeemableTicket {}

impl PartialOrd for RedeemableTicket {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for RedeemableTicket {
    fn cmp(&self, other: &Self) -> Ordering {
        self.ticket.cmp(&other.ticket)
    }
}

impl Display for RedeemableTicket {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "redeemable {}", self.ticket)
    }
}

impl From<RedeemableTicket> for AcknowledgedTicket {
    fn from(value: RedeemableTicket) -> Self {
        Self {
            status: AcknowledgedTicketStatus::Untouched,
            ticket: value.ticket,
            response: value.response,
        }
    }
}

/// Represents a ticket that could be transferred over the wire
/// and independently verified again by the other party.
///
/// The [`TransferableWinningTicket`] can be easily retrieved from [`RedeemableTicket`], which strips
/// information about verification.
/// [`TransferableWinningTicket`] can be attempted to be converted back to [`RedeemableTicket`] only
/// when verified via [`TransferableWinningTicket::into_redeemable`] again.
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TransferableWinningTicket {
    pub ticket: Ticket,
    pub response: Response,
    pub vrf_params: VrfParameters,
    pub signer: Address,
}

impl TransferableWinningTicket {
    /// Attempts to transform this ticket back into a [`RedeemableTicket`].
    ///
    /// Verifies that the `signer` matches the `expected_issuer` and that the
    /// ticket has a valid signature from the `signer`.
    /// Then it verifies if the ticket is winning and therefore if it can be successfully
    /// redeemed on-chain.
    pub fn into_redeemable(
        self,
        expected_issuer: &Address,
        domain_separator: &Hash,
    ) -> errors::Result<RedeemableTicket> {
        if !self.signer.eq(expected_issuer) {
            return Err(InvalidInputData("invalid ticket issuer".into()));
        }

        let verified_ticket = self
            .ticket
            .verify(&self.signer, domain_separator)
            .map_err(|_| CoreTypesError::CryptoError(CryptoError::SignatureVerification))?;

        if check_ticket_win(
            verified_ticket.verified_hash(),
            verified_ticket.verified_signature(),
            &verified_ticket.verified_ticket().win_prob(),
            &self.response,
            &self.vrf_params,
        ) {
            Ok(RedeemableTicket {
                ticket: verified_ticket,
                response: self.response,
                vrf_params: self.vrf_params,
                channel_dst: *domain_separator,
            })
        } else {
            Err(InvalidInputData("ticket is not a win".into()))
        }
    }
}

impl PartialEq for TransferableWinningTicket {
    fn eq(&self, other: &Self) -> bool {
        self.ticket == other.ticket
            && self.signer == other.signer
            && self.response == other.response
    }
}

impl From<RedeemableTicket> for TransferableWinningTicket {
    fn from(value: RedeemableTicket) -> Self {
        Self {
            response: value.response,
            vrf_params: value.vrf_params,
            signer: *value.ticket.verified_issuer(),
            ticket: value.ticket.leak(),
        }
    }
}

#[cfg(test)]
pub mod tests {
    use crate::crypto::{
        keypairs::{ChainKeypair, Keypair},
        types::{HalfKey, Hash, Response},
    };
    use crate::crypto_random::Randomizable;
    use crate::primitive::{
        prelude::UnitaryFloatOps,
        primitives::{Address, EthereumChallenge, U256},
    };
    use hex_literal::hex;

    use super::*;

    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");
    }

    #[test]
    pub fn test_win_prob_to_f64() -> anyhow::Result<()> {
        assert_eq!(0.0f64, WinningProbability::NEVER.as_f64());

        assert_eq!(1.0f64, WinningProbability::ALWAYS.as_f64());

        let mut test_bit_string = [0xffu8; 7];
        test_bit_string[0] = 0x7f;
        assert_eq!(0.5f64, WinningProbability::from(&test_bit_string).as_f64());

        test_bit_string[0] = 0x3f;
        assert_eq!(0.25f64, WinningProbability::from(&test_bit_string).as_f64());

        test_bit_string[0] = 0x1f;
        assert_eq!(
            0.125f64,
            WinningProbability::from(&test_bit_string).as_f64()
        );

        Ok(())
    }

    #[test]
    pub fn test_f64_to_win_prob() -> anyhow::Result<()> {
        assert_eq!([0u8; 7], WinningProbability::try_from(0.0f64)?.as_encoded());

        let mut test_bit_string = [0xffu8; 7];
        assert_eq!(
            test_bit_string,
            WinningProbability::try_from(1.0f64)?.as_encoded()
        );

        test_bit_string[0] = 0x7f;
        assert_eq!(
            test_bit_string,
            WinningProbability::try_from(0.5f64)?.as_encoded()
        );

        test_bit_string[0] = 0x3f;
        assert_eq!(
            test_bit_string,
            WinningProbability::try_from(0.25f64)?.as_encoded()
        );

        test_bit_string[0] = 0x1f;
        assert_eq!(
            test_bit_string,
            WinningProbability::try_from(0.125f64)?.as_encoded()
        );

        Ok(())
    }

    #[test]
    pub fn test_win_prob_approx_eq() -> anyhow::Result<()> {
        let wp_0 = WinningProbability(hex!("0020C49BBFFFFF"));
        let wp_1 = WinningProbability(hex!("0020C49BA5E34F"));

        // These two probabilities are equal up to epsilon, but different lexicographically
        assert_ne!(wp_0, wp_1.as_encoded());
        assert!(!wp_0.lex_eq(&wp_1));

        assert_eq!(wp_0, wp_1.as_f64());
        assert!(wp_0.approx_eq(&wp_1));

        Ok(())
    }

    #[test]
    pub fn test_win_prob_back_and_forth() -> anyhow::Result<()> {
        for float in [0.1f64, 0.002f64, 0.00001f64, 0.7311111f64, 1.0f64, 0.0f64] {
            assert!(
                (float - WinningProbability::try_from_f64(float)?.as_f64()).abs() < f64::EPSILON
            );
        }

        Ok(())
    }

    #[test]
    pub fn test_win_prob_must_be_correctly_approx_ordered() {
        let increment = WinningProbability::EPSILON * 100.0; // Testing the entire range would take too long
        let mut prev = WinningProbability::NEVER;
        while let Ok(next) = WinningProbability::try_from_f64(prev.as_f64() + increment) {
            assert!(prev.approx_cmp(&next).is_lt());
            prev = next;
        }
    }

    #[test]
    pub fn test_win_prob_must_be_correctly_lex_ordered() {
        let increment = WinningProbability::EPSILON * 100.0; // Testing the entire range would take too long
        let mut prev = WinningProbability::NEVER;
        while let Ok(next) = WinningProbability::try_from_f64(prev.as_f64() + increment) {
            assert!(prev.lex_cmp(&next).is_lt());
            prev = next;
        }
    }

    #[test]
    pub fn test_win_prob_epsilon_must_be_never() -> anyhow::Result<()> {
        assert!(
            WinningProbability::NEVER.approx_eq(&WinningProbability::try_from_f64(
                WinningProbability::EPSILON
            )?)
        );
        assert!(
            WinningProbability::NEVER.lex_eq(&WinningProbability::try_from_f64(
                WinningProbability::EPSILON
            )?)
        );
        Ok(())
    }

    #[test]
    pub fn test_win_prob_bounds_must_be_approx_eq() -> anyhow::Result<()> {
        let bound = 0.1 + WinningProbability::EPSILON;
        let other = 0.1;
        assert!(
            WinningProbability::try_from_f64(bound)?
                .approx_eq(&WinningProbability::try_from_f64(other)?)
        );
        Ok(())
    }

    #[test]
    pub fn test_win_prob_bounds_must_not_be_approx_eq_when_differ_by_more_then_epsilon()
    -> anyhow::Result<()> {
        let bound = 0.1 + 1.1 * WinningProbability::EPSILON;
        let other = 0.1;
        assert!(
            !WinningProbability::try_from_f64(bound)?
                .approx_eq(&WinningProbability::try_from_f64(other)?)
        );
        Ok(())
    }

    #[test]
    pub fn test_win_prob_bounds_must_not_be_lex_eq() -> anyhow::Result<()> {
        let bound = 0.1 + WinningProbability::EPSILON;
        let other = 0.1;
        assert!(
            !WinningProbability::try_from_f64(bound)?
                .lex_eq(&WinningProbability::try_from_f64(other)?)
        );
        Ok(())
    }

    #[test]
    pub fn test_ticket_builder_zero_hop() -> anyhow::Result<()> {
        let ticket = TicketBuilder::zero_hop()
            .counterparty(&*BOB)
            .eth_challenge(Default::default())
            .build()?;
        assert_eq!(0, ticket.index);
        assert_eq!(0.0, ticket.win_prob().as_f64());
        assert_eq!(0, ticket.channel_epoch);

        Ok(())
    }

    #[test]
    pub fn test_ticket_serialize_deserialize() -> anyhow::Result<()> {
        let initial_ticket = TicketBuilder::default()
            .counterparty(&*BOB)
            .balance(1.into())
            .index(0)
            .win_prob(1.0.try_into()?)
            .channel_epoch(1)
            .eth_challenge(Default::default())
            .build_signed(&ALICE, &Default::default())?;

        assert_ne!(initial_ticket.verified_hash().as_ref(), [0u8; Hash::SIZE]);

        let ticket_bytes: [u8; Ticket::SIZE] = (*initial_ticket.verified_ticket()).into();
        assert_eq!(
            initial_ticket.verified_ticket(),
            &Ticket::try_from(ticket_bytes.as_ref())?
        );
        Ok(())
    }

    #[test]
    #[cfg(feature = "serde")]
    pub fn test_ticket_serialize_deserialize_serde() -> anyhow::Result<()> {
        let initial_ticket = TicketBuilder::default()
            .counterparty(&*BOB)
            .balance(1.into())
            .index(0)
            .win_prob(1.0.try_into()?)
            .channel_epoch(1)
            .eth_challenge(Default::default())
            .build_signed(&ALICE, &Default::default())?;

        assert_eq!(
            initial_ticket,
            postcard::from_bytes(&postcard::to_allocvec(&initial_ticket)?)?
        );
        Ok(())
    }

    #[test]
    pub fn test_ticket_sign_verify() -> anyhow::Result<()> {
        let initial_ticket = TicketBuilder::default()
            .counterparty(&*BOB)
            .balance(1.into())
            .index(0)
            .win_prob(1.0.try_into()?)
            .channel_epoch(1)
            .eth_challenge(Default::default())
            .build_signed(&ALICE, &Default::default())?;

        assert_ne!(initial_ticket.verified_hash().as_ref(), [0u8; Hash::SIZE]);
        assert_eq!(
            initial_ticket.channel_id(),
            &generate_channel_id(&ALICE.public().to_address(), &BOB.public().to_address())
        );

        let ticket = initial_ticket.leak();
        assert!(
            ticket
                .verify(&ALICE.public().to_address(), &Default::default())
                .is_ok()
        );

        Ok(())
    }

    #[test]
    pub fn test_zero_hop() -> anyhow::Result<()> {
        let ticket = TicketBuilder::zero_hop()
            .counterparty(&*BOB)
            .eth_challenge(Default::default())
            .build_signed(&ALICE, &Default::default())?;

        assert!(
            ticket
                .leak()
                .verify(&ALICE.public().to_address(), &Hash::default())
                .is_ok()
        );
        Ok(())
    }

    fn mock_ticket(
        pk: &ChainKeypair,
        counterparty: &Address,
        domain_separator: Option<Hash>,
        challenge: Option<EthereumChallenge>,
    ) -> anyhow::Result<VerifiedTicket> {
        let win_prob = 1.0f64; // 100 %
        let price_per_packet: U256 = 10000000000000000u128.into(); // 0.01 HOPR
        let path_pos = 5u64;

        Ok(TicketBuilder::default()
            .counterparty(*counterparty)
            .amount(price_per_packet.div_f64(win_prob)? * U256::from(path_pos))
            .index(0)
            .win_prob(1.0.try_into()?)
            .channel_epoch(4)
            .eth_challenge(challenge.unwrap_or_default())
            .build_signed(pk, &domain_separator.unwrap_or_default())?)
    }

    #[test]
    fn test_unacknowledged_ticket_challenge_response() -> anyhow::Result<()> {
        let hk1 = HalfKey::try_from(
            hex!("3477d7de923ba3a7d5d72a7d6c43fd78395453532d03b2a1e2b9a7cc9b61bafa").as_ref(),
        )?;

        let hk2 = HalfKey::try_from(
            hex!("4471496ef88d9a7d86a92b7676f3c8871a60792a37fae6fc3abc347c3aa3b16b").as_ref(),
        )?;

        let challenge = Response::from_half_keys(&hk1, &hk2)?.to_challenge()?;

        let dst = Hash::default();
        let ack = mock_ticket(
            &ALICE,
            &BOB.public().to_address(),
            Some(dst),
            Some(challenge.to_ethereum_challenge()),
        )?
        .into_unacknowledged(hk1)
        .acknowledge(&hk2)?;

        assert!(ack.is_winning(&BOB, &dst), "ticket must be winning");
        Ok(())
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_acknowledged_ticket_serde() -> anyhow::Result<()> {
        let response = Response::try_from(
            hex!("876a41ee5fb2d27ac14d8e8d552692149627c2f52330ba066f9e549aef762f73").as_ref(),
        )?;

        let dst = Hash::default();

        let ticket = mock_ticket(
            &ALICE,
            &BOB.public().to_address(),
            Some(dst),
            Some(response.to_challenge()?.to_ethereum_challenge()),
        )?;

        let acked_ticket = ticket.into_acknowledged(response);

        let mut deserialized_ticket = postcard::from_bytes(&postcard::to_allocvec(&acked_ticket)?)?;
        assert_eq!(acked_ticket, deserialized_ticket);

        assert!(deserialized_ticket.is_winning(&BOB, &dst));

        deserialized_ticket.status = AcknowledgedTicketStatus::BeingRedeemed;

        assert_eq!(
            deserialized_ticket,
            postcard::from_bytes(&postcard::to_allocvec(&deserialized_ticket)?,)?
        );
        Ok(())
    }

    #[test]
    fn test_ticket_entire_ticket_transfer_flow() -> anyhow::Result<()> {
        let hk1 = HalfKey::random();
        let hk2 = HalfKey::random();
        let resp = Response::from_half_keys(&hk1, &hk2)?;

        let verified = TicketBuilder::default()
            .counterparty(&*BOB)
            .balance(1.into())
            .index(0)
            .win_prob(1.0.try_into()?)
            .channel_epoch(1)
            .challenge(resp.to_challenge()?)
            .build_signed(&ALICE, &Default::default())?;

        let unack = verified.into_unacknowledged(hk1);
        let acknowledged = unack.acknowledge(&hk2).expect("should acknowledge");

        let redeemable_1 = acknowledged.into_redeemable(&BOB, &Hash::default())?;

        let transferable = acknowledged.into_transferable(&BOB, &Hash::default())?;

        let redeemable_2 =
            transferable.into_redeemable(&ALICE.public().to_address(), &Hash::default())?;

        assert_eq!(redeemable_1, redeemable_2);
        assert_eq!(redeemable_1.vrf_params.V, redeemable_2.vrf_params.V);
        Ok(())
    }
}