Merge pull request #401 from ariard/2019-11-log-tx-broadcast
[rust-lightning] / lightning / src / ln / channelmonitor.rs
index 5bcd74f76f10108832922ad00d8cb93ea795357a..d619edcbcd98f7fd8a6c6c1c1e6c7f51a2f37194 100644 (file)
@@ -109,6 +109,12 @@ pub struct HTLCUpdate {
 /// channel's monitor everywhere (including remote watchtowers) *before* this function returns. If
 /// an update occurs and a remote watchtower is left with old state, it may broadcast transactions
 /// which we have revoked, allowing our counterparty to claim all funds in the channel!
+///
+/// User needs to notify implementors of ManyChannelMonitor when a new block is connected or
+/// disconnected using their `block_connected` and `block_disconnected` methods. However, rather
+/// than calling these methods directly, the user should register implementors as listeners to the
+/// BlockNotifier and call the BlockNotifier's `block_(dis)connected` methods, which will notify
+/// all registered listeners in one go.
 pub trait ManyChannelMonitor: Send + Sync {
        /// Adds or updates a monitor for the given `funding_txo`.
        ///
@@ -146,7 +152,8 @@ pub struct SimpleManyChannelMonitor<Key> {
        fee_estimator: Arc<FeeEstimator>
 }
 
-impl<Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonitor<Key> {
+impl<'a, Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonitor<Key> {
+
        fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], _indexes_of_txn_matched: &[u32]) {
                let block_hash = header.bitcoin_hash();
                let mut new_events: Vec<events::Event> = Vec::with_capacity(0);
@@ -223,8 +230,7 @@ impl<Key : Send + cmp::Eq + hash::Hash + 'static> SimpleManyChannelMonitor<Key>
                        logger,
                        fee_estimator: feeest,
                });
-               let weak_res = Arc::downgrade(&res);
-               res.chain_monitor.register_listener(weak_res);
+
                res
        }
 
@@ -1643,46 +1649,48 @@ impl ChannelMonitor {
                                                                return (txn_to_broadcast, (commitment_txid, watch_outputs), spendable_outputs); // Corrupted per_commitment_data, fuck this user
                                                        }
                                                        if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
