forked from lightningdevkit/rust-lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
1980 lines (1712 loc) · 62.5 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![deny(missing_docs)]
#![deny(non_upper_case_globals)]
#![deny(non_camel_case_types)]
#![deny(non_snake_case)]
#![deny(unused_mut)]
#![deny(broken_intra_doc_links)]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![cfg_attr(feature = "strict", deny(warnings))]
#![cfg_attr(all(not(feature = "std"), not(test)), no_std)]
//! This crate provides data structures to represent
//! [lightning BOLT11](https://github.com/lightningnetwork/lightning-rfc/blob/master/11-payment-encoding.md)
//! invoices and functions to create, encode and decode these. If you just want to use the standard
//! en-/decoding functionality this should get you started:
//!
//! * For parsing use `str::parse::<Invoice>(&self)` (see the docs of `impl FromStr for Invoice`)
//! * For constructing invoices use the `InvoiceBuilder`
//! * For serializing invoices use the `Display`/`ToString` traits
#[cfg(not(any(feature = "std", feature = "no-std")))]
compile_error!("at least one of the `std` or `no-std` features must be enabled");
pub mod payment;
pub mod utils;
extern crate bech32;
extern crate bitcoin_hashes;
#[macro_use] extern crate lightning;
extern crate num_traits;
extern crate secp256k1;
extern crate alloc;
#[cfg(any(test, feature = "std"))]
extern crate core;
#[cfg(feature = "std")]
use std::time::SystemTime;
use bech32::u5;
use bitcoin_hashes::Hash;
use bitcoin_hashes::sha256;
use lightning::ln::PaymentSecret;
use lightning::ln::features::InvoiceFeatures;
#[cfg(any(doc, test))]
use lightning::routing::network_graph::RoutingFees;
use lightning::routing::router::RouteHint;
use lightning::util::invoice::construct_invoice_preimage;
use secp256k1::PublicKey;
use secp256k1::{Message, Secp256k1};
use secp256k1::ecdsa::RecoverableSignature;
use core::fmt::{Display, Formatter, self};
use core::iter::FilterMap;
use core::num::ParseIntError;
use core::ops::Deref;
use core::slice::Iter;
use core::time::Duration;
use core::str;
mod de;
mod ser;
mod tb;
mod prelude {
#[cfg(feature = "hashbrown")]
extern crate hashbrown;
pub use alloc::{vec, vec::Vec, string::String, collections::VecDeque, boxed::Box};
#[cfg(not(feature = "hashbrown"))]
pub use std::collections::{HashMap, HashSet, hash_map};
#[cfg(feature = "hashbrown")]
pub use self::hashbrown::{HashMap, HashSet, hash_map};
pub use alloc::string::ToString;
}
use prelude::*;
/// Sync compat for std/no_std
#[cfg(feature = "std")]
mod sync {
pub use ::std::sync::{Mutex, MutexGuard};
}
/// Sync compat for std/no_std
#[cfg(not(feature = "std"))]
mod sync;
/// Errors that indicate what is wrong with the invoice. They have some granularity for debug
/// reasons, but should generally result in an "invalid BOLT11 invoice" message for the user.
#[allow(missing_docs)]
#[derive(PartialEq, Debug, Clone)]
pub enum ParseError {
Bech32Error(bech32::Error),
ParseAmountError(ParseIntError),
MalformedSignature(secp256k1::Error),
BadPrefix,
UnknownCurrency,
UnknownSiPrefix,
MalformedHRP,
TooShortDataPart,
UnexpectedEndOfTaggedFields,
DescriptionDecodeError(str::Utf8Error),
PaddingError,
IntegerOverflowError,
InvalidSegWitProgramLength,
InvalidPubKeyHashLength,
InvalidScriptHashLength,
InvalidRecoveryId,
InvalidSliceLength(String),
/// Not an error, but used internally to signal that a part of the invoice should be ignored
/// according to BOLT11
Skip,
}
/// Indicates that something went wrong while parsing or validating the invoice. Parsing errors
/// should be mostly seen as opaque and are only there for debugging reasons. Semantic errors
/// like wrong signatures, missing fields etc. could mean that someone tampered with the invoice.
#[derive(PartialEq, Debug, Clone)]
pub enum ParseOrSemanticError {
/// The invoice couldn't be decoded
ParseError(ParseError),
/// The invoice could be decoded but violates the BOLT11 standard
SemanticError(::SemanticError),
}
/// The number of bits used to represent timestamps as defined in BOLT 11.
const TIMESTAMP_BITS: usize = 35;
/// The maximum timestamp as [`Duration::as_secs`] since the Unix epoch allowed by [`BOLT 11`].
///
/// [BOLT 11]: https://github.com/lightning/bolts/blob/master/11-payment-encoding.md
pub const MAX_TIMESTAMP: u64 = (1 << TIMESTAMP_BITS) - 1;
/// Default expiry time as defined by [BOLT 11].
///
/// [BOLT 11]: https://github.com/lightning/bolts/blob/master/11-payment-encoding.md
pub const DEFAULT_EXPIRY_TIME: u64 = 3600;
/// Default minimum final CLTV expiry as defined by [BOLT 11].
///
/// Note that this is *not* the same value as rust-lightning's minimum CLTV expiry, which is
/// provided in [`MIN_FINAL_CLTV_EXPIRY`].
///
/// [BOLT 11]: https://github.com/lightning/bolts/blob/master/11-payment-encoding.md
/// [`MIN_FINAL_CLTV_EXPIRY`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY
pub const DEFAULT_MIN_FINAL_CLTV_EXPIRY: u64 = 18;
/// Builder for `Invoice`s. It's the most convenient and advised way to use this library. It ensures
/// that only a semantically and syntactically correct Invoice can be built using it.
///
/// ```
/// extern crate secp256k1;
/// extern crate lightning;
/// extern crate lightning_invoice;
/// extern crate bitcoin_hashes;
///
/// use bitcoin_hashes::Hash;
/// use bitcoin_hashes::sha256;
///
/// use secp256k1::Secp256k1;
/// use secp256k1::SecretKey;
///
/// use lightning::ln::PaymentSecret;
///
/// use lightning_invoice::{Currency, InvoiceBuilder};
///
/// # #[cfg(not(feature = "std"))]
/// # fn main() {}
/// # #[cfg(feature = "std")]
/// # fn main() {
/// let private_key = SecretKey::from_slice(
/// &[
/// 0xe1, 0x26, 0xf6, 0x8f, 0x7e, 0xaf, 0xcc, 0x8b, 0x74, 0xf5, 0x4d, 0x26, 0x9f,
/// 0xe2, 0x06, 0xbe, 0x71, 0x50, 0x00, 0xf9, 0x4d, 0xac, 0x06, 0x7d, 0x1c, 0x04,
/// 0xa8, 0xca, 0x3b, 0x2d, 0xb7, 0x34
/// ][..]
/// ).unwrap();
///
/// let payment_hash = sha256::Hash::from_slice(&[0; 32][..]).unwrap();
/// let payment_secret = PaymentSecret([42u8; 32]);
///
/// let invoice = InvoiceBuilder::new(Currency::Bitcoin)
/// .description("Coins pls!".into())
/// .payment_hash(payment_hash)
/// .payment_secret(payment_secret)
/// .current_timestamp()
/// .min_final_cltv_expiry(144)
/// .build_signed(|hash| {
/// Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
/// })
/// .unwrap();
///
/// assert!(invoice.to_string().starts_with("lnbc1"));
/// # }
/// ```
///
/// # Type parameters
/// The two parameters `D` and `H` signal if the builder already contains the correct amount of the
/// given field:
/// * `D`: exactly one `Description` or `DescriptionHash`
/// * `H`: exactly one `PaymentHash`
/// * `T`: the timestamp is set
///
/// (C-not exported) as we likely need to manually select one set of boolean type parameters.
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct InvoiceBuilder<D: tb::Bool, H: tb::Bool, T: tb::Bool, C: tb::Bool, S: tb::Bool> {
currency: Currency,
amount: Option<u64>,
si_prefix: Option<SiPrefix>,
timestamp: Option<PositiveTimestamp>,
tagged_fields: Vec<TaggedField>,
error: Option<CreationError>,
phantom_d: core::marker::PhantomData<D>,
phantom_h: core::marker::PhantomData<H>,
phantom_t: core::marker::PhantomData<T>,
phantom_c: core::marker::PhantomData<C>,
phantom_s: core::marker::PhantomData<S>,
}
/// Represents a syntactically and semantically correct lightning BOLT11 invoice.
///
/// There are three ways to construct an `Invoice`:
/// 1. using `InvoiceBuilder`
/// 2. using `Invoice::from_signed(SignedRawInvoice)`
/// 3. using `str::parse::<Invoice>(&str)`
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct Invoice {
signed_invoice: SignedRawInvoice,
}
/// Represents the description of an invoice which has to be either a directly included string or
/// a hash of a description provided out of band.
///
/// (C-not exported) As we don't have a good way to map the reference lifetimes making this
/// practically impossible to use safely in languages like C.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum InvoiceDescription<'f> {
/// Reference to the directly supplied description in the invoice
Direct(&'f Description),
/// Reference to the description's hash included in the invoice
Hash(&'f Sha256),
}
/// Represents a signed `RawInvoice` with cached hash. The signature is not checked and may be
/// invalid.
///
/// # Invariants
/// The hash has to be either from the deserialized invoice or from the serialized `raw_invoice`.
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct SignedRawInvoice {
/// The rawInvoice that the signature belongs to
raw_invoice: RawInvoice,
/// Hash of the `RawInvoice` that will be used to check the signature.
///
/// * if the `SignedRawInvoice` was deserialized the hash is of from the original encoded form,
/// since it's not guaranteed that encoding it again will lead to the same result since integers
/// could have been encoded with leading zeroes etc.
/// * if the `SignedRawInvoice` was constructed manually the hash will be the calculated hash
/// from the `RawInvoice`
hash: [u8; 32],
/// signature of the payment request
signature: InvoiceSignature,
}
/// Represents an syntactically correct Invoice for a payment on the lightning network,
/// but without the signature information.
/// De- and encoding should not lead to information loss but may lead to different hashes.
///
/// For methods without docs see the corresponding methods in `Invoice`.
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct RawInvoice {
/// human readable part
pub hrp: RawHrp,
/// data part
pub data: RawDataPart,
}
/// Data of the `RawInvoice` that is encoded in the human readable part
///
/// (C-not exported) As we don't yet support Option<Enum>
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct RawHrp {
/// The currency deferred from the 3rd and 4th character of the bech32 transaction
pub currency: Currency,
/// The amount that, multiplied by the SI prefix, has to be payed
pub raw_amount: Option<u64>,
/// SI prefix that gets multiplied with the `raw_amount`
pub si_prefix: Option<SiPrefix>,
}
/// Data of the `RawInvoice` that is encoded in the data part
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct RawDataPart {
/// generation time of the invoice
pub timestamp: PositiveTimestamp,
/// tagged fields of the payment request
pub tagged_fields: Vec<RawTaggedField>,
}
/// A timestamp that refers to a date after 1 January 1970.
///
/// # Invariants
///
/// The Unix timestamp representing the stored time has to be positive and no greater than
/// [`MAX_TIMESTAMP`].
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct PositiveTimestamp(Duration);
/// SI prefixes for the human readable part
#[derive(Eq, PartialEq, Debug, Clone, Copy)]
pub enum SiPrefix {
/// 10^-3
Milli,
/// 10^-6
Micro,
/// 10^-9
Nano,
/// 10^-12
Pico,
}
impl SiPrefix {
/// Returns the multiplier to go from a BTC value to picoBTC implied by this SiPrefix.
/// This is effectively 10^12 * the prefix multiplier
pub fn multiplier(&self) -> u64 {
match *self {
SiPrefix::Milli => 1_000_000_000,
SiPrefix::Micro => 1_000_000,
SiPrefix::Nano => 1_000,
SiPrefix::Pico => 1,
}
}
/// Returns all enum variants of `SiPrefix` sorted in descending order of their associated
/// multiplier.
///
/// (C-not exported) As we don't yet support a slice of enums, and also because this function
/// isn't the most critical to expose.
pub fn values_desc() -> &'static [SiPrefix] {
use SiPrefix::*;
static VALUES: [SiPrefix; 4] = [Milli, Micro, Nano, Pico];
&VALUES
}
}
/// Enum representing the crypto currencies (or networks) supported by this library
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub enum Currency {
/// Bitcoin mainnet
Bitcoin,
/// Bitcoin testnet
BitcoinTestnet,
/// Bitcoin regtest
Regtest,
/// Bitcoin simnet
Simnet,
/// Bitcoin signet
Signet,
}
/// Tagged field which may have an unknown tag
///
/// (C-not exported) as we don't currently support TaggedField
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub enum RawTaggedField {
/// Parsed tagged field with known tag
KnownSemantics(TaggedField),
/// tagged field which was not parsed due to an unknown tag or undefined field semantics
UnknownSemantics(Vec<u5>),
}
/// Tagged field with known tag
///
/// For descriptions of the enum values please refer to the enclosed type's docs.
///
/// (C-not exported) As we don't yet support enum variants with the same name the struct contained
/// in the variant.
#[allow(missing_docs)]
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub enum TaggedField {
PaymentHash(Sha256),
Description(Description),
PayeePubKey(PayeePubKey),
DescriptionHash(Sha256),
ExpiryTime(ExpiryTime),
MinFinalCltvExpiry(MinFinalCltvExpiry),
Fallback(Fallback),
PrivateRoute(PrivateRoute),
PaymentSecret(PaymentSecret),
Features(InvoiceFeatures),
}
/// SHA-256 hash
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct Sha256(/// (C-not exported) as the native hash types are not currently mapped
pub sha256::Hash);
/// Description string
///
/// # Invariants
/// The description can be at most 639 __bytes__ long
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct Description(String);
/// Payee public key
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct PayeePubKey(pub PublicKey);
/// Positive duration that defines when (relatively to the timestamp) in the future the invoice
/// expires
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct ExpiryTime(Duration);
/// `min_final_cltv_expiry` to use for the last HTLC in the route
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct MinFinalCltvExpiry(pub u64);
// TODO: better types instead onf byte arrays
/// Fallback address in case no LN payment is possible
#[allow(missing_docs)]
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub enum Fallback {
SegWitProgram {
version: u5,
program: Vec<u8>,
},
PubKeyHash([u8; 20]),
ScriptHash([u8; 20]),
}
/// Recoverable signature
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct InvoiceSignature(pub RecoverableSignature);
/// Private routing information
///
/// # Invariants
/// The encoded route has to be <1024 5bit characters long (<=639 bytes or <=12 hops)
///
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct PrivateRoute(RouteHint);
/// Tag constants as specified in BOLT11
#[allow(missing_docs)]
pub mod constants {
pub const TAG_PAYMENT_HASH: u8 = 1;
pub const TAG_DESCRIPTION: u8 = 13;
pub const TAG_PAYEE_PUB_KEY: u8 = 19;
pub const TAG_DESCRIPTION_HASH: u8 = 23;
pub const TAG_EXPIRY_TIME: u8 = 6;
pub const TAG_MIN_FINAL_CLTV_EXPIRY: u8 = 24;
pub const TAG_FALLBACK: u8 = 9;
pub const TAG_PRIVATE_ROUTE: u8 = 3;
pub const TAG_PAYMENT_SECRET: u8 = 16;
pub const TAG_FEATURES: u8 = 5;
}
impl InvoiceBuilder<tb::False, tb::False, tb::False, tb::False, tb::False> {
/// Construct new, empty `InvoiceBuilder`. All necessary fields have to be filled first before
/// `InvoiceBuilder::build(self)` becomes available.
pub fn new(currrency: Currency) -> Self {
InvoiceBuilder {
currency: currrency,
amount: None,
si_prefix: None,
timestamp: None,
tagged_fields: Vec::new(),
error: None,
phantom_d: core::marker::PhantomData,
phantom_h: core::marker::PhantomData,
phantom_t: core::marker::PhantomData,
phantom_c: core::marker::PhantomData,
phantom_s: core::marker::PhantomData,
}
}
}
impl<D: tb::Bool, H: tb::Bool, T: tb::Bool, C: tb::Bool, S: tb::Bool> InvoiceBuilder<D, H, T, C, S> {
/// Helper function to set the completeness flags.
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> {
InvoiceBuilder::<DN, HN, TN, CN, SN> {
currency: self.currency,
amount: self.amount,
si_prefix: self.si_prefix,
timestamp: self.timestamp,
tagged_fields: self.tagged_fields,
error: self.error,
phantom_d: core::marker::PhantomData,
phantom_h: core::marker::PhantomData,
phantom_t: core::marker::PhantomData,
phantom_c: core::marker::PhantomData,
phantom_s: core::marker::PhantomData,
}
}
/// Sets the amount in millisatoshis. The optimal SI prefix is chosen automatically.
pub fn amount_milli_satoshis(mut self, amount_msat: u64) -> Self {
let amount = amount_msat * 10; // Invoices are denominated in "pico BTC"
let biggest_possible_si_prefix = SiPrefix::values_desc()
.iter()
.find(|prefix| amount % prefix.multiplier() == 0)
.expect("Pico should always match");
self.amount = Some(amount / biggest_possible_si_prefix.multiplier());
self.si_prefix = Some(*biggest_possible_si_prefix);
self
}
/// Sets the payee's public key.
pub fn payee_pub_key(mut self, pub_key: PublicKey) -> Self {
self.tagged_fields.push(TaggedField::PayeePubKey(PayeePubKey(pub_key)));
self
}
/// Sets the expiry time
pub fn expiry_time(mut self, expiry_time: Duration) -> Self {
self.tagged_fields.push(TaggedField::ExpiryTime(ExpiryTime::from_duration(expiry_time)));
self
}
/// Adds a fallback address.
pub fn fallback(mut self, fallback: Fallback) -> Self {
self.tagged_fields.push(TaggedField::Fallback(fallback));
self
}
/// Adds a private route.
pub fn private_route(mut self, hint: RouteHint) -> Self {
match PrivateRoute::new(hint) {
Ok(r) => self.tagged_fields.push(TaggedField::PrivateRoute(r)),
Err(e) => self.error = Some(e),
}
self
}
}
impl<D: tb::Bool, H: tb::Bool, C: tb::Bool, S: tb::Bool> InvoiceBuilder<D, H, tb::True, C, S> {
/// Builds a `RawInvoice` if no `CreationError` occurred while construction any of the fields.
pub fn build_raw(self) -> Result<RawInvoice, CreationError> {
// If an error occurred at any time before, return it now
if let Some(e) = self.error {
return Err(e);
}
let hrp = RawHrp {
currency: self.currency,
raw_amount: self.amount,
si_prefix: self.si_prefix,
};
let timestamp = self.timestamp.expect("ensured to be Some(t) by type T");
let tagged_fields = self.tagged_fields.into_iter().map(|tf| {
RawTaggedField::KnownSemantics(tf)
}).collect::<Vec<_>>();
let data = RawDataPart {
timestamp: timestamp,
tagged_fields: tagged_fields,
};
Ok(RawInvoice {
hrp: hrp,
data: data,
})
}
}
impl<H: tb::Bool, T: tb::Bool, C: tb::Bool, S: tb::Bool> InvoiceBuilder<tb::False, H, T, C, S> {
/// Set the description. This function is only available if no description (hash) was set.
pub fn description(mut self, description: String) -> InvoiceBuilder<tb::True, H, T, C, S> {
match Description::new(description) {
Ok(d) => self.tagged_fields.push(TaggedField::Description(d)),
Err(e) => self.error = Some(e),
}
self.set_flags()
}
/// Set the description hash. This function is only available if no description (hash) was set.
pub fn description_hash(mut self, description_hash: sha256::Hash) -> InvoiceBuilder<tb::True, H, T, C, S> {
self.tagged_fields.push(TaggedField::DescriptionHash(Sha256(description_hash)));
self.set_flags()
}
}
impl<D: tb::Bool, T: tb::Bool, C: tb::Bool, S: tb::Bool> InvoiceBuilder<D, tb::False, T, C, S> {
/// Set the payment hash. This function is only available if no payment hash was set.
pub fn payment_hash(mut self, hash: sha256::Hash) -> InvoiceBuilder<D, tb::True, T, C, S> {
self.tagged_fields.push(TaggedField::PaymentHash(Sha256(hash)));
self.set_flags()
}
}
impl<D: tb::Bool, H: tb::Bool, C: tb::Bool, S: tb::Bool> InvoiceBuilder<D, H, tb::False, C, S> {
/// Sets the timestamp to a specific [`SystemTime`].
#[cfg(feature = "std")]
pub fn timestamp(mut self, time: SystemTime) -> InvoiceBuilder<D, H, tb::True, C, S> {
match PositiveTimestamp::from_system_time(time) {
Ok(t) => self.timestamp = Some(t),
Err(e) => self.error = Some(e),
}
self.set_flags()
}
/// Sets the timestamp to a duration since the Unix epoch.
pub fn duration_since_epoch(mut self, time: Duration) -> InvoiceBuilder<D, H, tb::True, C, S> {
match PositiveTimestamp::from_duration_since_epoch(time) {
Ok(t) => self.timestamp = Some(t),
Err(e) => self.error = Some(e),
}
self.set_flags()
}
/// Sets the timestamp to the current system time.
#[cfg(feature = "std")]
pub fn current_timestamp(mut self) -> InvoiceBuilder<D, H, tb::True, C, S> {
let now = PositiveTimestamp::from_system_time(SystemTime::now());
self.timestamp = Some(now.expect("for the foreseeable future this shouldn't happen"));
self.set_flags()
}
}
impl<D: tb::Bool, H: tb::Bool, T: tb::Bool, S: tb::Bool> InvoiceBuilder<D, H, T, tb::False, S> {
/// Sets `min_final_cltv_expiry`.
pub fn min_final_cltv_expiry(mut self, min_final_cltv_expiry: u64) -> InvoiceBuilder<D, H, T, tb::True, S> {
self.tagged_fields.push(TaggedField::MinFinalCltvExpiry(MinFinalCltvExpiry(min_final_cltv_expiry)));
self.set_flags()
}
}
impl<D: tb::Bool, H: tb::Bool, T: tb::Bool, C: tb::Bool> InvoiceBuilder<D, H, T, C, tb::False> {
/// Sets the payment secret and relevant features.
pub fn payment_secret(mut self, payment_secret: PaymentSecret) -> InvoiceBuilder<D, H, T, C, tb::True> {
let mut features = InvoiceFeatures::empty();
features.set_variable_length_onion_required();
features.set_payment_secret_required();
self.tagged_fields.push(TaggedField::PaymentSecret(payment_secret));
self.tagged_fields.push(TaggedField::Features(features));
self.set_flags()
}
}
impl<D: tb::Bool, H: tb::Bool, T: tb::Bool, C: tb::Bool> InvoiceBuilder<D, H, T, C, tb::True> {
/// Sets the `basic_mpp` feature as optional.
pub fn basic_mpp(mut self) -> Self {
for field in self.tagged_fields.iter_mut() {
if let TaggedField::Features(f) = field {
f.set_basic_mpp_optional();
}
}
self
}
}
impl InvoiceBuilder<tb::True, tb::True, tb::True, tb::True, tb::True> {
/// Builds and signs an invoice using the supplied `sign_function`. This function MAY NOT fail
/// and MUST produce a recoverable signature valid for the given hash and if applicable also for
/// the included payee public key.
pub fn build_signed<F>(self, sign_function: F) -> Result<Invoice, CreationError>
where F: FnOnce(&Message) -> RecoverableSignature
{
let invoice = self.try_build_signed::<_, ()>(|hash| {
Ok(sign_function(hash))
});
match invoice {
Ok(i) => Ok(i),
Err(SignOrCreationError::CreationError(e)) => Err(e),
Err(SignOrCreationError::SignError(())) => unreachable!(),
}
}
/// Builds and signs an invoice using the supplied `sign_function`. This function MAY fail with
/// an error of type `E` and MUST produce a recoverable signature valid for the given hash and
/// if applicable also for the included payee public key.
pub fn try_build_signed<F, E>(self, sign_function: F) -> Result<Invoice, SignOrCreationError<E>>
where F: FnOnce(&Message) -> Result<RecoverableSignature, E>
{
let raw = match self.build_raw() {
Ok(r) => r,
Err(e) => return Err(SignOrCreationError::CreationError(e)),
};
let signed = match raw.sign(sign_function) {
Ok(s) => s,
Err(e) => return Err(SignOrCreationError::SignError(e)),
};
let invoice = Invoice {
signed_invoice: signed,
};
invoice.check_field_counts().expect("should be ensured by type signature of builder");
invoice.check_feature_bits().expect("should be ensured by type signature of builder");
invoice.check_amount().expect("should be ensured by type signature of builder");
Ok(invoice)
}
}
impl SignedRawInvoice {
/// Disassembles the `SignedRawInvoice` into its three parts:
/// 1. raw invoice
/// 2. hash of the raw invoice
/// 3. signature
pub fn into_parts(self) -> (RawInvoice, [u8; 32], InvoiceSignature) {
(self.raw_invoice, self.hash, self.signature)
}
/// The `RawInvoice` which was signed.
pub fn raw_invoice(&self) -> &RawInvoice {
&self.raw_invoice
}
/// The hash of the `RawInvoice` that was signed.
pub fn hash(&self) -> &[u8; 32] {
&self.hash
}
/// InvoiceSignature for the invoice.
pub fn signature(&self) -> &InvoiceSignature {
&self.signature
}
/// Recovers the public key used for signing the invoice from the recoverable signature.
pub fn recover_payee_pub_key(&self) -> Result<PayeePubKey, secp256k1::Error> {
let hash = Message::from_slice(&self.hash[..])
.expect("Hash is 32 bytes long, same as MESSAGE_SIZE");
Ok(PayeePubKey(Secp256k1::new().recover_ecdsa(
&hash,
&self.signature
)?))
}
/// Checks if the signature is valid for the included payee public key or if none exists if it's
/// valid for the recovered signature (which should always be true?).
pub fn check_signature(&self) -> bool {
let included_pub_key = self.raw_invoice.payee_pub_key();
let mut recovered_pub_key = Option::None;
if recovered_pub_key.is_none() {
let recovered = match self.recover_payee_pub_key() {
Ok(pk) => pk,
Err(_) => return false,
};
recovered_pub_key = Some(recovered);
}
let pub_key = included_pub_key.or_else(|| recovered_pub_key.as_ref())
.expect("One is always present");
let hash = Message::from_slice(&self.hash[..])
.expect("Hash is 32 bytes long, same as MESSAGE_SIZE");
let secp_context = Secp256k1::new();
let verification_result = secp_context.verify_ecdsa(
&hash,
&self.signature.to_standard(),
pub_key
);
match verification_result {
Ok(()) => true,
Err(_) => false,
}
}
}
/// Finds the first element of an enum stream of a given variant and extracts one member of the
/// variant. If no element was found `None` gets returned.
///
/// The following example would extract the first B.
/// ```
/// use Enum::*
///
/// enum Enum {
/// A(u8),
/// B(u16)
/// }
///
/// let elements = vec![A(1), A(2), B(3), A(4)]
///
/// assert_eq!(find_extract!(elements.iter(), Enum::B(ref x), x), Some(3u16))
/// ```
macro_rules! find_extract {
($iter:expr, $enm:pat, $enm_var:ident) => {
find_all_extract!($iter, $enm, $enm_var).next()
};
}
/// Finds the all elements of an enum stream of a given variant and extracts one member of the
/// variant through an iterator.
///
/// The following example would extract all A.
/// ```
/// use Enum::*
///
/// enum Enum {
/// A(u8),
/// B(u16)
/// }
///
/// let elements = vec![A(1), A(2), B(3), A(4)]
///
/// assert_eq!(
/// find_all_extract!(elements.iter(), Enum::A(ref x), x).collect::<Vec<u8>>(),
/// vec![1u8, 2u8, 4u8])
/// ```
macro_rules! find_all_extract {
($iter:expr, $enm:pat, $enm_var:ident) => {
$iter.filter_map(|tf| match *tf {
$enm => Some($enm_var),
_ => None,
})
};
}
#[allow(missing_docs)]
impl RawInvoice {
/// Hash the HRP as bytes and signatureless data part.
fn hash_from_parts(hrp_bytes: &[u8], data_without_signature: &[u5]) -> [u8; 32] {
let preimage = construct_invoice_preimage(hrp_bytes, data_without_signature);
let mut hash: [u8; 32] = Default::default();
hash.copy_from_slice(&sha256::Hash::hash(&preimage)[..]);
hash
}
/// Calculate the hash of the encoded `RawInvoice`
pub fn hash(&self) -> [u8; 32] {
use bech32::ToBase32;
RawInvoice::hash_from_parts(
self.hrp.to_string().as_bytes(),
&self.data.to_base32()
)
}
/// Signs the invoice using the supplied `sign_function`. This function MAY fail with an error
/// of type `E`. Since the signature of a `SignedRawInvoice` is not required to be valid there
/// are no constraints regarding the validity of the produced signature.
///
/// (C-not exported) As we don't currently support passing function pointers into methods
/// explicitly.
pub fn sign<F, E>(self, sign_method: F) -> Result<SignedRawInvoice, E>
where F: FnOnce(&Message) -> Result<RecoverableSignature, E>
{
let raw_hash = self.hash();
let hash = Message::from_slice(&raw_hash[..])
.expect("Hash is 32 bytes long, same as MESSAGE_SIZE");
let signature = sign_method(&hash)?;
Ok(SignedRawInvoice {
raw_invoice: self,
hash: raw_hash,
signature: InvoiceSignature(signature),
})
}
/// Returns an iterator over all tagged fields with known semantics.
///
/// (C-not exported) As there is not yet a manual mapping for a FilterMap
pub fn known_tagged_fields(&self)
-> FilterMap<Iter<RawTaggedField>, fn(&RawTaggedField) -> Option<&TaggedField>>
{
// For 1.14.0 compatibility: closures' types can't be written an fn()->() in the
// function's type signature.
// TODO: refactor once impl Trait is available
fn match_raw(raw: &RawTaggedField) -> Option<&TaggedField> {
match *raw {
RawTaggedField::KnownSemantics(ref tf) => Some(tf),
_ => None,
}
}
self.data.tagged_fields.iter().filter_map(match_raw )
}
pub fn payment_hash(&self) -> Option<&Sha256> {
find_extract!(self.known_tagged_fields(), TaggedField::PaymentHash(ref x), x)
}
pub fn description(&self) -> Option<&Description> {
find_extract!(self.known_tagged_fields(), TaggedField::Description(ref x), x)
}
pub fn payee_pub_key(&self) -> Option<&PayeePubKey> {
find_extract!(self.known_tagged_fields(), TaggedField::PayeePubKey(ref x), x)
}
pub fn description_hash(&self) -> Option<&Sha256> {
find_extract!(self.known_tagged_fields(), TaggedField::DescriptionHash(ref x), x)
}
pub fn expiry_time(&self) -> Option<&ExpiryTime> {
find_extract!(self.known_tagged_fields(), TaggedField::ExpiryTime(ref x), x)
}
pub fn min_final_cltv_expiry(&self) -> Option<&MinFinalCltvExpiry> {
find_extract!(self.known_tagged_fields(), TaggedField::MinFinalCltvExpiry(ref x), x)
}
pub fn payment_secret(&self) -> Option<&PaymentSecret> {
find_extract!(self.known_tagged_fields(), TaggedField::PaymentSecret(ref x), x)
}
pub fn features(&self) -> Option<&InvoiceFeatures> {
find_extract!(self.known_tagged_fields(), TaggedField::Features(ref x), x)
}
/// (C-not exported) as we don't support Vec<&NonOpaqueType>
pub fn fallbacks(&self) -> Vec<&Fallback> {
find_all_extract!(self.known_tagged_fields(), TaggedField::Fallback(ref x), x).collect()
}
pub fn private_routes(&self) -> Vec<&PrivateRoute> {
find_all_extract!(self.known_tagged_fields(), TaggedField::PrivateRoute(ref x), x).collect()
}
pub fn amount_pico_btc(&self) -> Option<u64> {
self.hrp.raw_amount.map(|v| {
v * self.hrp.si_prefix.as_ref().map_or(1_000_000_000_000, |si| { si.multiplier() })
})
}
pub fn currency(&self) -> Currency {
self.hrp.currency.clone()
}
}
impl PositiveTimestamp {
/// Creates a `PositiveTimestamp` from a Unix timestamp in the range `0..=MAX_TIMESTAMP`.
///
/// Otherwise, returns a [`CreationError::TimestampOutOfBounds`].
pub fn from_unix_timestamp(unix_seconds: u64) -> Result<Self, CreationError> {
Self::from_duration_since_epoch(Duration::from_secs(unix_seconds))
}
/// Creates a `PositiveTimestamp` from a [`SystemTime`] with a corresponding Unix timestamp in
/// the range `0..=MAX_TIMESTAMP`.
///
/// Otherwise, returns a [`CreationError::TimestampOutOfBounds`].
#[cfg(feature = "std")]
pub fn from_system_time(time: SystemTime) -> Result<Self, CreationError> {
time.duration_since(SystemTime::UNIX_EPOCH)
.map(Self::from_duration_since_epoch)
.unwrap_or(Err(CreationError::TimestampOutOfBounds))
}
/// Creates a `PositiveTimestamp` from a [`Duration`] since the Unix epoch in the range
/// `0..=MAX_TIMESTAMP`.
///
/// Otherwise, returns a [`CreationError::TimestampOutOfBounds`].
pub fn from_duration_since_epoch(duration: Duration) -> Result<Self, CreationError> {
if duration.as_secs() <= MAX_TIMESTAMP {
Ok(PositiveTimestamp(duration))
} else {
Err(CreationError::TimestampOutOfBounds)
}
}
/// Returns the Unix timestamp representing the stored time
pub fn as_unix_timestamp(&self) -> u64 {
self.0.as_secs()
}
/// Returns the duration of the stored time since the Unix epoch
pub fn as_duration_since_epoch(&self) -> Duration {
self.0
}
/// Returns the [`SystemTime`] representing the stored time
#[cfg(feature = "std")]
pub fn as_time(&self) -> SystemTime {
SystemTime::UNIX_EPOCH + self.0
}
}