73965211004a228324c73ad33144e6a0f1814cac
[rust-lightning] / lightning-invoice / src / lib.rs
1 #![deny(missing_docs)]
2 #![deny(non_upper_case_globals)]
3 #![deny(non_camel_case_types)]
4 #![deny(non_snake_case)]
5 #![deny(unused_mut)]
6 #![deny(broken_intra_doc_links)]
7
8 #![cfg_attr(feature = "strict", deny(warnings))]
9 #![cfg_attr(all(not(feature = "std"), not(test)), no_std)]
10
11 //! This crate provides data structures to represent
12 //! [lightning BOLT11](https://github.com/lightningnetwork/lightning-rfc/blob/master/11-payment-encoding.md)
13 //! invoices and functions to create, encode and decode these. If you just want to use the standard
14 //! en-/decoding functionality this should get you started:
15 //!
16 //!   * For parsing use `str::parse::<Invoice>(&self)` (see the docs of `impl FromStr for Invoice`)
17 //!   * For constructing invoices use the `InvoiceBuilder`
18 //!   * For serializing invoices use the `Display`/`ToString` traits
19
20 #[cfg(not(any(feature = "std", feature = "no-std")))]
21 compile_error!("at least one of the `std` or `no-std` features must be enabled");
22
23 pub mod payment;
24 pub mod utils;
25
26 extern crate bech32;
27 extern crate bitcoin_hashes;
28 #[macro_use] extern crate lightning;
29 extern crate num_traits;
30 extern crate secp256k1;
31 extern crate alloc;
32 #[cfg(any(test, feature = "std"))]
33 extern crate core;
34
35 #[cfg(feature = "std")]
36 use std::time::SystemTime;
37
38 use bech32::u5;
39 use bitcoin_hashes::Hash;
40 use bitcoin_hashes::sha256;
41 use lightning::ln::PaymentSecret;
42 use lightning::ln::features::InvoiceFeatures;
43 #[cfg(any(doc, test))]
44 use lightning::routing::network_graph::RoutingFees;
45 use lightning::routing::router::RouteHint;
46 use lightning::util::invoice::construct_invoice_preimage;
47
48 use secp256k1::key::PublicKey;
49 use secp256k1::{Message, Secp256k1};
50 use secp256k1::recovery::RecoverableSignature;
51
52 use core::fmt::{Display, Formatter, self};
53 use core::iter::FilterMap;
54 use core::ops::Deref;
55 use core::slice::Iter;
56 use core::time::Duration;
57
58 mod de;
59 mod ser;
60 mod tb;
61
62 mod prelude {
63         #[cfg(feature = "hashbrown")]
64         extern crate hashbrown;
65
66         pub use alloc::{vec, vec::Vec, string::String, collections::VecDeque, boxed::Box};
67         #[cfg(not(feature = "hashbrown"))]
68         pub use std::collections::{HashMap, HashSet, hash_map};
69         #[cfg(feature = "hashbrown")]
70         pub use self::hashbrown::{HashMap, HashSet, hash_map};
71
72         pub use alloc::string::ToString;
73 }
74
75 use prelude::*;
76
77 /// Sync compat for std/no_std
78 #[cfg(feature = "std")]
79 mod sync {
80         pub use ::std::sync::{Mutex, MutexGuard};
81 }
82
83 /// Sync compat for std/no_std
84 #[cfg(not(feature = "std"))]
85 mod sync;
86
87 pub use de::{ParseError, ParseOrSemanticError};
88
89 /// The number of bits used to represent timestamps as defined in BOLT 11.
90 const TIMESTAMP_BITS: usize = 35;
91
92 /// The maximum timestamp as [`Duration::as_secs`] since the Unix epoch allowed by [`BOLT 11`].
93 ///
94 /// [BOLT 11]: https://github.com/lightning/bolts/blob/master/11-payment-encoding.md
95 pub const MAX_TIMESTAMP: u64 = (1 << TIMESTAMP_BITS) - 1;
96
97 /// Default expiry time as defined by [BOLT 11].
98 ///
99 /// [BOLT 11]: https://github.com/lightning/bolts/blob/master/11-payment-encoding.md
100 pub const DEFAULT_EXPIRY_TIME: u64 = 3600;
101
102 /// Default minimum final CLTV expiry as defined by [BOLT 11].
103 ///
104 /// Note that this is *not* the same value as rust-lightning's minimum CLTV expiry, which is
105 /// provided in [`MIN_FINAL_CLTV_EXPIRY`].
106 ///
107 /// [BOLT 11]: https://github.com/lightning/bolts/blob/master/11-payment-encoding.md
108 /// [`MIN_FINAL_CLTV_EXPIRY`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY
109 pub const DEFAULT_MIN_FINAL_CLTV_EXPIRY: u64 = 18;
110
111 /// Builder for `Invoice`s. It's the most convenient and advised way to use this library. It ensures
112 /// that only a semantically and syntactically correct Invoice can be built using it.
113 ///
114 /// ```
115 /// extern crate secp256k1;
116 /// extern crate lightning;
117 /// extern crate lightning_invoice;
118 /// extern crate bitcoin_hashes;
119 ///
120 /// use bitcoin_hashes::Hash;
121 /// use bitcoin_hashes::sha256;
122 ///
123 /// use secp256k1::Secp256k1;
124 /// use secp256k1::key::SecretKey;
125 ///
126 /// use lightning::ln::PaymentSecret;
127 ///
128 /// use lightning_invoice::{Currency, InvoiceBuilder};
129 ///
130 /// # #[cfg(not(feature = "std"))]
131 /// # fn main() {}
132 /// # #[cfg(feature = "std")]
133 /// # fn main() {
134 /// let private_key = SecretKey::from_slice(
135 ///             &[
136 ///                     0xe1, 0x26, 0xf6, 0x8f, 0x7e, 0xaf, 0xcc, 0x8b, 0x74, 0xf5, 0x4d, 0x26, 0x9f,
137 ///                     0xe2, 0x06, 0xbe, 0x71, 0x50, 0x00, 0xf9, 0x4d, 0xac, 0x06, 0x7d, 0x1c, 0x04,
138 ///             0xa8, 0xca, 0x3b, 0x2d, 0xb7, 0x34
139 ///     ][..]
140 ///     ).unwrap();
141 ///
142 /// let payment_hash = sha256::Hash::from_slice(&[0; 32][..]).unwrap();
143 /// let payment_secret = PaymentSecret([42u8; 32]);
144 ///
145 /// let invoice = InvoiceBuilder::new(Currency::Bitcoin)
146 ///     .description("Coins pls!".into())
147 ///     .payment_hash(payment_hash)
148 ///     .payment_secret(payment_secret)
149 ///     .current_timestamp()
150 ///     .min_final_cltv_expiry(144)
151 ///     .build_signed(|hash| {
152 ///             Secp256k1::new().sign_recoverable(hash, &private_key)
153 ///     })
154 ///     .unwrap();
155 ///
156 /// assert!(invoice.to_string().starts_with("lnbc1"));
157 /// # }
158 /// ```
159 ///
160 /// # Type parameters
161 /// The two parameters `D` and `H` signal if the builder already contains the correct amount of the
162 /// given field:
163 ///  * `D`: exactly one `Description` or `DescriptionHash`
164 ///  * `H`: exactly one `PaymentHash`
165 ///  * `T`: the timestamp is set
166 ///
167 /// (C-not exported) as we likely need to manually select one set of boolean type parameters.
168 #[derive(Eq, PartialEq, Debug, Clone)]
169 pub struct InvoiceBuilder<D: tb::Bool, H: tb::Bool, T: tb::Bool, C: tb::Bool, S: tb::Bool> {
170         currency: Currency,
171         amount: Option<u64>,
172         si_prefix: Option<SiPrefix>,
173         timestamp: Option<PositiveTimestamp>,
174         tagged_fields: Vec<TaggedField>,
175         error: Option<CreationError>,
176
177         phantom_d: core::marker::PhantomData<D>,
178         phantom_h: core::marker::PhantomData<H>,
179         phantom_t: core::marker::PhantomData<T>,
180         phantom_c: core::marker::PhantomData<C>,
181         phantom_s: core::marker::PhantomData<S>,
182 }
183
184 /// Represents a syntactically and semantically correct lightning BOLT11 invoice.
185 ///
186 /// There are three ways to construct an `Invoice`:
187 ///  1. using `InvoiceBuilder`
188 ///  2. using `Invoice::from_signed(SignedRawInvoice)`
189 ///  3. using `str::parse::<Invoice>(&str)`
190 #[derive(Eq, PartialEq, Debug, Clone)]
191 pub struct Invoice {
192         signed_invoice: SignedRawInvoice,
193 }
194
195 /// Represents the description of an invoice which has to be either a directly included string or
196 /// a hash of a description provided out of band.
197 ///
198 /// (C-not exported) As we don't have a good way to map the reference lifetimes making this
199 /// practically impossible to use safely in languages like C.
200 #[derive(Eq, PartialEq, Debug, Clone)]
201 pub enum InvoiceDescription<'f> {
202         /// Reference to the directly supplied description in the invoice
203         Direct(&'f Description),
204
205         /// Reference to the description's hash included in the invoice
206         Hash(&'f Sha256),
207 }
208
209 /// Represents a signed `RawInvoice` with cached hash. The signature is not checked and may be
210 /// invalid.
211 ///
212 /// # Invariants
213 /// The hash has to be either from the deserialized invoice or from the serialized `raw_invoice`.
214 #[derive(Eq, PartialEq, Debug, Clone)]
215 pub struct SignedRawInvoice {
216         /// The rawInvoice that the signature belongs to
217         raw_invoice: RawInvoice,
218
219         /// Hash of the `RawInvoice` that will be used to check the signature.
220         ///
221         /// * if the `SignedRawInvoice` was deserialized the hash is of from the original encoded form,
222         /// since it's not guaranteed that encoding it again will lead to the same result since integers
223         /// could have been encoded with leading zeroes etc.
224         /// * if the `SignedRawInvoice` was constructed manually the hash will be the calculated hash
225         /// from the `RawInvoice`
226         hash: [u8; 32],
227
228         /// signature of the payment request
229         signature: InvoiceSignature,
230 }
231
232 /// Represents an syntactically correct Invoice for a payment on the lightning network,
233 /// but without the signature information.
234 /// De- and encoding should not lead to information loss but may lead to different hashes.
235 ///
236 /// For methods without docs see the corresponding methods in `Invoice`.
237 #[derive(Eq, PartialEq, Debug, Clone)]
238 pub struct RawInvoice {
239         /// human readable part
240         pub hrp: RawHrp,
241
242         /// data part
243         pub data: RawDataPart,
244 }
245
246 /// Data of the `RawInvoice` that is encoded in the human readable part
247 ///
248 /// (C-not exported) As we don't yet support Option<Enum>
249 #[derive(Eq, PartialEq, Debug, Clone)]
250 pub struct RawHrp {
251         /// The currency deferred from the 3rd and 4th character of the bech32 transaction
252         pub currency: Currency,
253
254         /// The amount that, multiplied by the SI prefix, has to be payed
255         pub raw_amount: Option<u64>,
256
257         /// SI prefix that gets multiplied with the `raw_amount`
258         pub si_prefix: Option<SiPrefix>,
259 }
260
261 /// Data of the `RawInvoice` that is encoded in the data part
262 #[derive(Eq, PartialEq, Debug, Clone)]
263 pub struct RawDataPart {
264         /// generation time of the invoice
265         pub timestamp: PositiveTimestamp,
266
267         /// tagged fields of the payment request
268         pub tagged_fields: Vec<RawTaggedField>,
269 }
270
271 /// A timestamp that refers to a date after 1 January 1970.
272 ///
273 /// # Invariants
274 ///
275 /// The Unix timestamp representing the stored time has to be positive and no greater than
276 /// [`MAX_TIMESTAMP`].
277 #[derive(Eq, PartialEq, Debug, Clone)]
278 pub struct PositiveTimestamp(Duration);
279
280 /// SI prefixes for the human readable part
281 #[derive(Eq, PartialEq, Debug, Clone, Copy)]
282 pub enum SiPrefix {
283         /// 10^-3
284         Milli,
285         /// 10^-6
286         Micro,
287         /// 10^-9
288         Nano,
289         /// 10^-12
290         Pico,
291 }
292
293 impl SiPrefix {
294         /// Returns the multiplier to go from a BTC value to picoBTC implied by this SiPrefix.
295         /// This is effectively 10^12 * the prefix multiplier
296         pub fn multiplier(&self) -> u64 {
297                 match *self {
298                         SiPrefix::Milli => 1_000_000_000,
299                         SiPrefix::Micro => 1_000_000,
300                         SiPrefix::Nano => 1_000,
301                         SiPrefix::Pico => 1,
302                 }
303         }
304
305         /// Returns all enum variants of `SiPrefix` sorted in descending order of their associated
306         /// multiplier.
307         ///
308         /// (C-not exported) As we don't yet support a slice of enums, and also because this function
309         /// isn't the most critical to expose.
310         pub fn values_desc() -> &'static [SiPrefix] {
311                 use SiPrefix::*;
312                 static VALUES: [SiPrefix; 4] = [Milli, Micro, Nano, Pico];
313                 &VALUES
314         }
315 }
316
317 /// Enum representing the crypto currencies (or networks) supported by this library
318 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
319 pub enum Currency {
320         /// Bitcoin mainnet
321         Bitcoin,
322
323         /// Bitcoin testnet
324         BitcoinTestnet,
325
326         /// Bitcoin regtest
327         Regtest,
328
329         /// Bitcoin simnet
330         Simnet,
331
332         /// Bitcoin signet
333         Signet,
334 }
335
336 /// Tagged field which may have an unknown tag
337 ///
338 /// (C-not exported) as we don't currently support TaggedField
339 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
340 pub enum RawTaggedField {
341         /// Parsed tagged field with known tag
342         KnownSemantics(TaggedField),
343         /// tagged field which was not parsed due to an unknown tag or undefined field semantics
344         UnknownSemantics(Vec<u5>),
345 }
346
347 /// Tagged field with known tag
348 ///
349 /// For descriptions of the enum values please refer to the enclosed type's docs.
350 ///
351 /// (C-not exported) As we don't yet support enum variants with the same name the struct contained
352 /// in the variant.
353 #[allow(missing_docs)]
354 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
355 pub enum TaggedField {
356         PaymentHash(Sha256),
357         Description(Description),
358         PayeePubKey(PayeePubKey),
359         DescriptionHash(Sha256),
360         ExpiryTime(ExpiryTime),
361         MinFinalCltvExpiry(MinFinalCltvExpiry),
362         Fallback(Fallback),
363         PrivateRoute(PrivateRoute),
364         PaymentSecret(PaymentSecret),
365         PaymentMetadata(Vec<u8>),
366         Features(InvoiceFeatures),
367 }
368
369 /// SHA-256 hash
370 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
371 pub struct Sha256(/// (C-not exported) as the native hash types are not currently mapped
372         pub sha256::Hash);
373
374 /// Description string
375 ///
376 /// # Invariants
377 /// The description can be at most 639 __bytes__ long
378 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
379 pub struct Description(String);
380
381 /// Payee public key
382 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
383 pub struct PayeePubKey(pub PublicKey);
384
385 /// Positive duration that defines when (relatively to the timestamp) in the future the invoice
386 /// expires
387 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
388 pub struct ExpiryTime(Duration);
389
390 /// `min_final_cltv_expiry` to use for the last HTLC in the route
391 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
392 pub struct MinFinalCltvExpiry(pub u64);
393
394 // TODO: better types instead onf byte arrays
395 /// Fallback address in case no LN payment is possible
396 #[allow(missing_docs)]
397 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
398 pub enum Fallback {
399         SegWitProgram {
400                 version: u5,
401                 program: Vec<u8>,
402         },
403         PubKeyHash([u8; 20]),
404         ScriptHash([u8; 20]),
405 }
406
407 /// Recoverable signature
408 #[derive(Clone, Debug, Eq, PartialEq)]
409 pub struct InvoiceSignature(pub RecoverableSignature);
410
411 /// Private routing information
412 ///
413 /// # Invariants
414 /// The encoded route has to be <1024 5bit characters long (<=639 bytes or <=12 hops)
415 ///
416 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
417 pub struct PrivateRoute(RouteHint);
418
419 /// Tag constants as specified in BOLT11
420 #[allow(missing_docs)]
421 pub mod constants {
422         pub const TAG_PAYMENT_HASH: u8 = 1;
423         pub const TAG_DESCRIPTION: u8 = 13;
424         pub const TAG_PAYEE_PUB_KEY: u8 = 19;
425         pub const TAG_DESCRIPTION_HASH: u8 = 23;
426         pub const TAG_EXPIRY_TIME: u8 = 6;
427         pub const TAG_MIN_FINAL_CLTV_EXPIRY: u8 = 24;
428         pub const TAG_FALLBACK: u8 = 9;
429         pub const TAG_PRIVATE_ROUTE: u8 = 3;
430         pub const TAG_PAYMENT_SECRET: u8 = 16;
431         pub const TAG_PAYMENT_METADATA: u8 = 27;
432         pub const TAG_FEATURES: u8 = 5;
433 }
434
435 impl InvoiceBuilder<tb::False, tb::False, tb::False, tb::False, tb::False> {
436         /// Construct new, empty `InvoiceBuilder`. All necessary fields have to be filled first before
437         /// `InvoiceBuilder::build(self)` becomes available.
438         pub fn new(currrency: Currency) -> Self {
439                 InvoiceBuilder {
440                         currency: currrency,
441                         amount: None,
442                         si_prefix: None,
443                         timestamp: None,
444                         tagged_fields: Vec::new(),
445                         error: None,
446
447                         phantom_d: core::marker::PhantomData,
448                         phantom_h: core::marker::PhantomData,
449                         phantom_t: core::marker::PhantomData,
450                         phantom_c: core::marker::PhantomData,
451                         phantom_s: core::marker::PhantomData,
452                 }
453         }
454 }
455
456 impl<D: tb::Bool, H: tb::Bool, T: tb::Bool, C: tb::Bool, S: tb::Bool> InvoiceBuilder<D, H, T, C, S> {
457         /// Helper function to set the completeness flags.
458         fn set_flags<DN: tb::Bool, HN: tb::Bool, TN: tb::Bool, CN: tb::Bool, SN: tb::Bool>(self) -> InvoiceBuilder<DN, HN, TN, CN, SN> {
459                 InvoiceBuilder::<DN, HN, TN, CN, SN> {
460                         currency: self.currency,
461                         amount: self.amount,
462                         si_prefix: self.si_prefix,
463                         timestamp: self.timestamp,
464                         tagged_fields: self.tagged_fields,
465                         error: self.error,
466
467                         phantom_d: core::marker::PhantomData,
468                         phantom_h: core::marker::PhantomData,
469                         phantom_t: core::marker::PhantomData,
470                         phantom_c: core::marker::PhantomData,
471                         phantom_s: core::marker::PhantomData,
472                 }
473         }
474
475         /// Sets the amount in millisatoshis. The optimal SI prefix is chosen automatically.
476         pub fn amount_milli_satoshis(mut self, amount_msat: u64) -> Self {
477                 let amount = amount_msat * 10; // Invoices are denominated in "pico BTC"
478                 let biggest_possible_si_prefix = SiPrefix::values_desc()
479                         .iter()
480                         .find(|prefix| amount % prefix.multiplier() == 0)
481                         .expect("Pico should always match");
482                 self.amount = Some(amount / biggest_possible_si_prefix.multiplier());
483                 self.si_prefix = Some(*biggest_possible_si_prefix);
484                 self
485         }
486
487         /// Sets the payee's public key.
488         pub fn payee_pub_key(mut self, pub_key: PublicKey) -> Self {
489                 self.tagged_fields.push(TaggedField::PayeePubKey(PayeePubKey(pub_key)));
490                 self
491         }
492
493         /// Sets the expiry time
494         pub fn expiry_time(mut self, expiry_time: Duration) -> Self {
495                 self.tagged_fields.push(TaggedField::ExpiryTime(ExpiryTime::from_duration(expiry_time)));
496                 self
497         }
498
499         /// Adds a fallback address.
500         pub fn fallback(mut self, fallback: Fallback) -> Self {
501                 self.tagged_fields.push(TaggedField::Fallback(fallback));
502                 self
503         }
504
505         /// Adds a private route.
506         pub fn private_route(mut self, hint: RouteHint) -> Self {
507                 match PrivateRoute::new(hint) {
508                         Ok(r) => self.tagged_fields.push(TaggedField::PrivateRoute(r)),
509                         Err(e) => self.error = Some(e),
510                 }
511                 self
512         }
513 }
514
515 impl<D: tb::Bool, H: tb::Bool, C: tb::Bool, S: tb::Bool> InvoiceBuilder<D, H, tb::True, C, S> {
516         /// Builds a `RawInvoice` if no `CreationError` occurred while construction any of the fields.
517         pub fn build_raw(self) -> Result<RawInvoice, CreationError> {
518
519                 // If an error occurred at any time before, return it now
520                 if let Some(e) = self.error {
521                         return Err(e);
522                 }
523
524                 let hrp = RawHrp {
525                         currency: self.currency,
526                         raw_amount: self.amount,
527                         si_prefix: self.si_prefix,
528                 };
529
530                 let timestamp = self.timestamp.expect("ensured to be Some(t) by type T");
531
532                 let tagged_fields = self.tagged_fields.into_iter().map(|tf| {
533                         RawTaggedField::KnownSemantics(tf)
534                 }).collect::<Vec<_>>();
535
536                 let data = RawDataPart {
537                         timestamp: timestamp,
538                         tagged_fields: tagged_fields,
539                 };
540
541                 Ok(RawInvoice {
542                         hrp: hrp,
543                         data: data,
544                 })
545         }
546 }
547
548 impl<H: tb::Bool, T: tb::Bool, C: tb::Bool, S: tb::Bool> InvoiceBuilder<tb::False, H, T, C, S> {
549         /// Set the description. This function is only available if no description (hash) was set.
550         pub fn description(mut self, description: String) -> InvoiceBuilder<tb::True, H, T, C, S> {
551                 match Description::new(description) {
552                         Ok(d) => self.tagged_fields.push(TaggedField::Description(d)),
553                         Err(e) => self.error = Some(e),
554                 }
555                 self.set_flags()
556         }
557
558         /// Set the description hash. This function is only available if no description (hash) was set.
559         pub fn description_hash(mut self, description_hash: sha256::Hash) -> InvoiceBuilder<tb::True, H, T, C, S> {
560                 self.tagged_fields.push(TaggedField::DescriptionHash(Sha256(description_hash)));
561                 self.set_flags()
562         }
563 }
564
565 impl<D: tb::Bool, T: tb::Bool, C: tb::Bool, S: tb::Bool> InvoiceBuilder<D, tb::False, T, C, S> {
566         /// Set the payment hash. This function is only available if no payment hash was set.
567         pub fn payment_hash(mut self, hash: sha256::Hash) -> InvoiceBuilder<D, tb::True, T, C, S> {
568                 self.tagged_fields.push(TaggedField::PaymentHash(Sha256(hash)));
569                 self.set_flags()
570         }
571 }
572
573 impl<D: tb::Bool, H: tb::Bool, C: tb::Bool, S: tb::Bool> InvoiceBuilder<D, H, tb::False, C, S> {
574         /// Sets the timestamp to a specific [`SystemTime`].
575         #[cfg(feature = "std")]
576         pub fn timestamp(mut self, time: SystemTime) -> InvoiceBuilder<D, H, tb::True, C, S> {
577                 match PositiveTimestamp::from_system_time(time) {
578                         Ok(t) => self.timestamp = Some(t),
579                         Err(e) => self.error = Some(e),
580                 }
581
582                 self.set_flags()
583         }
584
585         /// Sets the timestamp to a duration since the Unix epoch.
586         pub fn duration_since_epoch(mut self, time: Duration) -> InvoiceBuilder<D, H, tb::True, C, S> {
587                 match PositiveTimestamp::from_duration_since_epoch(time) {
588                         Ok(t) => self.timestamp = Some(t),
589                         Err(e) => self.error = Some(e),
590                 }
591
592                 self.set_flags()
593         }
594
595         /// Sets the timestamp to the current system time.
596         #[cfg(feature = "std")]
597         pub fn current_timestamp(mut self) -> InvoiceBuilder<D, H, tb::True, C, S> {
598                 let now = PositiveTimestamp::from_system_time(SystemTime::now());
599                 self.timestamp = Some(now.expect("for the foreseeable future this shouldn't happen"));
600                 self.set_flags()
601         }
602 }
603
604 impl<D: tb::Bool, H: tb::Bool, T: tb::Bool, S: tb::Bool> InvoiceBuilder<D, H, T, tb::False, S> {
605         /// Sets `min_final_cltv_expiry`.
606         pub fn min_final_cltv_expiry(mut self, min_final_cltv_expiry: u64) -> InvoiceBuilder<D, H, T, tb::True, S> {
607                 self.tagged_fields.push(TaggedField::MinFinalCltvExpiry(MinFinalCltvExpiry(min_final_cltv_expiry)));
608                 self.set_flags()
609         }
610 }
611
612 impl<D: tb::Bool, H: tb::Bool, T: tb::Bool, C: tb::Bool> InvoiceBuilder<D, H, T, C, tb::False> {
613         /// Sets the payment secret and relevant features.
614         pub fn payment_secret(mut self, payment_secret: PaymentSecret) -> InvoiceBuilder<D, H, T, C, tb::True> {
615                 let features = InvoiceFeatures::empty()
616                         .set_variable_length_onion_required()
617                         .set_payment_secret_required();
618                 self.tagged_fields.push(TaggedField::PaymentSecret(payment_secret));
619                 self.tagged_fields.push(TaggedField::Features(features));
620                 self.set_flags()
621         }
622 }
623
624 impl<D: tb::Bool, H: tb::Bool, T: tb::Bool, C: tb::Bool> InvoiceBuilder<D, H, T, C, tb::True> {
625         /// Sets the `basic_mpp` feature as optional.
626         pub fn basic_mpp(mut self) -> Self {
627                 self.tagged_fields = self.tagged_fields
628                         .drain(..)
629                         .map(|field| match field {
630                                 TaggedField::Features(f) => TaggedField::Features(f.set_basic_mpp_optional()),
631                                 _ => field,
632                         })
633                         .collect();
634                 self
635         }
636 }
637
638 impl InvoiceBuilder<tb::True, tb::True, tb::True, tb::True, tb::True> {
639         /// Builds and signs an invoice using the supplied `sign_function`. This function MAY NOT fail
640         /// and MUST produce a recoverable signature valid for the given hash and if applicable also for
641         /// the included payee public key.
642         pub fn build_signed<F>(self, sign_function: F) -> Result<Invoice, CreationError>
643                 where F: FnOnce(&Message) -> RecoverableSignature
644         {
645                 let invoice = self.try_build_signed::<_, ()>(|hash| {
646                         Ok(sign_function(hash))
647                 });
648
649                 match invoice {
650                         Ok(i) => Ok(i),
651                         Err(SignOrCreationError::CreationError(e)) => Err(e),
652                         Err(SignOrCreationError::SignError(())) => unreachable!(),
653                 }
654         }
655
656         /// Builds and signs an invoice using the supplied `sign_function`. This function MAY fail with
657         /// an error of type `E` and MUST produce a recoverable signature valid for the given hash and
658         /// if applicable also for the included payee public key.
659         pub fn try_build_signed<F, E>(self, sign_function: F) -> Result<Invoice, SignOrCreationError<E>>
660                 where F: FnOnce(&Message) -> Result<RecoverableSignature, E>
661         {
662                 let raw = match self.build_raw() {
663                         Ok(r) => r,
664                         Err(e) => return Err(SignOrCreationError::CreationError(e)),
665                 };
666
667                 let signed = match raw.sign(sign_function) {
668                         Ok(s) => s,
669                         Err(e) => return Err(SignOrCreationError::SignError(e)),
670                 };
671
672                 let invoice = Invoice {
673                         signed_invoice: signed,
674                 };
675
676                 invoice.check_field_counts().expect("should be ensured by type signature of builder");
677                 invoice.check_feature_bits().expect("should be ensured by type signature of builder");
678                 invoice.check_amount().expect("should be ensured by type signature of builder");
679
680                 Ok(invoice)
681         }
682 }
683
684
685 impl SignedRawInvoice {
686         /// Disassembles the `SignedRawInvoice` into its three parts:
687         ///  1. raw invoice
688         ///  2. hash of the raw invoice
689         ///  3. signature
690         pub fn into_parts(self) -> (RawInvoice, [u8; 32], InvoiceSignature) {
691                 (self.raw_invoice, self.hash, self.signature)
692         }
693
694         /// The `RawInvoice` which was signed.
695         pub fn raw_invoice(&self) -> &RawInvoice {
696                 &self.raw_invoice
697         }
698
699         /// The hash of the `RawInvoice` that was signed.
700         pub fn hash(&self) -> &[u8; 32] {
701                 &self.hash
702         }
703
704         /// InvoiceSignature for the invoice.
705         pub fn signature(&self) -> &InvoiceSignature {
706                 &self.signature
707         }
708
709         /// Recovers the public key used for signing the invoice from the recoverable signature.
710         pub fn recover_payee_pub_key(&self) -> Result<PayeePubKey, secp256k1::Error> {
711                 let hash = Message::from_slice(&self.hash[..])
712                         .expect("Hash is 32 bytes long, same as MESSAGE_SIZE");
713
714                 Ok(PayeePubKey(Secp256k1::new().recover(
715                         &hash,
716                         &self.signature
717                 )?))
718         }
719
720         /// Checks if the signature is valid for the included payee public key or if none exists if it's
721         /// valid for the recovered signature (which should always be true?).
722         pub fn check_signature(&self) -> bool {
723                 let included_pub_key = self.raw_invoice.payee_pub_key();
724
725                 let mut recovered_pub_key = Option::None;
726                 if recovered_pub_key.is_none() {
727                         let recovered = match self.recover_payee_pub_key() {
728                                 Ok(pk) => pk,
729                                 Err(_) => return false,
730                         };
731                         recovered_pub_key = Some(recovered);
732                 }
733
734                 let pub_key = included_pub_key.or_else(|| recovered_pub_key.as_ref())
735                         .expect("One is always present");
736
737                 let hash = Message::from_slice(&self.hash[..])
738                         .expect("Hash is 32 bytes long, same as MESSAGE_SIZE");
739
740                 let secp_context = Secp256k1::new();
741                 let verification_result = secp_context.verify(
742                         &hash,
743                         &self.signature.to_standard(),
744                         pub_key
745                 );
746
747                 match verification_result {
748                         Ok(()) => true,
749                         Err(_) => false,
750                 }
751         }
752 }
753
754 /// Finds the first element of an enum stream of a given variant and extracts one member of the
755 /// variant. If no element was found `None` gets returned.
756 ///
757 /// The following example would extract the first B.
758 /// ```
759 /// use Enum::*
760 ///
761 /// enum Enum {
762 ///     A(u8),
763 ///     B(u16)
764 /// }
765 ///
766 /// let elements = vec![A(1), A(2), B(3), A(4)]
767 ///
768 /// assert_eq!(find_extract!(elements.iter(), Enum::B(ref x), x), Some(3u16))
769 /// ```
770 macro_rules! find_extract {
771         ($iter:expr, $enm:pat, $enm_var:ident) => {
772                 find_all_extract!($iter, $enm, $enm_var).next()
773         };
774 }
775
776 /// Finds the all elements of an enum stream of a given variant and extracts one member of the
777 /// variant through an iterator.
778 ///
779 /// The following example would extract all A.
780 /// ```
781 /// use Enum::*
782 ///
783 /// enum Enum {
784 ///     A(u8),
785 ///     B(u16)
786 /// }
787 ///
788 /// let elements = vec![A(1), A(2), B(3), A(4)]
789 ///
790 /// assert_eq!(
791 ///     find_all_extract!(elements.iter(), Enum::A(ref x), x).collect::<Vec<u8>>(),
792 ///     vec![1u8, 2u8, 4u8])
793 /// ```
794 macro_rules! find_all_extract {
795         ($iter:expr, $enm:pat, $enm_var:ident) => {
796                 $iter.filter_map(|tf| match *tf {
797                         $enm => Some($enm_var),
798                         _ => None,
799                 })
800         };
801 }
802
803 #[allow(missing_docs)]
804 impl RawInvoice {
805         /// Hash the HRP as bytes and signatureless data part.
806         fn hash_from_parts(hrp_bytes: &[u8], data_without_signature: &[u5]) -> [u8; 32] {
807                 let preimage = construct_invoice_preimage(hrp_bytes, data_without_signature);
808                 let mut hash: [u8; 32] = Default::default();
809                 hash.copy_from_slice(&sha256::Hash::hash(&preimage)[..]);
810                 hash
811         }
812
813         /// Calculate the hash of the encoded `RawInvoice`
814         pub fn hash(&self) -> [u8; 32] {
815                 use bech32::ToBase32;
816
817                 RawInvoice::hash_from_parts(
818                         self.hrp.to_string().as_bytes(),
819                         &self.data.to_base32()
820                 )
821         }
822
823         /// Signs the invoice using the supplied `sign_function`. This function MAY fail with an error
824         /// of type `E`. Since the signature of a `SignedRawInvoice` is not required to be valid there
825         /// are no constraints regarding the validity of the produced signature.
826         ///
827         /// (C-not exported) As we don't currently support passing function pointers into methods
828         /// explicitly.
829         pub fn sign<F, E>(self, sign_method: F) -> Result<SignedRawInvoice, E>
830                 where F: FnOnce(&Message) -> Result<RecoverableSignature, E>
831         {
832                 let raw_hash = self.hash();
833                 let hash = Message::from_slice(&raw_hash[..])
834                         .expect("Hash is 32 bytes long, same as MESSAGE_SIZE");
835                 let signature = sign_method(&hash)?;
836
837                 Ok(SignedRawInvoice {
838                         raw_invoice: self,
839                         hash: raw_hash,
840                         signature: InvoiceSignature(signature),
841                 })
842         }
843
844         /// Returns an iterator over all tagged fields with known semantics.
845         ///
846         /// (C-not exported) As there is not yet a manual mapping for a FilterMap
847         pub fn known_tagged_fields(&self)
848                 -> FilterMap<Iter<RawTaggedField>, fn(&RawTaggedField) -> Option<&TaggedField>>
849         {
850                 // For 1.14.0 compatibility: closures' types can't be written an fn()->() in the
851                 // function's type signature.
852                 // TODO: refactor once impl Trait is available
853                 fn match_raw(raw: &RawTaggedField) -> Option<&TaggedField> {
854                         match *raw {
855                                 RawTaggedField::KnownSemantics(ref tf) => Some(tf),
856                                 _ => None,
857                         }
858                 }
859
860                 self.data.tagged_fields.iter().filter_map(match_raw )
861         }
862
863         pub fn payment_hash(&self) -> Option<&Sha256> {
864                 find_extract!(self.known_tagged_fields(), TaggedField::PaymentHash(ref x), x)
865         }
866
867         pub fn description(&self) -> Option<&Description> {
868                 find_extract!(self.known_tagged_fields(), TaggedField::Description(ref x), x)
869         }
870
871         pub fn payee_pub_key(&self) -> Option<&PayeePubKey> {
872                 find_extract!(self.known_tagged_fields(), TaggedField::PayeePubKey(ref x), x)
873         }
874
875         pub fn description_hash(&self) -> Option<&Sha256> {
876                 find_extract!(self.known_tagged_fields(), TaggedField::DescriptionHash(ref x), x)
877         }
878
879         pub fn expiry_time(&self) -> Option<&ExpiryTime> {
880                 find_extract!(self.known_tagged_fields(), TaggedField::ExpiryTime(ref x), x)
881         }
882
883         pub fn min_final_cltv_expiry(&self) -> Option<&MinFinalCltvExpiry> {
884                 find_extract!(self.known_tagged_fields(), TaggedField::MinFinalCltvExpiry(ref x), x)
885         }
886
887         pub fn payment_secret(&self) -> Option<&PaymentSecret> {
888                 find_extract!(self.known_tagged_fields(), TaggedField::PaymentSecret(ref x), x)
889         }
890
891         pub fn payment_metadata(&self) -> Option<&Vec<u8>> {
892                 find_extract!(self.known_tagged_fields(), TaggedField::PaymentMetadata(ref x), x)
893         }
894
895         pub fn features(&self) -> Option<&InvoiceFeatures> {
896                 find_extract!(self.known_tagged_fields(), TaggedField::Features(ref x), x)
897         }
898
899         /// (C-not exported) as we don't support Vec<&NonOpaqueType>
900         pub fn fallbacks(&self) -> Vec<&Fallback> {
901                 find_all_extract!(self.known_tagged_fields(), TaggedField::Fallback(ref x), x).collect()
902         }
903
904         pub fn private_routes(&self) -> Vec<&PrivateRoute> {
905                 find_all_extract!(self.known_tagged_fields(), TaggedField::PrivateRoute(ref x), x).collect()
906         }
907
908         pub fn amount_pico_btc(&self) -> Option<u64> {
909                 self.hrp.raw_amount.map(|v| {
910                         v * self.hrp.si_prefix.as_ref().map_or(1_000_000_000_000, |si| { si.multiplier() })
911                 })
912         }
913
914         pub fn currency(&self) -> Currency {
915                 self.hrp.currency.clone()
916         }
917 }
918
919 impl PositiveTimestamp {
920         /// Creates a `PositiveTimestamp` from a Unix timestamp in the range `0..=MAX_TIMESTAMP`.
921         ///
922         /// Otherwise, returns a [`CreationError::TimestampOutOfBounds`].
923         pub fn from_unix_timestamp(unix_seconds: u64) -> Result<Self, CreationError> {
924                 Self::from_duration_since_epoch(Duration::from_secs(unix_seconds))
925         }
926
927         /// Creates a `PositiveTimestamp` from a [`SystemTime`] with a corresponding Unix timestamp in
928         /// the range `0..=MAX_TIMESTAMP`.
929         ///
930         /// Otherwise, returns a [`CreationError::TimestampOutOfBounds`].
931         #[cfg(feature = "std")]
932         pub fn from_system_time(time: SystemTime) -> Result<Self, CreationError> {
933                 time.duration_since(SystemTime::UNIX_EPOCH)
934                         .map(Self::from_duration_since_epoch)
935                         .unwrap_or(Err(CreationError::TimestampOutOfBounds))
936         }
937
938         /// Creates a `PositiveTimestamp` from a [`Duration`] since the Unix epoch in the range
939         /// `0..=MAX_TIMESTAMP`.
940         ///
941         /// Otherwise, returns a [`CreationError::TimestampOutOfBounds`].
942         pub fn from_duration_since_epoch(duration: Duration) -> Result<Self, CreationError> {
943                 if duration.as_secs() <= MAX_TIMESTAMP {
944                         Ok(PositiveTimestamp(duration))
945                 } else {
946                         Err(CreationError::TimestampOutOfBounds)
947                 }
948         }
949
950         /// Returns the Unix timestamp representing the stored time
951         pub fn as_unix_timestamp(&self) -> u64 {
952                 self.0.as_secs()
953         }
954
955         /// Returns the duration of the stored time since the Unix epoch
956         pub fn as_duration_since_epoch(&self) -> Duration {
957                 self.0
958         }
959
960         /// Returns the [`SystemTime`] representing the stored time
961         #[cfg(feature = "std")]
962         pub fn as_time(&self) -> SystemTime {
963                 SystemTime::UNIX_EPOCH + self.0
964         }
965 }
966
967 #[cfg(feature = "std")]
968 impl Into<SystemTime> for PositiveTimestamp {
969         fn into(self) -> SystemTime {
970                 SystemTime::UNIX_EPOCH + self.0
971         }
972 }
973
974 impl Invoice {
975         /// Transform the `Invoice` into it's unchecked version
976         pub fn into_signed_raw(self) -> SignedRawInvoice {
977                 self.signed_invoice
978         }
979
980         /// Check that all mandatory fields are present
981         fn check_field_counts(&self) -> Result<(), SemanticError> {
982                 // "A writer MUST include exactly one p field […]."
983                 let payment_hash_cnt = self.tagged_fields().filter(|&tf| match *tf {
984                         TaggedField::PaymentHash(_) => true,
985                         _ => false,
986                 }).count();
987                 if payment_hash_cnt < 1 {
988                         return Err(SemanticError::NoPaymentHash);
989                 } else if payment_hash_cnt > 1 {
990                         return Err(SemanticError::MultiplePaymentHashes);
991                 }
992
993                 // "A writer MUST include either exactly one d or exactly one h field."
994                 let description_cnt = self.tagged_fields().filter(|&tf| match *tf {
995                         TaggedField::Description(_) | TaggedField::DescriptionHash(_) => true,
996                         _ => false,
997                 }).count();
998                 if  description_cnt < 1 {
999                         return Err(SemanticError::NoDescription);
1000                 } else if description_cnt > 1 {
1001                         return  Err(SemanticError::MultipleDescriptions);
1002                 }
1003
1004                 self.check_payment_secret()?;
1005
1006                 Ok(())
1007         }
1008
1009         /// Checks that there is exactly one payment secret field
1010         fn check_payment_secret(&self) -> Result<(), SemanticError> {
1011                 // "A writer MUST include exactly one `s` field."
1012                 let payment_secret_count = self.tagged_fields().filter(|&tf| match *tf {
1013                         TaggedField::PaymentSecret(_) => true,
1014                         _ => false,
1015                 }).count();
1016                 if payment_secret_count < 1 {
1017                         return Err(SemanticError::NoPaymentSecret);
1018                 } else if payment_secret_count > 1 {
1019                         return Err(SemanticError::MultiplePaymentSecrets);
1020                 }
1021
1022                 Ok(())
1023         }
1024
1025         /// Check that amount is a whole number of millisatoshis
1026         fn check_amount(&self) -> Result<(), SemanticError> {
1027                 if let Some(amount_pico_btc) = self.amount_pico_btc() {
1028                         if amount_pico_btc % 10 != 0 {
1029                                 return Err(SemanticError::ImpreciseAmount);
1030                         }
1031                 }
1032                 Ok(())
1033         }
1034
1035         /// Check that feature bits are set as required
1036         fn check_feature_bits(&self) -> Result<(), SemanticError> {
1037                 self.check_payment_secret()?;
1038
1039                 // "A writer MUST set an s field if and only if the payment_secret feature is set."
1040                 // (this requirement has been since removed, and we now require the payment secret
1041                 // feature bit always).
1042                 let features = self.tagged_fields().find(|&tf| match *tf {
1043                         TaggedField::Features(_) => true,
1044                         _ => false,
1045                 });
1046                 match features {
1047                         None => Err(SemanticError::InvalidFeatures),
1048                         Some(TaggedField::Features(features)) => {
1049                                 if features.requires_unknown_bits() {
1050                                         Err(SemanticError::InvalidFeatures)
1051                                 } else if !features.supports_payment_secret() {
1052                                         Err(SemanticError::InvalidFeatures)
1053                                 } else {
1054                                         Ok(())
1055                                 }
1056                         },
1057                         Some(_) => unreachable!(),
1058                 }
1059         }
1060
1061         /// Check that the invoice is signed correctly and that key recovery works
1062         pub fn check_signature(&self) -> Result<(), SemanticError> {
1063                 match self.signed_invoice.recover_payee_pub_key() {
1064                         Err(secp256k1::Error::InvalidRecoveryId) =>
1065                                 return Err(SemanticError::InvalidRecoveryId),
1066                         Err(secp256k1::Error::InvalidSignature) =>
1067                                 return Err(SemanticError::InvalidSignature),
1068                         Err(e) => panic!("no other error may occur, got {:?}", e),
1069                         Ok(_) => {},
1070                 }
1071
1072                 if !self.signed_invoice.check_signature() {
1073                         return Err(SemanticError::InvalidSignature);
1074                 }
1075
1076                 Ok(())
1077         }
1078
1079         /// Constructs an `Invoice` from a `SignedRawInvoice` by checking all its invariants.
1080         /// ```
1081         /// use lightning_invoice::*;
1082         ///
1083         /// let invoice = "lnbc100p1psj9jhxdqud3jxktt5w46x7unfv9kz6mn0v3jsnp4q0d3p2sfluzdx45tqcs\
1084         /// h2pu5qc7lgq0xs578ngs6s0s68ua4h7cvspp5q6rmq35js88zp5dvwrv9m459tnk2zunwj5jalqtyxqulh0l\
1085         /// 5gflssp5nf55ny5gcrfl30xuhzj3nphgj27rstekmr9fw3ny5989s300gyus9qyysgqcqpcrzjqw2sxwe993\
1086         /// h5pcm4dxzpvttgza8zhkqxpgffcrf5v25nwpr3cmfg7z54kuqq8rgqqqqqqqq2qqqqq9qq9qrzjqd0ylaqcl\
1087         /// j9424x9m8h2vcukcgnm6s56xfgu3j78zyqzhgs4hlpzvznlugqq9vsqqqqqqqlgqqqqqeqq9qrzjqwldmj9d\
1088         /// ha74df76zhx6l9we0vjdquygcdt3kssupehe64g6yyp5yz5rhuqqwccqqyqqqqlgqqqqjcqq9qrzjqf9e58a\
1089         /// guqr0rcun0ajlvmzq3ek63cw2w282gv3z5uupmuwvgjtq2z55qsqqg6qqqyqqqrtnqqqzq3cqygrzjqvphms\
1090         /// ywntrrhqjcraumvc4y6r8v4z5v593trte429v4hredj7ms5z52usqq9ngqqqqqqqlgqqqqqqgq9qrzjq2v0v\
1091         /// p62g49p7569ev48cmulecsxe59lvaw3wlxm7r982zxa9zzj7z5l0cqqxusqqyqqqqlgqqqqqzsqygarl9fh3\
1092         /// 8s0gyuxjjgux34w75dnc6xp2l35j7es3jd4ugt3lu0xzre26yg5m7ke54n2d5sym4xcmxtl8238xxvw5h5h5\
1093         /// j5r6drg6k6zcqj0fcwg";
1094         ///
1095         /// let signed = invoice.parse::<SignedRawInvoice>().unwrap();
1096         ///
1097         /// assert!(Invoice::from_signed(signed).is_ok());
1098         /// ```
1099         pub fn from_signed(signed_invoice: SignedRawInvoice) -> Result<Self, SemanticError> {
1100                 let invoice = Invoice {
1101                         signed_invoice: signed_invoice,
1102                 };
1103                 invoice.check_field_counts()?;
1104                 invoice.check_feature_bits()?;
1105                 invoice.check_signature()?;
1106                 invoice.check_amount()?;
1107
1108                 Ok(invoice)
1109         }
1110
1111         /// Returns the `Invoice`'s timestamp (should equal its creation time)
1112         #[cfg(feature = "std")]
1113         pub fn timestamp(&self) -> SystemTime {
1114                 self.signed_invoice.raw_invoice().data.timestamp.as_time()
1115         }
1116
1117         /// Returns the `Invoice`'s timestamp as a duration since the Unix epoch
1118         pub fn duration_since_epoch(&self) -> Duration {
1119                 self.signed_invoice.raw_invoice().data.timestamp.0
1120         }
1121
1122         /// Returns an iterator over all tagged fields of this Invoice.
1123         ///
1124         /// (C-not exported) As there is not yet a manual mapping for a FilterMap
1125         pub fn tagged_fields(&self)
1126                 -> FilterMap<Iter<RawTaggedField>, fn(&RawTaggedField) -> Option<&TaggedField>> {
1127                 self.signed_invoice.raw_invoice().known_tagged_fields()
1128         }
1129
1130         /// Returns the hash to which we will receive the preimage on completion of the payment
1131         pub fn payment_hash(&self) -> &sha256::Hash {
1132                 &self.signed_invoice.payment_hash().expect("checked by constructor").0
1133         }
1134
1135         /// Return the description or a hash of it for longer ones
1136         ///
1137         /// (C-not exported) because we don't yet export InvoiceDescription
1138         pub fn description(&self) -> InvoiceDescription {
1139                 if let Some(ref direct) = self.signed_invoice.description() {
1140                         return InvoiceDescription::Direct(direct);
1141                 } else if let Some(ref hash) = self.signed_invoice.description_hash() {
1142                         return InvoiceDescription::Hash(hash);
1143                 }
1144                 unreachable!("ensured by constructor");
1145         }
1146
1147         /// Get the payee's public key if one was included in the invoice
1148         pub fn payee_pub_key(&self) -> Option<&PublicKey> {
1149                 self.signed_invoice.payee_pub_key().map(|x| &x.0)
1150         }
1151
1152         /// Get the payment secret if one was included in the invoice
1153         pub fn payment_secret(&self) -> &PaymentSecret {
1154                 self.signed_invoice.payment_secret().expect("was checked by constructor")
1155         }
1156
1157         /// Get the payment metadata blob if one was included in the invoice
1158         pub fn payment_metadata(&self) -> Option<&Vec<u8>> {
1159                 self.signed_invoice.payment_metadata()
1160         }
1161
1162         /// Get the invoice features if they were included in the invoice
1163         pub fn features(&self) -> Option<&InvoiceFeatures> {
1164                 self.signed_invoice.features()
1165         }
1166
1167         /// Recover the payee's public key (only to be used if none was included in the invoice)
1168         pub fn recover_payee_pub_key(&self) -> PublicKey {
1169                 self.signed_invoice.recover_payee_pub_key().expect("was checked by constructor").0
1170         }
1171
1172         /// Returns the invoice's expiry time, if present, otherwise [`DEFAULT_EXPIRY_TIME`].
1173         pub fn expiry_time(&self) -> Duration {
1174                 self.signed_invoice.expiry_time()
1175                         .map(|x| x.0)
1176                         .unwrap_or(Duration::from_secs(DEFAULT_EXPIRY_TIME))
1177         }
1178
1179         /// Returns whether the invoice has expired.
1180         #[cfg(feature = "std")]
1181         pub fn is_expired(&self) -> bool {
1182                 Self::is_expired_from_epoch(&self.timestamp(), self.expiry_time())
1183         }
1184
1185         /// Returns whether the expiry time from the given epoch has passed.
1186         #[cfg(feature = "std")]
1187         pub(crate) fn is_expired_from_epoch(epoch: &SystemTime, expiry_time: Duration) -> bool {
1188                 match epoch.elapsed() {
1189                         Ok(elapsed) => elapsed > expiry_time,
1190                         Err(_) => false,
1191                 }
1192         }
1193
1194         /// Returns whether the expiry time would pass at the given point in time.
1195         /// `at_time` is the timestamp as a duration since the Unix epoch.
1196         pub fn would_expire(&self, at_time: Duration) -> bool {
1197                 self.duration_since_epoch()
1198                         .checked_add(self.expiry_time())
1199                         .unwrap_or_else(|| Duration::new(u64::max_value(), 1_000_000_000 - 1)) < at_time
1200         }
1201
1202         /// Returns the invoice's `min_final_cltv_expiry` time, if present, otherwise
1203         /// [`DEFAULT_MIN_FINAL_CLTV_EXPIRY`].
1204         pub fn min_final_cltv_expiry(&self) -> u64 {
1205                 self.signed_invoice.min_final_cltv_expiry()
1206                         .map(|x| x.0)
1207                         .unwrap_or(DEFAULT_MIN_FINAL_CLTV_EXPIRY)
1208         }
1209
1210         /// Returns a list of all fallback addresses
1211         ///
1212         /// (C-not exported) as we don't support Vec<&NonOpaqueType>
1213         pub fn fallbacks(&self) -> Vec<&Fallback> {
1214                 self.signed_invoice.fallbacks()
1215         }
1216
1217         /// Returns a list of all routes included in the invoice
1218         pub fn private_routes(&self) -> Vec<&PrivateRoute> {
1219                 self.signed_invoice.private_routes()
1220         }
1221
1222         /// Returns a list of all routes included in the invoice as the underlying hints
1223         pub fn route_hints(&self) -> Vec<RouteHint> {
1224                 find_all_extract!(
1225                         self.signed_invoice.known_tagged_fields(), TaggedField::PrivateRoute(ref x), x
1226                 ).map(|route| (**route).clone()).collect()
1227         }
1228
1229         /// Returns the currency for which the invoice was issued
1230         pub fn currency(&self) -> Currency {
1231                 self.signed_invoice.currency()
1232         }
1233
1234         /// Returns the amount if specified in the invoice as millisatoshis.
1235         pub fn amount_milli_satoshis(&self) -> Option<u64> {
1236                 self.signed_invoice.amount_pico_btc().map(|v| v / 10)
1237         }
1238
1239         /// Returns the amount if specified in the invoice as pico <currency>.
1240         fn amount_pico_btc(&self) -> Option<u64> {
1241                 self.signed_invoice.amount_pico_btc()
1242         }
1243 }
1244
1245 impl From<TaggedField> for RawTaggedField {
1246         fn from(tf: TaggedField) -> Self {
1247                 RawTaggedField::KnownSemantics(tf)
1248         }
1249 }
1250
1251 impl TaggedField {
1252         /// Numeric representation of the field's tag
1253         pub fn tag(&self) -> u5 {
1254                 let tag = match *self {
1255                         TaggedField::PaymentHash(_) => constants::TAG_PAYMENT_HASH,
1256                         TaggedField::Description(_) => constants::TAG_DESCRIPTION,
1257                         TaggedField::PayeePubKey(_) => constants::TAG_PAYEE_PUB_KEY,
1258                         TaggedField::DescriptionHash(_) => constants::TAG_DESCRIPTION_HASH,
1259                         TaggedField::ExpiryTime(_) => constants::TAG_EXPIRY_TIME,
1260                         TaggedField::MinFinalCltvExpiry(_) => constants::TAG_MIN_FINAL_CLTV_EXPIRY,
1261                         TaggedField::Fallback(_) => constants::TAG_FALLBACK,
1262                         TaggedField::PrivateRoute(_) => constants::TAG_PRIVATE_ROUTE,
1263                         TaggedField::PaymentSecret(_) => constants::TAG_PAYMENT_SECRET,
1264                         TaggedField::PaymentMetadata(_) => constants::TAG_PAYMENT_METADATA,
1265                         TaggedField::Features(_) => constants::TAG_FEATURES,
1266                 };
1267
1268                 u5::try_from_u8(tag).expect("all tags defined are <32")
1269         }
1270 }
1271
1272 impl Description {
1273
1274         /// Creates a new `Description` if `description` is at most 1023 __bytes__ long,
1275         /// returns `CreationError::DescriptionTooLong` otherwise
1276         ///
1277         /// Please note that single characters may use more than one byte due to UTF8 encoding.
1278         pub fn new(description: String) -> Result<Description, CreationError> {
1279                 if description.len() > 639 {
1280                         Err(CreationError::DescriptionTooLong)
1281                 } else {
1282                         Ok(Description(description))
1283                 }
1284         }
1285
1286         /// Returns the underlying description `String`
1287         pub fn into_inner(self) -> String {
1288                 self.0
1289         }
1290 }
1291
1292 impl Into<String> for Description {
1293         fn into(self) -> String {
1294                 self.into_inner()
1295         }
1296 }
1297
1298 impl Deref for Description {
1299         type Target = str;
1300
1301         fn deref(&self) -> &str {
1302                 &self.0
1303         }
1304 }
1305
1306 impl From<PublicKey> for PayeePubKey {
1307         fn from(pk: PublicKey) -> Self {
1308                 PayeePubKey(pk)
1309         }
1310 }
1311
1312 impl Deref for PayeePubKey {
1313         type Target = PublicKey;
1314
1315         fn deref(&self) -> &PublicKey {
1316                 &self.0
1317         }
1318 }
1319
1320 impl ExpiryTime {
1321         /// Construct an `ExpiryTime` from seconds.
1322         pub fn from_seconds(seconds: u64) -> ExpiryTime {
1323                 ExpiryTime(Duration::from_secs(seconds))
1324         }
1325
1326         /// Construct an `ExpiryTime` from a `Duration`.
1327         pub fn from_duration(duration: Duration) -> ExpiryTime {
1328                 ExpiryTime(duration)
1329         }
1330
1331         /// Returns the expiry time in seconds
1332         pub fn as_seconds(&self) -> u64 {
1333                 self.0.as_secs()
1334         }
1335
1336         /// Returns a reference to the underlying `Duration` (=expiry time)
1337         pub fn as_duration(&self) -> &Duration {
1338                 &self.0
1339         }
1340 }
1341
1342 impl PrivateRoute {
1343         /// Creates a new (partial) route from a list of hops
1344         pub fn new(hops: RouteHint) -> Result<PrivateRoute, CreationError> {
1345                 if hops.0.len() <= 12 {
1346                         Ok(PrivateRoute(hops))
1347                 } else {
1348                         Err(CreationError::RouteTooLong)
1349                 }
1350         }
1351
1352         /// Returns the underlying list of hops
1353         pub fn into_inner(self) -> RouteHint {
1354                 self.0
1355         }
1356 }
1357
1358 impl Into<RouteHint> for PrivateRoute {
1359         fn into(self) -> RouteHint {
1360                 self.into_inner()
1361         }
1362 }
1363
1364 impl Deref for PrivateRoute {
1365         type Target = RouteHint;
1366
1367         fn deref(&self) -> &RouteHint {
1368                 &self.0
1369         }
1370 }
1371
1372 impl Deref for InvoiceSignature {
1373         type Target = RecoverableSignature;
1374
1375         fn deref(&self) -> &RecoverableSignature {
1376                 &self.0
1377         }
1378 }
1379
1380 impl Deref for SignedRawInvoice {
1381         type Target = RawInvoice;
1382
1383         fn deref(&self) -> &RawInvoice {
1384                 &self.raw_invoice
1385         }
1386 }
1387
1388 /// Errors that may occur when constructing a new `RawInvoice` or `Invoice`
1389 #[derive(Eq, PartialEq, Debug, Clone)]
1390 pub enum CreationError {
1391         /// The supplied description string was longer than 639 __bytes__ (see [`Description::new(…)`](./struct.Description.html#method.new))
1392         DescriptionTooLong,
1393
1394         /// The specified route has too many hops and can't be encoded
1395         RouteTooLong,
1396
1397         /// The Unix timestamp of the supplied date is less than zero or greater than 35-bits
1398         TimestampOutOfBounds,
1399
1400         /// The supplied millisatoshi amount was greater than the total bitcoin supply.
1401         InvalidAmount,
1402 }
1403
1404 impl Display for CreationError {
1405         fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1406                 match self {
1407                         CreationError::DescriptionTooLong => f.write_str("The supplied description string was longer than 639 bytes"),
1408                         CreationError::RouteTooLong => f.write_str("The specified route has too many hops and can't be encoded"),
1409                         CreationError::TimestampOutOfBounds => f.write_str("The Unix timestamp of the supplied date is less than zero or greater than 35-bits"),
1410                         CreationError::InvalidAmount => f.write_str("The supplied millisatoshi amount was greater than the total bitcoin supply"),
1411                 }
1412         }
1413 }
1414
1415 #[cfg(feature = "std")]
1416 impl std::error::Error for CreationError { }
1417
1418 /// Errors that may occur when converting a `RawInvoice` to an `Invoice`. They relate to the
1419 /// requirements sections in BOLT #11
1420 #[derive(Eq, PartialEq, Debug, Clone)]
1421 pub enum SemanticError {
1422         /// The invoice is missing the mandatory payment hash
1423         NoPaymentHash,
1424
1425         /// The invoice has multiple payment hashes which isn't allowed
1426         MultiplePaymentHashes,
1427
1428         /// No description or description hash are part of the invoice
1429         NoDescription,
1430
1431         /// The invoice contains multiple descriptions and/or description hashes which isn't allowed
1432         MultipleDescriptions,
1433
1434         /// The invoice is missing the mandatory payment secret, which all modern lightning nodes
1435         /// should provide.
1436         NoPaymentSecret,
1437
1438         /// The invoice contains multiple payment secrets
1439         MultiplePaymentSecrets,
1440
1441         /// The invoice's features are invalid
1442         InvalidFeatures,
1443
1444         /// The recovery id doesn't fit the signature/pub key
1445         InvalidRecoveryId,
1446
1447         /// The invoice's signature is invalid
1448         InvalidSignature,
1449
1450         /// The invoice's amount was not a whole number of millisatoshis
1451         ImpreciseAmount,
1452 }
1453
1454 impl Display for SemanticError {
1455         fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1456                 match self {
1457                         SemanticError::NoPaymentHash => f.write_str("The invoice is missing the mandatory payment hash"),
1458                         SemanticError::MultiplePaymentHashes => f.write_str("The invoice has multiple payment hashes which isn't allowed"),
1459                         SemanticError::NoDescription => f.write_str("No description or description hash are part of the invoice"),
1460                         SemanticError::MultipleDescriptions => f.write_str("The invoice contains multiple descriptions and/or description hashes which isn't allowed"),
1461                         SemanticError::NoPaymentSecret => f.write_str("The invoice is missing the mandatory payment secret"),
1462                         SemanticError::MultiplePaymentSecrets => f.write_str("The invoice contains multiple payment secrets"),
1463                         SemanticError::InvalidFeatures => f.write_str("The invoice's features are invalid"),
1464                         SemanticError::InvalidRecoveryId => f.write_str("The recovery id doesn't fit the signature/pub key"),
1465                         SemanticError::InvalidSignature => f.write_str("The invoice's signature is invalid"),
1466                         SemanticError::ImpreciseAmount => f.write_str("The invoice's amount was not a whole number of millisatoshis"),
1467                 }
1468         }
1469 }
1470
1471 #[cfg(feature = "std")]
1472 impl std::error::Error for SemanticError { }
1473
1474 /// When signing using a fallible method either an user-supplied `SignError` or a `CreationError`
1475 /// may occur.
1476 #[derive(Eq, PartialEq, Debug, Clone)]
1477 pub enum SignOrCreationError<S = ()> {
1478         /// An error occurred during signing
1479         SignError(S),
1480
1481         /// An error occurred while building the transaction
1482         CreationError(CreationError),
1483 }
1484
1485 impl<S> Display for SignOrCreationError<S> {
1486         fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1487                 match self {
1488                         SignOrCreationError::SignError(_) => f.write_str("An error occurred during signing"),
1489                         SignOrCreationError::CreationError(err) => err.fmt(f),
1490                 }
1491         }
1492 }
1493
1494 #[cfg(test)]
1495 mod test {
1496         use bitcoin_hashes::hex::FromHex;
1497         use bitcoin_hashes::sha256;
1498
1499         #[test]
1500         fn test_system_time_bounds_assumptions() {
1501                 assert_eq!(
1502                         ::PositiveTimestamp::from_unix_timestamp(::MAX_TIMESTAMP + 1),
1503                         Err(::CreationError::TimestampOutOfBounds)
1504                 );
1505         }
1506
1507         #[test]
1508         fn test_calc_invoice_hash() {
1509                 use ::{RawInvoice, RawHrp, RawDataPart, Currency, PositiveTimestamp};
1510                 use ::TaggedField::*;
1511
1512                 let invoice = RawInvoice {
1513                         hrp: RawHrp {
1514                                 currency: Currency::Bitcoin,
1515                                 raw_amount: None,
1516                                 si_prefix: None,
1517                         },
1518                         data: RawDataPart {
1519                                 timestamp: PositiveTimestamp::from_unix_timestamp(1496314658).unwrap(),
1520                                 tagged_fields: vec![
1521                                         PaymentHash(::Sha256(sha256::Hash::from_hex(
1522                                                 "0001020304050607080900010203040506070809000102030405060708090102"
1523                                         ).unwrap())).into(),
1524                                         Description(::Description::new(
1525                                                 "Please consider supporting this project".to_owned()
1526                                         ).unwrap()).into(),
1527                                 ],
1528                         },
1529                 };
1530
1531                 let expected_hash = [
1532                         0xc3, 0xd4, 0xe8, 0x3f, 0x64, 0x6f, 0xa7, 0x9a, 0x39, 0x3d, 0x75, 0x27, 0x7b, 0x1d,
1533                         0x85, 0x8d, 0xb1, 0xd1, 0xf7, 0xab, 0x71, 0x37, 0xdc, 0xb7, 0x83, 0x5d, 0xb2, 0xec,
1534                         0xd5, 0x18, 0xe1, 0xc9
1535                 ];
1536
1537                 assert_eq!(invoice.hash(), expected_hash)
1538         }
1539
1540         #[test]
1541         fn test_check_signature() {
1542                 use TaggedField::*;
1543                 use secp256k1::Secp256k1;
1544                 use secp256k1::recovery::{RecoveryId, RecoverableSignature};
1545                 use secp256k1::key::{SecretKey, PublicKey};
1546                 use {SignedRawInvoice, InvoiceSignature, RawInvoice, RawHrp, RawDataPart, Currency, Sha256,
1547                          PositiveTimestamp};
1548
1549                 let invoice = SignedRawInvoice {
1550                         raw_invoice: RawInvoice {
1551                                 hrp: RawHrp {
1552                                         currency: Currency::Bitcoin,
1553                                         raw_amount: None,
1554                                         si_prefix: None,
1555                                 },
1556                                 data: RawDataPart {
1557                                         timestamp: PositiveTimestamp::from_unix_timestamp(1496314658).unwrap(),
1558                                         tagged_fields: vec ! [
1559                                                 PaymentHash(Sha256(sha256::Hash::from_hex(
1560                                                         "0001020304050607080900010203040506070809000102030405060708090102"
1561                                                 ).unwrap())).into(),
1562                                                 Description(
1563                                                         ::Description::new(
1564                                                                 "Please consider supporting this project".to_owned()
1565                                                         ).unwrap()
1566                                                 ).into(),
1567                                         ],
1568                                 },
1569                         },
1570                         hash: [
1571                                 0xc3, 0xd4, 0xe8, 0x3f, 0x64, 0x6f, 0xa7, 0x9a, 0x39, 0x3d, 0x75, 0x27,
1572                                 0x7b, 0x1d, 0x85, 0x8d, 0xb1, 0xd1, 0xf7, 0xab, 0x71, 0x37, 0xdc, 0xb7,
1573                                 0x83, 0x5d, 0xb2, 0xec, 0xd5, 0x18, 0xe1, 0xc9
1574                         ],
1575                         signature: InvoiceSignature(RecoverableSignature::from_compact(
1576                                 & [
1577                                         0x38u8, 0xec, 0x68, 0x91, 0x34, 0x5e, 0x20, 0x41, 0x45, 0xbe, 0x8a,
1578                                         0x3a, 0x99, 0xde, 0x38, 0xe9, 0x8a, 0x39, 0xd6, 0xa5, 0x69, 0x43,
1579                                         0x4e, 0x18, 0x45, 0xc8, 0xaf, 0x72, 0x05, 0xaf, 0xcf, 0xcc, 0x7f,
1580                                         0x42, 0x5f, 0xcd, 0x14, 0x63, 0xe9, 0x3c, 0x32, 0x88, 0x1e, 0xad,
1581                                         0x0d, 0x6e, 0x35, 0x6d, 0x46, 0x7e, 0xc8, 0xc0, 0x25, 0x53, 0xf9,
1582                                         0xaa, 0xb1, 0x5e, 0x57, 0x38, 0xb1, 0x1f, 0x12, 0x7f
1583                                 ],
1584                                 RecoveryId::from_i32(0).unwrap()
1585                         ).unwrap()),
1586                 };
1587
1588                 assert!(invoice.check_signature());
1589
1590                 let private_key = SecretKey::from_slice(
1591                         &[
1592                                 0xe1, 0x26, 0xf6, 0x8f, 0x7e, 0xaf, 0xcc, 0x8b, 0x74, 0xf5, 0x4d, 0x26, 0x9f, 0xe2,
1593                                 0x06, 0xbe, 0x71, 0x50, 0x00, 0xf9, 0x4d, 0xac, 0x06, 0x7d, 0x1c, 0x04, 0xa8, 0xca,
1594                                 0x3b, 0x2d, 0xb7, 0x34
1595                         ][..]
1596                 ).unwrap();
1597                 let public_key = PublicKey::from_secret_key(&Secp256k1::new(), &private_key);
1598
1599                 assert_eq!(invoice.recover_payee_pub_key(), Ok(::PayeePubKey(public_key)));
1600
1601                 let (raw_invoice, _, _) = invoice.into_parts();
1602                 let new_signed = raw_invoice.sign::<_, ()>(|hash| {
1603                         Ok(Secp256k1::new().sign_recoverable(hash, &private_key))
1604                 }).unwrap();
1605
1606                 assert!(new_signed.check_signature());
1607         }
1608
1609         #[test]
1610         fn test_check_feature_bits() {
1611                 use TaggedField::*;
1612                 use lightning::ln::features::InvoiceFeatures;
1613                 use secp256k1::Secp256k1;
1614                 use secp256k1::key::SecretKey;
1615                 use {RawInvoice, RawHrp, RawDataPart, Currency, Sha256, PositiveTimestamp, Invoice,
1616                          SemanticError};
1617
1618                 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
1619                 let payment_secret = lightning::ln::PaymentSecret([21; 32]);
1620                 let invoice_template = RawInvoice {
1621                         hrp: RawHrp {
1622                                 currency: Currency::Bitcoin,
1623                                 raw_amount: None,
1624                                 si_prefix: None,
1625                         },
1626                         data: RawDataPart {
1627                                 timestamp: PositiveTimestamp::from_unix_timestamp(1496314658).unwrap(),
1628                                 tagged_fields: vec ! [
1629                                         PaymentHash(Sha256(sha256::Hash::from_hex(
1630                                                 "0001020304050607080900010203040506070809000102030405060708090102"
1631                                         ).unwrap())).into(),
1632                                         Description(
1633                                                 ::Description::new(
1634                                                         "Please consider supporting this project".to_owned()
1635                                                 ).unwrap()
1636                                         ).into(),
1637                                 ],
1638                         },
1639                 };
1640
1641                 // Missing features
1642                 let invoice = {
1643                         let mut invoice = invoice_template.clone();
1644                         invoice.data.tagged_fields.push(PaymentSecret(payment_secret).into());
1645                         invoice.sign::<_, ()>(|hash| Ok(Secp256k1::new().sign_recoverable(hash, &private_key)))
1646                 }.unwrap();
1647                 assert_eq!(Invoice::from_signed(invoice), Err(SemanticError::InvalidFeatures));
1648
1649                 // Missing feature bits
1650                 let invoice = {
1651                         let mut invoice = invoice_template.clone();
1652                         invoice.data.tagged_fields.push(PaymentSecret(payment_secret).into());
1653                         invoice.data.tagged_fields.push(Features(InvoiceFeatures::empty()).into());
1654                         invoice.sign::<_, ()>(|hash| Ok(Secp256k1::new().sign_recoverable(hash, &private_key)))
1655                 }.unwrap();
1656                 assert_eq!(Invoice::from_signed(invoice), Err(SemanticError::InvalidFeatures));
1657
1658                 // Including payment secret and feature bits
1659                 let invoice = {
1660                         let mut invoice = invoice_template.clone();
1661                         invoice.data.tagged_fields.push(PaymentSecret(payment_secret).into());
1662                         invoice.data.tagged_fields.push(Features(InvoiceFeatures::known()).into());
1663                         invoice.sign::<_, ()>(|hash| Ok(Secp256k1::new().sign_recoverable(hash, &private_key)))
1664                 }.unwrap();
1665                 assert!(Invoice::from_signed(invoice).is_ok());
1666
1667                 // No payment secret or features
1668                 let invoice = {
1669                         let invoice = invoice_template.clone();
1670                         invoice.sign::<_, ()>(|hash| Ok(Secp256k1::new().sign_recoverable(hash, &private_key)))
1671                 }.unwrap();
1672                 assert_eq!(Invoice::from_signed(invoice), Err(SemanticError::NoPaymentSecret));
1673
1674                 // No payment secret or feature bits
1675                 let invoice = {
1676                         let mut invoice = invoice_template.clone();
1677                         invoice.data.tagged_fields.push(Features(InvoiceFeatures::empty()).into());
1678                         invoice.sign::<_, ()>(|hash| Ok(Secp256k1::new().sign_recoverable(hash, &private_key)))
1679                 }.unwrap();
1680                 assert_eq!(Invoice::from_signed(invoice), Err(SemanticError::NoPaymentSecret));
1681
1682                 // Missing payment secret
1683                 let invoice = {
1684                         let mut invoice = invoice_template.clone();
1685                         invoice.data.tagged_fields.push(Features(InvoiceFeatures::known()).into());
1686                         invoice.sign::<_, ()>(|hash| Ok(Secp256k1::new().sign_recoverable(hash, &private_key)))
1687                 }.unwrap();
1688                 assert_eq!(Invoice::from_signed(invoice), Err(SemanticError::NoPaymentSecret));
1689
1690                 // Multiple payment secrets
1691                 let invoice = {
1692                         let mut invoice = invoice_template.clone();
1693                         invoice.data.tagged_fields.push(PaymentSecret(payment_secret).into());
1694                         invoice.data.tagged_fields.push(PaymentSecret(payment_secret).into());
1695                         invoice.sign::<_, ()>(|hash| Ok(Secp256k1::new().sign_recoverable(hash, &private_key)))
1696                 }.unwrap();
1697                 assert_eq!(Invoice::from_signed(invoice), Err(SemanticError::MultiplePaymentSecrets));
1698         }
1699
1700         #[test]
1701         fn test_builder_amount() {
1702                 use ::*;
1703
1704                 let builder = InvoiceBuilder::new(Currency::Bitcoin)
1705                         .description("Test".into())
1706                         .payment_hash(sha256::Hash::from_slice(&[0;32][..]).unwrap())
1707                         .duration_since_epoch(Duration::from_secs(1234567));
1708
1709                 let invoice = builder.clone()
1710                         .amount_milli_satoshis(1500)
1711                         .build_raw()
1712                         .unwrap();
1713
1714                 assert_eq!(invoice.hrp.si_prefix, Some(SiPrefix::Nano));
1715                 assert_eq!(invoice.hrp.raw_amount, Some(15));
1716
1717
1718                 let invoice = builder.clone()
1719                         .amount_milli_satoshis(150)
1720                         .build_raw()
1721                         .unwrap();
1722
1723                 assert_eq!(invoice.hrp.si_prefix, Some(SiPrefix::Pico));
1724                 assert_eq!(invoice.hrp.raw_amount, Some(1500));
1725         }
1726
1727         #[test]
1728         fn test_builder_fail() {
1729                 use ::*;
1730                 use lightning::routing::router::RouteHintHop;
1731                 use std::iter::FromIterator;
1732                 use secp256k1::key::PublicKey;
1733
1734                 let builder = InvoiceBuilder::new(Currency::Bitcoin)
1735                         .payment_hash(sha256::Hash::from_slice(&[0;32][..]).unwrap())
1736                         .duration_since_epoch(Duration::from_secs(1234567))
1737                         .min_final_cltv_expiry(144);
1738
1739                 let too_long_string = String::from_iter(
1740                         (0..1024).map(|_| '?')
1741                 );
1742
1743                 let long_desc_res = builder.clone()
1744                         .description(too_long_string)
1745                         .build_raw();
1746                 assert_eq!(long_desc_res, Err(CreationError::DescriptionTooLong));
1747
1748                 let route_hop = RouteHintHop {
1749                         src_node_id: PublicKey::from_slice(
1750                                         &[
1751                                                 0x03, 0x9e, 0x03, 0xa9, 0x01, 0xb8, 0x55, 0x34, 0xff, 0x1e, 0x92, 0xc4,
1752                                                 0x3c, 0x74, 0x43, 0x1f, 0x7c, 0xe7, 0x20, 0x46, 0x06, 0x0f, 0xcf, 0x7a,
1753                                                 0x95, 0xc3, 0x7e, 0x14, 0x8f, 0x78, 0xc7, 0x72, 0x55
1754                                         ][..]
1755                                 ).unwrap(),
1756                         short_channel_id: 0,
1757                         fees: RoutingFees {
1758                                 base_msat: 0,
1759                                 proportional_millionths: 0,
1760                         },
1761                         cltv_expiry_delta: 0,
1762                         htlc_minimum_msat: None,
1763                         htlc_maximum_msat: None,
1764                 };
1765                 let too_long_route = RouteHint(vec![route_hop; 13]);
1766                 let long_route_res = builder.clone()
1767                         .description("Test".into())
1768                         .private_route(too_long_route)
1769                         .build_raw();
1770                 assert_eq!(long_route_res, Err(CreationError::RouteTooLong));
1771
1772                 let sign_error_res = builder.clone()
1773                         .description("Test".into())
1774                         .payment_secret(PaymentSecret([0; 32]))
1775                         .try_build_signed(|_| {
1776                                 Err("ImaginaryError")
1777                         });
1778                 assert_eq!(sign_error_res, Err(SignOrCreationError::SignError("ImaginaryError")));
1779         }
1780
1781         #[test]
1782         fn test_builder_ok() {
1783                 use ::*;
1784                 use lightning::routing::router::RouteHintHop;
1785                 use secp256k1::Secp256k1;
1786                 use secp256k1::key::{SecretKey, PublicKey};
1787                 use std::time::{UNIX_EPOCH, Duration};
1788
1789                 let secp_ctx = Secp256k1::new();
1790
1791                 let private_key = SecretKey::from_slice(
1792                         &[
1793                                 0xe1, 0x26, 0xf6, 0x8f, 0x7e, 0xaf, 0xcc, 0x8b, 0x74, 0xf5, 0x4d, 0x26, 0x9f, 0xe2,
1794                                 0x06, 0xbe, 0x71, 0x50, 0x00, 0xf9, 0x4d, 0xac, 0x06, 0x7d, 0x1c, 0x04, 0xa8, 0xca,
1795                                 0x3b, 0x2d, 0xb7, 0x34
1796                         ][..]
1797                 ).unwrap();
1798                 let public_key = PublicKey::from_secret_key(&secp_ctx, &private_key);
1799
1800                 let route_1 = RouteHint(vec![
1801                         RouteHintHop {
1802                                 src_node_id: public_key.clone(),
1803                                 short_channel_id: de::parse_int_be(&[123; 8], 256).expect("short chan ID slice too big?"),
1804                                 fees: RoutingFees {
1805                                         base_msat: 2,
1806                                         proportional_millionths: 1,
1807                                 },
1808                                 cltv_expiry_delta: 145,
1809                                 htlc_minimum_msat: None,
1810                                 htlc_maximum_msat: None,
1811                         },
1812                         RouteHintHop {
1813                                 src_node_id: public_key.clone(),
1814                                 short_channel_id: de::parse_int_be(&[42; 8], 256).expect("short chan ID slice too big?"),
1815                                 fees: RoutingFees {
1816                                         base_msat: 3,
1817                                         proportional_millionths: 2,
1818                                 },
1819                                 cltv_expiry_delta: 146,
1820                                 htlc_minimum_msat: None,
1821                                 htlc_maximum_msat: None,
1822                         }
1823                 ]);
1824
1825                 let route_2 = RouteHint(vec![
1826                         RouteHintHop {
1827                                 src_node_id: public_key.clone(),
1828                                 short_channel_id: 0,
1829                                 fees: RoutingFees {
1830                                         base_msat: 4,
1831                                         proportional_millionths: 3,
1832                                 },
1833                                 cltv_expiry_delta: 147,
1834                                 htlc_minimum_msat: None,
1835                                 htlc_maximum_msat: None,
1836                         },
1837                         RouteHintHop {
1838                                 src_node_id: public_key.clone(),
1839                                 short_channel_id: de::parse_int_be(&[1; 8], 256).expect("short chan ID slice too big?"),
1840                                 fees: RoutingFees {
1841                                         base_msat: 5,
1842                                         proportional_millionths: 4,
1843                                 },
1844                                 cltv_expiry_delta: 148,
1845                                 htlc_minimum_msat: None,
1846                                 htlc_maximum_msat: None,
1847                         }
1848                 ]);
1849
1850                 let builder = InvoiceBuilder::new(Currency::BitcoinTestnet)
1851                         .amount_milli_satoshis(123)
1852                         .duration_since_epoch(Duration::from_secs(1234567))
1853                         .payee_pub_key(public_key.clone())
1854                         .expiry_time(Duration::from_secs(54321))
1855                         .min_final_cltv_expiry(144)
1856                         .fallback(Fallback::PubKeyHash([0;20]))
1857                         .private_route(route_1.clone())
1858                         .private_route(route_2.clone())
1859                         .description_hash(sha256::Hash::from_slice(&[3;32][..]).unwrap())
1860                         .payment_hash(sha256::Hash::from_slice(&[21;32][..]).unwrap())
1861                         .payment_secret(PaymentSecret([42; 32]))
1862                         .basic_mpp();
1863
1864                 let invoice = builder.clone().build_signed(|hash| {
1865                         secp_ctx.sign_recoverable(hash, &private_key)
1866                 }).unwrap();
1867
1868                 assert!(invoice.check_signature().is_ok());
1869                 assert_eq!(invoice.tagged_fields().count(), 10);
1870
1871                 assert_eq!(invoice.amount_milli_satoshis(), Some(123));
1872                 assert_eq!(invoice.amount_pico_btc(), Some(1230));
1873                 assert_eq!(invoice.currency(), Currency::BitcoinTestnet);
1874                 #[cfg(feature = "std")]
1875                 assert_eq!(
1876                         invoice.timestamp().duration_since(UNIX_EPOCH).unwrap().as_secs(),
1877                         1234567
1878                 );
1879                 assert_eq!(invoice.payee_pub_key(), Some(&public_key));
1880                 assert_eq!(invoice.expiry_time(), Duration::from_secs(54321));
1881                 assert_eq!(invoice.min_final_cltv_expiry(), 144);
1882                 assert_eq!(invoice.fallbacks(), vec![&Fallback::PubKeyHash([0;20])]);
1883                 assert_eq!(invoice.private_routes(), vec![&PrivateRoute(route_1), &PrivateRoute(route_2)]);
1884                 assert_eq!(
1885                         invoice.description(),
1886                         InvoiceDescription::Hash(&Sha256(sha256::Hash::from_slice(&[3;32][..]).unwrap()))
1887                 );
1888                 assert_eq!(invoice.payment_hash(), &sha256::Hash::from_slice(&[21;32][..]).unwrap());
1889                 assert_eq!(invoice.payment_secret(), &PaymentSecret([42; 32]));
1890                 assert_eq!(invoice.features(), Some(&InvoiceFeatures::empty()
1891                         .set_payment_secret_required().set_variable_length_onion_required().set_basic_mpp_optional()));
1892
1893                 let raw_invoice = builder.build_raw().unwrap();
1894                 assert_eq!(raw_invoice, *invoice.into_signed_raw().raw_invoice())
1895         }
1896
1897         #[test]
1898         fn test_default_values() {
1899                 use ::*;
1900                 use secp256k1::Secp256k1;
1901                 use secp256k1::key::SecretKey;
1902
1903                 let signed_invoice = InvoiceBuilder::new(Currency::Bitcoin)
1904                         .description("Test".into())
1905                         .payment_hash(sha256::Hash::from_slice(&[0;32][..]).unwrap())
1906                         .payment_secret(PaymentSecret([0; 32]))
1907                         .duration_since_epoch(Duration::from_secs(1234567))
1908                         .build_raw()
1909                         .unwrap()
1910                         .sign::<_, ()>(|hash| {
1911                                 let privkey = SecretKey::from_slice(&[41; 32]).unwrap();
1912                                 let secp_ctx = Secp256k1::new();
1913                                 Ok(secp_ctx.sign_recoverable(hash, &privkey))
1914                         })
1915                         .unwrap();
1916                 let invoice = Invoice::from_signed(signed_invoice).unwrap();
1917
1918                 assert_eq!(invoice.min_final_cltv_expiry(), DEFAULT_MIN_FINAL_CLTV_EXPIRY);
1919                 assert_eq!(invoice.expiry_time(), Duration::from_secs(DEFAULT_EXPIRY_TIME));
1920                 assert!(!invoice.would_expire(Duration::from_secs(1234568)));
1921         }
1922
1923         #[test]
1924         fn test_expiration() {
1925                 use ::*;
1926                 use secp256k1::Secp256k1;
1927                 use secp256k1::key::SecretKey;
1928
1929                 let signed_invoice = InvoiceBuilder::new(Currency::Bitcoin)
1930                         .description("Test".into())
1931                         .payment_hash(sha256::Hash::from_slice(&[0;32][..]).unwrap())
1932                         .payment_secret(PaymentSecret([0; 32]))
1933                         .duration_since_epoch(Duration::from_secs(1234567))
1934                         .build_raw()
1935                         .unwrap()
1936                         .sign::<_, ()>(|hash| {
1937                                 let privkey = SecretKey::from_slice(&[41; 32]).unwrap();
1938                                 let secp_ctx = Secp256k1::new();
1939                                 Ok(secp_ctx.sign_recoverable(hash, &privkey))
1940                         })
1941                         .unwrap();
1942                 let invoice = Invoice::from_signed(signed_invoice).unwrap();
1943
1944                 assert!(invoice.would_expire(Duration::from_secs(1234567 + DEFAULT_EXPIRY_TIME + 1)));
1945         }
1946 }