fiber-types 0.9.0-rc2

Core domain types for the Fiber Network
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
//! Invoice-related types: status, currency, hash algorithm, script wrapper, signature.

use crate::serde_utils::EntityHex;

use crate::gen::invoice as gen_invoice;
use arcode::bitbit::{BitReader, BitWriter, MSB};
use arcode::{ArithmeticDecoder, ArithmeticEncoder, EOFKind, Model};
use bech32::{encode, u5, FromBase32, ToBase32, Variant, WriteBase32};
use ckb_hash::blake2b_256;
use ckb_types::packed::Script as PackedScript;
use ckb_types::prelude::{Pack, Unpack};
use gen_invoice::{
    Description, ExpiryTime, FallbackAddr, Feature, FinalHtlcMinimumExpiryDelta, FinalHtlcTimeout,
    InvoiceAttr, InvoiceAttrUnion, InvoiceAttrsVec, PayeePublicKey, PaymentHash, PaymentSecret,
    RawInvoiceDataBuilder, UdtScript,
};
use molecule::prelude::Byte;
use molecule::prelude::{Builder, Entity};
use nom::{branch::alt, combinator::opt};
use nom::{
    bytes::{complete::take_while1, streaming::tag},
    IResult,
};
use secp256k1::ecdsa::{RecoverableSignature, RecoveryId};
use serde::{Deserialize, Serialize};
use serde_with::serde_as;
use sha2::{Digest, Sha256};
use std::cmp::Ordering;
use std::fmt::Display;
use std::io::{Cursor, Result as IoResult};
use std::num::ParseIntError;
use std::str::FromStr;
use thiserror::Error;

/// Wrapper for molecule verification errors.
#[derive(Error, Debug)]
pub struct VerificationError(pub molecule::error::VerificationError);

impl PartialEq for VerificationError {
    fn eq(&self, _other: &Self) -> bool {
        false
    }
}

impl Display for VerificationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

