ldk-node 0.6.1

A ready-to-go node implementation built using LDK.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
// 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, ElectrumSyncConfig,
	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::io::{
	self, PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE, PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE,
};
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::peer_store::PeerStore;
use crate::tx_broadcaster::TransactionBroadcaster;
use crate::types::{
	ChainMonitor, ChannelManager, DynStore, GossipSync, Graph, KeysManager, MessageRouter,
	OnionMessenger, PaymentStore, PeerManager,
};
use crate::wallet::persist::KVStoreWalletPersister;
use crate::wallet::Wallet;
use crate::{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> },
	Electrum { server_url: String, sync_config: Option<ElectrumSyncConfig> },
	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 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 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 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 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,
			PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE.to_string(),
			PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE.to_string(),
			Arc::clone(&kv_store),
			Arc::clone(&logger),
		)),
		Err(_) => {
			return Err(BuildError::ReadFailed);
		},
	};

	let wallet = Arc::new(Wallet::new(
		bdk_wallet,
		wallet_persister,
		Arc::clone(&tx_broadcaster),
		Arc::clone(&fee_estimator),
		Arc::clone(&payment_store),
		Arc::clone(&config),
		Arc::clone(&logger),
	));

	let chain_source = match chain_data_source_config {
		Some(ChainDataSourceConfig::Esplora { server_url, sync_config }) => {
			let sync_config = sync_config.unwrap_or(EsploraSyncConfig::default());
			Arc::new(ChainSource::new_esplora(
				server_url.clone(),
				sync_config,
				Arc::clone(&wallet),
				Arc::clone(&fee_estimator),
				Arc::clone(&tx_broadcaster),
				Arc::clone(&kv_store),
				Arc::clone(&config),
				Arc::clone(&logger),
				Arc::clone(&node_metrics),
			))
		},
		Some(ChainDataSourceConfig::Electrum { server_url, sync_config }) => {
			let sync_config = sync_config.unwrap_or(ElectrumSyncConfig::default());
			Arc::new(ChainSource::new_electrum(
				server_url.clone(),
				sync_config,
				Arc::clone(&wallet),
				Arc::clone(&fee_estimator),
				Arc::clone(&tx_broadcaster),
				Arc::clone(&kv_store),
				Arc::clone(&config),
				Arc::clone(&logger),
				Arc::clone(&node_metrics),
			))
		},
		Some(ChainDataSourceConfig::BitcoindRpc { rpc_host, rpc_port, rpc_user, rpc_password }) => {
			Arc::new(ChainSource::new_bitcoind_rpc(
				rpc_host.clone(),
				*rpc_port,
				rpc_user.clone(),
				rpc_password.clone(),
				Arc::clone(&wallet),
				Arc::clone(&fee_estimator),
				Arc::clone(&tx_broadcaster),
				Arc::clone(&kv_store),
				Arc::clone(&config),
				Arc::clone(&logger),
				Arc::clone(&node_metrics),
			))
		},
		None => {
			// Default to Esplora client.
			let server_url = DEFAULT_ESPLORA_SERVER_URL.to_string();
			let sync_config = EsploraSyncConfig::default();
			Arc::new(ChainSource::new_esplora(
				server_url.clone(),
				sync_config,
				Arc::clone(&wallet),
				Arc::clone(&fee_estimator),
				Arc::clone(&tx_broadcaster),
				Arc::clone(&kv_store),
				Arc::clone(&config),
				Arc::clone(&logger),
				Arc::clone(&node_metrics),
			))
		},
	};

	let runtime = Arc::new(RwLock::new(None));

	// Initialize the ChainMonitor
	let chain_monitor: Arc<ChainMonitor> = Arc::new(chainmonitor::ChainMonitor::new(
		Some(Arc::clone(&chain_source)),
		Arc::clone(&tx_broadcaster),
		Arc::clone(&logger),
		Arc::clone(&fee_estimator),
		Arc::clone(&kv_store),
	));

	// Initialize the KeysManager
	let cur_time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map_err(|e| {
		log_error!(logger, "Failed to get current time: {}", e);
		BuildError::InvalidSystemTime
	})?;

	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),
		Arc::clone(&logger),
	));

	// 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(Graph::new(config.network.into(), Arc::clone(&logger)))
				} else {
					return Err(BuildError::ReadFailed);
				}
			},
		};

	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 = ProbabilisticScoringDecayParameters::default();
				Arc::new(Mutex::new(ProbabilisticScorer::new(
					params,
					Arc::clone(&network_graph),
					Arc::clone(&logger),
				)))
			} else {
				return Err(BuildError::ReadFailed);
			}
		},
	};

	let scoring_fee_params = ProbabilisticScoringFeeParameters::default();
	let router = Arc::new(DefaultRouter::new(
		Arc::clone(&network_graph),
		Arc::clone(&logger),
		Arc::clone(&keys_manager),
		Arc::clone(&scorer),
		scoring_fee_params,
	));

	// Read ChannelMonitor state from store
	let channel_monitors = match read_channel_monitors(
		Arc::clone(&kv_store),
		Arc::clone(&keys_manager),
		Arc::clone(&keys_manager),
	) {
		Ok(monitors) => monitors,
		Err(e) => {
			if e.kind() == lightning::io::ErrorKind::NotFound {
				Vec::new()
			} else {
				log_error!(logger, "Failed to read channel monitors: {}", e.to_string());
				return Err(BuildError::ReadFailed);
			}
		},
	};

	let mut user_config = default_user_config(&config);
	if liquidity_source_config.and_then(|lsc| lsc.lsps2_client.as_ref()).is_some() {
		// Generally allow claiming underpaying HTLCs as the LSP will skim off some fee. We'll
		// check that they don't take too much before claiming.
		user_config.channel_config.accept_underpaying_htlcs = true;

		// FIXME: When we're an LSPS2 client, set maximum allowed inbound HTLC value in flight
		// to 100%. We should eventually be able to set this on a per-channel basis, but for
		// now we just bump the default for all channels.
		user_config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel =
			100;
	}

	if liquidity_source_config.and_then(|lsc| lsc.lsps2_service.as_ref()).is_some() {
		// If we act as an LSPS2 service, we need to to be able to intercept HTLCs and forward the
		// information to the service handler.
		user_config.accept_intercept_htlcs = true;

		// If we act as an LSPS2 service, we allow forwarding to unnannounced channels.
		user_config.accept_forwards_to_priv_channels = true;

		// If we act as an LSPS2 service, set the HTLC-value-in-flight to 100% of the channel value
		// to ensure we can forward the initial payment.
		user_config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel =
			100;
	}

	let message_router =
		Arc::new(MessageRouter::new(Arc::clone(&network_graph), Arc::clone(&keys_manager)));

	// Initialize the ChannelManager
	let channel_manager = {
		if let Ok(res) = kv_store.read(
			CHANNEL_MANAGER_PERSISTENCE_PRIMARY_NAMESPACE,
			CHANNEL_MANAGER_PERSISTENCE_SECONDARY_NAMESPACE,
			CHANNEL_MANAGER_PERSISTENCE_KEY,
		) {
			let mut reader = Cursor::new(res);
			let channel_monitor_references =
				channel_monitors.iter().map(|(_, chanmon)| chanmon).collect();
			let read_args = ChannelManagerReadArgs::new(
				Arc::clone(&keys_manager),
				Arc::clone(&keys_manager),
				Arc::clone(&keys_manager),
				Arc::clone(&fee_estimator),
				Arc::clone(&chain_monitor),
				Arc::clone(&tx_broadcaster),
				Arc::clone(&router),
				Arc::clone(&message_router),
				Arc::clone(&logger),
				user_config,
				channel_monitor_references,
			);
			let (_hash, channel_manager) =
				<(BlockHash, ChannelManager)>::read(&mut reader, read_args).map_err(|e| {
					log_error!(logger, "Failed to read channel manager from KVStore: {}", e);
					BuildError::ReadFailed
				})?;
			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.into(),
				best_block: BestBlock::new(genesis_block_hash, 0),
			};
			channelmanager::ChannelManager::new(
				Arc::clone(&fee_estimator),
				Arc::clone(&chain_monitor),
				Arc::clone(&tx_broadcaster),
				Arc::clone(&router),
				Arc::clone(&message_router),
				Arc::clone(&logger),
				Arc::clone(&keys_manager),
				Arc::clone(&keys_manager),
				Arc::clone(&keys_manager),
				user_config,
				chain_params,
				cur_time.as_secs() as u32,
			)
		}
	};

	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).map_err(|e| {
			log_error!(logger, "Failed to watch channel monitor: {:?}", e);
			BuildError::InvalidChannelMonitor
		})?;
	}

	// Initialize the PeerManager
	let onion_messenger: Arc<OnionMessenger> = Arc::new(OnionMessenger::new(
		Arc::clone(&keys_manager),
		Arc::clone(&keys_manager),
		Arc::clone(&logger),
		Arc::clone(&channel_manager),
		message_router,
		Arc::clone(&channel_manager),
		IgnoringMessageHandler {},
		IgnoringMessageHandler {},
		IgnoringMessageHandler {},
	));
	let ephemeral_bytes: [u8; 32] = keys_manager.get_secure_random_bytes();

	// Initialize the GossipSource
	// Use the configured gossip source, if the user set one, otherwise default to P2PNetwork.
	let gossip_source_config = gossip_source_config.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
			{
				let mut locked_node_metrics = node_metrics.write().unwrap();
				locked_node_metrics.latest_rgs_snapshot_timestamp = None;
				write_node_metrics(
					&*locked_node_metrics,
					Arc::clone(&kv_store),
					Arc::clone(&logger),
				)
				.map_err(|e| {
					log_error!(logger, "Failed writing to store: {}", e);
					BuildError::WriteFailed
				})?;
			}
			p2p_source
		},
		GossipSourceConfig::RapidGossipSync(rgs_server) => {
			let latest_sync_timestamp =
				node_metrics.read().unwrap().latest_rgs_snapshot_timestamp.unwrap_or(0);
			Arc::new(GossipSource::new_rgs(
				rgs_server.clone(),
				latest_sync_timestamp,
				Arc::clone(&network_graph),
				Arc::clone(&logger),
			))
		},
	};

	let (liquidity_source, custom_message_handler) =
		if let Some(lsc) = liquidity_source_config.as_ref() {
			let mut liquidity_source_builder = LiquiditySourceBuilder::new(
				Arc::clone(&wallet),
				Arc::clone(&channel_manager),
				Arc::clone(&keys_manager),
				Arc::clone(&chain_source),
				Arc::clone(&config),
				Arc::clone(&logger),
			);

			lsc.lsps1_client.as_ref().map(|config| {
				liquidity_source_builder.lsps1_client(
					config.node_id,
					config.address.clone(),
					config.token.clone(),
				)
			});

			lsc.lsps2_client.as_ref().map(|config| {
				liquidity_source_builder.lsps2_client(
					config.node_id,
					config.address.clone(),
					config.token.clone(),
				)
			});

			let promise_secret = {
				let lsps_xpriv = derive_xprv(
					Arc::clone(&config),
					&seed_bytes,
					LSPS_HARDENED_CHILD_INDEX,
					Arc::clone(&logger),
				)?;
				lsps_xpriv.private_key.secret_bytes()
			};
			lsc.lsps2_service.as_ref().map(|config| {
				liquidity_source_builder.lsps2_service(promise_secret, config.clone())
			});

			let liquidity_source = Arc::new(liquidity_source_builder.build());
			let custom_message_handler =
				Arc::new(NodeCustomMessageHandler::new_liquidity(Arc::clone(&liquidity_source)));
			(Some(liquidity_source), custom_message_handler)
		} else {
			(None, Arc::new(NodeCustomMessageHandler::new_ignoring()))
		};

	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: Arc::clone(&onion_messenger),
			custom_message_handler,
		},
		GossipSync::Rapid(_) => MessageHandler {
			chan_handler: Arc::clone(&channel_manager),
			route_handler: Arc::new(IgnoringMessageHandler {})
				as Arc<dyn RoutingMessageHandler + Sync + Send>,
			onion_message_handler: Arc::clone(&onion_messenger),
			custom_message_handler,
		},
		GossipSync::None => {
			unreachable!("We must always have a gossip sync!");
		},
	};

	let cur_time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map_err(|e| {
		log_error!(logger, "Failed to get current time: {}", e);
		BuildError::InvalidSystemTime
	})?;

	let peer_manager = Arc::new(PeerManager::new(
		msg_handler,
		cur_time.as_secs().try_into().map_err(|e| {
			log_error!(logger, "Failed to get current time: {}", e);
			BuildError::InvalidSystemTime
		})?,
		&ephemeral_bytes,
		Arc::clone(&logger),
		Arc::clone(&keys_manager),
	));

	liquidity_source.as_ref().map(|l| l.set_peer_manager(Arc::clone(&peer_manager)));

	gossip_source.set_gossip_verifier(
		Arc::clone(&chain_source),
		Arc::clone(&peer_manager),
		Arc::clone(&runtime),
	);

	let connection_manager =
		Arc::new(ConnectionManager::new(Arc::clone(&peer_manager), Arc::clone(&logger)));

	let output_sweeper = match io::utils::read_output_sweeper(
		Arc::clone(&tx_broadcaster),
		Arc::clone(&fee_estimator),
		Arc::clone(&chain_source),
		Arc::clone(&keys_manager),
		Arc::clone(&kv_store),
		Arc::clone(&logger),
	) {
		Ok(output_sweeper) => Arc::new(output_sweeper),
		Err(e) => {
			if e.kind() == std::io::ErrorKind::NotFound {
				Arc::new(OutputSweeper::new(
					channel_manager.current_best_block(),
					Arc::clone(&tx_broadcaster),
					Arc::clone(&fee_estimator),
					Some(Arc::clone(&chain_source)),
					Arc::clone(&keys_manager),
					Arc::clone(&keys_manager),
					Arc::clone(&kv_store),
					Arc::clone(&logger),
				))
			} else {
				return Err(BuildError::ReadFailed);
			}
		},
	};

	match io::utils::migrate_deprecated_spendable_outputs(
		Arc::clone(&output_sweeper),
		Arc::clone(&kv_store),
		Arc::clone(&logger),
	) {
		Ok(()) => {
			log_info!(logger, "Successfully migrated OutputSweeper data.");
		},
		Err(e) => {
			log_error!(logger, "Failed to migrate OutputSweeper data: {}", e);
			return Err(BuildError::ReadFailed);
		},
	}

	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 {
				return Err(BuildError::ReadFailed);
			}
		},
	};

	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 {
				return Err(BuildError::ReadFailed);
			}
		},
	};

	let (stop_sender, _) = tokio::sync::watch::channel(());
	let (event_handling_stopped_sender, _) = tokio::sync::watch::channel(());

	Ok(Node {
		runtime,
		stop_sender,
		event_handling_stopped_sender,
		config,
		wallet,
		chain_source,
		tx_broadcaster,
		event_queue,
		channel_manager,
		chain_monitor,
		output_sweeper,
		peer_manager,
		onion_messenger,
		connection_manager,
		keys_manager,
		network_graph,
		gossip_source,
		liquidity_source,
		kv_store,
		logger,
		_router: router,
		scorer,
		peer_store,
		payment_store,
		is_listening,
		node_metrics,
	})
}

