-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathbuilder.rs
1607 lines (1444 loc) · 55 KB
/
builder.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
// 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 crate::chain::{ChainSource, DEFAULT_ESPLORA_SERVER_URL};
use crate::config::{
default_user_config, may_announce_channel, AnnounceError, Config, EsploraSyncConfig,
DEFAULT_LOG_FILENAME, DEFAULT_LOG_LEVEL, WALLET_KEYS_SEED_LEN,
};
use crate::connection::ConnectionManager;
use crate::event::EventQueue;
use crate::fee_estimator::OnchainFeeEstimator;
use crate::gossip::GossipSource;
use crate::io::sqlite_store::SqliteStore;
use crate::io::utils::{read_node_metrics, write_node_metrics};
use crate::io::vss_store::VssStore;
use crate::liquidity::{
LSPS1ClientConfig, LSPS2ClientConfig, LSPS2ServiceConfig, LiquiditySourceBuilder,
};
use crate::logger::{log_error, log_info, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::store::PaymentStore;
use crate::peer_store::PeerStore;
use crate::tx_broadcaster::TransactionBroadcaster;
use crate::types::{
ChainMonitor, ChannelManager, DynStore, GossipSync, Graph, KeysManager, MessageRouter,
OnionMessenger, PeerManager,
};
use crate::wallet::persist::KVStoreWalletPersister;
use crate::wallet::Wallet;
use crate::{io, Node, NodeMetrics};
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::routing::gossip::NodeAlias;
use lightning::routing::router::DefaultRouter;
use lightning::routing::scoring::{
ProbabilisticScorer, ProbabilisticScoringDecayParameters, ProbabilisticScoringFeeParameters,
};
use lightning::sign::EntropySource;
use lightning::util::persist::{
read_channel_monitors, 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 bdk_wallet::template::Bip84;
use bdk_wallet::KeychainKind;
use bdk_wallet::Wallet as BdkWallet;
use bip39::Mnemonic;
use bitcoin::secp256k1::PublicKey;
use bitcoin::{BlockHash, Network};
use bitcoin::bip32::{ChildNumber, Xpriv};
use std::collections::HashMap;
use std::convert::TryInto;
use std::default::Default;
use std::fmt;
use std::fs;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex, RwLock};
use std::time::SystemTime;
use vss_client::headers::{FixedHeaders, LnurlAuthToJwtProvider, VssHeaderProvider};
const VSS_HARDENED_CHILD_INDEX: u32 = 877;
const VSS_LNURL_AUTH_HARDENED_CHILD_INDEX: u32 = 138;
const LSPS_HARDENED_CHILD_INDEX: u32 = 577;
#[derive(Debug, Clone)]
enum ChainDataSourceConfig {
Esplora { server_url: String, sync_config: Option<EsploraSyncConfig> },
BitcoindRpc { rpc_host: String, rpc_port: u16, rpc_user: String, rpc_password: String },
}
#[derive(Debug, Clone)]
enum EntropySourceConfig {
SeedFile(String),
SeedBytes([u8; WALLET_KEYS_SEED_LEN]),
Bip39Mnemonic { mnemonic: Mnemonic, passphrase: Option<String> },
}
#[derive(Debug, Clone)]
enum GossipSourceConfig {
P2PNetwork,
RapidGossipSync(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>,
}
#[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 given seed bytes are invalid, e.g., have invalid length.
InvalidSeedBytes,
/// The given seed file is invalid, e.g., has invalid length, or could not be read.
InvalidSeedFile,
/// 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,
/// We failed to read data from the [`KVStore`].
///
/// [`KVStore`]: lightning::util::persist::KVStore
ReadFailed,
/// We failed to write data to the [`KVStore`].
///
/// [`KVStore`]: lightning::util::persist::KVStore
WriteFailed,
/// We failed to access the given `storage_dir_path`.
StoragePathAccessFailed,
/// We failed to setup our [`KVStore`].
///
/// [`KVStore`]: lightning::util::persist::KVStore
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,
}
impl fmt::Display for BuildError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Self::InvalidSeedBytes => write!(f, "Given seed bytes are invalid."),
Self::InvalidSeedFile => write!(f, "Given seed file is invalid or could not be read."),
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::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.")
},
}
}
}
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,
entropy_source_config: Option<EntropySourceConfig>,
chain_data_source_config: Option<ChainDataSourceConfig>,
gossip_source_config: Option<GossipSourceConfig>,
liquidity_source_config: Option<LiquiditySourceConfig>,
log_writer_config: Option<LogWriterConfig>,
}
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 entropy_source_config = None;
let chain_data_source_config = None;
let gossip_source_config = None;
let liquidity_source_config = None;
let log_writer_config = None;
Self {
config,
entropy_source_config,
chain_data_source_config,
gossip_source_config,
liquidity_source_config,
log_writer_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
/// [`WALLET_KEYS_SEED_LEN`] 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 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: Mnemonic, passphrase: Option<String>,
) -> &mut Self {
self.entropy_source_config =
Some(EntropySourceConfig::Bip39Mnemonic { mnemonic, passphrase });
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, sync_config });
self
}
/// Configures the [`Node`] instance to source its chain data from the given Bitcoin Core RPC
/// endpoint.
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::BitcoindRpc { rpc_host, rpc_port, rpc_user, rpc_password });
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 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
}
/// 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)
}
/// Builds a [`Node`] instance with a [`SqliteStore`] backend and according to the options
/// previously configured.
pub fn build(&self) -> 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 = Arc::new(
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(kv_store)
}
/// Builds a [`Node`] instance with a [`FilesystemStore`] backend and according to the options
/// previously configured.
pub fn build_with_fs_store(&self) -> 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 = Arc::new(FilesystemStore::new(storage_dir_path));
self.build_with_store(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, vss_url: String, store_id: String, lnurl_auth_server_url: String,
fixed_headers: HashMap<String, String>,
) -> Result<Node, BuildError> {
use bitcoin::key::Secp256k1;
let logger = setup_logger(&self.log_writer_config, &self.config)?;
let seed_bytes = seed_bytes_from_config(
&self.config,
self.entropy_source_config.as_ref(),
Arc::clone(&logger),
)?;
let config = Arc::new(self.config.clone());
let vss_xprv =
derive_xprv(config, &seed_bytes, VSS_HARDENED_CHILD_INDEX, Arc::clone(&logger))?;
let lnurl_auth_xprv = vss_xprv
.derive_priv(
&Secp256k1::new(),
&[ChildNumber::Hardened { index: VSS_LNURL_AUTH_HARDENED_CHILD_INDEX }],
)
.map_err(|e| {
log_error!(logger, "Failed to derive VSS secret: {}", e);
BuildError::KVStoreSetupFailed
})?;
let lnurl_auth_jwt_provider =
LnurlAuthToJwtProvider::new(lnurl_auth_xprv, lnurl_auth_server_url, fixed_headers)
.map_err(|e| {
log_error!(logger, "Failed to create LnurlAuthToJwtProvider: {}", e);
BuildError::KVStoreSetupFailed
})?;
let header_provider = Arc::new(lnurl_auth_jwt_provider);
self.build_with_vss_store_and_header_provider(vss_url, store_id, header_provider)
}
/// 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
pub fn build_with_vss_store_and_fixed_headers(
&self, vss_url: String, store_id: String, fixed_headers: HashMap<String, String>,
) -> Result<Node, BuildError> {
let header_provider = Arc::new(FixedHeaders::new(fixed_headers));
self.build_with_vss_store_and_header_provider(vss_url, store_id, header_provider)
}
/// 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, 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 seed_bytes = seed_bytes_from_config(
&self.config,
self.entropy_source_config.as_ref(),
Arc::clone(&logger),
)?;
let config = Arc::new(self.config.clone());
let vss_xprv = derive_xprv(
config.clone(),
&seed_bytes,
VSS_HARDENED_CHILD_INDEX,
Arc::clone(&logger),
)?;
let vss_seed_bytes: [u8; 32] = vss_xprv.private_key.secret_bytes();
let vss_store =
VssStore::new(vss_url, store_id, vss_seed_bytes, header_provider).map_err(|e| {
log_error!(logger, "Failed to setup VssStore: {}", e);
BuildError::KVStoreSetupFailed
})?;
build_with_store_internal(
config,
self.chain_data_source_config.as_ref(),
self.gossip_source_config.as_ref(),
self.liquidity_source_config.as_ref(),
seed_bytes,
logger,
Arc::new(vss_store),
)
}
/// Builds a [`Node`] instance according to the options previously configured.
pub fn build_with_store(&self, kv_store: Arc<DynStore>) -> Result<Node, BuildError> {
let logger = setup_logger(&self.log_writer_config, &self.config)?;
let seed_bytes = seed_bytes_from_config(
&self.config,
self.entropy_source_config.as_ref(),
Arc::clone(&logger),
)?;
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(),
seed_bytes,
logger,
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 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(&self, seed_path: String) {
self.inner.write().unwrap().set_entropy_seed_path(seed_path);
}
/// Configures the [`Node`] instance to source its wallet entropy from the given
/// [`WALLET_KEYS_SEED_LEN`] seed bytes.
///
/// **Note:** Will return an error if the length of the given `seed_bytes` differs from
/// [`WALLET_KEYS_SEED_LEN`].
pub fn set_entropy_seed_bytes(&self, seed_bytes: Vec<u8>) -> Result<(), BuildError> {
if seed_bytes.len() != WALLET_KEYS_SEED_LEN {
return Err(BuildError::InvalidSeedBytes);
}
let mut bytes = [0u8; WALLET_KEYS_SEED_LEN];
bytes.copy_from_slice(&seed_bytes);
self.inner.write().unwrap().set_entropy_seed_bytes(bytes);
Ok(())
}
/// 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(&self, mnemonic: Mnemonic, passphrase: Option<String>) {
self.inner.write().unwrap().set_entropy_bip39_mnemonic(mnemonic, passphrase);
}
/// 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 Bitcoin Core RPC
/// endpoint.
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 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 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);
}
/// 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(|_| ())
}
/// Builds a [`Node`] instance with a [`SqliteStore`] backend and according to the options
/// previously configured.
pub fn build(&self) -> Result<Arc<Node>, BuildError> {
self.inner.read().unwrap().build().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) -> Result<Arc<Node>, BuildError> {
self.inner.read().unwrap().build_with_fs_store().map(Arc::new)
}
/// 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, vss_url: String, store_id: String, lnurl_auth_server_url: String,
fixed_headers: HashMap<String, String>,
) -> Result<Arc<Node>, BuildError> {
self.inner
.read()
.unwrap()
.build_with_vss_store(vss_url, store_id, lnurl_auth_server_url, fixed_headers)
.map(Arc::new)
}
/// 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
pub fn build_with_vss_store_and_fixed_headers(
&self, vss_url: String, store_id: String, fixed_headers: HashMap<String, String>,
) -> Result<Arc<Node>, BuildError> {
self.inner
.read()
.unwrap()
.build_with_vss_store_and_fixed_headers(vss_url, store_id, fixed_headers)
.map(Arc::new)
}
/// 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, vss_url: String, store_id: String, header_provider: Arc<dyn VssHeaderProvider>,
) -> Result<Arc<Node>, BuildError> {
self.inner
.read()
.unwrap()
.build_with_vss_store_and_header_provider(vss_url, store_id, header_provider)
.map(Arc::new)
}
/// Builds a [`Node`] instance according to the options previously configured.
pub fn build_with_store(&self, kv_store: Arc<DynStore>) -> Result<Arc<Node>, BuildError> {
self.inner.read().unwrap().build_with_store(kv_store).map(Arc::new)
}
}
/// Builds a [`Node`] instance according to the options previously configured.
fn build_with_store_internal(
config: Arc<Config>, chain_data_source_config: Option<&ChainDataSourceConfig>,
gossip_source_config: Option<&GossipSourceConfig>,
liquidity_source_config: Option<&LiquiditySourceConfig>, seed_bytes: [u8; 64],
logger: Arc<Logger>, kv_store: Arc<DynStore>,
) -> Result<Node, BuildError> {
if let Err(err) = may_announce_channel(&config) {
if config.announcement_addresses.is_some() {
log_error!(logger, "Announcement addresses were set but some required configuration options for node announcement are missing: {}", err);
let build_error = if matches!(err, AnnounceError::MissingNodeAlias) {
BuildError::InvalidNodeAlias
} else {
BuildError::InvalidListeningAddresses
};
return Err(build_error);
}
if config.node_alias.is_some() {
log_error!(logger, "Node alias was set but some required configuration options for node announcement are missing: {}", err);
return Err(BuildError::InvalidListeningAddresses);
}
}
// Initialize the status fields.
let is_listening = Arc::new(AtomicBool::new(false));
let node_metrics = match read_node_metrics(Arc::clone(&kv_store), Arc::clone(&logger)) {
Ok(metrics) => Arc::new(RwLock::new(metrics)),
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
Arc::new(RwLock::new(NodeMetrics::default()))
} else {
return Err(BuildError::ReadFailed);
}
},
};
// Initialize the on-chain wallet and chain access
let xprv = bitcoin::bip32::Xpriv::new_master(config.network, &seed_bytes).map_err(|e| {
log_error!(logger, "Failed to derive master secret: {}", e);
BuildError::InvalidSeedBytes
})?;
let descriptor = Bip84(xprv, KeychainKind::External);
let change_descriptor = Bip84(xprv, KeychainKind::Internal);
let mut wallet_persister =
KVStoreWalletPersister::new(Arc::clone(&kv_store), Arc::clone(&logger));
let wallet_opt = BdkWallet::load()
.descriptor(KeychainKind::External, Some(descriptor.clone()))
.descriptor(KeychainKind::Internal, Some(change_descriptor.clone()))
.extract_keys()
.check_network(config.network)
.load_wallet(&mut wallet_persister)
.map_err(|e| match e {
bdk_wallet::LoadWithPersistError::InvalidChangeSet(
bdk_wallet::LoadError::Mismatch(bdk_wallet::LoadMismatch::Network {
loaded,
expected,
}),
) => {
log_error!(
logger,
"Failed to setup wallet: Networks do not match. Expected {} but got {}",
expected,
loaded
);
BuildError::NetworkMismatch
},
_ => {
log_error!(logger, "Failed to set up wallet: {}", e);
BuildError::WalletSetupFailed
},
})?;
let bdk_wallet = match wallet_opt {
Some(wallet) => wallet,
None => BdkWallet::create(descriptor, change_descriptor)
.network(config.network)
.create_wallet(&mut wallet_persister)
.map_err(|e| {
log_error!(logger, "Failed to set up wallet: {}", e);
BuildError::WalletSetupFailed
})?,
};
let tx_broadcaster = Arc::new(TransactionBroadcaster::new(Arc::clone(&logger)));
let fee_estimator = Arc::new(OnchainFeeEstimator::new());
let payment_store = match io::utils::read_payments(Arc::clone(&kv_store), Arc::clone(&logger)) {
Ok(payments) => {
Arc::new(PaymentStore::new(payments, Arc::clone(&kv_store), Arc::clone(&logger)))
},
Err(_) => {
return Err(BuildError::ReadFailed);
},