Skip to content

Commit e7d646a

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

File tree

5 files changed

+294
-65
lines changed

5 files changed

+294
-65
lines changed

Diff for: 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

@@ -844,7 +851,7 @@ where
844851
gossip_sync,
845852
{
846853
if let Some(ref sweeper) = sweeper {
847-
sweeper.regenerate_and_broadcast_spend_if_necessary()
854+
sweeper.regenerate_and_broadcast_spend_if_necessary().await
848855
} else {
849856
Ok(())
850857
}
@@ -964,7 +971,7 @@ impl BackgroundProcessor {
964971
D: 'static + Deref,
965972
O: 'static + Deref,
966973
K: 'static + Deref,
967-
OS: 'static + Deref<Target = OutputSweeper<T, D, F, CF, K, L, O>> + Send + Sync,
974+
OS: 'static + Deref<Target = OutputSweeperSync<T, D, F, CF, K, L, O>> + Send + Sync,
968975
>(
969976
persister: PS, event_handler: EH, chain_monitor: M, channel_manager: CM,
970977
onion_messenger: Option<OM>, gossip_sync: GossipSync<PGS, RGS, G, UL, L>, peer_manager: PM,
@@ -981,8 +988,8 @@ impl BackgroundProcessor {
981988
CM::Target: AChannelManager + Send + Sync,
982989
OM::Target: AOnionMessenger + Send + Sync,
983990
PM::Target: APeerManager + Send + Sync,
991+
D::Target: ChangeDestinationSourceSync,
984992
O::Target: 'static + OutputSpender,
985-
D::Target: 'static + ChangeDestinationSource,
986993
K::Target: 'static + KVStore,
987994
{
988995
let stop_thread = Arc::new(AtomicBool::new(false));
@@ -1138,7 +1145,7 @@ mod tests {
11381145
use lightning::routing::gossip::{NetworkGraph, P2PGossipSync};
11391146
use lightning::routing::router::{CandidateRouteHop, DefaultRouter, Path, RouteHop};
11401147
use lightning::routing::scoring::{ChannelUsage, LockableScore, ScoreLookUp, ScoreUpdate};
1141-
use lightning::sign::{ChangeDestinationSource, InMemorySigner, KeysManager};
1148+
use lightning::sign::{ChangeDestinationSourceSync, InMemorySigner, KeysManager};
11421149
use lightning::types::features::{ChannelFeatures, NodeFeatures};
11431150
use lightning::types::payment::PaymentHash;
11441151
use lightning::util::config::UserConfig;
@@ -1150,7 +1157,7 @@ mod tests {
11501157
SCORER_PERSISTENCE_SECONDARY_NAMESPACE,
11511158
};
11521159
use lightning::util::ser::Writeable;
1153-
use lightning::util::sweep::{OutputSpendStatus, OutputSweeper, PRUNE_DELAY_BLOCKS};
1160+
use lightning::util::sweep::{OutputSpendStatus, OutputSweeperSync, PRUNE_DELAY_BLOCKS};
11541161
use lightning::util::test_utils;
11551162
use lightning::{get_event, get_event_msg};
11561163
use lightning_persister::fs_store::FilesystemStore;
@@ -1271,7 +1278,7 @@ mod tests {
12711278
best_block: BestBlock,
12721279
scorer: Arc<LockingWrapper<TestScorer>>,
12731280
sweeper: Arc<
1274-
OutputSweeper<
1281+
OutputSweeperSync<
12751282
Arc<test_utils::TestBroadcaster>,
12761283
Arc<TestWallet>,
12771284
Arc<test_utils::TestFeeEstimator>,
@@ -1572,7 +1579,7 @@ mod tests {
15721579

15731580
struct TestWallet {}
15741581

1575-
impl ChangeDestinationSource for TestWallet {
1582+
impl ChangeDestinationSourceSync for TestWallet {
15761583
fn get_change_destination_script(&self) -> Result<ScriptBuf, ()> {
15771584
Ok(ScriptBuf::new())
15781585
}
@@ -1650,7 +1657,7 @@ mod tests {
16501657
IgnoringMessageHandler {},
16511658
));
16521659
let wallet = Arc::new(TestWallet {});
1653-
let sweeper = Arc::new(OutputSweeper::new(
1660+
let sweeper = Arc::new(OutputSweeperSync::new(
16541661
best_block,
16551662
Arc::clone(&tx_broadcaster),
16561663
Arc::clone(&fee_estimator),
@@ -2054,7 +2061,7 @@ mod tests {
20542061
Some(nodes[0].messenger.clone()),
20552062
nodes[0].rapid_gossip_sync(),
20562063
nodes[0].peer_manager.clone(),
2057-
Some(nodes[0].sweeper.clone()),
2064+
Some(nodes[0].sweeper.sweeper_async()),
20582065
nodes[0].logger.clone(),
20592066
Some(nodes[0].scorer.clone()),
20602067
move |dur: Duration| {
@@ -2554,7 +2561,7 @@ mod tests {
25542561
Some(nodes[0].messenger.clone()),
25552562
nodes[0].rapid_gossip_sync(),
25562563
nodes[0].peer_manager.clone(),
2557-
Some(nodes[0].sweeper.clone()),
2564+
Some(nodes[0].sweeper.sweeper_async()),
25582565
nodes[0].logger.clone(),
25592566
Some(nodes[0].scorer.clone()),
25602567
move |dur: Duration| {
@@ -2768,7 +2775,7 @@ mod tests {
27682775
Some(nodes[0].messenger.clone()),
27692776
nodes[0].no_gossip_sync(),
27702777
nodes[0].peer_manager.clone(),
2771-
Some(nodes[0].sweeper.clone()),
2778+
Some(nodes[0].sweeper.sweeper_async()),
27722779
nodes[0].logger.clone(),
27732780
Some(nodes[0].scorer.clone()),
27742781
move |dur: Duration| {

Diff for: 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)]

Diff for: lightning/src/sign/mod.rs

+37
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,51 @@ 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+
pub struct ChangeDestinationSourceSyncWrapper<T: Deref>(T)
1004+
where
1005+
T::Target: ChangeDestinationSourceSync;
1006+
1007+
impl<T: Deref> ChangeDestinationSourceSyncWrapper<T>
1008+
where
1009+
T::Target: ChangeDestinationSourceSync,
1010+
{
1011+
/// Creates a new [`ChangeDestinationSourceSyncWrapper`].
1012+
pub fn new(source: T) -> Self {
1013+
Self(source)
1014+
}
1015+
}
1016+
impl<T: Deref> ChangeDestinationSource for ChangeDestinationSourceSyncWrapper<T>
1017+
where
1018+
T::Target: ChangeDestinationSourceSync,
1019+
{
1020+
fn get_change_destination_script<'a>(&self) -> AsyncResult<'a, ScriptBuf> {
1021+
let script = self.0.get_change_destination_script();
1022+
Box::pin(async move { script })
1023+
}
1024+
}
1025+
9891026
mod sealed {
9901027
use bitcoin::secp256k1::{Scalar, SecretKey};
9911028

Diff for: lightning/src/util/async_poll.rs

+20-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,22 @@ 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+
fn dummy_waker_clone(_: *const ()) -> RawWaker {
82+
RawWaker::new(core::ptr::null(), &DUMMY_WAKER_VTABLE)
83+
}
84+
fn dummy_waker_action(_: *const ()) {}
85+
86+
const DUMMY_WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new(
87+
dummy_waker_clone,
88+
dummy_waker_action,
89+
dummy_waker_action,
90+
dummy_waker_action,
91+
);
92+
93+
pub(crate) fn dummy_waker() -> Waker {
94+
unsafe { Waker::from_raw(RawWaker::new(core::ptr::null(), &DUMMY_WAKER_VTABLE)) }
95+
}

0 commit comments

Comments
 (0)