/// Sets up the node logger.
fn setup_logger(
	log_writer_config: &Option<LogWriterConfig>, config: &Config,
) -> Result<Arc<Logger>, BuildError> {
	let logger = match log_writer_config {
		Some(LogWriterConfig::File { log_file_path, max_log_level }) => {
			let log_file_path = log_file_path
				.clone()
				.unwrap_or_else(|| format!("{}/{}", config.storage_dir_path, DEFAULT_LOG_FILENAME));
			let max_log_level = max_log_level.unwrap_or_else(|| DEFAULT_LOG_LEVEL);

			Logger::new_fs_writer(log_file_path, max_log_level)
				.map_err(|_| BuildError::LoggerSetupFailed)?
		},
		Some(LogWriterConfig::Log) => Logger::new_log_facade(),

		Some(LogWriterConfig::Custom(custom_log_writer)) => {
			Logger::new_custom_writer(Arc::clone(&custom_log_writer))
		},
		None => {
			// Default to use `FileWriter`
			let log_file_path = format!("{}/{}", config.storage_dir_path, DEFAULT_LOG_FILENAME);
			let log_level = DEFAULT_LOG_LEVEL;
			Logger::new_fs_writer(log_file_path, log_level)
				.map_err(|_| BuildError::LoggerSetupFailed)?
		},
	};

	Ok(Arc::new(logger))
}

