Correctly update the last block hash on disconnect
[rust-lightning] / lightning / src / chain / channelmonitor.rs
index a997694722f4c908e7c9f61698363617310ebc5f..2352661271f46d8f48bb35703b6e1579951381dd 100644 (file)
@@ -50,7 +50,6 @@ use util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, U48};
 use util::byte_utils;
 use util::events::Event;
 
-use std::cell::RefCell;
 use std::collections::{HashMap, HashSet, hash_map};
 use std::{cmp, mem};
 use std::io::Error;
@@ -621,7 +620,7 @@ impl Readable for ChannelMonitorUpdateStep {
 /// reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
 /// gotten are fully handled before re-serializing the new state.
 ///
-/// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
+/// Note that the deserializer is only implemented for (BlockHash, ChannelMonitor), which
 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
 /// the "reorg path" (ie disconnecting blocks until you find a common ancestor from both the
 /// returned block hash and the the current chain and then reconnecting blocks to get to the
@@ -981,7 +980,8 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
                          channel_parameters: &ChannelTransactionParameters,
                          funding_redeemscript: Script, channel_value_satoshis: u64,
                          commitment_transaction_number_obscure_factor: u64,
-                         initial_holder_commitment_tx: HolderCommitmentTransaction) -> ChannelMonitor<Signer> {
+                         initial_holder_commitment_tx: HolderCommitmentTransaction,
+                         last_block_hash: BlockHash) -> ChannelMonitor<Signer> {
 
                assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
                let our_channel_close_key_hash = WPubkeyHash::hash(&shutdown_pubkey.serialize());
@@ -1068,7 +1068,7 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
                                lockdown_from_offchain: false,
                                holder_tx_signed: false,
 
-                               last_block_hash: Default::default(),
+                               last_block_hash,
                                secp_ctx,
                        }),
                }
@@ -2090,8 +2090,7 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
                      F::Target: FeeEstimator,
                      L::Target: Logger,
        {
-               let block_hash = header.block_hash();
-               log_trace!(logger, "Block {} at height {} disconnected", block_hash, height);
+               log_trace!(logger, "Block {} at height {} disconnected", header.block_hash(), height);
 
                if let Some(_) = self.onchain_events_waiting_threshold_conf.remove(&(height + ANTI_REORG_DELAY - 1)) {
                        //We may discard:
@@ -2101,7 +2100,7 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
 
                self.onchain_tx_handler.block_disconnected(height, broadcaster, fee_estimator, logger);
 
-               self.last_block_hash = block_hash;
+               self.last_block_hash = header.prev_blockhash;
        }
 
        /// Filters a block's `txdata` for transactions spending watched outputs or for any child
@@ -2474,7 +2473,7 @@ pub trait Persist<ChannelSigner: Sign>: Send + Sync {
        fn update_persisted_channel(&self, id: OutPoint, update: &ChannelMonitorUpdate, data: &ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr>;
 }
 
-impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Listen for (RefCell<ChannelMonitor<Signer>>, T, F, L)
+impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Listen for (ChannelMonitor<Signer>, T, F, L)
 where
        T::Target: BroadcasterInterface,
        F::Target: FeeEstimator,
@@ -2482,11 +2481,11 @@ where
 {
        fn block_connected(&self, block: &Block, height: u32) {
                let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
-               self.0.borrow_mut().block_connected(&block.header, &txdata, height, &*self.1, &*self.2, &*self.3);
+               self.0.block_connected(&block.header, &txdata, height, &*self.1, &*self.2, &*self.3);
        }
 
        fn block_disconnected(&self, header: &BlockHeader, height: u32) {
-               self.0.borrow_mut().block_disconnected(header, height, &*self.1, &*self.2, &*self.3);
+               self.0.block_disconnected(header, height, &*self.1, &*self.2, &*self.3);
        }
 }
 
@@ -2790,6 +2789,7 @@ impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
 
 #[cfg(test)]
 mod tests {
+       use bitcoin::blockdata::constants::genesis_block;
        use bitcoin::blockdata::script::{Script, Builder};
        use bitcoin::blockdata::opcodes;
        use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, SigHashType};
@@ -2799,6 +2799,7 @@ mod tests {
        use bitcoin::hashes::sha256::Hash as Sha256;
        use bitcoin::hashes::hex::FromHex;
        use bitcoin::hash_types::Txid;
+       use bitcoin::network::constants::Network;
        use hex;
        use chain::channelmonitor::ChannelMonitor;
        use chain::transaction::OutPoint;
@@ -2898,12 +2899,13 @@ mod tests {
                };
                // Prune with one old state and a holder commitment tx holding a few overlaps with the
                // old state.
+               let last_block_hash = genesis_block(Network::Testnet).block_hash();
                let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
                                                  &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0, &Script::new(),
                                                  (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, Script::new()),
                                                  &channel_parameters,
                                                  Script::new(), 46, 0,
-                                                 HolderCommitmentTransaction::dummy());
+                                                 HolderCommitmentTransaction::dummy(), last_block_hash);
 
                monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..10])).unwrap();
                let dummy_txid = dummy_tx.txid();