Skip to content

Commit 3d2b4de

Browse files
Merge pull request #3552 from TheBlueMatt/2025-01-3323-followups
`utils` cleanups
2 parents 86308e1 + bc7631f commit 3d2b4de

File tree

2 files changed

+49
-79
lines changed

2 files changed

+49
-79
lines changed

lightning/src/util/test_utils.rs

Lines changed: 42 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,10 @@ use crate::chain::chaininterface;
1515
use crate::chain::chaininterface::ConfirmationTarget;
1616
#[cfg(test)]
1717
use crate::chain::chaininterface::FEERATE_FLOOR_SATS_PER_KW;
18-
use crate::chain::chainmonitor;
19-
use crate::chain::channelmonitor;
20-
use crate::chain::channelmonitor::MonitorEvent;
18+
use crate::chain::chainmonitor::{ChainMonitor, Persist};
19+
use crate::chain::channelmonitor::{
20+
ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, MonitorEvent,
21+
};
2122
use crate::chain::transaction::OutPoint;
2223
use crate::chain::WatchedOutput;
2324
use crate::events;
@@ -386,16 +387,16 @@ impl SignerProvider for OnlyReadsKeysInterface {
386387
}
387388

388389
pub struct TestChainMonitor<'a> {
389-
pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<TestChannelSigner>)>>,
390-
pub monitor_updates: Mutex<HashMap<ChannelId, Vec<channelmonitor::ChannelMonitorUpdate>>>,
390+
pub added_monitors: Mutex<Vec<(OutPoint, ChannelMonitor<TestChannelSigner>)>>,
391+
pub monitor_updates: Mutex<HashMap<ChannelId, Vec<ChannelMonitorUpdate>>>,
391392
pub latest_monitor_update_id: Mutex<HashMap<ChannelId, (OutPoint, u64, u64)>>,
392-
pub chain_monitor: chainmonitor::ChainMonitor<
393+
pub chain_monitor: ChainMonitor<
393394
TestChannelSigner,
394395
&'a TestChainSource,
395396
&'a dyn chaininterface::BroadcasterInterface,
396397
&'a TestFeeEstimator,
397398
&'a TestLogger,
398-
&'a dyn chainmonitor::Persist<TestChannelSigner>,
399+
&'a dyn Persist<TestChannelSigner>,
399400
>,
400401
pub keys_manager: &'a TestKeysInterface,
401402
/// If this is set to Some(), the next update_channel call (not watch_channel) must be a
@@ -410,29 +411,23 @@ impl<'a> TestChainMonitor<'a> {
410411
pub fn new(
411412
chain_source: Option<&'a TestChainSource>,
412413
broadcaster: &'a dyn chaininterface::BroadcasterInterface, logger: &'a TestLogger,
413-
fee_estimator: &'a TestFeeEstimator,
414-
persister: &'a dyn chainmonitor::Persist<TestChannelSigner>,
414+
fee_estimator: &'a TestFeeEstimator, persister: &'a dyn Persist<TestChannelSigner>,
415415
keys_manager: &'a TestKeysInterface,
416416
) -> Self {
417-
let added_monitors = Mutex::new(Vec::new());
418-
let monitor_updates = Mutex::new(new_hash_map());
419-
let latest_monitor_update_id = Mutex::new(new_hash_map());
420-
let expect_channel_force_closed = Mutex::new(None);
421-
let expect_monitor_round_trip_fail = Mutex::new(None);
422417
Self {
423-
added_monitors,
424-
monitor_updates,
425-
latest_monitor_update_id,
426-
chain_monitor: chainmonitor::ChainMonitor::new(
418+
added_monitors: Mutex::new(Vec::new()),
419+
monitor_updates: Mutex::new(new_hash_map()),
420+
latest_monitor_update_id: Mutex::new(new_hash_map()),
421+
chain_monitor: ChainMonitor::new(
427422
chain_source,
428423
broadcaster,
429424
logger,
430425
fee_estimator,
431426
persister,
432427
),
433428
keys_manager,
434-
expect_channel_force_closed,
435-
expect_monitor_round_trip_fail,
429+
expect_channel_force_closed: Mutex::new(None),
430+
expect_monitor_round_trip_fail: Mutex::new(None),
436431
}
437432
}
438433

@@ -444,13 +439,13 @@ impl<'a> TestChainMonitor<'a> {
444439
}
445440
impl<'a> chain::Watch<TestChannelSigner> for TestChainMonitor<'a> {
446441
fn watch_channel(
447-
&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<TestChannelSigner>,
442+
&self, funding_txo: OutPoint, monitor: ChannelMonitor<TestChannelSigner>,
448443
) -> Result<chain::ChannelMonitorUpdateStatus, ()> {
449444
// At every point where we get a monitor update, we should be able to send a useful monitor
450445
// to a watchtower and disk...
451446
let mut w = TestVecWriter(Vec::new());
452447
monitor.write(&mut w).unwrap();
453-
let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
448+
let new_monitor = <(BlockHash, ChannelMonitor<TestChannelSigner>)>::read(
454449
&mut io::Cursor::new(&w.0),
455450
(self.keys_manager, self.keys_manager),
456451
)
@@ -466,15 +461,12 @@ impl<'a> chain::Watch<TestChannelSigner> for TestChainMonitor<'a> {
466461
}
467462

468463
fn update_channel(
469-
&self, funding_txo: OutPoint, update: &channelmonitor::ChannelMonitorUpdate,
464+
&self, funding_txo: OutPoint, update: &ChannelMonitorUpdate,
470465
) -> chain::ChannelMonitorUpdateStatus {
471466
// Every monitor update should survive roundtrip
472467
let mut w = TestVecWriter(Vec::new());
473468
update.write(&mut w).unwrap();
474-
assert!(
475-
channelmonitor::ChannelMonitorUpdate::read(&mut io::Cursor::new(&w.0)).unwrap()
476-
== *update
477-
);
469+
assert_eq!(ChannelMonitorUpdate::read(&mut &w.0[..]).unwrap(), *update);
478470
let channel_id =
479471
update.channel_id.unwrap_or(ChannelId::v1_from_funding_outpoint(funding_txo));
480472

@@ -488,11 +480,9 @@ impl<'a> chain::Watch<TestChannelSigner> for TestChainMonitor<'a> {
488480
if let Some(exp) = self.expect_channel_force_closed.lock().unwrap().take() {
489481
assert_eq!(channel_id, exp.0);
490482
assert_eq!(update.updates.len(), 1);
491-
if let channelmonitor::ChannelMonitorUpdateStep::ChannelForceClosed {
492-
should_broadcast,
493-
} = update.updates[0]
494-
{
495-
assert_eq!(should_broadcast, exp.1);
483+
let update = &update.updates[0];
484+
if let ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update {
485+
assert_eq!(*should_broadcast, exp.1);
496486
} else {
497487
panic!();
498488
}
@@ -508,7 +498,7 @@ impl<'a> chain::Watch<TestChannelSigner> for TestChainMonitor<'a> {
508498
let monitor = self.chain_monitor.get_monitor(funding_txo).unwrap();
509499
w.0.clear();
510500
monitor.write(&mut w).unwrap();
511-
let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
501+
let new_monitor = <(BlockHash, ChannelMonitor<TestChannelSigner>)>::read(
512502
&mut io::Cursor::new(&w.0),
513503
(self.keys_manager, self.keys_manager),
514504
)
@@ -598,11 +588,9 @@ impl WatchtowerPersister {
598588
}
599589

600590
#[cfg(test)]
601-
impl<Signer: sign::ecdsa::EcdsaChannelSigner> chainmonitor::Persist<Signer>
602-
for WatchtowerPersister
603-
{
591+
impl<Signer: sign::ecdsa::EcdsaChannelSigner> Persist<Signer> for WatchtowerPersister {
604592
fn persist_new_channel(
605-
&self, funding_txo: OutPoint, data: &channelmonitor::ChannelMonitor<Signer>,
593+
&self, funding_txo: OutPoint, data: &ChannelMonitor<Signer>,
606594
) -> chain::ChannelMonitorUpdateStatus {
607595
let res = self.persister.persist_new_channel(funding_txo, data);
608596

@@ -635,8 +623,8 @@ impl<Signer: sign::ecdsa::EcdsaChannelSigner> chainmonitor::Persist<Signer>
635623
}
636624

637625
fn update_persisted_channel(
638-
&self, funding_txo: OutPoint, update: Option<&channelmonitor::ChannelMonitorUpdate>,
639-
data: &channelmonitor::ChannelMonitor<Signer>,
626+
&self, funding_txo: OutPoint, update: Option<&ChannelMonitorUpdate>,
627+
data: &ChannelMonitor<Signer>,
640628
) -> chain::ChannelMonitorUpdateStatus {
641629
let res = self.persister.update_persisted_channel(funding_txo, update, data);
642630

@@ -679,7 +667,7 @@ impl<Signer: sign::ecdsa::EcdsaChannelSigner> chainmonitor::Persist<Signer>
679667
}
680668

681669
fn archive_persisted_channel(&self, funding_txo: OutPoint) {
682-
<TestPersister as chainmonitor::Persist<TestChannelSigner>>::archive_persisted_channel(
670+
<TestPersister as Persist<TestChannelSigner>>::archive_persisted_channel(
683671
&self.persister,
684672
funding_txo,
685673
);
@@ -692,8 +680,6 @@ pub struct TestPersister {
692680
pub update_rets: Mutex<VecDeque<chain::ChannelMonitorUpdateStatus>>,
693681
/// When we get an update_persisted_channel call *with* a ChannelMonitorUpdate, we insert the
694682
/// [`ChannelMonitor::get_latest_update_id`] here.
695-
///
696-
/// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
697683
pub offchain_monitor_updates: Mutex<HashMap<OutPoint, HashSet<u64>>>,
698684
/// When we get an update_persisted_channel call with no ChannelMonitorUpdate, we insert the
699685
/// monitor's funding outpoint here.
@@ -712,9 +698,9 @@ impl TestPersister {
712698
self.update_rets.lock().unwrap().push_back(next_ret);
713699
}
714700
}
715-
impl<Signer: sign::ecdsa::EcdsaChannelSigner> chainmonitor::Persist<Signer> for TestPersister {
701+
impl<Signer: sign::ecdsa::EcdsaChannelSigner> Persist<Signer> for TestPersister {
716702
fn persist_new_channel(
717-
&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<Signer>,
703+
&self, _funding_txo: OutPoint, _data: &ChannelMonitor<Signer>,
718704
) -> chain::ChannelMonitorUpdateStatus {
719705
if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
720706
return update_ret;
@@ -723,8 +709,8 @@ impl<Signer: sign::ecdsa::EcdsaChannelSigner> chainmonitor::Persist<Signer> for
723709
}
724710

725711
fn update_persisted_channel(
726-
&self, funding_txo: OutPoint, update: Option<&channelmonitor::ChannelMonitorUpdate>,
727-
_data: &channelmonitor::ChannelMonitor<Signer>,
712+
&self, funding_txo: OutPoint, update: Option<&ChannelMonitorUpdate>,
713+
_data: &ChannelMonitor<Signer>,
728714
) -> chain::ChannelMonitorUpdateStatus {
729715
let mut ret = chain::ChannelMonitorUpdateStatus::Completed;
730716
if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
@@ -918,13 +904,10 @@ impl TestChannelMessageHandler {
918904

919905
impl TestChannelMessageHandler {
920906
pub fn new(chain_hash: ChainHash) -> Self {
921-
let pending_events = Mutex::new(Vec::new());
922-
let expected_recv_msgs = Mutex::new(None);
923-
let connected_peers = Mutex::new(new_hash_set());
924907
TestChannelMessageHandler {
925-
pending_events,
926-
expected_recv_msgs,
927-
connected_peers,
908+
pending_events: Mutex::new(Vec::new()),
909+
expected_recv_msgs: Mutex::new(None),
910+
connected_peers: Mutex::new(new_hash_set()),
928911
chain_hash,
929912
}
930913
}
@@ -1576,19 +1559,14 @@ impl SignerProvider for TestKeysInterface {
15761559
impl TestKeysInterface {
15771560
pub fn new(seed: &[u8; 32], network: Network) -> Self {
15781561
let now = Duration::from_secs(genesis_block(network).header.time as u64);
1579-
let override_random_bytes = Mutex::new(None);
1580-
let enforcement_states = Mutex::new(new_hash_map());
1581-
let expectations = Mutex::new(None);
1582-
let unavailable_signers_ops = Mutex::new(new_hash_map());
1583-
let next_signer_disabled_ops = Mutex::new(new_hash_set());
15841562
Self {
15851563
backing: sign::PhantomKeysManager::new(seed, now.as_secs(), now.subsec_nanos(), seed),
1586-
override_random_bytes,
1564+
override_random_bytes: Mutex::new(None),
15871565
disable_revocation_policy_check: false,
1588-
enforcement_states,
1589-
expectations,
1590-
unavailable_signers_ops,
1591-
next_signer_disabled_ops,
1566+
enforcement_states: Mutex::new(new_hash_map()),
1567+
expectations: Mutex::new(None),
1568+
unavailable_signers_ops: Mutex::new(new_hash_map()),
1569+
next_signer_disabled_ops: Mutex::new(new_hash_set()),
15921570
}
15931571
}
15941572

@@ -1662,14 +1640,12 @@ impl TestChainSource {
16621640
let script_pubkey = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
16631641
let utxo_ret =
16641642
Mutex::new(UtxoResult::Sync(Ok(TxOut { value: Amount::MAX, script_pubkey })));
1665-
let watched_txn = Mutex::new(new_hash_set());
1666-
let watched_outputs = Mutex::new(new_hash_set());
16671643
Self {
16681644
chain_hash: ChainHash::using_genesis_block(network),
16691645
utxo_ret,
16701646
get_utxo_call_count: AtomicUsize::new(0),
1671-
watched_txn,
1672-
watched_outputs,
1647+
watched_txn: Mutex::new(new_hash_set()),
1648+
watched_outputs: Mutex::new(new_hash_set()),
16731649
}
16741650
}
16751651
pub fn remove_watched_txn_and_outputs(&self, outpoint: OutPoint, script_pubkey: ScriptBuf) {

lightning/src/util/transaction_utils.rs

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -219,10 +219,8 @@ mod tests {
219219
// If we have a bogus input amount or outputs valued more than inputs, we should fail
220220
let version = Version::TWO;
221221
let lock_time = LockTime::ZERO;
222-
let input = Vec::new();
223222
let tx_out = TxOut { script_pubkey: ScriptBuf::new(), value: Amount::from_sat(1000) };
224-
let output = vec![tx_out];
225-
let mut tx = Transaction { version, lock_time, input, output };
223+
let mut tx = Transaction { version, lock_time, input: Vec::new(), output: vec![tx_out] };
226224
let amount = Amount::from_sat(21_000_000_0000_0001);
227225
assert!(maybe_add_change_output(&mut tx, amount, 0, 253, ScriptBuf::new()).is_err());
228226
let amount = Amount::from_sat(400);
@@ -294,36 +292,32 @@ mod tests {
294292
let tx_in = TxIn { previous_output, script_sig, witness, sequence };
295293
let version = Version::TWO;
296294
let lock_time = LockTime::ZERO;
297-
let input = vec![tx_in];
298-
let output = vec![tx_out];
299-
let mut tx = Transaction { version, lock_time, input, output };
295+
let mut tx = Transaction { version, lock_time, input: vec![tx_in], output: vec![tx_out] };
300296
let orig_wtxid = tx.compute_wtxid();
301297
let orig_weight = tx.weight().to_wu();
302298
assert_eq!(orig_weight / 4, 61);
303299

304300
assert_eq!(Builder::new().push_int(2).into_script().minimal_non_dust().to_sat(), 474);
305301

302+
let script = Builder::new().push_int(2).into_script();
303+
306304
// Input value of the output value + fee - 1 should fail:
307305
let amount = Amount::from_sat(1000 + 61 + 100 - 1);
308-
let script = Builder::new().push_int(2).into_script();
309-
assert!(maybe_add_change_output(&mut tx, amount, 400, 250, script).is_err());
306+
assert!(maybe_add_change_output(&mut tx, amount, 400, 250, script.clone()).is_err());
310307
// Failure doesn't change the transaction
311308
assert_eq!(tx.compute_wtxid(), orig_wtxid);
312309
// but one more input sat should succeed, without changing the transaction
313310
let amount = Amount::from_sat(1000 + 61 + 100);
314-
let script = Builder::new().push_int(2).into_script();
315-
assert!(maybe_add_change_output(&mut tx, amount, 400, 250, script).is_ok());
311+
assert!(maybe_add_change_output(&mut tx, amount, 400, 250, script.clone()).is_ok());
316312
// If we don't add an output, we don't change the transaction
317313
assert_eq!(tx.compute_wtxid(), orig_wtxid);
318314
// In order to get a change output, we need to add 474 plus the output's weight / 4 (10)...
319315
let amount = Amount::from_sat(1000 + 61 + 100 + 474 + 9);
320-
let script = Builder::new().push_int(2).into_script();
321-
assert!(maybe_add_change_output(&mut tx, amount, 400, 250, script).is_ok());
316+
assert!(maybe_add_change_output(&mut tx, amount, 400, 250, script.clone()).is_ok());
322317
// If we don't add an output, we don't change the transaction
323318
assert_eq!(tx.compute_wtxid(), orig_wtxid);
324319

325320
let amount = Amount::from_sat(1000 + 61 + 100 + 474 + 10);
326-
let script = Builder::new().push_int(2).into_script();
327321
assert!(maybe_add_change_output(&mut tx, amount, 400, 250, script).is_ok());
328322
assert_eq!(tx.output.len(), 2);
329323
assert_eq!(tx.output[1].value.to_sat(), 474);

0 commit comments

Comments
 (0)