fn seed_bytes_from_config(
	config: &Config, entropy_source_config: Option<&EntropySourceConfig>, logger: Arc<Logger>,
) -> Result<[u8; 64], BuildError> {
	match entropy_source_config {
		Some(EntropySourceConfig::SeedBytes(bytes)) => Ok(bytes.clone()),
		Some(EntropySourceConfig::SeedFile(seed_path)) => {
			Ok(io::utils::read_or_generate_seed_file(seed_path, Arc::clone(&logger))
				.map_err(|_| BuildError::InvalidSeedFile)?)
		},
		Some(EntropySourceConfig::Bip39Mnemonic { mnemonic, passphrase }) => match passphrase {
			Some(passphrase) => Ok(mnemonic.to_seed(passphrase)),
			None => Ok(mnemonic.to_seed("")),
		},
		None => {
			// Default to read or generate from the default location generate a seed file.
			let seed_path = format!("{}/keys_seed", config.storage_dir_path);
			Ok(io::utils::read_or_generate_seed_file(&seed_path, Arc::clone(&logger))
				.map_err(|_| BuildError::InvalidSeedFile)?)
		},
	}
}

fn derive_xprv(
	config: Arc<Config>, seed_bytes: &[u8; 64], hardened_child_index: u32, logger: Arc<Logger>,
) -> Result<Xpriv, BuildError> {
	use bitcoin::key::Secp256k1;

	let xprv = Xpriv::new_master(config.network, seed_bytes).map_err(|e| {
		log_error!(logger, "Failed to derive master secret: {}", e);
		BuildError::InvalidSeedBytes
	})?;

	xprv.derive_priv(&Secp256k1::new(), &[ChildNumber::Hardened { index: hardened_child_index }])
		.map_err(|e| {
			log_error!(logger, "Failed to derive hardened child secret: {}", e);
			BuildError::InvalidSeedBytes
		})
}

