Make `confirmables` `Deref`
[rust-lightning] / lightning-transaction-sync / src / esplora.rs
index eb52faf33648cfb173985b13c29ecb9d754fdb87..82c49b9f9d2e8dfda23ea941ae41f5d5e3ebf943 100644 (file)
@@ -51,7 +51,7 @@ where
        pub fn new(server_url: String, logger: L) -> Self {
                let builder = Builder::new(&server_url);
                #[cfg(not(feature = "async-interface"))]
-               let client = builder.build_blocking().unwrap();
+               let client = builder.build_blocking();
                #[cfg(feature = "async-interface")]
                let client = builder.build_async().unwrap();
 
@@ -59,6 +59,8 @@ where
        }
 
        /// Returns a new [`EsploraSyncClient`] object using the given Esplora client.
+       ///
+       /// This is not exported to bindings users as the underlying client from BDK is not exported.
        pub fn from_client(client: EsploraClientType, logger: L) -> Self {
                let sync_state = MutexType::new(SyncState::new());
                let queue = std::sync::Mutex::new(FilterQueue::new());
@@ -82,7 +84,9 @@ where
        /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
        /// [`Filter`]: lightning::chain::Filter
        #[maybe_async]
-       pub fn sync(&self, confirmables: Vec<&(dyn Confirm + Sync + Send)>) -> Result<(), TxSyncError> {
+       pub fn sync<C: Deref>(&self, confirmables: Vec<C>) -> Result<(), TxSyncError>
+               where C::Target: Confirm
+       {
                // This lock makes sure we're syncing once at a time.
                #[cfg(not(feature = "async-interface"))]
                let mut sync_state = self.sync_state.lock().unwrap();
@@ -153,7 +157,7 @@ where
                                                }
                                        }
 
-                                       match maybe_await!(self.sync_best_block_updated(&confirmables, &tip_hash)) {
+                                       match maybe_await!(self.sync_best_block_updated(&confirmables, &mut sync_state, &tip_hash)) {
                                                Ok(()) => {}
                                                Err(InternalError::Inconsistency) => {
                                                        // Immediately restart syncing when we encounter any inconsistencies.
@@ -237,10 +241,11 @@ where
        }
 
        #[maybe_async]
-       fn sync_best_block_updated(
-               &self, confirmables: &Vec<&(dyn Confirm + Sync + Send)>, tip_hash: &BlockHash,
-       ) -> Result<(), InternalError> {
-
+       fn sync_best_block_updated<C: Deref>(
+               &self, confirmables: &Vec<C>, sync_state: &mut SyncState, tip_hash: &BlockHash,
+       ) -> Result<(), InternalError>
+               where C::Target: Confirm
+       {
                // Inform the interface of the new block.
                let tip_header = maybe_await!(self.client.get_header_by_hash(tip_hash))?;
                let tip_status = maybe_await!(self.client.get_block_status(&tip_hash))?;
@@ -249,6 +254,9 @@ where
                                for c in confirmables {
                                        c.best_block_updated(&tip_header, tip_height);
                                }
+
+                               // Prune any sufficiently confirmed output spends
+                               sync_state.prune_output_spends(tip_height);
                        }
                } else {
                        return Err(InternalError::Inconsistency);
@@ -264,10 +272,13 @@ where
                // First, check the confirmation status of registered transactions as well as the
                // status of dependent transactions of registered outputs.
 
-               let mut confirmed_txs = Vec::new();
+               let mut confirmed_txs: Vec<ConfirmedTx> = Vec::new();
 
                for txid in &sync_state.watched_transactions {
-                       if let Some(confirmed_tx) = maybe_await!(self.get_confirmed_tx(&txid, None, None))? {
+                       if confirmed_txs.iter().any(|ctx| ctx.txid == *txid) {
+                               continue;
+                       }
+                       if let Some(confirmed_tx) = maybe_await!(self.get_confirmed_tx(*txid, None, None))? {
                                confirmed_txs.push(confirmed_tx);
                        }
                }
@@ -278,9 +289,19 @@ where
                        {
                                if let Some(spending_txid) = output_status.txid {
                                        if let Some(spending_tx_status) = output_status.status {
+                                               if confirmed_txs.iter().any(|ctx| ctx.txid == spending_txid) {
+                                                       if spending_tx_status.confirmed {
+                                                               // Skip inserting duplicate ConfirmedTx entry
+                                                               continue;
+                                                       } else {
+                                                               log_trace!(self.logger, "Inconsistency: Detected previously-confirmed Tx {} as unconfirmed", spending_txid);
+                                                               return Err(InternalError::Inconsistency);
+                                                       }
+                                               }
+
                                                if let Some(confirmed_tx) = maybe_await!(self
                                                        .get_confirmed_tx(
-                                                               &spending_txid,
+                                                               spending_txid,
                                                                spending_tx_status.block_hash,
                                                                spending_tx_status.block_height,
                                                        ))?
@@ -303,7 +324,7 @@ where
 
        #[maybe_async]
        fn get_confirmed_tx(
-               &self, txid: &Txid, expected_block_hash: Option<BlockHash>, known_block_height: Option<u32>,
+               &self, txid: Txid, expected_block_hash: Option<BlockHash>, known_block_height: Option<u32>,
        ) -> Result<Option<ConfirmedTx>, InternalError> {
                if let Some(merkle_block) = maybe_await!(self.client.get_merkle_block(&txid))? {
                        let block_header = merkle_block.header;
@@ -318,7 +339,7 @@ where
                        let mut matches = Vec::new();
                        let mut indexes = Vec::new();
                        let _ = merkle_block.txn.extract_matches(&mut matches, &mut indexes);
-                       if indexes.len() != 1 || matches.len() != 1 || matches[0] != *txid {
+                       if indexes.len() != 1 || matches.len() != 1 || matches[0] != txid {
                                log_error!(self.logger, "Retrieved Merkle block for txid {} doesn't match expectations. This should not happen. Please verify server integrity.", txid);
                                return Err(InternalError::Failed);
                        }
@@ -326,14 +347,19 @@ where
                        // unwrap() safety: len() > 0 is checked above
                        let pos = *indexes.first().unwrap() as usize;
                        if let Some(tx) = maybe_await!(self.client.get_tx(&txid))? {
+                               if tx.txid() != txid {
+                                       log_error!(self.logger, "Retrieved transaction for txid {} doesn't match expectations. This should not happen. Please verify server integrity.", txid);
+                                       return Err(InternalError::Failed);
+                               }
+
                                if let Some(block_height) = known_block_height {
                                        // We can take a shortcut here if a previous call already gave us the height.
-                                       return Ok(Some(ConfirmedTx { tx, block_header, pos, block_height }));
+                                       return Ok(Some(ConfirmedTx { tx, txid, block_header, pos, block_height }));
                                }
 
                                let block_status = maybe_await!(self.client.get_block_status(&block_hash))?;
                                if let Some(block_height) = block_status.height {
-                                       return Ok(Some(ConfirmedTx { tx, block_header, pos, block_height }));
+                                       return Ok(Some(ConfirmedTx { tx, txid, block_header, pos, block_height }));
                                } else {
                                        // If any previously-confirmed block suddenly is no longer confirmed, we found
                                        // an inconsistency and should start over.
@@ -346,9 +372,11 @@ where
        }
 
        #[maybe_async]
-       fn get_unconfirmed_transactions(
-               &self, confirmables: &Vec<&(dyn Confirm + Sync + Send)>,
-       ) -> Result<Vec<Txid>, InternalError> {
+       fn get_unconfirmed_transactions<C: Deref>(
+               &self, confirmables: &Vec<C>,
+       ) -> Result<Vec<Txid>, InternalError>
+               where C::Target: Confirm
+       {
                // Query the interface for relevant txids and check whether the relevant blocks are still
                // in the best chain, mark them unconfirmed otherwise
                let relevant_txids = confirmables
@@ -376,6 +404,8 @@ where
        }
 
        /// Returns a reference to the underlying esplora client.
+       ///
+       /// This is not exported to bindings users as the underlying client from BDK is not exported.
        pub fn client(&self) -> &EsploraClientType {
                &self.client
        }