forked from lightningdevkit/rust-lightning
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlib.rs
More file actions
2457 lines (2153 loc) · 80 KB
/
lib.rs
File metadata and controls
2457 lines (2153 loc) · 80 KB
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(rustdoc::broken_intra_doc_links)]
#![deny(rustdoc::private_intra_doc_links)]
#![deny(missing_docs)]
#![deny(non_upper_case_globals)]
#![deny(non_camel_case_types)]
#![deny(non_snake_case)]
#![deny(unused_mut)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(all(not(feature = "std"), not(test)), no_std)]
//! This crate provides data structures to represent
//! [lightning BOLT11](https://github.com/lightning/bolts/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::<Bolt11Invoice>(&self)` (see [`Bolt11Invoice::from_str`])
//! * For constructing invoices use the [`InvoiceBuilder`]
//! * For serializing invoices use the [`Display`]/[`ToString`] traits
//!
//! [`Bolt11Invoice::from_str`]: crate::Bolt11Invoice#impl-FromStr
extern crate alloc;
extern crate bech32;
#[cfg(any(test, feature = "std"))]
extern crate core;
extern crate lightning_types;
#[cfg(feature = "serde")]
extern crate serde;
#[cfg(feature = "std")]
use std::time::SystemTime;
use bech32::primitives::decode::CheckedHrpstringError;
use bech32::{Checksum, Fe32};
use bitcoin::hashes::{sha256, Hash};
use bitcoin::{Address, Network, PubkeyHash, ScriptHash, WitnessProgram, WitnessVersion};
use lightning_types::features::Bolt11InvoiceFeatures;
use bitcoin::secp256k1::ecdsa::RecoverableSignature;
use bitcoin::secp256k1::PublicKey;
use bitcoin::secp256k1::{Message, Secp256k1};
use alloc::boxed::Box;
use alloc::string;
use core::cmp::Ordering;
use core::fmt::{self, Display, Formatter};
use core::iter::FilterMap;
use core::num::ParseIntError;
use core::ops::Deref;
use core::slice::Iter;
use core::str::FromStr;
use core::time::Duration;
#[cfg(feature = "serde")]
use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};
#[doc(no_inline)]
pub use lightning_types::payment::PaymentSecret;
#[doc(no_inline)]
pub use lightning_types::routing::{RouteHint, RouteHintHop, RoutingFees};
use lightning_types::string::UntrustedString;
mod de;
mod ser;
mod tb;
#[cfg(test)]
mod test_ser_de;
#[allow(unused_imports)]
mod prelude {
pub use alloc::{string::String, vec, vec::Vec};
pub use alloc::string::ToString;
}
use crate::prelude::*;
/// Re-export serialization traits
#[cfg(fuzzing)]
pub use crate::de::FromBase32;
#[cfg(not(fuzzing))]
use crate::de::FromBase32;
#[cfg(fuzzing)]
pub use crate::ser::Base32Iterable;
#[cfg(not(fuzzing))]
use crate::ser::Base32Iterable;
/// 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, Eq, Debug, Clone)]
pub enum Bolt11ParseError {
Bech32Error(
/// This is not exported to bindings users as the details don't matter much
CheckedHrpstringError,
),
ParseAmountError(ParseIntError),
MalformedSignature(bitcoin::secp256k1::Error),
BadPrefix,
UnknownCurrency,
UnknownSiPrefix,
MalformedHRP,
TooShortDataPart,
UnexpectedEndOfTaggedFields,
DescriptionDecodeError(string::FromUtf8Error),
PaddingError,
IntegerOverflowError,
InvalidSegWitProgramLength,
InvalidPubKeyHashLength,
InvalidScriptHashLength,
// Invalid length, with actual length, expected length, and name of the element
InvalidSliceLength(usize, usize, &'static str),
/// 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, Eq, Debug, Clone)]
pub enum ParseOrSemanticError {
/// The invoice couldn't be decoded
ParseError(Bolt11ParseError),
/// The invoice could be decoded but violates the BOLT11 standard
SemanticError(crate::Bolt11SemanticError),
}
/// 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.
///
/// [BOLT 11]: https://github.com/lightning/bolts/blob/master/11-payment-encoding.md
pub const DEFAULT_MIN_FINAL_CLTV_EXPIRY_DELTA: u64 = 18;
/// lightning-invoice will reject BOLT11 invoices that are longer than 7089 bytes.
///
/// ### Rationale
///
/// This value matches LND's implementation, which was chosen to be "the max number
/// of bytes that can fit in a QR code". LND's rationale is technically incorrect
/// as QR codes actually have a max capacity of 7089 _numeric_ characters and only
/// support up to 4296 all-uppercase alphanumeric characters. However, ecosystem-wide
/// consistency is more important.
pub const MAX_LENGTH: usize = 7089;
/// The [`bech32::Bech32`] checksum algorithm, with extended max length suitable
/// for BOLT11 invoices.
pub enum Bolt11Bech32 {}
impl Checksum for Bolt11Bech32 {
/// Extend the max length from the 1023 bytes default.
const CODE_LENGTH: usize = MAX_LENGTH;
// Inherit the other fields from `bech32::Bech32`.
type MidstateRepr = <bech32::Bech32 as Checksum>::MidstateRepr;
const CHECKSUM_LENGTH: usize = bech32::Bech32::CHECKSUM_LENGTH;
const GENERATOR_SH: [Self::MidstateRepr; 5] = bech32::Bech32::GENERATOR_SH;
const TARGET_RESIDUE: Self::MidstateRepr = bech32::Bech32::TARGET_RESIDUE;
}
/// Builder for [`Bolt11Invoice`]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 lightning_invoice;
/// extern crate bitcoin;
///
/// use bitcoin::hashes::Hash;
/// use bitcoin::hashes::sha256;
///
/// use bitcoin::secp256k1::Secp256k1;
/// use bitcoin::secp256k1::SecretKey;
///
/// use lightning_types::payment::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_delta(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 [`TaggedField::Description`] or [`TaggedField::DescriptionHash`]
/// * `H`: exactly one [`TaggedField::PaymentHash`]
/// * `T`: the timestamp is set
/// * `C`: the CLTV expiry is set
/// * `S`: the payment secret is set
/// * `M`: payment metadata is set
///
/// This is not exported to bindings users 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,
M: 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>,
phantom_m: core::marker::PhantomData<M>,
}
/// Represents a syntactically and semantically correct lightning BOLT11 invoice.
///
/// There are three ways to construct a `Bolt11Invoice`:
/// 1. using [`InvoiceBuilder`]
/// 2. using [`Bolt11Invoice::from_signed`]
/// 3. using `str::parse::<Bolt11Invoice>(&str)` (see [`Bolt11Invoice::from_str`])
///
/// [`Bolt11Invoice::from_str`]: crate::Bolt11Invoice#impl-FromStr
#[derive(Eq, PartialEq, Debug, Clone, Hash, Ord, PartialOrd)]
pub struct Bolt11Invoice {
signed_invoice: SignedRawBolt11Invoice,
}
/// 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.
#[derive(Eq, PartialEq, Debug, Clone, Ord, PartialOrd)]
pub enum Bolt11InvoiceDescription {
/// Description of what the invoice is for
Direct(Description),
/// Hash of the description of what the invoice is for
Hash(Sha256),
}
impl Display for Bolt11InvoiceDescription {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Bolt11InvoiceDescription::Direct(desc) => write!(f, "{}", desc.0),
Bolt11InvoiceDescription::Hash(hash) => write!(f, "{}", hash.0),
}
}
}
/// 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.
///
/// This is not exported to bindings users 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, Copy, Ord, PartialOrd)]
pub enum Bolt11InvoiceDescriptionRef<'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),
}
impl<'f> Display for Bolt11InvoiceDescriptionRef<'f> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Bolt11InvoiceDescriptionRef::Direct(desc) => write!(f, "{}", desc.0),
Bolt11InvoiceDescriptionRef::Hash(hash) => write!(f, "{}", hash.0),
}
}
}
/// Represents a signed [`RawBolt11Invoice`] 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 [`RawBolt11Invoice`].
#[derive(Eq, PartialEq, Debug, Clone, Hash, Ord, PartialOrd)]
pub struct SignedRawBolt11Invoice {
/// The raw invoice that the signature belongs to
raw_invoice: RawBolt11Invoice,
/// Hash of the [`RawBolt11Invoice`] that will be used to check the signature.
///
/// * if the `SignedRawBolt11Invoice` 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 `SignedRawBolt11Invoice` was constructed manually the hash will be the calculated hash
/// from the [`RawBolt11Invoice`]
hash: [u8; 32],
/// signature of the payment request
signature: Bolt11InvoiceSignature,
}
/// Represents an syntactically correct [`Bolt11Invoice`] for a payment on the lightning network,
/// but without the signature information.
/// Decoding and encoding should not lead to information loss but may lead to different hashes.
///
/// For methods without docs see the corresponding methods in [`Bolt11Invoice`].
#[derive(Eq, PartialEq, Debug, Clone, Hash, Ord, PartialOrd)]
pub struct RawBolt11Invoice {
/// human readable part
pub hrp: RawHrp,
/// data part
pub data: RawDataPart,
}
/// Data of the [`RawBolt11Invoice`] that is encoded in the human readable part.
///
/// This is not exported to bindings users as we don't yet support `Option<Enum>`
#[derive(Eq, PartialEq, Debug, Clone, Hash, Ord, PartialOrd)]
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>,
}
impl RawHrp {
/// Convert to bech32::Hrp
pub fn to_hrp(&self) -> bech32::Hrp {
let hrp_str = self.to_string();
let s = core::str::from_utf8(&hrp_str.as_bytes()).expect("HRP bytes should be ASCII");
debug_assert!(bech32::Hrp::parse(s).is_ok(), "We should always build BIP 173-valid HRPs");
bech32::Hrp::parse_unchecked(s)
}
}
/// Data of the [`RawBolt11Invoice`] that is encoded in the data part
#[derive(Eq, PartialEq, Debug, Clone, Hash, Ord, PartialOrd)]
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, Hash, Ord, PartialOrd)]
pub struct PositiveTimestamp(Duration);
/// SI prefixes for the human readable part
#[derive(Eq, PartialEq, Debug, Clone, Copy, Hash, Ord, PartialOrd)]
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.
///
/// This is not exported to bindings users 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 crate::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, Ord, PartialOrd)]
pub enum Currency {
/// Bitcoin mainnet
Bitcoin,
/// Bitcoin testnet
BitcoinTestnet,
/// Bitcoin regtest
Regtest,
/// Bitcoin simnet
Simnet,
/// Bitcoin signet
Signet,
}
impl From<Network> for Currency {
fn from(network: Network) -> Self {
match network {
Network::Bitcoin => Currency::Bitcoin,
Network::Testnet => Currency::BitcoinTestnet,
Network::Regtest => Currency::Regtest,
Network::Signet => Currency::Signet,
_ => {
debug_assert!(false, "Need to handle new rust-bitcoin network type");
Currency::Regtest
},
}
}
}
impl From<Currency> for Network {
fn from(currency: Currency) -> Self {
match currency {
Currency::Bitcoin => Network::Bitcoin,
Currency::BitcoinTestnet => Network::Testnet,
Currency::Regtest => Network::Regtest,
Currency::Simnet => Network::Regtest,
Currency::Signet => Network::Signet,
}
}
}
/// Tagged field which may have an unknown tag
///
/// This is not exported to bindings users 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<Fe32>),
}
impl PartialOrd for RawTaggedField {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}
/// Note: `Ord `cannot be simply derived because of `Fe32`.
impl Ord for RawTaggedField {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
match (self, other) {
(RawTaggedField::KnownSemantics(ref a), RawTaggedField::KnownSemantics(ref b)) => {
a.cmp(b)
},
(RawTaggedField::UnknownSemantics(ref a), RawTaggedField::UnknownSemantics(ref b)) => {
a.iter().map(|a| a.to_u8()).cmp(b.iter().map(|b| b.to_u8()))
},
(RawTaggedField::KnownSemantics(..), RawTaggedField::UnknownSemantics(..)) => {
core::cmp::Ordering::Less
},
(RawTaggedField::UnknownSemantics(..), RawTaggedField::KnownSemantics(..)) => {
core::cmp::Ordering::Greater
},
}
}
}
/// Tagged field with known tag
///
/// For descriptions of the enum values please refer to the enclosed type's docs.
///
/// This is not exported to bindings users 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, Ord, PartialOrd)]
pub enum TaggedField {
PaymentHash(Sha256),
Description(Description),
PayeePubKey(PayeePubKey),
DescriptionHash(Sha256),
ExpiryTime(ExpiryTime),
MinFinalCltvExpiryDelta(MinFinalCltvExpiryDelta),
Fallback(Fallback),
PrivateRoute(PrivateRoute),
PaymentSecret(PaymentSecret),
PaymentMetadata(Vec<u8>),
Features(Bolt11InvoiceFeatures),
}
/// SHA-256 hash
#[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct Sha256(
/// This is not exported to bindings users as the native hash types are not currently mapped
pub sha256::Hash,
);
impl Sha256 {
/// Constructs a new [`Sha256`] from the given bytes, which are assumed to be the output of a
/// single sha256 hash.
#[cfg(c_bindings)]
pub fn from_bytes(bytes: &[u8; 32]) -> Self {
Self(sha256::Hash::from_slice(bytes).expect("from_slice only fails if len is not 32"))
}
}
/// Description string
///
/// # Invariants
/// The description can be at most 639 __bytes__ long
#[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd, Default)]
pub struct Description(UntrustedString);
/// Payee public key
#[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
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, Ord, PartialOrd)]
pub struct ExpiryTime(Duration);
/// `min_final_cltv_expiry_delta` to use for the last HTLC in the route
#[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct MinFinalCltvExpiryDelta(pub u64);
/// Fallback address in case no LN payment is possible
#[allow(missing_docs)]
#[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub enum Fallback {
SegWitProgram { version: WitnessVersion, program: Vec<u8> },
PubKeyHash(PubkeyHash),
ScriptHash(ScriptHash),
}
/// Recoverable signature
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct Bolt11InvoiceSignature(pub RecoverableSignature);
impl PartialOrd for Bolt11InvoiceSignature {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Bolt11InvoiceSignature {
fn cmp(&self, other: &Self) -> Ordering {
self.0.serialize_compact().1.cmp(&other.0.serialize_compact().1)
}
}
/// 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, Ord, PartialOrd)]
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_DELTA: 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_PAYMENT_METADATA: u8 = 27;
pub const TAG_FEATURES: u8 = 5;
}
impl InvoiceBuilder<tb::False, 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(currency: Currency) -> Self {
InvoiceBuilder {
currency,
amount: None,
si_prefix: None,
timestamp: None,
tagged_fields: Vec::with_capacity(8),
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,
phantom_m: core::marker::PhantomData,
}
}
}
impl<D: tb::Bool, H: tb::Bool, T: tb::Bool, C: tb::Bool, S: tb::Bool, M: tb::Bool>
InvoiceBuilder<D, H, T, C, S, M>
{
/// 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,
MN: tb::Bool,
>(
self,
) -> InvoiceBuilder<DN, HN, TN, CN, SN, MN> {
InvoiceBuilder::<DN, HN, TN, CN, SN, MN> {
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,
phantom_m: 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 {
// Invoices are denominated in "pico BTC"
let amount = match amount_msat.checked_mul(10) {
Some(amt) => amt,
None => {
self.error = Some(CreationError::InvalidAmount);
return self;
},
};
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, dropping the subsecond part (which is not representable in BOLT 11
/// invoices).
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, M: tb::Bool>
InvoiceBuilder<D, H, tb::True, C, S, M>
{
/// Builds a [`RawBolt11Invoice`] if no [`CreationError`] occurred while construction any of the
/// fields.
pub fn build_raw(self) -> Result<RawBolt11Invoice, 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, tagged_fields };
Ok(RawBolt11Invoice { hrp, data })
}
}
impl<H: tb::Bool, T: tb::Bool, C: tb::Bool, S: tb::Bool, M: tb::Bool>
InvoiceBuilder<tb::False, H, T, C, S, M>
{
/// 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, M> {
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, M> {
self.tagged_fields.push(TaggedField::DescriptionHash(Sha256(description_hash)));
self.set_flags()
}
/// Set the description or description hash. This function is only available if no description (hash) was set.
pub fn invoice_description(
self, description: Bolt11InvoiceDescription,
) -> InvoiceBuilder<tb::True, H, T, C, S, M> {
match description {
Bolt11InvoiceDescription::Direct(desc) => self.description(desc.0 .0),
Bolt11InvoiceDescription::Hash(hash) => self.description_hash(hash.0),
}
}
/// Set the description or description hash. This function is only available if no description (hash) was set.
pub fn invoice_description_ref(
self, description_ref: Bolt11InvoiceDescriptionRef<'_>,
) -> InvoiceBuilder<tb::True, H, T, C, S, M> {
match description_ref {
Bolt11InvoiceDescriptionRef::Direct(desc) => self.description(desc.clone().0 .0),
Bolt11InvoiceDescriptionRef::Hash(hash) => self.description_hash(hash.0),
}
}
}
impl<D: tb::Bool, T: tb::Bool, C: tb::Bool, S: tb::Bool, M: tb::Bool>
InvoiceBuilder<D, tb::False, T, C, S, M>
{
/// 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, M> {
self.tagged_fields.push(TaggedField::PaymentHash(Sha256(hash)));
self.set_flags()
}
}
impl<D: tb::Bool, H: tb::Bool, C: tb::Bool, S: tb::Bool, M: tb::Bool>
InvoiceBuilder<D, H, tb::False, C, S, M>
{
/// Sets the timestamp to a specific [`SystemTime`].
#[cfg(feature = "std")]
pub fn timestamp(mut self, time: SystemTime) -> InvoiceBuilder<D, H, tb::True, C, S, M> {
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, dropping the subsecond part (which
/// is not representable in BOLT 11 invoices).
pub fn duration_since_epoch(
mut self, time: Duration,
) -> InvoiceBuilder<D, H, tb::True, C, S, M> {
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, M> {
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, M: tb::Bool>
InvoiceBuilder<D, H, T, tb::False, S, M>
{
/// Sets `min_final_cltv_expiry_delta`.
pub fn min_final_cltv_expiry_delta(
mut self, min_final_cltv_expiry_delta: u64,
) -> InvoiceBuilder<D, H, T, tb::True, S, M> {
self.tagged_fields.push(TaggedField::MinFinalCltvExpiryDelta(MinFinalCltvExpiryDelta(
min_final_cltv_expiry_delta,
)));
self.set_flags()
}
}
impl<D: tb::Bool, H: tb::Bool, T: tb::Bool, C: tb::Bool, M: tb::Bool>
InvoiceBuilder<D, H, T, C, tb::False, M>
{
/// Sets the payment secret and relevant features.
pub fn payment_secret(
mut self, payment_secret: PaymentSecret,
) -> InvoiceBuilder<D, H, T, C, tb::True, M> {
let mut found_features = false;
for field in self.tagged_fields.iter_mut() {
if let TaggedField::Features(f) = field {
found_features = true;
f.set_variable_length_onion_required();
f.set_payment_secret_required();
}
}
self.tagged_fields.push(TaggedField::PaymentSecret(payment_secret));
if !found_features {
let mut features = Bolt11InvoiceFeatures::empty();
features.set_variable_length_onion_required();
features.set_payment_secret_required();
self.tagged_fields.push(TaggedField::Features(features));
}
self.set_flags()
}
}
impl<D: tb::Bool, H: tb::Bool, T: tb::Bool, C: tb::Bool, S: tb::Bool>
InvoiceBuilder<D, H, T, C, S, tb::False>
{
/// Sets the payment metadata.
///
/// By default features are set to *optionally* allow the sender to include the payment metadata.
/// If you wish to require that the sender include the metadata (and fail to parse the invoice if
/// they don't support payment metadata fields), you need to call
/// [`InvoiceBuilder::require_payment_metadata`] after this.
pub fn payment_metadata(
mut self, payment_metadata: Vec<u8>,
) -> InvoiceBuilder<D, H, T, C, S, tb::True> {
self.tagged_fields.push(TaggedField::PaymentMetadata(payment_metadata));
let mut found_features = false;
for field in self.tagged_fields.iter_mut() {
if let TaggedField::Features(f) = field {
found_features = true;
f.set_payment_metadata_optional();
}
}
if !found_features {
let mut features = Bolt11InvoiceFeatures::empty();
features.set_payment_metadata_optional();
self.tagged_fields.push(TaggedField::Features(features));
}
self.set_flags()
}
}
impl<D: tb::Bool, H: tb::Bool, T: tb::Bool, C: tb::Bool, S: tb::Bool>
InvoiceBuilder<D, H, T, C, S, tb::True>
{
/// Sets forwarding of payment metadata as required. A reader of the invoice which does not
/// support sending payment metadata will fail to read the invoice.
pub fn require_payment_metadata(mut self) -> InvoiceBuilder<D, H, T, C, S, tb::True> {
for field in self.tagged_fields.iter_mut() {
if let TaggedField::Features(f) = field {
f.set_payment_metadata_required();
}
}
self
}
}
impl<D: tb::Bool, H: tb::Bool, T: tb::Bool, C: tb::Bool, M: tb::Bool>
InvoiceBuilder<D, H, T, C, tb::True, M>
{
/// 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<M: tb::Bool> InvoiceBuilder<tb::True, tb::True, tb::True, tb::True, tb::True, M> {
/// 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<Bolt11Invoice, 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<Bolt11Invoice, 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 = Bolt11Invoice { 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 SignedRawBolt11Invoice {
/// Disassembles the `SignedRawBolt11Invoice` into its three parts:
/// 1. raw invoice
/// 2. hash of the raw invoice
/// 3. signature
pub fn into_parts(self) -> (RawBolt11Invoice, [u8; 32], Bolt11InvoiceSignature) {
(self.raw_invoice, self.hash, self.signature)
}
/// The [`RawBolt11Invoice`] which was signed.
pub fn raw_invoice(&self) -> &RawBolt11Invoice {
&self.raw_invoice
}
/// The hash of the [`RawBolt11Invoice`] that was signed.
pub fn signable_hash(&self) -> &[u8; 32] {
&self.hash