Skip to content

Commit 470085a

Browse files
committed
rustfmt: Reformat lightning-transaction-sync/src/electrum.rs
1 parent 3ead263 commit 470085a

File tree

2 files changed

+98
-84
lines changed

2 files changed

+98
-84
lines changed

lightning-transaction-sync/src/electrum.rs

Lines changed: 98 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,24 @@
1-
use crate::common::{ConfirmedTx, SyncState, FilterQueue};
2-
use crate::error::{TxSyncError, InternalError};
1+
use crate::common::{ConfirmedTx, FilterQueue, SyncState};
2+
use crate::error::{InternalError, TxSyncError};
33

44
use electrum_client::Client as ElectrumClient;
55
use electrum_client::ElectrumApi;
66
use electrum_client::GetMerkleRes;
77

8-
use lightning::util::logger::Logger;
9-
use lightning::{log_error, log_debug, log_trace};
108
use lightning::chain::WatchedOutput;
119
use lightning::chain::{Confirm, Filter};
10+
use lightning::util::logger::Logger;
11+
use lightning::{log_debug, log_error, log_trace};
1212

13-
use bitcoin::{BlockHash, Script, Transaction, Txid};
1413
use bitcoin::block::Header;
1514
use bitcoin::hash_types::TxMerkleNode;
16-
use bitcoin::hashes::Hash;
1715
use bitcoin::hashes::sha256d::Hash as Sha256d;
16+
use bitcoin::hashes::Hash;
17+
use bitcoin::{BlockHash, Script, Transaction, Txid};
1818

19+
use std::collections::HashSet;
1920
use std::ops::Deref;
2021
use std::sync::Mutex;
21-
use std::collections::HashSet;
2222
use std::time::Instant;
2323

2424
/// Synchronizes LDK with a given Electrum server.
@@ -64,12 +64,7 @@ where
6464
let sync_state = Mutex::new(SyncState::new());
6565
let queue = Mutex::new(FilterQueue::new());
6666

67-
Ok(Self {
68-
sync_state,
69-
queue,
70-
client,
71-
logger,
72-
})
67+
Ok(Self { sync_state, queue, client, logger })
7368
}
7469

7570
/// Synchronizes the given `confirmables` via their [`Confirm`] interface implementations. This
@@ -84,7 +79,8 @@ where
8479
/// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
8580
/// [`Filter`]: lightning::chain::Filter
8681
pub fn sync<C: Deref>(&self, confirmables: Vec<C>) -> Result<(), TxSyncError>
87-
where C::Target: Confirm
82+
where
83+
C::Target: Confirm,
8884
{
8985
// This lock makes sure we're syncing once at a time.
9086
let mut sync_state = self.sync_state.lock().unwrap();
@@ -124,15 +120,15 @@ where
124120
num_unconfirmed += unconfirmed_txs.len();
125121
sync_state.sync_unconfirmed_transactions(
126122
&confirmables,
127-
unconfirmed_txs
123+
unconfirmed_txs,
128124
);
129-
}
125+
},
130126
Ok(true) => {
131127
log_debug!(self.logger,
132128
"Encountered inconsistency during transaction sync, restarting.");
133129
sync_state.pending_sync = true;
134130
continue;
135-
}
131+
},
136132
Err(err) => {
137133
// (Semi-)permanent failure, retry later.
138134
log_error!(self.logger,
@@ -142,7 +138,7 @@ where
142138
);
143139
sync_state.pending_sync = true;
144140
return Err(TxSyncError::from(err));
145-
}
141+
},
146142
}
147143
},
148144
Err(err) => {
@@ -154,7 +150,7 @@ where
154150
);
155151
sync_state.pending_sync = true;
156152
return Err(TxSyncError::from(err));
157-
}
153+
},
158154
}
159155

