forked from jl777/SuperNET
-
Notifications
You must be signed in to change notification settings - Fork 97
/
lightning.rs
1462 lines (1301 loc) · 62.2 KB
/
lightning.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
pub mod ln_conf;
pub(crate) mod ln_db;
pub mod ln_errors;
pub mod ln_events;
mod ln_filesystem_persister;
pub mod ln_p2p;
pub mod ln_platform;
pub(crate) mod ln_serialization;
mod ln_sql;
pub mod ln_storage;
pub mod ln_utils;
use crate::coin_errors::{MyAddressError, ValidatePaymentResult};
use crate::lightning::ln_utils::{filter_channels, pay_invoice_with_max_total_cltv_expiry_delta, PaymentError};
use crate::utxo::rpc_clients::UtxoRpcClientEnum;
use crate::utxo::utxo_common::{big_decimal_from_sat, big_decimal_from_sat_unsigned};
use crate::utxo::{sat_from_big_decimal, utxo_common, BlockchainNetwork};
use crate::{BalanceFut, CheckIfMyPaymentSentArgs, CoinBalance, CoinFutSpawner, ConfirmPaymentInput, DexFee,
FeeApproxStage, FoundSwapTxSpend, HistorySyncState, MakerSwapTakerCoin, MarketCoinOps, MmCoin, MmCoinEnum,
NegotiateSwapContractAddrErr, PaymentInstructionArgs, PaymentInstructions, PaymentInstructionsErr,
RawTransactionError, RawTransactionFut, RawTransactionRequest, RawTransactionResult, RefundError,
RefundPaymentArgs, RefundResult, SearchForSwapTxSpendInput, SendMakerPaymentSpendPreimageInput,
SendPaymentArgs, SignRawTransactionRequest, SignatureError, SignatureResult, SpendPaymentArgs, SwapOps,
TakerSwapMakerCoin, TradeFee, TradePreimageFut, TradePreimageResult, TradePreimageValue, Transaction,
TransactionEnum, TransactionErr, TransactionFut, TransactionResult, TxMarshalingErr,
UnexpectedDerivationMethod, UtxoStandardCoin, ValidateAddressResult, ValidateFeeArgs,
ValidateInstructionsErr, ValidateOtherPubKeyErr, ValidatePaymentError, ValidatePaymentFut,
ValidatePaymentInput, ValidateWatcherSpendInput, VerificationError, VerificationResult,
WaitForHTLCTxSpendArgs, WatcherOps, WatcherReward, WatcherRewardError, WatcherSearchForSwapTxSpendInput,
WatcherValidatePaymentInput, WatcherValidateTakerFeeInput, WithdrawError, WithdrawFut, WithdrawRequest};
use async_trait::async_trait;
use bitcoin::bech32::ToBase32;
use bitcoin::hashes::Hash;
use bitcoin_hashes::sha256::Hash as Sha256;
use bitcrypto::ChecksumType;
use bitcrypto::{dhash256, ripemd160};
use common::custom_futures::repeatable::{Ready, Retry};
use common::executor::{AbortableSystem, AbortedError, Timer};
use common::log::{error, info, LogOnError, LogState};
use common::{async_blocking, get_local_duration_since_epoch, log, now_sec, Future01CompatExt, PagingOptionsEnum};
use db_common::sqlite::rusqlite::Error as SqlError;
use futures::{FutureExt, TryFutureExt};
use futures01::Future;
use keys::{hash::H256, CompactSignature, KeyPair, Private, Public};
use lightning::chain::keysinterface::{KeysInterface, KeysManager, Recipient};
use lightning::ln::channelmanager::{ChannelDetails, MIN_FINAL_CLTV_EXPIRY};
use lightning::ln::{PaymentHash, PaymentPreimage};
use lightning::routing::router::{DefaultRouter, PaymentParameters, RouteParameters, Router as RouterTrait};
use lightning::util::ser::{Readable, Writeable};
use lightning_background_processor::BackgroundProcessor;
use lightning_invoice::payment::Payer;
use lightning_invoice::{payment, CreationError, InvoiceBuilder, SignOrCreationError};
use lightning_invoice::{Invoice, InvoiceDescription};
use ln_conf::{LightningCoinConf, PlatformCoinConfirmationTargets};
use ln_db::{DBChannelDetails, HTLCStatus, LightningDB, PaymentInfo, PaymentType};
use ln_errors::{EnableLightningError, EnableLightningResult};
use ln_events::LightningEventHandler;
use ln_filesystem_persister::LightningFilesystemPersister;
use ln_p2p::PeerManager;
use ln_platform::Platform;
use ln_serialization::{ChannelDetailsForRPC, PublicKeyForRPC};
use ln_sql::SqliteLightningDB;
use ln_storage::{NetworkGraph, NodesAddressesMapShared, Scorer, TrustedNodesShared};
use ln_utils::{ChainMonitor, ChannelManager, Router};
use mm2_core::mm_ctx::MmArc;
use mm2_err_handle::prelude::*;
use mm2_net::ip_addr::myipaddr;
use mm2_number::{BigDecimal, MmNumber};
use parking_lot::Mutex as PaMutex;
use rpc::v1::types::{Bytes as BytesJson, H256 as H256Json};
use script::TransactionInputSigner;
use secp256k1v24::PublicKey;
use serde::Deserialize;
use serde_json::Value as Json;
use std::collections::{HashMap, HashSet};
use std::convert::TryInto;
use std::fmt;
use std::io::Cursor;
use std::net::SocketAddr;
use std::str::FromStr;
use std::sync::Arc;
use uuid::Uuid;
const WAIT_FOR_REFUND_INTERVAL: f64 = 60.;
pub const DEFAULT_INVOICE_EXPIRY: u32 = 3600;
pub type InvoicePayer<E> = payment::InvoicePayer<Arc<ChannelManager>, Router, Arc<LogState>, E>;
#[derive(Clone)]
pub struct LightningCoin {
pub platform: Arc<Platform>,
pub conf: LightningCoinConf,
/// The lightning node background processor that takes care of tasks that need to happen periodically.
pub background_processor: Arc<BackgroundProcessor>,
/// The lightning node peer manager that takes care of connecting to peers, etc..
pub peer_manager: Arc<PeerManager>,
/// The lightning node channel manager which keeps track of the number of open channels and sends messages to the appropriate
/// channel, also tracks HTLC preimages and forwards onion packets appropriately.
pub channel_manager: Arc<ChannelManager>,
/// The lightning node chain monitor that takes care of monitoring the chain for transactions of interest.
pub chain_monitor: Arc<ChainMonitor>,
/// The lightning node keys manager that takes care of signing invoices.
pub keys_manager: Arc<KeysManager>,
/// The lightning node invoice payer.
pub invoice_payer: Arc<InvoicePayer<Arc<LightningEventHandler>>>,
/// The lightning node persister that takes care of writing/reading data from storage.
pub persister: Arc<LightningFilesystemPersister>,
/// The lightning node db struct that takes care of reading/writing data from/to db.
pub db: SqliteLightningDB,
/// The mutex storing the addresses of the nodes that the lightning node has open channels with,
/// these addresses are used for reconnecting.
pub open_channels_nodes: NodesAddressesMapShared,
/// The mutex storing the public keys of the nodes that our lightning node trusts to allow 0 confirmation
/// inbound channels from.
pub trusted_nodes: TrustedNodesShared,
/// The lightning node router that takes care of finding routes for payments.
// Todo: this should be removed once pay_invoice_with_max_total_cltv_expiry_delta similar functionality is implemented in rust-lightning
pub router: Arc<Router>,
/// The lightning node logger, this is required to be passed to some function so that logs from these functions are displayed in mm2 logs.
pub logger: Arc<LogState>,
}
impl fmt::Debug for LightningCoin {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "LightningCoin {{ conf: {:?} }}", self.conf) }
}
#[derive(Deserialize)]
pub struct OpenChannelsFilter {
pub channel_id: Option<H256Json>,
pub counterparty_node_id: Option<PublicKeyForRPC>,
pub funding_tx: Option<H256Json>,
pub from_funding_value_sats: Option<u64>,
pub to_funding_value_sats: Option<u64>,
pub is_outbound: Option<bool>,
pub from_balance_msat: Option<u64>,
pub to_balance_msat: Option<u64>,
pub from_outbound_capacity_msat: Option<u64>,
pub to_outbound_capacity_msat: Option<u64>,
pub from_inbound_capacity_msat: Option<u64>,
pub to_inbound_capacity_msat: Option<u64>,
pub is_ready: Option<bool>,
pub is_usable: Option<bool>,
pub is_public: Option<bool>,
}
pub(crate) struct GetOpenChannelsResult {
pub channels: Vec<ChannelDetailsForRPC>,
pub skipped: usize,
pub total: usize,
}
impl Transaction for PaymentHash {
fn tx_hex(&self) -> Vec<u8> { self.0.to_vec() }
fn tx_hash_as_bytes(&self) -> BytesJson { self.0.to_vec().into() }
}
impl LightningCoin {
pub fn platform_coin(&self) -> &UtxoStandardCoin { &self.platform.coin }
#[inline]
fn avg_blocktime(&self) -> u64 { self.platform.avg_blocktime }
#[inline]
fn my_node_id(&self) -> String { self.channel_manager.get_our_node_id().to_string() }
pub(crate) async fn list_channels(&self) -> Vec<ChannelDetails> {
let channel_manager = self.channel_manager.clone();
async_blocking(move || channel_manager.list_channels()).await
}
async fn get_balance_msat(&self) -> (u64, u64) {
self.list_channels()
.await
.iter()
.fold((0, 0), |(spendable, unspendable), chan| {
if chan.is_usable {
(
spendable + chan.outbound_capacity_msat,
unspendable + chan.balance_msat - chan.outbound_capacity_msat,
)
} else {
(spendable, unspendable + chan.balance_msat)
}
})
}
pub(crate) async fn get_channel_by_uuid(&self, uuid: Uuid) -> Option<ChannelDetails> {
self.list_channels()
.await
.into_iter()
.find(|chan| chan.user_channel_id == uuid.as_u128())
}
pub(crate) async fn pay_invoice(
&self,
invoice: Invoice,
max_total_cltv_expiry_delta: Option<u32>,
) -> Result<PaymentInfo, MmError<PaymentError>> {
let payment_hash = PaymentHash((invoice.payment_hash()).into_inner());
// check if the invoice was already paid
if let Some(info) = self.db.get_payment_from_db(payment_hash).await? {
// If payment is still pending pay_invoice_with_max_total_cltv_expiry_delta/pay_invoice will return an error later
if info.status == HTLCStatus::Succeeded {
return MmError::err(PaymentError::Invoice(format!(
"Invoice with payment hash {} is already paid!",
hex::encode(payment_hash.0)
)));
}
}
let payment_type = PaymentType::OutboundPayment {
destination: *invoice.payee_pub_key().unwrap_or(&invoice.recover_payee_pub_key()),
};
let description = match invoice.description() {
InvoiceDescription::Direct(d) => d.to_string(),
InvoiceDescription::Hash(h) => hex::encode(h.0.into_inner()),
};
let amt_msat = invoice.amount_milli_satoshis().map(|a| a as i64);
let selfi = self.clone();
match max_total_cltv_expiry_delta {
Some(total_cltv) => {
async_blocking(move || {
pay_invoice_with_max_total_cltv_expiry_delta(
selfi.channel_manager,
selfi.router,
&invoice,
total_cltv,
)
})
.await?
},
None => async_blocking(move || selfi.invoice_payer.pay_invoice(&invoice)).await?,
};
let payment_info = PaymentInfo::new(payment_hash, payment_type, description, amt_msat);
// So this only updates the payment in db if the user is retrying to pay an invoice payment that has failed
self.db.add_or_update_payment_in_db(&payment_info).await?;
Ok(payment_info)
}
pub(crate) async fn keysend(
&self,
destination: PublicKey,
amount_msat: u64,
final_cltv_expiry_delta: u32,
) -> Result<PaymentInfo, MmError<PaymentError>> {
if final_cltv_expiry_delta < MIN_FINAL_CLTV_EXPIRY {
return MmError::err(PaymentError::CLTVExpiry(final_cltv_expiry_delta, MIN_FINAL_CLTV_EXPIRY));
}
let payment_preimage = PaymentPreimage(self.keys_manager.get_secure_random_bytes());
let selfi = self.clone();
async_blocking(move || {
selfi
.invoice_payer
.pay_pubkey(destination, payment_preimage, amount_msat, final_cltv_expiry_delta)
.map_to_mm(|e| PaymentError::Keysend(format!("{:?}", e)))
})
.await?;
let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
let payment_type = PaymentType::OutboundPayment { destination };
let payment_info = PaymentInfo::new(payment_hash, payment_type, "".into(), Some(amount_msat as i64));
self.db.add_payment_to_db(&payment_info).await?;
Ok(payment_info)
}
pub(crate) async fn get_open_channels_by_filter(
&self,
filter: Option<OpenChannelsFilter>,
paging: PagingOptionsEnum<Uuid>,
limit: usize,
) -> GetOpenChannelsResult {
fn apply_open_channel_filter(channel_details: &ChannelDetailsForRPC, filter: &OpenChannelsFilter) -> bool {
// Checking if channel_id is some and not equal
if filter.channel_id.is_some() && Some(&channel_details.channel_id) != filter.channel_id.as_ref() {
return false;
}
// Checking if counterparty_node_id is some and not equal
if filter.counterparty_node_id.is_some()
&& Some(&channel_details.counterparty_node_id) != filter.counterparty_node_id.as_ref()
{
return false;
}
// Checking if funding_tx is some and not equal
if filter.funding_tx.is_some() && channel_details.funding_tx != filter.funding_tx {
return false;
}
// Checking if from_funding_value_sats is some and more than funding_tx_value_sats
if filter.from_funding_value_sats.is_some()
&& Some(&channel_details.funding_tx_value_sats) < filter.from_funding_value_sats.as_ref()
{
return false;
}
// Checking if to_funding_value_sats is some and less than funding_tx_value_sats
if filter.to_funding_value_sats.is_some()
&& Some(&channel_details.funding_tx_value_sats) > filter.to_funding_value_sats.as_ref()
{
return false;
}
// Checking if is_outbound is some and not equal
if filter.is_outbound.is_some() && Some(&channel_details.is_outbound) != filter.is_outbound.as_ref() {
return false;
}
// Checking if from_balance_msat is some and more than balance_msat
if filter.from_balance_msat.is_some()
&& Some(&channel_details.balance_msat) < filter.from_balance_msat.as_ref()
{
return false;
}
// Checking if to_balance_msat is some and less than balance_msat
if filter.to_balance_msat.is_some() && Some(&channel_details.balance_msat) > filter.to_balance_msat.as_ref()
{
return false;
}
// Checking if from_outbound_capacity_msat is some and more than outbound_capacity_msat
if filter.from_outbound_capacity_msat.is_some()
&& Some(&channel_details.outbound_capacity_msat) < filter.from_outbound_capacity_msat.as_ref()
{
return false;
}
// Checking if to_outbound_capacity_msat is some and less than outbound_capacity_msat
if filter.to_outbound_capacity_msat.is_some()
&& Some(&channel_details.outbound_capacity_msat) > filter.to_outbound_capacity_msat.as_ref()
{
return false;
}
// Checking if from_inbound_capacity_msat is some and more than outbound_capacity_msat
if filter.from_inbound_capacity_msat.is_some()
&& Some(&channel_details.inbound_capacity_msat) < filter.from_inbound_capacity_msat.as_ref()
{
return false;
}
// Checking if to_inbound_capacity_msat is some and less than inbound_capacity_msat
if filter.to_inbound_capacity_msat.is_some()
&& Some(&channel_details.inbound_capacity_msat) > filter.to_inbound_capacity_msat.as_ref()
{
return false;
}
// Checking if is_ready is some and not equal
if filter.is_ready.is_some() && Some(&channel_details.is_ready) != filter.is_ready.as_ref() {
return false;
}
// Checking if is_usable is some and not equal
if filter.is_usable.is_some() && Some(&channel_details.is_usable) != filter.is_usable.as_ref() {
return false;
}
// Checking if is_public is some and not equal
if filter.is_public.is_some() && Some(&channel_details.is_public) != filter.is_public.as_ref() {
return false;
}
// All checks pass
true
}
let mut total_open_channels = self.list_channels().await;
total_open_channels.sort_by(|a, b| {
b.short_channel_id
.unwrap_or(u64::MAX)
.cmp(&a.short_channel_id.unwrap_or(u64::MAX))
});
drop_mutability!(total_open_channels);
let total_open_channels: Vec<ChannelDetailsForRPC> = total_open_channels.into_iter().map(From::from).collect();
let open_channels_filtered = if let Some(ref f) = filter {
total_open_channels
.into_iter()
.filter(|chan| apply_open_channel_filter(chan, f))
.collect()
} else {
total_open_channels
};
let offset = match paging {
PagingOptionsEnum::PageNumber(page) => (page.get() - 1) * limit,
PagingOptionsEnum::FromId(uuid) => open_channels_filtered
.iter()
.position(|x| x.uuid == uuid)
.map(|pos| pos + 1)
.unwrap_or_default(),
};
let total = open_channels_filtered.len();
let channels = if offset + limit <= total {
open_channels_filtered[offset..offset + limit].to_vec()
} else {
open_channels_filtered[offset..].to_vec()
};
GetOpenChannelsResult {
channels,
skipped: offset,
total,
}
}
// Todo: this can be removed after next rust-lightning release when min_final_cltv_expiry can be specified in
// Todo: create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash https://github.com/lightningdevkit/rust-lightning/pull/1878
// Todo: The above PR will also validate min_final_cltv_expiry.
async fn create_invoice_for_hash(
&self,
payment_hash: PaymentHash,
amt_msat: Option<u64>,
description: String,
min_final_cltv_expiry: u64,
invoice_expiry_delta_secs: u32,
) -> Result<Invoice, MmError<SignOrCreationError<()>>> {
let open_channels_nodes = self.open_channels_nodes.lock().clone();
for (node_pubkey, node_addr) in open_channels_nodes {
ln_p2p::connect_to_ln_node(node_pubkey, node_addr, self.peer_manager.clone())
.await
.error_log_with_msg(&format!(
"Channel with node: {} can't be used for invoice routing hints due to connection error.",
node_pubkey
));
}
// `create_inbound_payment` only returns an error if the amount is greater than the total bitcoin
// supply.
let payment_secret = self
.channel_manager
.create_inbound_payment_for_hash(payment_hash, amt_msat, invoice_expiry_delta_secs)
.map_to_mm(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
let our_node_pubkey = self.channel_manager.get_our_node_id();
// Todo: Check if it's better to use UTC instead of local time for invoice generations
let duration = get_local_duration_since_epoch().expect("for the foreseeable future this shouldn't happen");
let mut invoice = InvoiceBuilder::new(self.platform.network.clone().into())
.description(description)
.duration_since_epoch(duration)
.payee_pub_key(our_node_pubkey)
.payment_hash(Hash::from_inner(payment_hash.0))
.payment_secret(payment_secret)
.basic_mpp()
.min_final_cltv_expiry(min_final_cltv_expiry)
.expiry_time(core::time::Duration::from_secs(invoice_expiry_delta_secs.into()));
if let Some(amt) = amt_msat {
invoice = invoice.amount_milli_satoshis(amt);
}
let route_hints = filter_channels(self.channel_manager.list_usable_channels(), amt_msat);
for hint in route_hints {
invoice = invoice.private_route(hint);
}
let raw_invoice = match invoice.build_raw() {
Ok(inv) => inv,
Err(e) => return MmError::err(SignOrCreationError::CreationError(e)),
};
let hrp_str = raw_invoice.hrp.to_string();
let hrp_bytes = hrp_str.as_bytes();
let data_without_signature = raw_invoice.data.to_base32();
let signed_raw_invoice = raw_invoice.sign(|_| {
self.keys_manager
.sign_invoice(hrp_bytes, &data_without_signature, Recipient::Node)
});
match signed_raw_invoice {
Ok(inv) => Ok(Invoice::from_signed(inv).map_err(|_| SignOrCreationError::SignError(()))?),
Err(e) => MmError::err(SignOrCreationError::SignError(e)),
}
}
fn estimate_blocks_from_duration(&self, duration: u64) -> u64 { duration / self.avg_blocktime() }
async fn swap_payment_instructions(
&self,
secret_hash: &[u8],
amount: BigDecimal,
expires_in: u64,
min_final_cltv_expiry: u64,
) -> Result<Vec<u8>, MmError<PaymentInstructionsErr>> {
// lightning decimals should be 11 in config since the smallest divisible unit in lightning coin is msat
let amt_msat = sat_from_big_decimal(&amount, self.decimals())?;
let payment_hash =
payment_hash_from_slice(secret_hash).map_to_mm(|e| PaymentInstructionsErr::InternalError(e.to_string()))?;
// note: No description is provided in the invoice to reduce the payload
let invoice = self
.create_invoice_for_hash(
payment_hash,
Some(amt_msat),
"".into(),
min_final_cltv_expiry,
expires_in.try_into().expect("expires_in shouldn't exceed u32::MAX"),
)
.await
.map_err(|e| PaymentInstructionsErr::LightningInvoiceErr(e.to_string()))?;
Ok(invoice.to_string().into_bytes())
}
fn validate_swap_instructions(
&self,
instructions: &[u8],
secret_hash: &[u8],
amount: BigDecimal,
min_final_cltv_expiry: u64,
) -> Result<PaymentInstructions, MmError<ValidateInstructionsErr>> {
let invoice = Invoice::from_str(&String::from_utf8_lossy(instructions))?;
if invoice.payment_hash().as_inner() != secret_hash
&& ripemd160(invoice.payment_hash().as_inner()).as_slice() != secret_hash
{
return MmError::err(ValidateInstructionsErr::ValidateLightningInvoiceErr(
"Invalid invoice payment hash!".into(),
));
}
let invoice_amount = invoice
.amount_milli_satoshis()
.or_mm_err(|| ValidateInstructionsErr::ValidateLightningInvoiceErr("No invoice amount!".into()))?;
if big_decimal_from_sat(invoice_amount as i64, self.decimals()) != amount {
return MmError::err(ValidateInstructionsErr::ValidateLightningInvoiceErr(
"Invalid invoice amount!".into(),
));
}
if invoice.min_final_cltv_expiry() != min_final_cltv_expiry {
return MmError::err(ValidateInstructionsErr::ValidateLightningInvoiceErr(
"Invalid invoice min_final_cltv_expiry!".into(),
));
}
Ok(PaymentInstructions::Lightning(invoice))
}
async fn spend_swap_payment(&self, spend_payment_args: SpendPaymentArgs<'_>) -> TransactionResult {
let payment_hash = try_tx_s!(payment_hash_from_slice(spend_payment_args.other_payment_tx));
let mut preimage = [b' '; 32];
preimage.copy_from_slice(spend_payment_args.secret);
drop_mutability!(preimage);
let payment_preimage = PaymentPreimage(preimage);
self.channel_manager.claim_funds(payment_preimage);
self.db
.update_payment_preimage_in_db(payment_hash, payment_preimage)
.await
.error_log_with_msg(&format!(
"Unable to update payment {} information in DB with preimage: {}!",
hex::encode(payment_hash.0),
hex::encode(preimage)
));
Ok(TransactionEnum::LightningPayment(payment_hash))
}
fn validate_swap_payment(&self, input: ValidatePaymentInput) -> ValidatePaymentFut<()> {
let payment_hash = try_f!(payment_hash_from_slice(&input.payment_tx)
.map_to_mm(|e| ValidatePaymentError::TxDeserializationError(e.to_string())));
let payment_hex = hex::encode(payment_hash.0);
let amt_msat = try_f!(sat_from_big_decimal(&input.amount, self.decimals()));
let coin = self.clone();
let fut = async move {
match coin.db.get_payment_from_db(payment_hash).await {
Ok(Some(payment)) => {
let amount_claimable = payment.amt_msat;
// Note: locktime doesn't need to be validated since min_final_cltv_expiry should be validated in rust-lightning after fixing the below issue
// https://github.com/lightningdevkit/rust-lightning/issues/1850
// Also, PaymentClaimable won't be fired if amount_claimable < the amount requested in the invoice, this check is probably not needed.
// But keeping it just in case any changes happen in rust-lightning
if amount_claimable != Some(amt_msat as i64) {
return MmError::err(ValidatePaymentError::WrongPaymentTx(format!(
"Provided payment {} amount {:?} doesn't match required amount {}",
payment_hex, amount_claimable, amt_msat
)));
}
Ok(())
},
Ok(None) => MmError::err(ValidatePaymentError::UnexpectedPaymentState(format!(
"Payment {} is not in the database when it should be!",
payment_hex
))),
Err(e) => MmError::err(ValidatePaymentError::InternalError(format!(
"Unable to retrieve payment {} from the database error: {}",
payment_hex, e
))),
}
};
Box::new(fut.boxed().compat())
}
async fn on_swap_refund(&self, payment: &[u8]) -> RefundResult<()> {
let payment_hash = payment_hash_from_slice(payment).map_err(|e| RefundError::DecodeErr(e.to_string()))?;
// Free the htlc to allow for this inbound liquidity to be used for other inbound payments
self.channel_manager.fail_htlc_backwards(&payment_hash);
self.db
.update_payment_status_in_db(payment_hash, &HTLCStatus::Failed)
.await
.map_to_mm(|e| RefundError::DbError(e.to_string()))
}
}
#[async_trait]
impl SwapOps for LightningCoin {
// Todo: This uses dummy data for now for the sake of swap P.O.C., this should be implemented probably after agreeing on how fees will work for lightning
async fn send_taker_fee(
&self,
_fee_addr: &[u8],
_dex_fee: DexFee,
_uuid: &[u8],
_expire_at: u64,
) -> TransactionResult {
Ok(TransactionEnum::LightningPayment(PaymentHash([1; 32])))
}
async fn send_maker_payment(&self, maker_payment_args: SendPaymentArgs<'_>) -> TransactionResult {
let invoice = match maker_payment_args.payment_instructions.clone() {
Some(PaymentInstructions::Lightning(invoice)) => invoice,
_ => try_tx_s!(ERR!("Invalid instructions, ligntning invoice is expected")),
};
// No need for max_total_cltv_expiry_delta for lightning maker payment since the maker is the side that reveals the secret/preimage
let payment = try_tx_s!(self.pay_invoice(invoice, None).await);
Ok(payment.payment_hash.into())
}
async fn send_taker_payment(&self, taker_payment_args: SendPaymentArgs<'_>) -> TransactionResult {
let invoice = match taker_payment_args.payment_instructions.clone() {
Some(PaymentInstructions::Lightning(invoice)) => invoice,
_ => try_tx_s!(ERR!("Invalid instructions, ligntning invoice is expected")),
};
let max_total_cltv_expiry_delta = self
.estimate_blocks_from_duration(taker_payment_args.time_lock_duration)
.try_into()
.expect("max_total_cltv_expiry_delta shouldn't exceed u32::MAX");
// Todo: The path/s used is already logged when PaymentPathSuccessful/PaymentPathFailed events are fired, it might be better to save it to the DB and retrieve it with the payment info.
let payment = try_tx_s!(self.pay_invoice(invoice, Some(max_total_cltv_expiry_delta)).await);
Ok(payment.payment_hash.into())
}
#[inline]
async fn send_maker_spends_taker_payment(
&self,
maker_spends_payment_args: SpendPaymentArgs<'_>,
) -> TransactionResult {
self.spend_swap_payment(maker_spends_payment_args).await
}
#[inline]
async fn send_taker_spends_maker_payment(
&self,
taker_spends_payment_args: SpendPaymentArgs<'_>,
) -> TransactionResult {
self.spend_swap_payment(taker_spends_payment_args).await
}
async fn send_taker_refunds_payment(
&self,
_taker_refunds_payment_args: RefundPaymentArgs<'_>,
) -> TransactionResult {
Err(TransactionErr::Plain(
"Doesn't need transaction broadcast to refund lightning HTLC".into(),
))
}
async fn send_maker_refunds_payment(
&self,
_maker_refunds_payment_args: RefundPaymentArgs<'_>,
) -> TransactionResult {
Err(TransactionErr::Plain(
"Doesn't need transaction broadcast to refund lightning HTLC".into(),
))
}
// Todo: This validates the dummy fee for now for the sake of swap P.O.C., this should be implemented probably after agreeing on how fees will work for lightning
async fn validate_fee(&self, _validate_fee_args: ValidateFeeArgs<'_>) -> ValidatePaymentResult<()> { Ok(()) }
#[inline]
async fn validate_maker_payment(&self, input: ValidatePaymentInput) -> ValidatePaymentResult<()> {
self.validate_swap_payment(input).compat().await
}
#[inline]
async fn validate_taker_payment(&self, input: ValidatePaymentInput) -> ValidatePaymentResult<()> {
self.validate_swap_payment(input).compat().await
}
async fn check_if_my_payment_sent(
&self,
if_my_payment_sent_args: CheckIfMyPaymentSentArgs<'_>,
) -> Result<Option<TransactionEnum>, String> {
let invoice = match if_my_payment_sent_args.payment_instructions.clone() {
Some(PaymentInstructions::Lightning(invoice)) => invoice,
_ => return ERR!("Invalid instructions, ligntning invoice is expected"),
};
let payment_hash = PaymentHash((invoice.payment_hash()).into_inner());
let payment_hex = hex::encode(payment_hash.0);
match self.db.get_payment_from_db(payment_hash).await {
Ok(maybe_payment) => Ok(maybe_payment.map(|p| p.payment_hash.into())),
Err(e) => ERR!(
"Unable to check if payment {} is in db or not error: {}",
payment_hex,
e
),
}
}
// Todo: need to also check on-chain spending
async fn search_for_swap_tx_spend_my(
&self,
input: SearchForSwapTxSpendInput<'_>,
) -> Result<Option<FoundSwapTxSpend>, String> {
let payment_hash = payment_hash_from_slice(input.tx).map_err(|e| e.to_string())?;
let payment_hex = hex::encode(payment_hash.0);
match self.db.get_payment_from_db(payment_hash).await {
Ok(Some(payment)) => {
if !payment.is_outbound() {
return ERR!("Payment {} should be an outbound payment!", payment_hex);
}
match payment.status {
HTLCStatus::Pending => Ok(None),
HTLCStatus::Succeeded => Ok(Some(FoundSwapTxSpend::Spent(TransactionEnum::LightningPayment(
payment_hash,
)))),
HTLCStatus::Claimable => {
ERR!(
"Payment {} has an invalid status of {} in the db",
payment_hex,
payment.status
)
},
HTLCStatus::Failed => Ok(Some(FoundSwapTxSpend::Refunded(TransactionEnum::LightningPayment(
payment_hash,
)))),
}
},
Ok(None) => ERR!("Payment {} is not in the database when it should be!", payment_hex),
Err(e) => ERR!(
"Unable to retrieve payment {} from the database error: {}",
payment_hex,
e
),
}
}
// Todo: need to also check on-chain spending
async fn search_for_swap_tx_spend_other(
&self,
input: SearchForSwapTxSpendInput<'_>,
) -> Result<Option<FoundSwapTxSpend>, String> {
let payment_hash = payment_hash_from_slice(input.tx).map_err(|e| e.to_string())?;
let payment_hex = hex::encode(payment_hash.0);
match self.db.get_payment_from_db(payment_hash).await {
Ok(Some(payment)) => {
if payment.is_outbound() {
return ERR!("Payment {} should be an inbound payment!", payment_hex);
}
match payment.status {
HTLCStatus::Pending | HTLCStatus::Claimable => Ok(None),
HTLCStatus::Succeeded => Ok(Some(FoundSwapTxSpend::Spent(TransactionEnum::LightningPayment(
payment_hash,
)))),
HTLCStatus::Failed => Ok(Some(FoundSwapTxSpend::Refunded(TransactionEnum::LightningPayment(
payment_hash,
)))),
}
},
Ok(None) => ERR!("Payment {} is not in the database when it should be!", payment_hex),
Err(e) => ERR!(
"Unable to retrieve payment {} from the database error: {}",
payment_hex,
e
),
}
}
fn check_tx_signed_by_pub(&self, _tx: &[u8], _expected_pub: &[u8]) -> Result<bool, MmError<ValidatePaymentError>> {
unimplemented!();
}
async fn extract_secret(
&self,
_secret_hash: &[u8],
spend_tx: &[u8],
_watcher_reward: bool,
) -> Result<Vec<u8>, String> {
let payment_hash = payment_hash_from_slice(spend_tx).map_err(|e| e.to_string())?;
let payment_hex = hex::encode(payment_hash.0);
match self.db.get_payment_from_db(payment_hash).await {
Ok(Some(payment)) => match payment.preimage {
Some(preimage) => Ok(preimage.0.to_vec()),
None => ERR!("Preimage for payment {} should be found on the database", payment_hex),
},
Ok(None) => ERR!("Payment {} is not in the database when it should be!", payment_hex),
Err(e) => ERR!(
"Unable to retrieve payment {} from the database error: {}",
payment_hex,
e
),
}
}
fn is_auto_refundable(&self) -> bool { true }
async fn wait_for_htlc_refund(&self, tx: &[u8], locktime: u64) -> RefundResult<()> {
let payment_hash = payment_hash_from_slice(tx).map_err(|e| RefundError::DecodeErr(e.to_string()))?;
let payment_hex = hex::encode(payment_hash.0);
repeatable!(async {
match self.db.get_payment_from_db(payment_hash).await {
Ok(Some(payment)) => match payment.status {
HTLCStatus::Failed => Ready(Ok(())),
HTLCStatus::Pending => Retry(()),
_ => Ready(MmError::err(RefundError::Internal(ERRL!(
"Payment {} has an invalid status of {} in the db",
payment_hex,
payment.status
)))),
},
Ok(None) => Ready(MmError::err(RefundError::Internal(ERRL!(
"Payment {} is not in the database when it should be!",
payment_hex
)))),
Err(e) => Ready(MmError::err(RefundError::DbError(ERRL!(
"Error getting payment {} from db: {}",
payment_hex,
e
)))),
}
})
.repeat_every_secs(WAIT_FOR_REFUND_INTERVAL)
.until_s(locktime)
.await
.map_err(|e| RefundError::Timeout(format!("{:?}", e)))?
}
fn negotiate_swap_contract_addr(
&self,
_other_side_address: Option<&[u8]>,
) -> Result<Option<BytesJson>, MmError<NegotiateSwapContractAddrErr>> {
Ok(None)
}
// Todo: This can be changed if private swaps were to be implemented for lightning
fn derive_htlc_key_pair(&self, swap_unique_data: &[u8]) -> KeyPair {
utxo_common::derive_htlc_key_pair(self.platform.coin.as_ref(), swap_unique_data)
}
#[inline]
fn derive_htlc_pubkey(&self, _swap_unique_data: &[u8]) -> Vec<u8> {
self.channel_manager.get_our_node_id().serialize().to_vec()
}
#[inline]
fn validate_other_pubkey(&self, raw_pubkey: &[u8]) -> MmResult<(), ValidateOtherPubKeyErr> {
utxo_common::validate_other_pubkey(raw_pubkey)
}
async fn maker_payment_instructions(
&self,
args: PaymentInstructionArgs<'_>,
) -> Result<Option<Vec<u8>>, MmError<PaymentInstructionsErr>> {
let min_final_cltv_expiry = self.estimate_blocks_from_duration(args.maker_lock_duration);
self.swap_payment_instructions(args.secret_hash, args.amount, args.expires_in, min_final_cltv_expiry)
.await
.map(Some)
}
#[inline]
async fn taker_payment_instructions(
&self,
args: PaymentInstructionArgs<'_>,
) -> Result<Option<Vec<u8>>, MmError<PaymentInstructionsErr>> {
self.swap_payment_instructions(
args.secret_hash,
args.amount,
args.expires_in,
MIN_FINAL_CLTV_EXPIRY as u64,
)
.await
.map(Some)
}
fn validate_maker_payment_instructions(
&self,
instructions: &[u8],
args: PaymentInstructionArgs,
) -> Result<PaymentInstructions, MmError<ValidateInstructionsErr>> {
let min_final_cltv_expiry = self.estimate_blocks_from_duration(args.maker_lock_duration);
self.validate_swap_instructions(instructions, args.secret_hash, args.amount, min_final_cltv_expiry)
}
#[inline]
fn validate_taker_payment_instructions(
&self,
instructions: &[u8],
args: PaymentInstructionArgs,
) -> Result<PaymentInstructions, MmError<ValidateInstructionsErr>> {
self.validate_swap_instructions(
instructions,
args.secret_hash,
args.amount,
MIN_FINAL_CLTV_EXPIRY as u64,
)
}
fn maker_locktime_multiplier(&self) -> f64 { 1.5 }
}
#[async_trait]
impl TakerSwapMakerCoin for LightningCoin {
async fn on_taker_payment_refund_start(&self, _maker_payment: &[u8]) -> RefundResult<()> { Ok(()) }
async fn on_taker_payment_refund_success(&self, maker_payment: &[u8]) -> RefundResult<()> {
self.on_swap_refund(maker_payment).await
}
}
#[async_trait]
impl MakerSwapTakerCoin for LightningCoin {
async fn on_maker_payment_refund_start(&self, taker_payment: &[u8]) -> RefundResult<()> {
self.on_swap_refund(taker_payment).await
}
async fn on_maker_payment_refund_success(&self, _taker_payment: &[u8]) -> RefundResult<()> { Ok(()) }
}
#[derive(Debug, Display)]
pub enum PaymentHashFromSliceErr {
#[display(fmt = "Invalid data length of {}", _0)]
InvalidLength(usize),
}
fn payment_hash_from_slice(data: &[u8]) -> Result<PaymentHash, PaymentHashFromSliceErr> {
let len = data.len();
if len != 32 {
return Err(PaymentHashFromSliceErr::InvalidLength(len));
}
let mut hash = [b' '; 32];
hash.copy_from_slice(data);
Ok(PaymentHash(hash))
}
#[async_trait]
impl WatcherOps for LightningCoin {
fn create_maker_payment_spend_preimage(
&self,
_maker_payment_tx: &[u8],
_time_lock: u64,
_maker_pub: &[u8],
_secret_hash: &[u8],
_swap_unique_data: &[u8],
) -> TransactionFut {
unimplemented!();
}
fn send_maker_payment_spend_preimage(&self, _input: SendMakerPaymentSpendPreimageInput) -> TransactionFut {
unimplemented!();
}
fn create_taker_payment_refund_preimage(
&self,
_taker_payment_tx: &[u8],
_time_lock: u64,
_maker_pub: &[u8],
_secret_hash: &[u8],
_swap_contract_address: &Option<BytesJson>,
_swap_unique_data: &[u8],
) -> TransactionFut {
unimplemented!();
}
fn send_taker_payment_refund_preimage(&self, _watcher_refunds_payment_args: RefundPaymentArgs) -> TransactionFut {
unimplemented!();
}
fn watcher_validate_taker_fee(&self, _input: WatcherValidateTakerFeeInput) -> ValidatePaymentFut<()> {
unimplemented!();
}
fn watcher_validate_taker_payment(&self, _input: WatcherValidatePaymentInput) -> ValidatePaymentFut<()> {
unimplemented!();
}
fn taker_validates_payment_spend_or_refund(&self, _input: ValidateWatcherSpendInput) -> ValidatePaymentFut<()> {
unimplemented!()
}
async fn watcher_search_for_swap_tx_spend(
&self,