Skip to content

Commit 4c3254b

Browse files
committed
refactor(electrum): remove unwrap()s and expect()s
1 parent 63923c6 commit 4c3254b

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

crates/electrum/src/bdk_electrum_client.rs

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ impl<E: ElectrumApi> BdkElectrumClient<E> {
3838
/// transactions.
3939
pub fn populate_tx_cache(&self, txs: impl IntoIterator<Item = impl Into<Arc<Transaction>>>) {
4040
let mut tx_cache = self.tx_cache.lock().unwrap();
41+
4142
for tx in txs {
4243
let tx = tx.into();
4344
let txid = tx.compute_txid();
@@ -385,11 +386,9 @@ impl<E: ElectrumApi> BdkElectrumClient<E> {
385386
Err(other_err) => return Err(other_err),
386387
};
387388

388-
let spk = tx
389-
.output
390-
.first()
391-
.map(|txo| &txo.script_pubkey)
392-
.expect("tx must have an output");
389+
let Some(spk) = tx.output.first().map(|txo| &txo.script_pubkey) else {
390+
continue;
391+
};
393392

394393
// because of restrictions of the Electrum API, we have to use the `script_get_history`
395394
// call to get confirmation status of our transaction
@@ -475,8 +474,11 @@ impl<E: ElectrumApi> BdkElectrumClient<E> {
475474
let outpoint = vin.previous_output;
476475
let vout = outpoint.vout;
477476
let prev_tx = self.fetch_tx(outpoint.txid)?;
478-
let txout = prev_tx.output[vout as usize].clone();
479-
let _ = tx_update.txouts.insert(outpoint, txout);
477+
// Only insert txout if it exists. This avoids panicking on malformed or
478+
// incomplete transactions.
479+
if let Some(txout) = prev_tx.output.get(vout as usize) {
480+
let _ = tx_update.txouts.insert(outpoint, txout.clone());
481+
}
480482
}
481483
}
482484
}
@@ -548,11 +550,11 @@ fn fetch_tip_and_latest_blocks(
548550
})
549551
.fold(agreement_cp, |prev_cp, block| {
550552
Some(match prev_cp {
551-
Some(cp) => cp.push(block).expect("must extend checkpoint"),
553+
Some(cp) => cp.push(block).ok()?,
552554
None => CheckPoint::new(block),
553555
})
554556
})
555-
.expect("must have at least one checkpoint");
557+
.ok_or_else(|| Error::Message("failed to construct new checkpoint tip".to_string()))?;
556558

557559
Ok((new_tip, new_blocks))
558560
}

0 commit comments

Comments
 (0)