160156
// Update the best block.
@@ -173,17 +169,15 @@ where
173169
match self.check_update_tip(&mut tip_header, &mut tip_height) {
174170
Ok(false) => {
175171
num_confirmed += confirmed_txs.len();
176-
sync_state.sync_confirmed_transactions(
177-
&confirmables,
178-
confirmed_txs
179-
);
180-
}
172+
sync_state
173+
.sync_confirmed_transactions(&confirmables, confirmed_txs);
174+
},
181175
Ok(true) => {
182176
log_debug!(self.logger,
183177
"Encountered inconsistency during transaction sync, restarting.");
184178
sync_state.pending_sync = true;
185179
continue;
186-
}
180+
},
187181
Err(err) => {
188182
// (Semi-)permanent failure, retry later.
189183
log_error!(self.logger,
@@ -193,16 +187,18 @@ where
193187
);
194188
sync_state.pending_sync = true;
195189
return Err(TxSyncError::from(err));
196-
}
190+
},
197191
}
198-
}
192+
},
199193
Err(InternalError::Inconsistency) => {
200194
// Immediately restart syncing when we encounter any inconsistencies.
201-
log_debug!(self.logger,
202-
"Encountered inconsistency during transaction sync, restarting.");
195+
log_debug!(
196+
self.logger,
197+
"Encountered inconsistency during transaction sync, restarting."
198+
);
203199
sync_state.pending_sync = true;
204200
continue;
205-
}
201+
},
206202
Err(err) => {
207203
// (Semi-)permanent failure, retry later.
208204
log_error!(self.logger,
@@ -212,27 +208,35 @@ where
212208
);
213209
sync_state.pending_sync = true;
214210
return Err(TxSyncError::from(err));
215-
}
211+
},
216212
}
217213
sync_state.last_sync_hash = Some(tip_header.block_hash());
218214
sync_state.pending_sync = false;
219215
}
220216
}
221217
#[cfg(feature = "time")]
222-
log_debug!(self.logger,
218+
log_debug!(
219+
self.logger,
223220
"Finished transaction sync at tip {} in {}ms: {} confirmed, {} unconfirmed.",
224-
tip_header.block_hash(), start_time.elapsed().as_millis(), num_confirmed,
225-
num_unconfirmed);
221+
tip_header.block_hash(),
222+
start_time.elapsed().as_millis(),
223+
num_confirmed,
224+
num_unconfirmed
225+
);
226226
#[cfg(not(feature = "time"))]
227-
log_debug!(self.logger,
227+
log_debug!(
228+
self.logger,
228229
"Finished transaction sync at tip {}: {} confirmed, {} unconfirmed.",
229-
tip_header.block_hash(), num_confirmed, num_unconfirmed);
230+
tip_header.block_hash(),
231+
num_confirmed,
232+
num_unconfirmed
233+
);
230234
Ok(())
231235
}
232236

233-
fn check_update_tip(&self, cur_tip_header: &mut Header, cur_tip_height: &mut u32)
234-
-> Result<bool, InternalError>
235-
{
237+
fn check_update_tip(
238+
&self, cur_tip_header: &mut Header, cur_tip_height: &mut u32,
239+
) -> Result<bool, InternalError> {
236240
let check_notification = self.client.block_headers_subscribe()?;
237241
let check_tip_hash = check_notification.header.block_hash();
238242

@@ -258,12 +262,12 @@ where
258262
fn get_confirmed_transactions(
259263
&self, sync_state: &SyncState,
260264
) -> Result<Vec<ConfirmedTx>, InternalError> {
261-
262265
// First, check the confirmation status of registered transactions as well as the
263266
// status of dependent transactions of registered outputs.
264267
let mut confirmed_txs: Vec<ConfirmedTx> = Vec::new();
265268
let mut watched_script_pubkeys = Vec::with_capacity(
266-
sync_state.watched_transactions.len() + sync_state.watched_outputs.len());
269+
sync_state.watched_transactions.len() + sync_state.watched_outputs.len(),
270+
);
267271
let mut watched_txs = Vec::with_capacity(sync_state.watched_transactions.len());
268272

269273
for txid in &sync_state.watched_transactions {
@@ -280,14 +284,14 @@ where
280284
log_error!(self.logger, "Failed due to retrieving invalid tx data.");
281285
return Err(InternalError::Failed);
282286
}
283-
}
287+
},
284288
Err(electrum_client::Error::Protocol(_)) => {
285289
// We couldn't find the tx, do nothing.
286-
}
290+
},
287291
Err(e) => {
288292
log_error!(self.logger, "Failed to look up transaction {}: {}.", txid, e);
289293
return Err(InternalError::Failed);
290-
}
294+
},
291295
}
292296
}
293297

@@ -312,18 +316,18 @@ where
312316
if confirmed_txs.iter().any(|ctx| ctx.txid == **txid) {
313317
continue;
314318
}
315-
let mut filtered_history = script_history.iter().filter(|h| h.tx_hash == **txid);
316-
if let Some(history) = filtered_history.next()
317-
{
319+
let mut filtered_history =
320+
script_history.iter().filter(|h| h.tx_hash == **txid);
321+
if let Some(history) = filtered_history.next() {
318322
let prob_conf_height = history.height as u32;
319323
let confirmed_tx = self.get_confirmed_tx(tx, prob_conf_height)?;
320324
confirmed_txs.push(confirmed_tx);
321325
}
322326
debug_assert!(filtered_history.next().is_none());
323327
}
324328

