Merge pull request #461 from ariard/2020-remove-duplicata
authorMatt Corallo <649246+TheBlueMatt@users.noreply.github.com>
Wed, 12 Feb 2020 17:38:21 +0000 (17:38 +0000)
committerGitHub <noreply@github.com>
Wed, 12 Feb 2020 17:38:21 +0000 (17:38 +0000)
Remove some duplicata of broadcast txn from ChannelMonitor

1  2 
lightning/src/ln/channelmonitor.rs
lightning/src/ln/functional_tests.rs
lightning/src/util/test_utils.rs

index 51446ccc57162d80fb1a1f56472959ddaa97d803,73cafa9eb580c64274c469ba521a7959887f6333..7d843506e10d4810726bdc3ec20f415d006275cd
@@@ -35,7 -35,7 +35,7 @@@ use ln::chan_utils::{HTLCOutputInCommit
  use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash};
  use chain::chaininterface::{ChainListener, ChainWatchInterface, BroadcasterInterface, FeeEstimator, ConfirmationTarget, MIN_RELAY_FEE_SAT_PER_1000_WEIGHT};
  use chain::transaction::OutPoint;
 -use chain::keysinterface::SpendableOutputDescriptor;
 +use chain::keysinterface::{SpendableOutputDescriptor, ChannelKeys};
  use util::logger::Logger;
  use util::ser::{ReadableArgs, Readable, Writer, Writeable, U48};
  use util::{byte_utils, events};
