400cf51a2944d47cc0afd19e227acb3216242959
[rust-lightning] / lightning / src / offers / parse.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Parsing and formatting for bech32 message encoding.
11
12 use bitcoin::bech32;
13 use bitcoin::secp256k1;
14 use core::convert::TryFrom;
15 use crate::io;
16 use crate::ln::msgs::DecodeError;
17 use crate::util::ser::SeekReadable;
18
19 use crate::prelude::*;
20
21 #[cfg(not(fuzzing))]
22 pub(super) use sealed::Bech32Encode;
23
24 #[cfg(fuzzing)]
25 pub use sealed::Bech32Encode;
26
27 mod sealed {
28         use bitcoin::bech32;
29         use bitcoin::bech32::{FromBase32, ToBase32};
30         use core::convert::TryFrom;
31         use core::fmt;
32         use super::Bolt12ParseError;
33
34         use crate::prelude::*;
35
36         /// Indicates a message can be encoded using bech32.
37         pub trait Bech32Encode: AsRef<[u8]> + TryFrom<Vec<u8>, Error=Bolt12ParseError> {
38                 /// Human readable part of the message's bech32 encoding.
39                 const BECH32_HRP: &'static str;
40
41                 /// Parses a bech32-encoded message into a TLV stream.
42                 fn from_bech32_str(s: &str) -> Result<Self, Bolt12ParseError> {
43                         // Offer encoding may be split by '+' followed by optional whitespace.
44                         let encoded = match s.split('+').skip(1).next() {
45                                 Some(_) => {
46                                         for chunk in s.split('+') {
47                                                 let chunk = chunk.trim_start();
48                                                 if chunk.is_empty() || chunk.contains(char::is_whitespace) {
49                                                         return Err(Bolt12ParseError::InvalidContinuation);
50                                                 }
51                                         }
52
53                                         let s: String = s.chars().filter(|c| *c != '+' && !c.is_whitespace()).collect();
54                                         Bech32String::Owned(s)
55                                 },
56                                 None => Bech32String::Borrowed(s),
57                         };
58
59                         let (hrp, data) = bech32::decode_without_checksum(encoded.as_ref())?;
60
61                         if hrp != Self::BECH32_HRP {
62                                 return Err(Bolt12ParseError::InvalidBech32Hrp);
63                         }
64
65                         let data = Vec::<u8>::from_base32(&data)?;
66                         Self::try_from(data)
67                 }
68
69                 /// Formats the message using bech32-encoding.
70                 fn fmt_bech32_str(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
71                         bech32::encode_without_checksum_to_fmt(f, Self::BECH32_HRP, self.as_ref().to_base32())
72                                 .expect("HRP is invalid").unwrap();
73
74                         Ok(())
75                 }
76         }
77
78         // Used to avoid copying a bech32 string not containing the continuation character (+).
79         enum Bech32String<'a> {
80                 Borrowed(&'a str),
81                 Owned(String),
82         }
83
84         impl<'a> AsRef<str> for Bech32String<'a> {
85                 fn as_ref(&self) -> &str {
86                         match self {
87                                 Bech32String::Borrowed(s) => s,
88                                 Bech32String::Owned(s) => s,
89                         }
90                 }
91         }
92 }
93
94 /// A wrapper for reading a message as a TLV stream `T` from a byte sequence, while still
95 /// maintaining ownership of the bytes for later use.
96 pub(super) struct ParsedMessage<T: SeekReadable> {
97         pub bytes: Vec<u8>,
98         pub tlv_stream: T,
99 }
100
101 impl<T: SeekReadable> TryFrom<Vec<u8>> for ParsedMessage<T> {
102         type Error = DecodeError;
103
104         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
105                 let mut cursor = io::Cursor::new(bytes);
106                 let tlv_stream: T = SeekReadable::read(&mut cursor)?;
107
108                 // Ensure that there are no more TLV records left to parse.
109                 if cursor.position() < cursor.get_ref().len() as u64 {
110                         return Err(DecodeError::InvalidValue);
111                 }
112
113                 let bytes = cursor.into_inner();
114                 Ok(Self { bytes, tlv_stream })
115         }
116 }
117
118 /// Error when parsing a bech32 encoded message using [`str::parse`].
119 #[derive(Clone, Debug, PartialEq)]
120 pub enum Bolt12ParseError {
121         /// The bech32 encoding does not conform to the BOLT 12 requirements for continuing messages
122         /// across multiple parts (i.e., '+' followed by whitespace).
123         InvalidContinuation,
124         /// The bech32 encoding's human-readable part does not match what was expected for the message
125         /// being parsed.
126         InvalidBech32Hrp,
127         /// The string could not be bech32 decoded.
128         Bech32(bech32::Error),
129         /// The bech32 decoded string could not be decoded as the expected message type.
130         Decode(DecodeError),
131         /// The parsed message has invalid semantics.
132         InvalidSemantics(Bolt12SemanticError),
133         /// The parsed message has an invalid signature.
134         InvalidSignature(secp256k1::Error),
135 }
136
137 /// Error when interpreting a TLV stream as a specific type.
138 #[derive(Clone, Debug, PartialEq)]
139 pub enum Bolt12SemanticError {
140         /// The current [`std::time::SystemTime`] is past the offer or invoice's expiration.
141         AlreadyExpired,
142         /// The provided chain hash does not correspond to a supported chain.
143         UnsupportedChain,
144         /// A chain was provided but was not expected.
145         UnexpectedChain,
146         /// An amount was expected but was missing.
147         MissingAmount,
148         /// The amount exceeded the total bitcoin supply.
149         InvalidAmount,
150         /// An amount was provided but was not sufficient in value.
151         InsufficientAmount,
152         /// An amount was provided but was not expected.
153         UnexpectedAmount,
154         /// A currency was provided that is not supported.
155         UnsupportedCurrency,
156         /// A feature was required but is unknown.
157         UnknownRequiredFeatures,
158         /// Features were provided but were not expected.
159         UnexpectedFeatures,
160         /// A required description was not provided.
161         MissingDescription,
162         /// A signing pubkey was not provided.
163         MissingSigningPubkey,
164         /// A signing pubkey was provided but a different one was expected.
165         InvalidSigningPubkey,
166         /// A signing pubkey was provided but was not expected.
167         UnexpectedSigningPubkey,
168         /// A quantity was expected but was missing.
169         MissingQuantity,
170         /// An unsupported quantity was provided.
171         InvalidQuantity,
172         /// A quantity or quantity bounds was provided but was not expected.
173         UnexpectedQuantity,
174         /// Metadata could not be used to verify the offers message.
175         InvalidMetadata,
176         /// Metadata was provided but was not expected.
177         UnexpectedMetadata,
178         /// Payer metadata was expected but was missing.
179         MissingPayerMetadata,
180         /// A payer id was expected but was missing.
181         MissingPayerId,
182         /// The payment id for a refund or request is already in use.
183         DuplicatePaymentId,
184         /// Blinded paths were expected but were missing.
185         MissingPaths,
186         /// The blinded payinfo given does not match the number of blinded path hops.
187         InvalidPayInfo,
188         /// An invoice creation time was expected but was missing.
189         MissingCreationTime,
190         /// An invoice payment hash was expected but was missing.
191         MissingPaymentHash,
192         /// A signature was expected but was missing.
193         MissingSignature,
194 }
195
196 impl From<bech32::Error> for Bolt12ParseError {
197         fn from(error: bech32::Error) -> Self {
198                 Self::Bech32(error)
199         }
200 }
201
202 impl From<DecodeError> for Bolt12ParseError {
203         fn from(error: DecodeError) -> Self {
204                 Self::Decode(error)
205         }
206 }
207
208 impl From<Bolt12SemanticError> for Bolt12ParseError {
209         fn from(error: Bolt12SemanticError) -> Self {
210                 Self::InvalidSemantics(error)
211         }
212 }
213
214 impl From<secp256k1::Error> for Bolt12ParseError {
215         fn from(error: secp256k1::Error) -> Self {
216                 Self::InvalidSignature(error)
217         }
218 }
219
220 #[cfg(test)]
221 mod bolt12_tests {
222         use super::Bolt12ParseError;
223         use crate::offers::offer::Offer;
224
225         #[test]
226         fn encodes_offer_as_bech32_without_checksum() {
227                 let encoded_offer = "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg";
228                 let offer = dbg!(encoded_offer.parse::<Offer>().unwrap());
229                 let reencoded_offer = offer.to_string();
230                 dbg!(reencoded_offer.parse::<Offer>().unwrap());
231                 assert_eq!(reencoded_offer, encoded_offer);
232         }
233
234         #[test]
235         fn parses_bech32_encoded_offers() {
236                 let offers = [
237                         // A complete string is valid
238                         "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
239
240                         // + can join anywhere
241                         "l+no1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
242
243                         // Multiple + can join
244                         "lno1pqps7sjqpgt+yzm3qv4uxzmtsd3jjqer9wd3hy6tsw3+5k7msjzfpy7nz5yqcn+ygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd+5xvxg",
245
246                         // + can be followed by whitespace
247                         "lno1pqps7sjqpgt+ yzm3qv4uxzmtsd3jjqer9wd3hy6tsw3+  5k7msjzfpy7nz5yqcn+\nygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd+\r\n 5xvxg",
248                 ];
249                 for encoded_offer in &offers {
250                         if let Err(e) = encoded_offer.parse::<Offer>() {
251                                 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
252                         }
253                 }
254         }
255
256         #[test]
257         fn fails_parsing_bech32_encoded_offers_with_invalid_continuations() {
258                 let offers = [
259                         // + must be surrounded by bech32 characters
260                         "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg+",
261                         "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg+ ",
262                         "+lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
263                         "+ lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
264                         "ln++o1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
265                 ];
266                 for encoded_offer in &offers {
267                         match encoded_offer.parse::<Offer>() {
268                                 Ok(_) => panic!("Valid offer: {}", encoded_offer),
269                                 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidContinuation),
270                         }
271                 }
272         }
273 }
274
275 #[cfg(test)]
276 mod tests {
277         use super::Bolt12ParseError;
278         use bitcoin::bech32;
279         use crate::ln::msgs::DecodeError;
280         use crate::offers::offer::Offer;
281
282         #[test]
283         fn fails_parsing_bech32_encoded_offer_with_invalid_hrp() {
284                 let encoded_offer = "lni1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg";
285                 match encoded_offer.parse::<Offer>() {
286                         Ok(_) => panic!("Valid offer: {}", encoded_offer),
287                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidBech32Hrp),
288                 }
289         }
290
291         #[test]
292         fn fails_parsing_bech32_encoded_offer_with_invalid_bech32_data() {
293                 let encoded_offer = "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxo";
294                 match encoded_offer.parse::<Offer>() {
295                         Ok(_) => panic!("Valid offer: {}", encoded_offer),
296                         Err(e) => assert_eq!(e, Bolt12ParseError::Bech32(bech32::Error::InvalidChar('o'))),
297                 }
298         }
299
300         #[test]
301         fn fails_parsing_bech32_encoded_offer_with_invalid_tlv_data() {
302                 let encoded_offer = "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxgqqqqq";
303                 match encoded_offer.parse::<Offer>() {
304                         Ok(_) => panic!("Valid offer: {}", encoded_offer),
305                         Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
306                 }
307         }
308 }