Skip to content

Commit 0fe2fac

Browse files
committed
Convert sweeper to use an async ChangeDestinationSource and provide
synchronous wrappers for usage in a sync context.
1 parent eb2254f commit 0fe2fac

File tree

5 files changed

+302
-65
lines changed

5 files changed

+302
-65
lines changed

lightning-background-processor/src/lib.rs

+19-12
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,18 @@ use lightning::onion_message::messenger::AOnionMessenger;
3636
use lightning::routing::gossip::{NetworkGraph, P2PGossipSync};
3737
use lightning::routing::scoring::{ScoreUpdate, WriteableScore};
3838
use lightning::routing::utxo::UtxoLookup;
39-
use lightning::sign::{ChangeDestinationSource, OutputSpender};
39+
#[cfg(feature = "futures")]
40+
use lightning::sign::ChangeDestinationSource;
41+
#[cfg(feature = "std")]
42+
use lightning::sign::ChangeDestinationSourceSync;
43+
use lightning::sign::OutputSpender;
4044
use lightning::util::logger::Logger;
4145
use lightning::util::persist::{KVStore, Persister};
46+
#[cfg(feature = "futures")]
4247
use lightning::util::sweep::OutputSweeper;
4348
#[cfg(feature = "std")]
49+
use lightning::util::sweep::OutputSweeperSync;
50+
#[cfg(feature = "std")]
4451
use lightning::util::wakers::Sleeper;
4552
use lightning_rapid_gossip_sync::RapidGossipSync;
4653

