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
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.

//! Data structures and encoding for `invoice_request` messages.
//!
//! An [`InvoiceRequest`] can be built from a parsed [`Offer`] as an "offer to be paid". It is
//! typically constructed by a customer and sent to the merchant who had published the corresponding
//! offer. The recipient of the request responds with a [`Bolt12Invoice`].
//!
//! For an "offer for money" (e.g., refund, ATM withdrawal), where an offer doesn't exist as a
//! precursor, see [`Refund`].
//!
//! [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
//! [`Refund`]: crate::offers::refund::Refund
//!
//! ```
//! extern crate bitcoin;
//! extern crate lightning;
//!
//! use bitcoin::network::constants::Network;
//! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
//! use core::convert::Infallible;
//! use lightning::ln::features::OfferFeatures;
//! use lightning::offers::offer::Offer;
//! use lightning::util::ser::Writeable;
//!
//! # fn parse() -> Result<(), lightning::offers::parse::Bolt12ParseError> {
//! let secp_ctx = Secp256k1::new();
//! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
//! let pubkey = PublicKey::from(keys);
//! let mut buffer = Vec::new();
//!
//! "lno1qcp4256ypq"
//!     .parse::<Offer>()?
//!     .request_invoice(vec![42; 64], pubkey)?
//!     .chain(Network::Testnet)?
//!     .amount_msats(1000)?
//!     .quantity(5)?
//!     .payer_note("foo".to_string())
//!     .build()?
//!     .sign::<_, Infallible>(
//!         |message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
//!     )
//!     .expect("failed verifying signature")
//!     .write(&mut buffer)
//!     .unwrap();
//! # Ok(())
//! # }
//! ```

use bitcoin::blockdata::constants::ChainHash;
use bitcoin::network::constants::Network;
use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, self};
use bitcoin::secp256k1::schnorr::Signature;
use core::convert::{AsRef, Infallible, TryFrom};
use core::ops::Deref;
use crate::sign::EntropySource;
use crate::io;
use crate::blinded_path::BlindedPath;
use crate::ln::PaymentHash;
use crate::ln::channelmanager::PaymentId;
use crate::ln::features::InvoiceRequestFeatures;
use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
use crate::ln::msgs::DecodeError;
use crate::offers::invoice::{BlindedPayInfo, DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder};
use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, TaggedHash, self};
use crate::offers::offer::{Offer, OfferContents, OfferTlvStream, OfferTlvStreamRef};
use crate::offers::parse::{Bolt12ParseError, ParsedMessage, Bolt12SemanticError};
use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
use crate::offers::signer::{Metadata, MetadataMaterial};
use crate::util::ser::{HighZeroBytesDroppedBigSize, SeekReadable, WithoutLength, Writeable, Writer};
use crate::util::string::PrintableString;

use crate::prelude::*;

/// Tag for the hash function used when signing an [`InvoiceRequest`]'s merkle root.
pub const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice_request", "signature");

pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Invreq ~~~~~";

/// Builds an [`InvoiceRequest`] from an [`Offer`] for the "offer to be paid" flow.
///
/// See [module-level documentation] for usage.
///
/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
///
/// [module-level documentation]: self
pub struct InvoiceRequestBuilder<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> {
	offer: &'a Offer,
	invoice_request: InvoiceRequestContentsWithoutPayerId,
	payer_id: Option<PublicKey>,
	payer_id_strategy: core::marker::PhantomData<P>,
	secp_ctx: Option<&'b Secp256k1<T>>,
}

/// Indicates how [`InvoiceRequest::payer_id`] will be set.
///
/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
pub trait PayerIdStrategy {}

/// [`InvoiceRequest::payer_id`] will be explicitly set.
///
/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
pub struct ExplicitPayerId {}

/// [`InvoiceRequest::payer_id`] will be derived.
///
/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
pub struct DerivedPayerId {}

impl PayerIdStrategy for ExplicitPayerId {}
impl PayerIdStrategy for DerivedPayerId {}

impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, ExplicitPayerId, T> {
	pub(super) fn new(offer: &'a Offer, metadata: Vec<u8>, payer_id: PublicKey) -> Self {
		Self {
			offer,
			invoice_request: Self::create_contents(offer, Metadata::Bytes(metadata)),
			payer_id: Some(payer_id),
			payer_id_strategy: core::marker::PhantomData,
			secp_ctx: None,
		}
	}

	pub(super) fn deriving_metadata<ES: Deref>(
		offer: &'a Offer, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
		payment_id: PaymentId,
	) -> Self where ES::Target: EntropySource {
		let nonce = Nonce::from_entropy_source(entropy_source);
		let payment_id = Some(payment_id);
		let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, payment_id);
		let metadata = Metadata::Derived(derivation_material);
		Self {
			offer,
			invoice_request: Self::create_contents(offer, metadata),
			payer_id: Some(payer_id),
			payer_id_strategy: core::marker::PhantomData,
			secp_ctx: None,
		}
	}
}

impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T> {
	pub(super) fn deriving_payer_id<ES: Deref>(
		offer: &'a Offer, expanded_key: &ExpandedKey, entropy_source: ES,
		secp_ctx: &'b Secp256k1<T>, payment_id: PaymentId
	) -> Self where ES::Target: EntropySource {
		let nonce = Nonce::from_entropy_source(entropy_source);
		let payment_id = Some(payment_id);
		let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, payment_id);
		let metadata = Metadata::DerivedSigningPubkey(derivation_material);
		Self {
			offer,
			invoice_request: Self::create_contents(offer, metadata),
			payer_id: None,
			payer_id_strategy: core::marker::PhantomData,
			secp_ctx: Some(secp_ctx),
		}
	}
}

impl<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, P, T> {
	fn create_contents(offer: &Offer, metadata: Metadata) -> InvoiceRequestContentsWithoutPayerId {
		let offer = offer.contents.clone();
		InvoiceRequestContentsWithoutPayerId {
			payer: PayerContents(metadata), offer, chain: None, amount_msats: None,
			features: InvoiceRequestFeatures::empty(), quantity: None, payer_note: None,
		}
	}

	/// Sets the [`InvoiceRequest::chain`] of the given [`Network`] for paying an invoice. If not
	/// called, [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported
	/// by the offer.
	///
	/// Successive calls to this method will override the previous setting.
	pub fn chain(self, network: Network) -> Result<Self, Bolt12SemanticError> {
		self.chain_hash(ChainHash::using_genesis_block(network))
	}

	/// Sets the [`InvoiceRequest::chain`] for paying an invoice. If not called, the chain hash of
	/// [`Network::Bitcoin`] is assumed. Errors if the chain for `network` is not supported by the
	/// offer.
	///
	/// Successive calls to this method will override the previous setting.
	pub(crate) fn chain_hash(mut self, chain: ChainHash) -> Result<Self, Bolt12SemanticError> {
		if !self.offer.supports_chain(chain) {
			return Err(Bolt12SemanticError::UnsupportedChain);
		}

		self.invoice_request.chain = Some(chain);
		Ok(self)
	}