/// Errors that can occur when parsing or validating an invoice.
#[derive(Error, PartialEq, Debug)]
pub enum InvoiceError {
    /// Bech32 encoding/decoding error.
    #[error("Bech32 error: {0}")]
    Bech32Error(bech32::Error),
    /// Molecule serialization error.
    #[error("Molecule error: {0}")]
    MoleculeError(VerificationError),
    /// Failed to parse amount from HRP.
    #[error("Failed to parse amount: {0}")]
    ParseAmountError(ParseIntError),
    /// Unknown currency in HRP.
    #[error("Unknown currency: {0}")]
    UnknownCurrency(String),
    /// Unknown SI prefix in amount.
    #[error("Unknown si prefix: {0}")]
    UnknownSiPrefix(String),
    /// Malformed HRP.
    #[error("Parsing failed with malformed HRP: {0}")]
    MalformedHRP(String),
    /// Data part is too short.
    #[error("Too short data part")]
    TooShortDataPart,
    /// Unexpected end of tagged fields.
    #[error("Unexpected end of tagged fields")]
    UnexpectedEndOfTaggedFields,
    /// Integer overflow error.
    #[error("Integer overflow error")]
    IntegerOverflowError,
    /// Invalid recovery ID in signature.
    #[error("Invalid recovery id")]
    InvalidRecoveryId,
    /// Invalid slice length.
    #[error("Invalid slice length: {0}")]
    InvalidSliceLength(String),
    /// Invalid signature.
    #[error("Invalid signature")]
    InvalidSignature,
    /// Duplicated attribute key.
    #[error("Duplicated attribute key: {0}")]
    DuplicatedAttributeKey(String),
    /// Payment secret is required for MPP payments.
    #[error("Payment secret is required for MPP payments")]
    PaymentSecretRequiredForMpp,
    /// Both payment_hash and payment_preimage are set.
    #[error("Both payment_hash and payment_preimage are set")]
    BothPaymenthashAndPreimage,
    /// Neither payment_hash nor payment_preimage is set.
    #[error("Neither payment_hash nor payment_preimage is set")]
    NeitherPaymenthashNorPreimage,
    /// An error occurred during signing.
    #[error("Sign error")]
    SignError,
    /// Hex decode error.
    #[error("Hex decode error: {0}")]
    HexDecodeError(#[from] hex::FromHexError),
    /// Duplicated invoice found.
    #[error("Duplicated invoice found: {0}")]
    DuplicatedInvoice(String),
    /// Description is too long.
    #[error("Description with length of {0} is too long, max length is 639")]
    DescriptionTooLong(usize),
    /// Invoice not found.
    #[error("Invoice not found")]
    InvoiceNotFound,
    /// Invoice already exists.
    #[error("Invoice already exists")]
    InvoiceAlreadyExists,
    /// Deprecated attribute.
    #[error("Deprecated attribute: {0}")]
    DeprecatedAttribute(String),
    /// Failed to decompress invoice data.
    #[error("Failed to decompress invoice data: {0}")]
    DecompressionError(String),
    /// Decompressed invoice data exceeds the parser limit.
    #[error("Invoice data length {len} exceeds max length {max}")]
    InvoiceDataTooLong { len: usize, max: usize },
    /// Invoice text attribute is not valid UTF-8.
    #[error("Invalid UTF-8 in invoice {0} attribute")]
    InvalidUtf8Attribute(&'static str),
    /// Invoice payee public key is malformed.
    #[error("Invalid payee public key")]
    InvalidPayeePublicKey,
    /// Invoice signature contains malformed base32 data.
    #[error("Invalid signature encoding")]
    InvalidSignatureEncoding,
}

/// Size of the signature in u5 encoding.
pub const SIGNATURE_U5_SIZE: usize = 104;

/// Maximum allowed length for an invoice description.
pub const MAX_DESCRIPTION_LENGTH: usize = 639;

/// Maximum decompressed molecule payload accepted by the invoice parser.
///
/// Current invoices only need a few hundred bytes for fixed fields plus the
/// 639-byte description limit. This leaves room for scripts, fallback
/// addresses and future attributes while bounding compressed-input expansion.
pub const MAX_INVOICE_DATA_LENGTH: usize = 16 * 1024;

/// Encodes bytes and returns the compressed form.
/// This is used for encoding the invoice data, to make the final Invoice encoded address shorter.
pub(crate) fn ar_encompress(data: &[u8]) -> IoResult<Vec<u8>> {
    let mut model = Model::builder().num_bits(8).eof(EOFKind::EndAddOne).build();
    let mut compressed_writer = BitWriter::new(Cursor::new(vec![]));
    let mut encoder = ArithmeticEncoder::new(48);
    for &sym in data {
        encoder.encode(sym as u32, &model, &mut compressed_writer)?;
        model.update_symbol(sym as u32);
    }

    encoder.encode(model.eof(), &model, &mut compressed_writer)?;
    encoder.finish_encode(&mut compressed_writer)?;
    compressed_writer.pad_to_byte()?;

    Ok(compressed_writer.get_ref().get_ref().clone())
}

fn ar_decompress_with_limit(data: &[u8], max_len: usize) -> Result<Vec<u8>, InvoiceError> {
    let mut model = Model::builder().num_bits(8).eof(EOFKind::EndAddOne).build();
    let mut input_reader = BitReader::<_, MSB>::new(data);
    let mut decoder = ArithmeticDecoder::new(48);
    let mut decompressed_data = vec![];

    while !decoder.finished() {
        let sym = decoder
            .decode(&model, &mut input_reader)
            .map_err(|err| InvoiceError::DecompressionError(err.to_string()))?;
        model.update_symbol(sym);
        decompressed_data.push(sym as u8);

        if !decoder.finished() && decompressed_data.len() > max_len {
            return Err(InvoiceError::InvoiceDataTooLong {
                len: decompressed_data.len(),
                max: max_len,
            });
        }
    }

    decompressed_data
        .pop()
        .ok_or_else(|| InvoiceError::DecompressionError("missing EOF marker".to_string()))?;
    Ok(decompressed_data)
}

/// Construct the invoice's HRP and signatureless data into a preimage to be hashed.
pub fn construct_invoice_preimage(hrp_bytes: &[u8], data_without_signature: &[u5]) -> Vec<u8> {
    let mut preimage = Vec::<u8>::from(hrp_bytes);

    let mut data_part = Vec::from(data_without_signature);
    let overhang = (data_part.len() * 5) % 8;
    if overhang > 0 {
        // add padding if data does not end at a byte boundary
        data_part.push(u5::try_from_u8(0).expect("u5 from u8"));

        // if overhang is in (1..3) we need to add u5(0) padding two times
        if overhang < 3 {
            data_part.push(u5::try_from_u8(0).expect("u5 from u8"));
        }
    }

    preimage.extend_from_slice(
        &Vec::<u8>::from_base32(&data_part)
            .expect("No padding error may occur due to appended zero above."),
    );
    preimage
}

fn nom_scan_hrp(input: &str) -> IResult<&str, (&str, Option<&str>)> {
    let (input, currency) = alt((tag("fibb"), tag("fibt"), tag("fibd")))(input)?;
    let (input, amount) = opt(take_while1(|c: char| c.is_numeric()))(input)?;
    Ok((input, (currency, amount)))
}

/// Parse the human-readable part of an invoice.
pub fn parse_hrp(input: &str) -> Result<(Currency, Option<u128>), InvoiceError> {
    match nom_scan_hrp(input) {
        Ok((left, (currency, amount))) => {
            if !left.is_empty() {
                return Err(InvoiceError::MalformedHRP(format!(
                    "{}, unexpected ending `{}`",
                    input, left
                )));
            }
            let currency =
                Currency::from_str(currency).map_err(|e| InvoiceError::UnknownCurrency(e.0))?;
            let amount = amount
                .map(|x| x.parse().map_err(InvoiceError::ParseAmountError))
                .transpose()?;
            Ok((currency, amount))
        }
        Err(_) => Err(InvoiceError::MalformedHRP(input.to_string())),
    }
}

/// The currency of the invoice, can also used to represent the CKB network chain.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
pub enum CkbInvoiceStatus {
    /// The invoice is open and can be paid.
    Open,
    /// The invoice is cancelled.
    Cancelled,
    /// The invoice is expired.
    Expired,
    /// The invoice is received, but not settled yet.
    Received,
    /// The invoice is paid.
    Paid,
}

impl Display for CkbInvoiceStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CkbInvoiceStatus::Open => write!(f, "Open"),
            CkbInvoiceStatus::Cancelled => write!(f, "Cancelled"),
            CkbInvoiceStatus::Expired => write!(f, "Expired"),
            CkbInvoiceStatus::Received => write!(f, "Received"),
            CkbInvoiceStatus::Paid => write!(f, "Paid"),
        }
    }
}

/// The currency of the invoice, can also used to represent the CKB network chain.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize, Default)]
pub enum Currency {
    /// The mainnet currency of CKB.
    Fibb,
    /// The testnet currency of the CKB network.
    Fibt,
    /// The devnet currency of the CKB network.
    #[default]
    Fibd,
}

impl Display for Currency {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Currency::Fibb => write!(f, "fibb"),
            Currency::Fibt => write!(f, "fibt"),
            Currency::Fibd => write!(f, "fibd"),
        }
    }
}

/// Error for unknown currency
#[derive(thiserror::Error, Debug)]
#[error("Unknown currency: {0}")]
pub struct UnknownCurrencyError(pub String);

impl FromStr for Currency {
    type Err = UnknownCurrencyError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "fibb" => Ok(Self::Fibb),
            "fibt" => Ok(Self::Fibt),
            "fibd" => Ok(Self::Fibd),
            _ => Err(UnknownCurrencyError(s.to_string())),
        }
    }
}

impl TryFrom<u8> for Currency {
    type Error = UnknownCurrencyError;