-                                                               let input = TxIn {
-                                                                       previous_output: BitcoinOutPoint {
-                                                                               txid: commitment_txid,
-                                                                               vout: transaction_output_index,
-                                                                       },
-                                                                       script_sig: Script::new(),
-                                                                       sequence: idx as u32, // reset to 0xfffffffd in sign_input
-                                                                       witness: Vec::new(),
-                                                               };
-                                                               if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
-                                                                       inputs.push(input);
-                                                                       inputs_desc.push(if htlc.offered { InputDescriptors::OfferedHTLC } else { InputDescriptors::ReceivedHTLC });
-                                                                       inputs_info.push((payment_preimage, tx.output[transaction_output_index as usize].value, htlc.cltv_expiry));
-                                                                       total_value += tx.output[transaction_output_index as usize].value;
-                                                               } else {
-                                                                       let mut single_htlc_tx = Transaction {
-                                                                               version: 2,
-                                                                               lock_time: 0,
-                                                                               input: vec![input],
-                                                                               output: vec!(TxOut {
-                                                                                       script_pubkey: self.destination_script.clone(),
-                                                                                       value: htlc.amount_msat / 1000,
-                                                                               }),
+                                                               if htlc.offered {
+                                                                       let input = TxIn {
+                                                                               previous_output: BitcoinOutPoint {
+                                                                                       txid: commitment_txid,
+                                                                                       vout: transaction_output_index,
+                                                                               },
+                                                                               script_sig: Script::new(),
+                                                                               sequence: idx as u32, // reset to 0xfffffffd in sign_input
+                                                                               witness: Vec::new(),
                                                                        };
-                                                                       let predicted_weight = single_htlc_tx.get_weight() + Self::get_witnesses_weight(&[if htlc.offered { InputDescriptors::OfferedHTLC } else { InputDescriptors::ReceivedHTLC }]);
-                                                                       let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
-                                                                       let mut used_feerate;
-                                                                       if subtract_high_prio_fee!(self, fee_estimator, single_htlc_tx.output[0].value, predicted_weight, tx.txid(), used_feerate) {
-                                                                               let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
-                                                                               let (redeemscript, htlc_key) = sign_input!(sighash_parts, single_htlc_tx.input[0], htlc.amount_msat / 1000, payment_preimage.0.to_vec());
-                                                                               assert!(predicted_weight >= single_htlc_tx.get_weight());
-                                                                               spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
-                                                                                       outpoint: BitcoinOutPoint { txid: single_htlc_tx.txid(), vout: 0 },
-                                                                                       output: single_htlc_tx.output[0].clone(),
-                                                                               });
-                                                                               match self.our_claim_txn_waiting_first_conf.entry(single_htlc_tx.input[0].previous_output.clone()) {
-                                                                                       hash_map::Entry::Occupied(_) => {},
-                                                                                       hash_map::Entry::Vacant(entry) => { entry.insert((height_timer, TxMaterial::RemoteHTLC { script: redeemscript, key: htlc_key, preimage: Some(*payment_preimage), amount: htlc.amount_msat / 1000 }, used_feerate, htlc.cltv_expiry, height)); }
+                                                                       if htlc.cltv_expiry > height + CLTV_SHARED_CLAIM_BUFFER {
+                                                                               inputs.push(input);
+                                                                               inputs_desc.push(if htlc.offered { InputDescriptors::OfferedHTLC } else { InputDescriptors::ReceivedHTLC });
+                                                                               inputs_info.push((payment_preimage, tx.output[transaction_output_index as usize].value, htlc.cltv_expiry));
+                                                                               total_value += tx.output[transaction_output_index as usize].value;
+                                                                       } else {
+                                                                               let mut single_htlc_tx = Transaction {
+                                                                                       version: 2,
+                                                                                       lock_time: 0,
+                                                                                       input: vec![input],
+                                                                                       output: vec!(TxOut {
+                                                                                               script_pubkey: self.destination_script.clone(),
+                                                                                               value: htlc.amount_msat / 1000,
+                                                                                       }),
+                                                                               };
+                                                                               let predicted_weight = single_htlc_tx.get_weight() + Self::get_witnesses_weight(&[if htlc.offered { InputDescriptors::OfferedHTLC } else { InputDescriptors::ReceivedHTLC }]);
+                                                                               let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
+                                                                               let mut used_feerate;
+                                                                               if subtract_high_prio_fee!(self, fee_estimator, single_htlc_tx.output[0].value, predicted_weight, tx.txid(), used_feerate) {
+                                                                                       let sighash_parts = bip143::SighashComponents::new(&single_htlc_tx);
+                                                                                       let (redeemscript, htlc_key) = sign_input!(sighash_parts, single_htlc_tx.input[0], htlc.amount_msat / 1000, payment_preimage.0.to_vec());
+                                                                                       assert!(predicted_weight >= single_htlc_tx.get_weight());
+                                                                                       spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
+                                                                                               outpoint: BitcoinOutPoint { txid: single_htlc_tx.txid(), vout: 0 },
+                                                                                               output: single_htlc_tx.output[0].clone(),
+                                                                                       });
+                                                                                       match self.our_claim_txn_waiting_first_conf.entry(single_htlc_tx.input[0].previous_output.clone()) {
+                                                                                               hash_map::Entry::Occupied(_) => {},
+                                                                                               hash_map::Entry::Vacant(entry) => { entry.insert((height_timer, TxMaterial::RemoteHTLC { script: redeemscript, key: htlc_key, preimage: Some(*payment_preimage), amount: htlc.amount_msat / 1000 }, used_feerate, htlc.cltv_expiry, height)); }
+                                                                                       }
+                                                                                       txn_to_broadcast.push(single_htlc_tx);
                                                                                }
-                                                                               txn_to_broadcast.push(single_htlc_tx);
                                                                        }
                                                                }
                                                        }
@@ -1738,7 +1746,7 @@ impl ChannelMonitor {
                                                output: outputs,
                                        };
 
