Skip to content

Commit 78eb34d

Browse files
committed
Clean up error types and logging outputs
Here we migrate from wrapping all upstream errors to exposing only select error variants to the downstream user. Also, we clean up and unify logging outputs.
1 parent 4b12fc7 commit 78eb34d

File tree

6 files changed

+143
-167
lines changed

6 files changed

+143
-167
lines changed

src/access.rs

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -64,11 +64,7 @@ where
6464
pub(crate) async fn sync_wallet(&self) -> Result<(), Error> {
6565
let sync_options = SyncOptions { progress: None };
6666

67-
self.wallet
68-
.lock()
69-
.unwrap()
70-
.sync(&self.blockchain, sync_options)
71-
.map_err(|e| Error::Bdk(e))?;
67+
self.wallet.lock().unwrap().sync(&self.blockchain, sync_options)?;
7268

7369
Ok(())
7470
}
@@ -140,11 +136,11 @@ where
140136
if let Some(merkle_proof) = client.get_merkle_proof(&txid).await? {
141137
if block_height == merkle_proof.block_height {
142138
confirmed_txs.push((
143-
tx,
144-
block_height,
145-
block_header,
146-
merkle_proof.pos,
147-
));
139+
tx,
140+
block_height,
141+
block_header,
142+
merkle_proof.pos,
143+
));
148144
continue;
149145
}
150146
}
@@ -300,7 +296,7 @@ where
300296
match self.blockchain.broadcast(tx) {
301297
Ok(_) => {}
302298
Err(err) => {
303-
log_error!(self.logger, "Failed to broadcast transaction: {}", err),
299+
log_error!(self.logger, "Failed to broadcast transaction: {}", err);
304300
panic!("Failed to broadcast transaction: {}", err);
305301
}
306302
}

src/error.rs

Lines changed: 42 additions & 94 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,5 @@
11
use bdk::blockchain::esplora;
2-
use lightning::ln::msgs;
3-
use lightning::util::errors;
4-
use lightning_invoice::payment;
52
use std::fmt;
6-
use std::io;
7-
use std::time;
83