    fn try_from(byte: u8) -> Result<Self, Self::Error> {
        match byte {
            0 => Ok(Self::Fibb),
            1 => Ok(Self::Fibt),
            2 => Ok(Self::Fibd),
            _ => Err(UnknownCurrencyError(byte.to_string())),
        }
    }
}

/// HashAlgorithm is the hash algorithm used in the hash lock.
#[repr(u8)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default, Hash)]
#[serde(rename_all = "snake_case")]
pub enum HashAlgorithm {
    /// The default hash algorithm, CkbHash
    #[default]
    CkbHash = 0,
    /// The sha256 hash algorithm
    Sha256 = 1,
}

/// Error for unknown hash algorithm
#[derive(thiserror::Error, Debug)]
#[error("Unknown Hash Algorithm: {0}")]
pub struct UnknownHashAlgorithmError(pub u8);

impl TryFrom<u8> for HashAlgorithm {
    type Error = UnknownHashAlgorithmError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0 => Ok(HashAlgorithm::CkbHash),
            1 => Ok(HashAlgorithm::Sha256),
            _ => Err(UnknownHashAlgorithmError(value)),
        }
    }
}

impl HashAlgorithm {
    pub fn supported_algorithms() -> Vec<HashAlgorithm> {
        vec![HashAlgorithm::CkbHash, HashAlgorithm::Sha256]
    }

    pub fn hash<T: AsRef<[u8]>>(&self, s: T) -> [u8; 32] {
        match self {
            HashAlgorithm::CkbHash => blake2b_256(s),
            HashAlgorithm::Sha256 => sha256(s),
        }
    }
}

/// SHA-256 hash helper function.
pub fn sha256<T: AsRef<[u8]>>(s: T) -> [u8; 32] {
    let mut hasher = Sha256::new();
    hasher.update(s.as_ref());
    hasher.finalize().into()
}

impl TryFrom<Byte> for HashAlgorithm {
    type Error = UnknownHashAlgorithmError;

    fn try_from(value: Byte) -> Result<Self, Self::Error> {
        let value: u8 = value.into();
        value.try_into()
    }
}