	/// Sets the [`InvoiceRequest::amount_msats`] for paying an invoice. Errors if `amount_msats` is
	/// not at least the expected invoice amount (i.e., [`Offer::amount`] times [`quantity`]).
	///
	/// Successive calls to this method will override the previous setting.
	///
	/// [`quantity`]: Self::quantity
	pub fn amount_msats(mut self, amount_msats: u64) -> Result<Self, Bolt12SemanticError> {
		self.invoice_request.offer.check_amount_msats_for_quantity(
			Some(amount_msats), self.invoice_request.quantity
		)?;
		self.invoice_request.amount_msats = Some(amount_msats);
		Ok(self)
	}

	/// Sets [`InvoiceRequest::quantity`] of items. If not set, `1` is assumed. Errors if `quantity`
	/// does not conform to [`Offer::is_valid_quantity`].
	///
	/// Successive calls to this method will override the previous setting.
	pub fn quantity(mut self, quantity: u64) -> Result<Self, Bolt12SemanticError> {
		self.invoice_request.offer.check_quantity(Some(quantity))?;
		self.invoice_request.quantity = Some(quantity);
		Ok(self)
	}

	/// Sets the [`InvoiceRequest::payer_note`].
	///
	/// Successive calls to this method will override the previous setting.
	pub fn payer_note(mut self, payer_note: String) -> Self {
		self.invoice_request.payer_note = Some(payer_note);
		self
	}

	fn build_with_checks(mut self) -> Result<
		(UnsignedInvoiceRequest, Option<KeyPair>, Option<&'b Secp256k1<T>>),
		Bolt12SemanticError
	> {
		#[cfg(feature = "std")] {
			if self.offer.is_expired() {
				return Err(Bolt12SemanticError::AlreadyExpired);
			}
		}

		let chain = self.invoice_request.chain();
		if !self.offer.supports_chain(chain) {
			return Err(Bolt12SemanticError::UnsupportedChain);
		}

		if chain == self.offer.implied_chain() {
			self.invoice_request.chain = None;
		}

		if self.offer.amount().is_none() && self.invoice_request.amount_msats.is_none() {
			return Err(Bolt12SemanticError::MissingAmount);
		}

		self.invoice_request.offer.check_quantity(self.invoice_request.quantity)?;
		self.invoice_request.offer.check_amount_msats_for_quantity(
			self.invoice_request.amount_msats, self.invoice_request.quantity
		)?;

		Ok(self.build_without_checks())
	}

	fn build_without_checks(mut self) ->
		(UnsignedInvoiceRequest, Option<KeyPair>, Option<&'b Secp256k1<T>>)
	{
		// Create the metadata for stateless verification of a Bolt12Invoice.
		let mut keys = None;
		let secp_ctx = self.secp_ctx.clone();
		if self.invoice_request.payer.0.has_derivation_material() {
			let mut metadata = core::mem::take(&mut self.invoice_request.payer.0);

			let mut tlv_stream = self.invoice_request.as_tlv_stream();
			debug_assert!(tlv_stream.2.payer_id.is_none());
			tlv_stream.0.metadata = None;
			if !metadata.derives_payer_keys() {
				tlv_stream.2.payer_id = self.payer_id.as_ref();
			}

			let (derived_metadata, derived_keys) = metadata.derive_from(tlv_stream, self.secp_ctx);
			metadata = derived_metadata;
			keys = derived_keys;
			if let Some(keys) = keys {
				debug_assert!(self.payer_id.is_none());
				self.payer_id = Some(keys.public_key());
			}

			self.invoice_request.payer.0 = metadata;
		}

		debug_assert!(self.invoice_request.payer.0.as_bytes().is_some());
		debug_assert!(self.payer_id.is_some());
		let payer_id = self.payer_id.unwrap();

		let invoice_request = InvoiceRequestContents {
			inner: self.invoice_request,
			payer_id,
		};
		let unsigned_invoice_request = UnsignedInvoiceRequest::new(self.offer, invoice_request);

		(unsigned_invoice_request, keys, secp_ctx)
	}
}

impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, ExplicitPayerId, T> {
	/// Builds an unsigned [`InvoiceRequest`] after checking for valid semantics. It can be signed
	/// by [`UnsignedInvoiceRequest::sign`].
	pub fn build(self) -> Result<UnsignedInvoiceRequest, Bolt12SemanticError> {
		let (unsigned_invoice_request, keys, _) = self.build_with_checks()?;
		debug_assert!(keys.is_none());
		Ok(unsigned_invoice_request)
	}
}

impl<'a, 'b, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T> {
	/// Builds a signed [`InvoiceRequest`] after checking for valid semantics.
	pub fn build_and_sign(self) -> Result<InvoiceRequest, Bolt12SemanticError> {
		let (unsigned_invoice_request, keys, secp_ctx) = self.build_with_checks()?;
		debug_assert!(keys.is_some());

		let secp_ctx = secp_ctx.unwrap();
		let keys = keys.unwrap();
		let invoice_request = unsigned_invoice_request
			.sign::<_, Infallible>(
				|message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
			)
			.unwrap();
		Ok(invoice_request)
	}
}

#[cfg(test)]
impl<'a, 'b, P: PayerIdStrategy, T: secp256k1::Signing> InvoiceRequestBuilder<'a, 'b, P, T> {
	fn chain_unchecked(mut self, network: Network) -> Self {
		let chain = ChainHash::using_genesis_block(network);
		self.invoice_request.chain = Some(chain);
		self
	}

	fn amount_msats_unchecked(mut self, amount_msats: u64) -> Self {
		self.invoice_request.amount_msats = Some(amount_msats);
		self
	}

	fn features_unchecked(mut self, features: InvoiceRequestFeatures) -> Self {
		self.invoice_request.features = features;
		self
	}

	fn quantity_unchecked(mut self, quantity: u64) -> Self {
		self.invoice_request.quantity = Some(quantity);
		self
	}

	pub(super) fn build_unchecked(self) -> UnsignedInvoiceRequest {
		self.build_without_checks().0
	}
}

/// A semantically valid [`InvoiceRequest`] that hasn't been signed.
///
/// # Serialization
///
/// This is serialized as a TLV stream, which includes TLV records from the originating message. As
/// such, it may include unknown, odd TLV records.
pub struct UnsignedInvoiceRequest {
	bytes: Vec<u8>,
	contents: InvoiceRequestContents,
	tagged_hash: TaggedHash,
}

impl UnsignedInvoiceRequest {
	fn new(offer: &Offer, contents: InvoiceRequestContents) -> Self {
		// Use the offer bytes instead of the offer TLV stream as the offer may have contained
		// unknown TLV records, which are not stored in `OfferContents`.
		let (payer_tlv_stream, _offer_tlv_stream, invoice_request_tlv_stream) =
			contents.as_tlv_stream();
		let offer_bytes = WithoutLength(&offer.bytes);
		let unsigned_tlv_stream = (payer_tlv_stream, offer_bytes, invoice_request_tlv_stream);

		let mut bytes = Vec::new();
		unsigned_tlv_stream.write(&mut bytes).unwrap();

		let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);

		Self { bytes, contents, tagged_hash }
	}

	/// Returns the [`TaggedHash`] of the invoice to sign.
	pub fn tagged_hash(&self) -> &TaggedHash {
		&self.tagged_hash
	}

