Merge pull request #2034 from wpaulino/anchor-revoked-aggregate-claim
[rust-lightning] / lightning-invoice / src / lib.rs
index c01dfa47ba0b086f8de39691de88df06ce3f2e91..37c74922ee6957fcb1a0211808e6e13a62f18fac 100644 (file)
@@ -154,11 +154,11 @@ pub const DEFAULT_EXPIRY_TIME: u64 = 3600;
 /// Default minimum final CLTV expiry as defined by [BOLT 11].
 ///
 /// Note that this is *not* the same value as rust-lightning's minimum CLTV expiry, which is
-/// provided in [`MIN_FINAL_CLTV_EXPIRY`].
+/// provided in [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
 ///
 /// [BOLT 11]: https://github.com/lightning/bolts/blob/master/11-payment-encoding.md
-/// [`MIN_FINAL_CLTV_EXPIRY`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY
-pub const DEFAULT_MIN_FINAL_CLTV_EXPIRY: u64 = 18;
+/// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA
+pub const DEFAULT_MIN_FINAL_CLTV_EXPIRY_DELTA: u64 = 18;
 
 /// Builder for `Invoice`s. It's the most convenient and advised way to use this library. It ensures
 /// that only a semantically and syntactically correct Invoice can be built using it.
@@ -199,7 +199,7 @@ pub const DEFAULT_MIN_FINAL_CLTV_EXPIRY: u64 = 18;
 ///    .payment_hash(payment_hash)
 ///    .payment_secret(payment_secret)
 ///    .current_timestamp()
-///    .min_final_cltv_expiry(144)
+///    .min_final_cltv_expiry_delta(144)
 ///    .build_signed(|hash| {
 ///            Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
 ///    })
@@ -410,7 +410,7 @@ pub enum TaggedField {
        PayeePubKey(PayeePubKey),
        DescriptionHash(Sha256),
        ExpiryTime(ExpiryTime),
-       MinFinalCltvExpiry(MinFinalCltvExpiry),
+       MinFinalCltvExpiryDelta(MinFinalCltvExpiryDelta),
        Fallback(Fallback),
        PrivateRoute(PrivateRoute),
        PaymentSecret(PaymentSecret),
@@ -438,9 +438,9 @@ pub struct PayeePubKey(pub PublicKey);
 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
 pub struct ExpiryTime(Duration);
 
-/// `min_final_cltv_expiry` to use for the last HTLC in the route
+/// `min_final_cltv_expiry_delta` to use for the last HTLC in the route
 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
-pub struct MinFinalCltvExpiry(pub u64);
+pub struct MinFinalCltvExpiryDelta(pub u64);
 
 // TODO: better types instead onf byte arrays
 /// Fallback address in case no LN payment is possible
@@ -475,7 +475,7 @@ pub mod constants {
        pub const TAG_PAYEE_PUB_KEY: u8 = 19;
        pub const TAG_DESCRIPTION_HASH: u8 = 23;
        pub const TAG_EXPIRY_TIME: u8 = 6;
-       pub const TAG_MIN_FINAL_CLTV_EXPIRY: u8 = 24;
+       pub const TAG_MIN_FINAL_CLTV_EXPIRY_DELTA: u8 = 24;
        pub const TAG_FALLBACK: u8 = 9;
        pub const TAG_PRIVATE_ROUTE: u8 = 3;
        pub const TAG_PAYMENT_SECRET: u8 = 16;
@@ -585,13 +585,13 @@ impl<D: tb::Bool, H: tb::Bool, C: tb::Bool, S: tb::Bool> InvoiceBuilder<D, H, tb
                }).collect::<Vec<_>>();
 
                let data = RawDataPart {
-                       timestamp: timestamp,
-                       tagged_fields: tagged_fields,
+                       timestamp,
+                       tagged_fields,
                };
 
                Ok(RawInvoice {
-                       hrp: hrp,
-                       data: data,
+                       hrp,
+                       data,
                })
        }
 }