/// A wrapper around `ckb_types::packed::Script` with hex serialization.
#[serde_as]
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct CkbScript(#[serde_as(as = "EntityHex")] pub PackedScript);

/// Recoverable signature
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct InvoiceSignature(pub RecoverableSignature);

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

impl Ord for InvoiceSignature {
    fn cmp(&self, other: &Self) -> Ordering {
        self.0
            .serialize_compact()
            .1
            .cmp(&other.0.serialize_compact().1)
    }
}

impl Serialize for InvoiceSignature {
    fn serialize<S>(
        &self,
        serializer: S,
    ) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error>
    where
        S: serde::Serializer,
    {
        let base32: Vec<u8> = self.to_base32().iter().map(|x| x.to_u8()).collect();
        let hex_str = hex::encode(base32);
        hex_str.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for InvoiceSignature {
    fn deserialize<D>(deserializer: D) -> Result<Self, <D as serde::Deserializer<'de>>::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let signature_hex: String = String::deserialize(deserializer)?;
        let signature_bytes = hex::decode(signature_hex).map_err(serde::de::Error::custom)?;
        let base32_values = signature_bytes
            .iter()
            .map(|x| u5::try_from_u8(*x))
            .collect::<Result<Vec<u5>, _>>()
            .map_err(serde::de::Error::custom)?;
        InvoiceSignature::from_base32(&base32_values).map_err(serde::de::Error::custom)
    }
}

struct BytesToBase32<'a, W: WriteBase32 + 'a> {
    writer: &'a mut W,
    buffer: u8,
    buffer_bits: u8,
}

impl<'a, W: WriteBase32> BytesToBase32<'a, W> {
    fn new(writer: &'a mut W) -> Self {
        BytesToBase32 {
            writer,
            buffer: 0,
            buffer_bits: 0,
        }
    }

    fn append(&mut self, byte: u8) -> Result<(), <W as WriteBase32>::Err> {
        let mut bits_remaining = 8;
        while bits_remaining > 0 {
            let bits_to_take = std::cmp::min(5 - self.buffer_bits, bits_remaining);
            self.buffer <<= bits_to_take;
            self.buffer |= (byte >> (bits_remaining - bits_to_take)) & ((1 << bits_to_take) - 1);
            self.buffer_bits += bits_to_take;
            bits_remaining -= bits_to_take;

            if self.buffer_bits == 5 {
                self.writer
                    .write_u5(u5::try_from_u8(self.buffer).expect("buffer is 5 bits"))?;
                self.buffer = 0;
                self.buffer_bits = 0;
            }
        }
        Ok(())
    }

    fn finalize(mut self) -> Result<(), <W as WriteBase32>::Err> {
        if self.buffer_bits > 0 {
            self.buffer <<= 5 - self.buffer_bits;
            self.writer
                .write_u5(u5::try_from_u8(self.buffer).expect("buffer is at most 5 bits"))?;
        }
        Ok(())
    }
}

impl ToBase32 for InvoiceSignature {
    fn write_base32<W: WriteBase32>(&self, writer: &mut W) -> Result<(), <W as WriteBase32>::Err> {
        let mut converter = BytesToBase32::new(writer);
        let (recovery_id, signature) = self.0.serialize_compact();
        for v in signature
            .iter()
            .chain(std::iter::once(&(i32::from(recovery_id) as u8)))
        {
            converter.append(*v)?;
        }
        converter.finalize()
    }
}

impl FromBase32 for InvoiceSignature {
    type Err = anyhow::Error;

    fn from_base32(field_data: &[u5]) -> Result<InvoiceSignature, Self::Err> {
        if field_data.len() < 104 {
            return Err(anyhow::anyhow!(
                "InvoiceSignature TryFrom<[u5]> failed: unexpected length {}",
                field_data.len()
            ));
        }

        let raw_bytes = Vec::<u8>::from_base32(field_data)?;
        if raw_bytes.len() != 65 {
            return Err(anyhow::anyhow!(
                "InvoiceSignature TryFrom<[u5]> failed: unexpected byte length {}",
                raw_bytes.len()
            ));
        }
        let recovery_id = RecoveryId::try_from(raw_bytes[64] as i32)?;
        let signature = RecoverableSignature::from_compact(&raw_bytes[0..64], recovery_id)?;
        Ok(InvoiceSignature(signature))
    }
}

impl InvoiceSignature {
    /// Parse an `InvoiceSignature` from base32-encoded data, returning `InvoiceError` on failure.
    pub fn from_base32_checked(signature: &[u5]) -> Result<Self, InvoiceError> {
        if signature.len() != SIGNATURE_U5_SIZE {
            return Err(InvoiceError::InvalidSliceLength(
                "InvoiceSignature::from_base32_checked()".into(),
            ));
        }
        let recoverable_signature_bytes =
            Vec::<u8>::from_base32(signature).map_err(InvoiceError::Bech32Error)?;
        let sig = &recoverable_signature_bytes[0..64];
        let recovery_id = RecoveryId::try_from(recoverable_signature_bytes[64] as i32)
            .map_err(|_| InvoiceError::InvalidRecoveryId)?;

        Ok(InvoiceSignature(
            RecoverableSignature::from_compact(sig, recovery_id)
                .map_err(|_| InvoiceError::InvalidSignature)?,
        ))
    }
}

use crate::protocol::FeatureVector;
use crate::serde_utils::{duration_hex, U128Hex, U64Hex};
use crate::Hash256;
use secp256k1::PublicKey;
use std::time::Duration;

/// The attributes of the invoice.
#[serde_as]
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Attribute {
    /// This attribute is deprecated since v0.6.0. The final TLC timeout, in milliseconds.
    #[serde(with = "U64Hex")]
    FinalHtlcTimeout(u64),
    /// The final TLC minimum expiry delta, in milliseconds. Default is 160 minutes.
    #[serde(with = "U64Hex")]
    FinalHtlcMinimumExpiryDelta(u64),
    /// The expiry time of the invoice, in seconds.
    #[serde(with = "duration_hex")]
    ExpiryTime(Duration),
    /// The description of the invoice.
    Description(String),
    /// The fallback address of the invoice.
    FallbackAddr(String),
    /// The UDT type script of the invoice.
    UdtScript(CkbScript),
    /// The payee public key of the invoice.
    PayeePublicKey(PublicKey),
    /// The hash algorithm of the invoice.
    HashAlgorithm(HashAlgorithm),
    /// The feature flags of the invoice.
    Feature(FeatureVector),
    /// The payment secret of the invoice.
    PaymentSecret(Hash256),
}

/// The metadata of the invoice.
#[serde_as]
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct InvoiceData {
    /// The timestamp of the invoice.
    #[serde_as(as = "U128Hex")]
    pub timestamp: u128,
    /// The payment hash of the invoice.
    pub payment_hash: Hash256,
    /// The attributes of the invoice, e.g. description, expiry time, etc.
    pub attrs: Vec<Attribute>,
}

/// Represents a syntactically and semantically correct Fiber invoice.
///
/// There are three ways to construct a `CkbInvoice`:
///  1. using `CkbInvoiceBuilder`
///  2. using `str::parse::<CkbInvoice>(&str)` (see `CkbInvoice::from_str`)
#[serde_as]
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct CkbInvoice {
    /// The currency of the invoice.
    pub currency: Currency,
    /// The amount of the invoice.
    #[serde_as(as = "Option<U128Hex>")]
    pub amount: Option<u128>,
    /// The signature of the invoice.
    pub signature: Option<InvoiceSignature>,
    /// The invoice data, including the payment hash, timestamp and other attributes.
    pub data: InvoiceData,
}

impl CkbInvoice {
    fn hrp_part(&self) -> String {
        format!(
            "{}{}",
            self.currency,
            self.amount
                .map_or_else(|| "".to_string(), |x| x.to_string()),
        )
    }

    // Use the lossless compression algorithm to compress the invoice data.
    // To make sure the final encoded invoice address is shorter
    fn data_part(&self) -> Vec<u5> {
        let invoice_data = gen_invoice::RawInvoiceData::from(self.data.clone());
        let compressed = ar_encompress(invoice_data.as_slice()).expect("compress invoice data");
        let mut base32 = Vec::with_capacity(compressed.len());
        compressed
            .write_base32(&mut base32)
            .expect("encode in base32");
        base32
    }

    /// Check that the invoice is signed correctly and that key recovery works.
    pub fn check_signature(&self) -> Result<(), InvoiceError> {
        if self.signature.is_none() {
            return Ok(());
        }
        match self.recover_payee_pub_key() {
            Err(secp256k1::Error::InvalidRecoveryId) => {
                return Err(InvoiceError::InvalidRecoveryId);
            }
            Err(secp256k1::Error::InvalidSignature) => return Err(InvoiceError::InvalidSignature),
            Err(e) => panic!("no other error may occur, got {:?}", e),
            Ok(_) => {}
        }

        if !self.validate_signature() {
            return Err(InvoiceError::InvalidSignature);
        }

        Ok(())
    }

    fn validate_signature(&self) -> bool {
        let Some(signature) = self.signature.as_ref() else {
            return true;
        };
        let included_pub_key = self.payee_pub_key();

        let mut recovered_pub_key = Option::None;
        if included_pub_key.is_none() {
            let recovered = match self.recover_payee_pub_key() {
                Ok(pk) => pk,
                Err(_) => return false,
            };
            recovered_pub_key = Some(recovered);
        }

        let Some(pub_key) = included_pub_key.or(recovered_pub_key.as_ref()) else {
            return false;
        };

        let hash = secp256k1::Message::from_digest_slice(&self.hash()[..])
            .expect("Hash is 32 bytes long, same as MESSAGE_SIZE");

        let verification_result =
            secp256k1::SECP256K1.verify_ecdsa(&hash, &signature.0.to_standard(), pub_key);
        match verification_result {
            Ok(()) => true,
            Err(_) => false,
        }
    }

    fn hash(&self) -> [u8; 32] {
        let hrp = self.hrp_part();
        let data = self.data_part();
        let preimage = construct_invoice_preimage(hrp.as_bytes(), &data);
        sha256(&preimage)
    }

    /// Recovers the public key used for signing the invoice from the recoverable signature.
    pub fn recover_payee_pub_key(&self) -> Result<PublicKey, secp256k1::Error> {
        let hash = secp256k1::Message::from_digest_slice(&self.hash()[..])
            .expect("Hash is 32 bytes long, same as MESSAGE_SIZE");

        secp256k1::SECP256K1.recover_ecdsa(
            &hash,
            &self
                .signature
                .as_ref()
                .ok_or(secp256k1::Error::InvalidSignature)?
                .0,
        )
    }

    /// Returns the payee public key if set in the invoice attributes.
    pub fn payee_pub_key(&self) -> Option<&PublicKey> {
        self.data
            .attrs
            .iter()
            .filter_map(|attr| match attr {
                Attribute::PayeePublicKey(val) => Some(val),
                _ => None,
            })
            .next()
    }

    /// Returns whether the invoice has a signature.
    pub fn is_signed(&self) -> bool {
        self.signature.is_some()
    }

    /// Returns the payment hash of the invoice.
    pub fn payment_hash(&self) -> &Hash256 {
        &self.data.payment_hash
    }

    /// Returns the amount of the invoice.
    pub fn amount(&self) -> Option<u128> {
        self.amount
    }

    /// Returns the UDT type script if set in the invoice attributes.
    pub fn udt_type_script(&self) -> Option<&PackedScript> {
        self.data
            .attrs
            .iter()
            .filter_map(|attr| match attr {
                Attribute::UdtScript(script) => Some(&script.0),
                _ => None,
            })
            .next()
    }

    /// Returns the expiry time if set in the invoice attributes.
    pub fn expiry_time(&self) -> Option<&Duration> {
        self.data
            .attrs
            .iter()
            .filter_map(|attr| match attr {
                Attribute::ExpiryTime(val) => Some(val),
                _ => None,
            })
            .next()
    }

    /// Returns the description if set in the invoice attributes.
    pub fn description(&self) -> Option<&String> {
        self.data
            .attrs
            .iter()
            .filter_map(|attr| match attr {
                Attribute::Description(val) => Some(val),
                _ => None,
            })
            .next()
    }

    /// Returns the final TLC minimum expiry delta if set in the invoice attributes.
    pub fn final_tlc_minimum_expiry_delta(&self) -> Option<&u64> {
        self.data
            .attrs
            .iter()
            .filter_map(|attr| match attr {
                Attribute::FinalHtlcMinimumExpiryDelta(val) => Some(val),
                _ => None,
            })
            .next()
    }

    /// Returns the fallback address if set in the invoice attributes.
    pub fn fallback_address(&self) -> Option<&String> {
        self.data
            .attrs
            .iter()
            .filter_map(|attr| match attr {
                Attribute::FallbackAddr(val) => Some(val),
                _ => None,
            })
            .next()
    }

    /// Returns the hash algorithm if set in the invoice attributes.
    pub fn hash_algorithm(&self) -> Option<&HashAlgorithm> {
        self.data
            .attrs
            .iter()
            .filter_map(|attr| match attr {
                Attribute::HashAlgorithm(val) => Some(val),
                _ => None,
            })
            .next()
    }

    /// Returns the payment secret if set in the invoice attributes.
    pub fn payment_secret(&self) -> Option<&Hash256> {
        self.data
            .attrs
            .iter()
            .filter_map(|attr| match attr {
                Attribute::PaymentSecret(val) => Some(val),
                _ => None,
            })
            .next()
    }

    /// Returns whether the invoice allows MPP (multi-part payments).
    pub fn allow_mpp(&self) -> bool {
        self.data
            .attrs
            .iter()
            .any(|attr| matches!(attr, Attribute::Feature(feature) if feature.supports_basic_mpp()))
    }

    /// Returns whether the invoice allows trampoline routing.
    pub fn allow_trampoline_routing(&self) -> bool {
        self.data
            .attrs
            .iter()
            .any(|attr| matches!(attr, Attribute::Feature(feature) if feature.supports_trampoline_routing()))
    }

    /// Returns whether the invoice has expired based on the current time.
    pub fn is_expired(&self) -> bool {
        self.expiry_time().is_some_and(|expiry| {
            self.data
                .timestamp
                .checked_add(expiry.as_millis())
                .is_some_and(|expiry_time| {
                    let now = crate::crate_time::UNIX_EPOCH
                        .elapsed()
                        .expect("Duration since unix epoch")
                        .as_millis();
                    expiry_time < now
                })
        })
    }

    /// Returns whether the TLC expiry is too soon for the given invoice.
    pub fn is_tlc_expire_too_soon(&self, tlc_expiry: u64) -> bool {
        let now = crate::crate_time::UNIX_EPOCH
            .elapsed()
            .expect("Duration since unix epoch")
            .as_millis();
        let required_expiry = now
            + (self
                .final_tlc_minimum_expiry_delta()
                .cloned()
                .unwrap_or_default() as u128);
        (tlc_expiry as u128) < required_expiry
    }

    /// Updates the invoice signature using the provided signing function.
    pub fn update_signature<F>(&mut self, sign_function: F) -> Result<(), InvoiceError>
    where
        F: FnOnce(&secp256k1::Message) -> RecoverableSignature,
    {
        let hash = self.hash();
        let message =
            secp256k1::Message::from_digest_slice(&hash).expect("message from digest slice");
        let signature = sign_function(&message);
        self.signature = Some(InvoiceSignature(signature));
        self.check_signature()?;
        Ok(())
    }
}

impl Display for CkbInvoice {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let hrp = self.hrp_part();
        let mut data = self.data_part();
        data.insert(
            0,
            u5::try_from_u8(if self.signature.is_some() { 1 } else { 0 }).expect("u5 from u8"),
        );
        if let Some(signature) = &self.signature {
            data.extend_from_slice(&signature.to_base32());
        }
        write!(
            f,
            "{}",
            encode(&hrp, data, Variant::Bech32m).expect("encode invoice using Bech32m")
        )
    }
}

impl FromStr for CkbInvoice {
    type Err = InvoiceError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (hrp, data, var) = bech32::decode(s).map_err(InvoiceError::Bech32Error)?;

        if var == bech32::Variant::Bech32 {
            return Err(InvoiceError::Bech32Error(bech32::Error::InvalidChecksum));
        }

        if data.len() < SIGNATURE_U5_SIZE {
            return Err(InvoiceError::TooShortDataPart);
        }
        let (currency, amount) = parse_hrp(&hrp)?;
        let is_signed = data[0].to_u8() == 1;
        let data_end = if is_signed {
            data.len() - SIGNATURE_U5_SIZE
        } else {
            data.len()
        };
        let data_part =
            Vec::<u8>::from_base32(&data[1..data_end]).map_err(InvoiceError::Bech32Error)?;
        let data_part = ar_decompress_with_limit(&data_part, MAX_INVOICE_DATA_LENGTH)?;
        let invoice_data = gen_invoice::RawInvoiceData::from_slice(&data_part)
            .map_err(|err| InvoiceError::MoleculeError(VerificationError(err)))?;
        let signature = if is_signed {
            Some(InvoiceSignature::from_base32(
                &data[data.len() - SIGNATURE_U5_SIZE..],
            )?)
        } else {
            None
        };

        let invoice = CkbInvoice {
            currency,
            amount,
            signature,
            data: invoice_data.try_into()?,
        };
        invoice.check_signature()?;
        Ok(invoice)
    }
}