@@ -867,7 +874,7 @@ where
867874
gossip_sync,
868875
{
869876
if let Some(ref sweeper) = sweeper {
870-
sweeper.regenerate_and_broadcast_spend_if_necessary()
877+
sweeper.regenerate_and_broadcast_spend_if_necessary().await
871878
} else {
872879
Ok(())
873880
}
@@ -995,7 +1002,7 @@ impl BackgroundProcessor {
9951002
D: 'static + Deref,
9961003
O: 'static + Deref,
9971004
K: 'static + Deref,
998-
OS: 'static + Deref<Target = OutputSweeper<T, D, F, CF, K, L, O>> + Send + Sync,
1005+
OS: 'static + Deref<Target = OutputSweeperSync<T, D, F, CF, K, L, O>> + Send + Sync,
9991006
>(
10001007
persister: PS, event_handler: EH, chain_monitor: M, channel_manager: CM,
10011008
onion_messenger: Option<OM>, gossip_sync: GossipSync<PGS, RGS, G, UL, L>, peer_manager: PM,
@@ -1013,8 +1020,8 @@ impl BackgroundProcessor {
10131020
OM::Target: AOnionMessenger,
10141021
PM::Target: APeerManager,
10151022
LM::Target: ALiquidityManager,
1023+
D::Target: ChangeDestinationSourceSync,
10161024
O::Target: 'static + OutputSpender,
1017-
D::Target: 'static + ChangeDestinationSource,
10181025
K::Target: 'static + KVStore,
10191026
{
10201027
let stop_thread = Arc::new(AtomicBool::new(false));
@@ -1180,7 +1187,7 @@ mod tests {
11801187
use lightning::routing::gossip::{NetworkGraph, P2PGossipSync};
11811188
use lightning::routing::router::{CandidateRouteHop, DefaultRouter, Path, RouteHop};
11821189
use lightning::routing::scoring::{ChannelUsage, LockableScore, ScoreLookUp, ScoreUpdate};
1183-
use lightning::sign::{ChangeDestinationSource, InMemorySigner, KeysManager};
1190+
use lightning::sign::{ChangeDestinationSourceSync, InMemorySigner, KeysManager};
11841191
use lightning::types::features::{ChannelFeatures, NodeFeatures};
11851192
use lightning::types::payment::PaymentHash;
11861193
use lightning::util::config::UserConfig;
@@ -1192,7 +1199,7 @@ mod tests {
11921199
SCORER_PERSISTENCE_SECONDARY_NAMESPACE,
11931200
};
11941201
use lightning::util::ser::Writeable;
1195-
use lightning::util::sweep::{OutputSpendStatus, OutputSweeper, PRUNE_DELAY_BLOCKS};
1202+
use lightning::util::sweep::{OutputSpendStatus, OutputSweeperSync, PRUNE_DELAY_BLOCKS};
11961203
use lightning::util::test_utils;
11971204
use lightning::{get_event, get_event_msg};
11981205
use lightning_liquidity::LiquidityManager;
@@ -1318,7 +1325,7 @@ mod tests {
13181325
best_block: BestBlock,
13191326
scorer: Arc<LockingWrapper<TestScorer>>,
13201327
sweeper: Arc<
1321-
OutputSweeper<
1328+
OutputSweeperSync<
13221329
Arc<test_utils::TestBroadcaster>,
13231330
Arc<TestWallet>,
13241331
Arc<test_utils::TestFeeEstimator>,
@@ -1619,7 +1626,7 @@ mod tests {
16191626

16201627
struct TestWallet {}
16211628

1622-
impl ChangeDestinationSource for TestWallet {
1629+
impl ChangeDestinationSourceSync for TestWallet {
16231630
fn get_change_destination_script(&self) -> Result<ScriptBuf, ()> {
16241631
Ok(ScriptBuf::new())
16251632
}
@@ -1697,7 +1704,7 @@ mod tests {
16971704
IgnoringMessageHandler {},
16981705
));
16991706
let wallet = Arc::new(TestWallet {});
1700-
let sweeper = Arc::new(OutputSweeper::new(
1707+
let sweeper = Arc::new(OutputSweeperSync::new(
17011708
best_block,
17021709
Arc::clone(&tx_broadcaster),
17031710
Arc::clone(&fee_estimator),
@@ -2114,7 +2121,7 @@ mod tests {
21142121
nodes[0].rapid_gossip_sync(),
21152122
nodes[0].peer_manager.clone(),
21162123
Some(Arc::clone(&nodes[0].liquidity_manager)),
2117-
Some(nodes[0].sweeper.clone()),
2124+
Some(nodes[0].sweeper.sweeper_async()),
21182125
nodes[0].logger.clone(),
21192126
Some(nodes[0].scorer.clone()),
21202127
move |dur: Duration| {
@@ -2622,7 +2629,7 @@ mod tests {
26222629
nodes[0].rapid_gossip_sync(),
26232630
nodes[0].peer_manager.clone(),
26242631
Some(Arc::clone(&nodes[0].liquidity_manager)),
2625-
Some(nodes[0].sweeper.clone()),
2632+
Some(nodes[0].sweeper.sweeper_async()),
26262633
nodes[0].logger.clone(),
26272634
Some(nodes[0].scorer.clone()),
26282635
move |dur: Duration| {
@@ -2838,7 +2845,7 @@ mod tests {
28382845
nodes[0].no_gossip_sync(),
28392846
nodes[0].peer_manager.clone(),
28402847
Some(Arc::clone(&nodes[0].liquidity_manager)),
2841-
Some(nodes[0].sweeper.clone()),
2848+
Some(nodes[0].sweeper.sweeper_async()),
28422849
nodes[0].logger.clone(),
28432850
Some(nodes[0].scorer.clone()),
28442851
move |dur: Duration| {

lightning/src/lib.rs

-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@
3030
//! * `grind_signatures`
3131
3232
#![cfg_attr(not(any(test, fuzzing, feature = "_test_utils")), deny(missing_docs))]
33-
#![cfg_attr(not(any(test, feature = "_test_utils")), forbid(unsafe_code))]
3433

3534
#![deny(rustdoc::broken_intra_doc_links)]
3635
#![deny(rustdoc::private_intra_doc_links)]

lightning/src/sign/mod.rs

+42
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,9 @@ use crate::sign::ecdsa::EcdsaChannelSigner;
6767
use crate::sign::taproot::TaprootChannelSigner;
6868
use crate::util::atomic_counter::AtomicCounter;
6969
use core::convert::TryInto;
70+
use core::future::Future;
71+
use core::ops::Deref;
72+
use core::pin::Pin;
7073
use core::sync::atomic::{AtomicUsize, Ordering};
7174
#[cfg(taproot)]
7275
use musig2::types::{PartialSignature, PublicNonce};
@@ -975,17 +978,56 @@ pub trait SignerProvider {
975978
fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()>;
976979
}
977980

981+
/// A type alias for a future that returns a result of type T.
982+
pub type AsyncResult<'a, T> = Pin<Box<dyn Future<Output = Result<T, ()>> + 'a + Send>>;
983+
978984
/// A helper trait that describes an on-chain wallet capable of returning a (change) destination
979985
/// script.
980986
pub trait ChangeDestinationSource {
981987
/// Returns a script pubkey which can be used as a change destination for
982988
/// [`OutputSpender::spend_spendable_outputs`].
983989
///
990+
/// This method should return a different value each time it is called, to avoid linking
991+
/// on-chain funds controlled to the same user.
992+
fn get_change_destination_script<'a>(&self) -> AsyncResult<'a, ScriptBuf>;
993+
}
994+
995+
/// A synchronous helper trait that describes an on-chain wallet capable of returning a (change) destination script.
996+
pub trait ChangeDestinationSourceSync {
984997
/// This method should return a different value each time it is called, to avoid linking
985998
/// on-chain funds controlled to the same user.
986999
fn get_change_destination_script(&self) -> Result<ScriptBuf, ()>;
9871000
}
9881001

1002+
/// A wrapper around [`ChangeDestinationSource`] to allow for async calls.
1003+
#[cfg(any(test, feature = "_test_utils"))]
1004+
pub struct ChangeDestinationSourceSyncWrapper<T: Deref>(T)
1005+
where
1006+
T::Target: ChangeDestinationSourceSync;
1007+
#[cfg(not(any(test, feature = "_test_utils")))]
1008+
pub(crate) struct ChangeDestinationSourceSyncWrapper<T: Deref>(T)
1009+
where
1010+
T::Target: ChangeDestinationSourceSync;
1011+
1012+
impl<T: Deref> ChangeDestinationSourceSyncWrapper<T>
1013+
where
1014+
T::Target: ChangeDestinationSourceSync,
1015+
{
1016+
/// Creates a new [`ChangeDestinationSourceSyncWrapper`].
1017+
pub fn new(source: T) -> Self {
1018+
Self(source)
1019+
}
1020+
}
1021+
impl<T: Deref> ChangeDestinationSource for ChangeDestinationSourceSyncWrapper<T>
1022+
where
1023+
T::Target: ChangeDestinationSourceSync,
1024+
{
1025+
fn get_change_destination_script<'a>(&self) -> AsyncResult<'a, ScriptBuf> {
1026+
let script = self.0.get_change_destination_script();
1027+
Box::pin(async move { script })
1028+
}
1029+
}
1030+
9891031
mod sealed {
9901032
use bitcoin::secp256k1::{Scalar, SecretKey};
9911033

lightning/src/util/async_poll.rs

+22-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use crate::prelude::*;
1313
use core::future::Future;
1414
use core::marker::Unpin;
1515
use core::pin::Pin;
16-
use core::task::{Context, Poll};
16+
use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
1717

1818
pub(crate) enum ResultFuture<F: Future<Output = Result<(), E>>, E: Copy + Unpin> {
1919
Pending(F),
@@ -74,3 +74,24 @@ impl<F: Future<Output = Result<(), E>> + Unpin, E: Copy + Unpin> Future
7474
}
7575
}
7676
}
77+
78+
// If we want to poll a future without an async context to figure out if it has completed or
79+
// not without awaiting, we need a Waker, which needs a vtable...we fill it with dummy values
80+
// but sadly there's a good bit of boilerplate here.
81+
//
82+
// Waker::noop() would be preferable, but requires an MSRV of 1.85.
83+
fn dummy_waker_clone(_: *const ()) -> RawWaker {
84+
RawWaker::new(core::ptr::null(), &DUMMY_WAKER_VTABLE)
85+
}
86+
fn dummy_waker_action(_: *const ()) {}
87+
88+
const DUMMY_WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new(
89+
dummy_waker_clone,
90+
dummy_waker_action,
91+
dummy_waker_action,
92+
dummy_waker_action,
93+
);
94+
95+
pub(crate) fn dummy_waker() -> Waker {
96+
unsafe { Waker::from_raw(RawWaker::new(core::ptr::null(), &DUMMY_WAKER_VTABLE)) }
97+
}

0 commit comments

Comments
 (0)