X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning%2Fsrc%2Fln%2Fchannelmonitor.rs;h=bbcbe75c67bf43bc78c0069e734c11ecff3ee447;hb=ab7a0a54318cdd55bedc3a02604af200b16e2e2c;hp=e17111256ea016ae6df06abaa22fcb5b846f8043;hpb=d421816e8420a9402461bbc96588843a1519cdff;p=rust-lightning diff --git a/lightning/src/ln/channelmonitor.rs b/lightning/src/ln/channelmonitor.rs index e1711125..bbcbe75c 100644 --- a/lightning/src/ln/channelmonitor.rs +++ b/lightning/src/ln/channelmonitor.rs @@ -16,7 +16,7 @@ use bitcoin::blockdata::transaction::{TxIn,TxOut,SigHashType,Transaction}; use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint; use bitcoin::blockdata::script::{Script, Builder}; use bitcoin::blockdata::opcodes; -use bitcoin::consensus::encode::{self, Decodable, Encodable}; +use bitcoin::consensus::encode; use bitcoin::util::hash::BitcoinHash; use bitcoin::util::bip143; @@ -31,19 +31,58 @@ use secp256k1; use ln::msgs::DecodeError; use ln::chan_utils; -use ln::chan_utils::HTLCOutputInCommitment; +use ln::chan_utils::{CounterpartyCommitmentSecrets, HTLCOutputInCommitment, LocalCommitmentTransaction, HTLCType}; use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash}; -use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT}; use chain::chaininterface::{ChainListener, ChainWatchInterface, BroadcasterInterface, FeeEstimator, ConfirmationTarget, MIN_RELAY_FEE_SAT_PER_1000_WEIGHT}; use chain::transaction::OutPoint; -use chain::keysinterface::SpendableOutputDescriptor; +use chain::keysinterface::{SpendableOutputDescriptor, ChannelKeys}; use util::logger::Logger; -use util::ser::{ReadableArgs, Readable, Writer, Writeable, WriterWriteAdaptor, U48}; +use util::ser::{ReadableArgs, Readable, Writer, Writeable, U48}; use util::{byte_utils, events}; -use std::collections::{HashMap, hash_map}; +use std::collections::{HashMap, hash_map, HashSet}; use std::sync::{Arc,Mutex}; use std::{hash,cmp, mem}; +use std::ops::Deref; + +/// An update generated by the underlying Channel itself which contains some new information the +/// ChannelMonitor should be made aware of. +#[cfg_attr(test, derive(PartialEq))] +#[derive(Clone)] +#[must_use] +pub struct ChannelMonitorUpdate { + pub(super) updates: Vec, + /// The sequence number of this update. Updates *must* be replayed in-order according to this + /// sequence number (and updates may panic if they are not). The update_id values are strictly + /// increasing and increase by one for each new update. + /// + /// This sequence number is also used to track up to which points updates which returned + /// ChannelMonitorUpdateErr::TemporaryFailure have been applied to all copies of a given + /// ChannelMonitor when ChannelManager::channel_monitor_updated is called. + pub update_id: u64, +} + +impl Writeable for ChannelMonitorUpdate { + fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> { + self.update_id.write(w)?; + (self.updates.len() as u64).write(w)?; + for update_step in self.updates.iter() { + update_step.write(w)?; + } + Ok(()) + } +} +impl Readable for ChannelMonitorUpdate { + fn read(r: &mut R) -> Result { + let update_id: u64 = Readable::read(r)?; + let len: u64 = Readable::read(r)?; + let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::std::mem::size_of::())); + for _ in 0..len { + updates.push(Readable::read(r)?); + } + Ok(Self { update_id, updates }) + } +} /// An error enum representing a failure to persist a channel monitor update. #[derive(Clone)] @@ -52,13 +91,13 @@ pub enum ChannelMonitorUpdateErr { /// our state failed, but is expected to succeed at some point in the future). /// /// Such a failure will "freeze" a channel, preventing us from revoking old states or - /// submitting new commitment transactions to the remote party. - /// ChannelManager::test_restore_channel_monitor can be used to retry the update(s) and restore - /// the channel to an operational state. + /// submitting new commitment transactions to the remote party. Once the update(s) which failed + /// have been successfully applied, ChannelManager::channel_monitor_updated can be used to + /// restore the channel to an operational state. /// - /// Note that continuing to operate when no copy of the updated ChannelMonitor could be - /// persisted is unsafe - if you failed to store the update on your own local disk you should - /// instead return PermanentFailure to force closure of the channel ASAP. + /// Note that a given ChannelManager will *never* re-generate a given ChannelMonitorUpdate. If + /// you return a TemporaryFailure you must ensure that it is written to disk safely before + /// writing out the latest ChannelManager state. /// /// Even when a channel has been "frozen" updates to the ChannelMonitor can continue to occur /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting @@ -69,8 +108,15 @@ pub enum ChannelMonitorUpdateErr { /// been "frozen". /// /// Note that even if updates made after TemporaryFailure succeed you must still call - /// test_restore_channel_monitor to ensure you have the latest monitor and re-enable normal - /// channel operation. + /// channel_monitor_updated to ensure you have the latest monitor and re-enable normal channel + /// operation. + /// + /// Note that the update being processed here will not be replayed for you when you call + /// ChannelManager::channel_monitor_updated, so you must store the update itself along + /// with the persisted ChannelMonitor on your own local disk prior to returning a + /// TemporaryFailure. You may, of course, employ a journaling approach, storing only the + /// ChannelMonitorUpdate on disk without updating the monitor itself, replaying the journal at + /// reload-time. /// /// For deployments where a copy of ChannelMonitors and other local state are backed up in a /// remote location (with local copies persisted immediately), it is anticipated that all @@ -85,24 +131,26 @@ pub enum ChannelMonitorUpdateErr { } /// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is -/// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::insert_combine this -/// means you tried to merge two monitors for different channels or for a channel which was -/// restored from a backup and then generated new commitment updates. +/// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::update_monitor this +/// means you tried to update a monitor for a different channel or the ChannelMonitorUpdate was +/// corrupted. /// Contains a human-readable error message. #[derive(Debug)] pub struct MonitorUpdateError(pub &'static str); /// Simple structure send back by ManyChannelMonitor in case of HTLC detected onchain from a /// forward channel and from which info are needed to update HTLC in a backward channel. +#[derive(Clone, PartialEq)] pub struct HTLCUpdate { pub(super) payment_hash: PaymentHash, pub(super) payment_preimage: Option, pub(super) source: HTLCSource } +impl_writeable!(HTLCUpdate, 0, { payment_hash, payment_preimage, source }); /// Simple trait indicating ability to track a set of ChannelMonitors and multiplex events between /// them. Generally should be implemented by keeping a local SimpleManyChannelMonitor and passing -/// events to it, while also taking any add_update_monitor events and passing them to some remote +/// events to it, while also taking any add/update_monitor events and passing them to some remote /// server(s). /// /// Note that any updates to a channel's monitor *must* be applied to each instance of the @@ -115,17 +163,42 @@ 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 { - /// Adds or updates a monitor for the given `funding_txo`. +pub trait ManyChannelMonitor: Send + Sync { + /// Adds a monitor for the given `funding_txo`. + /// + /// Implementer must also ensure that the funding_txo txid *and* outpoint are registered with + /// any relevant ChainWatchInterfaces such that the provided monitor receives block_connected + /// callbacks with the funding transaction, or any spends of it. + /// + /// Further, the implementer must also ensure that each output returned in + /// monitor.get_outputs_to_watch() is registered to ensure that the provided monitor learns about + /// any spends of any of the outputs. + /// + /// Any spends of outputs which should have been registered which aren't passed to + /// ChannelMonitors via block_connected may result in FUNDS LOSS. + fn add_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr>; + + /// Updates a monitor for the given `funding_txo`. + /// + /// Implementer must also ensure that the funding_txo txid *and* outpoint are registered with + /// any relevant ChainWatchInterfaces such that the provided monitor receives block_connected + /// callbacks with the funding transaction, or any spends of it. /// - /// 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>; + /// Further, the implementer must also ensure that each output returned in + /// monitor.get_watch_outputs() is registered to ensure that the provided monitor learns about + /// any spends of any of the outputs. + /// + /// Any spends of outputs which should have been registered which aren't passed to + /// ChannelMonitors via block_connected may result in FUNDS LOSS. + fn update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr>; /// Used by ChannelManager to get list of HTLC resolved onchain and which needed to be updated - /// with success or failure backward - fn fetch_pending_htlc_updated(&self) -> Vec; + /// with success or failure. + /// + /// You should probably just call through to + /// ChannelMonitor::get_and_clear_pending_htlcs_updated() for each ChannelMonitor and return + /// the full list. + fn get_and_clear_pending_htlcs_updated(&self) -> Vec; } /// A simple implementation of a ManyChannelMonitor and ChainListener. Can be used to create a @@ -139,29 +212,28 @@ pub trait ManyChannelMonitor: Send + Sync { /// /// 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 { +pub struct SimpleManyChannelMonitor where T::Target: BroadcasterInterface { #[cfg(test)] // Used in ChannelManager tests to manipulate channels directly - pub monitors: Mutex>, + pub monitors: Mutex>>, #[cfg(not(test))] - monitors: Mutex>, + monitors: Mutex>>, chain_monitor: Arc, - broadcaster: Arc, + broadcaster: T, pending_events: Mutex>, - pending_htlc_updated: Mutex)>>>, logger: Arc, fee_estimator: Arc } -impl<'a, Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonitor { - +impl<'a, Key : Send + cmp::Eq + hash::Hash, ChanSigner: ChannelKeys, T: Deref + Sync + Send> ChainListener for SimpleManyChannelMonitor + where T::Target: BroadcasterInterface +{ 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 = Vec::with_capacity(0); - let mut htlc_updated_infos = Vec::new(); { let mut monitors = self.monitors.lock().unwrap(); for monitor in monitors.values_mut() { - let (txn_outputs, spendable_outputs, mut htlc_updated) = monitor.block_connected(txn_matched, height, &block_hash, &*self.broadcaster, &*self.fee_estimator); + let (txn_outputs, spendable_outputs) = monitor.block_connected(txn_matched, height, &block_hash, &*self.broadcaster, &*self.fee_estimator); if spendable_outputs.len() > 0 { new_events.push(events::Event::SpendableOutputs { outputs: spendable_outputs, @@ -173,35 +245,6 @@ impl<'a, Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelM self.chain_monitor.install_watch_outpoint((txid.clone(), idx as u32), &output.script_pubkey); } } - htlc_updated_infos.append(&mut htlc_updated); - } - } - { - // ChannelManager will just need to fetch pending_htlc_updated and pass state backward - let mut pending_htlc_updated = self.pending_htlc_updated.lock().unwrap(); - for htlc in htlc_updated_infos.drain(..) { - match pending_htlc_updated.entry(htlc.2) { - hash_map::Entry::Occupied(mut e) => { - // In case of reorg we may have htlc outputs solved in a different way so - // we prefer to keep claims but don't store duplicate updates for a given - // (payment_hash, HTLCSource) pair. - let mut existing_claim = false; - e.get_mut().retain(|htlc_data| { - if htlc.0 == htlc_data.0 { - if htlc_data.1.is_some() { - existing_claim = true; - true - } else { false } - } else { true } - }); - if !existing_claim { - e.get_mut().push((htlc.0, htlc.1)); - } - } - hash_map::Entry::Vacant(e) => { - e.insert(vec![(htlc.0, htlc.1)]); - } - } } } let mut pending_events = self.pending_events.lock().unwrap(); @@ -217,32 +260,30 @@ impl<'a, Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelM } } -impl SimpleManyChannelMonitor { +impl SimpleManyChannelMonitor + where T::Target: BroadcasterInterface +{ /// 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, broadcaster: Arc, logger: Arc, feeest: Arc) -> Arc> { - let res = Arc::new(SimpleManyChannelMonitor { + pub fn new(chain_monitor: Arc, broadcaster: T, logger: Arc, feeest: Arc) -> SimpleManyChannelMonitor { + let res = SimpleManyChannelMonitor { monitors: Mutex::new(HashMap::new()), chain_monitor, broadcaster, pending_events: Mutex::new(Vec::new()), - pending_htlc_updated: Mutex::new(HashMap::new()), logger, fee_estimator: feeest, - }); + }; res } /// 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_monitor_by_key(&self, key: Key, monitor: ChannelMonitor) -> Result<(), MonitorUpdateError> { let mut monitors = self.monitors.lock().unwrap(); - match monitors.get_mut(&key) { - Some(orig_monitor) => { - log_trace!(self, "Updating Channel Monitor for channel {}", log_funding_info!(monitor.key_storage)); - return orig_monitor.insert_combine(monitor); - }, - None => {} + let entry = match monitors.entry(key) { + hash_map::Entry::Occupied(_) => return Err(MonitorUpdateError("Channel monitor for given key is already present")), + hash_map::Entry::Vacant(e) => e, }; match monitor.key_storage { Storage::Local { ref funding_info, .. } => { @@ -261,36 +302,57 @@ impl SimpleManyChannelMonitor self.chain_monitor.watch_all_txn(); } } - monitors.insert(key, monitor); + for (txid, outputs) in monitor.get_outputs_to_watch().iter() { + for (idx, script) in outputs.iter().enumerate() { + self.chain_monitor.install_watch_outpoint((*txid, idx as u32), script); + } + } + entry.insert(monitor); Ok(()) } + + /// Updates the monitor which monitors the channel referred to by the given key. + pub fn update_monitor_by_key(&self, key: Key, update: ChannelMonitorUpdate) -> Result<(), MonitorUpdateError> { + let mut monitors = self.monitors.lock().unwrap(); + match monitors.get_mut(&key) { + Some(orig_monitor) => { + log_trace!(self, "Updating Channel Monitor for channel {}", log_funding_info!(orig_monitor.key_storage)); + orig_monitor.update_monitor(update) + }, + None => Err(MonitorUpdateError("No such monitor registered")) + } + } } -impl ManyChannelMonitor for SimpleManyChannelMonitor { - fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr> { - match self.add_update_monitor_by_key(funding_txo, monitor) { +impl ManyChannelMonitor for SimpleManyChannelMonitor + where T::Target: BroadcasterInterface +{ + fn add_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr> { + match self.add_monitor_by_key(funding_txo, monitor) { Ok(_) => Ok(()), Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure), } } - fn fetch_pending_htlc_updated(&self) -> Vec { - let mut updated = self.pending_htlc_updated.lock().unwrap(); - let mut pending_htlcs_updated = Vec::with_capacity(updated.len()); - for (k, v) in updated.drain() { - for htlc_data in v { - pending_htlcs_updated.push(HTLCUpdate { - payment_hash: k, - payment_preimage: htlc_data.1, - source: htlc_data.0, - }); - } + fn update_monitor(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr> { + match self.update_monitor_by_key(funding_txo, update) { + Ok(_) => Ok(()), + Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure), + } + } + + fn get_and_clear_pending_htlcs_updated(&self) -> Vec { + let mut pending_htlcs_updated = Vec::new(); + for chan in self.monitors.lock().unwrap().values_mut() { + pending_htlcs_updated.append(&mut chan.get_and_clear_pending_htlcs_updated()); } pending_htlcs_updated } } -impl events::EventsProvider for SimpleManyChannelMonitor { +impl events::EventsProvider for SimpleManyChannelMonitor + where T::Target: BroadcasterInterface +{ fn get_and_clear_pending_events(&self) -> Vec { let mut pending_events = self.pending_events.lock().unwrap(); let mut ret = Vec::new(); @@ -328,16 +390,15 @@ pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3; /// keeping bumping another claim tx to solve the outpoint. pub(crate) const ANTI_REORG_DELAY: u32 = 6; -#[derive(Clone, PartialEq)] -enum Storage { +enum Storage { Local { + keys: ChanSigner, + funding_key: SecretKey, revocation_base_key: SecretKey, htlc_base_key: SecretKey, delayed_payment_base_key: SecretKey, payment_base_key: SecretKey, shutdown_pubkey: PublicKey, - prev_latest_per_commitment_point: Option, - latest_per_commitment_point: Option, funding_info: Option<(OutPoint, Script)>, current_remote_commitment_txid: Option, prev_remote_commitment_txid: Option, @@ -348,17 +409,41 @@ enum Storage { } } +#[cfg(any(test, feature = "fuzztarget"))] +impl PartialEq for Storage { + 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 txid: Sha256dHash, - tx: Transaction, + tx: LocalCommitmentTransaction, revocation_key: PublicKey, a_htlc_key: PublicKey, b_htlc_key: PublicKey, delayed_payment_key: PublicKey, + per_commitment_point: PublicKey, feerate_per_kw: u64, - htlc_outputs: Vec<(HTLCOutputInCommitment, Option<(Signature, Signature)>, Option)>, + htlc_outputs: Vec<(HTLCOutputInCommitment, Option, Option)>, } #[derive(PartialEq)] @@ -513,7 +598,7 @@ enum OnchainEvent { /// Higher-level cache structure needed to re-generate bumped claim txn if needed #[derive(Clone, PartialEq)] -struct ClaimTxBumpMaterial { +pub struct ClaimTxBumpMaterial { // At every block tick, used to check if pending claiming tx is taking too // much time for confirmation and we need to bump it. height_timer: u32, @@ -559,25 +644,162 @@ impl Readable for ClaimTxBumpMaterial { const SERIALIZATION_VERSION: u8 = 1; const MIN_SERIALIZATION_VERSION: u8 = 1; +#[cfg_attr(test, derive(PartialEq))] +#[derive(Clone)] +pub(super) enum ChannelMonitorUpdateStep { + LatestLocalCommitmentTXInfo { + // TODO: We really need to not be generating a fully-signed transaction in Channel and + // passing it here, we need to hold off so that the ChanSigner can enforce a + // only-sign-local-state-for-broadcast once invariant: + commitment_tx: LocalCommitmentTransaction, + local_keys: chan_utils::TxCreationKeys, + feerate_per_kw: u64, + htlc_outputs: Vec<(HTLCOutputInCommitment, Option, Option)>, + }, + LatestRemoteCommitmentTXInfo { + unsigned_commitment_tx: Transaction, // TODO: We should actually only need the txid here + htlc_outputs: Vec<(HTLCOutputInCommitment, Option>)>, + commitment_number: u64, + their_revocation_point: PublicKey, + }, + PaymentPreimage { + payment_preimage: PaymentPreimage, + }, + CommitmentSecret { + idx: u64, + secret: [u8; 32], + }, + /// Indicates our channel is likely a stale version, we're closing, but this update should + /// allow us to spend what is ours if our counterparty broadcasts their latest state. + RescueRemoteCommitmentTXInfo { + their_current_per_commitment_point: PublicKey, + }, +} + +impl Writeable for ChannelMonitorUpdateStep { + fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> { + match self { + &ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { ref commitment_tx, ref local_keys, ref feerate_per_kw, ref htlc_outputs } => { + 0u8.write(w)?; + commitment_tx.write(w)?; + local_keys.write(w)?; + feerate_per_kw.write(w)?; + (htlc_outputs.len() as u64).write(w)?; + for &(ref output, ref signature, ref source) in htlc_outputs.iter() { + output.write(w)?; + signature.write(w)?; + source.write(w)?; + } + } + &ChannelMonitorUpdateStep::LatestRemoteCommitmentTXInfo { ref unsigned_commitment_tx, ref htlc_outputs, ref commitment_number, ref their_revocation_point } => { + 1u8.write(w)?; + unsigned_commitment_tx.write(w)?; + commitment_number.write(w)?; + their_revocation_point.write(w)?; + (htlc_outputs.len() as u64).write(w)?; + for &(ref output, ref source) in htlc_outputs.iter() { + output.write(w)?; + match source { + &None => 0u8.write(w)?, + &Some(ref s) => { + 1u8.write(w)?; + s.write(w)?; + }, + } + } + }, + &ChannelMonitorUpdateStep::PaymentPreimage { ref payment_preimage } => { + 2u8.write(w)?; + payment_preimage.write(w)?; + }, + &ChannelMonitorUpdateStep::CommitmentSecret { ref idx, ref secret } => { + 3u8.write(w)?; + idx.write(w)?; + secret.write(w)?; + }, + &ChannelMonitorUpdateStep::RescueRemoteCommitmentTXInfo { ref their_current_per_commitment_point } => { + 4u8.write(w)?; + their_current_per_commitment_point.write(w)?; + }, + } + Ok(()) + } +} +impl Readable for ChannelMonitorUpdateStep { + fn read(r: &mut R) -> Result { + match Readable::read(r)? { + 0u8 => { + Ok(ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { + commitment_tx: Readable::read(r)?, + local_keys: Readable::read(r)?, + feerate_per_kw: Readable::read(r)?, + htlc_outputs: { + let len: u64 = Readable::read(r)?; + let mut res = Vec::new(); + for _ in 0..len { + res.push((Readable::read(r)?, Readable::read(r)?, Readable::read(r)?)); + } + res + }, + }) + }, + 1u8 => { + Ok(ChannelMonitorUpdateStep::LatestRemoteCommitmentTXInfo { + unsigned_commitment_tx: Readable::read(r)?, + commitment_number: Readable::read(r)?, + their_revocation_point: Readable::read(r)?, + htlc_outputs: { + let len: u64 = Readable::read(r)?; + let mut res = Vec::new(); + for _ in 0..len { + res.push((Readable::read(r)?, as Readable>::read(r)?.map(|o| Box::new(o)))); + } + res + }, + }) + }, + 2u8 => { + Ok(ChannelMonitorUpdateStep::PaymentPreimage { + payment_preimage: Readable::read(r)?, + }) + }, + 3u8 => { + Ok(ChannelMonitorUpdateStep::CommitmentSecret { + idx: Readable::read(r)?, + secret: Readable::read(r)?, + }) + }, + 4u8 => { + Ok(ChannelMonitorUpdateStep::RescueRemoteCommitmentTXInfo { + their_current_per_commitment_point: Readable::read(r)?, + }) + }, + _ => Err(DecodeError::InvalidValue), + } + } +} + /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates /// on-chain transactions to ensure no loss of funds occurs. /// /// 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 { + latest_update_id: u64, commitment_transaction_number_obscure_factor: u64, - key_storage: Storage, + key_storage: Storage, their_htlc_base_key: Option, their_delayed_payment_base_key: Option, + funding_redeemscript: Option