325-
for (watched_output, script_history) in sync_state.watched_outputs.values()
326-
.zip(output_results)
329+
for (watched_output, script_history) in
330+
sync_state.watched_outputs.values().zip(output_results)
327331
{
328332
for possible_output_spend in script_history {
329333
if possible_output_spend.height <= 0 {
@@ -339,8 +343,8 @@ where
339343
Ok(tx) => {
340344
let mut is_spend = false;
341345
for txin in &tx.input {
342-
let watched_outpoint = watched_output.outpoint
343-
.into_bitcoin_outpoint();
346+
let watched_outpoint =
347+
watched_output.outpoint.into_bitcoin_outpoint();
344348
if txin.previous_output == watched_outpoint {
345349
is_spend = true;
346350
break;
@@ -354,21 +358,24 @@ where
354358
let prob_conf_height = possible_output_spend.height as u32;
355359
let confirmed_tx = self.get_confirmed_tx(&tx, prob_conf_height)?;
356360
confirmed_txs.push(confirmed_tx);
357-
}
361+
},
358362
Err(e) => {
359-
log_trace!(self.logger,
363+
log_trace!(
364+
self.logger,
360365
"Inconsistency: Tx {} was unconfirmed during syncing: {}",
361-
txid, e);
366+
txid,
367+
e
368+
);
362369
return Err(InternalError::Inconsistency);
363-
}
370+
},
364371
}
365372
}
366373
}
367-
}
374+
},
368375
Err(e) => {
369376
log_error!(self.logger, "Failed to look up script histories: {}.", e);
370377
return Err(InternalError::Failed);
371-
}
378+
},
372379
}
373380

374381
// Sort all confirmed transactions first by block height, then by in-block
@@ -383,7 +390,8 @@ where
383390
fn get_unconfirmed_transactions<C: Deref>(
384391
&self, confirmables: &Vec<C>,
385392
) -> Result<Vec<Txid>, InternalError>
386-
where C::Target: Confirm
393+
where
394+
C::Target: Confirm,
387395
{
388396
// Query the interface for relevant txids and check whether the relevant blocks are still
389397
// in the best chain, mark them unconfirmed otherwise
@@ -412,46 +420,57 @@ where
412420
Ok(unconfirmed_txs)
413421
}
414422

415-
fn get_confirmed_tx(&self, tx: &Transaction, prob_conf_height: u32)
416-
-> Result<ConfirmedTx, InternalError>
417-
{
423+
fn get_confirmed_tx(
424+
&self, tx: &Transaction, prob_conf_height: u32,
425+
) -> Result<ConfirmedTx, InternalError> {
418426
let txid = tx.txid();
419427
match self.client.transaction_get_merkle(&txid, prob_conf_height as usize) {
420428
Ok(merkle_res) => {
421429
debug_assert_eq!(prob_conf_height, merkle_res.block_height as u32);
422430
match self.client.block_header(prob_conf_height as usize) {
423431
Ok(block_header) => {
424432
let pos = merkle_res.pos;
425-
if !self.validate_merkle_proof(&txid,
426-
&block_header.merkle_root, merkle_res)?
427-
{
428-
log_trace!(self.logger,
433+
if !self.validate_merkle_proof(
434+
&txid,
435+
&block_header.merkle_root,
436+
merkle_res,
437+
)? {
438+
log_trace!(
439+
self.logger,
429440
"Inconsistency: Block {} was unconfirmed during syncing.",
430-
block_header.block_hash());
441+
block_header.block_hash()
442+
);
431443
return Err(InternalError::Inconsistency);
432444
}
433445
let confirmed_tx = ConfirmedTx {
434446
tx: tx.clone(),
435447
txid,
436-
block_header, block_height: prob_conf_height,
448+
block_header,
449+
block_height: prob_conf_height,
437450
pos,
438451
};
439452
Ok(confirmed_tx)
440-
}
453+
},
441454
Err(e) => {
442-
log_error!(self.logger,
455+
log_error!(
456+
self.logger,
443457
"Failed to retrieve block header for height {}: {}.",
444-
prob_conf_height, e);
458+
prob_conf_height,
459+
e
460+
);
445461
Err(InternalError::Failed)
446-
}
462+
},
447463
}
448-
}
464+
},
449465
Err(e) => {
450-
log_trace!(self.logger,
466+
log_trace!(
467+
self.logger,
451468
"Inconsistency: Tx {} was unconfirmed during syncing: {}",
452-
txid, e);
469+
txid,
470+
e
471+
);
453472
Err(InternalError::Inconsistency)
454-
}
473+
},
455474
}
456475
}
457476

@@ -462,20 +481,16 @@ where
462481
&self.client
463482
}
464483

465-
fn validate_merkle_proof(&self, txid: &Txid, merkle_root: &TxMerkleNode,
466-
merkle_res: GetMerkleRes) -> Result<bool, InternalError>
467-
{
484+
fn validate_merkle_proof(
485+
&self, txid: &Txid, merkle_root: &TxMerkleNode, merkle_res: GetMerkleRes,
486+
) -> Result<bool, InternalError> {
468487
let mut index = merkle_res.pos;
469488
let mut cur = txid.to_raw_hash();
470489
for mut bytes in merkle_res.merkle {
471490
bytes.reverse();
472491
// unwrap() safety: `bytes` has len 32 so `from_slice` can never fail.
473492
let next_hash = Sha256d::from_slice(&bytes).unwrap();
474-
let (left, right) = if index % 2 == 0 {
475-
(cur, next_hash)
476-
} else {
477-
(next_hash, cur)
478-
};
493+
let (left, right) = if index % 2 == 0 { (cur, next_hash) } else { (next_hash, cur) };
479494

480495
let data = [&left[..], &right[..]].concat();
481496
cur = Sha256d::hash(&data);

0 commit comments

Comments
 (0)