/// Converts a `[u8]` slice to `[Byte; 32]`.
fn u8_slice_to_bytes(slice: &[u8]) -> Result<[Byte; 32], &'static str> {
    let vec: Vec<Byte> = slice.iter().map(|&x| Byte::new(x)).collect();
    let boxed_slice = vec.into_boxed_slice();
    let boxed_array: Box<[Byte; 32]> = match boxed_slice.try_into() {
        Ok(ba) => ba,
        Err(_) => return Err("Slice length doesn't match array length"),
    };
    Ok(*boxed_array)
}

/// Converts molecule bytes to `[u8; 32]`.
fn bytes_to_u8_array(array: &molecule::bytes::Bytes) -> [u8; 32] {
    let mut res = [0u8; 32];
    res.copy_from_slice(array);
    res
}

impl From<InvoiceData> for gen_invoice::RawInvoiceData {
    fn from(data: InvoiceData) -> Self {
        RawInvoiceDataBuilder::default()
            .timestamp(data.timestamp.pack())
            .payment_hash(
                PaymentHash::new_builder()
                    .set(
                        u8_slice_to_bytes(data.payment_hash.as_ref()).expect("bytes from u8 slice"),
                    )
                    .build(),
            )
            .attrs(
                InvoiceAttrsVec::new_builder()
                    .set(
                        data.attrs
                            .iter()
                            .map(|a| a.to_owned().into())
                            .collect::<Vec<InvoiceAttr>>(),
                    )
                    .build(),
            )
            .build()
    }
}