94
#[derive(Debug)]
105
/// An error that possibly needs to be handled by the user.
@@ -19,112 +14,65 @@ pub enum LdkLiteError {
1914
ConnectionFailed,
2015
/// Payment of the given invoice has already been intiated.
2116
NonUniquePaymentHash,
17+
/// The given invoice is invalid.
18+
InvoiceInvalid,
19+
/// Invoice creation failed.
20+
InvoiceCreationFailed,
21+
/// No route for the given target could be found.
22+
RoutingFailed,
2223
/// A given peer info could not be parsed.
23-
PeerInfoParse(&'static str),
24-
/// A wrapped LDK `APIError`
25-
LdkApi(errors::APIError),
26-
/// A wrapped LDK `DecodeError`
27-
LdkDecode(msgs::DecodeError),
28-
/// A wrapped LDK `PaymentError`
29-
LdkPayment(payment::PaymentError),
30-
/// A wrapped LDK `SignOrCreationError`
31-
LdkInvoiceCreation(lightning_invoice::SignOrCreationError),
32-
/// A wrapped BDK error
33-
Bdk(bdk::Error),
34-
/// A wrapped `EsploraError`
35-
Esplora(esplora::EsploraError),
36-
/// A wrapped `Bip32` error
37-
Bip32(bitcoin::util::bip32::Error),
38-
/// A wrapped `std::io::Error`
39-
StdIo(io::Error),
40-
/// A wrapped `SystemTimeError`
41-
StdTime(time::SystemTimeError),
24+
PeerInfoParseFailed,
25+
/// A channel could not be opened.
26+
ChannelCreationFailed,
27+
/// A channel could not be closed.
28+
ChannelClosingFailed,
29+
/// Persistence failed.
30+
PersistenceFailed,
31+
/// A wallet operation failed.
32+
WalletOperationFailed,
33+
/// A siging operation failed.
34+
WalletSigningFailed,
35+
/// A chain access operation failed.
36+
ChainAccessFailed,
4237
}
4338

4439
impl fmt::Display for LdkLiteError {
4540
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4641
match *self {
47-
LdkLiteError::AlreadyRunning => write!(f, "LDKLite is already running."),
48-
LdkLiteError::NotRunning => write!(f, "LDKLite is not running."),
49-
LdkLiteError::FundingTxCreationFailed => {
50-
write!(f, "the funding transaction could not be created")
42+
Self::AlreadyRunning => write!(f, "LDKLite is already running."),
43+
Self::NotRunning => write!(f, "LDKLite is not running."),
44+
Self::FundingTxCreationFailed => {
45+
write!(f, "Funding transaction could not be created.")
5146
}
52-
LdkLiteError::ConnectionFailed => write!(f, "network connection closed"),
53-
LdkLiteError::NonUniquePaymentHash => write!(f, "an invoice must not get payed twice."),
54-
LdkLiteError::PeerInfoParse(ref e) => {
55-
write!(f, "given peer info could not be parsed: {}", e)
56-
}
57-
LdkLiteError::LdkDecode(ref e) => write!(f, "LDK decode error: {}", e),
58-
LdkLiteError::LdkApi(ref e) => write!(f, "LDK API error: {:?}", e),
59-
LdkLiteError::LdkPayment(ref e) => write!(f, "LDK payment error: {:?}", e),
60-
LdkLiteError::LdkInvoiceCreation(ref e) => {
61-
write!(f, "LDK invoice sign or creation error: {:?}", e)
62-
}
63-
LdkLiteError::Bdk(ref e) => write!(f, "BDK error: {}", e),
64-
LdkLiteError::Esplora(ref e) => write!(f, "Esplora error: {}", e),
65-
LdkLiteError::Bip32(ref e) => write!(f, "Bitcoin error: {}", e),
66-
LdkLiteError::StdIo(ref e) => write!(f, "IO error: {}", e),
67-
LdkLiteError::StdTime(ref e) => write!(f, "time error: {}", e),
47+
Self::ConnectionFailed => write!(f, "Network connection closed."),
48+
Self::NonUniquePaymentHash => write!(f, "An invoice must not get payed twice."),
49+
Self::InvoiceInvalid => write!(f, "The given invoice is invalid."),
50+
Self::InvoiceCreationFailed => write!(f, "Failed to create invoice."),
51+
Self::RoutingFailed => write!(f, "Failed to find route."),
52+
Self::PeerInfoParseFailed => write!(f, "Failed to parse the given peer information."),
53+
Self::ChannelCreationFailed => write!(f, "Failed to create channel."),
54+
Self::ChannelClosingFailed => write!(f, "Failed to close channel."),
55+
Self::PersistenceFailed => write!(f, "Failed to persist data."),
56+
Self::WalletOperationFailed => write!(f, "Failed to conduct wallet operation."),
57+
Self::WalletSigningFailed => write!(f, "Failed to sign given transaction."),
58+
Self::ChainAccessFailed => write!(f, "Failed to conduct chain access operation."),
6859
}
6960
}
7061
}
7162

72-
impl From<errors::APIError> for LdkLiteError {
73-
fn from(e: errors::APIError) -> Self {
74-
Self::LdkApi(e)
75-
}
76-
}
77-
78-
impl From<msgs::DecodeError> for LdkLiteError {
79-
fn from(e: msgs::DecodeError) -> Self {
80-
Self::LdkDecode(e)
81-
}
82-
}
83-
84-
impl From<payment::PaymentError> for LdkLiteError {
85-
fn from(e: payment::PaymentError) -> Self {
86-
Self::LdkPayment(e)
87-
}
88-
}
89-
90-
impl From<lightning_invoice::SignOrCreationError> for LdkLiteError {
91-
fn from(e: lightning_invoice::SignOrCreationError) -> Self {
92-
Self::LdkInvoiceCreation(e)
93-
}
94-
}
63+
impl std::error::Error for LdkLiteError {}
9564

9665
impl From<bdk::Error> for LdkLiteError {
9766
fn from(e: bdk::Error) -> Self {
98-
Self::Bdk(e)
99-
}
100-
}
101-
102-
impl From<bdk::sled::Error> for LdkLiteError {
103-
fn from(e: bdk::sled::Error) -> Self {
104-
Self::Bdk(bdk::Error::Sled(e))
105-
}
106-
}
107-
108-
impl From<bitcoin::util::bip32::Error> for LdkLiteError {
109-
fn from(e: bitcoin::util::bip32::Error) -> Self {
110-
Self::Bip32(e)
111-
}
112-
}
113-
114-
impl From<io::Error> for LdkLiteError {
115-
fn from(e: io::Error) -> Self {
116-
Self::StdIo(e)
117-
}
118-
}
119-
120-
impl From<time::SystemTimeError> for LdkLiteError {
121-
fn from(e: time::SystemTimeError) -> Self {
122-
Self::StdTime(e)
67+
match e {
68+
bdk::Error::Signer(_) => Self::WalletSigningFailed,
69+
_ => Self::WalletOperationFailed,
70+
}
12371
}
12472
}
12573

12674
impl From<esplora::EsploraError> for LdkLiteError {
127-
fn from(e: esplora::EsploraError) -> Self {
128-
Self::Esplora(e)
75+
fn from(_e: esplora::EsploraError) -> Self {
76+
Self::ChainAccessFailed
12977
}
13078
}

src/event.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,9 @@ impl<K: KVStorePersister> LdkLiteEventQueue<K> {
154154
let mut locked_queue = self.queue.lock().unwrap();
155155
locked_queue.0.push_back(event);
156156

157-
self.persister.persist(EVENTS_PERSISTENCE_KEY, &*locked_queue)?;
157+
self.persister
158+
.persist(EVENTS_PERSISTENCE_KEY, &*locked_queue)
159+
.map_err(|_| Error::PersistenceFailed)?;
158160

159161
self.notifier.notify_one();
160162
Ok(())
@@ -171,7 +173,9 @@ impl<K: KVStorePersister> LdkLiteEventQueue<K> {
171173
pub(crate) fn event_handled(&self) -> Result<(), Error> {
172174
let mut locked_queue = self.queue.lock().unwrap();
173175
locked_queue.0.pop_front();
174-
self.persister.persist(EVENTS_PERSISTENCE_KEY, &*locked_queue)?;
176+
self.persister
177+
.persist(EVENTS_PERSISTENCE_KEY, &*locked_queue)
178+
.map_err(|_| Error::PersistenceFailed)?;
175179
self.notifier.notify_one();
176180
Ok(())
177181
}

src/io_utils.rs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,13 @@ use std::convert::TryFrom;
1414
use std::fs;
1515
use std::io::{BufRead, BufReader, Write};
1616
use std::net::SocketAddr;
17+
use std::path::Path;
1718
use std::sync::Arc;
1819

19-
pub(crate) fn read_or_generate_seed_file(config: Arc<LdkLiteConfig>) -> Result<[u8; 32], Error> {
20+
pub(crate) fn read_or_generate_seed_file(config: Arc<LdkLiteConfig>) -> [u8; 32] {
2021
let keys_seed_path = format!("{}/keys_seed", config.storage_dir_path);
21-
let keys_seed = if let Ok(seed) = fs::read(keys_seed_path.clone()) {
22+
let keys_seed = if Path::new(&keys_seed_path).exists() {
23+
let seed = fs::read(keys_seed_path.clone()).expect("Failed to read keys seed file");
2224
assert_eq!(seed.len(), 32);
2325
let mut key = [0; 32];
2426
key.copy_from_slice(&seed);
@@ -27,13 +29,14 @@ pub(crate) fn read_or_generate_seed_file(config: Arc<LdkLiteConfig>) -> Result<[
2729
let mut key = [0; 32];
2830
thread_rng().fill_bytes(&mut key);
2931

30-
let mut f = fs::File::create(keys_seed_path.clone()).map_err(|e| Error::StdIo(e))?;
32+
let mut f =
33+
fs::File::create(keys_seed_path.clone()).expect("Failed to create keys seed file");
3134
f.write_all(&key).expect("Failed to write node keys seed to disk");
3235
f.sync_all().expect("Failed to sync node keys seed to disk");
3336
key
3437
};
3538

36-
Ok(keys_seed)
39+
keys_seed
3740
}
3841

3942
pub(crate) fn read_network_graph(

0 commit comments

Comments
 (0)