@@ -654,9 +654,9 @@ impl<D: tb::Bool, H: tb::Bool, C: tb::Bool, S: tb::Bool> InvoiceBuilder<D, H, tb
 }
 
 impl<D: tb::Bool, H: tb::Bool, T: tb::Bool, S: tb::Bool> InvoiceBuilder<D, H, T, tb::False, S> {
-       /// Sets `min_final_cltv_expiry`.
-       pub fn min_final_cltv_expiry(mut self, min_final_cltv_expiry: u64) -> InvoiceBuilder<D, H, T, tb::True, S> {
-               self.tagged_fields.push(TaggedField::MinFinalCltvExpiry(MinFinalCltvExpiry(min_final_cltv_expiry)));
+       /// Sets `min_final_cltv_expiry_delta`.
+       pub fn min_final_cltv_expiry_delta(mut self, min_final_cltv_expiry_delta: u64) -> InvoiceBuilder<D, H, T, tb::True, S> {
+               self.tagged_fields.push(TaggedField::MinFinalCltvExpiryDelta(MinFinalCltvExpiryDelta(min_final_cltv_expiry_delta)));
                self.set_flags()
        }
 }
@@ -781,7 +781,7 @@ impl SignedRawInvoice {
                        recovered_pub_key = Some(recovered);
                }
 
-               let pub_key = included_pub_key.or_else(|| recovered_pub_key.as_ref())
+               let pub_key = included_pub_key.or(recovered_pub_key.as_ref())
                        .expect("One is always present");
 
                let hash = Message::from_slice(&self.hash[..])
@@ -929,8 +929,8 @@ impl RawInvoice {
                find_extract!(self.known_tagged_fields(), TaggedField::ExpiryTime(ref x), x)
        }
 
-       pub fn min_final_cltv_expiry(&self) -> Option<&MinFinalCltvExpiry> {
-               find_extract!(self.known_tagged_fields(), TaggedField::MinFinalCltvExpiry(ref x), x)
+       pub fn min_final_cltv_expiry_delta(&self) -> Option<&MinFinalCltvExpiryDelta> {
+               find_extract!(self.known_tagged_fields(), TaggedField::MinFinalCltvExpiryDelta(ref x), x)
        }
 
        pub fn payment_secret(&self) -> Option<&PaymentSecret> {
@@ -1014,9 +1014,9 @@ impl PositiveTimestamp {
 }
 
 #[cfg(feature = "std")]
-impl Into<SystemTime> for PositiveTimestamp {
-       fn into(self) -> SystemTime {
-               SystemTime::UNIX_EPOCH + self.0
+impl From<PositiveTimestamp> for SystemTime {
+       fn from(val: PositiveTimestamp) -> Self {
+               SystemTime::UNIX_EPOCH + val.0
        }
 }
 
@@ -1147,7 +1147,7 @@ impl Invoice {
        /// ```
        pub fn from_signed(signed_invoice: SignedRawInvoice) -> Result<Self, SemanticError> {
                let invoice = Invoice {
-                       signed_invoice: signed_invoice,
+                       signed_invoice,
                };
                invoice.check_field_counts()?;
                invoice.check_feature_bits()?;
@@ -1185,9 +1185,9 @@ impl Invoice {
        ///
        /// (C-not exported) because we don't yet export InvoiceDescription
        pub fn description(&self) -> InvoiceDescription {
-               if let Some(ref direct) = self.signed_invoice.description() {
+               if let Some(direct) = self.signed_invoice.description() {
                        return InvoiceDescription::Direct(direct);
-               } else if let Some(ref hash) = self.signed_invoice.description_hash() {
+               } else if let Some(hash) = self.signed_invoice.description_hash() {
                        return InvoiceDescription::Hash(hash);
                }
                unreachable!("ensured by constructor");
@@ -1243,12 +1243,12 @@ impl Invoice {
                        .unwrap_or_else(|| Duration::new(u64::max_value(), 1_000_000_000 - 1)) < at_time
        }
 
-       /// Returns the invoice's `min_final_cltv_expiry` time, if present, otherwise
-       /// [`DEFAULT_MIN_FINAL_CLTV_EXPIRY`].
-       pub fn min_final_cltv_expiry(&self) -> u64 {
-               self.signed_invoice.min_final_cltv_expiry()
+       /// Returns the invoice's `min_final_cltv_expiry_delta` time, if present, otherwise
+       /// [`DEFAULT_MIN_FINAL_CLTV_EXPIRY_DELTA`].
+       pub fn min_final_cltv_expiry_delta(&self) -> u64 {
+               self.signed_invoice.min_final_cltv_expiry_delta()
                        .map(|x| x.0)
-                       .unwrap_or(DEFAULT_MIN_FINAL_CLTV_EXPIRY)
+                       .unwrap_or(DEFAULT_MIN_FINAL_CLTV_EXPIRY_DELTA)
        }
 
        /// Returns a list of all fallback addresses
@@ -1301,7 +1301,7 @@ impl TaggedField {
                        TaggedField::PayeePubKey(_) => constants::TAG_PAYEE_PUB_KEY,
                        TaggedField::DescriptionHash(_) => constants::TAG_DESCRIPTION_HASH,
                        TaggedField::ExpiryTime(_) => constants::TAG_EXPIRY_TIME,
-                       TaggedField::MinFinalCltvExpiry(_) => constants::TAG_MIN_FINAL_CLTV_EXPIRY,
+                       TaggedField::MinFinalCltvExpiryDelta(_) => constants::TAG_MIN_FINAL_CLTV_EXPIRY_DELTA,
                        TaggedField::Fallback(_) => constants::TAG_FALLBACK,
                        TaggedField::PrivateRoute(_) => constants::TAG_PRIVATE_ROUTE,
                        TaggedField::PaymentSecret(_) => constants::TAG_PAYMENT_SECRET,
@@ -1332,9 +1332,9 @@ impl Description {
        }
 }
 
-impl Into<String> for Description {
-       fn into(self) -> String {
-               self.into_inner()
+impl From<Description> for String {
+       fn from(val: Description) -> Self {
+               val.into_inner()
        }
 }
 
@@ -1398,9 +1398,9 @@ impl PrivateRoute {
        }
 }
 
-impl Into<RouteHint> for PrivateRoute {
-       fn into(self) -> RouteHint {
-               self.into_inner()
+impl From<PrivateRoute> for RouteHint {
+       fn from(val: PrivateRoute) -> Self {
+               val.into_inner()
        }
 }
 
@@ -1448,6 +1448,11 @@ pub enum CreationError {
        ///
        /// [phantom invoices]: crate::utils::create_phantom_invoice
        MissingRouteHints,
+
+       /// The provided `min_final_cltv_expiry_delta` was less than [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
+       ///
+       /// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA
+       MinFinalCltvExpiryDeltaTooShort,
 }
 
 impl Display for CreationError {
@@ -1458,6 +1463,8 @@ impl Display for CreationError {
                        CreationError::TimestampOutOfBounds => f.write_str("The Unix timestamp of the supplied date is less than zero or greater than 35-bits"),
                        CreationError::InvalidAmount => f.write_str("The supplied millisatoshi amount was greater than the total bitcoin supply"),
                        CreationError::MissingRouteHints => f.write_str("The invoice required route hints and they weren't provided"),
+                       CreationError::MinFinalCltvExpiryDeltaTooShort => f.write_str(
+                               "The supplied final CLTV expiry delta was less than LDK's `MIN_FINAL_CLTV_EXPIRY_DELTA`"),
                }
        }
 }
@@ -1759,7 +1766,7 @@ mod test {
 
                // Multiple payment secrets
                let invoice = {
-                       let mut invoice = invoice_template.clone();
+                       let mut invoice = invoice_template;
                        invoice.data.tagged_fields.push(PaymentSecret(payment_secret).into());
                        invoice.data.tagged_fields.push(PaymentSecret(payment_secret).into());
                        invoice.sign::<_, ()>(|hash| Ok(Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)))
@@ -1785,7 +1792,7 @@ mod test {
                assert_eq!(invoice.hrp.raw_amount, Some(15));
 
 
-               let invoice = builder.clone()
+               let invoice = builder
                        .amount_milli_satoshis(150)
                        .build_raw()
                        .unwrap();
@@ -1804,7 +1811,7 @@ mod test {
                let builder = InvoiceBuilder::new(Currency::Bitcoin)
                        .payment_hash(sha256::Hash::from_slice(&[0;32][..]).unwrap())
                        .duration_since_epoch(Duration::from_secs(1234567))
-                       .min_final_cltv_expiry(144);
+                       .min_final_cltv_expiry_delta(144);
 
                let too_long_string = String::from_iter(
                        (0..1024).map(|_| '?')
@@ -1839,7 +1846,7 @@ mod test {
                        .build_raw();
                assert_eq!(long_route_res, Err(CreationError::RouteTooLong));
 
-               let sign_error_res = builder.clone()
+               let sign_error_res = builder
                        .description("Test".into())
                        .payment_secret(PaymentSecret([0; 32]))
                        .try_build_signed(|_| {
@@ -1869,7 +1876,7 @@ mod test {
 
                let route_1 = RouteHint(vec![
                        RouteHintHop {
-                               src_node_id: public_key.clone(),
+                               src_node_id: public_key,
                                short_channel_id: de::parse_int_be(&[123; 8], 256).expect("short chan ID slice too big?"),
                                fees: RoutingFees {
                                        base_msat: 2,
@@ -1880,7 +1887,7 @@ mod test {
                                htlc_maximum_msat: None,
                        },
                        RouteHintHop {
-                               src_node_id: public_key.clone(),
+                               src_node_id: public_key,
                                short_channel_id: de::parse_int_be(&[42; 8], 256).expect("short chan ID slice too big?"),
                                fees: RoutingFees {
                                        base_msat: 3,
@@ -1894,7 +1901,7 @@ mod test {
 
                let route_2 = RouteHint(vec![
                        RouteHintHop {
-                               src_node_id: public_key.clone(),
+                               src_node_id: public_key,
                                short_channel_id: 0,
                                fees: RoutingFees {
                                        base_msat: 4,
@@ -1905,7 +1912,7 @@ mod test {
                                htlc_maximum_msat: None,
                        },
                        RouteHintHop {
-                               src_node_id: public_key.clone(),
+                               src_node_id: public_key,
                                short_channel_id: de::parse_int_be(&[1; 8], 256).expect("short chan ID slice too big?"),
                                fees: RoutingFees {
                                        base_msat: 5,
@@ -1920,9 +1927,9 @@ mod test {
                let builder = InvoiceBuilder::new(Currency::BitcoinTestnet)
                        .amount_milli_satoshis(123)
                        .duration_since_epoch(Duration::from_secs(1234567))
-                       .payee_pub_key(public_key.clone())
+                       .payee_pub_key(public_key)
                        .expiry_time(Duration::from_secs(54321))
-                       .min_final_cltv_expiry(144)
+                       .min_final_cltv_expiry_delta(144)
                        .fallback(Fallback::PubKeyHash([0;20]))
                        .private_route(route_1.clone())
                        .private_route(route_2.clone())
@@ -1948,7 +1955,7 @@ mod test {
                );
                assert_eq!(invoice.payee_pub_key(), Some(&public_key));
                assert_eq!(invoice.expiry_time(), Duration::from_secs(54321));
-               assert_eq!(invoice.min_final_cltv_expiry(), 144);
+               assert_eq!(invoice.min_final_cltv_expiry_delta(), 144);
                assert_eq!(invoice.fallbacks(), vec![&Fallback::PubKeyHash([0;20])]);
                assert_eq!(invoice.private_routes(), vec![&PrivateRoute(route_1), &PrivateRoute(route_2)]);
                assert_eq!(
@@ -1989,7 +1996,7 @@ mod test {
                        .unwrap();
                let invoice = Invoice::from_signed(signed_invoice).unwrap();
 
-               assert_eq!(invoice.min_final_cltv_expiry(), DEFAULT_MIN_FINAL_CLTV_EXPIRY);
+               assert_eq!(invoice.min_final_cltv_expiry_delta(), DEFAULT_MIN_FINAL_CLTV_EXPIRY_DELTA);
                assert_eq!(invoice.expiry_time(), Duration::from_secs(DEFAULT_EXPIRY_TIME));
                assert!(!invoice.would_expire(Duration::from_secs(1234568)));
        }