impl TryFrom<gen_invoice::RawInvoiceData> for InvoiceData {
    type Error = InvoiceError;

    fn try_from(data: gen_invoice::RawInvoiceData) -> Result<Self, Self::Error> {
        Ok(InvoiceData {
            timestamp: data.timestamp().unpack(),
            payment_hash: bytes_to_u8_array(&data.payment_hash().as_bytes()).into(),
            attrs: data
                .attrs()
                .into_iter()
                .map(Attribute::try_from)
                .collect::<Result<Vec<Attribute>, InvoiceError>>()?,
        })
    }
}

impl From<Attribute> for InvoiceAttr {
    fn from(attr: Attribute) -> Self {
        let a = match attr {
            Attribute::ExpiryTime(x) => {
                let seconds = x.as_secs();
                let value = ExpiryTime::new_builder().value(seconds.pack()).build();
                InvoiceAttrUnion::ExpiryTime(value)
            }
            Attribute::Description(value) => InvoiceAttrUnion::Description(
                Description::new_builder().value(value.pack()).build(),
            ),
            Attribute::FinalHtlcTimeout(value) => InvoiceAttrUnion::FinalHtlcTimeout(
                FinalHtlcTimeout::new_builder().value(value.pack()).build(),
            ),
            Attribute::FinalHtlcMinimumExpiryDelta(value) => {
                InvoiceAttrUnion::FinalHtlcMinimumExpiryDelta(
                    FinalHtlcMinimumExpiryDelta::new_builder()
                        .value(value.pack())
                        .build(),
                )
            }
            Attribute::FallbackAddr(value) => InvoiceAttrUnion::FallbackAddr(
                FallbackAddr::new_builder().value(value.pack()).build(),
            ),
            Attribute::Feature(value) => InvoiceAttrUnion::Feature(
                Feature::new_builder().value(value.bytes().pack()).build(),
            ),
            Attribute::UdtScript(script) => {
                InvoiceAttrUnion::UdtScript(UdtScript::new_builder().value(script.0).build())
            }
            Attribute::PayeePublicKey(pubkey) => InvoiceAttrUnion::PayeePublicKey(
                PayeePublicKey::new_builder()
                    .value(pubkey.serialize().pack())
                    .build(),
            ),
            Attribute::HashAlgorithm(hash_algorithm) => InvoiceAttrUnion::HashAlgorithm(
                gen_invoice::HashAlgorithm::new_builder()
                    .value(Byte::new(hash_algorithm as u8))
                    .build(),
            ),
            Attribute::PaymentSecret(payment_secret) => InvoiceAttrUnion::PaymentSecret(
                PaymentSecret::new_builder()
                    .value(payment_secret.into())
                    .build(),
            ),
        };
        InvoiceAttr::new_builder().set(a).build()
    }
}

