Explicit pass index at HTLC spending transaction signing
[rust-lightning] / lightning / src / ln / channelmonitor.rs
index d1ca6ede5ebaec7c8c172cdad7d727fc21c54504..73cafa9eb580c64274c469ba521a7959887f6333 100644 (file)
@@ -31,9 +31,8 @@ use secp256k1;
 
 use ln::msgs::DecodeError;
 use ln::chan_utils;
-use ln::chan_utils::{HTLCOutputInCommitment, LocalCommitmentTransaction};
+use ln::chan_utils::{HTLCOutputInCommitment, LocalCommitmentTransaction, HTLCType};
 use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash};
-use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT};
 use chain::chaininterface::{ChainListener, ChainWatchInterface, BroadcasterInterface, FeeEstimator, ConfirmationTarget, MIN_RELAY_FEE_SAT_PER_1000_WEIGHT};
 use chain::transaction::OutPoint;
 use chain::keysinterface::SpendableOutputDescriptor;
@@ -153,7 +152,6 @@ pub struct 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);
@@ -220,8 +218,8 @@ impl<'a, Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelM
 impl<Key : Send + cmp::Eq + hash::Hash + 'static> SimpleManyChannelMonitor<Key> {
        /// Creates a new object which can be used to monitor several channels given the chain
        /// interface with which to register to receive notifications.
