1 use std::io::{Read, Seek, SeekFrom};
2 use std::path::PathBuf;
4 use std::time::Duration;
7 use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
8 use lightning::sign::{EntropySource, KeysManager, SpendableOutputDescriptor};
9 use lightning::util::logger::Logger;
10 use lightning::util::persist::KVStorePersister;
11 use lightning::util::ser::{Readable, WithoutLength};
13 use bitcoin::secp256k1::Secp256k1;
14 use bitcoin::{LockTime, PackedLockTime};
15 use rand::{thread_rng, Rng};
18 use crate::BitcoindClient;
19 use crate::ChannelManager;
20 use crate::FilesystemLogger;
21 use crate::FilesystemPersister;
23 /// If we have any pending claimable outputs, we should slowly sweep them to our Bitcoin Core
24 /// wallet. We technically don't need to do this - they're ours to spend when we want and can just
25 /// use them to build new transactions instead, but we cannot feed them direclty into Bitcoin
26 /// Core's wallet so we have to sweep.
28 /// Note that this is unececssary for [`SpendableOutputDescriptor::StaticOutput`]s, which *do* have
29 /// an associated secret key we could simply import into Bitcoin Core's wallet, but for consistency
30 /// we don't do that here either.
31 pub(crate) async fn periodic_sweep(
32 ldk_data_dir: String, keys_manager: Arc<KeysManager>, logger: Arc<FilesystemLogger>,
33 persister: Arc<FilesystemPersister>, bitcoind_client: Arc<BitcoindClient>,
34 channel_manager: Arc<ChannelManager>,
36 // Regularly claim outputs which are exclusively spendable by us and send them to Bitcoin Core.
37 // Note that if you more tightly integrate your wallet with LDK you may not need to do this -
38 // these outputs can just be treated as normal outputs during coin selection.
39 let pending_spendables_dir =
40 format!("{}/{}", ldk_data_dir, crate::PENDING_SPENDABLE_OUTPUT_DIR);
41 let processing_spendables_dir = format!("{}/processing_spendable_outputs", ldk_data_dir);
42 let spendables_dir = format!("{}/spendable_outputs", ldk_data_dir);
44 // We batch together claims of all spendable outputs generated each day, however only after
45 // batching any claims of spendable outputs which were generated prior to restart. On a mobile
46 // device we likely won't ever be online for more than a minute, so we have to ensure we sweep
47 // any pending claims on startup, but for an always-online node you may wish to sweep even less
48 // frequently than this (or move the interval await to the top of the loop)!
50 // There is no particular rush here, we just have to ensure funds are availably by the time we
51 // need to send funds.
52 let mut interval = tokio::time::interval(Duration::from_secs(60 * 60 * 24));
55 interval.tick().await; // Note that the first tick completes immediately
56 if let Ok(dir_iter) = fs::read_dir(&pending_spendables_dir) {
57 // Move any spendable descriptors from pending folder so that we don't have any
58 // races with new files being added.
59 for file_res in dir_iter {
60 let file = file_res.unwrap();
61 // Only move a file if its a 32-byte-hex'd filename, otherwise it might be a
63 if file.file_name().len() == 64 {
64 fs::create_dir_all(&processing_spendables_dir).unwrap();
65 let mut holding_path = PathBuf::new();
66 holding_path.push(&processing_spendables_dir);
67 holding_path.push(&file.file_name());
68 fs::rename(file.path(), holding_path).unwrap();
71 // Now concatenate all the pending files we moved into one file in the
72 // `spendable_outputs` directory and drop the processing directory.
73 let mut outputs = Vec::new();
74 if let Ok(processing_iter) = fs::read_dir(&processing_spendables_dir) {
75 for file_res in processing_iter {
76 outputs.append(&mut fs::read(file_res.unwrap().path()).unwrap());
79 if !outputs.is_empty() {
80 let key = hex_utils::hex_str(&keys_manager.get_secure_random_bytes());
82 .persist(&format!("spendable_outputs/{}", key), &WithoutLength(&outputs))
84 fs::remove_dir_all(&processing_spendables_dir).unwrap();
87 // Iterate over all the sets of spendable outputs in `spendables_dir` and try to claim
89 // Note that here we try to claim each set of spendable outputs over and over again
90 // forever, even long after its been claimed. While this isn't an issue per se, in practice
91 // you may wish to track when the claiming transaction has confirmed and remove the
92 // spendable outputs set. You may also wish to merge groups of unspent spendable outputs to
94 if let Ok(dir_iter) = fs::read_dir(&spendables_dir) {
95 for file_res in dir_iter {
96 let mut outputs: Vec<SpendableOutputDescriptor> = Vec::new();
97 let mut file = fs::File::open(file_res.unwrap().path()).unwrap();
99 // Check if there are any bytes left to read, and if so read a descriptor.
100 match file.read_exact(&mut [0; 1]) {
102 file.seek(SeekFrom::Current(-1)).unwrap();
104 Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => break,
105 Err(e) => Err(e).unwrap(),
107 outputs.push(Readable::read(&mut file).unwrap());
109 let destination_address = bitcoind_client.get_new_address().await;
110 let output_descriptors = &outputs.iter().map(|a| a).collect::<Vec<_>>();
112 bitcoind_client.get_est_sat_per_1000_weight(ConfirmationTarget::Background);
114 // We set nLockTime to the current height to discourage fee sniping.
115 // Occasionally randomly pick a nLockTime even further back, so
116 // that transactions that are delayed after signing for whatever reason,
117 // e.g. high-latency mix networks and some CoinJoin implementations, have
119 // Logic copied from core: https://github.com/bitcoin/bitcoin/blob/1d4846a8443be901b8a5deb0e357481af22838d0/src/wallet/spend.cpp#L936
120 let mut cur_height = channel_manager.current_best_block().height();
123 if thread_rng().gen_range(0, 10) == 0 {
124 // subtract random number between 0 and 100
125 cur_height = cur_height.saturating_sub(thread_rng().gen_range(0, 100));
128 let locktime: PackedLockTime =
129 LockTime::from_height(cur_height).map_or(PackedLockTime::ZERO, |l| l.into());
131 if let Ok(spending_tx) = keys_manager.spend_spendable_outputs(
134 destination_address.script_pubkey(),
139 // Note that, most likely, we've already sweeped this set of outputs
140 // and they're already confirmed on-chain, so this broadcast will fail.
141 bitcoind_client.broadcast_transactions(&[&spending_tx]);
143 lightning::log_error!(
145 "Failed to sweep spendable outputs! This may indicate the outputs are dust. Will try again in a day.");