-                                       let mut predicted_weight = spend_tx.get_weight() + Self::get_witnesses_weight(&inputs_desc[..]);
+                                       let predicted_weight = spend_tx.get_weight() + Self::get_witnesses_weight(&inputs_desc[..]);
 
                                        let mut used_feerate;
                                        if !subtract_high_prio_fee!(self, fee_estimator, spend_tx.output[0].value, predicted_weight, tx.txid(), used_feerate) {
@@ -2136,14 +2144,14 @@ impl ChannelMonitor {
                                };
                                if funding_txo.is_none() || (prevout.txid == funding_txo.as_ref().unwrap().0.txid && prevout.vout == funding_txo.as_ref().unwrap().0.index as u32) {
                                        if (tx.input[0].sequence >> 8*3) as u8 == 0x80 && (tx.lock_time >> 8*3) as u8 == 0x20 {
-                                               let (remote_txn, new_outputs, mut spendable_output) = self.check_spend_remote_transaction(tx, height, fee_estimator);
+                                               let (remote_txn, new_outputs, mut spendable_output) = self.check_spend_remote_transaction(&tx, height, fee_estimator);
                                                txn = remote_txn;
                                                spendable_outputs.append(&mut spendable_output);
                                                if !new_outputs.1.is_empty() {
                                                        watch_outputs.push(new_outputs);
                                                }
                                                if txn.is_empty() {
-                                                       let (local_txn, mut spendable_output, new_outputs) = self.check_spend_local_transaction(tx, height);
+                                                       let (local_txn, mut spendable_output, new_outputs) = self.check_spend_local_transaction(&tx, height);
                                                        spendable_outputs.append(&mut spendable_output);
                                                        txn = local_txn;
                                                        if !new_outputs.1.is_empty() {
@@ -2152,13 +2160,13 @@ impl ChannelMonitor {
                                                }
                                        }
                                        if !funding_txo.is_none() && txn.is_empty() {
-                                               if let Some(spendable_output) = self.check_spend_closing_transaction(tx) {
+                                               if let Some(spendable_output) = self.check_spend_closing_transaction(&tx) {
                                                        spendable_outputs.push(spendable_output);
                                                }
                                        }
                                } else {
                                        if let Some(&(commitment_number, _)) = self.remote_commitment_txn_on_chain.get(&prevout.txid) {
-                                               let (tx, spendable_output) = self.check_spend_remote_htlc(tx, commitment_number, height, fee_estimator);
+                                               let (tx, spendable_output) = self.check_spend_remote_htlc(&tx, commitment_number, height, fee_estimator);
                                                if let Some(tx) = tx {
                                                        txn.push(tx);
                                                }
@@ -2168,13 +2176,14 @@ impl ChannelMonitor {
                                        }
                                }
                                for tx in txn.iter() {
+                                       log_trace!(self, "Broadcast onchain {}", log_tx!(tx));
                                        broadcaster.broadcast_transaction(tx);
                                }
                        }
                        // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
                        // can also be resolved in a few other ways which can have more than one output. Thus,
                        // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
-                       let mut updated = self.is_resolving_htlc_output(tx, height);
+                       let mut updated = self.is_resolving_htlc_output(&tx, height);
                        if updated.len() > 0 {
                                htlc_updated.append(&mut updated);
                        }
@@ -2203,6 +2212,7 @@ impl ChannelMonitor {
                let mut pending_claims = Vec::new();
                if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
                        if self.would_broadcast_at_height(height) {
+                               log_trace!(self, "Broadcast onchain {}", log_tx!(cur_local_tx.tx));
                                broadcaster.broadcast_transaction(&cur_local_tx.tx);
                                match self.key_storage {
                                        Storage::Local { ref delayed_payment_base_key, ref latest_per_commitment_point, .. } => {
@@ -2213,6 +2223,7 @@ impl ChannelMonitor {
                                                        watch_outputs.push((cur_local_tx.txid.clone(), new_outputs));
                                                }
                                                for tx in txs {
+                                                       log_trace!(self, "Broadcast onchain {}", log_tx!(tx));
                                                        broadcaster.broadcast_transaction(&tx);
                                                }
                                        },
@@ -2224,6 +2235,7 @@ impl ChannelMonitor {
                                                        watch_outputs.push((cur_local_tx.txid.clone(), new_outputs));
                                                }
                                                for tx in txs {
+                                                       log_trace!(self, "Broadcast onchain {}", log_tx!(tx));
                                                        broadcaster.broadcast_transaction(&tx);
                                                }
                                        }