Merge pull request #2023 from futurepaul/fallback-to-address
[rust-lightning] / lightning-invoice / src / de.rs
index 9e96849a274c24d9ba1a08845b8d69622c75a4ff..925d7265c553526d993f94b29354adcac1db9ac1 100644 (file)
@@ -1,30 +1,31 @@
 #[cfg(feature = "std")]
 use std::error;
+use core::convert::TryFrom;
 use core::fmt;
 use core::fmt::{Display, Formatter};
 use core::num::ParseIntError;
 use core::str;
 use core::str::FromStr;
 
-use bech32;
 use bech32::{u5, FromBase32};
 
+use bitcoin::{PubkeyHash, ScriptHash};
+use bitcoin::util::address::WitnessVersion;
 use bitcoin_hashes::Hash;
 use bitcoin_hashes::sha256;
 use crate::prelude::*;
 use lightning::ln::PaymentSecret;
-use lightning::routing::network_graph::RoutingFees;
+use lightning::routing::gossip::RoutingFees;
 use lightning::routing::router::{RouteHint, RouteHintHop};
 
 use num_traits::{CheckedAdd, CheckedMul};
 
-use secp256k1;
-use secp256k1::recovery::{RecoveryId, RecoverableSignature};
-use secp256k1::key::PublicKey;
+use secp256k1::ecdsa::{RecoveryId, RecoverableSignature};
+use secp256k1::PublicKey;
 
-use super::{Invoice, Sha256, TaggedField, ExpiryTime, MinFinalCltvExpiry, Fallback, PayeePubKey, InvoiceSignature, PositiveTimestamp,
-       SemanticError, PrivateRoute, Description, RawTaggedField, Currency, RawHrp, SiPrefix, RawInvoice, constants, SignedRawInvoice,
-       RawDataPart, InvoiceFeatures};
+use super::{Invoice, Sha256, TaggedField, ExpiryTime, MinFinalCltvExpiryDelta, Fallback, PayeePubKey, InvoiceSignature, PositiveTimestamp,
+       SemanticError, PrivateRoute, ParseError, ParseOrSemanticError, Description, RawTaggedField, Currency, RawHrp, SiPrefix, RawInvoice,
+       constants, SignedRawInvoice, RawDataPart, InvoiceFeatures};
 
 use self::hrp_sm::parse_hrp;
 
