X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning%2Fsrc%2Fln%2Fchannelmanager.rs;h=353de9240cc3007a010b73d01f4853e9a2c6d909;hb=6cd6816cd7efce593ef487d07adfff66cee0daa2;hp=cc15861f8772f4556ad2600b431c6b4a54a95a26;hpb=00d063df5c46ef313901f2a69cff8ffe2cf8cb55;p=rust-lightning diff --git a/lightning/src/ln/channelmanager.rs b/lightning/src/ln/channelmanager.rs index cc15861f..353de924 100644 --- a/lightning/src/ln/channelmanager.rs +++ b/lightning/src/ln/channelmanager.rs @@ -18,7 +18,6 @@ //! imply it needs to fail HTLCs/payments/channels it manages). use bitcoin::blockdata::block::BlockHeader; -use bitcoin::blockdata::transaction::Transaction; use bitcoin::blockdata::constants::genesis_block; use bitcoin::network::constants::Network; @@ -34,10 +33,12 @@ use bitcoin::secp256k1::Secp256k1; use bitcoin::secp256k1::ecdh::SharedSecret; use bitcoin::secp256k1; -use chain::chaininterface::{BroadcasterInterface,ChainListener,FeeEstimator}; -use chain::transaction::OutPoint; +use chain; +use chain::Watch; +use chain::chaininterface::{BroadcasterInterface, FeeEstimator}; +use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent}; +use chain::transaction::{OutPoint, TransactionData}; use ln::channel::{Channel, ChannelError}; -use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, ManyChannelMonitor, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent}; use ln::features::{InitFeatures, NodeFeatures}; use routing::router::{Route, RouteHop}; use ln::msgs; @@ -128,7 +129,7 @@ pub(super) enum HTLCForwardInfo { /// Tracks the inbound corresponding to an outbound HTLC #[derive(Clone, PartialEq)] -pub(super) struct HTLCPreviousHopData { +pub(crate) struct HTLCPreviousHopData { short_channel_id: u64, htlc_id: u64, incoming_packet_shared_secret: [u8; 32], @@ -147,7 +148,7 @@ struct ClaimableHTLC { /// Tracks the inbound corresponding to an outbound HTLC #[derive(Clone, PartialEq)] -pub(super) enum HTLCSource { +pub(crate) enum HTLCSource { PreviousHopData(HTLCPreviousHopData), OutboundRoute { path: Vec, @@ -360,7 +361,7 @@ pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L> = ChannelManage /// /// Note that you can be a bit lazier about writing out ChannelManager than you can be with /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before -/// returning from ManyChannelMonitor::add_/update_monitor, with ChannelManagers, writing updates +/// returning from chain::Watch::watch_/update_channel, with ChannelManagers, writing updates /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during /// the serialization process). If the deserialized version is out-of-date compared to the /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the @@ -384,7 +385,7 @@ pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L> = ChannelManage /// SimpleArcChannelManager when you require a ChannelManager with a static lifetime, such as when /// you're using lightning-net-tokio. pub struct ChannelManager - where M::Target: ManyChannelMonitor, + where M::Target: chain::Watch, T::Target: BroadcasterInterface, K::Target: KeysInterface, F::Target: FeeEstimator, @@ -393,7 +394,7 @@ pub struct ChannelManager ChannelManager - where M::Target: ManyChannelMonitor, + where M::Target: chain::Watch, T::Target: BroadcasterInterface, K::Target: KeysInterface, F::Target: FeeEstimator, @@ -717,18 +718,14 @@ impl /// /// Users need to notify the new ChannelManager when a new block is connected or /// disconnected using its `block_connected` and `block_disconnected` methods. - /// However, rather than calling these methods directly, the user should register - /// the ChannelManager as a listener to the BlockNotifier and call the BlockNotifier's - /// `block_(dis)connected` methods, which will notify all registered listeners in one - /// go. - pub fn new(network: Network, fee_est: F, monitor: M, tx_broadcaster: T, logger: L, keys_manager: K, config: UserConfig, current_blockchain_height: usize) -> Self { + pub fn new(network: Network, fee_est: F, chain_monitor: M, tx_broadcaster: T, logger: L, keys_manager: K, config: UserConfig, current_blockchain_height: usize) -> Self { let secp_ctx = Secp256k1::new(); ChannelManager { default_configuration: config.clone(), genesis_hash: genesis_block(network).header.block_hash(), fee_estimator: fee_est, - monitor, + chain_monitor, tx_broadcaster, latest_block_height: AtomicUsize::new(current_blockchain_height), @@ -903,7 +900,7 @@ impl // force-closing. The monitor update on the required in-memory copy should broadcast // the latest local state, which is the best we can do anyway. Thus, it is safe to // ignore the result here. - let _ = self.monitor.update_monitor(funding_txo, monitor_update); + let _ = self.chain_monitor.update_channel(funding_txo, monitor_update); } } @@ -1228,7 +1225,7 @@ impl timestamp: chan.get_update_time_counter(), flags: (!were_node_one) as u8 | ((!chan.is_live() as u8) << 1), cltv_expiry_delta: CLTV_EXPIRY_DELTA, - htlc_minimum_msat: chan.get_holder_htlc_minimum_msat(), + htlc_minimum_msat: chan.get_counterparty_htlc_minimum_msat(), htlc_maximum_msat: OptionalField::Present(chan.get_announced_htlc_max_msat()), fee_base_msat: chan.get_holder_fee_base_msat(&self.fee_estimator), fee_proportional_millionths: chan.get_fee_proportional_millionths(), @@ -1283,7 +1280,7 @@ impl }, onion_packet, &self.logger), channel_state, chan) } { Some((update_add, commitment_signed, monitor_update)) => { - if let Err(e) = self.monitor.update_monitor(chan.get().get_funding_txo().unwrap(), monitor_update) { + if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) { maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true); // Note that MonitorUpdateFailed here indicates (per function docs) // that we will resend the commitment update once monitor updating @@ -1679,7 +1676,7 @@ impl continue; } }; - if let Err(e) = self.monitor.update_monitor(chan.get().get_funding_txo().unwrap(), monitor_update) { + if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) { handle_errors.push((chan.get().get_counterparty_node_id(), handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true))); continue; } @@ -2089,7 +2086,7 @@ impl match chan.get_mut().get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &self.logger) { Ok((msgs, monitor_option)) => { if let Some(monitor_update) = monitor_option { - if let Err(e) = self.monitor.update_monitor(chan.get().get_funding_txo().unwrap(), monitor_update) { + if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) { if was_frozen_for_monitor { assert!(msgs.is_none()); } else { @@ -2173,7 +2170,7 @@ impl /// exists largely only to prevent races between this and concurrent update_monitor calls. /// /// Thus, the anticipated use is, at a high level: - /// 1) You register a ManyChannelMonitor with this ChannelManager, + /// 1) You register a chain::Watch with this ChannelManager, /// 2) it stores each update to disk, and begins updating any remote (eg watchtower) copies of /// said ChannelMonitors as it can, returning ChannelMonitorUpdateErr::TemporaryFailures /// any time it cannot do so instantly, @@ -2314,7 +2311,7 @@ impl } fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> { - let ((funding_msg, monitor_update), mut chan) = { + let ((funding_msg, monitor), mut chan) = { let mut channel_lock = self.channel_state.lock().unwrap(); let channel_state = &mut *channel_lock; match channel_state.by_id.entry(msg.temporary_channel_id.clone()) { @@ -2328,8 +2325,8 @@ impl } }; // Because we have exclusive ownership of the channel here we can release the channel_state - // lock before add_monitor - if let Err(e) = self.monitor.add_monitor(monitor_update.get_funding_txo().0, monitor_update) { + // lock before watch_channel + if let Err(e) = self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor) { match e { ChannelMonitorUpdateErr::PermanentFailure => { // Note that we reply with the new channel_id in error messages if we gave up on the @@ -2377,7 +2374,7 @@ impl Ok(update) => update, Err(e) => try_chan_entry!(self, Err(e), channel_state, chan), }; - if let Err(e) = self.monitor.add_monitor(chan.get().get_funding_txo().unwrap(), monitor) { + if let Err(e) = self.chain_monitor.watch_channel(chan.get().get_funding_txo().unwrap(), monitor) { return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, false, false); } (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id()) @@ -2647,13 +2644,13 @@ impl Err((None, e)) => try_chan_entry!(self, Err(e), channel_state, chan), Err((Some(update), e)) => { assert!(chan.get().is_awaiting_monitor_update()); - let _ = self.monitor.update_monitor(chan.get().get_funding_txo().unwrap(), update); + let _ = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), update); try_chan_entry!(self, Err(e), channel_state, chan); unreachable!(); }, Ok(res) => res }; - if let Err(e) = self.monitor.update_monitor(chan.get().get_funding_txo().unwrap(), monitor_update) { + if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) { return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, true, commitment_signed.is_some()); //TODO: Rebroadcast closing_signed if present on monitor update restoration } @@ -2735,7 +2732,7 @@ impl let (commitment_update, pending_forwards, pending_failures, closing_signed, monitor_update, htlcs_to_fail_in) = break_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &self.fee_estimator, &self.logger), channel_state, chan); htlcs_to_fail = htlcs_to_fail_in; - if let Err(e) = self.monitor.update_monitor(chan.get().get_funding_txo().unwrap(), monitor_update) { + if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) { if was_frozen_for_monitor { assert!(commitment_update.is_none() && closing_signed.is_none() && pending_forwards.is_empty() && pending_failures.is_empty()); break Err(MsgHandleErrInternal::ignore_no_close("Previous monitor update failure prevented responses to RAA".to_owned())); @@ -2860,7 +2857,7 @@ impl let (funding_locked, revoke_and_ack, commitment_update, monitor_update_opt, mut order, shutdown) = try_chan_entry!(self, chan.get_mut().channel_reestablish(msg, &self.logger), channel_state, chan); if let Some(monitor_update) = monitor_update_opt { - if let Err(e) = self.monitor.update_monitor(chan.get().get_funding_txo().unwrap(), monitor_update) { + if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) { // channel_reestablish doesn't guarantee the order it returns is sensical // for the messages it returns, but if we're setting what messages to // re-transmit on monitor update success, we need to make sure it is sane. @@ -2947,7 +2944,7 @@ impl if let Some((update_fee, commitment_signed, monitor_update)) = break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw, &self.logger), channel_state, chan) { - if let Err(_e) = self.monitor.update_monitor(chan.get().get_funding_txo().unwrap(), monitor_update) { + if let Err(_e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) { unimplemented!(); } channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs { @@ -2973,11 +2970,11 @@ impl } } - /// Process pending events from the ManyChannelMonitor. + /// Process pending events from the `chain::Watch`. fn process_pending_monitor_events(&self) { let mut failed_channels = Vec::new(); { - for monitor_event in self.monitor.get_and_clear_pending_monitor_events() { + for monitor_event in self.chain_monitor.release_pending_monitor_events() { match monitor_event { MonitorEvent::HTLCEvent(htlc_update) => { if let Some(preimage) = htlc_update.payment_preimage { @@ -3017,7 +3014,7 @@ impl } impl MessageSendEventsProvider for ChannelManager - where M::Target: ManyChannelMonitor, + where M::Target: chain::Watch, T::Target: BroadcasterInterface, K::Target: KeysInterface, F::Target: FeeEstimator, @@ -3036,7 +3033,7 @@ impl } impl EventsProvider for ChannelManager - where M::Target: ManyChannelMonitor, + where M::Target: chain::Watch, T::Target: BroadcasterInterface, K::Target: KeysInterface, F::Target: FeeEstimator, @@ -3054,17 +3051,17 @@ impl } } -impl - ChainListener for ChannelManager - where M::Target: ManyChannelMonitor, +impl ChannelManager + where M::Target: chain::Watch, T::Target: BroadcasterInterface, K::Target: KeysInterface, F::Target: FeeEstimator, - L::Target: Logger, + L::Target: Logger, { - fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[usize]) { + /// Updates channel state based on transactions seen in a connected block. + pub fn block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) { let header_hash = header.block_hash(); - log_trace!(self.logger, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len()); + log_trace!(self.logger, "Block {} at height {} connected", header_hash, height); let _ = self.total_consistency_lock.read().unwrap(); let mut failed_channels = Vec::new(); let mut timed_out_htlcs = Vec::new(); @@ -3074,7 +3071,7 @@ impl ChannelMessageHandler for ChannelManager - where M::Target: ManyChannelMonitor, + where M::Target: chain::Watch, T::Target: BroadcasterInterface, K::Target: KeysInterface, F::Target: FeeEstimator, @@ -3652,7 +3652,7 @@ impl Readable for HTLCForwardInfo { } impl Writeable for ChannelManager - where M::Target: ManyChannelMonitor, + where M::Target: chain::Watch, T::Target: BroadcasterInterface, K::Target: KeysInterface, F::Target: FeeEstimator, @@ -3732,11 +3732,10 @@ impl - where M::Target: ManyChannelMonitor, + where M::Target: chain::Watch, T::Target: BroadcasterInterface, K::Target: KeysInterface, F::Target: FeeEstimator, @@ -3750,12 +3749,12 @@ pub struct ChannelManagerReadArgs<'a, ChanSigner: 'a + ChannelKeys, M: Deref, T: /// /// No calls to the FeeEstimator will be made during deserialization. pub fee_estimator: F, - /// The ManyChannelMonitor for use in the ChannelManager in the future. + /// The chain::Watch for use in the ChannelManager in the future. /// - /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that + /// No calls to the chain::Watch will be made during deserialization. It is assumed that /// you have deserialized ChannelMonitors separately and will add them to your - /// ManyChannelMonitor after deserializing this ChannelManager. - pub monitor: M, + /// chain::Watch after deserializing this ChannelManager. + pub chain_monitor: M, /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be /// used to broadcast the latest local commitment transactions of channels which must be @@ -3785,7 +3784,7 @@ pub struct ChannelManagerReadArgs<'a, ChanSigner: 'a + ChannelKeys, M: Deref, T: impl<'a, ChanSigner: 'a + ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManagerReadArgs<'a, ChanSigner, M, T, K, F, L> - where M::Target: ManyChannelMonitor, + where M::Target: chain::Watch, T::Target: BroadcasterInterface, K::Target: KeysInterface, F::Target: FeeEstimator, @@ -3794,10 +3793,10 @@ impl<'a, ChanSigner: 'a + ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor /// HashMap for you. This is primarily useful for C bindings where it is not practical to /// populate a HashMap directly from C. - pub fn new(keys_manager: K, fee_estimator: F, monitor: M, tx_broadcaster: T, logger: L, default_config: UserConfig, + pub fn new(keys_manager: K, fee_estimator: F, chain_monitor: M, tx_broadcaster: T, logger: L, default_config: UserConfig, mut channel_monitors: Vec<&'a mut ChannelMonitor>) -> Self { Self { - keys_manager, fee_estimator, monitor, tx_broadcaster, logger, default_config, + keys_manager, fee_estimator, chain_monitor, tx_broadcaster, logger, default_config, channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect() } } @@ -3807,7 +3806,7 @@ impl<'a, ChanSigner: 'a + ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L // SipmleArcChannelManager type: impl<'a, ChanSigner: ChannelKeys + Readable, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ReadableArgs> for (BlockHash, Arc>) - where M::Target: ManyChannelMonitor, + where M::Target: chain::Watch, T::Target: BroadcasterInterface, K::Target: KeysInterface, F::Target: FeeEstimator, @@ -3821,7 +3820,7 @@ impl<'a, ChanSigner: ChannelKeys + Readable, M: Deref, T: Deref, K: Deref, F: De impl<'a, ChanSigner: ChannelKeys + Readable, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ReadableArgs> for (BlockHash, ChannelManager) - where M::Target: ManyChannelMonitor, + where M::Target: chain::Watch, T::Target: BroadcasterInterface, K::Target: KeysInterface, F::Target: FeeEstimator, @@ -3933,7 +3932,7 @@ impl<'a, ChanSigner: ChannelKeys + Readable, M: Deref, T: Deref, K: Deref, F: De let channel_manager = ChannelManager { genesis_hash, fee_estimator: args.fee_estimator, - monitor: args.monitor, + chain_monitor: args.chain_monitor, tx_broadcaster: args.tx_broadcaster, latest_block_height: AtomicUsize::new(latest_block_height as usize),