Skip to content

Commit 47cb293

Browse files
authored
Merge pull request #898 from jkczyz/2021-04-invoice-expiry
Require min_final_cltv_expiry in invoices
2 parents 3b67be2 + aafa741 commit 47cb293

File tree

2 files changed

+78
-34
lines changed

2 files changed

+78
-34
lines changed

lightning-invoice/src/lib.rs

Lines changed: 73 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,16 @@ const SYSTEM_TIME_MAX_UNIX_TIMESTAMP: u64 = std::i32::MAX as u64;
5656
/// it should be rather low as long as we still have to support 32bit time representations
5757
const MAX_EXPIRY_TIME: u64 = 60 * 60 * 24 * 356;
5858

59+
/// Default expiry time as defined by [BOLT 11].
60+
///
61+
/// [BOLT 11]: https://github.com/lightningnetwork/lightning-rfc/blob/master/11-payment-encoding.md
62+
const DEFAULT_EXPIRY_TIME: u64 = 3600;
63+
64+
/// Default minimum final CLTV expiry as defined by [BOLT 11].
65+
///
66+
/// [BOLT 11]: https://github.com/lightningnetwork/lightning-rfc/blob/master/11-payment-encoding.md
67+
const DEFAULT_MIN_FINAL_CLTV_EXPIRY: u64 = 18;
68+
5969
/// This function is used as a static assert for the size of `SystemTime`. If the crate fails to
6070
/// compile due to it this indicates that your system uses unexpected bounds for `SystemTime`. You
6171
/// can remove this functions and run the test `test_system_time_bounds_assumptions`. In any case,
@@ -138,6 +148,7 @@ pub fn check_platform() {
138148
/// .description("Coins pls!".into())
139149
/// .payment_hash(payment_hash)
140150
/// .current_timestamp()
151+
/// .min_final_cltv_expiry(144)
141152
/// .build_signed(|hash| {
142153
/// Secp256k1::new().sign_recoverable(hash, &private_key)
143154
/// })
@@ -156,7 +167,7 @@ pub fn check_platform() {
156167
///
157168
/// (C-not exported) as we likely need to manually select one set of boolean type parameters.
158169
#[derive(Eq, PartialEq, Debug, Clone)]
159-
pub struct InvoiceBuilder<D: tb::Bool, H: tb::Bool, T: tb::Bool> {
170+
pub struct InvoiceBuilder<D: tb::Bool, H: tb::Bool, T: tb::Bool, C: tb::Bool> {
160171
currency: Currency,
161172
amount: Option<u64>,
162173
si_prefix: Option<SiPrefix>,
@@ -167,6 +178,7 @@ pub struct InvoiceBuilder<D: tb::Bool, H: tb::Bool, T: tb::Bool> {
167178
phantom_d: std::marker::PhantomData<D>,
168179
phantom_h: std::marker::PhantomData<H>,
169180
phantom_t: std::marker::PhantomData<T>,
181+
phantom_c: std::marker::PhantomData<C>,
170182
}
171183

172184
/// Represents a syntactically and semantically correct lightning BOLT11 invoice.
@@ -414,7 +426,7 @@ pub mod constants {
414426
pub const TAG_FEATURES: u8 = 5;
415427
}
416428

417-
impl InvoiceBuilder<tb::False, tb::False, tb::False> {
429+
impl InvoiceBuilder<tb::False, tb::False, tb::False, tb::False> {
418430
/// Construct new, empty `InvoiceBuilder`. All necessary fields have to be filled first before
419431
/// `InvoiceBuilder::build(self)` becomes available.
420432
pub fn new(currrency: Currency) -> Self {
@@ -429,14 +441,15 @@ impl InvoiceBuilder<tb::False, tb::False, tb::False> {
429441
phantom_d: std::marker::PhantomData,
430442
phantom_h: std::marker::PhantomData,
431443
phantom_t: std::marker::PhantomData,
444+
phantom_c: std::marker::PhantomData,
432445
}
433446
}
434447
}
435448

436-
impl<D: tb::Bool, H: tb::Bool, T: tb::Bool> InvoiceBuilder<D, H, T> {
449+
impl<D: tb::Bool, H: tb::Bool, T: tb::Bool, C: tb::Bool> InvoiceBuilder<D, H, T, C> {
437450
/// Helper function to set the completeness flags.
438-
fn set_flags<DN: tb::Bool, HN: tb::Bool, TN: tb::Bool>(self) -> InvoiceBuilder<DN, HN, TN> {
439-
InvoiceBuilder::<DN, HN, TN> {
451+
fn set_flags<DN: tb::Bool, HN: tb::Bool, TN: tb::Bool, CN: tb::Bool>(self) -> InvoiceBuilder<DN, HN, TN, CN> {
452+
InvoiceBuilder::<DN, HN, TN, CN> {
440453
currency: self.currency,
441454
amount: self.amount,
442455
si_prefix: self.si_prefix,
@@ -447,6 +460,7 @@ impl<D: tb::Bool, H: tb::Bool, T: tb::Bool> InvoiceBuilder<D, H, T> {
447460
phantom_d: std::marker::PhantomData,
448461
phantom_h: std::marker::PhantomData,
449462
phantom_t: std::marker::PhantomData,
463+
phantom_c: std::marker::PhantomData,
450464
}
451465
}
452466

@@ -482,12 +496,6 @@ impl<D: tb::Bool, H: tb::Bool, T: tb::Bool> InvoiceBuilder<D, H, T> {
482496
self
483497
}
484498

485-
/// Sets `min_final_cltv_expiry`.
486-
pub fn min_final_cltv_expiry(mut self, min_final_cltv_expiry: u64) -> Self {
487-
self.tagged_fields.push(TaggedField::MinFinalCltvExpiry(MinFinalCltvExpiry(min_final_cltv_expiry)));
488-
self
489-
}
490-
491499
/// Adds a fallback address.
492500
pub fn fallback(mut self, fallback: Fallback) -> Self {
493501
self.tagged_fields.push(TaggedField::Fallback(fallback));
@@ -511,7 +519,7 @@ impl<D: tb::Bool, H: tb::Bool, T: tb::Bool> InvoiceBuilder<D, H, T> {
511519
}
512520
}
513521

514-
impl<D: tb::Bool, H: tb::Bool> InvoiceBuilder<D, H, tb::True> {
522+
impl<D: tb::Bool, H: tb::Bool, C: tb::Bool> InvoiceBuilder<D, H, tb::True, C> {
515523
/// Builds a `RawInvoice` if no `CreationError` occurred while construction any of the fields.
516524
pub fn build_raw(self) -> Result<RawInvoice, CreationError> {
517525

@@ -544,9 +552,9 @@ impl<D: tb::Bool, H: tb::Bool> InvoiceBuilder<D, H, tb::True> {
544552
}
545553
}
546554

547-
impl<H: tb::Bool, T: tb::Bool> InvoiceBuilder<tb::False, H, T> {
555+
impl<H: tb::Bool, T: tb::Bool, C: tb::Bool> InvoiceBuilder<tb::False, H, T, C> {
548556
/// Set the description. This function is only available if no description (hash) was set.
549-
pub fn description(mut self, description: String) -> InvoiceBuilder<tb::True, H, T> {
557+
pub fn description(mut self, description: String) -> InvoiceBuilder<tb::True, H, T, C> {
550558
match Description::new(description) {
551559
Ok(d) => self.tagged_fields.push(TaggedField::Description(d)),
552560
Err(e) => self.error = Some(e),
@@ -555,23 +563,23 @@ impl<H: tb::Bool, T: tb::Bool> InvoiceBuilder<tb::False, H, T> {
555563
}
556564

557565
/// Set the description hash. This function is only available if no description (hash) was set.
558-
pub fn description_hash(mut self, description_hash: sha256::Hash) -> InvoiceBuilder<tb::True, H, T> {
566+
pub fn description_hash(mut self, description_hash: sha256::Hash) -> InvoiceBuilder<tb::True, H, T, C> {
559567
self.tagged_fields.push(TaggedField::DescriptionHash(Sha256(description_hash)));
560568
self.set_flags()
561569
}
562570
}
563571

564-
impl<D: tb::Bool, T: tb::Bool> InvoiceBuilder<D, tb::False, T> {
572+
impl<D: tb::Bool, T: tb::Bool, C: tb::Bool> InvoiceBuilder<D, tb::False, T, C> {
565573
/// Set the payment hash. This function is only available if no payment hash was set.
566-
pub fn payment_hash(mut self, hash: sha256::Hash) -> InvoiceBuilder<D, tb::True, T> {
574+
pub fn payment_hash(mut self, hash: sha256::Hash) -> InvoiceBuilder<D, tb::True, T, C> {
567575
self.tagged_fields.push(TaggedField::PaymentHash(Sha256(hash)));
568576
self.set_flags()
569577
}
570578
}
571579

572-
impl<D: tb::Bool, H: tb::Bool> InvoiceBuilder<D, H, tb::False> {
580+
impl<D: tb::Bool, H: tb::Bool, C: tb::Bool> InvoiceBuilder<D, H, tb::False, C> {
573581
/// Sets the timestamp.
574-
pub fn timestamp(mut self, time: SystemTime) -> InvoiceBuilder<D, H, tb::True> {
582+
pub fn timestamp(mut self, time: SystemTime) -> InvoiceBuilder<D, H, tb::True, C> {
575583
match PositiveTimestamp::from_system_time(time) {
576584
Ok(t) => self.timestamp = Some(t),
577585
Err(e) => self.error = Some(e),
@@ -581,14 +589,22 @@ impl<D: tb::Bool, H: tb::Bool> InvoiceBuilder<D, H, tb::False> {
581589
}
582590

583591
/// Sets the timestamp to the current UNIX timestamp.
584-
pub fn current_timestamp(mut self) -> InvoiceBuilder<D, H, tb::True> {
592+
pub fn current_timestamp(mut self) -> InvoiceBuilder<D, H, tb::True, C> {
585593
let now = PositiveTimestamp::from_system_time(SystemTime::now());
586594
self.timestamp = Some(now.expect("for the foreseeable future this shouldn't happen"));
587595
self.set_flags()
588596
}
589597
}
590598

591-
impl InvoiceBuilder<tb::True, tb::True, tb::True> {
599+
impl<D: tb::Bool, H: tb::Bool, T: tb::Bool> InvoiceBuilder<D, H, T, tb::False> {
600+
/// Sets `min_final_cltv_expiry`.
601+
pub fn min_final_cltv_expiry(mut self, min_final_cltv_expiry: u64) -> InvoiceBuilder<D, H, T, tb::True> {
602+
self.tagged_fields.push(TaggedField::MinFinalCltvExpiry(MinFinalCltvExpiry(min_final_cltv_expiry)));
603+
self.set_flags()
604+
}
605+
}
606+
607+
impl InvoiceBuilder<tb::True, tb::True, tb::True, tb::True> {
592608
/// Builds and signs an invoice using the supplied `sign_function`. This function MAY NOT fail
593609
/// and MUST produce a recoverable signature valid for the given hash and if applicable also for
594610
/// the included payee public key.
@@ -1044,16 +1060,19 @@ impl Invoice {
10441060
self.signed_invoice.recover_payee_pub_key().expect("was checked by constructor").0
10451061
}
10461062

1047-
/// Returns the invoice's expiry time if present
1063+
/// Returns the invoice's expiry time, if present, otherwise [`DEFAULT_EXPIRY_TIME`].
10481064
pub fn expiry_time(&self) -> Duration {
10491065
self.signed_invoice.expiry_time()
10501066
.map(|x| x.0)
1051-
.unwrap_or(Duration::from_secs(3600))
1067+
.unwrap_or(Duration::from_secs(DEFAULT_EXPIRY_TIME))
10521068
}
10531069

1054-
/// Returns the invoice's `min_cltv_expiry` time if present
1055-
pub fn min_final_cltv_expiry(&self) -> Option<u64> {
1056-
self.signed_invoice.min_final_cltv_expiry().map(|x| x.0)
1070+
/// Returns the invoice's `min_final_cltv_expiry` time, if present, otherwise
1071+
/// [`DEFAULT_MIN_FINAL_CLTV_EXPIRY`].
1072+
pub fn min_final_cltv_expiry(&self) -> u64 {
1073+
self.signed_invoice.min_final_cltv_expiry()
1074+
.map(|x| x.0)
1075+
.unwrap_or(DEFAULT_MIN_FINAL_CLTV_EXPIRY)
10571076
}
10581077

10591078
/// Returns a list of all fallback addresses
@@ -1479,7 +1498,8 @@ mod test {
14791498

14801499
let builder = InvoiceBuilder::new(Currency::Bitcoin)
14811500
.payment_hash(sha256::Hash::from_slice(&[0;32][..]).unwrap())
1482-
.current_timestamp();
1501+
.current_timestamp()
1502+
.min_final_cltv_expiry(144);
14831503

14841504
let too_long_string = String::from_iter(
14851505
(0..1024).map(|_| '?')
@@ -1596,7 +1616,6 @@ mod test {
15961616
.payee_pub_key(public_key.clone())
15971617
.expiry_time(Duration::from_secs(54321))
15981618
.min_final_cltv_expiry(144)
1599-
.min_final_cltv_expiry(143)
16001619
.fallback(Fallback::PubKeyHash([0;20]))
16011620
.route(route_1.clone())
16021621
.route(route_2.clone())
@@ -1608,7 +1627,7 @@ mod test {
16081627
}).unwrap();
16091628

16101629
assert!(invoice.check_signature().is_ok());
1611-
assert_eq!(invoice.tagged_fields().count(), 9);
1630+
assert_eq!(invoice.tagged_fields().count(), 8);
16121631

16131632
assert_eq!(invoice.amount_pico_btc(), Some(123));
16141633
assert_eq!(invoice.currency(), Currency::BitcoinTestnet);
@@ -1618,7 +1637,7 @@ mod test {
16181637
);
16191638
assert_eq!(invoice.payee_pub_key(), Some(&public_key));
16201639
assert_eq!(invoice.expiry_time(), Duration::from_secs(54321));
1621-
assert_eq!(invoice.min_final_cltv_expiry(), Some(144));
1640+
assert_eq!(invoice.min_final_cltv_expiry(), 144);
16221641
assert_eq!(invoice.fallbacks(), vec![&Fallback::PubKeyHash([0;20])]);
16231642
assert_eq!(invoice.routes(), vec![&RouteHint(route_1), &RouteHint(route_2)]);
16241643
assert_eq!(
@@ -1630,4 +1649,28 @@ mod test {
16301649
let raw_invoice = builder.build_raw().unwrap();
16311650
assert_eq!(raw_invoice, *invoice.into_signed_raw().raw_invoice())
16321651
}
1652+
1653+
#[test]
1654+
fn test_default_values() {
1655+
use ::*;
1656+
use secp256k1::Secp256k1;
1657+
use secp256k1::key::SecretKey;
1658+
1659+
let signed_invoice = InvoiceBuilder::new(Currency::Bitcoin)
1660+
.description("Test".into())
1661+
.payment_hash(sha256::Hash::from_slice(&[0;32][..]).unwrap())
1662+
.current_timestamp()
1663+
.build_raw()
1664+
.unwrap()
1665+
.sign::<_, ()>(|hash| {
1666+
let privkey = SecretKey::from_slice(&[41; 32]).unwrap();
1667+
let secp_ctx = Secp256k1::new();
1668+
Ok(secp_ctx.sign_recoverable(hash, &privkey))
1669+
})
1670+
.unwrap();
1671+
let invoice = Invoice::from_signed(signed_invoice).unwrap();
1672+
1673+
assert_eq!(invoice.min_final_cltv_expiry(), DEFAULT_MIN_FINAL_CLTV_EXPIRY);
1674+
assert_eq!(invoice.expiry_time(), Duration::from_secs(DEFAULT_EXPIRY_TIME));
1675+
}
16331676
}

lightning-invoice/tests/ser_de.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -112,13 +112,14 @@ fn get_test_tuples() -> Vec<(String, SignedRawInvoice, Option<SemanticError>)> {
112112
.amount_pico_btc(20000000000)
113113
.timestamp(UNIX_EPOCH + Duration::from_secs(1496314658))
114114
.payment_secret(PaymentSecret([42; 32]))
115-
.build_signed(|msg_hash| {
115+
.build_raw()
116+
.unwrap()
117+
.sign::<_, ()>(|msg_hash| {
116118
let privkey = SecretKey::from_slice(&[41; 32]).unwrap();
117119
let secp_ctx = Secp256k1::new();
118-
secp_ctx.sign_recoverable(msg_hash, &privkey)
120+
Ok(secp_ctx.sign_recoverable(msg_hash, &privkey))
119121
})
120-
.unwrap()
121-
.into_signed_raw(),
122+
.unwrap(),
122123
None
123124
)
124125
]

0 commit comments

Comments
 (0)