impl TryFrom<InvoiceAttr> for Attribute {
    type Error = InvoiceError;

    fn try_from(attr: InvoiceAttr) -> Result<Self, Self::Error> {
        let attr = match attr.to_enum() {
            InvoiceAttrUnion::Description(x) => {
                let value: Vec<u8> = x.value().unpack();
                Attribute::Description(
                    String::from_utf8(value)
                        .map_err(|_| InvoiceError::InvalidUtf8Attribute("description"))?,
                )
            }
            InvoiceAttrUnion::ExpiryTime(x) => {
                let seconds: u64 = x.value().unpack();
                Attribute::ExpiryTime(Duration::from_secs(seconds))
            }

            InvoiceAttrUnion::FinalHtlcTimeout(x) => {
                // This attribute is deprecated since v0.6.0, but we still keep it in molecule for consistency
                Attribute::FinalHtlcTimeout(x.value().unpack())
            }
            InvoiceAttrUnion::FinalHtlcMinimumExpiryDelta(x) => {
                Attribute::FinalHtlcMinimumExpiryDelta(x.value().unpack())
            }
            InvoiceAttrUnion::FallbackAddr(x) => {
                let value: Vec<u8> = x.value().unpack();
                Attribute::FallbackAddr(
                    String::from_utf8(value)
                        .map_err(|_| InvoiceError::InvalidUtf8Attribute("fallback_addr"))?,
                )
            }
            InvoiceAttrUnion::Feature(x) => {
                Attribute::Feature(FeatureVector::from(x.value().unpack()))
            }
            InvoiceAttrUnion::UdtScript(x) => Attribute::UdtScript(CkbScript(x.value())),
            InvoiceAttrUnion::PayeePublicKey(x) => {
                let value: Vec<u8> = x.value().unpack();
                Attribute::PayeePublicKey(
                    PublicKey::from_slice(&value)
                        .map_err(|_| InvoiceError::InvalidPayeePublicKey)?,
                )
            }
            InvoiceAttrUnion::HashAlgorithm(x) => {
                let value = x.value();
                // Consider unknown algorithm as the default one.
                let hash_algorithm = value.try_into().unwrap_or_default();
                Attribute::HashAlgorithm(hash_algorithm)
            }
            InvoiceAttrUnion::PaymentSecret(x) => Attribute::PaymentSecret(x.value().into()),
        };
        Ok(attr)
    }
}

impl From<anyhow::Error> for InvoiceError {
    fn from(_err: anyhow::Error) -> Self {
        InvoiceError::InvalidSignature
    }
}

impl TryFrom<gen_invoice::RawCkbInvoice> for CkbInvoice {
    type Error = InvoiceError;

    fn try_from(invoice: gen_invoice::RawCkbInvoice) -> Result<Self, Self::Error> {
        Ok(CkbInvoice {
            currency: (u8::from(invoice.currency()))
                .try_into()
                .map_err(|e: UnknownCurrencyError| InvoiceError::UnknownCurrency(e.0))?,
            amount: invoice.amount().to_opt().map(|x| x.unpack()),
            signature: invoice
                .signature()
                .to_opt()
                .map(|x| {
                    let signature = x
                        .as_bytes()
                        .into_iter()
                        .map(|x| {
                            u5::try_from_u8(x).map_err(|_| InvoiceError::InvalidSignatureEncoding)
                        })
                        .collect::<Result<Vec<u5>, InvoiceError>>()?;
                    InvoiceSignature::from_base32_checked(&signature)
                })
                .transpose()?,
            data: InvoiceData::try_from(invoice.data())?,
        })
    }
}

impl From<CkbInvoice> for gen_invoice::RawCkbInvoice {
    fn from(invoice: CkbInvoice) -> Self {
        gen_invoice::RawCkbInvoiceBuilder::default()
            .currency((invoice.currency as u8).into())
            .amount(
                gen_invoice::AmountOpt::new_builder()
                    .set(invoice.amount.map(|x| x.pack()))
                    .build(),
            )
            .signature(
                gen_invoice::SignatureOpt::new_builder()
                    .set({
                        invoice.signature.map(|x| {
                            let bytes: [Byte; SIGNATURE_U5_SIZE] = x
                                .to_base32()
                                .iter()
                                .map(|x| Byte::new(x.to_u8()))
                                .collect::<Vec<_>>()
                                .as_slice()
                                .try_into()
                                .expect("[Byte; 104] from [Byte] slice");
                            gen_invoice::Signature::new_builder().set(bytes).build()
                        })
                    })
                    .build(),
            )
            .data(invoice.data.into())
            .build()
    }
}