/// Sanitize the user-provided node alias to ensure that it is a valid protocol-specified UTF-8 string.
pub(crate) fn sanitize_alias(alias_str: &str) -> Result<NodeAlias, BuildError> {
	let alias = alias_str.trim();

	// Alias must be 32-bytes long or less.
	if alias.as_bytes().len() > 32 {
		return Err(BuildError::InvalidNodeAlias);
	}

	let mut bytes = [0u8; 32];
	bytes[..alias.as_bytes().len()].copy_from_slice(alias.as_bytes());
	Ok(NodeAlias(bytes))
}

#[cfg(test)]
mod tests {
	use super::{sanitize_alias, BuildError, NodeAlias};

	#[test]
	fn sanitize_empty_node_alias() {
		// Empty node alias
		let alias = "";
		let mut buf = [0u8; 32];
		buf[..alias.as_bytes().len()].copy_from_slice(alias.as_bytes());

		let expected_node_alias = NodeAlias([0; 32]);
		let node_alias = sanitize_alias(alias).unwrap();
		assert_eq!(node_alias, expected_node_alias);
	}

	#[test]
	fn sanitize_alias_with_sandwiched_null() {
		// Alias with emojis
		let alias = "I\u{1F496}LDK-Node!";
		let mut buf = [0u8; 32];
		buf[..alias.as_bytes().len()].copy_from_slice(alias.as_bytes());
		let expected_alias = NodeAlias(buf);

		let user_provided_alias = "I\u{1F496}LDK-Node!\0\u{26A1}";
		let node_alias = sanitize_alias(user_provided_alias).unwrap();

		let node_alias_display = format!("{}", node_alias);

		assert_eq!(alias, &node_alias_display);
		assert_ne!(expected_alias, node_alias);
	}

	#[test]
	fn sanitize_alias_gt_32_bytes() {
		let alias = "This is a string longer than thirty-two bytes!"; // 46 bytes
		let node = sanitize_alias(alias);
		assert_eq!(node.err().unwrap(), BuildError::InvalidNodeAlias);
	}
}