-
Notifications
You must be signed in to change notification settings - Fork 131
Expand file tree
/
Copy pathtypes.rs
More file actions
1750 lines (1502 loc) · 55.8 KB
/
types.rs
File metadata and controls
1750 lines (1502 loc) · 55.8 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
// This file is Copyright its original authors, visible in version control history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
// accordance with one or both of these licenses.
// Importing these items ensures they are accessible in the uniffi bindings
// without introducing unused import warnings in lib.rs.
//
// Make sure to add any re-exported items that need to be used in uniffi below.
use std::convert::TryInto;
use std::ops::Deref;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
pub use bip39::Mnemonic;
use bitcoin::hashes::sha256::Hash as Sha256;
use bitcoin::hashes::Hash;
use bitcoin::secp256k1::PublicKey;
pub use bitcoin::{Address, BlockHash, FeeRate, Network, OutPoint, ScriptBuf, Txid};
pub use lightning::chain::channelmonitor::BalanceSource;
pub use lightning::events::{ClosureReason, PaymentFailureReason};
use lightning::ln::channelmanager::PaymentId;
pub use lightning::ln::types::ChannelId;
use lightning::offers::invoice::Bolt12Invoice as LdkBolt12Invoice;
pub use lightning::offers::offer::OfferId;
use lightning::offers::offer::{Amount as LdkAmount, Offer as LdkOffer};
use lightning::offers::refund::Refund as LdkRefund;
use lightning::onion_message::dns_resolution::HumanReadableName as LdkHumanReadableName;
pub use lightning::routing::gossip::{NodeAlias, NodeId, RoutingFees};
pub use lightning::routing::router::RouteParametersConfig;
use lightning::util::ser::Writeable;
use lightning_invoice::{Bolt11Invoice as LdkBolt11Invoice, Bolt11InvoiceDescriptionRef};
pub use lightning_invoice::{Description, SignedRawBolt11Invoice};
pub use lightning_liquidity::lsps0::ser::LSPSDateTime;
pub use lightning_liquidity::lsps1::msgs::{
LSPS1ChannelInfo, LSPS1OrderId, LSPS1OrderParams, LSPS1PaymentState,
};
pub use lightning_types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
pub use lightning_types::string::UntrustedString;
pub use vss_client::headers::{VssHeaderProvider, VssHeaderProviderError};
use crate::builder::sanitize_alias;
pub use crate::config::{
default_config, AnchorChannelsConfig, BackgroundSyncConfig, ElectrumSyncConfig,
EsploraSyncConfig, MaxDustHTLCExposure, SyncTimeoutsConfig,
};
pub use crate::entropy::{generate_entropy_mnemonic, EntropyError, NodeEntropy, WordCount};
use crate::error::Error;
pub use crate::graph::{ChannelInfo, ChannelUpdateInfo, NodeAnnouncementInfo, NodeInfo};
pub use crate::liquidity::{LSPS1OrderStatus, LSPS2ServiceConfig};
pub use crate::logger::{LogLevel, LogRecord, LogWriter};
pub use crate::payment::store::{
Channel, ConfirmationStatus, LSPFeeLimits, PaymentDirection, PaymentKind, PaymentStatus,
TransactionType,
};
pub use crate::payment::UnifiedPaymentResult;
use crate::{hex_utils, SocketAddress, UniffiCustomTypeConverter, UserChannelId};
impl UniffiCustomTypeConverter for PublicKey {
type Builtin = String;
fn into_custom(val: Self::Builtin) -> uniffi::Result<Self> {
if let Ok(key) = PublicKey::from_str(&val) {
return Ok(key);
}
Err(Error::InvalidPublicKey.into())
}
fn from_custom(obj: Self) -> Self::Builtin {
obj.to_string()
}
}
impl UniffiCustomTypeConverter for NodeId {
type Builtin = String;
fn into_custom(val: Self::Builtin) -> uniffi::Result<Self> {
if let Ok(key) = NodeId::from_str(&val) {
return Ok(key);
}
Err(Error::InvalidNodeId.into())
}
fn from_custom(obj: Self) -> Self::Builtin {
obj.to_string()
}
}
impl UniffiCustomTypeConverter for Address {
type Builtin = String;
fn into_custom(val: Self::Builtin) -> uniffi::Result<Self> {
if let Ok(addr) = Address::from_str(&val) {
return Ok(addr.assume_checked());
}
Err(Error::InvalidAddress.into())
}
fn from_custom(obj: Self) -> Self::Builtin {
obj.to_string()
}
}
impl UniffiCustomTypeConverter for ScriptBuf {
type Builtin = String;
fn into_custom(val: Self::Builtin) -> uniffi::Result<Self> {
if let Ok(key) = ScriptBuf::from_hex(&val) {
return Ok(key);
}
Err(Error::InvalidScriptPubKey.into())
}
fn from_custom(obj: Self) -> Self::Builtin {
obj.to_string()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OfferAmount {
Bitcoin { amount_msats: u64 },
Currency { iso4217_code: String, amount: u64 },
}
impl From<LdkAmount> for OfferAmount {
fn from(ldk_amount: LdkAmount) -> Self {
match ldk_amount {
LdkAmount::Bitcoin { amount_msats } => OfferAmount::Bitcoin { amount_msats },
LdkAmount::Currency { iso4217_code, amount } => {
OfferAmount::Currency { iso4217_code: iso4217_code.as_str().to_owned(), amount }
},
}
}
}
/// An `Offer` is a potentially long-lived proposal for payment of a good or service.
///
/// An offer is a precursor to an [`InvoiceRequest`]. A merchant publishes an offer from which a
/// customer may request an [`Bolt12Invoice`] for a specific quantity and using an amount sufficient
/// to cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
///
/// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
/// latter.
///
/// Through the use of [`BlindedMessagePath`]s, offers provide recipient privacy.
///
/// [`InvoiceRequest`]: lightning::offers::invoice_request::InvoiceRequest
/// [`Bolt12Invoice`]: lightning::offers::invoice::Bolt12Invoice
/// [`Offer`]: lightning::offers::Offer:amount
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Offer {
pub(crate) inner: LdkOffer,
}
impl Offer {
pub fn from_str(offer_str: &str) -> Result<Self, Error> {
offer_str.parse()
}
/// Returns the id of the offer.
pub fn id(&self) -> OfferId {
OfferId(self.inner.id().0)
}
/// Whether the offer has expired.
pub fn is_expired(&self) -> bool {
self.inner.is_expired()
}
/// A complete description of the purpose of the payment.
///
/// Intended to be displayed to the user but with the caveat that it has not been verified in any way.
pub fn offer_description(&self) -> Option<String> {
self.inner.description().map(|printable| printable.to_string())
}
/// The issuer of the offer, possibly beginning with `user@domain` or `domain`.
///
/// Intended to be displayed to the user but with the caveat that it has not been verified in any way.
pub fn issuer(&self) -> Option<String> {
self.inner.issuer().map(|printable| printable.to_string())
}
/// The minimum amount required for a successful payment of a single item.
pub fn amount(&self) -> Option<OfferAmount> {
self.inner.amount().map(|amount| amount.into())
}
/// Returns whether the given quantity is valid for the offer.
pub fn is_valid_quantity(&self, quantity: u64) -> bool {
self.inner.is_valid_quantity(quantity)
}
/// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
///
/// [`InvoiceRequest`]: lightning::offers::invoice_request::InvoiceRequest
pub fn expects_quantity(&self) -> bool {
self.inner.expects_quantity()
}
/// Returns whether the given chain is supported by the offer.
pub fn supports_chain(&self, chain: Network) -> bool {
self.inner.supports_chain(chain.chain_hash())
}
/// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
///
/// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
/// for the selected chain.
pub fn chains(&self) -> Vec<Network> {
self.inner.chains().into_iter().filter_map(Network::from_chain_hash).collect()
}
/// Opaque bytes set by the originator.
///
/// Useful for authentication and validating fields since it is reflected in `invoice_request`
/// messages along with all the other fields from the `offer`.
pub fn metadata(&self) -> Option<Vec<u8>> {
self.inner.metadata().cloned()
}
/// Seconds since the Unix epoch when an invoice should no longer be requested.
///
/// If `None`, the offer does not expire.
pub fn absolute_expiry_seconds(&self) -> Option<u64> {
self.inner.absolute_expiry().map(|duration| duration.as_secs())
}
/// The public key corresponding to the key used by the recipient to sign invoices.
/// - If [`Offer::paths`] is empty, MUST be `Some` and contain the recipient's node id for
/// sending an [`InvoiceRequest`].
/// - If [`Offer::paths`] is not empty, MAY be `Some` and contain a transient id.
/// - If `None`, the signing pubkey will be the final blinded node id from the
/// [`BlindedMessagePath`] in [`Offer::paths`] used to send the [`InvoiceRequest`].
///
/// See also [`Bolt12Invoice::signing_pubkey`].
///
/// [`InvoiceRequest`]: lightning::offers::invoice_request::InvoiceRequest
/// [`Bolt12Invoice::signing_pubkey`]: lightning::offers::invoice::Bolt12Invoice::signing_pubkey
pub fn issuer_signing_pubkey(&self) -> Option<PublicKey> {
self.inner.issuer_signing_pubkey()
}
}
impl std::str::FromStr for Offer {
type Err = Error;
fn from_str(offer_str: &str) -> Result<Self, Self::Err> {
offer_str
.parse::<LdkOffer>()
.map(|offer| Offer { inner: offer })
.map_err(|_| Error::InvalidOffer)
}
}
impl From<LdkOffer> for Offer {
fn from(offer: LdkOffer) -> Self {
Offer { inner: offer }
}
}
impl Deref for Offer {
type Target = LdkOffer;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl AsRef<LdkOffer> for Offer {
fn as_ref(&self) -> &LdkOffer {
self.deref()
}
}
impl std::fmt::Display for Offer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.inner)
}
}
/// A struct containing the two parts of a BIP 353 Human-Readable Name - the user and domain parts.
///
/// The `user` and `domain` parts combined cannot exceed 231 bytes in length;
/// each DNS label within them must be non-empty and no longer than 63 bytes.
///
/// If you intend to handle non-ASCII `user` or `domain` parts, you must handle [Homograph Attacks]
/// and do punycode en-/de-coding yourself. This struct will always handle only plain ASCII `user`
/// and `domain` parts.
///
/// This struct can also be used for LN-Address recipients.
///
/// [Homograph Attacks]: https://en.wikipedia.org/wiki/IDN_homograph_attack
pub struct HumanReadableName {
pub(crate) inner: LdkHumanReadableName,
}
impl HumanReadableName {
/// Constructs a new [`HumanReadableName`] from the standard encoding - `user`@`domain`.
///
/// If `user` includes the standard BIP 353 ₿ prefix it is automatically removed as required by
/// BIP 353.
pub fn from_encoded(encoded: &str) -> Result<Self, Error> {
let hrn = match LdkHumanReadableName::from_encoded(encoded) {
Ok(hrn) => Ok(hrn),
Err(_) => Err(Error::HrnParsingFailed),
}?;
Ok(Self { inner: hrn })
}
/// Gets the `user` part of this Human-Readable Name
pub fn user(&self) -> String {
self.inner.user().to_string()
}
/// Gets the `domain` part of this Human-Readable Name
pub fn domain(&self) -> String {
self.inner.domain().to_string()
}
}
impl From<LdkHumanReadableName> for HumanReadableName {
fn from(ldk_hrn: LdkHumanReadableName) -> Self {
HumanReadableName { inner: ldk_hrn }
}
}
impl From<HumanReadableName> for LdkHumanReadableName {
fn from(wrapper: HumanReadableName) -> Self {
wrapper.inner
}
}
impl Deref for HumanReadableName {
type Target = LdkHumanReadableName;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl AsRef<LdkHumanReadableName> for HumanReadableName {
fn as_ref(&self) -> &LdkHumanReadableName {
self.deref()
}
}
/// A `Refund` is a request to send an [`Bolt12Invoice`] without a preceding [`Offer`].
///
/// Typically, after an invoice is paid, the recipient may publish a refund allowing the sender to
/// recoup their funds. A refund may be used more generally as an "offer for money", such as with a
/// bitcoin ATM.
///
/// [`Bolt12Invoice`]: lightning::offers::invoice::Bolt12Invoice
/// [`Offer`]: lightning::offers::offer::Offer
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Refund {
pub(crate) inner: LdkRefund,
}
impl Refund {
pub fn from_str(refund_str: &str) -> Result<Self, Error> {
refund_str.parse()
}
/// A complete description of the purpose of the refund.
///
/// Intended to be displayed to the user but with the caveat that it has not been verified in any way.
pub fn refund_description(&self) -> String {
self.inner.description().to_string()
}
/// Seconds since the Unix epoch when an invoice should no longer be sent.
///
/// If `None`, the refund does not expire.
pub fn absolute_expiry_seconds(&self) -> Option<u64> {
self.inner.absolute_expiry().map(|duration| duration.as_secs())
}
/// Whether the refund has expired.
pub fn is_expired(&self) -> bool {
self.inner.is_expired()
}
/// The issuer of the refund, possibly beginning with `user@domain` or `domain`.
///
/// Intended to be displayed to the user but with the caveat that it has not been verified in any way.
pub fn issuer(&self) -> Option<String> {
self.inner.issuer().map(|printable| printable.to_string())
}
/// An unpredictable series of bytes, typically containing information about the derivation of
/// [`payer_signing_pubkey`].
///
/// [`payer_signing_pubkey`]: Self::payer_signing_pubkey
pub fn payer_metadata(&self) -> Vec<u8> {
self.inner.payer_metadata().to_vec()
}
/// A chain that the refund is valid for.
pub fn chain(&self) -> Option<Network> {
Network::try_from(self.inner.chain()).ok()
}
/// The amount to refund in msats (i.e., the minimum lightning-payable unit for [`chain`]).
///
/// [`chain`]: Self::chain
pub fn amount_msats(&self) -> u64 {
self.inner.amount_msats()
}
/// The quantity of an item that refund is for.
pub fn quantity(&self) -> Option<u64> {
self.inner.quantity()
}
/// A public node id to send to in the case where there are no [`paths`].
///
/// Otherwise, a possibly transient pubkey.
///
/// [`paths`]: lightning::offers::refund::Refund::paths
pub fn payer_signing_pubkey(&self) -> PublicKey {
self.inner.payer_signing_pubkey()
}
/// Payer provided note to include in the invoice.
pub fn payer_note(&self) -> Option<String> {
self.inner.payer_note().map(|printable| printable.to_string())
}
}
impl std::str::FromStr for Refund {
type Err = Error;
fn from_str(refund_str: &str) -> Result<Self, Self::Err> {
refund_str
.parse::<LdkRefund>()
.map(|refund| Refund { inner: refund })
.map_err(|_| Error::InvalidRefund)
}
}
impl From<LdkRefund> for Refund {
fn from(refund: LdkRefund) -> Self {
Refund { inner: refund }
}
}
impl Deref for Refund {
type Target = LdkRefund;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl AsRef<LdkRefund> for Refund {
fn as_ref(&self) -> &LdkRefund {
self.deref()
}
}
impl std::fmt::Display for Refund {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.inner)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bolt12Invoice {
pub(crate) inner: LdkBolt12Invoice,
}
impl Bolt12Invoice {
pub fn from_str(invoice_str: &str) -> Result<Self, Error> {
invoice_str.parse()
}
/// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
pub fn payment_hash(&self) -> PaymentHash {
PaymentHash(self.inner.payment_hash().0)
}
/// The minimum amount required for a successful payment of the invoice.
pub fn amount_msats(&self) -> u64 {
self.inner.amount_msats()
}
/// The minimum amount required for a successful payment of a single item.
///
/// From [`Offer::amount`]; `None` if the invoice was created in response to a [`Refund`] or if
/// the [`Offer`] did not set it.
///
/// [`Offer`]: lightning::offers::offer::Offer
/// [`Offer::amount`]: lightning::offers::offer::Offer::amount
/// [`Refund`]: lightning::offers::refund::Refund
pub fn amount(&self) -> Option<OfferAmount> {
self.inner.amount().map(|amount| amount.into())
}
/// A typically transient public key corresponding to the key used to sign the invoice.
///
/// If the invoices was created in response to an [`Offer`], then this will be:
/// - [`Offer::issuer_signing_pubkey`] if it's `Some`, otherwise
/// - the final blinded node id from a [`BlindedMessagePath`] in [`Offer::paths`] if `None`.
///
/// If the invoice was created in response to a [`Refund`], then it is a valid pubkey chosen by
/// the recipient.
///
/// [`Offer`]: lightning::offers::offer::Offer
/// [`Offer::issuer_signing_pubkey`]: lightning::offers::offer::Offer::issuer_signing_pubkey
/// [`Offer::paths`]: lightning::offers::offer::Offer::paths
/// [`Refund`]: lightning::offers::refund::Refund
pub fn signing_pubkey(&self) -> PublicKey {
self.inner.signing_pubkey()
}
/// Duration since the Unix epoch when the invoice was created.
pub fn created_at(&self) -> u64 {
self.inner.created_at().as_secs()
}
/// Seconds since the Unix epoch when an invoice should no longer be requested.
///
/// From [`Offer::absolute_expiry`] or [`Refund::absolute_expiry`].
///
/// [`Offer::absolute_expiry`]: lightning::offers::offer::Offer::absolute_expiry
pub fn absolute_expiry_seconds(&self) -> Option<u64> {
self.inner.absolute_expiry().map(|duration| duration.as_secs())
}
/// When the invoice has expired and therefore should no longer be paid.
pub fn relative_expiry(&self) -> u64 {
self.inner.relative_expiry().as_secs()
}
/// Whether the invoice has expired.
pub fn is_expired(&self) -> bool {
self.inner.is_expired()
}
/// A complete description of the purpose of the originating offer or refund.
///
/// From [`Offer::description`] or [`Refund::description`].
///
/// [`Offer::description`]: lightning::offers::offer::Offer::description
/// [`Refund::description`]: lightning::offers::refund::Refund::description
pub fn invoice_description(&self) -> Option<String> {
self.inner.description().map(|printable| printable.to_string())
}
/// The issuer of the offer or refund.
///
/// From [`Offer::issuer`] or [`Refund::issuer`].
///
/// [`Offer::issuer`]: lightning::offers::offer::Offer::issuer
/// [`Refund::issuer`]: lightning::offers::refund::Refund::issuer
pub fn issuer(&self) -> Option<String> {
self.inner.issuer().map(|printable| printable.to_string())
}
/// A payer-provided note reflected back in the invoice.
///
/// From [`InvoiceRequest::payer_note`] or [`Refund::payer_note`].
///
/// [`Refund::payer_note`]: lightning::offers::refund::Refund::payer_note
pub fn payer_note(&self) -> Option<String> {
self.inner.payer_note().map(|note| note.to_string())
}
/// Opaque bytes set by the originating [`Offer`].
///
/// From [`Offer::metadata`]; `None` if the invoice was created in response to a [`Refund`] or
/// if the [`Offer`] did not set it.
///
/// [`Offer`]: lightning::offers::offer::Offer
/// [`Offer::metadata`]: lightning::offers::offer::Offer::metadata
/// [`Refund`]: lightning::offers::refund::Refund
pub fn metadata(&self) -> Option<Vec<u8>> {
self.inner.metadata().cloned()
}
/// The quantity of items requested or refunded for.
///
/// From [`InvoiceRequest::quantity`] or [`Refund::quantity`].
///
/// [`Refund::quantity`]: lightning::offers::refund::Refund::quantity
pub fn quantity(&self) -> Option<u64> {
self.inner.quantity()
}
/// Hash that was used for signing the invoice.
pub fn signable_hash(&self) -> Vec<u8> {
self.inner.signable_hash().to_vec()
}
/// A possibly transient pubkey used to sign the invoice request or to send an invoice for a
/// refund in case there are no [`message_paths`].
///
/// [`message_paths`]: lightning::offers::invoice::Bolt12Invoice
pub fn payer_signing_pubkey(&self) -> PublicKey {
self.inner.payer_signing_pubkey()
}
/// The public key used by the recipient to sign invoices.
///
/// From [`Offer::issuer_signing_pubkey`] and may be `None`; also `None` if the invoice was
/// created in response to a [`Refund`].
///
/// [`Offer::issuer_signing_pubkey`]: lightning::offers::offer::Offer::issuer_signing_pubkey
/// [`Refund`]: lightning::offers::refund::Refund
pub fn issuer_signing_pubkey(&self) -> Option<PublicKey> {
self.inner.issuer_signing_pubkey()
}
/// The chain that must be used when paying the invoice; selected from [`offer_chains`] if the
/// invoice originated from an offer.
///
/// From [`InvoiceRequest::chain`] or [`Refund::chain`].
///
/// [`offer_chains`]: lightning::offers::invoice::Bolt12Invoice::offer_chains
/// [`InvoiceRequest::chain`]: lightning::offers::invoice_request::InvoiceRequest::chain
/// [`Refund::chain`]: lightning::offers::refund::Refund::chain
pub fn chain(&self) -> Vec<u8> {
self.inner.chain().to_bytes().to_vec()
}
/// The chains that may be used when paying a requested invoice.
///
/// From [`Offer::chains`]; `None` if the invoice was created in response to a [`Refund`].
///
/// [`Offer::chains`]: lightning::offers::offer::Offer::chains
/// [`Refund`]: lightning::offers::refund::Refund
pub fn offer_chains(&self) -> Option<Vec<Vec<u8>>> {
self.inner
.offer_chains()
.map(|chains| chains.iter().map(|chain| chain.to_bytes().to_vec()).collect())
}
/// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
/// least-preferred.
pub fn fallback_addresses(&self) -> Vec<Address> {
self.inner.fallbacks()
}
/// Writes `self` out to a `Vec<u8>`.
pub fn encode(&self) -> Vec<u8> {
self.inner.encode()
}
}
impl std::str::FromStr for Bolt12Invoice {
type Err = Error;
fn from_str(invoice_str: &str) -> Result<Self, Self::Err> {
if let Some(bytes_vec) = hex_utils::to_vec(invoice_str) {
if let Ok(invoice) = LdkBolt12Invoice::try_from(bytes_vec) {
return Ok(Bolt12Invoice { inner: invoice });
}
}
Err(Error::InvalidInvoice)
}
}
impl From<LdkBolt12Invoice> for Bolt12Invoice {
fn from(invoice: LdkBolt12Invoice) -> Self {
Bolt12Invoice { inner: invoice }
}
}
impl Deref for Bolt12Invoice {
type Target = LdkBolt12Invoice;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl AsRef<LdkBolt12Invoice> for Bolt12Invoice {
fn as_ref(&self) -> &LdkBolt12Invoice {
self.deref()
}
}
impl UniffiCustomTypeConverter for OfferId {
type Builtin = String;
fn into_custom(val: Self::Builtin) -> uniffi::Result<Self> {
if let Some(bytes_vec) = hex_utils::to_vec(&val) {
let bytes_res = bytes_vec.try_into();
if let Ok(bytes) = bytes_res {
return Ok(OfferId(bytes));
}
}
Err(Error::InvalidOfferId.into())
}
fn from_custom(obj: Self) -> Self::Builtin {
hex_utils::to_string(&obj.0)
}
}
impl UniffiCustomTypeConverter for PaymentId {
type Builtin = String;
fn into_custom(val: Self::Builtin) -> uniffi::Result<Self> {
if let Some(bytes_vec) = hex_utils::to_vec(&val) {
let bytes_res = bytes_vec.try_into();
if let Ok(bytes) = bytes_res {
return Ok(PaymentId(bytes));
}
}
Err(Error::InvalidPaymentId.into())
}
fn from_custom(obj: Self) -> Self::Builtin {
hex_utils::to_string(&obj.0)
}
}
impl UniffiCustomTypeConverter for PaymentHash {
type Builtin = String;
fn into_custom(val: Self::Builtin) -> uniffi::Result<Self> {
if let Ok(hash) = Sha256::from_str(&val) {
Ok(PaymentHash(hash.to_byte_array()))
} else {
Err(Error::InvalidPaymentHash.into())
}
}
fn from_custom(obj: Self) -> Self::Builtin {
Sha256::from_slice(&obj.0).unwrap().to_string()
}
}
impl UniffiCustomTypeConverter for PaymentPreimage {
type Builtin = String;
fn into_custom(val: Self::Builtin) -> uniffi::Result<Self> {
if let Some(bytes_vec) = hex_utils::to_vec(&val) {
let bytes_res = bytes_vec.try_into();
if let Ok(bytes) = bytes_res {
return Ok(PaymentPreimage(bytes));
}
}
Err(Error::InvalidPaymentPreimage.into())
}
fn from_custom(obj: Self) -> Self::Builtin {
hex_utils::to_string(&obj.0)
}
}
impl UniffiCustomTypeConverter for PaymentSecret {
type Builtin = String;
fn into_custom(val: Self::Builtin) -> uniffi::Result<Self> {
if let Some(bytes_vec) = hex_utils::to_vec(&val) {
let bytes_res = bytes_vec.try_into();
if let Ok(bytes) = bytes_res {
return Ok(PaymentSecret(bytes));
}
}
Err(Error::InvalidPaymentSecret.into())
}
fn from_custom(obj: Self) -> Self::Builtin {
hex_utils::to_string(&obj.0)
}
}
impl UniffiCustomTypeConverter for ChannelId {
type Builtin = String;
fn into_custom(val: Self::Builtin) -> uniffi::Result<Self> {
if let Some(hex_vec) = hex_utils::to_vec(&val) {
if hex_vec.len() == 32 {
let mut channel_id = [0u8; 32];
channel_id.copy_from_slice(&hex_vec[..]);
return Ok(Self(channel_id));
}
}
Err(Error::InvalidChannelId.into())
}
fn from_custom(obj: Self) -> Self::Builtin {
hex_utils::to_string(&obj.0)
}
}
impl UniffiCustomTypeConverter for UserChannelId {
type Builtin = String;
fn into_custom(val: Self::Builtin) -> uniffi::Result<Self> {
Ok(UserChannelId(u128::from_str(&val).map_err(|_| Error::InvalidChannelId)?))
}
fn from_custom(obj: Self) -> Self::Builtin {
obj.0.to_string()
}
}
impl UniffiCustomTypeConverter for Txid {
type Builtin = String;
fn into_custom(val: Self::Builtin) -> uniffi::Result<Self> {
Ok(Txid::from_str(&val)?)
}
fn from_custom(obj: Self) -> Self::Builtin {
obj.to_string()
}
}
impl UniffiCustomTypeConverter for BlockHash {
type Builtin = String;
fn into_custom(val: Self::Builtin) -> uniffi::Result<Self> {
Ok(BlockHash::from_str(&val)?)
}
fn from_custom(obj: Self) -> Self::Builtin {
obj.to_string()
}
}
impl UniffiCustomTypeConverter for Mnemonic {
type Builtin = String;
fn into_custom(val: Self::Builtin) -> uniffi::Result<Self> {
Ok(Mnemonic::from_str(&val).map_err(|_| Error::InvalidSecretKey)?)
}
fn from_custom(obj: Self) -> Self::Builtin {
obj.to_string()
}
}
impl UniffiCustomTypeConverter for SocketAddress {
type Builtin = String;
fn into_custom(val: Self::Builtin) -> uniffi::Result<Self> {
Ok(SocketAddress::from_str(&val).map_err(|_| Error::InvalidSocketAddress)?)
}
fn from_custom(obj: Self) -> Self::Builtin {
obj.to_string()
}
}
impl UniffiCustomTypeConverter for UntrustedString {
type Builtin = String;
fn into_custom(val: Self::Builtin) -> uniffi::Result<Self> {
Ok(UntrustedString(val))
}
fn from_custom(obj: Self) -> Self::Builtin {
obj.to_string()
}
}
impl UniffiCustomTypeConverter for NodeAlias {
type Builtin = String;
fn into_custom(val: Self::Builtin) -> uniffi::Result<Self> {
Ok(sanitize_alias(&val).map_err(|_| Error::InvalidNodeAlias)?)
}
fn from_custom(obj: Self) -> Self::Builtin {
obj.to_string()
}
}
/// 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(Debug, Clone, PartialEq, Eq)]
pub enum Bolt11InvoiceDescription {
/// Contains a full description.
Direct {
/// Description of what the invoice is for
description: String,
},
/// Contains a hash.
Hash {
/// Hash of the description of what the invoice is for
hash: String,
},
}
impl TryFrom<&Bolt11InvoiceDescription> for lightning_invoice::Bolt11InvoiceDescription {
type Error = Error;
fn try_from(value: &Bolt11InvoiceDescription) -> Result<Self, Self::Error> {
match value {
Bolt11InvoiceDescription::Direct { description } => {
Description::new(description.clone())
.map(lightning_invoice::Bolt11InvoiceDescription::Direct)
.map_err(|_| Error::InvoiceCreationFailed)
},
Bolt11InvoiceDescription::Hash { hash } => Sha256::from_str(&hash)
.map(lightning_invoice::Sha256)
.map(lightning_invoice::Bolt11InvoiceDescription::Hash)
.map_err(|_| Error::InvoiceCreationFailed),
}
}
}
impl From<lightning_invoice::Bolt11InvoiceDescription> for Bolt11InvoiceDescription {
fn from(value: lightning_invoice::Bolt11InvoiceDescription) -> Self {
match value {
lightning_invoice::Bolt11InvoiceDescription::Direct(description) => {
Bolt11InvoiceDescription::Direct { description: description.to_string() }
},
lightning_invoice::Bolt11InvoiceDescription::Hash(hash) => {
Bolt11InvoiceDescription::Hash { hash: hex_utils::to_string(hash.0.as_ref()) }
},
}
}
}
impl<'a> From<Bolt11InvoiceDescriptionRef<'a>> for Bolt11InvoiceDescription {
fn from(value: Bolt11InvoiceDescriptionRef<'a>) -> Self {
match value {
lightning_invoice::Bolt11InvoiceDescriptionRef::Direct(description) => {
Bolt11InvoiceDescription::Direct { description: description.to_string() }
},
lightning_invoice::Bolt11InvoiceDescriptionRef::Hash(hash) => {
Bolt11InvoiceDescription::Hash { hash: hex_utils::to_string(hash.0.as_ref()) }
},
}
}
}
/// Enum representing the crypto currencies (or networks) supported by this library
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum Currency {
/// Bitcoin mainnet
Bitcoin,
/// Bitcoin testnet
BitcoinTestnet,
/// Bitcoin regtest
Regtest,
/// Bitcoin simnet
Simnet,
/// Bitcoin signet
Signet,
}
impl From<lightning_invoice::Currency> for Currency {
fn from(currency: lightning_invoice::Currency) -> Self {
match currency {
lightning_invoice::Currency::Bitcoin => Currency::Bitcoin,
lightning_invoice::Currency::BitcoinTestnet => Currency::BitcoinTestnet,
lightning_invoice::Currency::Regtest => Currency::Regtest,
lightning_invoice::Currency::Simnet => Currency::Simnet,
lightning_invoice::Currency::Signet => Currency::Signet,
}
}
}
/// A channel descriptor for a hop along a payment path.
///
/// While this generally comes from BOLT 11's `r` field, this struct includes more fields than are
/// available in BOLT 11.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RouteHintHop {
/// The node_id of the non-target end of the route
pub src_node_id: PublicKey,
/// The short_channel_id of this channel
pub short_channel_id: u64,
/// The fees which must be paid to use this channel
pub fees: RoutingFees,
/// The difference in CLTV values between this node and the next node.
pub cltv_expiry_delta: u16,
/// The minimum value, in msat, which must be relayed to the next hop.
pub htlc_minimum_msat: Option<u64>,
/// The maximum value in msat available for routing with a single HTLC.
pub htlc_maximum_msat: Option<u64>,
}
impl From<lightning::routing::router::RouteHintHop> for RouteHintHop {
fn from(hop: lightning::routing::router::RouteHintHop) -> Self {
Self {
src_node_id: hop.src_node_id,
short_channel_id: hop.short_channel_id,
cltv_expiry_delta: hop.cltv_expiry_delta,
htlc_minimum_msat: hop.htlc_minimum_msat,
htlc_maximum_msat: hop.htlc_maximum_msat,
fees: hop.fees,
}
}
}
/// Represents a syntactically and semantically correct lightning BOLT11 invoice.