-       pub fn new(chain_monitor: Arc<ChainWatchInterface>, broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>, feeest: Arc<FeeEstimator>) -> Arc<SimpleManyChannelMonitor<Key>> {
-               let res = Arc::new(SimpleManyChannelMonitor {
+       pub fn new(chain_monitor: Arc<ChainWatchInterface>, broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>, feeest: Arc<FeeEstimator>) -> SimpleManyChannelMonitor<Key> {
+               let res = SimpleManyChannelMonitor {
                        monitors: Mutex::new(HashMap::new()),
                        chain_monitor,
                        broadcaster,
@@ -229,7 +227,7 @@ impl<Key : Send + cmp::Eq + hash::Hash + 'static> SimpleManyChannelMonitor<Key>
                        pending_htlc_updated: Mutex::new(HashMap::new()),
                        logger,
                        fee_estimator: feeest,
-               });
+               };
 
                res
        }
@@ -337,8 +335,6 @@ enum Storage {
                delayed_payment_base_key: SecretKey,
                payment_base_key: SecretKey,
                shutdown_pubkey: PublicKey,
-               prev_latest_per_commitment_point: Option<PublicKey>,
-               latest_per_commitment_point: Option<PublicKey>,
                funding_info: Option<(OutPoint, Script)>,
                current_remote_commitment_txid: Option<Sha256dHash>,
                prev_remote_commitment_txid: Option<Sha256dHash>,
@@ -358,8 +354,9 @@ struct LocalSignedTx {
        a_htlc_key: PublicKey,
        b_htlc_key: PublicKey,
        delayed_payment_key: PublicKey,
+       per_commitment_point: PublicKey,
        feerate_per_kw: u64,
-       htlc_outputs: Vec<(HTLCOutputInCommitment, Option<(Signature, Signature)>, Option<HTLCSource>)>,
+       htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
 }
 
 #[derive(PartialEq)]
@@ -741,8 +738,6 @@ impl ChannelMonitor {
                                delayed_payment_base_key: delayed_payment_base_key.clone(),
                                payment_base_key: payment_base_key.clone(),
                                shutdown_pubkey: shutdown_pubkey.clone(),
-                               prev_latest_per_commitment_point: None,
-                               latest_per_commitment_point: None,
                                funding_info: None,
                                current_remote_commitment_txid: None,
                                prev_remote_commitment_txid: None,
@@ -969,9 +964,7 @@ impl ChannelMonitor {
        /// is important that any clones of this channel monitor (including remote clones) by kept
        /// up-to-date as our local commitment transaction is updated.
        /// Panics if set_their_to_self_delay has never been called.
-       /// Also update Storage with latest local per_commitment_point to derive local_delayedkey in
-       /// case of onchain HTLC tx
-       pub(super) fn provide_latest_local_commitment_tx_info(&mut self, commitment_tx: LocalCommitmentTransaction, local_keys: chan_utils::TxCreationKeys, feerate_per_kw: u64, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<(Signature, Signature)>, Option<HTLCSource>)>) {
+       pub(super) fn provide_latest_local_commitment_tx_info(&mut self, commitment_tx: LocalCommitmentTransaction, local_keys: chan_utils::TxCreationKeys, feerate_per_kw: u64, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>) {
                assert!(self.their_to_self_delay.is_some());
                self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
                self.current_local_signed_commitment_tx = Some(LocalSignedTx {
@@ -981,15 +974,10 @@ impl ChannelMonitor {
                        a_htlc_key: local_keys.a_htlc_key,
                        b_htlc_key: local_keys.b_htlc_key,
                        delayed_payment_key: local_keys.a_delayed_payment_key,
+                       per_commitment_point: local_keys.per_commitment_point,
                        feerate_per_kw,
                        htlc_outputs,
                });
-
-               if let Storage::Local { ref mut latest_per_commitment_point, .. } = self.key_storage {
-                       *latest_per_commitment_point = Some(local_keys.per_commitment_point);
-               } else {
-                       panic!("Channel somehow ended up with its internal ChannelMonitor being in Watchtower mode?");
-               }
        }
 
        /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
@@ -1152,7 +1140,7 @@ impl ChannelMonitor {
                }
 
                match self.key_storage {
-                       Storage::Local { ref funding_key, ref revocation_base_key, ref htlc_base_key, ref delayed_payment_base_key, ref payment_base_key, ref shutdown_pubkey, ref prev_latest_per_commitment_point, ref latest_per_commitment_point, ref funding_info, ref current_remote_commitment_txid, ref prev_remote_commitment_txid } => {
+                       Storage::Local { ref funding_key, ref revocation_base_key, ref htlc_base_key, ref delayed_payment_base_key, ref payment_base_key, ref shutdown_pubkey, ref funding_info, ref current_remote_commitment_txid, ref prev_remote_commitment_txid } => {
                                writer.write_all(&[0; 1])?;
                                writer.write_all(&funding_key[..])?;
                                writer.write_all(&revocation_base_key[..])?;
@@ -1160,8 +1148,6 @@ impl ChannelMonitor {
                                writer.write_all(&delayed_payment_base_key[..])?;
                                writer.write_all(&payment_base_key[..])?;
                                writer.write_all(&shutdown_pubkey.serialize())?;
-                               prev_latest_per_commitment_point.write(writer)?;
-                               latest_per_commitment_point.write(writer)?;
                                match funding_info  {
                                        &Some((ref outpoint, ref script)) => {
                                                writer.write_all(&outpoint.txid[..])?;
@@ -1256,15 +1242,15 @@ impl ChannelMonitor {
                                writer.write_all(&$local_tx.a_htlc_key.serialize())?;
                                writer.write_all(&$local_tx.b_htlc_key.serialize())?;
                                writer.write_all(&$local_tx.delayed_payment_key.serialize())?;
+                               writer.write_all(&$local_tx.per_commitment_point.serialize())?;
 
                                writer.write_all(&byte_utils::be64_to_array($local_tx.feerate_per_kw))?;
                                writer.write_all(&byte_utils::be64_to_array($local_tx.htlc_outputs.len() as u64))?;
-                               for &(ref htlc_output, ref sigs, ref htlc_source) in $local_tx.htlc_outputs.iter() {
+                               for &(ref htlc_output, ref sig, ref htlc_source) in $local_tx.htlc_outputs.iter() {
                                        serialize_htlc_in_commitment!(htlc_output);
-                                       if let &Some((ref their_sig, ref our_sig)) = sigs {
+                                       if let &Some(ref their_sig) = sig {
                                                1u8.write(writer)?;
                                                writer.write_all(&their_sig.serialize_compact())?;
-                                               writer.write_all(&our_sig.serialize_compact())?;
                                        } else {
                                                0u8.write(writer)?;
                                        }
@@ -1785,11 +1771,11 @@ impl ChannelMonitor {
                                        let mut inputs_info = Vec::new();
 
                                        macro_rules! sign_input {
-                                               ($sighash_parts: expr, $input: expr, $amount: expr, $preimage: expr) => {
+                                               ($sighash_parts: expr, $input: expr, $amount: expr, $preimage: expr, $idx: expr) => {
                                                        {
                                                                let (sig, redeemscript, htlc_key) = match self.key_storage {
                                                                        Storage::Local { ref htlc_base_key, .. } => {
-                                                                               let htlc = &per_commitment_option.unwrap()[$input.sequence as usize].0;
+                                                                               let htlc = &per_commitment_option.unwrap()[$idx as usize].0;
                                                                                let redeemscript = chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
                                                                                let sighash = hash_to_message!(&$sighash_parts.sighash_all(&$input, &redeemscript, $amount)[..]);
                                                                                let htlc_key = ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, revocation_point, &htlc_base_key));
@@ -1818,19 +1804,19 @@ impl ChannelMonitor {
                                                        }
                                                        if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
                                                                if htlc.offered {
-                                                                       let input = TxIn {
+                                                                       let mut 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
+                                                                               sequence: 0xff_ff_ff_fd,
                                                                                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));
+                                                                               inputs_info.push((payment_preimage, tx.output[transaction_output_index as usize].value, htlc.cltv_expiry, idx));
                                                                                total_value += tx.output[transaction_output_index as usize].value;
                                                                        } else {
                                                                                let mut single_htlc_tx = Transaction {
@@ -1847,7 +1833,7 @@ impl ChannelMonitor {
                                                                                let mut used_feerate;
                                                                                if subtract_high_prio_fee!(self, fee_estimator, single_htlc_tx.output[0].value, predicted_weight, 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());
+                                                                                       let (redeemscript, htlc_key) = sign_input!(sighash_parts, single_htlc_tx.input[0], htlc.amount_msat / 1000, payment_preimage.0.to_vec(), idx);
                                                                                        assert!(predicted_weight >= single_htlc_tx.get_weight());
                                                                                        spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
                                                                                                outpoint: BitcoinOutPoint { txid: single_htlc_tx.txid(), vout: 0 },
@@ -1878,7 +1864,7 @@ impl ChannelMonitor {
                                                                                vout: transaction_output_index,
                                                                        },
                                                                        script_sig: Script::new(),
-                                                                       sequence: idx as u32,
+                                                                       sequence: 0xff_ff_ff_fd,
                                                                        witness: Vec::new(),
                                                                };
                                                                let mut timeout_tx = Transaction {
@@ -1895,7 +1881,7 @@ impl ChannelMonitor {
                                                                let mut used_feerate;
                                                                if subtract_high_prio_fee!(self, fee_estimator, timeout_tx.output[0].value, predicted_weight, used_feerate) {
                                                                        let sighash_parts = bip143::SighashComponents::new(&timeout_tx);
-                                                                       let (redeemscript, htlc_key) = sign_input!(sighash_parts, timeout_tx.input[0], htlc.amount_msat / 1000, vec![0]);
+                                                                       let (redeemscript, htlc_key) = sign_input!(sighash_parts, timeout_tx.input[0], htlc.amount_msat / 1000, vec![0], idx);
                                                                        assert!(predicted_weight >= timeout_tx.get_weight());
                                                                        //TODO: track SpendableOutputDescriptor
                                                                        log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", timeout_tx.input[0].previous_output.txid, timeout_tx.input[0].previous_output.vout, height_timer);
@@ -1947,7 +1933,7 @@ impl ChannelMonitor {
                                        let height_timer = Self::get_height_timer(height, soonest_timelock);
                                        let spend_txid = spend_tx.txid();
                                        for (input, info) in spend_tx.input.iter_mut().zip(inputs_info.iter()) {
-                                               let (redeemscript, htlc_key) = sign_input!(sighash_parts, input, info.1, (info.0).0.to_vec());
+                                               let (redeemscript, htlc_key) = sign_input!(sighash_parts, input, info.1, (info.0).0.to_vec(), info.3);
                                                log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", input.previous_output.txid, input.previous_output.vout, height_timer);
                                                per_input_material.insert(input.previous_output, InputMaterial::RemoteHTLC { script: redeemscript, key: htlc_key, preimage: Some(*(info.0)), amount: info.1, locktime: 0});
                                                match self.claimable_outpoints.entry(input.previous_output) {
@@ -2071,7 +2057,7 @@ impl ChannelMonitor {
                        assert!(predicted_weight >= spend_tx.get_weight());
                        let outpoint = BitcoinOutPoint { txid: spend_tx.txid(), vout: 0 };
                        let output = spend_tx.output[0].clone();
-                       let height_timer = Self::get_height_timer(height, self.their_to_self_delay.unwrap() as u32); // We can safely unwrap given we are past channel opening
+                       let height_timer = Self::get_height_timer(height, height + self.our_to_self_delay as u32);
                        log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", spend_tx.input[0].previous_output.txid, spend_tx.input[0].previous_output.vout, height_timer);
                        let mut per_input_material = HashMap::with_capacity(1);
                        per_input_material.insert(spend_tx.input[0].previous_output, InputMaterial::Revoked { script: redeemscript, pubkey: None, key: revocation_key, is_htlc: false, amount: tx.output[0].value });
@@ -2087,7 +2073,7 @@ impl ChannelMonitor {
                } else { (None, None) }
        }
 
-       fn broadcast_by_local_state(&self, local_tx: &LocalSignedTx, per_commitment_point: &Option<PublicKey>, delayed_payment_base_key: &Option<SecretKey>, height: u32) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>, Vec<TxOut>, Vec<(Sha256dHash, ClaimTxBumpMaterial)>) {
+       fn broadcast_by_local_state(&self, local_tx: &LocalSignedTx, delayed_payment_base_key: &SecretKey, height: u32) -> (Vec<Transaction>, Vec<SpendableOutputDescriptor>, Vec<TxOut>, Vec<(Sha256dHash, ClaimTxBumpMaterial)>) {
                let mut res = Vec::with_capacity(local_tx.htlc_outputs.len());
                let mut spendable_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
                let mut watch_outputs = Vec::with_capacity(local_tx.htlc_outputs.len());
@@ -2095,18 +2081,14 @@ impl ChannelMonitor {
 
                macro_rules! add_dynamic_output {
                        ($father_tx: expr, $vout: expr) => {
-                               if let Some(ref per_commitment_point) = *per_commitment_point {
-                                       if let Some(ref delayed_payment_base_key) = *delayed_payment_base_key {
-                                               if let Ok(local_delayedkey) = chan_utils::derive_private_key(&self.secp_ctx, per_commitment_point, delayed_payment_base_key) {
-                                                       spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WSH {
-                                                               outpoint: BitcoinOutPoint { txid: $father_tx.txid(), vout: $vout },
-                                                               key: local_delayedkey,
-                                                               witness_script: chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.our_to_self_delay, &local_tx.delayed_payment_key),
-                                                               to_self_delay: self.our_to_self_delay,
-                                                               output: $father_tx.output[$vout as usize].clone(),
-                                                       });
-                                               }
-                                       }
+                               if let Ok(local_delayedkey) = chan_utils::derive_private_key(&self.secp_ctx, &local_tx.per_commitment_point, delayed_payment_base_key) {
+                                       spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WSH {
+                                               outpoint: BitcoinOutPoint { txid: $father_tx.txid(), vout: $vout },
+                                               key: local_delayedkey,
+                                               witness_script: chan_utils::get_revokeable_redeemscript(&local_tx.revocation_key, self.our_to_self_delay, &local_tx.delayed_payment_key),
+                                               to_self_delay: self.our_to_self_delay,
+                                               output: $father_tx.output[$vout as usize].clone(),
+                                       });
                                }
                        }
                }
@@ -2120,60 +2102,50 @@ impl ChannelMonitor {
                        }
                }
 
-               for &(ref htlc, ref sigs, _) in local_tx.htlc_outputs.iter() {
-                       if let Some(transaction_output_index) = htlc.transaction_output_index {
-                               if let &Some((ref their_sig, ref our_sig)) = sigs {
-                                       if htlc.offered {
-                                               log_trace!(self, "Broadcasting HTLC-Timeout transaction against local commitment transactions");
-                                               let mut htlc_timeout_tx = chan_utils::build_htlc_transaction(&local_tx.txid, local_tx.feerate_per_kw, self.their_to_self_delay.unwrap(), htlc, &local_tx.delayed_payment_key, &local_tx.revocation_key);
-
-                                               htlc_timeout_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
-
-                                               htlc_timeout_tx.input[0].witness.push(their_sig.serialize_der().to_vec());
-                                               htlc_timeout_tx.input[0].witness[1].push(SigHashType::All as u8);
-                                               htlc_timeout_tx.input[0].witness.push(our_sig.serialize_der().to_vec());
-                                               htlc_timeout_tx.input[0].witness[2].push(SigHashType::All as u8);
-
-                                               htlc_timeout_tx.input[0].witness.push(Vec::new());
-                                               let htlc_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &local_tx.a_htlc_key, &local_tx.b_htlc_key, &local_tx.revocation_key);
-                                               htlc_timeout_tx.input[0].witness.push(htlc_script.clone().into_bytes());
-
-                                               add_dynamic_output!(htlc_timeout_tx, 0);
-                                               let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
-                                               let mut per_input_material = HashMap::with_capacity(1);
-                                               per_input_material.insert(htlc_timeout_tx.input[0].previous_output, InputMaterial::LocalHTLC { script: htlc_script, sigs: (*their_sig, *our_sig), preimage: None, amount: htlc.amount_msat / 1000});
-                                               //TODO: with option_simplified_commitment track outpoint too
-                                               log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", htlc_timeout_tx.input[0].previous_output.vout, htlc_timeout_tx.input[0].previous_output.txid, height_timer);
-                                               pending_claims.push((htlc_timeout_tx.txid(), ClaimTxBumpMaterial { height_timer, feerate_previous: 0, soonest_timelock: htlc.cltv_expiry, per_input_material }));
-                                               res.push(htlc_timeout_tx);
-                                       } else {
-                                               if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
-                                                       log_trace!(self, "Broadcasting HTLC-Success transaction against local commitment transactions");
-                                                       let mut htlc_success_tx = chan_utils::build_htlc_transaction(&local_tx.txid, local_tx.feerate_per_kw, self.their_to_self_delay.unwrap(), htlc, &local_tx.delayed_payment_key, &local_tx.revocation_key);
-
-                                                       htlc_success_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
-
-                                                       htlc_success_tx.input[0].witness.push(their_sig.serialize_der().to_vec());
-                                                       htlc_success_tx.input[0].witness[1].push(SigHashType::All as u8);
-                                                       htlc_success_tx.input[0].witness.push(our_sig.serialize_der().to_vec());
-                                                       htlc_success_tx.input[0].witness[2].push(SigHashType::All as u8);
-
-                                                       htlc_success_tx.input[0].witness.push(payment_preimage.0.to_vec());
-                                                       let htlc_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(htlc, &local_tx.a_htlc_key, &local_tx.b_htlc_key, &local_tx.revocation_key);
-                                                       htlc_success_tx.input[0].witness.push(htlc_script.clone().into_bytes());
+               if let &Storage::Local { ref htlc_base_key, .. } = &self.key_storage {
+                       for &(ref htlc, ref sigs, _) in local_tx.htlc_outputs.iter() {
+                               if let Some(transaction_output_index) = htlc.transaction_output_index {
+                                       if let &Some(ref their_sig) = sigs {
+                                               if htlc.offered {
+                                                       log_trace!(self, "Broadcasting HTLC-Timeout transaction against local commitment transactions");
+                                                       let mut htlc_timeout_tx = chan_utils::build_htlc_transaction(&local_tx.txid, local_tx.feerate_per_kw, self.their_to_self_delay.unwrap(), htlc, &local_tx.delayed_payment_key, &local_tx.revocation_key);
+                                                       let (our_sig, htlc_script) = match
+                                                                       chan_utils::sign_htlc_transaction(&mut htlc_timeout_tx, their_sig, &None, htlc, &local_tx.a_htlc_key, &local_tx.b_htlc_key, &local_tx.revocation_key, &local_tx.per_commitment_point, htlc_base_key, &self.secp_ctx) {
+                                                               Ok(res) => res,
+                                                               Err(_) => continue,
+                                                       };
 
-                                                       add_dynamic_output!(htlc_success_tx, 0);
+                                                       add_dynamic_output!(htlc_timeout_tx, 0);
                                                        let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
                                                        let mut per_input_material = HashMap::with_capacity(1);
-                                                       per_input_material.insert(htlc_success_tx.input[0].previous_output, InputMaterial::LocalHTLC { script: htlc_script, sigs: (*their_sig, *our_sig), preimage: Some(*payment_preimage), amount: htlc.amount_msat / 1000});
+                                                       per_input_material.insert(htlc_timeout_tx.input[0].previous_output, InputMaterial::LocalHTLC { script: htlc_script, sigs: (*their_sig, our_sig), preimage: None, amount: htlc.amount_msat / 1000});
                                                        //TODO: with option_simplified_commitment track outpoint too
-                                                       log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", htlc_success_tx.input[0].previous_output.vout, htlc_success_tx.input[0].previous_output.txid, height_timer);
-                                                       pending_claims.push((htlc_success_tx.txid(), ClaimTxBumpMaterial { height_timer, feerate_previous: 0, soonest_timelock: htlc.cltv_expiry, per_input_material }));
-                                                       res.push(htlc_success_tx);
+                                                       log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", htlc_timeout_tx.input[0].previous_output.vout, htlc_timeout_tx.input[0].previous_output.txid, height_timer);
+                                                       pending_claims.push((htlc_timeout_tx.txid(), ClaimTxBumpMaterial { height_timer, feerate_previous: 0, soonest_timelock: htlc.cltv_expiry, per_input_material }));
+                                                       res.push(htlc_timeout_tx);
+                                               } else {
+                                                       if let Some(payment_preimage) = self.payment_preimages.get(&htlc.payment_hash) {
+                                                               log_trace!(self, "Broadcasting HTLC-Success transaction against local commitment transactions");
+                                                               let mut htlc_success_tx = chan_utils::build_htlc_transaction(&local_tx.txid, local_tx.feerate_per_kw, self.their_to_self_delay.unwrap(), htlc, &local_tx.delayed_payment_key, &local_tx.revocation_key);
+                                                               let (our_sig, htlc_script) = match
+                                                                               chan_utils::sign_htlc_transaction(&mut htlc_success_tx, their_sig, &Some(*payment_preimage), htlc, &local_tx.a_htlc_key, &local_tx.b_htlc_key, &local_tx.revocation_key, &local_tx.per_commitment_point, htlc_base_key, &self.secp_ctx) {
+                                                                       Ok(res) => res,
+                                                                       Err(_) => continue,
+                                                               };
+
+                                                               add_dynamic_output!(htlc_success_tx, 0);
+                                                               let height_timer = Self::get_height_timer(height, htlc.cltv_expiry);
+                                                               let mut per_input_material = HashMap::with_capacity(1);
+                                                               per_input_material.insert(htlc_success_tx.input[0].previous_output, InputMaterial::LocalHTLC { script: htlc_script, sigs: (*their_sig, our_sig), preimage: Some(*payment_preimage), amount: htlc.amount_msat / 1000});
+                                                               //TODO: with option_simplified_commitment track outpoint too
+                                                               log_trace!(self, "Outpoint {}:{} is being being claimed, if it doesn't succeed, a bumped claiming txn is going to be broadcast at height {}", htlc_success_tx.input[0].previous_output.vout, htlc_success_tx.input[0].previous_output.txid, height_timer);
+                                                               pending_claims.push((htlc_success_tx.txid(), ClaimTxBumpMaterial { height_timer, feerate_previous: 0, soonest_timelock: htlc.cltv_expiry, per_input_material }));
+                                                               res.push(htlc_success_tx);
+                                                       }
                                                }
-                                       }
-                                       watch_outputs.push(local_tx.tx.without_valid_witness().output[transaction_output_index as usize].clone());
-                               } else { panic!("Should have sigs for non-dust local tx outputs!") }
+                                               watch_outputs.push(local_tx.tx.without_valid_witness().output[transaction_output_index as usize].clone());
+                                       } else { panic!("Should have sigs for non-dust local tx outputs!") }
+                               }
                        }
                }
 
@@ -2245,12 +2217,11 @@ impl ChannelMonitor {
                                log_trace!(self, "Got latest local commitment tx broadcast, searching for available HTLCs to claim");
                                assert!(local_tx.tx.has_local_sig());
                                match self.key_storage {
-                                       Storage::Local { ref delayed_payment_base_key, ref latest_per_commitment_point, .. } => {
-                                               append_onchain_update!(self.broadcast_by_local_state(local_tx, latest_per_commitment_point, &Some(*delayed_payment_base_key), height));
+                                       Storage::Local { ref delayed_payment_base_key, .. } => {
+                                               let mut res = self.broadcast_by_local_state(local_tx, delayed_payment_base_key, height);
+                                               append_onchain_update!(res);
                                        },
-                                       Storage::Watchtower { .. } => {
-                                               append_onchain_update!(self.broadcast_by_local_state(local_tx, &None, &None, height));
-                                       }
+                                       Storage::Watchtower { .. } => { }
                                }
                        }
                }
@@ -2270,12 +2241,11 @@ impl ChannelMonitor {
                                log_trace!(self, "Got previous local commitment tx broadcast, searching for available HTLCs to claim");
                                assert!(local_tx.tx.has_local_sig());
                                match self.key_storage {
-                                       Storage::Local { ref delayed_payment_base_key, ref prev_latest_per_commitment_point, .. } => {
-                                               append_onchain_update!(self.broadcast_by_local_state(local_tx, prev_latest_per_commitment_point, &Some(*delayed_payment_base_key), height));
+                                       Storage::Local { ref delayed_payment_base_key, .. } => {
+                                               let mut res = self.broadcast_by_local_state(local_tx, delayed_payment_base_key, height);
+                                               append_onchain_update!(res);
                                        },
-                                       Storage::Watchtower { .. } => {
-                                               append_onchain_update!(self.broadcast_by_local_state(local_tx, &None, &None, height));
-                                       }
+                                       Storage::Watchtower { .. } => { }
                                }
                        }
                }
@@ -2351,8 +2321,8 @@ impl ChannelMonitor {
                if let &Some(ref local_tx) = &self.current_local_signed_commitment_tx {
                        let mut res = vec![local_tx.tx.with_valid_witness().clone()];
                        match self.key_storage {
-                               Storage::Local { ref delayed_payment_base_key, ref prev_latest_per_commitment_point, .. } => {
-                                       res.append(&mut self.broadcast_by_local_state(local_tx, prev_latest_per_commitment_point, &Some(*delayed_payment_base_key), 0).0);
+                               Storage::Local { ref delayed_payment_base_key, .. } => {
+                                       res.append(&mut self.broadcast_by_local_state(local_tx, delayed_payment_base_key, 0).0);
                                        // We throw away the generated waiting_first_conf data as we aren't (yet) confirmed and we don't actually know what the caller wants to do.
                                        // The data will be re-generated and tracked in check_spend_local_transaction if we get a confirmation.
                                },
@@ -2524,8 +2494,8 @@ impl ChannelMonitor {
                                log_trace!(self, "Broadcast onchain {}", log_tx!(cur_local_tx.tx.with_valid_witness()));
                                broadcaster.broadcast_transaction(&cur_local_tx.tx.with_valid_witness());
                                match self.key_storage {
-                                       Storage::Local { ref delayed_payment_base_key, ref latest_per_commitment_point, .. } => {
-                                               let (txs, mut spendable_output, new_outputs, _) = self.broadcast_by_local_state(&cur_local_tx, latest_per_commitment_point, &Some(*delayed_payment_base_key), height);
+                                       Storage::Local { ref delayed_payment_base_key, .. } => {
+                                               let (txs, mut spendable_output, new_outputs, _) = self.broadcast_by_local_state(&cur_local_tx, delayed_payment_base_key, height);
                                                spendable_outputs.append(&mut spendable_output);
                                                if !new_outputs.is_empty() {
                                                        watch_outputs.push((cur_local_tx.txid.clone(), new_outputs));
@@ -2535,17 +2505,7 @@ impl ChannelMonitor {
                                                        broadcaster.broadcast_transaction(&tx);
                                                }
                                        },
-                                       Storage::Watchtower { .. } => {
-                                               let (txs, mut spendable_output, new_outputs, _) = self.broadcast_by_local_state(&cur_local_tx, &None, &None, height);
-                                               spendable_outputs.append(&mut spendable_output);
-                                               if !new_outputs.is_empty() {
-                                                       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);
-                                               }
-                                       }
+                                       Storage::Watchtower { .. } => { },
                                }
                        }
                }
@@ -2596,6 +2556,7 @@ impl ChannelMonitor {
        }
 
        fn block_disconnected(&mut self, height: u32, block_hash: &Sha256dHash, broadcaster: &BroadcasterInterface, fee_estimator: &FeeEstimator) {
+               log_trace!(self, "Block {} at height {} disconnected", block_hash, height);
                let mut bump_candidates = HashMap::new();
                if let Some(events) = self.onchain_events_waiting_threshold_conf.remove(&(height + ANTI_REORG_DELAY - 1)) {
                        //We may discard:
@@ -2716,10 +2677,10 @@ impl ChannelMonitor {
 
                'outer_loop: for input in &tx.input {
                        let mut payment_data = None;
-                       let revocation_sig_claim = (input.witness.len() == 3 && input.witness[2].len() == OFFERED_HTLC_SCRIPT_WEIGHT && input.witness[1].len() == 33)
-                               || (input.witness.len() == 3 && input.witness[2].len() == ACCEPTED_HTLC_SCRIPT_WEIGHT && input.witness[1].len() == 33);
-                       let accepted_preimage_claim = input.witness.len() == 5 && input.witness[4].len() == ACCEPTED_HTLC_SCRIPT_WEIGHT;
-                       let offered_preimage_claim = input.witness.len() == 3 && input.witness[2].len() == OFFERED_HTLC_SCRIPT_WEIGHT;
+                       let revocation_sig_claim = (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC) && input.witness[1].len() == 33)
+                               || (input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::AcceptedHTLC) && input.witness[1].len() == 33);
+                       let accepted_preimage_claim = input.witness.len() == 5 && HTLCType::scriptlen_to_htlctype(input.witness[4].len()) == Some(HTLCType::AcceptedHTLC);
+                       let offered_preimage_claim = input.witness.len() == 3 && HTLCType::scriptlen_to_htlctype(input.witness[2].len()) == Some(HTLCType::OfferedHTLC);
 
                        macro_rules! log_claim {
                                ($tx_info: expr, $local_tx: expr, $htlc: expr, $source_avail: expr) => {
@@ -2910,7 +2871,7 @@ impl ChannelMonitor {
                for per_outp_material in cached_claim_datas.per_input_material.values() {
                        match per_outp_material {
                                &InputMaterial::Revoked { ref script, ref is_htlc, ref amount, .. } => {
-                                       inputs_witnesses_weight += Self::get_witnesses_weight(if !is_htlc { &[InputDescriptors::RevokedOutput] } else if script.len() == OFFERED_HTLC_SCRIPT_WEIGHT { &[InputDescriptors::RevokedOfferedHTLC] } else if script.len() == ACCEPTED_HTLC_SCRIPT_WEIGHT { &[InputDescriptors::RevokedReceivedHTLC] } else { &[] });
+                                       inputs_witnesses_weight += Self::get_witnesses_weight(if !is_htlc { &[InputDescriptors::RevokedOutput] } else if HTLCType::scriptlen_to_htlctype(script.len()) == Some(HTLCType::OfferedHTLC) { &[InputDescriptors::RevokedOfferedHTLC] } else if HTLCType::scriptlen_to_htlctype(script.len()) == Some(HTLCType::AcceptedHTLC) { &[InputDescriptors::RevokedReceivedHTLC] } else { unreachable!() });
                                        amt += *amount;
                                },
                                &InputMaterial::RemoteHTLC { ref preimage, ref amount, .. } => {
@@ -2950,7 +2911,7 @@ impl ChannelMonitor {
                                                bumped_tx.input[i].witness.push(vec!(1));
                                        }
                                        bumped_tx.input[i].witness.push(script.clone().into_bytes());
-                                       log_trace!(self, "Going to broadcast bumped Penalty Transaction {} claiming revoked {} output {} from {} with new feerate {}", bumped_tx.txid(), if !is_htlc { "to_local" } else if script.len() == OFFERED_HTLC_SCRIPT_WEIGHT { "offered" } else if script.len() == ACCEPTED_HTLC_SCRIPT_WEIGHT { "received" } else { "" }, outp.vout, outp.txid, new_feerate);
+                                       log_trace!(self, "Going to broadcast bumped Penalty Transaction {} claiming revoked {} output {} from {} with new feerate {}", bumped_tx.txid(), if !is_htlc { "to_local" } else if HTLCType::scriptlen_to_htlctype(script.len()) == Some(HTLCType::OfferedHTLC) { "offered" } else if HTLCType::scriptlen_to_htlctype(script.len()) == Some(HTLCType::AcceptedHTLC) { "received" } else { "" }, outp.vout, outp.txid, new_feerate);
                                },
                                &InputMaterial::RemoteHTLC { ref script, ref key, ref preimage, ref amount, ref locktime } => {
                                        if !preimage.is_some() { bumped_tx.lock_time = *locktime };
@@ -3010,8 +2971,6 @@ impl<R: ::std::io::Read> ReadableArgs<R, Arc<Logger>> for (Sha256dHash, ChannelM
                                let delayed_payment_base_key = Readable::read(reader)?;
                                let payment_base_key = Readable::read(reader)?;
                                let shutdown_pubkey = Readable::read(reader)?;
-                               let prev_latest_per_commitment_point = Readable::read(reader)?;
-                               let latest_per_commitment_point = Readable::read(reader)?;
                                // Technically this can fail and serialize fail a round-trip, but only for serialization of
                                // barely-init'd ChannelMonitors that we can't do anything with.
                                let outpoint = OutPoint {
@@ -3028,8 +2987,6 @@ impl<R: ::std::io::Read> ReadableArgs<R, Arc<Logger>> for (Sha256dHash, ChannelM
                                        delayed_payment_base_key,
                                        payment_base_key,
                                        shutdown_pubkey,
-                                       prev_latest_per_commitment_point,
-                                       latest_per_commitment_point,
                                        funding_info,
                                        current_remote_commitment_txid,
                                        prev_remote_commitment_txid,
@@ -3130,6 +3087,7 @@ impl<R: ::std::io::Read> ReadableArgs<R, Arc<Logger>> for (Sha256dHash, ChannelM
                                        let a_htlc_key = Readable::read(reader)?;
                                        let b_htlc_key = Readable::read(reader)?;
                                        let delayed_payment_key = Readable::read(reader)?;
+                                       let per_commitment_point = Readable::read(reader)?;
                                        let feerate_per_kw: u64 = Readable::read(reader)?;
 
                                        let htlcs_len: u64 = Readable::read(reader)?;
@@ -3138,7 +3096,7 @@ impl<R: ::std::io::Read> ReadableArgs<R, Arc<Logger>> for (Sha256dHash, ChannelM
                                                let htlc = read_htlc_in_commitment!();
                                                let sigs = match <u8 as Readable<R>>::read(reader)? {
                                                        0 => None,
-                                                       1 => Some((Readable::read(reader)?, Readable::read(reader)?)),
+                                                       1 => Some(Readable::read(reader)?),
                                                        _ => return Err(DecodeError::InvalidValue),
                                                };
                                                htlcs.push((htlc, sigs, Readable::read(reader)?));
@@ -3146,7 +3104,7 @@ impl<R: ::std::io::Read> ReadableArgs<R, Arc<Logger>> for (Sha256dHash, ChannelM
 
                                        LocalSignedTx {
                                                txid: tx.txid(),
-                                               tx, revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, feerate_per_kw,
+                                               tx, revocation_key, a_htlc_key, b_htlc_key, delayed_payment_key, per_commitment_point, feerate_per_kw,
                                                htlc_outputs: htlcs
                                        }
                                }