forked from jl777/SuperNET
-
Notifications
You must be signed in to change notification settings - Fork 94
/
lightning.rs
1602 lines (1423 loc) · 58.9 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;
mod ln_db;
pub mod ln_errors;
mod ln_events;
mod ln_filesystem_persister;
mod ln_p2p;
mod ln_platform;
mod ln_serialization;
mod ln_sql;
mod ln_storage;
mod ln_utils;
use super::{lp_coinfind_or_err, DerivationMethod, MmCoinEnum};
use crate::lightning::ln_events::init_events_abort_handlers;
use crate::lightning::ln_sql::SqliteLightningDB;
use crate::utxo::rpc_clients::UtxoRpcClientEnum;
use crate::utxo::utxo_common::{big_decimal_from_sat_unsigned, UtxoTxBuilder};
use crate::utxo::{sat_from_big_decimal, BlockchainNetwork, FeePolicy, GetUtxoListOps, UtxoTxGenerationOps};
use crate::{BalanceFut, CoinBalance, FeeApproxStage, FoundSwapTxSpend, HistorySyncState, MarketCoinOps, MmCoin,
NegotiateSwapContractAddrErr, RawTransactionFut, RawTransactionRequest, SearchForSwapTxSpendInput,
SignatureError, SignatureResult, SwapOps, TradeFee, TradePreimageFut, TradePreimageResult,
TradePreimageValue, TransactionEnum, TransactionFut, UnexpectedDerivationMethod, UtxoStandardCoin,
ValidateAddressResult, ValidatePaymentInput, VerificationError, VerificationResult, WithdrawError,
WithdrawFut, WithdrawRequest};
use async_trait::async_trait;
use bitcoin::hashes::Hash;
use bitcoin_hashes::sha256::Hash as Sha256;
use bitcrypto::dhash256;
use bitcrypto::ChecksumType;
use chain::TransactionOutput;
use common::executor::spawn;
use common::log::{error, LogOnError, LogState};
use common::{async_blocking, calc_total_pages, log, now_ms, ten, PagingOptionsEnum};
use futures::{FutureExt, TryFutureExt};
use futures01::Future;
use keys::{hash::H256, AddressHashEnum, CompactSignature, KeyPair, Private, Public};
use lightning::chain::channelmonitor::Balance;
use lightning::chain::keysinterface::{KeysInterface, KeysManager, Recipient};
use lightning::chain::Access;
use lightning::ln::channelmanager::{ChannelDetails, MIN_FINAL_CLTV_EXPIRY};
use lightning::ln::{PaymentHash, PaymentPreimage};
use lightning::routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
use lightning::util::config::UserConfig;
use lightning_background_processor::BackgroundProcessor;
use lightning_invoice::payment;
use lightning_invoice::utils::{create_invoice_from_channelmanager, DefaultRouter};
use lightning_invoice::{Invoice, InvoiceDescription};
use ln_conf::{ChannelOptions, LightningCoinConf, LightningProtocolConf, PlatformCoinConfirmations};
use ln_db::{ClosedChannelsFilter, DBChannelDetails, DBPaymentInfo, DBPaymentsFilter, HTLCStatus, LightningDB,
PaymentType};
use ln_errors::{ClaimableBalancesError, ClaimableBalancesResult, CloseChannelError, CloseChannelResult,
ConnectToNodeError, ConnectToNodeResult, EnableLightningError, EnableLightningResult,
GenerateInvoiceError, GenerateInvoiceResult, GetChannelDetailsError, GetChannelDetailsResult,
GetPaymentDetailsError, GetPaymentDetailsResult, ListChannelsError, ListChannelsResult,
ListPaymentsError, ListPaymentsResult, OpenChannelError, OpenChannelResult, SendPaymentError,
SendPaymentResult};
use ln_events::LightningEventHandler;
use ln_filesystem_persister::{LightningFilesystemPersister, LightningPersisterShared};
use ln_p2p::{connect_to_node, ConnectToNodeRes, PeerManager};
use ln_platform::{h256_json_from_txid, Platform};
use ln_serialization::{InvoiceForRPC, NodeAddress, PublicKeyForRPC};
use ln_storage::{LightningStorage, NodesAddressesMapShared, Scorer};
use ln_utils::{ChainMonitor, ChannelManager};
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::{Builder, TransactionInputSigner};
use secp256k1::PublicKey;
use serde::{Deserialize, Serialize};
use serde_json::Value as Json;
use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::net::SocketAddr;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
type Router = DefaultRouter<Arc<NetworkGraph>, Arc<LogState>>;
type InvoicePayer<E> = payment::InvoicePayer<Arc<ChannelManager>, Router, Arc<Mutex<Scorer>>, Arc<LogState>, E>;
#[derive(Clone)]
pub struct LightningCoin {
pub platform: Arc<Platform>,
pub conf: LightningCoinConf,
/// The lightning node peer manager that takes care of connecting to peers, etc..
pub peer_manager: Arc<PeerManager>,
/// The lightning node background processor that takes care of tasks that need to happen periodically.
pub background_processor: Arc<BackgroundProcessor>,
/// 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: LightningPersisterShared,
/// 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,
}
impl fmt::Debug for LightningCoin {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "LightningCoin {{ conf: {:?} }}", self.conf) }
}
impl LightningCoin {
fn platform_coin(&self) -> &UtxoStandardCoin { &self.platform.coin }
#[inline]
fn my_node_id(&self) -> String { self.channel_manager.get_our_node_id().to_string() }
fn get_balance_msat(&self) -> (u64, u64) {
self.channel_manager
.list_channels()
.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)
}
})
}
fn pay_invoice(&self, invoice: Invoice) -> SendPaymentResult<DBPaymentInfo> {
self.invoice_payer
.pay_invoice(&invoice)
.map_to_mm(|e| SendPaymentError::PaymentError(format!("{:?}", e)))?;
let payment_hash = PaymentHash((*invoice.payment_hash()).into_inner());
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 payment_secret = Some(*invoice.payment_secret());
Ok(DBPaymentInfo {
payment_hash,
payment_type,
description,
preimage: None,
secret: payment_secret,
amt_msat: invoice.amount_milli_satoshis().map(|a| a as i64),
fee_paid_msat: None,
status: HTLCStatus::Pending,
created_at: (now_ms() / 1000) as i64,
last_updated: (now_ms() / 1000) as i64,
})
}
fn keysend(
&self,
destination: PublicKey,
amount_msat: u64,
final_cltv_expiry_delta: u32,
) -> SendPaymentResult<DBPaymentInfo> {
if final_cltv_expiry_delta < MIN_FINAL_CLTV_EXPIRY {
return MmError::err(SendPaymentError::CLTVExpiryError(
final_cltv_expiry_delta,
MIN_FINAL_CLTV_EXPIRY,
));
}
let payment_preimage = PaymentPreimage(self.keys_manager.get_secure_random_bytes());
self.invoice_payer
.pay_pubkey(destination, payment_preimage, amount_msat, final_cltv_expiry_delta)
.map_to_mm(|e| SendPaymentError::PaymentError(format!("{:?}", e)))?;
let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
let payment_type = PaymentType::OutboundPayment { destination };
Ok(DBPaymentInfo {
payment_hash,
payment_type,
description: "".into(),
preimage: Some(payment_preimage),
secret: None,
amt_msat: Some(amount_msat as i64),
fee_paid_msat: None,
status: HTLCStatus::Pending,
created_at: (now_ms() / 1000) as i64,
last_updated: (now_ms() / 1000) as i64,
})
}
async fn get_open_channels_by_filter(
&self,
filter: Option<OpenChannelsFilter>,
paging: PagingOptionsEnum<u64>,
limit: usize,
) -> ListChannelsResult<GetOpenChannelsResult> {
let mut total_open_channels: Vec<ChannelDetailsForRPC> = self
.channel_manager
.list_channels()
.into_iter()
.map(From::from)
.collect();
total_open_channels.sort_by(|a, b| a.rpc_channel_id.cmp(&b.rpc_channel_id));
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(rpc_id) => open_channels_filtered
.iter()
.position(|x| x.rpc_channel_id == rpc_id)
.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()
};
Ok(GetOpenChannelsResult {
channels,
skipped: offset,
total,
})
}
}
#[async_trait]
// Todo: Implement this when implementing swaps for lightning as it's is used only for swaps
impl SwapOps for LightningCoin {
fn send_taker_fee(&self, _fee_addr: &[u8], _amount: BigDecimal, _uuid: &[u8]) -> TransactionFut { unimplemented!() }
fn send_maker_payment(
&self,
_time_lock: u32,
_taker_pub: &[u8],
_secret_hash: &[u8],
_amount: BigDecimal,
_swap_contract_address: &Option<BytesJson>,
_swap_unique_data: &[u8],
) -> TransactionFut {
unimplemented!()
}
fn send_taker_payment(
&self,
_time_lock: u32,
_maker_pub: &[u8],
_secret_hash: &[u8],
_amount: BigDecimal,
_swap_contract_address: &Option<BytesJson>,
_swap_unique_data: &[u8],
) -> TransactionFut {
unimplemented!()
}
fn send_maker_spends_taker_payment(
&self,
_taker_payment_tx: &[u8],
_time_lock: u32,
_taker_pub: &[u8],
_secret: &[u8],
_swap_contract_address: &Option<BytesJson>,
_swap_unique_data: &[u8],
) -> TransactionFut {
unimplemented!()
}
fn send_taker_spends_maker_payment(
&self,
_maker_payment_tx: &[u8],
_time_lock: u32,
_maker_pub: &[u8],
_secret: &[u8],
_swap_contract_address: &Option<BytesJson>,
_swap_unique_data: &[u8],
) -> TransactionFut {
unimplemented!()
}
fn send_taker_refunds_payment(
&self,
_taker_payment_tx: &[u8],
_time_lock: u32,
_maker_pub: &[u8],
_secret_hash: &[u8],
_swap_contract_address: &Option<BytesJson>,
_swap_unique_data: &[u8],
) -> TransactionFut {
unimplemented!()
}
fn send_maker_refunds_payment(
&self,
_maker_payment_tx: &[u8],
_time_lock: u32,
_taker_pub: &[u8],
_secret_hash: &[u8],
_swap_contract_address: &Option<BytesJson>,
_swap_unique_data: &[u8],
) -> TransactionFut {
unimplemented!()
}
fn validate_fee(
&self,
_fee_tx: &TransactionEnum,
_expected_sender: &[u8],
_fee_addr: &[u8],
_amount: &BigDecimal,
_min_block_number: u64,
_uuid: &[u8],
) -> Box<dyn Future<Item = (), Error = String> + Send> {
unimplemented!()
}
fn validate_maker_payment(
&self,
_input: ValidatePaymentInput,
) -> Box<dyn Future<Item = (), Error = String> + Send> {
unimplemented!()
}
fn validate_taker_payment(
&self,
_input: ValidatePaymentInput,
) -> Box<dyn Future<Item = (), Error = String> + Send> {
unimplemented!()
}
fn check_if_my_payment_sent(
&self,
_time_lock: u32,
_other_pub: &[u8],
_secret_hash: &[u8],
_search_from_block: u64,
_swap_contract_address: &Option<BytesJson>,
_swap_unique_data: &[u8],
) -> Box<dyn Future<Item = Option<TransactionEnum>, Error = String> + Send> {
unimplemented!()
}
async fn search_for_swap_tx_spend_my(
&self,
_: SearchForSwapTxSpendInput<'_>,
) -> Result<Option<FoundSwapTxSpend>, String> {
unimplemented!()
}
async fn search_for_swap_tx_spend_other(
&self,
_: SearchForSwapTxSpendInput<'_>,
) -> Result<Option<FoundSwapTxSpend>, String> {
unimplemented!()
}
fn extract_secret(&self, _secret_hash: &[u8], _spend_tx: &[u8]) -> Result<Vec<u8>, String> { unimplemented!() }
fn negotiate_swap_contract_addr(
&self,
_other_side_address: Option<&[u8]>,
) -> Result<Option<BytesJson>, MmError<NegotiateSwapContractAddrErr>> {
unimplemented!()
}
fn derive_htlc_key_pair(&self, _swap_unique_data: &[u8]) -> KeyPair { unimplemented!() }
}
impl MarketCoinOps for LightningCoin {
fn ticker(&self) -> &str { &self.conf.ticker }
fn my_address(&self) -> Result<String, String> { Ok(self.my_node_id()) }
fn get_public_key(&self) -> Result<String, MmError<UnexpectedDerivationMethod>> { unimplemented!() }
fn sign_message_hash(&self, message: &str) -> Option<[u8; 32]> {
let mut _message_prefix = self.conf.sign_message_prefix.clone()?;
let prefixed_message = format!("{}{}", _message_prefix, message);
Some(dhash256(prefixed_message.as_bytes()).take())
}
fn sign_message(&self, message: &str) -> SignatureResult<String> {
let message_hash = self.sign_message_hash(message).ok_or(SignatureError::PrefixNotFound)?;
let secret_key = self
.keys_manager
.get_node_secret(Recipient::Node)
.map_err(|_| SignatureError::InternalError("Error accessing node keys".to_string()))?;
let private = Private {
prefix: 239,
secret: H256::from(*secret_key.as_ref()),
compressed: true,
checksum_type: ChecksumType::DSHA256,
};
let signature = private.sign_compact(&H256::from(message_hash))?;
Ok(zbase32::encode_full_bytes(&*signature))
}
fn verify_message(&self, signature: &str, message: &str, pubkey: &str) -> VerificationResult<bool> {
let message_hash = self
.sign_message_hash(message)
.ok_or(VerificationError::PrefixNotFound)?;
let signature = CompactSignature::from(
zbase32::decode_full_bytes_str(signature)
.map_err(|e| VerificationError::SignatureDecodingError(e.to_string()))?,
);
let recovered_pubkey = Public::recover_compact(&H256::from(message_hash), &signature)?;
Ok(recovered_pubkey.to_string() == pubkey)
}
fn my_balance(&self) -> BalanceFut<CoinBalance> {
let decimals = self.decimals();
let (spendable_msat, unspendable_msat) = self.get_balance_msat();
let my_balance = CoinBalance {
spendable: big_decimal_from_sat_unsigned(spendable_msat, decimals),
unspendable: big_decimal_from_sat_unsigned(unspendable_msat, decimals),
};
Box::new(futures01::future::ok(my_balance))
}
fn base_coin_balance(&self) -> BalanceFut<BigDecimal> {
Box::new(self.platform_coin().my_balance().map(|res| res.spendable))
}
fn platform_ticker(&self) -> &str { self.platform_coin().ticker() }
fn send_raw_tx(&self, _tx: &str) -> Box<dyn Future<Item = String, Error = String> + Send> {
Box::new(futures01::future::err(
MmError::new(
"send_raw_tx is not supported for lightning, please use send_payment method instead.".to_string(),
)
.to_string(),
))
}
fn send_raw_tx_bytes(&self, _tx: &[u8]) -> Box<dyn Future<Item = String, Error = String> + Send> {
Box::new(futures01::future::err(
MmError::new(
"send_raw_tx is not supported for lightning, please use send_payment method instead.".to_string(),
)
.to_string(),
))
}
// Todo: Implement this when implementing swaps for lightning as it's is used mainly for swaps
fn wait_for_confirmations(
&self,
_tx: &[u8],
_confirmations: u64,
_requires_nota: bool,
_wait_until: u64,
_check_every: u64,
) -> Box<dyn Future<Item = (), Error = String> + Send> {
unimplemented!()
}
// Todo: Implement this when implementing swaps for lightning as it's is used mainly for swaps
fn wait_for_tx_spend(
&self,
_transaction: &[u8],
_wait_until: u64,
_from_block: u64,
_swap_contract_address: &Option<BytesJson>,
) -> TransactionFut {
unimplemented!()
}
// Todo: Implement this when implementing swaps for lightning as it's is used mainly for swaps
fn tx_enum_from_bytes(&self, _bytes: &[u8]) -> Result<TransactionEnum, String> { unimplemented!() }
fn current_block(&self) -> Box<dyn Future<Item = u64, Error = String> + Send> { Box::new(futures01::future::ok(0)) }
fn display_priv_key(&self) -> Result<String, String> {
Ok(self
.keys_manager
.get_node_secret(Recipient::Node)
.map_err(|_| "Unsupported recipient".to_string())?
.to_string())
}
// Todo: Implement this when implementing swaps for lightning as it's is used only for swaps
fn min_tx_amount(&self) -> BigDecimal { unimplemented!() }
// Todo: Implement this when implementing swaps for lightning as it's is used only for order matching/swaps
fn min_trading_vol(&self) -> MmNumber { unimplemented!() }
}
#[async_trait]
impl MmCoin for LightningCoin {
fn is_asset_chain(&self) -> bool { false }
fn get_raw_transaction(&self, req: RawTransactionRequest) -> RawTransactionFut {
Box::new(self.platform_coin().get_raw_transaction(req))
}
fn withdraw(&self, _req: WithdrawRequest) -> WithdrawFut {
let fut = async move {
MmError::err(WithdrawError::InternalError(
"withdraw method is not supported for lightning, please use generate_invoice method instead.".into(),
))
};
Box::new(fut.boxed().compat())
}
fn decimals(&self) -> u8 { self.conf.decimals }
fn convert_to_address(&self, _from: &str, _to_address_format: Json) -> Result<String, String> {
Err(MmError::new("Address conversion is not available for LightningCoin".to_string()).to_string())
}
fn validate_address(&self, address: &str) -> ValidateAddressResult {
match PublicKey::from_str(address) {
Ok(_) => ValidateAddressResult {
is_valid: true,
reason: None,
},
Err(e) => ValidateAddressResult {
is_valid: false,
reason: Some(format!("Error {} on parsing node public key", e)),
},
}
}
// Todo: Implement this when implementing payments history for lightning
fn process_history_loop(&self, _ctx: MmArc) -> Box<dyn Future<Item = (), Error = ()> + Send> { unimplemented!() }
// Todo: Implement this when implementing payments history for lightning
fn history_sync_status(&self) -> HistorySyncState { unimplemented!() }
// Todo: Implement this when implementing swaps for lightning as it's is used only for swaps
fn get_trade_fee(&self) -> Box<dyn Future<Item = TradeFee, Error = String> + Send> { unimplemented!() }
// Todo: Implement this when implementing swaps for lightning as it's is used only for swaps
async fn get_sender_trade_fee(
&self,
_value: TradePreimageValue,
_stage: FeeApproxStage,
) -> TradePreimageResult<TradeFee> {
unimplemented!()
}
// Todo: Implement this when implementing swaps for lightning as it's is used only for swaps
fn get_receiver_trade_fee(&self, _stage: FeeApproxStage) -> TradePreimageFut<TradeFee> { unimplemented!() }
// Todo: Implement this when implementing swaps for lightning as it's is used only for swaps
async fn get_fee_to_send_taker_fee(
&self,
_dex_fee_amount: BigDecimal,
_stage: FeeApproxStage,
) -> TradePreimageResult<TradeFee> {
unimplemented!()
}
// Lightning payments are either pending, successful or failed. Once a payment succeeds there is no need to for confirmations
// unlike onchain transactions.
fn required_confirmations(&self) -> u64 { 0 }
fn requires_notarization(&self) -> bool { false }
fn set_required_confirmations(&self, _confirmations: u64) {}
fn set_requires_notarization(&self, _requires_nota: bool) {}
fn swap_contract_address(&self) -> Option<BytesJson> { None }
fn mature_confirmations(&self) -> Option<u32> { None }
// Todo: Implement this when implementing order matching for lightning as it's is used only for order matching
fn coin_protocol_info(&self) -> Vec<u8> { unimplemented!() }
// Todo: Implement this when implementing order matching for lightning as it's is used only for order matching
fn is_coin_protocol_supported(&self, _info: &Option<Vec<u8>>) -> bool { unimplemented!() }
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct LightningParams {
// The listening port for the p2p LN node
pub listening_port: u16,
// Printable human-readable string to describe this node to other users.
pub node_name: [u8; 32],
// Node's RGB color. This is used for showing the node in a network graph with the desired color.
pub node_color: [u8; 3],
// Invoice Payer is initialized while starting the lightning node, and it requires the number of payment retries that
// it should do before considering a payment failed or partially failed. If not provided the number of retries will be 5
// as this is a good default value.
pub payment_retries: Option<usize>,
// Node's backup path for channels and other data that requires backup.
pub backup_path: Option<String>,
}
pub async fn start_lightning(
ctx: &MmArc,
platform_coin: UtxoStandardCoin,
protocol_conf: LightningProtocolConf,
conf: LightningCoinConf,
params: LightningParams,
) -> EnableLightningResult<LightningCoin> {
// Todo: add support for Hardware wallets for funding transactions and spending spendable outputs (channel closing transactions)
if let DerivationMethod::HDWallet(_) = platform_coin.as_ref().derivation_method {
return MmError::err(EnableLightningError::UnsupportedMode(
"'start_lightning'".into(),
"iguana".into(),
));
}
let platform = Arc::new(Platform::new(
platform_coin.clone(),
protocol_conf.network.clone(),
protocol_conf.confirmations,
));
// Initialize the Logger
let logger = ctx.log.0.clone();
// Initialize Persister
let persister = ln_utils::init_persister(ctx, conf.ticker.clone(), params.backup_path).await?;
// Initialize the KeysManager
let keys_manager = ln_utils::init_keys_manager(ctx)?;
// Initialize the NetGraphMsgHandler. This is used for providing routes to send payments over
let network_graph = Arc::new(persister.get_network_graph(protocol_conf.network.into()).await?);
let network_gossip = Arc::new(NetGraphMsgHandler::new(
network_graph.clone(),
None::<Arc<dyn Access + Send + Sync>>,
logger.clone(),
));
// Initialize DB
let db = ln_utils::init_db(ctx, conf.ticker.clone()).await?;
// Initialize the ChannelManager
let (chain_monitor, channel_manager) = ln_utils::init_channel_manager(
platform.clone(),
logger.clone(),
persister.clone(),
db.clone(),
keys_manager.clone(),
conf.clone().into(),
)
.await?;
// Initialize the PeerManager
let peer_manager = ln_p2p::init_peer_manager(
ctx.clone(),
params.listening_port,
channel_manager.clone(),
network_gossip.clone(),
keys_manager
.get_node_secret(Recipient::Node)
.map_to_mm(|_| EnableLightningError::UnsupportedMode("'start_lightning'".into(), "local node".into()))?,
logger.clone(),
)
.await?;
let events_abort_handlers = init_events_abort_handlers(platform.clone(), db.clone()).await?;
// Initialize the event handler
let event_handler = Arc::new(ln_events::LightningEventHandler::new(
platform.clone(),
channel_manager.clone(),
keys_manager.clone(),
db.clone(),
events_abort_handlers,
));
// Initialize routing Scorer
let scorer = Arc::new(Mutex::new(persister.get_scorer(network_graph.clone()).await?));
spawn(ln_utils::persist_scorer_loop(persister.clone(), scorer.clone()));
// Create InvoicePayer
// random_seed_bytes are additional random seed to improve privacy by adding a random CLTV expiry offset to each path's final hop.
// This helps obscure the intended recipient from adversarial intermediate hops. The seed is also used to randomize candidate paths during route selection.
// TODO: random_seed_bytes should be taken in consideration when implementing swaps because they change the payment lock-time.
// https://github.com/lightningdevkit/rust-lightning/issues/158
// https://github.com/lightningdevkit/rust-lightning/pull/1286
// https://github.com/lightningdevkit/rust-lightning/pull/1359
let router = DefaultRouter::new(network_graph, logger.clone(), keys_manager.get_secure_random_bytes());
let invoice_payer = Arc::new(InvoicePayer::new(
channel_manager.clone(),
router,
scorer,
logger.clone(),
event_handler,
payment::RetryAttempts(params.payment_retries.unwrap_or(5)),
));
// Start Background Processing. Runs tasks periodically in the background to keep LN node operational.
// InvoicePayer will act as our event handler as it handles some of the payments related events before
// delegating it to LightningEventHandler.
// note: background_processor stops automatically when dropped since BackgroundProcessor implements the Drop trait.
let background_processor = Arc::new(BackgroundProcessor::start(
persister.clone(),
invoice_payer.clone(),
chain_monitor.clone(),
channel_manager.clone(),
Some(network_gossip),
peer_manager.clone(),
logger,
));
// If channel_nodes_data file exists, read channels nodes data from disk and reconnect to channel nodes/peers if possible.
let open_channels_nodes = Arc::new(PaMutex::new(
ln_utils::get_open_channels_nodes_addresses(persister.clone(), channel_manager.clone()).await?,
));
spawn(ln_p2p::connect_to_nodes_loop(
open_channels_nodes.clone(),
peer_manager.clone(),
));
// Broadcast Node Announcement
spawn(ln_p2p::ln_node_announcement_loop(
channel_manager.clone(),
params.node_name,
params.node_color,
params.listening_port,
));
Ok(LightningCoin {
platform,
conf,
peer_manager,
background_processor,
channel_manager,
chain_monitor,
keys_manager,
invoice_payer,
persister,
db,
open_channels_nodes,
})
}
#[derive(Deserialize)]
pub struct ConnectToNodeRequest {
pub coin: String,
pub node_address: NodeAddress,
}
/// Connect to a certain node on the lightning network.
pub async fn connect_to_lightning_node(ctx: MmArc, req: ConnectToNodeRequest) -> ConnectToNodeResult<String> {
let coin = lp_coinfind_or_err(&ctx, &req.coin).await?;
let ln_coin = match coin {
MmCoinEnum::LightningCoin(c) => c,
_ => return MmError::err(ConnectToNodeError::UnsupportedCoin(coin.ticker().to_string())),
};
let node_pubkey = req.node_address.pubkey;
let node_addr = req.node_address.addr;
let res = connect_to_node(node_pubkey, node_addr, ln_coin.peer_manager.clone()).await?;
// If a node that we have an open channel with changed it's address, "connect_to_lightning_node"
// can be used to reconnect to the new address while saving this new address for reconnections.
if let ConnectToNodeRes::ConnectedSuccessfully { .. } = res {
if let Entry::Occupied(mut entry) = ln_coin.open_channels_nodes.lock().entry(node_pubkey) {
entry.insert(node_addr);
}
ln_coin
.persister
.save_nodes_addresses(ln_coin.open_channels_nodes)
.await?;
}
Ok(res.to_string())
}
#[derive(Clone, Debug, Deserialize, PartialEq)]
#[serde(tag = "type", content = "value")]
pub enum ChannelOpenAmount {
Exact(BigDecimal),
Max,
}
#[derive(Deserialize)]
pub struct OpenChannelRequest {
pub coin: String,
pub node_address: NodeAddress,
pub amount: ChannelOpenAmount,
/// The amount to push to the counterparty as part of the open, in milli-satoshi. Creates inbound liquidity for the channel.
/// By setting push_msat to a value, opening channel request will be equivalent to opening a channel then sending a payment with
/// the push_msat amount.
#[serde(default)]
pub push_msat: u64,
pub channel_options: Option<ChannelOptions>,
pub counterparty_locktime: Option<u16>,
pub our_htlc_minimum_msat: Option<u64>,
}
#[derive(Serialize)]
pub struct OpenChannelResponse {
rpc_channel_id: u64,
node_address: NodeAddress,
}
/// Opens a channel on the lightning network.
pub async fn open_channel(ctx: MmArc, req: OpenChannelRequest) -> OpenChannelResult<OpenChannelResponse> {
let coin = lp_coinfind_or_err(&ctx, &req.coin).await?;
let ln_coin = match coin {
MmCoinEnum::LightningCoin(c) => c,
_ => return MmError::err(OpenChannelError::UnsupportedCoin(coin.ticker().to_string())),
};
// Making sure that the node data is correct and that we can connect to it before doing more operations
let node_pubkey = req.node_address.pubkey;
let node_addr = req.node_address.addr;
connect_to_node(node_pubkey, node_addr, ln_coin.peer_manager.clone()).await?;
let platform_coin = ln_coin.platform_coin().clone();
let decimals = platform_coin.as_ref().decimals;
let my_address = platform_coin.as_ref().derivation_method.iguana_or_err()?;
let (unspents, _) = platform_coin.get_unspent_ordered_list(my_address).await?;
let (value, fee_policy) = match req.amount.clone() {
ChannelOpenAmount::Max => (
unspents.iter().fold(0, |sum, unspent| sum + unspent.value),
FeePolicy::DeductFromOutput(0),
),
ChannelOpenAmount::Exact(v) => {
let value = sat_from_big_decimal(&v, decimals)?;
(value, FeePolicy::SendExact)
},
};
// The actual script_pubkey will replace this before signing the transaction after receiving the required
// output script from the other node when the channel is accepted
let script_pubkey =
Builder::build_witness_script(&AddressHashEnum::WitnessScriptHash(Default::default())).to_bytes();
let outputs = vec![TransactionOutput { value, script_pubkey }];
let mut tx_builder = UtxoTxBuilder::new(&platform_coin)
.add_available_inputs(unspents)
.add_outputs(outputs)
.with_fee_policy(fee_policy);
let fee = platform_coin
.get_tx_fee()
.await
.map_err(|e| OpenChannelError::RpcError(e.to_string()))?;
tx_builder = tx_builder.with_fee(fee);
let (unsigned, _) = tx_builder.build().await?;
let amount_in_sat = unsigned.outputs[0].value;
let push_msat = req.push_msat;
let channel_manager = ln_coin.channel_manager.clone();
let mut conf = ln_coin.conf.clone();
if let Some(options) = req.channel_options {
match conf.channel_options.as_mut() {
Some(o) => o.update(options),
None => conf.channel_options = Some(options),
}
}
let mut user_config: UserConfig = conf.into();
if let Some(locktime) = req.counterparty_locktime {
user_config.own_channel_config.our_to_self_delay = locktime;
}
if let Some(min) = req.our_htlc_minimum_msat {
user_config.own_channel_config.our_htlc_minimum_msat = min;
}
let rpc_channel_id = ln_coin.db.get_last_channel_rpc_id().await? as u64 + 1;
let temp_channel_id = async_blocking(move || {
channel_manager
.create_channel(node_pubkey, amount_in_sat, push_msat, rpc_channel_id, Some(user_config))
.map_to_mm(|e| OpenChannelError::FailureToOpenChannel(node_pubkey.to_string(), format!("{:?}", e)))
})
.await?;
{
let mut unsigned_funding_txs = ln_coin.platform.unsigned_funding_txs.lock();
unsigned_funding_txs.insert(rpc_channel_id, unsigned);
}
let pending_channel_details = DBChannelDetails::new(
rpc_channel_id,
temp_channel_id,
node_pubkey,
true,
user_config.channel_options.announced_channel,
);
// Saving node data to reconnect to it on restart
ln_coin.open_channels_nodes.lock().insert(node_pubkey, node_addr);
ln_coin
.persister
.save_nodes_addresses(ln_coin.open_channels_nodes)
.await?;
if let Err(e) = ln_coin.db.add_channel_to_db(pending_channel_details).await {
error!("Unable to add new outbound channel {} to db: {}", rpc_channel_id, e);
}
Ok(OpenChannelResponse {
rpc_channel_id,
node_address: req.node_address,
})
}
#[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 confirmed: Option<bool>,
pub is_usable: Option<bool>,
pub is_public: Option<bool>,
}
fn apply_open_channel_filter(channel_details: &ChannelDetailsForRPC, filter: &OpenChannelsFilter) -> bool {
let is_channel_id = filter.channel_id.is_none() || Some(&channel_details.channel_id) == filter.channel_id.as_ref();
let is_counterparty_node_id = filter.counterparty_node_id.is_none()
|| Some(&channel_details.counterparty_node_id) == filter.counterparty_node_id.as_ref();
let is_funding_tx = filter.funding_tx.is_none() || channel_details.funding_tx == filter.funding_tx;
let is_from_funding_value_sats =
Some(&channel_details.funding_tx_value_sats) >= filter.from_funding_value_sats.as_ref();
let is_to_funding_value_sats = filter.to_funding_value_sats.is_none()
|| Some(&channel_details.funding_tx_value_sats) <= filter.to_funding_value_sats.as_ref();
let is_outbound = filter.is_outbound.is_none() || Some(&channel_details.is_outbound) == filter.is_outbound.as_ref();
let is_from_balance_msat = Some(&channel_details.balance_msat) >= filter.from_balance_msat.as_ref();
let is_to_balance_msat =
filter.to_balance_msat.is_none() || Some(&channel_details.balance_msat) <= filter.to_balance_msat.as_ref();
let is_from_outbound_capacity_msat =
Some(&channel_details.outbound_capacity_msat) >= filter.from_outbound_capacity_msat.as_ref();
let is_to_outbound_capacity_msat = filter.to_outbound_capacity_msat.is_none()
|| Some(&channel_details.outbound_capacity_msat) <= filter.to_outbound_capacity_msat.as_ref();
let is_from_inbound_capacity_msat =
Some(&channel_details.inbound_capacity_msat) >= filter.from_inbound_capacity_msat.as_ref();
let is_to_inbound_capacity_msat = filter.to_inbound_capacity_msat.is_none()
|| Some(&channel_details.inbound_capacity_msat) <= filter.to_inbound_capacity_msat.as_ref();
let is_confirmed = filter.confirmed.is_none() || Some(&channel_details.confirmed) == filter.confirmed.as_ref();
let is_usable = filter.is_usable.is_none() || Some(&channel_details.is_usable) == filter.is_usable.as_ref();
let is_public = filter.is_public.is_none() || Some(&channel_details.is_public) == filter.is_public.as_ref();
is_channel_id
&& is_counterparty_node_id
&& is_funding_tx
&& is_from_funding_value_sats
&& is_to_funding_value_sats
&& is_outbound
&& is_from_balance_msat
&& is_to_balance_msat
&& is_from_outbound_capacity_msat
&& is_to_outbound_capacity_msat
&& is_from_inbound_capacity_msat
&& is_to_inbound_capacity_msat
&& is_confirmed
&& is_usable
&& is_public
}
#[derive(Deserialize)]
pub struct ListOpenChannelsRequest {
pub coin: String,
pub filter: Option<OpenChannelsFilter>,
#[serde(default = "ten")]
limit: usize,
#[serde(default)]
paging_options: PagingOptionsEnum<u64>,