	/// Signs the [`TaggedHash`] of the invoice request using the given function.
	///
	/// Note: The hash computation may have included unknown, odd TLV records.
	///
	/// This is not exported to bindings users as functions are not yet mapped.
	pub fn sign<F, E>(mut self, sign: F) -> Result<InvoiceRequest, SignError<E>>
	where
		F: FnOnce(&Self) -> Result<Signature, E>
	{
		let pubkey = self.contents.payer_id;
		let signature = merkle::sign_message(sign, &self, pubkey)?;

		// Append the signature TLV record to the bytes.
		let signature_tlv_stream = SignatureTlvStreamRef {
			signature: Some(&signature),
		};
		signature_tlv_stream.write(&mut self.bytes).unwrap();

		Ok(InvoiceRequest {
			bytes: self.bytes,
			contents: self.contents,
			signature,
		})
	}
}

impl AsRef<TaggedHash> for UnsignedInvoiceRequest {
	fn as_ref(&self) -> &TaggedHash {
		&self.tagged_hash
	}
}

/// An `InvoiceRequest` is a request for a [`Bolt12Invoice`] formulated from an [`Offer`].
///
/// An offer may provide choices such as quantity, amount, chain, features, etc. An invoice request
/// specifies these such that its recipient can send an invoice for payment.
///
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Offer`]: crate::offers::offer::Offer
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub struct InvoiceRequest {
	pub(super) bytes: Vec<u8>,
	pub(super) contents: InvoiceRequestContents,
	signature: Signature,
}

/// An [`InvoiceRequest`] that has been verified by [`InvoiceRequest::verify`] and exposes different
/// ways to respond depending on whether the signing keys were derived.
#[derive(Clone, Debug)]
pub struct VerifiedInvoiceRequest {
	/// The verified request.
	inner: InvoiceRequest,

	/// Keys used for signing a [`Bolt12Invoice`] if they can be derived.
	///
	/// If `Some`, must call [`respond_using_derived_keys`] when responding. Otherwise, call
	/// [`respond_with`].
	///
	/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
	/// [`respond_using_derived_keys`]: Self::respond_using_derived_keys
	/// [`respond_with`]: Self::respond_with
	pub keys: Option<KeyPair>,
}

/// The contents of an [`InvoiceRequest`], which may be shared with an [`Bolt12Invoice`].
///
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub(super) struct InvoiceRequestContents {
	pub(super) inner: InvoiceRequestContentsWithoutPayerId,
	payer_id: PublicKey,
}

#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub(super) struct InvoiceRequestContentsWithoutPayerId {
	payer: PayerContents,
	pub(super) offer: OfferContents,
	chain: Option<ChainHash>,
	amount_msats: Option<u64>,
	features: InvoiceRequestFeatures,
	quantity: Option<u64>,
	payer_note: Option<String>,
}

macro_rules! invoice_request_accessors { ($self: ident, $contents: expr) => {
	/// An unpredictable series of bytes, typically containing information about the derivation of
	/// [`payer_id`].
	///
	/// [`payer_id`]: Self::payer_id
	pub fn payer_metadata(&$self) -> &[u8] {
		$contents.metadata()
	}

	/// A chain from [`Offer::chains`] that the offer is valid for.
	pub fn chain(&$self) -> ChainHash {
		$contents.chain()
	}

	/// The amount to pay in msats (i.e., the minimum lightning-payable unit for [`chain`]), which
	/// must be greater than or equal to [`Offer::amount`], converted if necessary.
	///
	/// [`chain`]: Self::chain
	pub fn amount_msats(&$self) -> Option<u64> {
		$contents.amount_msats()
	}

	/// Features pertaining to requesting an invoice.
	pub fn invoice_request_features(&$self) -> &InvoiceRequestFeatures {
		&$contents.features()
	}

	/// The quantity of the offer's item conforming to [`Offer::is_valid_quantity`].
	pub fn quantity(&$self) -> Option<u64> {
		$contents.quantity()
	}

	/// A possibly transient pubkey used to sign the invoice request.
	pub fn payer_id(&$self) -> PublicKey {
		$contents.payer_id()
	}

	/// A payer-provided note which will be seen by the recipient and reflected back in the invoice
	/// response.
	pub fn payer_note(&$self) -> Option<PrintableString> {
		$contents.payer_note()
	}
} }

impl UnsignedInvoiceRequest {
	offer_accessors!(self, self.contents.inner.offer);
	invoice_request_accessors!(self, self.contents);
}

impl InvoiceRequest {
	offer_accessors!(self, self.contents.inner.offer);
	invoice_request_accessors!(self, self.contents);

	/// Signature of the invoice request using [`payer_id`].
	///
	/// [`payer_id`]: Self::payer_id
	pub fn signature(&self) -> Signature {
		self.signature
	}

	/// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
	/// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
	///
	/// See [`InvoiceRequest::respond_with_no_std`] for further details where the aforementioned
	/// creation time is used for the `created_at` parameter.
	///
	/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
	///
	/// [`Duration`]: core::time::Duration
	#[cfg(feature = "std")]
	pub fn respond_with(
		&self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
	) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
		let created_at = std::time::SystemTime::now()
			.duration_since(std::time::SystemTime::UNIX_EPOCH)
			.expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");

		self.respond_with_no_std(payment_paths, payment_hash, created_at)
	}

	/// Creates an [`InvoiceBuilder`] for the request with the given required fields.
	///
	/// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
	/// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
	/// where [`std::time::SystemTime`] is not available.
	///
	/// The caller is expected to remember the preimage of `payment_hash` in order to claim a payment
	/// for the invoice.
	///
	/// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
	/// must contain one or more elements ordered from most-preferred to least-preferred, if there's
	/// a preference. Note, however, that any privacy is lost if a public node id was used for
	/// [`Offer::signing_pubkey`].
	///
	/// Errors if the request contains unknown required features.
	///
	/// # Note
	///
	/// If the originating [`Offer`] was created using [`OfferBuilder::deriving_signing_pubkey`],
	/// then use [`InvoiceRequest::verify`] and [`VerifiedInvoiceRequest`] methods instead.
	///
	/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
	///
	/// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
	/// [`OfferBuilder::deriving_signing_pubkey`]: crate::offers::offer::OfferBuilder::deriving_signing_pubkey
	pub fn respond_with_no_std(
		&self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
		created_at: core::time::Duration
	) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
		if self.invoice_request_features().requires_unknown_bits() {
			return Err(Bolt12SemanticError::UnknownRequiredFeatures);
		}

		InvoiceBuilder::for_offer(self, payment_paths, created_at, payment_hash)
	}

	/// Verifies that the request was for an offer created using the given key. Returns the verified
	/// request which contains the derived keys needed to sign a [`Bolt12Invoice`] for the request
	/// if they could be extracted from the metadata.
	///
	/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
	pub fn verify<T: secp256k1::Signing>(
		self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
	) -> Result<VerifiedInvoiceRequest, ()> {
		let keys = self.contents.inner.offer.verify(&self.bytes, key, secp_ctx)?;
		Ok(VerifiedInvoiceRequest {
			inner: self,
			keys,
		})
	}

	pub(crate) fn as_tlv_stream(&self) -> FullInvoiceRequestTlvStreamRef {
		let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream) =
			self.contents.as_tlv_stream();
		let signature_tlv_stream = SignatureTlvStreamRef {
			signature: Some(&self.signature),
		};
		(payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, signature_tlv_stream)
	}
}

impl VerifiedInvoiceRequest {
	offer_accessors!(self, self.inner.contents.inner.offer);
	invoice_request_accessors!(self, self.inner.contents);

	/// Creates an [`InvoiceBuilder`] for the request with the given required fields and using the
	/// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
	///
	/// See [`InvoiceRequest::respond_with_no_std`] for further details.
	///
	/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
	///
	/// [`Duration`]: core::time::Duration
	#[cfg(feature = "std")]
	pub fn respond_with(
		&self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
	) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
		self.inner.respond_with(payment_paths, payment_hash)
	}

	/// Creates an [`InvoiceBuilder`] for the request with the given required fields.
	///
	/// See [`InvoiceRequest::respond_with_no_std`] for further details.
	///
	/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
	pub fn respond_with_no_std(
		&self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
		created_at: core::time::Duration
	) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
		self.inner.respond_with_no_std(payment_paths, payment_hash, created_at)
	}

	/// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
	/// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
	/// the same [`ExpandedKey`] as the one used to create the offer.
	///
	/// See [`InvoiceRequest::respond_with`] for further details.
	///
	/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
	///
	/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
	#[cfg(feature = "std")]
	pub fn respond_using_derived_keys(
		&self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash
	) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError> {
		let created_at = std::time::SystemTime::now()
			.duration_since(std::time::SystemTime::UNIX_EPOCH)
			.expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");

		self.respond_using_derived_keys_no_std(payment_paths, payment_hash, created_at)
	}

	/// Creates an [`InvoiceBuilder`] for the request using the given required fields and that uses
	/// derived signing keys from the originating [`Offer`] to sign the [`Bolt12Invoice`]. Must use
	/// the same [`ExpandedKey`] as the one used to create the offer.
	///
	/// See [`InvoiceRequest::respond_with_no_std`] for further details.
	///
	/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
	///
	/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
	pub fn respond_using_derived_keys_no_std(
		&self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
		created_at: core::time::Duration
	) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError> {
		if self.inner.invoice_request_features().requires_unknown_bits() {
			return Err(Bolt12SemanticError::UnknownRequiredFeatures);
		}

		let keys = match self.keys {
			None => return Err(Bolt12SemanticError::InvalidMetadata),
			Some(keys) => keys,
		};

		InvoiceBuilder::for_offer_using_keys(
			&self.inner, payment_paths, created_at, payment_hash, keys
		)
	}
}

impl InvoiceRequestContents {
	pub(super) fn metadata(&self) -> &[u8] {
		self.inner.metadata()
	}

	pub(super) fn derives_keys(&self) -> bool {
		self.inner.payer.0.derives_payer_keys()
	}

	pub(super) fn chain(&self) -> ChainHash {
		self.inner.chain()
	}

	pub(super) fn amount_msats(&self) -> Option<u64> {
		self.inner.amount_msats
	}

	pub(super) fn features(&self) -> &InvoiceRequestFeatures {
		&self.inner.features
	}

	pub(super) fn quantity(&self) -> Option<u64> {
		self.inner.quantity
	}

	pub(super) fn payer_id(&self) -> PublicKey {
		self.payer_id
	}

	pub(super) fn payer_note(&self) -> Option<PrintableString> {
		self.inner.payer_note.as_ref()
			.map(|payer_note| PrintableString(payer_note.as_str()))
	}

	pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
		let (payer, offer, mut invoice_request) = self.inner.as_tlv_stream();
		invoice_request.payer_id = Some(&self.payer_id);
		(payer, offer, invoice_request)
	}
}

impl InvoiceRequestContentsWithoutPayerId {
	pub(super) fn metadata(&self) -> &[u8] {
		self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
	}

	pub(super) fn chain(&self) -> ChainHash {
		self.chain.unwrap_or_else(|| self.offer.implied_chain())
	}

	pub(super) fn as_tlv_stream(&self) -> PartialInvoiceRequestTlvStreamRef {
		let payer = PayerTlvStreamRef {
			metadata: self.payer.0.as_bytes(),
		};

		let offer = self.offer.as_tlv_stream();

		let features = {
			if self.features == InvoiceRequestFeatures::empty() { None }
			else { Some(&self.features) }
		};

		let invoice_request = InvoiceRequestTlvStreamRef {
			chain: self.chain.as_ref(),
			amount: self.amount_msats,
			features,
			quantity: self.quantity,
			payer_id: None,
			payer_note: self.payer_note.as_ref(),
		};

		(payer, offer, invoice_request)
	}
}

impl Writeable for UnsignedInvoiceRequest {
	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
		WithoutLength(&self.bytes).write(writer)
	}
}

impl Writeable for InvoiceRequest {
	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
		WithoutLength(&self.bytes).write(writer)
	}
}

impl Writeable for InvoiceRequestContents {
	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
		self.as_tlv_stream().write(writer)
	}
}

/// Valid type range for invoice_request TLV records.
pub(super) const INVOICE_REQUEST_TYPES: core::ops::Range<u64> = 80..160;

/// TLV record type for [`InvoiceRequest::payer_id`] and [`Refund::payer_id`].
///
/// [`Refund::payer_id`]: crate::offers::refund::Refund::payer_id
pub(super) const INVOICE_REQUEST_PAYER_ID_TYPE: u64 = 88;

tlv_stream!(InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef, INVOICE_REQUEST_TYPES, {
	(80, chain: ChainHash),
	(82, amount: (u64, HighZeroBytesDroppedBigSize)),
	(84, features: (InvoiceRequestFeatures, WithoutLength)),
	(86, quantity: (u64, HighZeroBytesDroppedBigSize)),
	(INVOICE_REQUEST_PAYER_ID_TYPE, payer_id: PublicKey),
	(89, payer_note: (String, WithoutLength)),
});

type FullInvoiceRequestTlvStream =
	(PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, SignatureTlvStream);

type FullInvoiceRequestTlvStreamRef<'a> = (
	PayerTlvStreamRef<'a>,
	OfferTlvStreamRef<'a>,
	InvoiceRequestTlvStreamRef<'a>,
	SignatureTlvStreamRef<'a>,
);

impl SeekReadable for FullInvoiceRequestTlvStream {
	fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
		let payer = SeekReadable::read(r)?;
		let offer = SeekReadable::read(r)?;
		let invoice_request = SeekReadable::read(r)?;
		let signature = SeekReadable::read(r)?;

		Ok((payer, offer, invoice_request, signature))
	}
}

type PartialInvoiceRequestTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);

type PartialInvoiceRequestTlvStreamRef<'a> = (
	PayerTlvStreamRef<'a>,
	OfferTlvStreamRef<'a>,
	InvoiceRequestTlvStreamRef<'a>,
);

impl TryFrom<Vec<u8>> for UnsignedInvoiceRequest {
	type Error = Bolt12ParseError;

	fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
		let invoice_request = ParsedMessage::<PartialInvoiceRequestTlvStream>::try_from(bytes)?;
		let ParsedMessage { bytes, tlv_stream } = invoice_request;
		let (
			payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
		) = tlv_stream;
		let contents = InvoiceRequestContents::try_from(
			(payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
		)?;

		let tagged_hash = TaggedHash::new(SIGNATURE_TAG, &bytes);

		Ok(UnsignedInvoiceRequest { bytes, contents, tagged_hash })
	}
}

impl TryFrom<Vec<u8>> for InvoiceRequest {
	type Error = Bolt12ParseError;

	fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
		let invoice_request = ParsedMessage::<FullInvoiceRequestTlvStream>::try_from(bytes)?;
		let ParsedMessage { bytes, tlv_stream } = invoice_request;
		let (
			payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream,
			SignatureTlvStream { signature },
		) = tlv_stream;
		let contents = InvoiceRequestContents::try_from(
			(payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
		)?;

		let signature = match signature {
			None => return Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
			Some(signature) => signature,
		};
		let message = TaggedHash::new(SIGNATURE_TAG, &bytes);
		merkle::verify_signature(&signature, &message, contents.payer_id)?;

		Ok(InvoiceRequest { bytes, contents, signature })
	}
}

impl TryFrom<PartialInvoiceRequestTlvStream> for InvoiceRequestContents {
	type Error = Bolt12SemanticError;

	fn try_from(tlv_stream: PartialInvoiceRequestTlvStream) -> Result<Self, Self::Error> {
		let (
			PayerTlvStream { metadata },
			offer_tlv_stream,
			InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
		) = tlv_stream;

		let payer = match metadata {
			None => return Err(Bolt12SemanticError::MissingPayerMetadata),
			Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
		};
		let offer = OfferContents::try_from(offer_tlv_stream)?;

		if !offer.supports_chain(chain.unwrap_or_else(|| offer.implied_chain())) {
			return Err(Bolt12SemanticError::UnsupportedChain);
		}

		if offer.amount().is_none() && amount.is_none() {
			return Err(Bolt12SemanticError::MissingAmount);
		}

		offer.check_quantity(quantity)?;
		offer.check_amount_msats_for_quantity(amount, quantity)?;

		let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);

		let payer_id = match payer_id {
			None => return Err(Bolt12SemanticError::MissingPayerId),
			Some(payer_id) => payer_id,
		};

		Ok(InvoiceRequestContents {
			inner: InvoiceRequestContentsWithoutPayerId {
				payer, offer, chain, amount_msats: amount, features, quantity, payer_note,
			},
			payer_id,
		})
	}
}

#[cfg(test)]
mod tests {
	use super::{InvoiceRequest, InvoiceRequestTlvStreamRef, SIGNATURE_TAG, UnsignedInvoiceRequest};

	use bitcoin::blockdata::constants::ChainHash;
	use bitcoin::network::constants::Network;
	use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey, self};
	use core::convert::{Infallible, TryFrom};
	use core::num::NonZeroU64;
	#[cfg(feature = "std")]
	use core::time::Duration;
	use crate::sign::KeyMaterial;
	use crate::ln::channelmanager::PaymentId;
	use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
	use crate::ln::inbound_payment::ExpandedKey;
	use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
	use crate::offers::invoice::{Bolt12Invoice, SIGNATURE_TAG as INVOICE_SIGNATURE_TAG};
	use crate::offers::merkle::{SignError, SignatureTlvStreamRef, TaggedHash, self};
	use crate::offers::offer::{Amount, OfferBuilder, OfferTlvStreamRef, Quantity};
	use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
	use crate::offers::payer::PayerTlvStreamRef;
	use crate::offers::test_utils::*;
	use crate::util::ser::{BigSize, Writeable};
	use crate::util::string::PrintableString;

	#[test]
	fn builds_invoice_request_with_defaults() {
		let unsigned_invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.build().unwrap();

		let mut buffer = Vec::new();
		unsigned_invoice_request.write(&mut buffer).unwrap();

		assert_eq!(unsigned_invoice_request.bytes, buffer.as_slice());
		assert_eq!(unsigned_invoice_request.payer_metadata(), &[1; 32]);
		assert_eq!(unsigned_invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
		assert_eq!(unsigned_invoice_request.metadata(), None);
		assert_eq!(unsigned_invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
		assert_eq!(unsigned_invoice_request.description(), PrintableString("foo"));
		assert_eq!(unsigned_invoice_request.offer_features(), &OfferFeatures::empty());
		assert_eq!(unsigned_invoice_request.absolute_expiry(), None);
		assert_eq!(unsigned_invoice_request.paths(), &[]);
		assert_eq!(unsigned_invoice_request.issuer(), None);
		assert_eq!(unsigned_invoice_request.supported_quantity(), Quantity::One);
		assert_eq!(unsigned_invoice_request.signing_pubkey(), recipient_pubkey());
		assert_eq!(unsigned_invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
		assert_eq!(unsigned_invoice_request.amount_msats(), None);
		assert_eq!(unsigned_invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
		assert_eq!(unsigned_invoice_request.quantity(), None);
		assert_eq!(unsigned_invoice_request.payer_id(), payer_pubkey());
		assert_eq!(unsigned_invoice_request.payer_note(), None);

		match UnsignedInvoiceRequest::try_from(buffer) {
			Err(e) => panic!("error parsing unsigned invoice request: {:?}", e),
			Ok(parsed) => {
				assert_eq!(parsed.bytes, unsigned_invoice_request.bytes);
				assert_eq!(parsed.tagged_hash, unsigned_invoice_request.tagged_hash);
			},
		}

		let invoice_request = unsigned_invoice_request.sign(payer_sign).unwrap();

		let mut buffer = Vec::new();
		invoice_request.write(&mut buffer).unwrap();

		assert_eq!(invoice_request.bytes, buffer.as_slice());
		assert_eq!(invoice_request.payer_metadata(), &[1; 32]);
		assert_eq!(invoice_request.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
		assert_eq!(invoice_request.metadata(), None);
		assert_eq!(invoice_request.amount(), Some(&Amount::Bitcoin { amount_msats: 1000 }));
		assert_eq!(invoice_request.description(), PrintableString("foo"));
		assert_eq!(invoice_request.offer_features(), &OfferFeatures::empty());
		assert_eq!(invoice_request.absolute_expiry(), None);
		assert_eq!(invoice_request.paths(), &[]);
		assert_eq!(invoice_request.issuer(), None);
		assert_eq!(invoice_request.supported_quantity(), Quantity::One);
		assert_eq!(invoice_request.signing_pubkey(), recipient_pubkey());
		assert_eq!(invoice_request.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
		assert_eq!(invoice_request.amount_msats(), None);
		assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
		assert_eq!(invoice_request.quantity(), None);
		assert_eq!(invoice_request.payer_id(), payer_pubkey());
		assert_eq!(invoice_request.payer_note(), None);

		let message = TaggedHash::new(SIGNATURE_TAG, &invoice_request.bytes);
		assert!(merkle::verify_signature(&invoice_request.signature, &message, payer_pubkey()).is_ok());

		assert_eq!(
			invoice_request.as_tlv_stream(),
			(
				PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
				OfferTlvStreamRef {
					chains: None,
					metadata: None,
					currency: None,
					amount: Some(1000),
					description: Some(&String::from("foo")),
					features: None,
					absolute_expiry: None,
					paths: None,
					issuer: None,
					quantity_max: None,
					node_id: Some(&recipient_pubkey()),
				},
				InvoiceRequestTlvStreamRef {
					chain: None,
					amount: None,
					features: None,
					quantity: None,
					payer_id: Some(&payer_pubkey()),
					payer_note: None,
				},
				SignatureTlvStreamRef { signature: Some(&invoice_request.signature()) },
			),
		);

		if let Err(e) = InvoiceRequest::try_from(buffer) {
			panic!("error parsing invoice request: {:?}", e);
		}
	}

	#[cfg(feature = "std")]
	#[test]
	fn builds_invoice_request_from_offer_with_expiration() {
		let future_expiry = Duration::from_secs(u64::max_value());
		let past_expiry = Duration::from_secs(0);

		if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.absolute_expiry(future_expiry)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.build()
		{
			panic!("error building invoice_request: {:?}", e);
		}

		match OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.absolute_expiry(past_expiry)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.build()
		{
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, Bolt12SemanticError::AlreadyExpired),
		}
	}

	#[test]
	fn builds_invoice_request_with_derived_metadata() {
		let payer_id = payer_pubkey();
		let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
		let entropy = FixedEntropy {};
		let secp_ctx = Secp256k1::new();
		let payment_id = PaymentId([1; 32]);

		let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap();
		let invoice_request = offer
			.request_invoice_deriving_metadata(payer_id, &expanded_key, &entropy, payment_id)
			.unwrap()
			.build().unwrap()
			.sign(payer_sign).unwrap();
		assert_eq!(invoice_request.payer_id(), payer_pubkey());

		let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
			.unwrap()
			.build().unwrap()
			.sign(recipient_sign).unwrap();
		match invoice.verify(&expanded_key, &secp_ctx) {
			Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
			Err(()) => panic!("verification failed"),
		}

		// Fails verification with altered fields
		let (
			payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
			mut invoice_tlv_stream, mut signature_tlv_stream
		) = invoice.as_tlv_stream();
		invoice_request_tlv_stream.amount = Some(2000);
		invoice_tlv_stream.amount = Some(2000);

		let tlv_stream =
			(payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
		let mut bytes = Vec::new();
		tlv_stream.write(&mut bytes).unwrap();

		let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
		let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
		signature_tlv_stream.signature = Some(&signature);

		let mut encoded_invoice = bytes;
		signature_tlv_stream.write(&mut encoded_invoice).unwrap();

		let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
		assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());

		// Fails verification with altered metadata
		let (
			mut payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
			mut signature_tlv_stream
		) = invoice.as_tlv_stream();
		let metadata = payer_tlv_stream.metadata.unwrap().iter().copied().rev().collect();
		payer_tlv_stream.metadata = Some(&metadata);

		let tlv_stream =
			(payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
		let mut bytes = Vec::new();
		tlv_stream.write(&mut bytes).unwrap();

		let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
		let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
		signature_tlv_stream.signature = Some(&signature);

		let mut encoded_invoice = bytes;
		signature_tlv_stream.write(&mut encoded_invoice).unwrap();

		let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
		assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
	}

	#[test]
	fn builds_invoice_request_with_derived_payer_id() {
		let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
		let entropy = FixedEntropy {};
		let secp_ctx = Secp256k1::new();
		let payment_id = PaymentId([1; 32]);

		let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap();
		let invoice_request = offer
			.request_invoice_deriving_payer_id(&expanded_key, &entropy, &secp_ctx, payment_id)
			.unwrap()
			.build_and_sign()
			.unwrap();

		let invoice = invoice_request.respond_with_no_std(payment_paths(), payment_hash(), now())
			.unwrap()
			.build().unwrap()
			.sign(recipient_sign).unwrap();
		match invoice.verify(&expanded_key, &secp_ctx) {
			Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
			Err(()) => panic!("verification failed"),
		}

		// Fails verification with altered fields
		let (
			payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream,
			mut invoice_tlv_stream, mut signature_tlv_stream
		) = invoice.as_tlv_stream();
		invoice_request_tlv_stream.amount = Some(2000);
		invoice_tlv_stream.amount = Some(2000);

		let tlv_stream =
			(payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
		let mut bytes = Vec::new();
		tlv_stream.write(&mut bytes).unwrap();

		let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
		let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
		signature_tlv_stream.signature = Some(&signature);

		let mut encoded_invoice = bytes;
		signature_tlv_stream.write(&mut encoded_invoice).unwrap();

		let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
		assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());

		// Fails verification with altered payer id
		let (
			payer_tlv_stream, offer_tlv_stream, mut invoice_request_tlv_stream, invoice_tlv_stream,
			mut signature_tlv_stream
		) = invoice.as_tlv_stream();
		let payer_id = pubkey(1);
		invoice_request_tlv_stream.payer_id = Some(&payer_id);

		let tlv_stream =
			(payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream);
		let mut bytes = Vec::new();
		tlv_stream.write(&mut bytes).unwrap();

		let message = TaggedHash::new(INVOICE_SIGNATURE_TAG, &bytes);
		let signature = merkle::sign_message(recipient_sign, &message, recipient_pubkey()).unwrap();
		signature_tlv_stream.signature = Some(&signature);

		let mut encoded_invoice = bytes;
		signature_tlv_stream.write(&mut encoded_invoice).unwrap();

		let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
		assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
	}

	#[test]
	fn builds_invoice_request_with_chain() {
		let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
		let testnet = ChainHash::using_genesis_block(Network::Testnet);

		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.chain(Network::Bitcoin).unwrap()
			.build().unwrap()
			.sign(payer_sign).unwrap();
		let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
		assert_eq!(invoice_request.chain(), mainnet);
		assert_eq!(tlv_stream.chain, None);

		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.chain(Network::Testnet)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.chain(Network::Testnet).unwrap()
			.build().unwrap()
			.sign(payer_sign).unwrap();
		let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
		assert_eq!(invoice_request.chain(), testnet);
		assert_eq!(tlv_stream.chain, Some(&testnet));

		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.chain(Network::Bitcoin)
			.chain(Network::Testnet)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.chain(Network::Bitcoin).unwrap()
			.build().unwrap()
			.sign(payer_sign).unwrap();
		let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
		assert_eq!(invoice_request.chain(), mainnet);
		assert_eq!(tlv_stream.chain, None);

		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.chain(Network::Bitcoin)
			.chain(Network::Testnet)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.chain(Network::Bitcoin).unwrap()
			.chain(Network::Testnet).unwrap()
			.build().unwrap()
			.sign(payer_sign).unwrap();
		let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
		assert_eq!(invoice_request.chain(), testnet);
		assert_eq!(tlv_stream.chain, Some(&testnet));

		match OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.chain(Network::Testnet)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.chain(Network::Bitcoin)
		{
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
		}

		match OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.chain(Network::Testnet)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.build()
		{
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
		}
	}

	#[test]
	fn builds_invoice_request_with_amount() {
		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.amount_msats(1000).unwrap()
			.build().unwrap()
			.sign(payer_sign).unwrap();
		let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
		assert_eq!(invoice_request.amount_msats(), Some(1000));
		assert_eq!(tlv_stream.amount, Some(1000));

		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.amount_msats(1001).unwrap()
			.amount_msats(1000).unwrap()
			.build().unwrap()
			.sign(payer_sign).unwrap();
		let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
		assert_eq!(invoice_request.amount_msats(), Some(1000));
		assert_eq!(tlv_stream.amount, Some(1000));

		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.amount_msats(1001).unwrap()
			.build().unwrap()
			.sign(payer_sign).unwrap();
		let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
		assert_eq!(invoice_request.amount_msats(), Some(1001));
		assert_eq!(tlv_stream.amount, Some(1001));

		match OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.amount_msats(999)
		{
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
		}

		match OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.supported_quantity(Quantity::Unbounded)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.quantity(2).unwrap()
			.amount_msats(1000)
		{
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
		}

		match OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.amount_msats(MAX_VALUE_MSAT + 1)
		{
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
		}

		match OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.supported_quantity(Quantity::Unbounded)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.amount_msats(1000).unwrap()
			.quantity(2).unwrap()
			.build()
		{
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, Bolt12SemanticError::InsufficientAmount),
		}

		match OfferBuilder::new("foo".into(), recipient_pubkey())
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.build()
		{
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, Bolt12SemanticError::MissingAmount),
		}

		match OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.supported_quantity(Quantity::Unbounded)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.quantity(u64::max_value()).unwrap()
			.build()
		{
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
		}
	}

	#[test]
	fn builds_invoice_request_with_features() {
		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.features_unchecked(InvoiceRequestFeatures::unknown())
			.build().unwrap()
			.sign(payer_sign).unwrap();
		let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
		assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::unknown());
		assert_eq!(tlv_stream.features, Some(&InvoiceRequestFeatures::unknown()));

		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.features_unchecked(InvoiceRequestFeatures::unknown())
			.features_unchecked(InvoiceRequestFeatures::empty())
			.build().unwrap()
			.sign(payer_sign).unwrap();
		let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
		assert_eq!(invoice_request.invoice_request_features(), &InvoiceRequestFeatures::empty());
		assert_eq!(tlv_stream.features, None);
	}

	#[test]
	fn builds_invoice_request_with_quantity() {
		let one = NonZeroU64::new(1).unwrap();
		let ten = NonZeroU64::new(10).unwrap();

		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.supported_quantity(Quantity::One)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.build().unwrap()
			.sign(payer_sign).unwrap();
		let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
		assert_eq!(invoice_request.quantity(), None);
		assert_eq!(tlv_stream.quantity, None);

		match OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.supported_quantity(Quantity::One)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.amount_msats(2_000).unwrap()
			.quantity(2)
		{
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, Bolt12SemanticError::UnexpectedQuantity),
		}

		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.supported_quantity(Quantity::Bounded(ten))
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.amount_msats(10_000).unwrap()
			.quantity(10).unwrap()
			.build().unwrap()
			.sign(payer_sign).unwrap();
		let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
		assert_eq!(invoice_request.amount_msats(), Some(10_000));
		assert_eq!(tlv_stream.amount, Some(10_000));

		match OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.supported_quantity(Quantity::Bounded(ten))
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.amount_msats(11_000).unwrap()
			.quantity(11)
		{
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidQuantity),
		}

		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.supported_quantity(Quantity::Unbounded)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.amount_msats(2_000).unwrap()
			.quantity(2).unwrap()
			.build().unwrap()
			.sign(payer_sign).unwrap();
		let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
		assert_eq!(invoice_request.amount_msats(), Some(2_000));
		assert_eq!(tlv_stream.amount, Some(2_000));

		match OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.supported_quantity(Quantity::Unbounded)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.build()
		{
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
		}

		match OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.supported_quantity(Quantity::Bounded(one))
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.build()
		{
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, Bolt12SemanticError::MissingQuantity),
		}
	}

	#[test]
	fn builds_invoice_request_with_payer_note() {
		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.payer_note("bar".into())
			.build().unwrap()
			.sign(payer_sign).unwrap();
		let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
		assert_eq!(invoice_request.payer_note(), Some(PrintableString("bar")));
		assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));

		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.payer_note("bar".into())
			.payer_note("baz".into())
			.build().unwrap()
			.sign(payer_sign).unwrap();
		let (_, _, tlv_stream, _) = invoice_request.as_tlv_stream();
		assert_eq!(invoice_request.payer_note(), Some(PrintableString("baz")));
		assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
	}

	#[test]
	fn fails_signing_invoice_request() {
		match OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.build().unwrap()
			.sign(|_| Err(()))
		{
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, SignError::Signing(())),
		}

		match OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.build().unwrap()
			.sign(recipient_sign)
		{
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
		}
	}

	#[test]
	fn fails_responding_with_unknown_required_features() {
		match OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap()
			.request_invoice(vec![42; 32], payer_pubkey()).unwrap()
			.features_unchecked(InvoiceRequestFeatures::unknown())
			.build().unwrap()
			.sign(payer_sign).unwrap()
			.respond_with_no_std(payment_paths(), payment_hash(), now())
		{
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
		}
	}

	#[test]
	fn parses_invoice_request_with_metadata() {
		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.build().unwrap()
			.sign(payer_sign).unwrap();

		let mut buffer = Vec::new();
		invoice_request.write(&mut buffer).unwrap();

		if let Err(e) = InvoiceRequest::try_from(buffer) {
			panic!("error parsing invoice_request: {:?}", e);
		}
	}

	#[test]
	fn parses_invoice_request_with_chain() {
		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.chain(Network::Bitcoin).unwrap()
			.build().unwrap()
			.sign(payer_sign).unwrap();

		let mut buffer = Vec::new();
		invoice_request.write(&mut buffer).unwrap();

		if let Err(e) = InvoiceRequest::try_from(buffer) {
			panic!("error parsing invoice_request: {:?}", e);
		}

		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.chain_unchecked(Network::Testnet)
			.build_unchecked()
			.sign(payer_sign).unwrap();

		let mut buffer = Vec::new();
		invoice_request.write(&mut buffer).unwrap();

		match InvoiceRequest::try_from(buffer) {
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedChain)),
		}
	}

	#[test]
	fn parses_invoice_request_with_amount() {
		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.build().unwrap()
			.sign(payer_sign).unwrap();

		let mut buffer = Vec::new();
		invoice_request.write(&mut buffer).unwrap();

		if let Err(e) = InvoiceRequest::try_from(buffer) {
			panic!("error parsing invoice_request: {:?}", e);
		}

		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.amount_msats(1000).unwrap()
			.build().unwrap()
			.sign(payer_sign).unwrap();

		let mut buffer = Vec::new();
		invoice_request.write(&mut buffer).unwrap();

		if let Err(e) = InvoiceRequest::try_from(buffer) {
			panic!("error parsing invoice_request: {:?}", e);
		}

		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.build_unchecked()
			.sign(payer_sign).unwrap();

		let mut buffer = Vec::new();
		invoice_request.write(&mut buffer).unwrap();

		match InvoiceRequest::try_from(buffer) {
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
		}

		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.amount_msats_unchecked(999)
			.build_unchecked()
			.sign(payer_sign).unwrap();

		let mut buffer = Vec::new();
		invoice_request.write(&mut buffer).unwrap();

		match InvoiceRequest::try_from(buffer) {
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InsufficientAmount)),
		}

		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount(Amount::Currency { iso4217_code: *b"USD", amount: 1000 })
			.build_unchecked()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.build_unchecked()
			.sign(payer_sign).unwrap();

		let mut buffer = Vec::new();
		invoice_request.write(&mut buffer).unwrap();

		match InvoiceRequest::try_from(buffer) {
			Ok(_) => panic!("expected error"),
			Err(e) => {
				assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnsupportedCurrency));
			},
		}

		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.supported_quantity(Quantity::Unbounded)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.quantity(u64::max_value()).unwrap()
			.build_unchecked()
			.sign(payer_sign).unwrap();

		let mut buffer = Vec::new();
		invoice_request.write(&mut buffer).unwrap();

		match InvoiceRequest::try_from(buffer) {
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
		}
	}

	#[test]
	fn parses_invoice_request_with_quantity() {
		let one = NonZeroU64::new(1).unwrap();
		let ten = NonZeroU64::new(10).unwrap();

		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.supported_quantity(Quantity::One)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.build().unwrap()
			.sign(payer_sign).unwrap();

		let mut buffer = Vec::new();
		invoice_request.write(&mut buffer).unwrap();

		if let Err(e) = InvoiceRequest::try_from(buffer) {
			panic!("error parsing invoice_request: {:?}", e);
		}

		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.supported_quantity(Quantity::One)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.amount_msats(2_000).unwrap()
			.quantity_unchecked(2)
			.build_unchecked()
			.sign(payer_sign).unwrap();

		let mut buffer = Vec::new();
		invoice_request.write(&mut buffer).unwrap();

		match InvoiceRequest::try_from(buffer) {
			Ok(_) => panic!("expected error"),
			Err(e) => {
				assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
			},
		}

		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.supported_quantity(Quantity::Bounded(ten))
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.amount_msats(10_000).unwrap()
			.quantity(10).unwrap()
			.build().unwrap()
			.sign(payer_sign).unwrap();

		let mut buffer = Vec::new();
		invoice_request.write(&mut buffer).unwrap();

		if let Err(e) = InvoiceRequest::try_from(buffer) {
			panic!("error parsing invoice_request: {:?}", e);
		}

		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.supported_quantity(Quantity::Bounded(ten))
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.amount_msats(11_000).unwrap()
			.quantity_unchecked(11)
			.build_unchecked()
			.sign(payer_sign).unwrap();

		let mut buffer = Vec::new();
		invoice_request.write(&mut buffer).unwrap();

		match InvoiceRequest::try_from(buffer) {
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidQuantity)),
		}

		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.supported_quantity(Quantity::Unbounded)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.amount_msats(2_000).unwrap()
			.quantity(2).unwrap()
			.build().unwrap()
			.sign(payer_sign).unwrap();

		let mut buffer = Vec::new();
		invoice_request.write(&mut buffer).unwrap();

		if let Err(e) = InvoiceRequest::try_from(buffer) {
			panic!("error parsing invoice_request: {:?}", e);
		}

		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.supported_quantity(Quantity::Unbounded)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.build_unchecked()
			.sign(payer_sign).unwrap();

		let mut buffer = Vec::new();
		invoice_request.write(&mut buffer).unwrap();

		match InvoiceRequest::try_from(buffer) {
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
		}

		let invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.supported_quantity(Quantity::Bounded(one))
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.build_unchecked()
			.sign(payer_sign).unwrap();

		let mut buffer = Vec::new();
		invoice_request.write(&mut buffer).unwrap();

		match InvoiceRequest::try_from(buffer) {
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingQuantity)),
		}
	}

	#[test]
	fn fails_parsing_invoice_request_without_metadata() {
		let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap();
		let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.build().unwrap();
		let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
		tlv_stream.0.metadata = None;

		let mut buffer = Vec::new();
		tlv_stream.write(&mut buffer).unwrap();

		match InvoiceRequest::try_from(buffer) {
			Ok(_) => panic!("expected error"),
			Err(e) => {
				assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
			},
		}
	}

	#[test]
	fn fails_parsing_invoice_request_without_payer_id() {
		let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap();
		let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.build().unwrap();
		let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
		tlv_stream.2.payer_id = None;

		let mut buffer = Vec::new();
		tlv_stream.write(&mut buffer).unwrap();

		match InvoiceRequest::try_from(buffer) {
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId)),
		}
	}

	#[test]
	fn fails_parsing_invoice_request_without_node_id() {
		let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap();
		let unsigned_invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.build().unwrap();
		let mut tlv_stream = unsigned_invoice_request.contents.as_tlv_stream();
		tlv_stream.1.node_id = None;

		let mut buffer = Vec::new();
		tlv_stream.write(&mut buffer).unwrap();

		match InvoiceRequest::try_from(buffer) {
			Ok(_) => panic!("expected error"),
			Err(e) => {
				assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
			},
		}
	}

	#[test]
	fn fails_parsing_invoice_request_without_signature() {
		let mut buffer = Vec::new();
		OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.build().unwrap()
			.contents
			.write(&mut buffer).unwrap();

		match InvoiceRequest::try_from(buffer) {
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSignature)),
		}
	}

	#[test]
	fn fails_parsing_invoice_request_with_invalid_signature() {
		let mut invoice_request = OfferBuilder::new("foo".into(), recipient_pubkey())
			.amount_msats(1000)
			.build().unwrap()
			.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
			.build().unwrap()
			.sign(payer_sign).unwrap();
		let last_signature_byte = invoice_request.bytes.last_mut().unwrap();
		*last_signature_byte = last_signature_byte.wrapping_add(1);

		let mut buffer = Vec::new();
		invoice_request.write(&mut buffer).unwrap();

		match InvoiceRequest::try_from(buffer) {
			Ok(_) => panic!("expected error"),
			Err(e) => {
				assert_eq!(e, Bolt12ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
			},
		}
	}

	#[test]
	fn fails_parsing_invoice_request_with_extra_tlv_records() {
		let secp_ctx = Secp256k1::new();
		let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
		let invoice_request = OfferBuilder::new("foo".into(), keys.public_key())
			.amount_msats(1000)
			.build().unwrap()
			.request_invoice(vec![1; 32], keys.public_key()).unwrap()
			.build().unwrap()
			.sign::<_, Infallible>(
				|message| Ok(secp_ctx.sign_schnorr_no_aux_rand(message.as_ref().as_digest(), &keys))
			)
			.unwrap();

		let mut encoded_invoice_request = Vec::new();
		invoice_request.write(&mut encoded_invoice_request).unwrap();
		BigSize(1002).write(&mut encoded_invoice_request).unwrap();
		BigSize(32).write(&mut encoded_invoice_request).unwrap();
		[42u8; 32].write(&mut encoded_invoice_request).unwrap();

		match InvoiceRequest::try_from(encoded_invoice_request) {
			Ok(_) => panic!("expected error"),
			Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
		}
	}
}