X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning-invoice%2Fsrc%2Fde.rs;h=92c1cb5c28f5385b5eb2f37c2cbbac62b58ac398;hb=6ddf69c93b1c3e418251ed7a898efd943e47bc30;hp=dbcb74e073aeaec450a3333159cfb6ace5232115;hpb=bee9a1e4030e04a91a2d774784a2e2fc545ae797;p=rust-lightning diff --git a/lightning-invoice/src/de.rs b/lightning-invoice/src/de.rs index dbcb74e0..92c1cb5c 100644 --- a/lightning-invoice/src/de.rs +++ b/lightning-invoice/src/de.rs @@ -1,34 +1,36 @@ +#[cfg(feature = "std")] use std::error; -use std::fmt; -use std::fmt::{Display, Formatter}; -use std::num::ParseIntError; -use std::str; -use std::str::FromStr; +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_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, CreationError, 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; /// State machine to parse the hrp mod hrp_sm { - use std::ops::Range; + use core::ops::Range; #[derive(PartialEq, Eq, Debug)] enum States { @@ -77,7 +79,7 @@ mod hrp_sm { } else if ['m', 'u', 'n', 'p'].contains(&read_symbol) { Ok(States::ParseAmountSiPrefix) } else { - Err(super::ParseError::MalformedHRP) + Err(super::ParseError::UnknownSiPrefix) } }, States::ParseAmountSiPrefix => Err(super::ParseError::MalformedHRP), @@ -195,7 +197,7 @@ impl FromStr for SiPrefix { type Err = ParseError; fn from_str(currency_prefix: &str) -> Result { - use SiPrefix::*; + use crate::SiPrefix::*; match currency_prefix { "m" => Ok(Milli), "u" => Ok(Micro), @@ -209,10 +211,18 @@ impl FromStr for SiPrefix { /// ``` /// use lightning_invoice::Invoice; /// -/// let invoice = "lnbc1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdp\ -/// l2pkx2ctnv5sxxmmwwd5kgetjypeh2ursdae8g6twvus8g6rfwvs8qun0dfjkxaq8rkx3yf5tcsyz3d7\ -/// 3gafnh3cax9rn449d9p5uxz9ezhhypd0elx87sjle52x86fux2ypatgddc6k63n7erqz25le42c4u4ec\ -/// ky03ylcqca784w"; +/// +/// let invoice = "lnbc100p1psj9jhxdqud3jxktt5w46x7unfv9kz6mn0v3jsnp4q0d3p2sfluzdx45tqcs\ +/// h2pu5qc7lgq0xs578ngs6s0s68ua4h7cvspp5q6rmq35js88zp5dvwrv9m459tnk2zunwj5jalqtyxqulh0l\ +/// 5gflssp5nf55ny5gcrfl30xuhzj3nphgj27rstekmr9fw3ny5989s300gyus9qyysgqcqpcrzjqw2sxwe993\ +/// h5pcm4dxzpvttgza8zhkqxpgffcrf5v25nwpr3cmfg7z54kuqq8rgqqqqqqqq2qqqqq9qq9qrzjqd0ylaqcl\ +/// j9424x9m8h2vcukcgnm6s56xfgu3j78zyqzhgs4hlpzvznlugqq9vsqqqqqqqlgqqqqqeqq9qrzjqwldmj9d\ +/// ha74df76zhx6l9we0vjdquygcdt3kssupehe64g6yyp5yz5rhuqqwccqqyqqqqlgqqqqjcqq9qrzjqf9e58a\ +/// guqr0rcun0ajlvmzq3ek63cw2w282gv3z5uupmuwvgjtq2z55qsqqg6qqqyqqqrtnqqqzq3cqygrzjqvphms\ +/// ywntrrhqjcraumvc4y6r8v4z5v593trte429v4hredj7ms5z52usqq9ngqqqqqqqlgqqqqqqgq9qrzjq2v0v\ +/// p62g49p7569ev48cmulecsxe59lvaw3wlxm7r982zxa9zzj7z5l0cqqxusqqyqqqqlgqqqqqzsqygarl9fh3\ +/// 8s0gyuxjjgux34w75dnc6xp2l35j7es3jd4ugt3lu0xzre26yg5m7ke54n2d5sym4xcmxtl8238xxvw5h5h5\ +/// j5r6drg6k6zcqj0fcwg"; /// /// assert!(invoice.parse::().is_ok()); /// ``` @@ -228,10 +238,17 @@ impl FromStr for Invoice { /// ``` /// use lightning_invoice::*; /// -/// let invoice = "lnbc1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdp\ -/// l2pkx2ctnv5sxxmmwwd5kgetjypeh2ursdae8g6twvus8g6rfwvs8qun0dfjkxaq8rkx3yf5tcsyz3d7\ -/// 3gafnh3cax9rn449d9p5uxz9ezhhypd0elx87sjle52x86fux2ypatgddc6k63n7erqz25le42c4u4ec\ -/// ky03ylcqca784w"; +/// let invoice = "lnbc100p1psj9jhxdqud3jxktt5w46x7unfv9kz6mn0v3jsnp4q0d3p2sfluzdx45tqcs\ +/// h2pu5qc7lgq0xs578ngs6s0s68ua4h7cvspp5q6rmq35js88zp5dvwrv9m459tnk2zunwj5jalqtyxqulh0l\ +/// 5gflssp5nf55ny5gcrfl30xuhzj3nphgj27rstekmr9fw3ny5989s300gyus9qyysgqcqpcrzjqw2sxwe993\ +/// h5pcm4dxzpvttgza8zhkqxpgffcrf5v25nwpr3cmfg7z54kuqq8rgqqqqqqqq2qqqqq9qq9qrzjqd0ylaqcl\ +/// j9424x9m8h2vcukcgnm6s56xfgu3j78zyqzhgs4hlpzvznlugqq9vsqqqqqqqlgqqqqqeqq9qrzjqwldmj9d\ +/// ha74df76zhx6l9we0vjdquygcdt3kssupehe64g6yyp5yz5rhuqqwccqqyqqqqlgqqqqjcqq9qrzjqf9e58a\ +/// guqr0rcun0ajlvmzq3ek63cw2w282gv3z5uupmuwvgjtq2z55qsqqg6qqqyqqqrtnqqqzq3cqygrzjqvphms\ +/// ywntrrhqjcraumvc4y6r8v4z5v593trte429v4hredj7ms5z52usqq9ngqqqqqqqlgqqqqqqgq9qrzjq2v0v\ +/// p62g49p7569ev48cmulecsxe59lvaw3wlxm7r982zxa9zzj7z5l0cqqxusqqyqqqqlgqqqqqzsqygarl9fh3\ +/// 8s0gyuxjjgux34w75dnc6xp2l35j7es3jd4ugt3lu0xzre26yg5m7ke54n2d5sym4xcmxtl8238xxvw5h5h5\ +/// j5r6drg6k6zcqj0fcwg"; /// /// let parsed_1 = invoice.parse::(); /// @@ -342,7 +359,6 @@ impl FromBase32 for PositiveTimestamp { .expect("7*5bit < 64bit, no overflow possible"); match PositiveTimestamp::from_unix_timestamp(timestamp) { Ok(t) => Ok(t), - Err(CreationError::TimestampOutOfBounds) => Err(ParseError::TimestampOverflow), Err(_) => unreachable!(), } } @@ -404,7 +420,7 @@ fn parse_tagged_parts(data: &[u5]) -> Result, ParseError> { Ok(field) => { parts.push(RawTaggedField::KnownSemantics(field)) }, - Err(ParseError::Skip) => { + Err(ParseError::Skip)|Err(ParseError::Bech32Error(bech32::Error::InvalidLength)) => { parts.push(RawTaggedField::UnknownSemantics(field.into())) }, Err(e) => {return Err(e)} @@ -435,8 +451,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 => @@ -499,7 +515,7 @@ impl FromBase32 for ExpiryTime { fn from_base32(field_data: &[u5]) -> Result { match parse_int_be::(field_data, 32) - .and_then(|t| ExpiryTime::from_seconds(t).ok()) // ok, since the only error is out of bounds + .map(|t| ExpiryTime::from_seconds(t)) { Some(t) => Ok(t), None => Err(ParseError::IntegerOverflowError), @@ -507,13 +523,13 @@ impl FromBase32 for ExpiryTime { } } -impl FromBase32 for MinFinalCltvExpiry { +impl FromBase32 for MinFinalCltvExpiryDelta { type Err = ParseError; - fn from_base32(field_data: &[u5]) -> Result { + fn from_base32(field_data: &[u5]) -> Result { let expiry = parse_int_be::(field_data, 32); if let Some(expiry) = expiry { - Ok(MinFinalCltvExpiry(expiry)) + Ok(MinFinalCltvExpiryDelta(expiry)) } else { Err(ParseError::IntegerOverflowError) } @@ -603,47 +619,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, - TimestampOverflow, -} - -/// 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 { @@ -692,9 +667,6 @@ impl Display for ParseError { ParseError::Skip => { f.write_str("the tagged field has to be skipped because of an unexpected, but allowed property") }, - ParseError::TimestampOverflow => { - f.write_str("the invoice's timestamp could not be represented as SystemTime") - }, } } } @@ -708,8 +680,10 @@ impl Display for ParseOrSemanticError { } } +#[cfg(feature = "std")] impl error::Error for ParseError {} +#[cfg(feature = "std")] impl error::Error for ParseOrSemanticError {} macro_rules! from_error { @@ -741,7 +715,7 @@ impl From for ParseOrSemanticError { } } -impl From<::SemanticError> for ParseOrSemanticError { +impl From for ParseOrSemanticError { fn from(e: SemanticError) -> Self { ParseOrSemanticError::SemanticError(e) } @@ -749,7 +723,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; @@ -775,7 +749,7 @@ mod test { #[test] fn test_parse_currency_prefix() { - use Currency; + use crate::Currency; assert_eq!("bc".parse::(), Ok(Currency::Bitcoin)); assert_eq!("tb".parse::(), Ok(Currency::BitcoinTestnet)); @@ -787,7 +761,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::(&[1, 2, 3, 4], 256), Some(16909060)); assert_eq!(parse_int_be::(&[1, 3], 32), Some(35)); @@ -797,7 +771,7 @@ mod test { #[test] fn test_parse_sha256_hash() { - use Sha256; + use crate::Sha256; use bech32::FromBase32; let input = from_bech32( @@ -820,7 +794,7 @@ mod test { #[test] fn test_parse_description() { - use ::Description; + use crate::Description; use bech32::FromBase32; let input = from_bech32("xysxxatsyp3k7enxv4js".as_bytes()); @@ -830,7 +804,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()); @@ -854,11 +828,11 @@ mod test { #[test] fn test_parse_expiry_time() { - use ::ExpiryTime; + use crate::ExpiryTime; use bech32::FromBase32; let input = from_bech32("pu".as_bytes()); - let expected = Ok(ExpiryTime::from_seconds(60).unwrap()); + let expected = Ok(ExpiryTime::from_seconds(60)); assert_eq!(ExpiryTime::from_base32(&input), expected); let input_too_large = from_bech32("sqqqqqqqqqqqq".as_bytes()); @@ -866,19 +840,19 @@ 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; let cases = vec![ @@ -935,11 +909,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\ @@ -993,9 +967,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. @@ -1014,8 +988,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, @@ -1039,9 +1013,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!( @@ -1062,7 +1036,7 @@ mod test { "0001020304050607080900010203040506070809000102030405060708090102" ).unwrap())).into(), Description( - ::Description::new( + crate::Description::new( "Please consider supporting this project".to_owned() ).unwrap() ).into(),