+ pub fn send_update_fee_and_commit(&mut self, feerate_per_kw: u64) -> Result<Option<(msgs::UpdateFee, msgs::CommitmentSigned, ChannelMonitor)>, HandleError> {
+ match self.send_update_fee(feerate_per_kw) {
+ Some(update_fee) => {
+ let (commitment_signed, monitor_update) = self.send_commitment_no_status_check()?;
+ Ok(Some((update_fee, commitment_signed, monitor_update)))
+ },
+ None => Ok(None)
+ }
+ }
+
+ /// Removes any uncommitted HTLCs, to be used on peer disconnection, including any pending
+ /// HTLCs that we intended to add but haven't as we were waiting on a remote revoke.
+ /// Returns the set of PendingHTLCStatuses from remote uncommitted HTLCs (which we're
+ /// implicitly dropping) and the payment_hashes of HTLCs we tried to add but are dropping.
+ /// No further message handling calls may be made until a channel_reestablish dance has
+ /// completed.
+ pub fn remove_uncommitted_htlcs_and_mark_paused(&mut self) -> Vec<(HTLCSource, [u8; 32])> {
+ let mut outbound_drops = Vec::new();
+
+ assert_eq!(self.channel_state & ChannelState::ShutdownComplete as u32, 0);
+ if self.channel_state < ChannelState::FundingSent as u32 {
+ self.channel_state = ChannelState::ShutdownComplete as u32;
+ return outbound_drops;
+ }
+ // Upon reconnect we have to start the closing_signed dance over, but shutdown messages
+ // will be retransmitted.
+ self.last_sent_closing_fee = None;
+
+ let mut inbound_drop_count = 0;
+ self.pending_inbound_htlcs.retain(|htlc| {
+ match htlc.state {
+ InboundHTLCState::RemoteAnnounced(_) => {
+ // They sent us an update_add_htlc but we never got the commitment_signed.
+ // We'll tell them what commitment_signed we're expecting next and they'll drop
+ // this HTLC accordingly
+ inbound_drop_count += 1;
+ false
+ },
+ InboundHTLCState::AwaitingRemoteRevokeToAnnounce(_)|InboundHTLCState::AwaitingAnnouncedRemoteRevoke(_) => {
+ // We received a commitment_signed updating this HTLC and (at least hopefully)
+ // sent a revoke_and_ack (which we can re-transmit) and have heard nothing
+ // in response to it yet, so don't touch it.
+ true
+ },
+ InboundHTLCState::Committed => true,
+ InboundHTLCState::LocalRemoved(_) => {
+ // We (hopefully) sent a commitment_signed updating this HTLC (which we can
+ // re-transmit if needed) and they may have even sent a revoke_and_ack back
+ // (that we missed). Keep this around for now and if they tell us they missed
+ // the commitment_signed we can re-transmit the update then.
+ true
+ },
+ }
+ });
+ self.next_remote_htlc_id -= inbound_drop_count;
+
+ for htlc in self.pending_outbound_htlcs.iter_mut() {
+ if let OutboundHTLCState::RemoteRemoved = htlc.state {
+ // They sent us an update to remove this but haven't yet sent the corresponding
+ // commitment_signed, we need to move it back to Committed and they can re-send
+ // the update upon reconnection.
+ htlc.state = OutboundHTLCState::Committed;
+ }
+ }
+
+ self.holding_cell_htlc_updates.retain(|htlc_update| {
+ match htlc_update {
+ &HTLCUpdateAwaitingACK::AddHTLC { ref payment_hash, ref source, .. } => {
+ outbound_drops.push((source.clone(), payment_hash.clone()));
+ false
+ },
+ &HTLCUpdateAwaitingACK::ClaimHTLC {..} | &HTLCUpdateAwaitingACK::FailHTLC {..} => true,
+ }
+ });
+ self.channel_state |= ChannelState::PeerDisconnected as u32;
+ log_debug!(self, "Peer disconnection resulted in {} remote-announced HTLC drops and {} waiting-to-locally-announced HTLC drops on channel {}", outbound_drops.len(), inbound_drop_count, log_bytes!(self.channel_id()));
+ outbound_drops
+ }
+
+ /// Indicates that a ChannelMonitor update failed to be stored by the client and further
+ /// updates are partially paused.
+ /// This must be called immediately after the call which generated the ChannelMonitor update
+ /// which failed, with the order argument set to the type of call it represented (ie a
+ /// commitment update or a revoke_and_ack generation). The messages which were generated from
+ /// that original call must *not* have been sent to the remote end, and must instead have been
+ /// dropped. They will be regenerated when monitor_updating_restored is called.
+ pub fn monitor_update_failed(&mut self, order: RAACommitmentOrder) {
+ assert_eq!(self.channel_state & ChannelState::MonitorUpdateFailed as u32, 0);
+ match order {
+ RAACommitmentOrder::CommitmentFirst => {
+ self.monitor_pending_revoke_and_ack = false;
+ self.monitor_pending_commitment_signed = true;
+ },
+ RAACommitmentOrder::RevokeAndACKFirst => {
+ self.monitor_pending_revoke_and_ack = true;
+ self.monitor_pending_commitment_signed = false;
+ },
+ }
+ self.monitor_pending_order = Some(order);
+ self.channel_state |= ChannelState::MonitorUpdateFailed as u32;
+ }
+
+ /// Indicates that the latest ChannelMonitor update has been committed by the client
+ /// successfully and we should restore normal operation. Returns messages which should be sent
+ /// to the remote side.
+ pub fn monitor_updating_restored(&mut self) -> (Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, RAACommitmentOrder, Vec<(PendingForwardHTLCInfo, u64)>, Vec<(HTLCSource, [u8; 32], HTLCFailReason)>) {
+ assert_eq!(self.channel_state & ChannelState::MonitorUpdateFailed as u32, ChannelState::MonitorUpdateFailed as u32);
+ self.channel_state &= !(ChannelState::MonitorUpdateFailed as u32);
+
+ let mut forwards = Vec::new();
+ mem::swap(&mut forwards, &mut self.monitor_pending_forwards);
+ let mut failures = Vec::new();
+ mem::swap(&mut failures, &mut self.monitor_pending_failures);
+
+ if self.channel_state & (ChannelState::PeerDisconnected as u32) != 0 {
+ // Leave monitor_pending_order so we can order our channel_reestablish responses
+ self.monitor_pending_revoke_and_ack = false;
+ self.monitor_pending_commitment_signed = false;
+ return (None, None, RAACommitmentOrder::RevokeAndACKFirst, forwards, failures);
+ }
+
+ let raa = if self.monitor_pending_revoke_and_ack {
+ Some(self.get_last_revoke_and_ack())
+ } else { None };
+ let commitment_update = if self.monitor_pending_commitment_signed {
+ Some(self.get_last_commitment_update())
+ } else { None };
+
+ self.monitor_pending_revoke_and_ack = false;
+ self.monitor_pending_commitment_signed = false;
+ (raa, commitment_update, self.monitor_pending_order.clone().unwrap(), forwards, failures)
+ }
+
+ pub fn update_fee(&mut self, fee_estimator: &FeeEstimator, msg: &msgs::UpdateFee) -> Result<(), ChannelError> {
+ if self.channel_outbound {
+ return Err(ChannelError::Close("Non-funding remote tried to update channel fee"));
+ }
+ if self.channel_state & (ChannelState::PeerDisconnected as u32) == ChannelState::PeerDisconnected as u32 {
+ return Err(ChannelError::Close("Peer sent update_fee when we needed a channel_reestablish"));
+ }
+ Channel::check_remote_fee(fee_estimator, msg.feerate_per_kw)?;
+ self.pending_update_fee = Some(msg.feerate_per_kw as u64);
+ self.channel_update_count += 1;
+ Ok(())
+ }
+
+ fn get_last_revoke_and_ack(&self) -> msgs::RevokeAndACK {
+ let next_per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &self.build_local_commitment_secret(self.cur_local_commitment_transaction_number));
+ let per_commitment_secret = chan_utils::build_commitment_secret(self.local_keys.commitment_seed, self.cur_local_commitment_transaction_number + 2);
+ msgs::RevokeAndACK {
+ channel_id: self.channel_id,
+ per_commitment_secret,
+ next_per_commitment_point,
+ }
+ }
+
+ fn get_last_commitment_update(&self) -> msgs::CommitmentUpdate {
+ let mut update_add_htlcs = Vec::new();
+ let mut update_fulfill_htlcs = Vec::new();
+ let mut update_fail_htlcs = Vec::new();
+ let mut update_fail_malformed_htlcs = Vec::new();
+
+ for htlc in self.pending_outbound_htlcs.iter() {
+ if let &OutboundHTLCState::LocalAnnounced(ref onion_packet) = &htlc.state {
+ update_add_htlcs.push(msgs::UpdateAddHTLC {
+ channel_id: self.channel_id(),
+ htlc_id: htlc.htlc_id,
+ amount_msat: htlc.amount_msat,
+ payment_hash: htlc.payment_hash,
+ cltv_expiry: htlc.cltv_expiry,
+ onion_routing_packet: (**onion_packet).clone(),
+ });
+ }
+ }
+
+ for htlc in self.pending_inbound_htlcs.iter() {
+ if let &InboundHTLCState::LocalRemoved(ref reason) = &htlc.state {
+ match reason {
+ &InboundHTLCRemovalReason::FailRelay(ref err_packet) => {
+ update_fail_htlcs.push(msgs::UpdateFailHTLC {
+ channel_id: self.channel_id(),
+ htlc_id: htlc.htlc_id,
+ reason: err_packet.clone()
+ });
+ },
+ &InboundHTLCRemovalReason::FailMalformed((ref sha256_of_onion, ref failure_code)) => {
+ update_fail_malformed_htlcs.push(msgs::UpdateFailMalformedHTLC {
+ channel_id: self.channel_id(),
+ htlc_id: htlc.htlc_id,
+ sha256_of_onion: sha256_of_onion.clone(),
+ failure_code: failure_code.clone(),
+ });
+ },
+ &InboundHTLCRemovalReason::Fulfill(ref payment_preimage) => {
+ update_fulfill_htlcs.push(msgs::UpdateFulfillHTLC {
+ channel_id: self.channel_id(),
+ htlc_id: htlc.htlc_id,
+ payment_preimage: payment_preimage.clone(),
+ });
+ },
+ }
+ }
+ }
+
+ msgs::CommitmentUpdate {
+ update_add_htlcs, update_fulfill_htlcs, update_fail_htlcs, update_fail_malformed_htlcs,
+ update_fee: None, //TODO: We need to support re-generating any update_fees in the last commitment_signed!
+ commitment_signed: self.send_commitment_no_state_update().expect("It looks like we failed to re-generate a commitment_signed we had previously sent?").0,
+ }
+ }
+
+ /// May panic if some calls other than message-handling calls (which will all Err immediately)
+ /// have been called between remove_uncommitted_htlcs_and_mark_paused and this call.
+ pub fn channel_reestablish(&mut self, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>, Option<ChannelMonitor>, RAACommitmentOrder, Option<msgs::Shutdown>), ChannelError> {
+ if self.channel_state & (ChannelState::PeerDisconnected as u32) == 0 {
+ // While BOLT 2 doesn't indicate explicitly we should error this channel here, it
+ // almost certainly indicates we are going to end up out-of-sync in some way, so we
+ // just close here instead of trying to recover.
+ return Err(ChannelError::Close("Peer sent a loose channel_reestablish not after reconnect"));
+ }
+
+ if msg.next_local_commitment_number >= INITIAL_COMMITMENT_NUMBER || msg.next_remote_commitment_number >= INITIAL_COMMITMENT_NUMBER {
+ return Err(ChannelError::Close("Peer sent a garbage channel_reestablish"));
+ }
+
+ // Go ahead and unmark PeerDisconnected as various calls we may make check for it (and all
+ // remaining cases either succeed or ErrorMessage-fail).
+ self.channel_state &= !(ChannelState::PeerDisconnected as u32);
+
+ let shutdown_msg = if self.channel_state & (ChannelState::LocalShutdownSent as u32) != 0 {
+ Some(msgs::Shutdown {
+ channel_id: self.channel_id,
+ scriptpubkey: self.get_closing_scriptpubkey(),
+ })
+ } else { None };
+
+ if self.channel_state & (ChannelState::FundingSent as u32 | ChannelState::OurFundingLocked as u32) == ChannelState::FundingSent as u32 {
+ // Short circuit the whole handler as there is nothing we can resend them
+ return Ok((None, None, None, None, RAACommitmentOrder::CommitmentFirst, shutdown_msg));
+ }
+
+ if msg.next_local_commitment_number == 0 || msg.next_remote_commitment_number == 0 {
+ if self.channel_state & (ChannelState::FundingSent as u32) != ChannelState::FundingSent as u32 {
+ return Err(ChannelError::Close("Peer sent a pre-funding channel_reestablish after we exchanged funding_locked"));
+ }
+ // We have OurFundingLocked set!
+ let next_per_commitment_secret = self.build_local_commitment_secret(self.cur_local_commitment_transaction_number);
+ let next_per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &next_per_commitment_secret);
+ return Ok((Some(msgs::FundingLocked {
+ channel_id: self.channel_id(),
+ next_per_commitment_point: next_per_commitment_point,
+ }), None, None, None, RAACommitmentOrder::CommitmentFirst, shutdown_msg));
+ }
+
+ let required_revoke = if msg.next_remote_commitment_number == INITIAL_COMMITMENT_NUMBER - self.cur_local_commitment_transaction_number {
+ // Remote isn't waiting on any RevokeAndACK from us!
+ // Note that if we need to repeat our FundingLocked we'll do that in the next if block.
+ None
+ } else if msg.next_remote_commitment_number == (INITIAL_COMMITMENT_NUMBER - 1) - self.cur_local_commitment_transaction_number {
+ if self.channel_state & (ChannelState::MonitorUpdateFailed as u32) != 0 {
+ self.monitor_pending_revoke_and_ack = true;
+ None
+ } else {
+ Some(self.get_last_revoke_and_ack())
+ }
+ } else {
+ return Err(ChannelError::Close("Peer attempted to reestablish channel with a very old local commitment transaction"));
+ };
+
+ // We increment cur_remote_commitment_transaction_number only upon receipt of
+ // revoke_and_ack, not on sending commitment_signed, so we add one if have
+ // AwaitingRemoteRevoke set, which indicates we sent a commitment_signed but haven't gotten
+ // the corresponding revoke_and_ack back yet.
+ let our_next_remote_commitment_number = INITIAL_COMMITMENT_NUMBER - self.cur_remote_commitment_transaction_number + if (self.channel_state & ChannelState::AwaitingRemoteRevoke as u32) != 0 { 1 } else { 0 };
+
+ let resend_funding_locked = if msg.next_local_commitment_number == 1 && INITIAL_COMMITMENT_NUMBER - self.cur_local_commitment_transaction_number == 1 {
+ // We should never have to worry about MonitorUpdateFailed resending FundingLocked
+ let next_per_commitment_secret = self.build_local_commitment_secret(self.cur_local_commitment_transaction_number);
+ let next_per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &next_per_commitment_secret);
+ Some(msgs::FundingLocked {
+ channel_id: self.channel_id(),
+ next_per_commitment_point: next_per_commitment_point,
+ })
+ } else { None };
+
+ let order = self.monitor_pending_order.clone().unwrap_or(if self.received_commitment_while_awaiting_raa {
+ RAACommitmentOrder::CommitmentFirst
+ } else {
+ RAACommitmentOrder::RevokeAndACKFirst
+ });
+
+ if msg.next_local_commitment_number == our_next_remote_commitment_number {
+ if required_revoke.is_some() {
+ log_debug!(self, "Reconnected channel {} with only lost outbound RAA", log_bytes!(self.channel_id()));
+ } else {
+ log_debug!(self, "Reconnected channel {} with no loss", log_bytes!(self.channel_id()));
+ }
+
+ if (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32 | ChannelState::MonitorUpdateFailed as u32)) == 0 &&
+ self.monitor_pending_order.is_none() { // monitor_pending_order indicates we're waiting on a response to a unfreeze
+ // We're up-to-date and not waiting on a remote revoke (if we are our
+ // channel_reestablish should result in them sending a revoke_and_ack), but we may
+ // have received some updates while we were disconnected. Free the holding cell
+ // now!
+ match self.free_holding_cell_htlcs() {
+ Err(e) => {
+ if let &Some(msgs::ErrorAction::DisconnectPeer{msg: Some(_)}) = &e.action {
+ return Err(ChannelError::Close(e.err));
+ } else if let &Some(msgs::ErrorAction::SendErrorMessage{msg: _}) = &e.action {
+ return Err(ChannelError::Close(e.err));
+ } else {
+ panic!("Got non-channel-failing result from free_holding_cell_htlcs");
+ }
+ },
+ Ok(Some((commitment_update, channel_monitor))) => return Ok((resend_funding_locked, required_revoke, Some(commitment_update), Some(channel_monitor), order, shutdown_msg)),
+ Ok(None) => return Ok((resend_funding_locked, required_revoke, None, None, order, shutdown_msg)),
+ }
+ } else {
+ return Ok((resend_funding_locked, required_revoke, None, None, order, shutdown_msg));
+ }
+ } else if msg.next_local_commitment_number == our_next_remote_commitment_number - 1 {
+ if required_revoke.is_some() {
+ log_debug!(self, "Reconnected channel {} with lost outbound RAA and lost remote commitment tx", log_bytes!(self.channel_id()));
+ } else {
+ log_debug!(self, "Reconnected channel {} with only lost remote commitment tx", log_bytes!(self.channel_id()));
+ }
+
+ // If monitor_pending_order is set, it must be CommitmentSigned if we have no RAA
+ debug_assert!(self.monitor_pending_order != Some(RAACommitmentOrder::RevokeAndACKFirst) || required_revoke.is_some());
+
+ if self.channel_state & (ChannelState::MonitorUpdateFailed as u32) != 0 {
+ self.monitor_pending_commitment_signed = true;
+ return Ok((resend_funding_locked, None, None, None, order, shutdown_msg));
+ }
+
+ return Ok((resend_funding_locked, required_revoke, Some(self.get_last_commitment_update()), None, order, shutdown_msg));
+ } else {
+ return Err(ChannelError::Close("Peer attempted to reestablish channel with a very old remote commitment transaction"));
+ }
+ }
+
+ fn maybe_propose_first_closing_signed(&mut self, fee_estimator: &FeeEstimator) -> Option<msgs::ClosingSigned> {
+ if !self.channel_outbound || !self.pending_inbound_htlcs.is_empty() || !self.pending_outbound_htlcs.is_empty() ||
+ self.channel_state & (BOTH_SIDES_SHUTDOWN_MASK | ChannelState::AwaitingRemoteRevoke as u32) != BOTH_SIDES_SHUTDOWN_MASK ||
+ self.last_sent_closing_fee.is_some() ||
+ self.cur_remote_commitment_transaction_number != self.cur_local_commitment_transaction_number{
+ return None;
+ }
+
+ let mut proposed_feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background);
+ if self.feerate_per_kw > proposed_feerate {
+ proposed_feerate = self.feerate_per_kw;
+ }
+ let tx_weight = Self::get_closing_transaction_weight(&self.get_closing_scriptpubkey(), self.their_shutdown_scriptpubkey.as_ref().unwrap());
+ let proposed_total_fee_satoshis = proposed_feerate * tx_weight / 1000;
+
+ let (closing_tx, total_fee_satoshis) = self.build_closing_transaction(proposed_total_fee_satoshis, false);
+ let funding_redeemscript = self.get_funding_redeemscript();
+ let sighash = Message::from_slice(&bip143::SighashComponents::new(&closing_tx).sighash_all(&closing_tx.input[0], &funding_redeemscript, self.channel_value_satoshis)[..]).unwrap();
+
+ self.last_sent_closing_fee = Some((proposed_feerate, total_fee_satoshis));
+ Some(msgs::ClosingSigned {
+ channel_id: self.channel_id,
+ fee_satoshis: total_fee_satoshis,
+ signature: self.secp_ctx.sign(&sighash, &self.local_keys.funding_key),
+ })
+ }
+
+ pub fn shutdown(&mut self, fee_estimator: &FeeEstimator, msg: &msgs::Shutdown) -> Result<(Option<msgs::Shutdown>, Option<msgs::ClosingSigned>, Vec<(HTLCSource, [u8; 32])>), ChannelError> {
+ if self.channel_state & (ChannelState::PeerDisconnected as u32) == ChannelState::PeerDisconnected as u32 {
+ return Err(ChannelError::Close("Peer sent shutdown when we needed a channel_reestablish"));
+ }
+ if self.channel_state < ChannelState::FundingSent as u32 {
+ // Spec says we should fail the connection, not the channel, but that's nonsense, there
+ // are plenty of reasons you may want to fail a channel pre-funding, and spec says you
+ // can do that via error message without getting a connection fail anyway...
+ return Err(ChannelError::Close("Peer sent shutdown pre-funding generation"));
+ }
+ for htlc in self.pending_inbound_htlcs.iter() {
+ if let InboundHTLCState::RemoteAnnounced(_) = htlc.state {
+ return Err(ChannelError::Close("Got shutdown with remote pending HTLCs"));
+ }
+ }
+ assert_eq!(self.channel_state & ChannelState::ShutdownComplete as u32, 0);
+
+ // BOLT 2 says we must only send a scriptpubkey of certain standard forms, which are up to
+ // 34 bytes in length, so dont let the remote peer feed us some super fee-heavy script.
+ if self.channel_outbound && msg.scriptpubkey.len() > 34 {
+ return Err(ChannelError::Close("Got shutdown_scriptpubkey of absurd length from remote peer"));
+ }
+
+ //Check shutdown_scriptpubkey form as BOLT says we must
+ if !msg.scriptpubkey.is_p2pkh() && !msg.scriptpubkey.is_p2sh() && !msg.scriptpubkey.is_v0_p2wpkh() && !msg.scriptpubkey.is_v0_p2wsh() {
+ return Err(ChannelError::Close("Got a nonstandard scriptpubkey from remote peer"));
+ }
+
+ if self.their_shutdown_scriptpubkey.is_some() {
+ if Some(&msg.scriptpubkey) != self.their_shutdown_scriptpubkey.as_ref() {
+ return Err(ChannelError::Close("Got shutdown request with a scriptpubkey which did not match their previous scriptpubkey"));
+ }
+ } else {
+ self.their_shutdown_scriptpubkey = Some(msg.scriptpubkey.clone());
+ }