@@ -197,7 +198,7 @@ impl FromStr for SiPrefix {
        type Err = ParseError;
 
        fn from_str(currency_prefix: &str) -> Result<Self, ParseError> {
-               use SiPrefix::*;
+               use crate::SiPrefix::*;
                match currency_prefix {
                        "m" => Ok(Milli),
                        "u" => Ok(Micro),
@@ -323,9 +324,9 @@ impl FromStr for RawHrp {
                };
 
                Ok(RawHrp {
-                       currency: currency,
+                       currency,
                        raw_amount: amount,
-                       si_prefix: si_prefix,
+                       si_prefix,
                })
        }
 }
@@ -342,7 +343,7 @@ impl FromBase32 for RawDataPart {
                let tagged = parse_tagged_parts(&data[7..])?;
 
                Ok(RawDataPart {
-                       timestamp: timestamp,
+                       timestamp,
                        tagged_fields: tagged,
                })
        }
@@ -451,8 +452,8 @@ impl FromBase32 for TaggedField {
                                Ok(TaggedField::DescriptionHash(Sha256::from_base32(field_data)?)),
                        constants::TAG_EXPIRY_TIME =>
                                Ok(TaggedField::ExpiryTime(ExpiryTime::from_base32(field_data)?)),
-                       constants::TAG_MIN_FINAL_CLTV_EXPIRY =>
-                               Ok(TaggedField::MinFinalCltvExpiry(MinFinalCltvExpiry::from_base32(field_data)?)),
+                       constants::TAG_MIN_FINAL_CLTV_EXPIRY_DELTA =>
+                               Ok(TaggedField::MinFinalCltvExpiryDelta(MinFinalCltvExpiryDelta::from_base32(field_data)?)),
                        constants::TAG_FALLBACK =>
                                Ok(TaggedField::Fallback(Fallback::from_base32(field_data)?)),
                        constants::TAG_PRIVATE_ROUTE =>
@@ -515,7 +516,7 @@ impl FromBase32 for ExpiryTime {
 
        fn from_base32(field_data: &[u5]) -> Result<ExpiryTime, ParseError> {
                match parse_int_be::<u64, u5>(field_data, 32)
-                       .map(|t| ExpiryTime::from_seconds(t))
+                       .map(ExpiryTime::from_seconds)
                {
                        Some(t) => Ok(t),
                        None => Err(ParseError::IntegerOverflowError),
@@ -523,13 +524,13 @@ impl FromBase32 for ExpiryTime {
        }
 }
 
-impl FromBase32 for MinFinalCltvExpiry {
+impl FromBase32 for MinFinalCltvExpiryDelta {
        type Err = ParseError;
 
-       fn from_base32(field_data: &[u5]) -> Result<MinFinalCltvExpiry, ParseError> {
+       fn from_base32(field_data: &[u5]) -> Result<MinFinalCltvExpiryDelta, ParseError> {
                let expiry = parse_int_be::<u64, u5>(field_data, 32);
                if let Some(expiry) = expiry {
-                       Ok(MinFinalCltvExpiry(expiry))
+                       Ok(MinFinalCltvExpiryDelta(expiry))
                } else {
                        Err(ParseError::IntegerOverflowError)
                }
@@ -540,7 +541,7 @@ impl FromBase32 for Fallback {
        type Err = ParseError;
 
        fn from_base32(field_data: &[u5]) -> Result<Fallback, ParseError> {
-               if field_data.len() < 1 {
+               if field_data.is_empty() {
                        return Err(ParseError::UnexpectedEndOfTaggedFields);
                }
 
@@ -552,27 +553,24 @@ impl FromBase32 for Fallback {
                                if bytes.len() < 2 || bytes.len() > 40 {
                                        return Err(ParseError::InvalidSegWitProgramLength);
                                }
-
+                               let version = WitnessVersion::try_from(version).expect("0 through 16 are valid SegWit versions");
                                Ok(Fallback::SegWitProgram {
-                                       version: version,
+                                       version,
                                        program: bytes
                                })
                        },
                        17 => {
-                               if bytes.len() != 20 {
-                                       return Err(ParseError::InvalidPubKeyHashLength);
-                               }
-                               //TODO: refactor once const generics are available
-                               let mut pkh = [0u8; 20];
-                               pkh.copy_from_slice(&bytes);
+                               let pkh = match PubkeyHash::from_slice(&bytes) {
+                                       Ok(pkh) => pkh,
+                                       Err(bitcoin_hashes::Error::InvalidLength(_, _)) => return Err(ParseError::InvalidPubKeyHashLength),
+                               };
                                Ok(Fallback::PubKeyHash(pkh))
                        }
                        18 => {
-                               if bytes.len() != 20 {
-                                       return Err(ParseError::InvalidScriptHashLength);
-                               }
-                               let mut sh = [0u8; 20];
-                               sh.copy_from_slice(&bytes);
+                               let sh = match ScriptHash::from_slice(&bytes) {
+                                       Ok(sh) => sh,
+                                       Err(bitcoin_hashes::Error::InvalidLength(_, _)) => return Err(ParseError::InvalidScriptHashLength),
+                               };
                                Ok(Fallback::ScriptHash(sh))
                        }
                        _ => Err(ParseError::Skip)
@@ -619,46 +617,6 @@ impl FromBase32 for PrivateRoute {
        }
 }
 
-/// Errors that indicate what is wrong with the invoice. They have some granularity for debug
-/// reasons, but should generally result in an "invalid BOLT11 invoice" message for the user.
-#[allow(missing_docs)]
-#[derive(PartialEq, Debug, Clone)]
-pub enum ParseError {
-       Bech32Error(bech32::Error),
-       ParseAmountError(ParseIntError),
-       MalformedSignature(secp256k1::Error),
-       BadPrefix,
-       UnknownCurrency,
-       UnknownSiPrefix,
-       MalformedHRP,
-       TooShortDataPart,
-       UnexpectedEndOfTaggedFields,
-       DescriptionDecodeError(str::Utf8Error),
-       PaddingError,
-       IntegerOverflowError,
-       InvalidSegWitProgramLength,
-       InvalidPubKeyHashLength,
-       InvalidScriptHashLength,
-       InvalidRecoveryId,
-       InvalidSliceLength(String),
-
-       /// Not an error, but used internally to signal that a part of the invoice should be ignored
-       /// according to BOLT11
-       Skip,
-}
-
-/// Indicates that something went wrong while parsing or validating the invoice. Parsing errors
-/// should be mostly seen as opaque and are only there for debugging reasons. Semantic errors
-/// like wrong signatures, missing fields etc. could mean that someone tampered with the invoice.
-#[derive(PartialEq, Debug, Clone)]
-pub enum ParseOrSemanticError {
-       /// The invoice couldn't be decoded
-       ParseError(ParseError),
-
-       /// The invoice could be decoded but violates the BOLT11 standard
-       SemanticError(::SemanticError),
-}
-
 impl Display for ParseError {
        fn fmt(&self, f: &mut Formatter) -> fmt::Result {
                match *self {
@@ -755,7 +713,7 @@ impl From<ParseError> for ParseOrSemanticError {
        }
 }
 
-impl From<::SemanticError> for ParseOrSemanticError {
+impl From<crate::SemanticError> for ParseOrSemanticError {
        fn from(e: SemanticError) -> Self {
                ParseOrSemanticError::SemanticError(e)
        }
@@ -763,7 +721,7 @@ impl From<::SemanticError> for ParseOrSemanticError {
 
 #[cfg(test)]
 mod test {
-       use de::ParseError;
+       use crate::de::ParseError;
        use secp256k1::PublicKey;
        use bech32::u5;
        use bitcoin_hashes::hex::FromHex;
@@ -789,7 +747,7 @@ mod test {
 
        #[test]
        fn test_parse_currency_prefix() {
-               use Currency;
+               use crate::Currency;
 
                assert_eq!("bc".parse::<Currency>(), Ok(Currency::Bitcoin));
                assert_eq!("tb".parse::<Currency>(), Ok(Currency::BitcoinTestnet));
@@ -801,7 +759,7 @@ mod test {
 
        #[test]
        fn test_parse_int_from_bytes_be() {
-               use de::parse_int_be;
+               use crate::de::parse_int_be;
 
                assert_eq!(parse_int_be::<u32, u8>(&[1, 2, 3, 4], 256), Some(16909060));
                assert_eq!(parse_int_be::<u32, u8>(&[1, 3], 32), Some(35));
@@ -811,7 +769,7 @@ mod test {
 
        #[test]
        fn test_parse_sha256_hash() {
-               use Sha256;
+               use crate::Sha256;
                use bech32::FromBase32;
 
                let input = from_bech32(
@@ -834,7 +792,7 @@ mod test {
 
        #[test]
        fn test_parse_description() {
-               use ::Description;
+               use crate::Description;
                use bech32::FromBase32;
 
                let input = from_bech32("xysxxatsyp3k7enxv4js".as_bytes());
@@ -844,7 +802,7 @@ mod test {
 
        #[test]
        fn test_parse_payee_pub_key() {
-               use ::PayeePubKey;
+               use crate::PayeePubKey;
                use bech32::FromBase32;
 
                let input = from_bech32("q0n326hr8v9zprg8gsvezcch06gfaqqhde2aj730yg0durunfhv66".as_bytes());
@@ -868,7 +826,7 @@ mod test {
 
        #[test]
        fn test_parse_expiry_time() {
-               use ::ExpiryTime;
+               use crate::ExpiryTime;
                use bech32::FromBase32;
 
                let input = from_bech32("pu".as_bytes());
@@ -880,40 +838,43 @@ mod test {
        }
 
        #[test]
-       fn test_parse_min_final_cltv_expiry() {
-               use ::MinFinalCltvExpiry;
+       fn test_parse_min_final_cltv_expiry_delta() {
+               use crate::MinFinalCltvExpiryDelta;
                use bech32::FromBase32;
 
                let input = from_bech32("pr".as_bytes());
-               let expected = Ok(MinFinalCltvExpiry(35));
+               let expected = Ok(MinFinalCltvExpiryDelta(35));
 
-               assert_eq!(MinFinalCltvExpiry::from_base32(&input), expected);
+               assert_eq!(MinFinalCltvExpiryDelta::from_base32(&input), expected);
        }
 
        #[test]
        fn test_parse_fallback() {
-               use Fallback;
+               use crate::Fallback;
                use bech32::FromBase32;
+               use bitcoin::{PubkeyHash, ScriptHash};
+               use bitcoin::util::address::WitnessVersion;
+               use bitcoin_hashes::Hash;
 
                let cases = vec![
                        (
                                from_bech32("3x9et2e20v6pu37c5d9vax37wxq72un98".as_bytes()),
-                               Ok(Fallback::PubKeyHash([
+                               Ok(Fallback::PubKeyHash(PubkeyHash::from_slice(&[
                                        0x31, 0x72, 0xb5, 0x65, 0x4f, 0x66, 0x83, 0xc8, 0xfb, 0x14, 0x69, 0x59, 0xd3,
                                        0x47, 0xce, 0x30, 0x3c, 0xae, 0x4c, 0xa7
-                               ]))
+                               ]).unwrap()))
                        ),
                        (
                                from_bech32("j3a24vwu6r8ejrss3axul8rxldph2q7z9".as_bytes()),
-                               Ok(Fallback::ScriptHash([
+                               Ok(Fallback::ScriptHash(ScriptHash::from_slice(&[
                                        0x8f, 0x55, 0x56, 0x3b, 0x9a, 0x19, 0xf3, 0x21, 0xc2, 0x11, 0xe9, 0xb9, 0xf3,
                                        0x8c, 0xdf, 0x68, 0x6e, 0xa0, 0x78, 0x45
-                               ]))
+                               ]).unwrap()))
                        ),
                        (
                                from_bech32("qw508d6qejxtdg4y5r3zarvary0c5xw7k".as_bytes()),
                                Ok(Fallback::SegWitProgram {
-                                       version: u5::try_from_u8(0).unwrap(),
+                                       version: WitnessVersion::V0,
                                        program: Vec::from(&[
                                                0x75u8, 0x1e, 0x76, 0xe8, 0x19, 0x91, 0x96, 0xd4, 0x54, 0x94, 0x1c, 0x45,
                                                0xd1, 0xb3, 0xa3, 0x23, 0xf1, 0x43, 0x3b, 0xd6
@@ -949,11 +910,11 @@ mod test {
 
        #[test]
        fn test_parse_route() {
-               use lightning::routing::network_graph::RoutingFees;
+               use lightning::routing::gossip::RoutingFees;
                use lightning::routing::router::{RouteHint, RouteHintHop};
-               use ::PrivateRoute;
+               use crate::PrivateRoute;
                use bech32::FromBase32;
-               use de::parse_int_be;
+               use crate::de::parse_int_be;
 
                let input = from_bech32(
                        "q20q82gphp2nflc7jtzrcazrra7wwgzxqc8u7754cdlpfrmccae92qgzqvzq2ps8pqqqqqqpqqqqq9qqqvpeuqa\
@@ -1007,9 +968,9 @@ mod test {
        #[test]
        fn test_payment_secret_and_features_de_and_ser() {
                use lightning::ln::features::InvoiceFeatures;
-               use secp256k1::recovery::{RecoveryId, RecoverableSignature};
-               use TaggedField::*;
-               use {SiPrefix, SignedRawInvoice, InvoiceSignature, RawInvoice, RawHrp, RawDataPart,
+               use secp256k1::ecdsa::{RecoveryId, RecoverableSignature};
+               use crate::TaggedField::*;
+               use crate::{SiPrefix, SignedRawInvoice, InvoiceSignature, RawInvoice, RawHrp, RawDataPart,
                                 Currency, Sha256, PositiveTimestamp};
 
                // Feature bits 9, 15, and 99 are set.
@@ -1028,8 +989,8 @@ mod test {
                                                                PaymentHash(Sha256(sha256::Hash::from_hex(
                                                                        "0001020304050607080900010203040506070809000102030405060708090102"
                                                                ).unwrap())).into(),
-                                                               Description(::Description::new("coffee beans".to_owned()).unwrap()).into(),
-                                                               PaymentSecret(::PaymentSecret([17; 32])).into(),
+                                                               Description(crate::Description::new("coffee beans".to_owned()).unwrap()).into(),
+                                                               PaymentSecret(crate::PaymentSecret([17; 32])).into(),
                                                                Features(expected_features).into()]}
                                                                },
                                        hash: [0xb1, 0x96, 0x46, 0xc3, 0xbc, 0x56, 0x76, 0x1d, 0x20, 0x65, 0x6e, 0x0e, 0x32,
@@ -1053,9 +1014,9 @@ mod test {
 
        #[test]
        fn test_raw_signed_invoice_deserialization() {
-               use TaggedField::*;
-               use secp256k1::recovery::{RecoveryId, RecoverableSignature};
-               use {SignedRawInvoice, InvoiceSignature, RawInvoice, RawHrp, RawDataPart, Currency, Sha256,
+               use crate::TaggedField::*;
+               use secp256k1::ecdsa::{RecoveryId, RecoverableSignature};
+               use crate::{SignedRawInvoice, InvoiceSignature, RawInvoice, RawHrp, RawDataPart, Currency, Sha256,
                         PositiveTimestamp};
 
                assert_eq!(
@@ -1076,7 +1037,7 @@ mod test {
                                                        "0001020304050607080900010203040506070809000102030405060708090102"
                                                ).unwrap())).into(),
                                                Description(
-                                                       ::Description::new(
+                                                       crate::Description::new(
                                                                "Please consider supporting this project".to_owned()
                                                        ).unwrap()
                                                ).into(),