-
Notifications
You must be signed in to change notification settings - Fork 130
Expand file tree
/
Copy pathbuilder.rs
More file actions
1904 lines (1737 loc) · 66.4 KB
/
builder.rs
File metadata and controls
1904 lines (1737 loc) · 66.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is Copyright its original authors, visible in version control history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
// accordance with one or both of these licenses.
use std::collections::HashMap;
use std::convert::TryInto;
use std::default::Default;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, Once, RwLock};
use std::time::SystemTime;
use std::{fmt, fs};
use bdk_wallet::template::Bip84;
use bdk_wallet::{KeychainKind, Wallet as BdkWallet};
use bitcoin::bip32::{ChildNumber, Xpriv};
use bitcoin::key::Secp256k1;
use bitcoin::secp256k1::PublicKey;
use bitcoin::{BlockHash, Network};
use lightning::chain::{chainmonitor, BestBlock, Watch};
use lightning::io::Cursor;
use lightning::ln::channelmanager::{self, ChainParameters, ChannelManagerReadArgs};
use lightning::ln::msgs::{RoutingMessageHandler, SocketAddress};
use lightning::ln::peer_handler::{IgnoringMessageHandler, MessageHandler};
use lightning::log_trace;
use lightning::routing::gossip::NodeAlias;
use lightning::routing::router::DefaultRouter;
use lightning::routing::scoring::{
CombinedScorer, ProbabilisticScorer, ProbabilisticScoringDecayParameters,
ProbabilisticScoringFeeParameters,
};
use lightning::sign::{EntropySource, NodeSigner};
use lightning::util::persist::{
KVStoreSync, CHANNEL_MANAGER_PERSISTENCE_KEY, CHANNEL_MANAGER_PERSISTENCE_PRIMARY_NAMESPACE,
CHANNEL_MANAGER_PERSISTENCE_SECONDARY_NAMESPACE,
};
use lightning::util::ser::ReadableArgs;
use lightning::util::sweep::OutputSweeper;
use lightning_persister::fs_store::FilesystemStore;
use vss_client::headers::VssHeaderProvider;
use crate::chain::ChainSource;
use crate::config::{
default_user_config, may_announce_channel, AnnounceError, AsyncPaymentsRole,
BitcoindRestClientConfig, Config, ElectrumSyncConfig, EsploraSyncConfig,
DEFAULT_ESPLORA_SERVER_URL, DEFAULT_LOG_FILENAME, DEFAULT_LOG_LEVEL,
};
use crate::connection::ConnectionManager;
use crate::entropy::NodeEntropy;
use crate::event::EventQueue;
use crate::fee_estimator::OnchainFeeEstimator;
use crate::gossip::GossipSource;
use crate::io::sqlite_store::SqliteStore;
use crate::io::utils::{
read_external_pathfinding_scores_from_cache, read_node_metrics, write_node_metrics,
};
use crate::io::vss_store::VssStoreBuilder;
use crate::io::{
self, PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE, PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE,
};
use crate::liquidity::{
LSPS1ClientConfig, LSPS2ClientConfig, LSPS2ServiceConfig, LSPS5ClientConfig,
LiquiditySourceBuilder,
};
use crate::logger::{log_error, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::asynchronous::om_mailbox::OnionMessageMailbox;
use crate::peer_store::PeerStore;
use crate::runtime::Runtime;
use crate::tx_broadcaster::TransactionBroadcaster;
use crate::types::{
ChainMonitor, ChannelManager, DynStore, DynStoreWrapper, GossipSync, Graph, KeysManager,
LSPS5ServiceConfig, MessageRouter, OnionMessenger, PaymentStore, PeerManager, Persister,
SyncAndAsyncKVStore,
};
use crate::wallet::persist::KVStoreWalletPersister;
use crate::wallet::Wallet;
use crate::{Node, NodeMetrics};
const LSPS_HARDENED_CHILD_INDEX: u32 = 577;
const PERSISTER_MAX_PENDING_UPDATES: u64 = 100;
#[derive(Debug, Clone)]
enum ChainDataSourceConfig {
Esplora {
server_url: String,
headers: HashMap<String, String>,
sync_config: Option<EsploraSyncConfig>,
},
Electrum {
server_url: String,
sync_config: Option<ElectrumSyncConfig>,
},
Bitcoind {
rpc_host: String,
rpc_port: u16,
rpc_user: String,
rpc_password: String,
rest_client_config: Option<BitcoindRestClientConfig>,
},
}
#[derive(Debug, Clone)]
enum GossipSourceConfig {
P2PNetwork,
RapidGossipSync(String),
}
#[derive(Debug, Clone)]
struct PathfindingScoresSyncConfig {
url: String,
}
#[derive(Debug, Clone, Default)]
struct LiquiditySourceConfig {
// Act as an LSPS1 client connecting to the given service.
lsps1_client: Option<LSPS1ClientConfig>,
// Act as an LSPS2 client connecting to the given service.
lsps2_client: Option<LSPS2ClientConfig>,
// Act as an LSPS2 service.
lsps2_service: Option<LSPS2ServiceConfig>,
// Act as an LSPS5 client connecting to the given service.
lsps5_client: Option<LSPS5ClientConfig>,
// Act as an LSPS5 service.
lsps5_service: Option<LSPS5ServiceConfig>,
// Optional custom HTTP client to be used by LSPS5 service.
http_client: Option<reqwest::Client>,
}
#[derive(Clone)]
enum LogWriterConfig {
File { log_file_path: Option<String>, max_log_level: Option<LogLevel> },
Log,
Custom(Arc<dyn LogWriter>),
}
impl std::fmt::Debug for LogWriterConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
LogWriterConfig::File { max_log_level, log_file_path } => f
.debug_struct("LogWriterConfig")
.field("max_log_level", max_log_level)
.field("log_file_path", log_file_path)
.finish(),
LogWriterConfig::Log => write!(f, "LogWriterConfig::Log"),
LogWriterConfig::Custom(_) => {
f.debug_tuple("Custom").field(&"<config internal to custom log writer>").finish()
},
}
}
}
/// An error encountered during building a [`Node`].
///
/// [`Node`]: crate::Node
#[derive(Debug, Clone, PartialEq)]
pub enum BuildError {
/// The current system time is invalid, clocks might have gone backwards.
InvalidSystemTime,
/// The a read channel monitor is invalid.
InvalidChannelMonitor,
/// The given listening addresses are invalid, e.g. too many were passed.
InvalidListeningAddresses,
/// The given announcement addresses are invalid, e.g. too many were passed.
InvalidAnnouncementAddresses,
/// The provided alias is invalid.
InvalidNodeAlias,
/// An attempt to setup a runtime has failed.
RuntimeSetupFailed,
/// We failed to read data from the [`KVStore`].
///
/// [`KVStore`]: lightning::util::persist::KVStoreSync
ReadFailed,
/// We failed to write data to the [`KVStore`].
///
/// [`KVStore`]: lightning::util::persist::KVStoreSync
WriteFailed,
/// We failed to access the given `storage_dir_path`.
StoragePathAccessFailed,
/// We failed to setup our [`KVStore`].
///
/// [`KVStore`]: lightning::util::persist::KVStoreSync
KVStoreSetupFailed,
/// We failed to setup the onchain wallet.
WalletSetupFailed,
/// We failed to setup the logger.
LoggerSetupFailed,
/// The given network does not match the node's previously configured network.
NetworkMismatch,
/// The role of the node in an asynchronous payments context is not compatible with the current configuration.
AsyncPaymentsConfigMismatch,
}
impl fmt::Display for BuildError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Self::InvalidSystemTime => {
write!(f, "System time is invalid. Clocks might have gone back in time.")
},
Self::InvalidChannelMonitor => {
write!(f, "Failed to watch a deserialized ChannelMonitor")
},
Self::InvalidListeningAddresses => write!(f, "Given listening addresses are invalid."),
Self::InvalidAnnouncementAddresses => {
write!(f, "Given announcement addresses are invalid.")
},
Self::RuntimeSetupFailed => write!(f, "Failed to setup a runtime."),
Self::ReadFailed => write!(f, "Failed to read from store."),
Self::WriteFailed => write!(f, "Failed to write to store."),
Self::StoragePathAccessFailed => write!(f, "Failed to access the given storage path."),
Self::KVStoreSetupFailed => write!(f, "Failed to setup KVStore."),
Self::WalletSetupFailed => write!(f, "Failed to setup onchain wallet."),
Self::LoggerSetupFailed => write!(f, "Failed to setup the logger."),
Self::InvalidNodeAlias => write!(f, "Given node alias is invalid."),
Self::NetworkMismatch => {
write!(f, "Given network does not match the node's previously configured network.")
},
Self::AsyncPaymentsConfigMismatch => {
write!(
f,
"The async payments role is not compatible with the current configuration."
)
},
}
}
}
impl std::error::Error for BuildError {}
/// A builder for an [`Node`] instance, allowing to set some configuration and module choices from
/// the getgo.
///
/// ### Defaults
/// - Wallet entropy is sourced from a `keys_seed` file located under [`Config::storage_dir_path`]
/// - Chain data is sourced from the Esplora endpoint `https://blockstream.info/api`
/// - Gossip data is sourced via the peer-to-peer network
#[derive(Debug)]
pub struct NodeBuilder {
config: Config,
chain_data_source_config: Option<ChainDataSourceConfig>,
gossip_source_config: Option<GossipSourceConfig>,
liquidity_source_config: Option<LiquiditySourceConfig>,
log_writer_config: Option<LogWriterConfig>,
async_payments_role: Option<AsyncPaymentsRole>,
runtime_handle: Option<tokio::runtime::Handle>,
pathfinding_scores_sync_config: Option<PathfindingScoresSyncConfig>,
}
impl NodeBuilder {
/// Creates a new builder instance with the default configuration.
pub fn new() -> Self {
let config = Config::default();
Self::from_config(config)
}
/// Creates a new builder instance from an [`Config`].
pub fn from_config(config: Config) -> Self {
let chain_data_source_config = None;
let gossip_source_config = None;
let liquidity_source_config = None;
let log_writer_config = None;
let runtime_handle = None;
let pathfinding_scores_sync_config = None;
Self {
config,
chain_data_source_config,
gossip_source_config,
liquidity_source_config,
log_writer_config,
runtime_handle,
async_payments_role: None,
pathfinding_scores_sync_config,
}
}
/// Configures the [`Node`] instance to (re-)use a specific `tokio` runtime.
///
/// If not provided, the node will spawn its own runtime or reuse any outer runtime context it
/// can detect.
#[cfg_attr(feature = "uniffi", allow(dead_code))]
pub fn set_runtime(&mut self, runtime_handle: tokio::runtime::Handle) -> &mut Self {
self.runtime_handle = Some(runtime_handle);
self
}
/// Configures the [`Node`] instance to source its chain data from the given Esplora server.
///
/// If no `sync_config` is given, default values are used. See [`EsploraSyncConfig`] for more
/// information.
pub fn set_chain_source_esplora(
&mut self, server_url: String, sync_config: Option<EsploraSyncConfig>,
) -> &mut Self {
self.chain_data_source_config = Some(ChainDataSourceConfig::Esplora {
server_url,
headers: Default::default(),
sync_config,
});
self
}
/// Configures the [`Node`] instance to source its chain data from the given Esplora server.
///
/// The given `headers` will be included in all requests to the Esplora server, typically used for
/// authentication purposes.
///
/// If no `sync_config` is given, default values are used. See [`EsploraSyncConfig`] for more
/// information.
pub fn set_chain_source_esplora_with_headers(
&mut self, server_url: String, headers: HashMap<String, String>,
sync_config: Option<EsploraSyncConfig>,
) -> &mut Self {
self.chain_data_source_config =
Some(ChainDataSourceConfig::Esplora { server_url, headers, sync_config });
self
}
/// Configures the [`Node`] instance to source its chain data from the given Electrum server.
///
/// If no `sync_config` is given, default values are used. See [`ElectrumSyncConfig`] for more
/// information.
pub fn set_chain_source_electrum(
&mut self, server_url: String, sync_config: Option<ElectrumSyncConfig>,
) -> &mut Self {
self.chain_data_source_config =
Some(ChainDataSourceConfig::Electrum { server_url, sync_config });
self
}
/// Configures the [`Node`] instance to connect to a Bitcoin Core node via RPC.
///
/// This method establishes an RPC connection that enables all essential chain operations including
/// transaction broadcasting and chain data synchronization.
///
/// ## Parameters:
/// * `rpc_host`, `rpc_port`, `rpc_user`, `rpc_password` - Required parameters for the Bitcoin Core RPC
/// connection.
pub fn set_chain_source_bitcoind_rpc(
&mut self, rpc_host: String, rpc_port: u16, rpc_user: String, rpc_password: String,
) -> &mut Self {
self.chain_data_source_config = Some(ChainDataSourceConfig::Bitcoind {
rpc_host,
rpc_port,
rpc_user,
rpc_password,
rest_client_config: None,
});
self
}
/// Configures the [`Node`] instance to synchronize chain data from a Bitcoin Core REST endpoint.
///
/// This method enables chain data synchronization via Bitcoin Core's REST interface. We pass
/// additional RPC configuration to non-REST-supported API calls like transaction broadcasting.
///
/// ## Parameters:
/// * `rest_host`, `rest_port` - Required parameters for the Bitcoin Core REST connection.
/// * `rpc_host`, `rpc_port`, `rpc_user`, `rpc_password` - Required parameters for the Bitcoin Core RPC
/// connection
pub fn set_chain_source_bitcoind_rest(
&mut self, rest_host: String, rest_port: u16, rpc_host: String, rpc_port: u16,
rpc_user: String, rpc_password: String,
) -> &mut Self {
self.chain_data_source_config = Some(ChainDataSourceConfig::Bitcoind {
rpc_host,
rpc_port,
rpc_user,
rpc_password,
rest_client_config: Some(BitcoindRestClientConfig { rest_host, rest_port }),
});
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 external scores from the given URL.
///
/// The external scores are merged into the local scoring system to improve routing.
pub fn set_pathfinding_scores_source(&mut self, url: String) -> &mut Self {
self.pathfinding_scores_sync_config = Some(PathfindingScoresSyncConfig { url });
self
}
/// Configures the [`Node`] instance to source inbound liquidity from the given
/// [bLIP-51 / LSPS1] service.
///
/// Will mark the LSP as trusted for 0-confirmation channels, see [`Config::trusted_peers_0conf`].
///
/// The given `token` will be used by the LSP to authenticate the user.
///
/// [bLIP-51 / LSPS1]: https://github.com/lightning/blips/blob/master/blip-0051.md
pub fn set_liquidity_source_lsps1(
&mut self, node_id: PublicKey, address: SocketAddress, token: Option<String>,
) -> &mut Self {
// Mark the LSP as trusted for 0conf
self.config.trusted_peers_0conf.push(node_id.clone());
let liquidity_source_config =
self.liquidity_source_config.get_or_insert(LiquiditySourceConfig::default());
let lsps1_client_config = LSPS1ClientConfig { node_id, address, token };
liquidity_source_config.lsps1_client = Some(lsps1_client_config);
self
}
/// Configures the [`Node`] instance to source just-in-time inbound liquidity from the given
/// [bLIP-52 / LSPS2] service.
///
/// Will mark the LSP as trusted for 0-confirmation channels, see [`Config::trusted_peers_0conf`].
///
/// The given `token` will be used by the LSP to authenticate the user.
///
/// [bLIP-52 / LSPS2]: https://github.com/lightning/blips/blob/master/blip-0052.md
pub fn set_liquidity_source_lsps2(
&mut self, node_id: PublicKey, address: SocketAddress, token: Option<String>,
) -> &mut Self {
// Mark the LSP as trusted for 0conf
self.config.trusted_peers_0conf.push(node_id.clone());
let liquidity_source_config =
self.liquidity_source_config.get_or_insert(LiquiditySourceConfig::default());
let lsps2_client_config = LSPS2ClientConfig { node_id, address, token };
liquidity_source_config.lsps2_client = Some(lsps2_client_config);
self
}
/// Configures the [`Node`] instance to provide an [LSPS2] service, issuing just-in-time
/// channels to clients.
///
/// **Caution**: LSP service support is in **alpha** and is considered an experimental feature.
///
/// [LSPS2]: https://github.com/BitcoinAndLightningLayerSpecs/lsp/blob/main/LSPS2/README.md
pub fn set_liquidity_provider_lsps2(
&mut self, service_config: LSPS2ServiceConfig,
) -> &mut Self {
let liquidity_source_config =
self.liquidity_source_config.get_or_insert(LiquiditySourceConfig::default());
liquidity_source_config.lsps2_service = Some(service_config);
self
}
/// Configures the [`Node`] instance to source webhook notifications from the given
/// [bLIP-55 / LSPS5] service.
///
/// This allows the client to register webhook endpoints with the LSP to receive
/// push notifications for Lightning events when the client is offline.
///
/// [bLIP-55 / LSPS5]: https://github.com/lightning/blips/blob/master/blip-0055.md
pub fn set_liquidity_source_lsps5(
&mut self, node_id: PublicKey, address: SocketAddress,
) -> &mut Self {
let liquidity_source_config =
self.liquidity_source_config.get_or_insert(LiquiditySourceConfig::default());
let lsps5_client_config = LSPS5ClientConfig { node_id, address };
liquidity_source_config.lsps5_client = Some(lsps5_client_config);
self
}
/// Configures the [`Node`] instance to provide an [LSPS5] service, enabling clients
/// to register webhooks for push notifications.
///
/// [LSPS5]: https://github.com/lightning/blips/blob/master/blip-0055.md
pub fn set_liquidity_provider_lsps5(
&mut self, service_config: LSPS5ServiceConfig,
) -> &mut Self {
let liquidity_source_config =
self.liquidity_source_config.get_or_insert(LiquiditySourceConfig::default());
liquidity_source_config.lsps5_service = Some(service_config);
self
}
/// Sets a custom HTTP client to be used by the LSPS5 service.
pub fn set_liquidity_http_client(&mut self, http_client: reqwest::Client) -> &mut Self {
let liquidity_source_config =
self.liquidity_source_config.get_or_insert(LiquiditySourceConfig::default());
liquidity_source_config.http_client = Some(http_client);
self
}
/// Sets the used storage directory path.
pub fn set_storage_dir_path(&mut self, storage_dir_path: String) -> &mut Self {
self.config.storage_dir_path = storage_dir_path;
self
}
/// Configures the [`Node`] instance to write logs to the filesystem.
///
/// The `log_file_path` defaults to [`DEFAULT_LOG_FILENAME`] in the configured
/// [`Config::storage_dir_path`] if set to `None`.
///
/// If set, the `max_log_level` sets the maximum log level. Otherwise, the latter defaults to
/// [`DEFAULT_LOG_LEVEL`].
///
/// [`DEFAULT_LOG_FILENAME`]: crate::config::DEFAULT_LOG_FILENAME
pub fn set_filesystem_logger(
&mut self, log_file_path: Option<String>, max_log_level: Option<LogLevel>,
) -> &mut Self {
self.log_writer_config = Some(LogWriterConfig::File { log_file_path, max_log_level });
self
}
/// Configures the [`Node`] instance to write logs to the [`log`](https://crates.io/crates/log) facade.
pub fn set_log_facade_logger(&mut self) -> &mut Self {
self.log_writer_config = Some(LogWriterConfig::Log);
self
}
/// Configures the [`Node`] instance to write logs to the provided custom [`LogWriter`].
pub fn set_custom_logger(&mut self, log_writer: Arc<dyn LogWriter>) -> &mut Self {
self.log_writer_config = Some(LogWriterConfig::Custom(log_writer));
self
}
/// Sets the Bitcoin network used.
pub fn set_network(&mut self, network: Network) -> &mut Self {
self.config.network = network;
self
}
/// Sets the IP address and TCP port on which [`Node`] will listen for incoming network connections.
pub fn set_listening_addresses(
&mut self, listening_addresses: Vec<SocketAddress>,
) -> Result<&mut Self, BuildError> {
if listening_addresses.len() > 100 {
return Err(BuildError::InvalidListeningAddresses);
}
self.config.listening_addresses = Some(listening_addresses);
Ok(self)
}
/// Sets the IP address and TCP port which [`Node`] will announce to the gossip network that it accepts connections on.
///
/// **Note**: If unset, the [`listening_addresses`] will be used as the list of addresses to announce.
///
/// [`listening_addresses`]: Self::set_listening_addresses
pub fn set_announcement_addresses(
&mut self, announcement_addresses: Vec<SocketAddress>,
) -> Result<&mut Self, BuildError> {
if announcement_addresses.len() > 100 {
return Err(BuildError::InvalidAnnouncementAddresses);
}
self.config.announcement_addresses = Some(announcement_addresses);
Ok(self)
}
/// Sets the node alias that will be used when broadcasting announcements to the gossip
/// network.
///
/// The provided alias must be a valid UTF-8 string and no longer than 32 bytes in total.
pub fn set_node_alias(&mut self, node_alias: String) -> Result<&mut Self, BuildError> {
let node_alias = sanitize_alias(&node_alias)?;
self.config.node_alias = Some(node_alias);
Ok(self)
}
/// Sets the role of the node in an asynchronous payments context.
///
/// See <https://github.com/lightning/bolts/pull/1149> for more information about the async payments protocol.
pub fn set_async_payments_role(
&mut self, role: Option<AsyncPaymentsRole>,
) -> Result<&mut Self, BuildError> {
if let Some(AsyncPaymentsRole::Server) = role {
may_announce_channel(&self.config)
.map_err(|_| BuildError::AsyncPaymentsConfigMismatch)?;
}
self.async_payments_role = role;
Ok(self)
}
/// Builds a [`Node`] instance with a [`SqliteStore`] backend and according to the options
/// previously configured.
pub fn build(&self, node_entropy: NodeEntropy) -> Result<Node, BuildError> {
let storage_dir_path = self.config.storage_dir_path.clone();
fs::create_dir_all(storage_dir_path.clone())
.map_err(|_| BuildError::StoragePathAccessFailed)?;
let kv_store = SqliteStore::new(
storage_dir_path.into(),
Some(io::sqlite_store::SQLITE_DB_FILE_NAME.to_string()),
Some(io::sqlite_store::KV_TABLE_NAME.to_string()),
)
.map_err(|_| BuildError::KVStoreSetupFailed)?;
self.build_with_store(node_entropy, kv_store)
}
/// Builds a [`Node`] instance with a [`FilesystemStore`] backend and according to the options
/// previously configured.
pub fn build_with_fs_store(&self, node_entropy: NodeEntropy) -> Result<Node, BuildError> {
let mut storage_dir_path: PathBuf = self.config.storage_dir_path.clone().into();
storage_dir_path.push("fs_store");
fs::create_dir_all(storage_dir_path.clone())
.map_err(|_| BuildError::StoragePathAccessFailed)?;
let kv_store = FilesystemStore::new(storage_dir_path);
self.build_with_store(node_entropy, kv_store)
}
/// Builds a [`Node`] instance with a [VSS] backend and according to the options
/// previously configured.
///
/// Uses [LNURL-auth] based authentication scheme as default method for authentication/authorization.
///
/// The LNURL challenge will be retrieved by making a request to the given `lnurl_auth_server_url`.
/// The returned JWT token in response to the signed LNURL request, will be used for
/// authentication/authorization of all the requests made to VSS.
///
/// `fixed_headers` are included as it is in all the requests made to VSS and LNURL auth server.
///
/// **Caution**: VSS support is in **alpha** and is considered experimental.
/// Using VSS (or any remote persistence) may cause LDK to panic if persistence failures are
/// unrecoverable, i.e., if they remain unresolved after internal retries are exhausted.
///
/// [VSS]: https://github.com/lightningdevkit/vss-server/blob/main/README.md
/// [LNURL-auth]: https://github.com/lnurl/luds/blob/luds/04.md
pub fn build_with_vss_store(
&self, node_entropy: NodeEntropy, vss_url: String, store_id: String,
lnurl_auth_server_url: String, fixed_headers: HashMap<String, String>,
) -> Result<Node, BuildError> {
let logger = setup_logger(&self.log_writer_config, &self.config)?;
let builder = VssStoreBuilder::new(node_entropy, vss_url, store_id, self.config.network);
let vss_store = builder.build(lnurl_auth_server_url, fixed_headers).map_err(|e| {
log_error!(logger, "Failed to setup VSS store: {}", e);
BuildError::KVStoreSetupFailed
})?;
self.build_with_store(node_entropy, vss_store)
}
/// Builds a [`Node`] instance with a [VSS] backend and according to the options
/// previously configured.
///
/// Uses [`FixedHeaders`] as default method for authentication/authorization.
///
/// Given `fixed_headers` are included as it is in all the requests made to VSS.
///
/// **Caution**: VSS support is in **alpha** and is considered experimental.
/// Using VSS (or any remote persistence) may cause LDK to panic if persistence failures are
/// unrecoverable, i.e., if they remain unresolved after internal retries are exhausted.
///
/// [VSS]: https://github.com/lightningdevkit/vss-server/blob/main/README.md
/// [`FixedHeaders`]: vss_client::headers::FixedHeaders
pub fn build_with_vss_store_and_fixed_headers(
&self, node_entropy: NodeEntropy, vss_url: String, store_id: String,
fixed_headers: HashMap<String, String>,
) -> Result<Node, BuildError> {
let logger = setup_logger(&self.log_writer_config, &self.config)?;
let builder = VssStoreBuilder::new(node_entropy, vss_url, store_id, self.config.network);
let vss_store = builder.build_with_fixed_headers(fixed_headers).map_err(|e| {
log_error!(logger, "Failed to setup VSS store: {}", e);
BuildError::KVStoreSetupFailed
})?;
self.build_with_store(node_entropy, vss_store)
}
/// Builds a [`Node`] instance with a [VSS] backend and according to the options
/// previously configured.
///
/// Given `header_provider` is used to attach headers to every request made
/// to VSS.
///
/// **Caution**: VSS support is in **alpha** and is considered experimental.
/// Using VSS (or any remote persistence) may cause LDK to panic if persistence failures are
/// unrecoverable, i.e., if they remain unresolved after internal retries are exhausted.
///
/// [VSS]: https://github.com/lightningdevkit/vss-server/blob/main/README.md
pub fn build_with_vss_store_and_header_provider(
&self, node_entropy: NodeEntropy, vss_url: String, store_id: String,
header_provider: Arc<dyn VssHeaderProvider>,
) -> Result<Node, BuildError> {
let logger = setup_logger(&self.log_writer_config, &self.config)?;
let builder = VssStoreBuilder::new(node_entropy, vss_url, store_id, self.config.network);
let vss_store = builder.build_with_header_provider(header_provider).map_err(|e| {
log_error!(logger, "Failed to setup VSS store: {}", e);
BuildError::KVStoreSetupFailed
})?;
self.build_with_store(node_entropy, vss_store)
}
/// Builds a [`Node`] instance according to the options previously configured.
pub fn build_with_store<S: SyncAndAsyncKVStore + Send + Sync + 'static>(
&self, node_entropy: NodeEntropy, kv_store: S,
) -> Result<Node, BuildError> {
let logger = setup_logger(&self.log_writer_config, &self.config)?;
let runtime = if let Some(handle) = self.runtime_handle.as_ref() {
Arc::new(Runtime::with_handle(handle.clone(), Arc::clone(&logger)))
} else {
Arc::new(Runtime::new(Arc::clone(&logger)).map_err(|e| {
log_error!(logger, "Failed to setup tokio runtime: {}", e);
BuildError::RuntimeSetupFailed
})?)
};
let seed_bytes = node_entropy.to_seed_bytes();
let config = Arc::new(self.config.clone());
build_with_store_internal(
config,
self.chain_data_source_config.as_ref(),
self.gossip_source_config.as_ref(),
self.liquidity_source_config.as_ref(),
self.pathfinding_scores_sync_config.as_ref(),
self.async_payments_role,
seed_bytes,
runtime,
logger,
Arc::new(DynStoreWrapper(kv_store)),
)
}
}
/// A builder for an [`Node`] instance, allowing to set some configuration and module choices from
/// the getgo.
///
/// ### Defaults
/// - Wallet entropy is sourced from a `keys_seed` file located under [`Config::storage_dir_path`]
/// - Chain data is sourced from the Esplora endpoint `https://blockstream.info/api`
/// - Gossip data is sourced via the peer-to-peer network
#[derive(Debug)]
#[cfg(feature = "uniffi")]
pub struct ArcedNodeBuilder {
inner: RwLock<NodeBuilder>,
}
#[cfg(feature = "uniffi")]
impl ArcedNodeBuilder {
/// Creates a new builder instance with the default configuration.
pub fn new() -> Self {
let inner = RwLock::new(NodeBuilder::new());
Self { inner }
}
/// Creates a new builder instance from an [`Config`].
pub fn from_config(config: Config) -> Self {
let inner = RwLock::new(NodeBuilder::from_config(config));
Self { inner }
}
/// Configures the [`Node`] instance to source its chain data from the given Esplora server.
///
/// If no `sync_config` is given, default values are used. See [`EsploraSyncConfig`] for more
/// information.
pub fn set_chain_source_esplora(
&self, server_url: String, sync_config: Option<EsploraSyncConfig>,
) {
self.inner.write().unwrap().set_chain_source_esplora(server_url, sync_config);
}
/// Configures the [`Node`] instance to source its chain data from the given Esplora server.
///
/// The given `headers` will be included in all requests to the Esplora server, typically used for
/// authentication purposes.
///
/// If no `sync_config` is given, default values are used. See [`EsploraSyncConfig`] for more
/// information.
pub fn set_chain_source_esplora_with_headers(
&self, server_url: String, headers: HashMap<String, String>,
sync_config: Option<EsploraSyncConfig>,
) {
self.inner.write().unwrap().set_chain_source_esplora_with_headers(
server_url,
headers,
sync_config,
);
}
/// Configures the [`Node`] instance to source its chain data from the given Electrum server.
///
/// If no `sync_config` is given, default values are used. See [`ElectrumSyncConfig`] for more
/// information.
pub fn set_chain_source_electrum(
&self, server_url: String, sync_config: Option<ElectrumSyncConfig>,
) {
self.inner.write().unwrap().set_chain_source_electrum(server_url, sync_config);
}
/// Configures the [`Node`] instance to connect to a Bitcoin Core node via RPC.
///
/// This method establishes an RPC connection that enables all essential chain operations including
/// transaction broadcasting and chain data synchronization.
///
/// ## Parameters:
/// * `rpc_host`, `rpc_port`, `rpc_user`, `rpc_password` - Required parameters for the Bitcoin Core RPC
/// connection.
pub fn set_chain_source_bitcoind_rpc(
&self, rpc_host: String, rpc_port: u16, rpc_user: String, rpc_password: String,
) {
self.inner.write().unwrap().set_chain_source_bitcoind_rpc(
rpc_host,
rpc_port,
rpc_user,
rpc_password,
);
}
/// Configures the [`Node`] instance to synchronize chain data from a Bitcoin Core REST endpoint.
///
/// This method enables chain data synchronization via Bitcoin Core's REST interface. We pass
/// additional RPC configuration to non-REST-supported API calls like transaction broadcasting.
///
/// ## Parameters:
/// * `rest_host`, `rest_port` - Required parameters for the Bitcoin Core REST connection.
/// * `rpc_host`, `rpc_port`, `rpc_user`, `rpc_password` - Required parameters for the Bitcoin Core RPC
/// connection
pub fn set_chain_source_bitcoind_rest(
&self, rest_host: String, rest_port: u16, rpc_host: String, rpc_port: u16,
rpc_user: String, rpc_password: String,
) {
self.inner.write().unwrap().set_chain_source_bitcoind_rest(
rest_host,
rest_port,
rpc_host,
rpc_port,
rpc_user,
rpc_password,
);
}
/// Configures the [`Node`] instance to source its gossip data from the Lightning peer-to-peer
/// network.
pub fn set_gossip_source_p2p(&self) {
self.inner.write().unwrap().set_gossip_source_p2p();
}
/// Configures the [`Node`] instance to source its gossip data from the given RapidGossipSync
/// server.
pub fn set_gossip_source_rgs(&self, rgs_server_url: String) {
self.inner.write().unwrap().set_gossip_source_rgs(rgs_server_url);
}
/// Configures the [`Node`] instance to source its external scores from the given URL.
///
/// The external scores are merged into the local scoring system to improve routing.
pub fn set_pathfinding_scores_source(&self, url: String) {
self.inner.write().unwrap().set_pathfinding_scores_source(url);
}
/// Configures the [`Node`] instance to source inbound liquidity from the given
/// [bLIP-51 / LSPS1] service.
///
/// Will mark the LSP as trusted for 0-confirmation channels, see [`Config::trusted_peers_0conf`].
///
/// The given `token` will be used by the LSP to authenticate the user.
///
/// [bLIP-51 / LSPS1]: https://github.com/lightning/blips/blob/master/blip-0051.md
pub fn set_liquidity_source_lsps1(
&self, node_id: PublicKey, address: SocketAddress, token: Option<String>,
) {
self.inner.write().unwrap().set_liquidity_source_lsps1(node_id, address, token);
}
/// Configures the [`Node`] instance to source just-in-time inbound liquidity from the given
/// [bLIP-52 / LSPS2] service.
///
/// Will mark the LSP as trusted for 0-confirmation channels, see [`Config::trusted_peers_0conf`].
///
/// The given `token` will be used by the LSP to authenticate the user.
///
/// [bLIP-52 / LSPS2]: https://github.com/lightning/blips/blob/master/blip-0052.md
pub fn set_liquidity_source_lsps2(
&self, node_id: PublicKey, address: SocketAddress, token: Option<String>,
) {
self.inner.write().unwrap().set_liquidity_source_lsps2(node_id, address, token);
}
/// Configures the [`Node`] instance to provide an [LSPS2] service, issuing just-in-time
/// channels to clients.
///
/// **Caution**: LSP service support is in **alpha** and is considered an experimental feature.
///
/// [LSPS2]: https://github.com/BitcoinAndLightningLayerSpecs/lsp/blob/main/LSPS2/README.md
pub fn set_liquidity_provider_lsps2(&self, service_config: LSPS2ServiceConfig) {
self.inner.write().unwrap().set_liquidity_provider_lsps2(service_config);
}
/// Configures the [`Node`] instance to source webhook notifications from the given
/// [bLIP-55 / LSPS5] service.
///
/// This allows the client to register webhook endpoints with the LSP to receive
/// push notifications for Lightning events when the client is offline.
///
/// [bLIP-55 / LSPS5]: https://github.com/lightning/blips/blob/master/blip-0055.md
pub fn set_liquidity_source_lsps5(&self, node_id: PublicKey, address: SocketAddress) {
self.inner.write().unwrap().set_liquidity_source_lsps5(node_id, address);
}
/// Configures the [`Node`] instance to provide an [LSPS5] service, enabling clients
/// to register webhooks for push notifications.
///
/// [LSPS5]: https://github.com/lightning/blips/blob/master/blip-0055.md
pub fn set_liquidity_provider_lsps5(&self, service_config: LSPS5ServiceConfig) {
self.inner.write().unwrap().set_liquidity_provider_lsps5(service_config);
}
/// Sets a custom HTTP client to be used by the LSPS5 service.
pub fn set_liquidity_http_client(&self, http_client: reqwest::Client) {
self.inner.write().unwrap().set_liquidity_http_client(http_client);
}
/// Sets the used storage directory path.
pub fn set_storage_dir_path(&self, storage_dir_path: String) {
self.inner.write().unwrap().set_storage_dir_path(storage_dir_path);
}
/// Configures the [`Node`] instance to write logs to the filesystem.
///
/// The `log_file_path` defaults to [`DEFAULT_LOG_FILENAME`] in the configured
/// [`Config::storage_dir_path`] if set to `None`.
///
/// If set, the `max_log_level` sets the maximum log level. Otherwise, the latter defaults to
/// [`DEFAULT_LOG_LEVEL`].
///
/// [`DEFAULT_LOG_FILENAME`]: crate::config::DEFAULT_LOG_FILENAME
pub fn set_filesystem_logger(
&self, log_file_path: Option<String>, log_level: Option<LogLevel>,
) {
self.inner.write().unwrap().set_filesystem_logger(log_file_path, log_level);
}
/// Configures the [`Node`] instance to write logs to the [`log`](https://crates.io/crates/log) facade.
pub fn set_log_facade_logger(&self) {
self.inner.write().unwrap().set_log_facade_logger();
}
/// Configures the [`Node`] instance to write logs to the provided custom [`LogWriter`].
pub fn set_custom_logger(&self, log_writer: Arc<dyn LogWriter>) {
self.inner.write().unwrap().set_custom_logger(log_writer);
}
/// Sets the Bitcoin network used.
pub fn set_network(&self, network: Network) {
self.inner.write().unwrap().set_network(network);
}
/// Sets the IP address and TCP port on which [`Node`] will listen for incoming network connections.
pub fn set_listening_addresses(
&self, listening_addresses: Vec<SocketAddress>,
) -> Result<(), BuildError> {
self.inner.write().unwrap().set_listening_addresses(listening_addresses).map(|_| ())
}
/// Sets the IP address and TCP port which [`Node`] will announce to the gossip network that it accepts connections on.
///
/// **Note**: If unset, the [`listening_addresses`] will be used as the list of addresses to announce.
///
/// [`listening_addresses`]: Self::set_listening_addresses
pub fn set_announcement_addresses(
&self, announcement_addresses: Vec<SocketAddress>,
) -> Result<(), BuildError> {
self.inner.write().unwrap().set_announcement_addresses(announcement_addresses).map(|_| ())
}
/// Sets the node alias that will be used when broadcasting announcements to the gossip
/// network.
///
/// The provided alias must be a valid UTF-8 string and no longer than 32 bytes in total.
pub fn set_node_alias(&self, node_alias: String) -> Result<(), BuildError> {
self.inner.write().unwrap().set_node_alias(node_alias).map(|_| ())
}
/// Sets the role of the node in an asynchronous payments context.
pub fn set_async_payments_role(
&self, role: Option<AsyncPaymentsRole>,
) -> Result<(), BuildError> {
self.inner.write().unwrap().set_async_payments_role(role).map(|_| ())
}
/// Builds a [`Node`] instance with a [`SqliteStore`] backend and according to the options
/// previously configured.
pub fn build(&self, node_entropy: Arc<NodeEntropy>) -> Result<Arc<Node>, BuildError> {
self.inner.read().unwrap().build(*node_entropy).map(Arc::new)
}
/// Builds a [`Node`] instance with a [`FilesystemStore`] backend and according to the options
/// previously configured.
pub fn build_with_fs_store(
&self, node_entropy: Arc<NodeEntropy>,
) -> Result<Arc<Node>, BuildError> {
self.inner.read().unwrap().build_with_fs_store(*node_entropy).map(Arc::new)
}
/// Builds a [`Node`] instance with a [VSS] backend and according to the options