@@@ -114,13 -114,13 +114,13 @@@ pub struct HTLCUpdate 
  /// 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 {
 +pub trait ManyChannelMonitor<ChanSigner: ChannelKeys>: Send + Sync {
        /// Adds or updates a monitor for the given `funding_txo`.
        ///
        /// Implementor must also ensure that the funding_txo outpoint is registered with any relevant
        /// ChainWatchInterfaces such that the provided monitor receives block_connected callbacks with
        /// any spends of it.
 -      fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr>;
 +      fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr>;
  
        /// Used by ChannelManager to get list of HTLC resolved onchain and which needed to be updated
        /// with success or failure backward
  ///
  /// If you're using this for local monitoring of your own channels, you probably want to use
  /// `OutPoint` as the key, which will give you a ManyChannelMonitor implementation.
 -pub struct SimpleManyChannelMonitor<Key> {
 +pub struct SimpleManyChannelMonitor<Key, ChanSigner: ChannelKeys> {
        #[cfg(test)] // Used in ChannelManager tests to manipulate channels directly
 -      pub monitors: Mutex<HashMap<Key, ChannelMonitor>>,
 +      pub monitors: Mutex<HashMap<Key, ChannelMonitor<ChanSigner>>>,
        #[cfg(not(test))]
 -      monitors: Mutex<HashMap<Key, ChannelMonitor>>,
 +      monitors: Mutex<HashMap<Key, ChannelMonitor<ChanSigner>>>,
        chain_monitor: Arc<ChainWatchInterface>,
        broadcaster: Arc<BroadcasterInterface>,
        pending_events: Mutex<Vec<events::Event>>,
        fee_estimator: Arc<FeeEstimator>
  }
  
 -impl<'a, Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonitor<Key> {
 +impl<'a, Key : Send + cmp::Eq + hash::Hash, ChanSigner: ChannelKeys> ChainListener for SimpleManyChannelMonitor<Key, ChanSigner> {
        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);
        }
  }
  
 -impl<Key : Send + cmp::Eq + hash::Hash + 'static> SimpleManyChannelMonitor<Key> {
 +impl<Key : Send + cmp::Eq + hash::Hash + 'static, ChanSigner: ChannelKeys> SimpleManyChannelMonitor<Key, ChanSigner> {
        /// 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>) -> SimpleManyChannelMonitor<Key> {
 +      pub fn new(chain_monitor: Arc<ChainWatchInterface>, broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>, feeest: Arc<FeeEstimator>) -> SimpleManyChannelMonitor<Key, ChanSigner> {
                let res = SimpleManyChannelMonitor {
                        monitors: Mutex::new(HashMap::new()),
                        chain_monitor,
        }
  
        /// Adds or updates the monitor which monitors the channel referred to by the given key.
 -      pub fn add_update_monitor_by_key(&self, key: Key, monitor: ChannelMonitor) -> Result<(), MonitorUpdateError> {
 +      pub fn add_update_monitor_by_key(&self, key: Key, monitor: ChannelMonitor<ChanSigner>) -> Result<(), MonitorUpdateError> {
                let mut monitors = self.monitors.lock().unwrap();
                match monitors.get_mut(&key) {
                        Some(orig_monitor) => {
        }
  }
  
 -impl ManyChannelMonitor for SimpleManyChannelMonitor<OutPoint> {
 -      fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr> {
 +impl<ChanSigner: ChannelKeys> ManyChannelMonitor<ChanSigner> for SimpleManyChannelMonitor<OutPoint, ChanSigner> {
 +      fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr> {
                match self.add_update_monitor_by_key(funding_txo, monitor) {
                        Ok(_) => Ok(()),
                        Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
        }
  }
  
 -impl<Key : Send + cmp::Eq + hash::Hash> events::EventsProvider for SimpleManyChannelMonitor<Key> {
 +impl<Key : Send + cmp::Eq + hash::Hash, ChanSigner: ChannelKeys> events::EventsProvider for SimpleManyChannelMonitor<Key, ChanSigner> {
        fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
                let mut pending_events = self.pending_events.lock().unwrap();
                let mut ret = Vec::new();
@@@ -326,10 -326,9 +326,10 @@@ pub(crate) const LATENCY_GRACE_PERIOD_B
  /// keeping bumping another claim tx to solve the outpoint.
  pub(crate) const ANTI_REORG_DELAY: u32 = 6;
  
 -#[derive(Clone, PartialEq)]
 -enum Storage {
 +#[derive(Clone)]
 +enum Storage<ChanSigner: ChannelKeys> {
        Local {
 +              keys: ChanSigner,
                funding_key: SecretKey,
                revocation_base_key: SecretKey,
                htlc_base_key: SecretKey,
        }
  }
  
 +#[cfg(any(test, feature = "fuzztarget"))]
 +impl<ChanSigner: ChannelKeys> PartialEq for Storage<ChanSigner> {
 +      fn eq(&self, other: &Self) -> bool {
 +              match *self {
 +                      Storage::Local { ref keys, .. } => {
 +                              let k = keys;
 +                              match *other {
 +                                      Storage::Local { ref keys, .. } => keys.pubkeys() == k.pubkeys(),
 +                                      Storage::Watchtower { .. } => false,
 +                              }
 +                      },
 +                      Storage::Watchtower {ref revocation_base_key, ref htlc_base_key} => {
 +                              let (rbk, hbk) = (revocation_base_key, htlc_base_key);
 +                              match *other {
 +                                      Storage::Local { .. } => false,
 +                                      Storage::Watchtower {ref revocation_base_key, ref htlc_base_key} =>
 +                                              revocation_base_key == rbk && htlc_base_key == hbk,
 +                              }
 +                      },
 +              }
 +      }
 +}
 +
  #[derive(Clone, PartialEq)]
  struct LocalSignedTx {
        /// txid of the transaction in tx, just used to make comparison faster
@@@ -587,10 -563,10 +587,10 @@@ const MIN_SERIALIZATION_VERSION: u8 = 1
  /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
  /// information and are actively monitoring the chain.
  #[derive(Clone)]
 -pub struct ChannelMonitor {
 +pub struct ChannelMonitor<ChanSigner: ChannelKeys> {
        commitment_transaction_number_obscure_factor: u64,
  
 -      key_storage: Storage,
 +      key_storage: Storage<ChanSigner>,
        their_htlc_base_key: Option<PublicKey>,
        their_delayed_payment_base_key: Option<PublicKey>,
        funding_redeemscript: Option<Script>,
@@@ -714,7 -690,7 +714,7 @@@ macro_rules! subtract_high_prio_fee 
  #[cfg(any(test, feature = "fuzztarget"))]
  /// Used only in testing and fuzztarget to check serialization roundtrips don't change the
  /// underlying object
 -impl PartialEq for ChannelMonitor {
 +impl<ChanSigner: ChannelKeys> PartialEq for ChannelMonitor<ChanSigner> {
        fn eq(&self, other: &Self) -> bool {
                if self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
                        self.key_storage != other.key_storage ||
        }
  }
  
 -impl ChannelMonitor {
 -      pub(super) fn new(funding_key: &SecretKey, revocation_base_key: &SecretKey, delayed_payment_base_key: &SecretKey, htlc_base_key: &SecretKey, payment_base_key: &SecretKey, shutdown_pubkey: &PublicKey, our_to_self_delay: u16, destination_script: Script, logger: Arc<Logger>) -> ChannelMonitor {
 +impl<ChanSigner: ChannelKeys + Writeable> ChannelMonitor<ChanSigner> {
 +      /// Serializes into a vec, with various modes for the exposed pub fns
 +      fn write<W: Writer>(&self, writer: &mut W, for_local_storage: bool) -> Result<(), ::std::io::Error> {
 +              //TODO: We still write out all the serialization here manually instead of using the fancy
 +              //serialization framework we have, we should migrate things over to it.
 +              writer.write_all(&[SERIALIZATION_VERSION; 1])?;
 +              writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
 +
 +              // Set in initial Channel-object creation, so should always be set by now:
 +              U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
 +
 +              macro_rules! write_option {
 +                      ($thing: expr) => {
 +                              match $thing {
 +                                      &Some(ref t) => {
 +                                              1u8.write(writer)?;
 +                                              t.write(writer)?;
 +                                      },
 +                                      &None => 0u8.write(writer)?,
 +                              }
 +                      }
 +              }
 +
 +              match self.key_storage {
 +                      Storage::Local { ref keys, 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])?;
 +                              keys.write(writer)?;
 +                              writer.write_all(&funding_key[..])?;
 +                              writer.write_all(&revocation_base_key[..])?;
 +                              writer.write_all(&htlc_base_key[..])?;
 +                              writer.write_all(&delayed_payment_base_key[..])?;
 +                              writer.write_all(&payment_base_key[..])?;
 +                              writer.write_all(&shutdown_pubkey.serialize())?;
 +                              match funding_info  {
 +                                      &Some((ref outpoint, ref script)) => {
 +                                              writer.write_all(&outpoint.txid[..])?;
 +                                              writer.write_all(&byte_utils::be16_to_array(outpoint.index))?;
 +                                              script.write(writer)?;
 +                                      },
 +                                      &None => {
 +                                              debug_assert!(false, "Try to serialize a useless Local monitor !");
 +                                      },
 +                              }
 +                              current_remote_commitment_txid.write(writer)?;
 +                              prev_remote_commitment_txid.write(writer)?;
 +                      },
 +                      Storage::Watchtower { .. } => unimplemented!(),
 +              }
 +
 +              writer.write_all(&self.their_htlc_base_key.as_ref().unwrap().serialize())?;
 +              writer.write_all(&self.their_delayed_payment_base_key.as_ref().unwrap().serialize())?;
 +              self.funding_redeemscript.as_ref().unwrap().write(writer)?;
 +              self.channel_value_satoshis.unwrap().write(writer)?;
 +
 +              match self.their_cur_revocation_points {
 +                      Some((idx, pubkey, second_option)) => {
 +                              writer.write_all(&byte_utils::be48_to_array(idx))?;
 +                              writer.write_all(&pubkey.serialize())?;
 +                              match second_option {
 +                                      Some(second_pubkey) => {
 +                                              writer.write_all(&second_pubkey.serialize())?;
 +                                      },
 +                                      None => {
 +                                              writer.write_all(&[0; 33])?;
 +                                      },
 +                              }
 +                      },
 +                      None => {
 +                              writer.write_all(&byte_utils::be48_to_array(0))?;
 +                      },
 +              }
 +
 +              writer.write_all(&byte_utils::be16_to_array(self.our_to_self_delay))?;
 +              writer.write_all(&byte_utils::be16_to_array(self.their_to_self_delay.unwrap()))?;
 +
 +              for &(ref secret, ref idx) in self.old_secrets.iter() {
 +                      writer.write_all(secret)?;
 +                      writer.write_all(&byte_utils::be64_to_array(*idx))?;
 +              }
 +
 +              macro_rules! serialize_htlc_in_commitment {
 +                      ($htlc_output: expr) => {
 +                              writer.write_all(&[$htlc_output.offered as u8; 1])?;
 +                              writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
 +                              writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
 +                              writer.write_all(&$htlc_output.payment_hash.0[..])?;
 +                              $htlc_output.transaction_output_index.write(writer)?;
 +                      }
 +              }
 +
 +              writer.write_all(&byte_utils::be64_to_array(self.remote_claimable_outpoints.len() as u64))?;
 +              for (ref txid, ref htlc_infos) in self.remote_claimable_outpoints.iter() {
 +                      writer.write_all(&txid[..])?;
 +                      writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
 +                      for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
 +                              serialize_htlc_in_commitment!(htlc_output);
 +                              write_option!(htlc_source);
 +                      }
 +              }
 +
 +              writer.write_all(&byte_utils::be64_to_array(self.remote_commitment_txn_on_chain.len() as u64))?;
 +              for (ref txid, &(commitment_number, ref txouts)) in self.remote_commitment_txn_on_chain.iter() {
 +                      writer.write_all(&txid[..])?;
 +                      writer.write_all(&byte_utils::be48_to_array(commitment_number))?;
 +                      (txouts.len() as u64).write(writer)?;
 +                      for script in txouts.iter() {
 +                              script.write(writer)?;
 +                      }
 +              }
 +
 +              if for_local_storage {
 +                      writer.write_all(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64))?;
 +                      for (ref payment_hash, commitment_number) in self.remote_hash_commitment_number.iter() {
 +                              writer.write_all(&payment_hash.0[..])?;
 +                              writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
 +                      }
 +              } else {
 +                      writer.write_all(&byte_utils::be64_to_array(0))?;
 +              }
 +
 +              macro_rules! serialize_local_tx {
 +                      ($local_tx: expr) => {
 +                              $local_tx.tx.write(writer)?;
 +                              writer.write_all(&$local_tx.revocation_key.serialize())?;
 +                              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 sig, ref htlc_source) in $local_tx.htlc_outputs.iter() {
 +                                      serialize_htlc_in_commitment!(htlc_output);
 +                                      if let &Some(ref their_sig) = sig {
 +                                              1u8.write(writer)?;
 +                                              writer.write_all(&their_sig.serialize_compact())?;
 +                                      } else {
 +                                              0u8.write(writer)?;
 +                                      }
 +                                      write_option!(htlc_source);
 +                              }
 +                      }
 +              }
 +
 +              if let Some(ref prev_local_tx) = self.prev_local_signed_commitment_tx {
 +                      writer.write_all(&[1; 1])?;
 +                      serialize_local_tx!(prev_local_tx);
 +              } else {
 +                      writer.write_all(&[0; 1])?;
 +              }
 +
 +              if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
 +                      writer.write_all(&[1; 1])?;
 +                      serialize_local_tx!(cur_local_tx);
 +              } else {
 +                      writer.write_all(&[0; 1])?;
 +              }
 +
 +              if for_local_storage {
 +                      writer.write_all(&byte_utils::be48_to_array(self.current_remote_commitment_number))?;
 +              } else {
 +                      writer.write_all(&byte_utils::be48_to_array(0))?;
 +              }
 +
 +              writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
 +              for payment_preimage in self.payment_preimages.values() {
 +                      writer.write_all(&payment_preimage.0[..])?;
 +              }
 +
 +              self.last_block_hash.write(writer)?;
 +              self.destination_script.write(writer)?;
 +              if let Some((ref to_remote_script, ref local_key)) = self.to_remote_rescue {
 +                      writer.write_all(&[1; 1])?;
 +                      to_remote_script.write(writer)?;
 +                      local_key.write(writer)?;
 +              } else {
 +                      writer.write_all(&[0; 1])?;
 +              }
 +
 +              writer.write_all(&byte_utils::be64_to_array(self.pending_claim_requests.len() as u64))?;
 +              for (ref ancestor_claim_txid, claim_tx_data) in self.pending_claim_requests.iter() {
 +                      ancestor_claim_txid.write(writer)?;
 +                      claim_tx_data.write(writer)?;
 +              }
 +
 +              writer.write_all(&byte_utils::be64_to_array(self.claimable_outpoints.len() as u64))?;
 +              for (ref outp, ref claim_and_height) in self.claimable_outpoints.iter() {
 +                      outp.write(writer)?;
 +                      claim_and_height.0.write(writer)?;
 +                      claim_and_height.1.write(writer)?;
 +              }
 +
 +              writer.write_all(&byte_utils::be64_to_array(self.onchain_events_waiting_threshold_conf.len() as u64))?;
 +              for (ref target, ref events) in self.onchain_events_waiting_threshold_conf.iter() {
 +                      writer.write_all(&byte_utils::be32_to_array(**target))?;
 +                      writer.write_all(&byte_utils::be64_to_array(events.len() as u64))?;
 +                      for ev in events.iter() {
 +                              match *ev {
 +                                      OnchainEvent::Claim { ref claim_request } => {
 +                                              writer.write_all(&[0; 1])?;
 +                                              claim_request.write(writer)?;
 +                                      },
 +                                      OnchainEvent::HTLCUpdate { ref htlc_update } => {
 +                                              writer.write_all(&[1; 1])?;
 +                                              htlc_update.0.write(writer)?;
 +                                              htlc_update.1.write(writer)?;
 +                                      },
 +                                      OnchainEvent::ContentiousOutpoint { ref outpoint, ref input_material } => {
 +                                              writer.write_all(&[2; 1])?;
 +                                              outpoint.write(writer)?;
 +                                              input_material.write(writer)?;
 +                                      }
 +                              }
 +                      }
 +              }
 +
 +              Ok(())
 +      }
 +
 +      /// Writes this monitor into the given writer, suitable for writing to disk.
 +      ///
 +      /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
 +      /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
 +      /// the "reorg path" (ie not just starting at the same height but starting at the highest
 +      /// common block that appears on your best chain as well as on the chain which contains the
 +      /// last block hash returned) upon deserializing the object!
 +      pub fn write_for_disk<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
 +              self.write(writer, true)
 +      }
 +
 +      /// Encodes this monitor into the given writer, suitable for sending to a remote watchtower
 +      ///
 +      /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
 +      /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
 +      /// the "reorg path" (ie not just starting at the same height but starting at the highest
 +      /// common block that appears on your best chain as well as on the chain which contains the
 +      /// last block hash returned) upon deserializing the object!
 +      pub fn write_for_watchtower<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
 +              self.write(writer, false)
 +      }
 +}
 +
 +impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
 +      pub(super) fn new(keys: ChanSigner, funding_key: &SecretKey, revocation_base_key: &SecretKey, delayed_payment_base_key: &SecretKey, htlc_base_key: &SecretKey, payment_base_key: &SecretKey, shutdown_pubkey: &PublicKey, our_to_self_delay: u16, destination_script: Script, logger: Arc<Logger>) -> ChannelMonitor<ChanSigner> {
                ChannelMonitor {
                        commitment_transaction_number_obscure_factor: 0,
  
                        key_storage: Storage::Local {
 +                              keys,
                                funding_key: funding_key.clone(),
                                revocation_base_key: revocation_base_key.clone(),
                                htlc_base_key: htlc_base_key.clone(),
        /// needed by local commitment transactions HTCLs nor by remote ones. Unless we haven't already seen remote
        /// commitment transaction's secret, they are de facto pruned (we can use revocation key).
        pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), MonitorUpdateError> {
 -              let pos = ChannelMonitor::place_secret(idx);
 +              let pos = ChannelMonitor::<ChanSigner>::place_secret(idx);
                for i in 0..pos {
                        let (old_secret, old_idx) = self.old_secrets[i as usize];
 -                      if ChannelMonitor::derive_secret(secret, pos, old_idx) != old_secret {
 +                      if ChannelMonitor::<ChanSigner>::derive_secret(secret, pos, old_idx) != old_secret {
                                return Err(MonitorUpdateError("Previous secret did not match new one"));
                        }
                }
  
        pub(super) fn provide_rescue_remote_commitment_tx_info(&mut self, their_revocation_point: PublicKey) {
                match self.key_storage {
 -                      Storage::Local { ref payment_base_key, .. } => {
 -                              if let Ok(payment_key) = chan_utils::derive_public_key(&self.secp_ctx, &their_revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &payment_base_key)) {
 +                      Storage::Local { ref payment_base_key, ref keys, .. } => {
 +                              if let Ok(payment_key) = chan_utils::derive_public_key(&self.secp_ctx, &their_revocation_point, &keys.pubkeys().payment_basepoint) {
                                        let to_remote_script =  Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
                                                .push_slice(&Hash160::hash(&payment_key.serialize())[..])
                                                .into_script();
        /// Combines this ChannelMonitor with the information contained in the other ChannelMonitor.
        /// After a successful call this ChannelMonitor is up-to-date and is safe to use to monitor the
        /// chain for new blocks/transactions.
 -      pub fn insert_combine(&mut self, mut other: ChannelMonitor) -> Result<(), MonitorUpdateError> {
 +      pub fn insert_combine(&mut self, mut other: ChannelMonitor<ChanSigner>) -> Result<(), MonitorUpdateError> {
                match self.key_storage {
                        Storage::Local { ref funding_info, .. } => {
                                if funding_info.is_none() { return Err(MonitorUpdateError("Try to combine a Local monitor without funding_info")); }
                res
        }
  
 -      /// Serializes into a vec, with various modes for the exposed pub fns
 -      fn write<W: Writer>(&self, writer: &mut W, for_local_storage: bool) -> Result<(), ::std::io::Error> {
 -              //TODO: We still write out all the serialization here manually instead of using the fancy
 -              //serialization framework we have, we should migrate things over to it.
 -              writer.write_all(&[SERIALIZATION_VERSION; 1])?;
 -              writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
 -
 -              // Set in initial Channel-object creation, so should always be set by now:
 -              U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
 -
 -              macro_rules! write_option {
 -                      ($thing: expr) => {
 -                              match $thing {
 -                                      &Some(ref t) => {
 -                                              1u8.write(writer)?;
 -                                              t.write(writer)?;
 -                                      },
 -                                      &None => 0u8.write(writer)?,
 -                              }
 -                      }
 -              }
 -
 -              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 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[..])?;
 -                              writer.write_all(&htlc_base_key[..])?;
 -                              writer.write_all(&delayed_payment_base_key[..])?;
 -                              writer.write_all(&payment_base_key[..])?;
 -                              writer.write_all(&shutdown_pubkey.serialize())?;
 -                              match funding_info  {
 -                                      &Some((ref outpoint, ref script)) => {
 -                                              writer.write_all(&outpoint.txid[..])?;
 -                                              writer.write_all(&byte_utils::be16_to_array(outpoint.index))?;
 -                                              script.write(writer)?;
 -                                      },
 -                                      &None => {
 -                                              debug_assert!(false, "Try to serialize a useless Local monitor !");
 -                                      },
 -                              }
 -                              current_remote_commitment_txid.write(writer)?;
 -                              prev_remote_commitment_txid.write(writer)?;
 -                      },
 -                      Storage::Watchtower { .. } => unimplemented!(),
 -              }
 -
 -              writer.write_all(&self.their_htlc_base_key.as_ref().unwrap().serialize())?;
 -              writer.write_all(&self.their_delayed_payment_base_key.as_ref().unwrap().serialize())?;
 -              self.funding_redeemscript.as_ref().unwrap().write(writer)?;
 -              self.channel_value_satoshis.unwrap().write(writer)?;
 -
 -              match self.their_cur_revocation_points {
 -                      Some((idx, pubkey, second_option)) => {
 -                              writer.write_all(&byte_utils::be48_to_array(idx))?;
 -                              writer.write_all(&pubkey.serialize())?;
 -                              match second_option {
 -                                      Some(second_pubkey) => {
 -                                              writer.write_all(&second_pubkey.serialize())?;
 -                                      },
 -                                      None => {
 -                                              writer.write_all(&[0; 33])?;
 -                                      },
 -                              }
 -                      },
 -                      None => {
 -                              writer.write_all(&byte_utils::be48_to_array(0))?;
 -                      },
 -              }
 -
 -              writer.write_all(&byte_utils::be16_to_array(self.our_to_self_delay))?;
 -              writer.write_all(&byte_utils::be16_to_array(self.their_to_self_delay.unwrap()))?;
 -
 -              for &(ref secret, ref idx) in self.old_secrets.iter() {
 -                      writer.write_all(secret)?;
 -                      writer.write_all(&byte_utils::be64_to_array(*idx))?;
 -              }
 -
 -              macro_rules! serialize_htlc_in_commitment {
 -                      ($htlc_output: expr) => {
 -                              writer.write_all(&[$htlc_output.offered as u8; 1])?;
 -                              writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
 -                              writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
 -                              writer.write_all(&$htlc_output.payment_hash.0[..])?;
 -                              $htlc_output.transaction_output_index.write(writer)?;
 -                      }
 -              }
 -
 -              writer.write_all(&byte_utils::be64_to_array(self.remote_claimable_outpoints.len() as u64))?;
 -              for (ref txid, ref htlc_infos) in self.remote_claimable_outpoints.iter() {
 -                      writer.write_all(&txid[..])?;
 -                      writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
 -                      for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
 -                              serialize_htlc_in_commitment!(htlc_output);
 -                              write_option!(htlc_source);
 -                      }
 -              }
 -
 -              writer.write_all(&byte_utils::be64_to_array(self.remote_commitment_txn_on_chain.len() as u64))?;
 -              for (ref txid, &(commitment_number, ref txouts)) in self.remote_commitment_txn_on_chain.iter() {
 -                      writer.write_all(&txid[..])?;
 -                      writer.write_all(&byte_utils::be48_to_array(commitment_number))?;
 -                      (txouts.len() as u64).write(writer)?;
 -                      for script in txouts.iter() {
 -                              script.write(writer)?;
 -                      }
 -              }
 -
 -              if for_local_storage {
 -                      writer.write_all(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64))?;
 -                      for (ref payment_hash, commitment_number) in self.remote_hash_commitment_number.iter() {
 -                              writer.write_all(&payment_hash.0[..])?;
 -                              writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
 -                      }
 -              } else {
 -                      writer.write_all(&byte_utils::be64_to_array(0))?;
 -              }
 -
 -              macro_rules! serialize_local_tx {
 -                      ($local_tx: expr) => {
 -                              $local_tx.tx.write(writer)?;
 -                              writer.write_all(&$local_tx.revocation_key.serialize())?;
 -                              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 sig, ref htlc_source) in $local_tx.htlc_outputs.iter() {
 -                                      serialize_htlc_in_commitment!(htlc_output);
 -                                      if let &Some(ref their_sig) = sig {
 -                                              1u8.write(writer)?;
 -                                              writer.write_all(&their_sig.serialize_compact())?;
 -                                      } else {
 -                                              0u8.write(writer)?;
 -                                      }
 -                                      write_option!(htlc_source);
 -                              }
 -                      }
 -              }
 -
 -              if let Some(ref prev_local_tx) = self.prev_local_signed_commitment_tx {
 -                      writer.write_all(&[1; 1])?;
 -                      serialize_local_tx!(prev_local_tx);
 -              } else {
 -                      writer.write_all(&[0; 1])?;
 -              }
 -
 -              if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
 -                      writer.write_all(&[1; 1])?;
 -                      serialize_local_tx!(cur_local_tx);
 -              } else {
 -                      writer.write_all(&[0; 1])?;
 -              }
 -
 -              if for_local_storage {
 -                      writer.write_all(&byte_utils::be48_to_array(self.current_remote_commitment_number))?;
 -              } else {
 -                      writer.write_all(&byte_utils::be48_to_array(0))?;
 -              }
 -
 -              writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
 -              for payment_preimage in self.payment_preimages.values() {
 -                      writer.write_all(&payment_preimage.0[..])?;
 -              }
 -
 -              self.last_block_hash.write(writer)?;
 -              self.destination_script.write(writer)?;
 -              if let Some((ref to_remote_script, ref local_key)) = self.to_remote_rescue {
 -                      writer.write_all(&[1; 1])?;
 -                      to_remote_script.write(writer)?;
 -                      local_key.write(writer)?;
 -              } else {
 -                      writer.write_all(&[0; 1])?;
 -              }
 -
 -              writer.write_all(&byte_utils::be64_to_array(self.pending_claim_requests.len() as u64))?;
 -              for (ref ancestor_claim_txid, claim_tx_data) in self.pending_claim_requests.iter() {
 -                      ancestor_claim_txid.write(writer)?;
 -                      claim_tx_data.write(writer)?;
 -              }
 -
 -              writer.write_all(&byte_utils::be64_to_array(self.claimable_outpoints.len() as u64))?;
 -              for (ref outp, ref claim_and_height) in self.claimable_outpoints.iter() {
 -                      outp.write(writer)?;
 -                      claim_and_height.0.write(writer)?;
 -                      claim_and_height.1.write(writer)?;
 -              }
 -
 -              writer.write_all(&byte_utils::be64_to_array(self.onchain_events_waiting_threshold_conf.len() as u64))?;
 -              for (ref target, ref events) in self.onchain_events_waiting_threshold_conf.iter() {
 -                      writer.write_all(&byte_utils::be32_to_array(**target))?;
 -                      writer.write_all(&byte_utils::be64_to_array(events.len() as u64))?;
 -                      for ev in events.iter() {
 -                              match *ev {
 -                                      OnchainEvent::Claim { ref claim_request } => {
 -                                              writer.write_all(&[0; 1])?;
 -                                              claim_request.write(writer)?;
 -                                      },
 -                                      OnchainEvent::HTLCUpdate { ref htlc_update } => {
 -                                              writer.write_all(&[1; 1])?;
 -                                              htlc_update.0.write(writer)?;
 -                                              htlc_update.1.write(writer)?;
 -                                      },
 -                                      OnchainEvent::ContentiousOutpoint { ref outpoint, ref input_material } => {
 -                                              writer.write_all(&[2; 1])?;
 -                                              outpoint.write(writer)?;
 -                                              input_material.write(writer)?;
 -                                      }
 -                              }
 -                      }
 -              }
 -
 -              Ok(())
 -      }
 -
 -      /// Writes this monitor into the given writer, suitable for writing to disk.
 -      ///
 -      /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
 -      /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
 -      /// the "reorg path" (ie not just starting at the same height but starting at the highest
 -      /// common block that appears on your best chain as well as on the chain which contains the
 -      /// last block hash returned) upon deserializing the object!
 -      pub fn write_for_disk<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
 -              self.write(writer, true)
 -      }
 -
 -      /// Encodes this monitor into the given writer, suitable for sending to a remote watchtower
 -      ///
 -      /// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
 -      /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
 -      /// the "reorg path" (ie not just starting at the same height but starting at the highest
 -      /// common block that appears on your best chain as well as on the chain which contains the
 -      /// last block hash returned) upon deserializing the object!
 -      pub fn write_for_watchtower<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
 -              self.write(writer, false)
 -      }
 -
        /// Can only fail if idx is < get_min_seen_secret
        pub(super) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
                for i in 0..self.old_secrets.len() {
                        if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
 -                              return Some(ChannelMonitor::derive_secret(self.old_secrets[i].0, i as u8, idx))
 +                              return Some(ChannelMonitor::<ChanSigner>::derive_secret(self.old_secrets[i].0, i as u8, idx))
                        }
                }
                assert!(idx < self.get_min_seen_secret());
                        let secret = self.get_secret(commitment_number).unwrap();
                        let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
                        let (revocation_pubkey, b_htlc_key, local_payment_key) = match self.key_storage {
 -                              Storage::Local { ref revocation_base_key, ref htlc_base_key, ref payment_base_key, .. } => {
 +                              Storage::Local { ref keys, ref payment_base_key, .. } => {
                                        let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
 -                                      (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
 -                                      ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))),
 +                                      (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &keys.pubkeys().revocation_basepoint)),
 +                                      ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &keys.pubkeys().htlc_basepoint)),
                                        Some(ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, &per_commitment_point, &payment_base_key))))
                                },
                                Storage::Watchtower { ref revocation_base_key, ref htlc_base_key, .. } => {
                                        } else { None };
                                if let Some(revocation_point) = revocation_point_option {
                                        let (revocation_pubkey, b_htlc_key) = match self.key_storage {
 -                                              Storage::Local { ref revocation_base_key, ref htlc_base_key, .. } => {
 -                                                      (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key))),
 -                                                      ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &PublicKey::from_secret_key(&self.secp_ctx, &htlc_base_key))))
 +                                              Storage::Local { ref keys, .. } => {
 +                                                      (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &keys.pubkeys().revocation_basepoint)),
 +                                                      ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &keys.pubkeys().htlc_basepoint)))
                                                },
                                                Storage::Watchtower { ref revocation_base_key, ref htlc_base_key, .. } => {
                                                        (ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, revocation_point, &revocation_base_key)),
                                        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));
                                                        }
                                                        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 {
                                                                                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 },
                                                                                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 {
                                                                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);
                                        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) {
                let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
                let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
                let revocation_pubkey = match self.key_storage {
 -                      Storage::Local { ref revocation_base_key, .. } => {
 -                              ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &PublicKey::from_secret_key(&self.secp_ctx, &revocation_base_key)))
 +                      Storage::Local { ref keys, .. } => {
 +                              ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &keys.pubkeys().revocation_basepoint))
                        },
                        Storage::Watchtower { ref revocation_base_key, .. } => {
                                ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &revocation_base_key))
        }
  
        fn block_connected(&mut self, txn_matched: &[&Transaction], height: u32, block_hash: &Sha256dHash, broadcaster: &BroadcasterInterface, fee_estimator: &FeeEstimator)-> (Vec<(Sha256dHash, Vec<TxOut>)>, Vec<SpendableOutputDescriptor>, Vec<(HTLCSource, Option<PaymentPreimage>, PaymentHash)>) {
 +              for tx in txn_matched {
 +                      let mut output_val = 0;
 +                      for out in tx.output.iter() {
 +                              if out.value > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
 +                              output_val += out.value;
 +                              if output_val > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
 +                      }
 +              }
 +
                log_trace!(self, "Block {} at height {} connected with {} txn matched", block_hash, height, txn_matched.len());
                let mut watch_outputs = Vec::new();
                let mut spendable_outputs = Vec::new();
                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, .. } => {
-                                       log_trace!(self, "Is HLTC ? {}", is_htlc);
                                        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;
                                },
  
  const MAX_ALLOC_SIZE: usize = 64*1024;
  
 -impl<R: ::std::io::Read> ReadableArgs<R, Arc<Logger>> for (Sha256dHash, ChannelMonitor) {
 +impl<R: ::std::io::Read, ChanSigner: ChannelKeys + Readable<R>> ReadableArgs<R, Arc<Logger>> for (Sha256dHash, ChannelMonitor<ChanSigner>) {
        fn read(reader: &mut R, logger: Arc<Logger>) -> Result<Self, DecodeError> {
                let secp_ctx = Secp256k1::new();
                macro_rules! unwrap_obj {
  
                let key_storage = match <u8 as Readable<R>>::read(reader)? {
                        0 => {
 +                              let keys = Readable::read(reader)?;
                                let funding_key = Readable::read(reader)?;
                                let revocation_base_key = Readable::read(reader)?;
                                let htlc_base_key = Readable::read(reader)?;
                                let current_remote_commitment_txid = Readable::read(reader)?;
                                let prev_remote_commitment_txid = Readable::read(reader)?;
                                Storage::Local {
 +                                      keys,
                                        funding_key,
                                        revocation_base_key,
                                        htlc_base_key,
@@@ -3304,14 -3264,12 +3303,14 @@@ mod tests 
        use secp256k1::Secp256k1;
        use rand::{thread_rng,Rng};
        use std::sync::Arc;
 +      use chain::keysinterface::InMemoryChannelKeys;
 +
  
        #[test]
        fn test_per_commitment_storage() {
                // Test vectors from BOLT 3:
                let mut secrets: Vec<[u8; 32]> = Vec::new();
 -              let mut monitor: ChannelMonitor;
 +              let mut monitor: ChannelMonitor<InMemoryChannelKeys>;
                let secp_ctx = Secp256k1::new();
                let logger = Arc::new(TestLogger::new());
  
                        };
                }
  
 +              let keys = InMemoryChannelKeys::new(
 +                      &secp_ctx,
 +                      SecretKey::from_slice(&[41; 32]).unwrap(),
 +                      SecretKey::from_slice(&[41; 32]).unwrap(),
 +                      SecretKey::from_slice(&[41; 32]).unwrap(),
 +                      SecretKey::from_slice(&[41; 32]).unwrap(),
 +                      SecretKey::from_slice(&[41; 32]).unwrap(),
 +                      [41; 32],
 +                      0,
 +              );
 +
                {
                        // insert_secret correct sequence
 -                      monitor = ChannelMonitor::new(&SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
 +                      monitor = ChannelMonitor::new(keys.clone(), &SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
                        secrets.clear();
  
                        secrets.push([0; 32]);
  
                {
                        // insert_secret #1 incorrect
 -                      monitor = ChannelMonitor::new(&SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
 +                      monitor = ChannelMonitor::new(keys.clone(), &SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
                        secrets.clear();
  
                        secrets.push([0; 32]);
  
                {
                        // insert_secret #2 incorrect (#1 derived from incorrect)
 -                      monitor = ChannelMonitor::new(&SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
 +                      monitor = ChannelMonitor::new(keys.clone(), &SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
                        secrets.clear();
  
                        secrets.push([0; 32]);
  
                {
                        // insert_secret #3 incorrect
 -                      monitor = ChannelMonitor::new(&SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
 +                      monitor = ChannelMonitor::new(keys.clone(), &SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
                        secrets.clear();
  
                        secrets.push([0; 32]);
  
                {
                        // insert_secret #4 incorrect (1,2,3 derived from incorrect)
 -                      monitor = ChannelMonitor::new(&SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
 +                      monitor = ChannelMonitor::new(keys.clone(), &SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
                        secrets.clear();
  
                        secrets.push([0; 32]);
  
                {
                        // insert_secret #5 incorrect
 -                      monitor = ChannelMonitor::new(&SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
 +                      monitor = ChannelMonitor::new(keys.clone(), &SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
                        secrets.clear();
  
                        secrets.push([0; 32]);
  
                {
                        // insert_secret #6 incorrect (5 derived from incorrect)
 -                      monitor = ChannelMonitor::new(&SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
 +                      monitor = ChannelMonitor::new(keys.clone(), &SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
                        secrets.clear();
  
                        secrets.push([0; 32]);
  
                {
                        // insert_secret #7 incorrect
 -                      monitor = ChannelMonitor::new(&SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
 +                      monitor = ChannelMonitor::new(keys.clone(), &SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
                        secrets.clear();
  
                        secrets.push([0; 32]);
  
                {
                        // insert_secret #8 incorrect
 -                      monitor = ChannelMonitor::new(&SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
 +                      monitor = ChannelMonitor::new(keys.clone(), &SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
                        secrets.clear();
  
                        secrets.push([0; 32]);
                        }
                }
  
 +              let keys = InMemoryChannelKeys::new(
 +                      &secp_ctx,
 +                      SecretKey::from_slice(&[41; 32]).unwrap(),
 +                      SecretKey::from_slice(&[41; 32]).unwrap(),
 +                      SecretKey::from_slice(&[41; 32]).unwrap(),
 +                      SecretKey::from_slice(&[41; 32]).unwrap(),
 +                      SecretKey::from_slice(&[41; 32]).unwrap(),
 +                      [41; 32],
 +                      0,
 +              );
 +
                // Prune with one old state and a local commitment tx holding a few overlaps with the
                // old state.
 -              let mut monitor = ChannelMonitor::new(&SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
 +              let mut monitor = ChannelMonitor::new(keys, &SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
                monitor.their_to_self_delay = Some(10);
  
                monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10]));
                for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
                        sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
                }
 -              assert_eq!(base_weight + ChannelMonitor::get_witnesses_weight(&inputs_des[..]),  claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
 +              assert_eq!(base_weight + ChannelMonitor::<InMemoryChannelKeys>::get_witnesses_weight(&inputs_des[..]),  claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
  
                // Claim tx with 1 offered HTLCs, 3 received HTLCs
                claim_tx.input.clear();
                for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
                        sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
                }
 -              assert_eq!(base_weight + ChannelMonitor::get_witnesses_weight(&inputs_des[..]),  claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
 +              assert_eq!(base_weight + ChannelMonitor::<InMemoryChannelKeys>::get_witnesses_weight(&inputs_des[..]),  claim_tx.get_weight() + /* max_length_sig */ (73 * inputs_des.len() - sum_actual_sigs));
  
                // Justice tx with 1 revoked HTLC-Success tx output
                claim_tx.input.clear();
                for (idx, inp) in claim_tx.input.iter_mut().zip(inputs_des.iter()).enumerate() {
                        sign_input!(sighash_parts, inp.0, idx as u32, 0, inp.1, sum_actual_sigs);
                }
 -              assert_eq!(base_weight + ChannelMonitor::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_des.len() - sum_actual_sigs));
 +              assert_eq!(base_weight + ChannelMonitor::<InMemoryChannelKeys>::get_witnesses_weight(&inputs_des[..]), claim_tx.get_weight() + /* max_length_isg */ (73 * inputs_des.len() - sum_actual_sigs));
        }
  
        // Further testing is done in the ChannelManager integration tests.
index 5c16e72748198917d93ae7bd956106f94df641f3,e9153fb63ae5f30477a4323b626130a2bb8704d9..9b1907cbb776e4b048482ba21328947b4f68b497
@@@ -3,13 -3,13 +3,13 @@@
  //! claim outputs on-chain.
  
  use chain::transaction::OutPoint;
 -use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
 +use chain::keysinterface::{ChannelKeys, KeysInterface, SpendableOutputDescriptor};
  use chain::chaininterface::{ChainListener, ChainWatchInterfaceUtil, BlockNotifier};
  use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
  use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,HTLCForwardInfo,RAACommitmentOrder, PaymentPreimage, PaymentHash, BREAKDOWN_TIMEOUT};
  use ln::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ManyChannelMonitor, ANTI_REORG_DELAY};
  use ln::channel::{Channel, ChannelError};
 -use ln::onion_utils;
 +use ln::{chan_utils, onion_utils};
  use ln::router::{Route, RouteHop};
  use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
  use ln::msgs;
@@@ -18,7 -18,7 +18,7 @@@ use util::enforcing_trait_impls::Enforc
  use util::test_utils;
  use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
  use util::errors::APIError;
 -use util::ser::{Writeable, ReadableArgs};
 +use util::ser::{Writeable, Writer, ReadableArgs};
  use util::config::UserConfig;
  use util::logger::Logger;
  
@@@ -44,7 -44,7 +44,7 @@@ use std::collections::{BTreeSet, HashMa
  use std::default::Default;
  use std::sync::{Arc, Mutex};
  use std::sync::atomic::Ordering;
 -use std::mem;
 +use std::{mem, io};
  
  use rand::{thread_rng, Rng};
  
@@@ -378,41 -378,6 +378,41 @@@ fn test_multi_flight_update_fee() 
        check_added_monitors!(nodes[1], 1);
  }
  
 +#[test]
 +fn test_1_conf_open() {
 +      // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
 +      // tests that we properly send one in that case.
 +      let mut alice_config = UserConfig::default();
 +      alice_config.own_channel_config.minimum_depth = 1;
 +      alice_config.channel_options.announced_channel = true;
 +      alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
 +      let mut bob_config = UserConfig::default();
 +      bob_config.own_channel_config.minimum_depth = 1;
 +      bob_config.channel_options.announced_channel = true;
 +      bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
 +      let node_cfgs = create_node_cfgs(2);
 +      let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
 +      let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
 +
 +      let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::supported(), InitFeatures::supported());
 +      assert!(nodes[0].chain_monitor.does_match_tx(&tx));
 +      assert!(nodes[1].chain_monitor.does_match_tx(&tx));
 +
 +      let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
 +      nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version; 1]);
 +      nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id()));
 +
 +      nodes[0].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version; 1]);
 +      let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
 +      let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
 +
 +      for node in nodes {
 +              assert!(node.router.handle_channel_announcement(&announcement).unwrap());
 +              node.router.handle_channel_update(&as_update).unwrap();
 +              node.router.handle_channel_update(&bs_update).unwrap();
 +      }
 +}
 +
  #[test]
  fn test_update_fee_vanilla() {
        let node_cfgs = create_node_cfgs(2);
@@@ -1378,11 -1343,9 +1378,9 @@@ fn test_duplicate_htlc_different_direct
        // Check we only broadcast 1 timeout tx
        let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
        let htlc_pair = if claim_txn[0].output[0].value == 800_000 / 1000 { (claim_txn[0].clone(), claim_txn[1].clone()) } else { (claim_txn[1].clone(), claim_txn[0].clone()) };
-       assert_eq!(claim_txn.len(), 7);
+       assert_eq!(claim_txn.len(), 5);
        check_spends!(claim_txn[2], chan_1.3);
        check_spends!(claim_txn[3], claim_txn[2]);
-       assert_eq!(claim_txn[0], claim_txn[5]);
-       assert_eq!(claim_txn[1], claim_txn[6]);
        assert_eq!(htlc_pair.0.input.len(), 1);
        assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
        check_spends!(htlc_pair.0, remote_txn[0].clone());
@@@ -1999,8 -1962,7 +1997,7 @@@ fn test_justice_tx() 
                nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
                {
                        let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
-                       assert_eq!(node_txn.len(), 3);
-                       assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
+                       assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
                        assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
  
                        check_spends!(node_txn[0], revoked_local_txn[0].clone());
                nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
                {
                        let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
-                       assert_eq!(node_txn.len(), 3);
-                       assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
+                       assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
                        assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
  
                        check_spends!(node_txn[0], revoked_local_txn[0].clone());
@@@ -2083,9 -2044,7 +2079,7 @@@ fn revoked_output_claim() 
        let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
        nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
        let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
-       assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
-       assert_eq!(node_txn[0], node_txn[2]);
+       assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
  
        check_spends!(node_txn[0], revoked_local_txn[0].clone());
        check_spends!(node_txn[1], chan_1.3.clone());
@@@ -2140,13 -2099,11 +2134,11 @@@ fn claim_htlc_outputs_shared_tx() 
                }
  
                let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
-               assert_eq!(node_txn.len(), 4);
+               assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
  
                assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
                check_spends!(node_txn[0], revoked_local_txn[0].clone());
  
-               assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
                let mut witness_lens = BTreeSet::new();
                witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
                witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
@@@ -2210,15 -2167,28 +2202,28 @@@ fn claim_htlc_outputs_single_tx() 
                }
  
                let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
-               assert_eq!(node_txn.len(), 29); // ChannelManager : 2, ChannelMontitor: 8 (1 standard revoked output, 2 revocation htlc tx, 1 local commitment tx + 1 htlc timeout tx) * 2 (block-rescan) + 5 * (1 local commitment tx + 1 htlc timeout tx)
-               assert_eq!(node_txn[0], node_txn[7]);
-               assert_eq!(node_txn[1], node_txn[8]);
-               assert_eq!(node_txn[2], node_txn[9]);
-               assert_eq!(node_txn[3], node_txn[10]);
-               assert_eq!(node_txn[4], node_txn[11]);
-               assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcasted by ChannelManger
+               assert_eq!(node_txn.len(), 26);
+               // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
+               // ChannelManager: local commmitment + local HTLC-timeout (2)
+               // ChannelMonitor: bumped justice tx * 7 (7), after one increase, bumps on HTLC aren't generated not being substantial anymore
+               // ChannelMonitor: local commitment + local HTLC-timeout (14)
+               assert_eq!(node_txn[3], node_txn[5]);
+               assert_eq!(node_txn[3], node_txn[7]);
+               assert_eq!(node_txn[3], node_txn[9]);
+               assert_eq!(node_txn[3], node_txn[14]);
+               assert_eq!(node_txn[3], node_txn[17]);
+               assert_eq!(node_txn[3], node_txn[20]);
+               assert_eq!(node_txn[3], node_txn[23]);
                assert_eq!(node_txn[4], node_txn[6]);
+               assert_eq!(node_txn[4], node_txn[8]);
+               assert_eq!(node_txn[4], node_txn[10]);
+               assert_eq!(node_txn[4], node_txn[15]);
+               assert_eq!(node_txn[4], node_txn[18]);
+               assert_eq!(node_txn[4], node_txn[21]);
+               assert_eq!(node_txn[4], node_txn[24]);
  
                assert_eq!(node_txn[0].input.len(), 1);
                assert_eq!(node_txn[1].input.len(), 1);
@@@ -2350,13 -2320,16 +2355,16 @@@ fn test_htlc_on_chain_success() 
        };
        macro_rules! check_tx_local_broadcast {
                ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
-                       // ChannelManager : 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor : 2 (timeout tx) * 2 (block-rescan)
                        let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
-                       assert_eq!(node_txn.len(), 7);
-                       assert_eq!(node_txn[0], node_txn[5]);
-                       assert_eq!(node_txn[1], node_txn[6]);
+                       assert_eq!(node_txn.len(), if $htlc_offered { 7 } else { 5 });
+                       // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
+                       // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout * 2 (block-rescan)
                        check_spends!(node_txn[0], $commitment_tx.clone());
                        check_spends!(node_txn[1], $commitment_tx.clone());
+                       if $htlc_offered {
+                               assert_eq!(node_txn[0], node_txn[5]);
+                               assert_eq!(node_txn[1], node_txn[6]);
+                       }
                        assert_ne!(node_txn[0].lock_time, 0);
                        assert_ne!(node_txn[1].lock_time, 0);
                        if $htlc_offered {
        check_spends!(commitment_tx[0], chan_1.3.clone());
        nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
        check_closed_broadcast!(nodes[1], false);
-       let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + 2*HTLC-Success), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
-       assert_eq!(node_txn.len(), 5);
-       assert_eq!(node_txn[0], node_txn[4]);
+       let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
+       assert_eq!(node_txn.len(), 4);
        check_spends!(node_txn[0], commitment_tx[0].clone());
        assert_eq!(node_txn[0].input.len(), 2);
        assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
@@@ -2490,10 -2462,11 +2497,11 @@@ fn test_htlc_on_chain_timeout() 
        let timeout_tx;
        {
                let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
-               assert_eq!(node_txn.len(), 8); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 6 (HTLC-Timeout tx, commitment tx, timeout tx) * 2 (block-rescan)
-               assert_eq!(node_txn[0], node_txn[5]);
-               assert_eq!(node_txn[1], node_txn[6]);
-               assert_eq!(node_txn[2], node_txn[7]);
+               assert_eq!(node_txn.len(), 7); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : (local commitment tx + HTLC-timeout) * 2 (block-rescan), timeout tx
+               assert_eq!(node_txn[1], node_txn[3]);
+               assert_eq!(node_txn[1], node_txn[5]);
+               assert_eq!(node_txn[2], node_txn[4]);
+               assert_eq!(node_txn[2], node_txn[6]);
                check_spends!(node_txn[0], commitment_tx[0].clone());
                assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
                check_spends!(node_txn[1], chan_2.3.clone());
  
        nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
        check_closed_broadcast!(nodes[0], false);
-       let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (timeout tx) * 2 block-rescan
-       assert_eq!(node_txn.len(), 4);
-       assert_eq!(node_txn[0], node_txn[3]);
+       let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
+       assert_eq!(node_txn.len(), 3);
        check_spends!(node_txn[0], commitment_tx[0].clone());
        assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
        check_spends!(node_txn[1], chan_1.3.clone());
@@@ -3467,8 -3439,8 +3474,8 @@@ fn test_invalid_channel_announcement() 
  
        nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
  
 -      let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().inner.funding_key);
 -      let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().inner.funding_key);
 +      let as_bitcoin_key = as_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
 +      let bs_bitcoin_key = bs_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
  
        let as_network_key = nodes[0].node.get_our_node_id();
        let bs_network_key = nodes[1].node.get_our_node_id();
        macro_rules! sign_msg {
                ($unsigned_msg: expr) => {
                        let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
 -                      let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().inner.funding_key);
 -                      let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().inner.funding_key);
 +                      let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().inner.funding_key());
 +                      let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().inner.funding_key());
                        let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
                        let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
                        chan_announcement = msgs::ChannelAnnouncement {
@@@ -3545,7 -3517,7 +3552,7 @@@ fn test_no_txn_manager_serialize_deseri
        new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }));
        nodes[0].chan_monitor = &new_chan_monitor;
        let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
 -      let (_, mut chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
 +      let (_, mut chan_0_monitor) = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
        assert!(chan_0_monitor_read.is_empty());
  
        let mut nodes_0_read = &nodes_0_serialized[..];
@@@ -3615,7 -3587,7 +3622,7 @@@ fn test_simple_manager_serialize_deseri
        new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }));
        nodes[0].chan_monitor = &new_chan_monitor;
        let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
 -      let (_, mut chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
 +      let (_, mut chan_0_monitor) = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
        assert!(chan_0_monitor_read.is_empty());
  
        let mut nodes_0_read = &nodes_0_serialized[..];
@@@ -3682,7 -3654,7 +3689,7 @@@ fn test_manager_serialize_deserialize_i
        let mut node_0_monitors = Vec::new();
        for serialized in node_0_monitors_serialized.iter() {
                let mut read = &serialized[..];
 -              let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
 +              let (_, monitor) = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
                assert!(read.is_empty());
                node_0_monitors.push(monitor);
        }
@@@ -3956,10 -3928,9 +3963,9 @@@ fn test_static_spendable_outputs_preima
        }
  
        // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
-       let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: 2 (1 preimage tx)
-       assert_eq!(node_txn.len(), 4);
+       let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
+       assert_eq!(node_txn.len(), 3);
        check_spends!(node_txn[0], commitment_tx[0].clone());
-       assert_eq!(node_txn[0], node_txn[3]);
        assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
  eprintln!("{:?}", node_txn[1]);
        check_spends!(node_txn[1], chan_1.3.clone());
@@@ -3991,9 -3962,8 +3997,8 @@@ fn test_static_spendable_outputs_justic
        nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
        check_closed_broadcast!(nodes[1], false);
  
-       let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
-       assert_eq!(node_txn.len(), 3);
-       assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
+       let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
+       assert_eq!(node_txn.len(), 2);
        assert_eq!(node_txn[0].input.len(), 2);
        check_spends!(node_txn[0], revoked_local_txn[0].clone());
  
@@@ -4037,16 -4007,16 +4042,16 @@@ fn test_static_spendable_outputs_justic
        check_closed_broadcast!(nodes[1], false);
  
        let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
-       assert_eq!(node_txn.len(), 5);
-       assert_eq!(node_txn[3].input.len(), 1);
-       check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
+       assert_eq!(node_txn.len(), 4 ); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-timeout, adjusted justice tx, ChannelManager: local commitment tx
+       assert_eq!(node_txn[2].input.len(), 1);
+       check_spends!(node_txn[2], revoked_htlc_txn[0].clone());
  
        // Check B's ChannelMonitor was able to generate the right spendable output descriptor
        let spend_txn = check_spendable_outputs!(nodes[1], 1);
        assert_eq!(spend_txn.len(), 3);
        assert_eq!(spend_txn[0], spend_txn[1]);
        check_spends!(spend_txn[0], node_txn[0].clone());
-       check_spends!(spend_txn[2], node_txn[3].clone());
+       check_spends!(spend_txn[2], node_txn[2].clone());
  }
  
  #[test]
@@@ -4082,9 -4052,9 +4087,9 @@@ fn test_static_spendable_outputs_justic
        check_closed_broadcast!(nodes[0], false);
  
        let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
-       assert_eq!(node_txn.len(), 4);
-       assert_eq!(node_txn[3].input.len(), 1);
-       check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
+       assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
+       assert_eq!(node_txn[2].input.len(), 1);
+       check_spends!(node_txn[2], revoked_htlc_txn[0].clone());
  
        // Check A's ChannelMonitor was able to generate the right spendable output descriptor
        let spend_txn = check_spendable_outputs!(nodes[0], 1);
        assert_eq!(spend_txn[0], spend_txn[2]);
        assert_eq!(spend_txn[1], spend_txn[3]);
        check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
-       check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
-       check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
+       check_spends!(spend_txn[1], node_txn[0].clone()); // spending justice tx output from revoked local tx htlc received output
+       check_spends!(spend_txn[4], node_txn[2].clone()); // spending justice tx output on htlc success tx
  }
  
  #[test]
@@@ -4149,8 -4119,8 +4154,8 @@@ fn test_onchain_to_onchain_claim() 
        nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
        {
                let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
-               assert_eq!(b_txn.len(), 4);
-               assert_eq!(b_txn[0], b_txn[3]);
+               // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
+               assert_eq!(b_txn.len(), 3);
                check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
                check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
                assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
        let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
        nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
        let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
-       assert_eq!(b_txn.len(), 4);
-       check_spends!(b_txn[1], chan_1.3); // Local commitment tx, issued by ChannelManager
-       check_spends!(b_txn[2], b_txn[1]); // HTLC-Success tx, as a part of the local txn rebroadcast by ChannelManager in the force close
-       assert_eq!(b_txn[0], b_txn[3]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan
+       // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
+       assert_eq!(b_txn.len(), 3);
+       check_spends!(b_txn[1], chan_1.3);
+       check_spends!(b_txn[2], b_txn[1].clone());
        check_spends!(b_txn[0], commitment_tx[0].clone());
        assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
        assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
-       assert_eq!(b_txn[2].lock_time, 0); // Success tx
+       assert_eq!(b_txn[0].lock_time, 0); // Success tx
  
        check_closed_broadcast!(nodes[1], false);
  }
@@@ -4220,14 -4190,15 +4225,15 @@@ fn test_duplicate_payment_hash_one_fail
        let htlc_timeout_tx;
        { // Extract one of the two HTLC-Timeout transaction
                let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
-               assert_eq!(node_txn.len(), 7);
-               assert_eq!(node_txn[0], node_txn[5]);
-               assert_eq!(node_txn[1], node_txn[6]);
+               // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
+               assert_eq!(node_txn.len(), 5);
                check_spends!(node_txn[0], commitment_txn[0].clone());
                assert_eq!(node_txn[0].input.len(), 1);
                check_spends!(node_txn[1], commitment_txn[0].clone());
                assert_eq!(node_txn[1].input.len(), 1);
                assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
+               assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
+               assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
                check_spends!(node_txn[2], chan_2.3.clone());
                check_spends!(node_txn[3], node_txn[2].clone());
                check_spends!(node_txn[4], node_txn[2].clone());
@@@ -5007,20 -4978,6 +5013,20 @@@ impl msgs::ChannelUpdate 
        }
  }
  
 +struct BogusOnionHopData {
 +      data: Vec<u8>
 +}
 +impl BogusOnionHopData {
 +      fn new(orig: msgs::OnionHopData) -> Self {
 +              Self { data: orig.encode() }
 +      }
 +}
 +impl Writeable for BogusOnionHopData {
 +      fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
 +              writer.write_all(&self.data[..])
 +      }
 +}
 +
  #[test]
  fn test_onion_failure() {
        use ln::msgs::ChannelUpdate;
                let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
                let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
                let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
 -              onion_payloads[0].realm = 3;
 -              msg.onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
 -      }, ||{}, true, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));//XXX incremented channels idx here
 +              let mut new_payloads = Vec::new();
 +              for payload in onion_payloads.drain(..) {
 +                      new_payloads.push(BogusOnionHopData::new(payload));
 +              }
 +              // break the first (non-final) hop payload by swapping the realm (0) byte for a byte
 +              // describing a length-1 TLV payload, which is obviously bogus.
 +              new_payloads[0].data[0] = 1;
 +              msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
 +      }, ||{}, true, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));//XXX incremented channels idx here
  
        // final node failure
        run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
                let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
                let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
                let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
 -              onion_payloads[1].realm = 3;
 -              msg.onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
 -      }, ||{}, false, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
 +              let mut new_payloads = Vec::new();
 +              for payload in onion_payloads.drain(..) {
 +                      new_payloads.push(BogusOnionHopData::new(payload));
 +              }
 +              // break the last-hop payload by swapping the realm (0) byte for a byte describing a
 +              // length-1 TLV payload, which is obviously bogus.
 +              new_payloads[1].data[0] = 1;
 +              msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
 +      }, ||{}, false, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
  
        // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
        // receiving simulated fail messages
@@@ -6371,9 -6316,9 +6377,9 @@@ fn test_data_loss_protect() 
  
        // Restore node A from previous state
        let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", 0)));
 -      let mut chan_monitor = <(Sha256dHash, ChannelMonitor)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0), Arc::clone(&logger)).unwrap().1;
 +      let mut chan_monitor = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0), Arc::clone(&logger)).unwrap().1;
        let chain_monitor = Arc::new(ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
-       let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
+       let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), broadcasted_txn: Mutex::new(HashSet::new())});
        let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
        monitor = test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone(), feeest.clone());
        node_state_0 = {
@@@ -6614,8 -6559,7 +6620,7 @@@ fn test_bump_penalty_txn_on_revoked_com
        let feerate_1;
        {
                let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
-               assert_eq!(node_txn.len(), 4); // justice tx (broadcasted from ChannelMonitor) * 2 (block-reparsing) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
-               assert_eq!(node_txn[0], node_txn[3]);
+               assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
                assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
                assert_eq!(node_txn[0].output.len(), 1);
                check_spends!(node_txn[0], revoked_txn[0].clone());
@@@ -6733,21 -6677,21 +6738,21 @@@ fn test_bump_penalty_txn_on_revoked_htl
        let feerate_2;
        {
                let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
-               assert_eq!(node_txn.len(), 9); // 3 penalty txn on revoked commitment tx * 2 (block-rescan) + A commitment tx + 2 penalty tnx on revoked HTLC txn
+               assert_eq!(node_txn.len(), 6); // 3 penalty txn on revoked commitment tx + A commitment tx + 2 penalty tnx on revoked HTLC txn
                // Verify claim tx are spending revoked HTLC txn
-               assert_eq!(node_txn[7].input.len(), 1);
-               assert_eq!(node_txn[7].output.len(), 1);
-               check_spends!(node_txn[7], revoked_htlc_txn[0].clone());
-               first = node_txn[7].txid();
-               assert_eq!(node_txn[8].input.len(), 1);
-               assert_eq!(node_txn[8].output.len(), 1);
-               check_spends!(node_txn[8], revoked_htlc_txn[1].clone());
-               second = node_txn[8].txid();
+               assert_eq!(node_txn[4].input.len(), 1);
+               assert_eq!(node_txn[4].output.len(), 1);
+               check_spends!(node_txn[4], revoked_htlc_txn[0].clone());
+               first = node_txn[4].txid();
+               assert_eq!(node_txn[5].input.len(), 1);
+               assert_eq!(node_txn[5].output.len(), 1);
+               check_spends!(node_txn[5], revoked_htlc_txn[1].clone());
+               second = node_txn[5].txid();
                // Store both feerates for later comparison
-               let fee_1 = revoked_htlc_txn[0].output[0].value - node_txn[7].output[0].value;
-               feerate_1 = fee_1 * 1000 / node_txn[7].get_weight() as u64;
-               let fee_2 = revoked_htlc_txn[1].output[0].value - node_txn[8].output[0].value;
-               feerate_2 = fee_2 * 1000 / node_txn[8].get_weight() as u64;
+               let fee_1 = revoked_htlc_txn[0].output[0].value - node_txn[4].output[0].value;
+               feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
+               let fee_2 = revoked_htlc_txn[1].output[0].value - node_txn[5].output[0].value;
+               feerate_2 = fee_2 * 1000 / node_txn[5].get_weight() as u64;
                node_txn.clear();
        }
  
@@@ -6862,9 -6806,7 +6867,7 @@@ fn test_bump_penalty_txn_on_remote_comm
        let feerate_preimage;
        {
                let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
-               assert_eq!(node_txn.len(), 7); // 2 * claim tx (broadcasted from ChannelMonitor) * 2 (block-reparsing) + local commitment tx + local HTLC-timeout + HTLC-success (broadcasted from ChannelManager)
-               assert_eq!(node_txn[0], node_txn[5]);
-               assert_eq!(node_txn[1], node_txn[6]);
+               assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
                assert_eq!(node_txn[0].input.len(), 1);
                assert_eq!(node_txn[1].input.len(), 1);
                check_spends!(node_txn[0], remote_txn[0].clone());
@@@ -6976,8 -6918,8 +6979,8 @@@ fn test_set_outpoints_partial_claiming(
        // Verify node A broadcast tx claiming both HTLCs
        {
                let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
-               assert_eq!(node_txn.len(), 5);
-               assert_eq!(node_txn[0], node_txn[4]);
+               // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
+               assert_eq!(node_txn.len(), 4);
                check_spends!(node_txn[0], remote_txn[0].clone());
                check_spends!(node_txn[1], chan.3.clone());
                check_spends!(node_txn[2], node_txn[1]);
        }
  }
  
 +#[test]
 +fn test_counterparty_raa_skip_no_crash() {
 +      // Previously, if our counterparty sent two RAAs in a row without us having provided a
 +      // commitment transaction, we would have happily carried on and provided them the next
 +      // commitment transaction based on one RAA forward. This would probably eventually have led to
 +      // channel closure, but it would not have resulted in funds loss. Still, our
 +      // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
 +      // check simply that the channel is closed in response to such an RAA, but don't check whether
 +      // we decide to punish our counterparty for revoking their funds (as we don't currently
 +      // implement that).
 +      let node_cfgs = create_node_cfgs(2);
 +      let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
 +      let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
 +      let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported()).2;
 +
 +      let commitment_seed = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&channel_id).unwrap().local_keys.commitment_seed().clone();
 +      const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
 +      let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
 +              &SecretKey::from_slice(&chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
 +      let per_commitment_secret = chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER);
 +
 +      nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
 +              &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
 +      assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
 +}
 +
  #[test]
  fn test_bump_txn_sanitize_tracking_maps() {
        // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
        check_closed_broadcast!(nodes[0], false);
        let penalty_txn = {
                let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
-               assert_eq!(node_txn.len(), 7);
+               assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
                check_spends!(node_txn[0], revoked_local_txn[0].clone());
                check_spends!(node_txn[1], revoked_local_txn[0].clone());
                check_spends!(node_txn[2], revoked_local_txn[0].clone());
index cd2064a4ea330cacc824a6dc453c371f96acaf61,0e67d6bbd25e708318dd3ada5de20e6636e9ee30..b343ac35379f17195e785d70f6f6dea9dab5829e
@@@ -10,8 -10,7 +10,8 @@@ use ln::channelmonitor::HTLCUpdate
  use util::enforcing_trait_impls::EnforcingChannelKeys;
  use util::events;
  use util::logger::{Logger, Level, Record};
 -use util::ser::{ReadableArgs, Writer};
 +use util::ser::ReadableArgs;
 +use util::ser::Writer;
  
  use bitcoin::blockdata::transaction::Transaction;
  use bitcoin::blockdata::script::Script;
@@@ -23,7 -22,7 +23,7 @@@ use secp256k1::{SecretKey, PublicKey}
  use std::time::{SystemTime, UNIX_EPOCH};
  use std::sync::{Arc,Mutex};
  use std::{mem};
- use std::collections::HashMap;
+ use std::collections::{HashMap, HashSet};
  
  pub struct TestVecWriter(pub Vec<u8>);
  impl Writer for TestVecWriter {
@@@ -46,8 -45,8 +46,8 @@@ impl chaininterface::FeeEstimator for T
  }
  
  pub struct TestChannelMonitor {
 -      pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor)>>,
 -      pub simple_monitor: channelmonitor::SimpleManyChannelMonitor<OutPoint>,
 +      pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>>,
 +      pub simple_monitor: channelmonitor::SimpleManyChannelMonitor<OutPoint, EnforcingChannelKeys>,
        pub update_ret: Mutex<Result<(), channelmonitor::ChannelMonitorUpdateErr>>,
  }
  impl TestChannelMonitor {
                }
        }
  }
 -impl channelmonitor::ManyChannelMonitor for TestChannelMonitor {
 -      fn add_update_monitor(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
 +impl channelmonitor::ManyChannelMonitor<EnforcingChannelKeys> for TestChannelMonitor {
 +      fn add_update_monitor(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
                // At every point where we get a monitor update, we should be able to send a useful monitor
                // to a watchtower and disk...
                let mut w = TestVecWriter(Vec::new());
                monitor.write_for_disk(&mut w).unwrap();
 -              assert!(<(Sha256dHash, channelmonitor::ChannelMonitor)>::read(
 +              assert!(<(Sha256dHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
                                &mut ::std::io::Cursor::new(&w.0), Arc::new(TestLogger::new())).unwrap().1 == monitor);
                w.0.clear();
                monitor.write_for_watchtower(&mut w).unwrap(); // This at least shouldn't crash...
  
  pub struct TestBroadcaster {
        pub txn_broadcasted: Mutex<Vec<Transaction>>,
+       pub broadcasted_txn: Mutex<HashSet<Sha256dHash>> // Temporary field while refactoring out tx duplication
  }
  impl chaininterface::BroadcasterInterface for TestBroadcaster {
        fn broadcast_transaction(&self, tx: &Transaction) {
+               {
+                       if let Some(_) = self.broadcasted_txn.lock().unwrap().get(&tx.txid()) {
+                               // If commitment tx, HTLC-timeout or HTLC-Success, duplicate broadcast are still ok
+                               if tx.input[0].sequence == 0xfffffffd {
+                                       return;
+                               }
+                       }
+               }
+               self.broadcasted_txn.lock().unwrap().insert(tx.txid());
                self.txn_broadcasted.lock().unwrap().push(tx.clone());
        }
  }
@@@ -155,9 -164,6 +165,9 @@@ impl msgs::RoutingMessageHandler for Te
        fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
                Vec::new()
        }
 +      fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
 +              true
 +      }
  }
  
  pub struct TestLogger {