2a168a7d9235bbf4af012857ef36273863dd3b80
[ldk-sample] / src / sweep.rs
1 use std::io::{Read, Seek, SeekFrom};
2 use std::path::PathBuf;
3 use std::sync::Arc;
4 use std::time::Duration;
5 use std::{fs, io};
6
7 use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
8 use lightning::chain::keysinterface::{EntropySource, KeysManager, SpendableOutputDescriptor};
9 use lightning::util::logger::Logger;
10 use lightning::util::persist::KVStorePersister;
11 use lightning::util::ser::{Readable, WithoutLength};
12
13 use bitcoin::secp256k1::Secp256k1;
14
15 use crate::hex_utils;
16 use crate::BitcoindClient;
17 use crate::FilesystemLogger;
18 use crate::FilesystemPersister;
19
20 /// If we have any pending claimable outputs, we should slowly sweep them to our Bitcoin Core
21 /// wallet. We technically don't need to do this - they're ours to spend when we want and can just
22 /// use them to build new transactions instead, but we cannot feed them direclty into Bitcoin
23 /// Core's wallet so we have to sweep.
24 ///
25 /// Note that this is unececssary for [`SpendableOutputDescriptor::StaticOutput`]s, which *do* have
26 /// an associated secret key we could simply import into Bitcoin Core's wallet, but for consistency
27 /// we don't do that here either.
28 pub(crate) async fn periodic_sweep(
29         ldk_data_dir: String, keys_manager: Arc<KeysManager>, logger: Arc<FilesystemLogger>,
30         persister: Arc<FilesystemPersister>, bitcoind_client: Arc<BitcoindClient>,
31 ) {
32         // Regularly claim outputs which are exclusively spendable by us and send them to Bitcoin Core.
33         // Note that if you more tightly integrate your wallet with LDK you may not need to do this -
34         // these outputs can just be treated as normal outputs during coin selection.
35         let pending_spendables_dir =
36                 format!("{}/{}", crate::PENDING_SPENDABLE_OUTPUT_DIR, ldk_data_dir);
37         let processing_spendables_dir = format!("{}/processing_spendable_outputs", ldk_data_dir);
38         let spendables_dir = format!("{}/spendable_outputs", ldk_data_dir);
39
40         // We batch together claims of all spendable outputs generated each day, however only after
41         // batching any claims of spendable outputs which were generated prior to restart. On a mobile
42         // device we likely won't ever be online for more than a minute, so we have to ensure we sweep
43         // any pending claims on startup, but for an always-online node you may wish to sweep even less
44         // frequently than this (or move the interval await to the top of the loop)!
45         //
46         // There is no particular rush here, we just have to ensure funds are availably by the time we
47         // need to send funds.
48         let mut interval = tokio::time::interval(Duration::from_secs(60 * 60 * 24));
49
50         loop {
51                 interval.tick().await; // Note that the first tick completes immediately
52                 if let Ok(dir_iter) = fs::read_dir(&pending_spendables_dir) {
53                         // Move any spendable descriptors from pending folder so that we don't have any
54                         // races with new files being added.
55                         for file_res in dir_iter {
56                                 let file = file_res.unwrap();
57                                 // Only move a file if its a 32-byte-hex'd filename, otherwise it might be a
58                                 // temporary file.
59                                 if file.file_name().len() == 64 {
60                                         fs::create_dir_all(&processing_spendables_dir).unwrap();
61                                         let mut holding_path = PathBuf::new();
62                                         holding_path.push(&processing_spendables_dir);
63                                         holding_path.push(&file.file_name());
64                                         fs::rename(file.path(), holding_path).unwrap();
65                                 }
66                         }
67                         // Now concatenate all the pending files we moved into one file in the
68                         // `spendable_outputs` directory and drop the processing directory.
69                         let mut outputs = Vec::new();
70                         if let Ok(processing_iter) = fs::read_dir(&processing_spendables_dir) {
71                                 for file_res in processing_iter {
72                                         outputs.append(&mut fs::read(file_res.unwrap().path()).unwrap());
73                                 }
74                         }
75                         if !outputs.is_empty() {
76                                 let key = hex_utils::hex_str(&keys_manager.get_secure_random_bytes());
77                                 persister
78                                         .persist(&format!("spendable_outputs/{}", key), &WithoutLength(&outputs))
79                                         .unwrap();
80                                 fs::remove_dir_all(&processing_spendables_dir).unwrap();
81                         }
82                 }
83                 // Iterate over all the sets of spendable outputs in `spendables_dir` and try to claim
84                 // them.
85                 // Note that here we try to claim each set of spendable outputs over and over again
86                 // forever, even long after its been claimed. While this isn't an issue per se, in practice
87                 // you may wish to track when the claiming transaction has confirmed and remove the
88                 // spendable outputs set. You may also wish to merge groups of unspent spendable outputs to
89                 // combine batches.
90                 if let Ok(dir_iter) = fs::read_dir(&spendables_dir) {
91                         for file_res in dir_iter {
92                                 let mut outputs: Vec<SpendableOutputDescriptor> = Vec::new();
93                                 let mut file = fs::File::open(file_res.unwrap().path()).unwrap();
94                                 loop {
95                                         // Check if there are any bytes left to read, and if so read a descriptor.
96                                         match file.read_exact(&mut [0; 1]) {
97                                                 Ok(_) => {
98                                                         file.seek(SeekFrom::Current(-1)).unwrap();
99                                                 }
100                                                 Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => break,
101                                                 Err(e) => Err(e).unwrap(),
102                                         }
103                                         outputs.push(Readable::read(&mut file).unwrap());
104                                 }
105                                 let destination_address = bitcoind_client.get_new_address().await;
106                                 let output_descriptors = &outputs.iter().map(|a| a).collect::<Vec<_>>();
107                                 let tx_feerate =
108                                         bitcoind_client.get_est_sat_per_1000_weight(ConfirmationTarget::Background);
109                                 if let Ok(spending_tx) = keys_manager.spend_spendable_outputs(
110                                         output_descriptors,
111                                         Vec::new(),
112                                         destination_address.script_pubkey(),
113                                         tx_feerate,
114                                         &Secp256k1::new(),
115                                 ) {
116                                         // Note that, most likely, we've already sweeped this set of outputs
117                                         // and they're already confirmed on-chain, so this broadcast will fail.
118                                         bitcoind_client.broadcast_transaction(&spending_tx);
119                                 } else {
120                                         lightning::log_error!(
121                                                 logger,
122                                                 "Failed to sweep spendable outputs! This may indicate the outputs are dust. Will try again in a day.");
123                                 }
124                         }
125                 }
126         }
127 }