forked from lightningdevkit/ldk-node
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlib.rs
More file actions
1653 lines (1470 loc) · 51.5 KB
/
lib.rs
File metadata and controls
1653 lines (1470 loc) · 51.5 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 contror
// 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.
#![crate_name = "ldk_node"]
//! # LDK Node
//! A ready-to-go Lightning node library built using [LDK](https://lightningdevkit.org/) and
//! [BDK](https://bitcoindevkit.org/).
//!
//! LDK Node is a non-custodial Lightning node in library form. Its central goal is to provide a
//! small, simple, and straightforward interface that enables users to easily set up and run a
//! Lightning node with an integrated on-chain wallet. While minimalism is at its core, LDK Node
//! aims to be sufficiently modular and configurable to be useful for a variety of use cases.
//!
//! ## Getting Started
//!
//! The primary abstraction of the library is the [`Node`], which can be retrieved by setting up
//! and configuring a [`Builder`] to your liking and calling [`build`]. `Node` can then be
//! controlled via commands such as [`start`], [`stop`], [`connect_open_channel`],
//! [`send_payment`], etc.:
//!
//! ```no_run
//! use ldk_node::{Builder, NetAddress};
//! use ldk_node::lightning_invoice::Invoice;
//! use ldk_node::bitcoin::secp256k1::PublicKey;
//! use std::str::FromStr;
//!
//! fn main() {
//! let node = Builder::new()
//! .set_network("testnet")
//! .set_esplora_server_url("https://blockstream.info/testnet/api".to_string())
//! .build();
//!
//! node.start().unwrap();
//!
//! let _funding_address = node.new_funding_address();
//!
//! // .. fund address ..
//!
//! node.sync_wallets().unwrap();
//!
//! let node_id = PublicKey::from_str("NODE_ID").unwrap();
//! let node_addr = NetAddress::from_str("IP_ADDR:PORT").unwrap();
//! node.connect_open_channel(node_id, node_addr, 10000, None, false).unwrap();
//!
//! let invoice = Invoice::from_str("INVOICE_STR").unwrap();
//! node.send_payment(&invoice).unwrap();
//!
//! node.stop().unwrap();
//! }
//! ```
//!
//! [`build`]: Builder::build
//! [`start`]: Node::start
//! [`stop`]: Node::stop
//! [`connect_open_channel`]: Node::connect_open_channel
//! [`send_payment`]: Node::send_payment
//!
// We currently disable the missing_docs lint due to incompatibility with the generated Uniffi
// scaffolding.
// TODO: Re-enable after https://github.com/mozilla/uniffi-rs/issues/1502 has been
// addressed.
//#![deny(missing_docs)]
#![deny(rustdoc::broken_intra_doc_links)]
#![deny(rustdoc::private_intra_doc_links)]
#![allow(bare_trait_objects)]
#![allow(ellipsis_inclusive_range_patterns)]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
mod error;
mod event;
mod gossip;
mod hex_utils;
mod io;
mod logger;
mod payment_store;
mod peer_store;
#[cfg(test)]
mod test;
mod types;
mod wallet;
pub use bip39;
pub use bitcoin;
pub use lightning;
use lightning::ln::msgs::RoutingMessageHandler;
pub use lightning_invoice;
pub use error::Error as NodeError;
use error::Error;
pub use event::Event;
pub use types::NetAddress;
use event::{EventHandler, EventQueue};
use gossip::GossipSource;
use io::fs_store::FilesystemStore;
use io::{KVStore, CHANNEL_MANAGER_PERSISTENCE_KEY, CHANNEL_MANAGER_PERSISTENCE_NAMESPACE};
use payment_store::PaymentStore;
pub use payment_store::{PaymentDetails, PaymentDirection, PaymentStatus};
use peer_store::{PeerInfo, PeerStore};
use types::{
ChainMonitor, ChannelManager, GossipSync, KeysManager, NetworkGraph, OnionMessenger,
PeerManager, Scorer,
};
pub use types::{ChannelDetails, ChannelId, PeerDetails, UserChannelId};
use wallet::Wallet;
use logger::{log_error, log_info, FilesystemLogger, Logger};
use lightning::chain::keysinterface::EntropySource;
use lightning::chain::{chainmonitor, BestBlock, Confirm, Watch};
use lightning::ln::channelmanager::{
self, ChainParameters, ChannelManagerReadArgs, PaymentId, RecipientOnionFields, Retry,
};
use lightning::ln::peer_handler::{IgnoringMessageHandler, MessageHandler};
use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
use lightning::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
use lightning::util::config::{ChannelHandshakeConfig, ChannelHandshakeLimits, UserConfig};
use lightning::util::ser::ReadableArgs;
use lightning_background_processor::process_events_async;
use lightning_transaction_sync::EsploraSyncClient;
use lightning::routing::router::{DefaultRouter, PaymentParameters, RouteParameters};
use lightning_invoice::{payment, Currency, Invoice};
use bdk::bitcoin::secp256k1::Secp256k1;
use bdk::blockchain::esplora::EsploraBlockchain;
use bdk::database::SqliteDatabase;
use bdk::template::Bip84;
use bitcoin::hashes::sha256::Hash as Sha256;
use bitcoin::hashes::Hash;
use bitcoin::secp256k1::PublicKey;
use bitcoin::Network;
use bitcoin::{Address, BlockHash, OutPoint, Txid};
use rand::Rng;
use std::convert::TryInto;
use std::default::Default;
use std::fs;
use std::net::ToSocketAddrs;
use std::str::FromStr;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant, SystemTime};
uniffi::include_scaffolding!("ldk_node");
// The 'stop gap' parameter used by BDK's wallet sync. This seems to configure the threshold
// number of blocks after which BDK stops looking for scripts belonging to the wallet.
const BDK_CLIENT_STOP_GAP: usize = 20;
// The number of concurrent requests made against the API provider.
const BDK_CLIENT_CONCURRENCY: u8 = 8;
// The timeout after which we abandon retrying failed payments.
const LDK_PAYMENT_RETRY_TIMEOUT: Duration = Duration::from_secs(10);
// The time in between peer reconnection attempts.
const PEER_RECONNECTION_INTERVAL: Duration = Duration::from_secs(10);
// The length in bytes of our wallets' keys seed.
const WALLET_KEYS_SEED_LEN: usize = 64;
#[derive(Debug, Clone)]
/// Represents the configuration of an [`Node`] instance.
pub struct Config {
/// The path where the underlying LDK and BDK persist their data.
pub storage_dir_path: String,
/// The URL of the utilized Esplora server.
pub esplora_server_url: String,
/// The used Bitcoin network.
pub network: Network,
/// The IP address and TCP port the node will listen on.
pub listening_address: Option<NetAddress>,
/// The default CLTV expiry delta to be used for payments.
pub default_cltv_expiry_delta: u32,
}
impl Default for Config {
fn default() -> Self {
Self {
storage_dir_path: "/tmp/ldk_node/".to_string(),
esplora_server_url: "http://localhost:3002".to_string(),
network: Network::Regtest,
listening_address: Some("0.0.0.0:9735".parse().unwrap()),
default_cltv_expiry_delta: 144,
}
}
}
#[derive(Debug, Clone)]
enum EntropySourceConfig {
SeedFile(String),
SeedBytes([u8; WALLET_KEYS_SEED_LEN]),
Bip39Mnemonic { mnemonic: bip39::Mnemonic, passphrase: Option<String> },
}
#[derive(Debug, Clone)]
enum GossipSourceConfig {
P2PNetwork,
RapidGossipSync(String),
}
/// A builder for an [`Node`] instance, allowing to set some configuration and module choices from
/// the getgo.
#[derive(Debug, Clone)]
pub struct Builder {
config: Config,
entropy_source_config: Option<EntropySourceConfig>,
gossip_source_config: Option<GossipSourceConfig>,
}
impl Builder {
/// Creates a new builder instance with the default configuration.
pub fn new() -> Self {
let config = Config::default();
let entropy_source_config = None;
let gossip_source_config = None;
Self { config, entropy_source_config, gossip_source_config }
}
/// Creates a new builder instance from an [`Config`].
pub fn from_config(config: Config) -> Self {
let entropy_source_config = None;
let gossip_source_config = None;
Self { config, entropy_source_config, gossip_source_config }
}
/// Configures the [`Node`] instance to source its wallet entropy from a seed file on disk.
///
/// If the given file does not exist a new random seed file will be generated and
/// stored at the given location.
pub fn set_entropy_seed_path(&mut self, seed_path: String) -> &mut Self {
self.entropy_source_config = Some(EntropySourceConfig::SeedFile(seed_path));
self
}
/// Configures the [`Node`] instance to source its wallet entropy from the given seed bytes.
pub fn set_entropy_seed_bytes(&mut self, seed_bytes: [u8; WALLET_KEYS_SEED_LEN]) -> &mut Self {
self.entropy_source_config = Some(EntropySourceConfig::SeedBytes(seed_bytes));
self
}
/// Configures the [`Node`] instance to source its gossip data from the Lightning peer-to-peer
/// network.
pub fn set_gossip_source_p2p(&mut self) -> &mut Self {
self.gossip_source_config = Some(GossipSourceConfig::P2PNetwork);
self
}
/// Configures the [`Node`] instance to source its gossip data from the given RapidGossipSync
/// server.
pub fn set_gossip_source_rgs(&mut self, rgs_server_url: String) -> &mut Self {
self.gossip_source_config = Some(GossipSourceConfig::RapidGossipSync(rgs_server_url));
self
}
/// Configures the [`Node`] instance to source its wallet entropy from a [BIP 39] mnemonic.
///
/// [BIP 39]: https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki
pub fn set_entropy_bip39_mnemonic(
&mut self, mnemonic: bip39::Mnemonic, passphrase: Option<String>,
) -> &mut Self {
self.entropy_source_config =
Some(EntropySourceConfig::Bip39Mnemonic { mnemonic, passphrase });
self
}
/// Sets the used storage directory path.
///
/// Default: `/tmp/ldk_node/`
pub fn set_storage_dir_path(&mut self, storage_dir_path: String) -> &mut Self {
self.config.storage_dir_path = storage_dir_path;
self
}
/// Sets the Esplora server URL.
///
/// Default: `https://blockstream.info/api`
pub fn set_esplora_server_url(&mut self, esplora_server_url: String) -> &mut Self {
self.config.esplora_server_url = esplora_server_url;
self
}
/// Sets the Bitcoin network used.
///
/// Options: `mainnet`/`bitcoin`, `testnet`, `regtest`, `signet`
///
/// Default: `regtest`
pub fn set_network(&mut self, network: &str) -> &mut Self {
self.config.network = Network::from_str(network).unwrap_or(Network::Regtest);
self
}
/// Sets the IP address and TCP port on which [`Node`] will listen for incoming network connections.
///
/// Default: `0.0.0.0:9735`
pub fn set_listening_address(&mut self, listening_address: NetAddress) -> &mut Self {
self.config.listening_address = Some(listening_address);
self
}
/// Builds a [`Node`] instance according to the options previously configured.
pub fn build(&self) -> Arc<Node> {
let config = Arc::new(self.config.clone());
let ldk_data_dir = format!("{}/ldk", config.storage_dir_path);
fs::create_dir_all(ldk_data_dir.clone()).expect("Failed to create LDK data directory");
let bdk_data_dir = format!("{}/bdk", config.storage_dir_path);
fs::create_dir_all(bdk_data_dir.clone()).expect("Failed to create BDK data directory");
// Initialize the Logger
let log_file_path = format!("{}/ldk_node.log", config.storage_dir_path);
let logger = Arc::new(FilesystemLogger::new(log_file_path));
// Initialize the on-chain wallet and chain access
let seed_bytes = if let Some(entropy_source_config) = &self.entropy_source_config {
// Use the configured entropy source, if the user set one.
match entropy_source_config {
EntropySourceConfig::SeedBytes(bytes) => bytes.clone(),
EntropySourceConfig::SeedFile(seed_path) => {
io::utils::read_or_generate_seed_file(seed_path)
}
EntropySourceConfig::Bip39Mnemonic { mnemonic, passphrase } => match passphrase {
Some(passphrase) => mnemonic.to_seed(passphrase),
None => mnemonic.to_seed(""),
},
}
} else {
// Default to read or generate from the default location generate a seed file.
let seed_path = format!("{}/keys_seed", config.storage_dir_path);
io::utils::read_or_generate_seed_file(&seed_path)
};
let xprv = bitcoin::util::bip32::ExtendedPrivKey::new_master(config.network, &seed_bytes)
.expect("Failed to read wallet master key");
let wallet_name = bdk::wallet::wallet_name_from_descriptor(
Bip84(xprv, bdk::KeychainKind::External),
Some(Bip84(xprv, bdk::KeychainKind::Internal)),
config.network,
&Secp256k1::new(),
)
.expect("Failed to derive on-chain wallet name");
let database_path = format!("{}/{}.sqlite", bdk_data_dir, wallet_name);
let database = SqliteDatabase::new(database_path);
let bdk_wallet = bdk::Wallet::new(
Bip84(xprv, bdk::KeychainKind::External),
Some(Bip84(xprv, bdk::KeychainKind::Internal)),
config.network,
database,
)
.expect("Failed to set up on-chain wallet");
let tx_sync = Arc::new(EsploraSyncClient::new(
config.esplora_server_url.clone(),
Arc::clone(&logger),
));
let blockchain =
EsploraBlockchain::from_client(tx_sync.client().clone(), BDK_CLIENT_STOP_GAP)
.with_concurrency(BDK_CLIENT_CONCURRENCY);
let runtime = Arc::new(RwLock::new(None));
let wallet = Arc::new(Wallet::new(
blockchain,
bdk_wallet,
Arc::clone(&runtime),
Arc::clone(&logger),
));
let kv_store = Arc::new(FilesystemStore::new(ldk_data_dir.clone().into()));
// Initialize the ChainMonitor
let chain_monitor: Arc<ChainMonitor> = Arc::new(chainmonitor::ChainMonitor::new(
Some(Arc::clone(&tx_sync)),
Arc::clone(&wallet),
Arc::clone(&logger),
Arc::clone(&wallet),
Arc::clone(&kv_store),
));
// Initialize the KeysManager
let cur_time = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.expect("System time error: Clock may have gone backwards");
let ldk_seed_bytes: [u8; 32] = xprv.private_key.secret_bytes();
let keys_manager = Arc::new(KeysManager::new(
&ldk_seed_bytes,
cur_time.as_secs(),
cur_time.subsec_nanos(),
Arc::clone(&wallet),
));
// Initialize the network graph, scorer, and router
let network_graph =
match io::utils::read_network_graph(Arc::clone(&kv_store), Arc::clone(&logger)) {
Ok(graph) => Arc::new(graph),
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
Arc::new(NetworkGraph::new(config.network, Arc::clone(&logger)))
} else {
log_error!(logger, "Failed to read network graph: {}", e.to_string());
panic!("Failed to read network graph: {}", e.to_string());
}
}
};
let scorer = match io::utils::read_scorer(
Arc::clone(&kv_store),
Arc::clone(&network_graph),
Arc::clone(&logger),
) {
Ok(scorer) => Arc::new(Mutex::new(scorer)),
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
let params = ProbabilisticScoringParameters::default();
Arc::new(Mutex::new(ProbabilisticScorer::new(
params,
Arc::clone(&network_graph),
Arc::clone(&logger),
)))
} else {
log_error!(logger, "Failed to read scorer: {}", e.to_string());
panic!("Failed to read scorer: {}", e.to_string());
}
}
};
let router = Arc::new(DefaultRouter::new(
Arc::clone(&network_graph),
Arc::clone(&logger),
keys_manager.get_secure_random_bytes(),
Arc::clone(&scorer),
));
// Read ChannelMonitor state from store
let mut channel_monitors = match io::utils::read_channel_monitors(
Arc::clone(&kv_store),
Arc::clone(&keys_manager),
Arc::clone(&keys_manager),
) {
Ok(monitors) => monitors,
Err(e) => {
log_error!(logger, "Failed to read channel monitors: {}", e.to_string());
panic!("Failed to read channel monitors: {}", e.to_string());
}
};
// Initialize the ChannelManager
let mut user_config = UserConfig::default();
user_config.channel_handshake_limits.force_announced_channel_preference = false;
let channel_manager = {
if let Ok(mut reader) = kv_store
.read(CHANNEL_MANAGER_PERSISTENCE_NAMESPACE, CHANNEL_MANAGER_PERSISTENCE_KEY)
{
let channel_monitor_references =
channel_monitors.iter_mut().map(|(_, chanmon)| chanmon).collect();
let read_args = ChannelManagerReadArgs::new(
Arc::clone(&keys_manager),
Arc::clone(&keys_manager),
Arc::clone(&keys_manager),
Arc::clone(&wallet),
Arc::clone(&chain_monitor),
Arc::clone(&wallet),
Arc::clone(&router),
Arc::clone(&logger),
user_config,
channel_monitor_references,
);
let (_hash, channel_manager) =
<(BlockHash, ChannelManager)>::read(&mut reader, read_args)
.expect("Failed to read channel manager from store");
channel_manager
} else {
// We're starting a fresh node.
let genesis_block_hash =
bitcoin::blockdata::constants::genesis_block(config.network).block_hash();
let chain_params = ChainParameters {
network: config.network,
best_block: BestBlock::new(genesis_block_hash, 0),
};
channelmanager::ChannelManager::new(
Arc::clone(&wallet),
Arc::clone(&chain_monitor),
Arc::clone(&wallet),
Arc::clone(&router),
Arc::clone(&logger),
Arc::clone(&keys_manager),
Arc::clone(&keys_manager),
Arc::clone(&keys_manager),
user_config,
chain_params,
)
}
};
let channel_manager = Arc::new(channel_manager);
// Give ChannelMonitors to ChainMonitor
for (_blockhash, channel_monitor) in channel_monitors.into_iter() {
let funding_outpoint = channel_monitor.get_funding_txo().0;
chain_monitor.watch_channel(funding_outpoint, channel_monitor);
}
// Initialize the PeerManager
let onion_messenger: Arc<OnionMessenger> = Arc::new(OnionMessenger::new(
Arc::clone(&keys_manager),
Arc::clone(&keys_manager),
Arc::clone(&logger),
IgnoringMessageHandler {},
));
let ephemeral_bytes: [u8; 32] = keys_manager.get_secure_random_bytes();
let cur_time = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.expect("System time error: Clock may have gone backwards");
// Initialize the GossipSource
// Use the configured gossip source, if the user set one, otherwise default to P2PNetwork.
let gossip_source_config =
self.gossip_source_config.as_ref().unwrap_or(&GossipSourceConfig::P2PNetwork);
let gossip_source = match gossip_source_config {
GossipSourceConfig::P2PNetwork => {
let p2p_source = Arc::new(GossipSource::new_p2p(
Arc::clone(&network_graph),
Arc::clone(&logger),
));
// Reset the RGS sync timestamp in case we somehow switch gossip sources
io::utils::write_rgs_latest_sync_timestamp(
0,
Arc::clone(&kv_store),
Arc::clone(&logger),
)
.expect("Persistence failed");
p2p_source
}
GossipSourceConfig::RapidGossipSync(rgs_server) => {
let latest_sync_timestamp =
io::utils::read_rgs_latest_sync_timestamp(Arc::clone(&kv_store)).unwrap_or(0);
Arc::new(GossipSource::new_rgs(
rgs_server.clone(),
latest_sync_timestamp,
Arc::clone(&network_graph),
Arc::clone(&logger),
))
}
};
let msg_handler = match gossip_source.as_gossip_sync() {
GossipSync::P2P(p2p_gossip_sync) => MessageHandler {
chan_handler: Arc::clone(&channel_manager),
route_handler: Arc::clone(&p2p_gossip_sync)
as Arc<dyn RoutingMessageHandler + Sync + Send>,
onion_message_handler: onion_messenger,
},
GossipSync::Rapid(_) => MessageHandler {
chan_handler: Arc::clone(&channel_manager),
route_handler: Arc::new(IgnoringMessageHandler {})
as Arc<dyn RoutingMessageHandler + Sync + Send>,
onion_message_handler: onion_messenger,
},
GossipSync::None => {
unreachable!("We must always have a gossip sync!");
}
};
let peer_manager = Arc::new(PeerManager::new(
msg_handler,
cur_time.as_secs().try_into().expect("System time error"),
&ephemeral_bytes,
Arc::clone(&logger),
IgnoringMessageHandler {},
Arc::clone(&keys_manager),
));
// Init payment info storage
let payment_store = match io::utils::read_payments(Arc::clone(&kv_store)) {
Ok(payments) => {
Arc::new(PaymentStore::new(payments, Arc::clone(&kv_store), Arc::clone(&logger)))
}
Err(e) => {
log_error!(logger, "Failed to read payment information: {}", e.to_string());
panic!("Failed to read payment information: {}", e.to_string());
}
};
let event_queue =
match io::utils::read_event_queue(Arc::clone(&kv_store), Arc::clone(&logger)) {
Ok(event_queue) => Arc::new(event_queue),
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
Arc::new(EventQueue::new(Arc::clone(&kv_store), Arc::clone(&logger)))
} else {
log_error!(logger, "Failed to read event queue: {}", e.to_string());
panic!("Failed to read event queue: {}", e.to_string());
}
}
};
let peer_store = match io::utils::read_peer_info(Arc::clone(&kv_store), Arc::clone(&logger))
{
Ok(peer_store) => Arc::new(peer_store),
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
Arc::new(PeerStore::new(Arc::clone(&kv_store), Arc::clone(&logger)))
} else {
log_error!(logger, "Failed to read peer store: {}", e.to_string());
panic!("Failed to read peer store: {}", e.to_string());
}
}
};
let stop_running = Arc::new(AtomicBool::new(false));
Arc::new(Node {
runtime,
stop_running,
config,
wallet,
tx_sync,
event_queue,
channel_manager,
chain_monitor,
peer_manager,
keys_manager,
network_graph,
gossip_source,
kv_store,
logger,
scorer,
peer_store,
payment_store,
})
}
}
/// The main interface object of LDK Node, wrapping the necessary LDK and BDK functionalities.
///
/// Needs to be initialized and instantiated through [`Builder::build`].
pub struct Node {
runtime: Arc<RwLock<Option<tokio::runtime::Runtime>>>,
stop_running: Arc<AtomicBool>,
config: Arc<Config>,
wallet: Arc<Wallet<bdk::database::SqliteDatabase>>,
tx_sync: Arc<EsploraSyncClient<Arc<FilesystemLogger>>>,
event_queue: Arc<EventQueue<Arc<FilesystemStore>, Arc<FilesystemLogger>>>,
channel_manager: Arc<ChannelManager>,
chain_monitor: Arc<ChainMonitor>,
peer_manager: Arc<PeerManager>,
keys_manager: Arc<KeysManager>,
network_graph: Arc<NetworkGraph>,
gossip_source: Arc<GossipSource>,
kv_store: Arc<FilesystemStore>,
logger: Arc<FilesystemLogger>,
scorer: Arc<Mutex<Scorer>>,
peer_store: Arc<PeerStore<Arc<FilesystemStore>, Arc<FilesystemLogger>>>,
payment_store: Arc<PaymentStore<Arc<FilesystemStore>, Arc<FilesystemLogger>>>,
}
impl Node {
/// Starts the necessary background tasks, such as handling events coming from user input,
/// LDK/BDK, and the peer-to-peer network.
///
/// After this returns, the [`Node`] instance can be controlled via the provided API methods in
/// a thread-safe manner.
pub fn start(&self) -> Result<(), Error> {
// Acquire a run lock and hold it until we're setup.
let mut runtime_lock = self.runtime.write().unwrap();
if runtime_lock.is_some() {
// We're already running.
return Err(Error::AlreadyRunning);
}
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap();
let stop_running = Arc::new(AtomicBool::new(false));
let event_handler = Arc::new(EventHandler::new(
Arc::clone(&self.wallet),
Arc::clone(&self.event_queue),
Arc::clone(&self.channel_manager),
Arc::clone(&self.network_graph),
Arc::clone(&self.keys_manager),
Arc::clone(&self.payment_store),
Arc::clone(&self.runtime),
Arc::clone(&self.logger),
Arc::clone(&self.config),
));
// Setup wallet sync
let wallet = Arc::clone(&self.wallet);
let tx_sync = Arc::clone(&self.tx_sync);
let sync_cman = Arc::clone(&self.channel_manager);
let sync_cmon = Arc::clone(&self.chain_monitor);
let sync_logger = Arc::clone(&self.logger);
let stop_sync = Arc::clone(&stop_running);
std::thread::spawn(move || {
tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(
async move {
loop {
if stop_sync.load(Ordering::Acquire) {
return;
}
let now = Instant::now();
match wallet.sync().await {
Ok(()) => log_info!(
sync_logger,
"Background sync of on-chain wallet finished in {}ms.",
now.elapsed().as_millis()
),
Err(err) => {
log_error!(
sync_logger,
"Background sync of on-chain wallet failed: {}",
err
)
}
}
tokio::time::sleep(Duration::from_secs(20)).await;
}
},
);
});
if self.gossip_source.is_rgs() {
let gossip_source = Arc::clone(&self.gossip_source);
let gossip_sync_store = Arc::clone(&self.kv_store);
let gossip_sync_logger = Arc::clone(&self.logger);
let stop_gossip_sync = Arc::clone(&stop_running);
runtime.spawn(async move {
loop {
let gossip_sync_logger = Arc::clone(&gossip_sync_logger);
let stop_gossip_sync = Arc::clone(&stop_gossip_sync);
if stop_gossip_sync.load(Ordering::Acquire) {
return;
}
let now = Instant::now();
match gossip_source.update_rgs_snapshot().await {
Ok(updated_timestamp) => {
log_info!(
gossip_sync_logger,
"Background sync of RGS gossip data finished in {}ms.",
now.elapsed().as_millis()
);
io::utils::write_rgs_latest_sync_timestamp(
updated_timestamp,
Arc::clone(&gossip_sync_store),
Arc::clone(&gossip_sync_logger),
)
.expect("Persistence failed");
}
Err(e) => log_error!(
gossip_sync_logger,
"Background sync of RGS gossip data failed: {}",
e
),
}
tokio::time::sleep(Duration::from_secs(60 * 60)).await;
}
});
}
let sync_logger = Arc::clone(&self.logger);
let stop_sync = Arc::clone(&stop_running);
runtime.spawn(async move {
loop {
if stop_sync.load(Ordering::Acquire) {
return;
}
let now = Instant::now();
let confirmables = vec![
&*sync_cman as &(dyn Confirm + Sync + Send),
&*sync_cmon as &(dyn Confirm + Sync + Send),
];
match tx_sync.sync(confirmables).await {
Ok(()) => log_info!(
sync_logger,
"Background sync of Lightning wallet finished in {}ms.",
now.elapsed().as_millis()
),
Err(e) => {
log_error!(sync_logger, "Background sync of Lightning wallet failed: {}", e)
}
}
tokio::time::sleep(Duration::from_secs(5)).await;
}
});
if let Some(listening_address) = &self.config.listening_address {
// Setup networking
let peer_manager_connection_handler = Arc::clone(&self.peer_manager);
let stop_listen = Arc::clone(&stop_running);
let listening_address = listening_address.clone();
let bind_addr = listening_address
.to_socket_addrs()
.expect("Unable to resolve listing address")
.next()
.expect("Unable to resolve listing address");
runtime.spawn(async move {
let listener =
tokio::net::TcpListener::bind(bind_addr).await.expect(
"Failed to bind to listen address/port - is something else already listening on it?",
);
loop {
if stop_listen.load(Ordering::Acquire) {
return;
}
let peer_mgr = Arc::clone(&peer_manager_connection_handler);
let tcp_stream = listener.accept().await.unwrap().0;
tokio::spawn(async move {
lightning_net_tokio::setup_inbound(
Arc::clone(&peer_mgr),
tcp_stream.into_std().unwrap(),
)
.await;
});
}
});
}
// Regularly reconnect to channel peers.
let connect_cm = Arc::clone(&self.channel_manager);
let connect_pm = Arc::clone(&self.peer_manager);
let connect_logger = Arc::clone(&self.logger);
let connect_peer_store = Arc::clone(&self.peer_store);
let stop_connect = Arc::clone(&stop_running);
runtime.spawn(async move {
let mut interval = tokio::time::interval(PEER_RECONNECTION_INTERVAL);
loop {
if stop_connect.load(Ordering::Acquire) {
return;
}
let pm_peers = connect_pm
.get_peer_node_ids()
.iter()
.map(|(peer, _addr)| *peer)
.collect::<Vec<_>>();
for node_id in connect_cm
.list_channels()
.iter()
.map(|chan| chan.counterparty.node_id)
.filter(|id| !pm_peers.contains(id))
{
if let Some(peer_info) = connect_peer_store.get_peer(&node_id) {
let _ = do_connect_peer(
peer_info.node_id,
peer_info.address,
Arc::clone(&connect_pm),
Arc::clone(&connect_logger),
)
.await;
}
}
interval.tick().await;
}
});
// Setup background processing
let background_persister = Arc::clone(&self.kv_store);
let background_event_handler = Arc::clone(&event_handler);
let background_chain_mon = Arc::clone(&self.chain_monitor);
let background_chan_man = Arc::clone(&self.channel_manager);
let background_gossip_sync = self.gossip_source.as_gossip_sync();
let background_peer_man = Arc::clone(&self.peer_manager);
let background_logger = Arc::clone(&self.logger);
let background_scorer = Arc::clone(&self.scorer);
let stop_background_processing = Arc::clone(&stop_running);
let sleeper = move |d| {
let stop = Arc::clone(&stop_background_processing);
Box::pin(async move {
if stop.load(Ordering::Acquire) {
true
} else {
tokio::time::sleep(d).await;
false
}
})
};
runtime.spawn(async move {
process_events_async(
background_persister,
|e| background_event_handler.handle_event(e),
background_chain_mon,
background_chan_man,
background_gossip_sync,
background_peer_man,
background_logger,
Some(background_scorer),
sleeper,
true,
)
.await
.expect("Failed to process events");
});
*runtime_lock = Some(runtime);
Ok(())
}
/// Disconnects all peers, stops all running background tasks, and shuts down [`Node`].
///
/// After this returns most API methods will return [`Error::NotRunning`].
pub fn stop(&self) -> Result<(), Error> {
let runtime = self.runtime.write().unwrap().take().ok_or(Error::NotRunning)?;
// Stop the runtime.
self.stop_running.store(true, Ordering::Release);
// Stop disconnect peers.
self.peer_manager.disconnect_all_peers();
runtime.shutdown_timeout(Duration::from_secs(10));
Ok(())
}
/// Returns the next event in the event queue, if currently available.
///
/// Will return `Some(..)` if an event is available and `None` otherwise.
///
/// **Note:** this will always return the same event until handling is confirmed via [`Node::event_handled`].
pub fn next_event(&self) -> Option<Event> {
self.event_queue.next_event()
}
/// Returns the next event in the event queue.
///
/// Will block the current thread until the next event is available.
///
/// **Note:** this will always return the same event until handling is confirmed via [`Node::event_handled`].
pub fn wait_next_event(&self) -> Event {
self.event_queue.wait_next_event()
}
/// Confirm the last retrieved event handled.
///
/// **Note:** This **MUST** be called after each event has been handled.
pub fn event_handled(&self) {
self.event_queue.event_handled().unwrap();
}
/// Returns our own node id
pub fn node_id(&self) -> PublicKey {
self.channel_manager.get_our_node_id()
}
/// Returns our own listening address.
pub fn listening_address(&self) -> Option<NetAddress> {
self.config.listening_address.clone()
}
/// Retrieve a new on-chain/funding address.
pub fn new_funding_address(&self) -> Result<Address, Error> {
let funding_address = self.wallet.get_new_address()?;
log_info!(self.logger, "Generated new funding address: {}", funding_address);
Ok(funding_address)
}
/// Retrieve the current on-chain balance.
pub fn onchain_balance(&self) -> Result<bdk::Balance, Error> {
self.wallet.get_balance()
}
/// Send an on-chain payment to the given address.
pub fn send_to_onchain_address(
&self, address: &bitcoin::Address, amount_sats: u64,
) -> Result<Txid, Error> {
let rt_lock = self.runtime.read().unwrap();
if rt_lock.is_none() {
return Err(Error::NotRunning);
}
let cur_balance = self.wallet.get_balance()?;
if cur_balance.get_spendable() < amount_sats {
log_error!(self.logger, "Unable to send payment due to insufficient funds.");