#[cfg(test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn test_parse_hrp() {
    use super::InvoiceError;

    let res = parse_hrp("fibb1280");
    assert_eq!(res, Ok((Currency::Fibb, Some(1280))));

    let res = parse_hrp("fibb");
    assert_eq!(res, Ok((Currency::Fibb, None)));

    let res = parse_hrp("fibt1023");
    assert_eq!(res, Ok((Currency::Fibt, Some(1023))));

    let res = parse_hrp("fibt10");
    assert_eq!(res, Ok((Currency::Fibt, Some(10))));

    let res = parse_hrp("fibt");
    assert_eq!(res, Ok((Currency::Fibt, None)));

    let res = parse_hrp("xnfibb");
    assert_eq!(res, Err(InvoiceError::MalformedHRP("xnfibb".to_string())));

    let res = parse_hrp("lxfibt");
    assert_eq!(res, Err(InvoiceError::MalformedHRP("lxfibt".to_string())));

    let res = parse_hrp("fibt");
    assert_eq!(res, Ok((Currency::Fibt, None)));

    let res = parse_hrp("fixt");
    assert_eq!(res, Err(InvoiceError::MalformedHRP("fixt".to_string())));

    let res = parse_hrp("fibtt");
    assert_eq!(
        res,
        Err(InvoiceError::MalformedHRP(
            "fibtt, unexpected ending `t`".to_string()
        ))
    );

    let res = parse_hrp("fibt1x24");
    assert_eq!(
        res,
        Err(InvoiceError::MalformedHRP(
            "fibt1x24, unexpected ending `x24`".to_string()
        ))
    );

    let res = parse_hrp("fibt000");
    assert_eq!(res, Ok((Currency::Fibt, Some(0))));

    let res = parse_hrp("fibt1024444444444444444444444444444444444444444444444444444444444444");
    assert!(matches!(res, Err(InvoiceError::ParseAmountError(_))));

    let res = parse_hrp("fibt0x");
    assert!(matches!(res, Err(InvoiceError::MalformedHRP(_))));

    let res = parse_hrp("");
    assert!(matches!(res, Err(InvoiceError::MalformedHRP(_))));
}

#[cfg(test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn test_compress() {
    let input = "hrp1gyqsqqq5qqqqq9gqqqqp6qqqqq0qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq2qqqqqqqqqqqyvqsqqqsqqqqqvqqqqq8";
    let bytes = input.as_bytes();
    let compressed = ar_encompress(input.as_bytes()).unwrap();

    let decompressed = ar_decompress_with_limit(&compressed, MAX_INVOICE_DATA_LENGTH).unwrap();
    let decompressed_str = std::str::from_utf8(&decompressed).unwrap();
    assert_eq!(input, decompressed_str);
    assert!(compressed.len() < bytes.len());
}

#[cfg(test)]
fn raw_invoice_data_with_attrs(attrs: Vec<InvoiceAttr>) -> gen_invoice::RawInvoiceData {
    RawInvoiceDataBuilder::default()
        .timestamp(0u128.pack())
        .payment_hash(PaymentHash::new_builder().set([Byte::new(0); 32]).build())
        .attrs(InvoiceAttrsVec::new_builder().set(attrs).build())
        .build()
}

#[cfg(test)]
fn encode_unsigned_invoice(raw_invoice_data: gen_invoice::RawInvoiceData) -> String {
    let compressed = ar_encompress(raw_invoice_data.as_slice()).unwrap();
    let mut data = vec![u5::try_from_u8(0).unwrap()];
    data.extend(compressed.to_base32());
    assert!(data.len() >= SIGNATURE_U5_SIZE);
    encode("fibb", data, Variant::Bech32m).unwrap()
}

#[cfg(test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn test_parse_malformed_compressed_invoice_returns_error_without_panic() {
    let mut data = vec![u5::try_from_u8(0).unwrap()];
    data.extend(std::iter::repeat(u5::try_from_u8(31).unwrap()).take(SIGNATURE_U5_SIZE));
    let invoice = encode("fibb", data, Variant::Bech32m).unwrap();

    let result = std::panic::catch_unwind(|| CkbInvoice::from_str(&invoice));

    assert!(result.is_ok());
    assert!(result.unwrap().is_err());
}

#[cfg(test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn test_decompressed_invoice_data_length_is_limited() {
    let payload = vec![0u8; MAX_INVOICE_DATA_LENGTH + 1];
    let compressed = ar_encompress(&payload).unwrap();

    let result = ar_decompress_with_limit(&compressed, MAX_INVOICE_DATA_LENGTH);

    assert!(matches!(
        result,
        Err(InvoiceError::InvoiceDataTooLong {
            len,
            max: MAX_INVOICE_DATA_LENGTH,
        }) if len > MAX_INVOICE_DATA_LENGTH
    ));
}

#[cfg(test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn test_malformed_text_attribute_returns_error_without_panic() {
    let attr = InvoiceAttr::new_builder()
        .set(InvoiceAttrUnion::Description(
            Description::new_builder()
                .value(vec![0xff; 200].pack())
                .build(),
        ))
        .build();
    let invoice = encode_unsigned_invoice(raw_invoice_data_with_attrs(vec![attr]));

    let result = std::panic::catch_unwind(|| CkbInvoice::from_str(&invoice));

    assert!(matches!(
        result,
        Ok(Err(InvoiceError::InvalidUtf8Attribute("description")))
    ));
}

#[cfg(test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn test_malformed_payee_public_key_returns_error_without_panic() {
    let attr = InvoiceAttr::new_builder()
        .set(InvoiceAttrUnion::PayeePublicKey(
            PayeePublicKey::new_builder()
                .value(vec![1, 2, 3].pack())
                .build(),
        ))
        .build();
    let raw_invoice_data = raw_invoice_data_with_attrs(vec![attr]);

    let result = std::panic::catch_unwind(|| InvoiceData::try_from(raw_invoice_data));

    assert!(matches!(
        result,
        Ok(Err(InvoiceError::InvalidPayeePublicKey))
    ));
}

#[cfg(test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn test_malformed_raw_invoice_signature_returns_error_without_panic() {
    let signature = gen_invoice::Signature::new_builder()
        .set([Byte::new(32); SIGNATURE_U5_SIZE])
        .build();
    let raw_invoice = gen_invoice::RawCkbInvoiceBuilder::default()
        .currency(Byte::new(Currency::Fibb as u8))
        .signature(
            gen_invoice::SignatureOpt::new_builder()
                .set(Some(signature))
                .build(),
        )
        .data(raw_invoice_data_with_attrs(vec![]))
        .build();

    let result = std::panic::catch_unwind(|| CkbInvoice::try_from(raw_invoice));

    assert!(matches!(
        result,
        Ok(Err(InvoiceError::InvalidSignatureEncoding))
    ));
}