Fail HTLC backwards on unrevoked remote commitment tx broadcast
[rust-lightning] / src / ln / channel.rs
index 1e5c38b45968d83dc2c9b568d8e68a56161e6327..ddfb809ccdeaf6f7b542c0c08e2850f7646a80cf 100644 (file)
@@ -2,16 +2,18 @@ use bitcoin::blockdata::block::BlockHeader;
 use bitcoin::blockdata::script::{Script,Builder};
 use bitcoin::blockdata::transaction::{TxIn, TxOut, Transaction, SigHashType};
 use bitcoin::blockdata::opcodes;
-use bitcoin::util::hash::{BitcoinHash, Sha256dHash, Hash160};
+use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
 use bitcoin::util::bip143;
 use bitcoin::consensus::encode::{self, Encodable, Decodable};
 
+use bitcoin_hashes::{Hash, HashEngine};
+use bitcoin_hashes::sha256::Hash as Sha256;
+use bitcoin_hashes::hash160::Hash as Hash160;
+
 use secp256k1::key::{PublicKey,SecretKey};
 use secp256k1::{Secp256k1,Message,Signature};
 use secp256k1;
 
-use crypto::digest::Digest;
-
 use ln::msgs;
 use ln::msgs::DecodeError;
 use ln::channelmonitor::ChannelMonitor;
@@ -23,7 +25,6 @@ use chain::transaction::OutPoint;
 use chain::keysinterface::{ChannelKeys, KeysInterface};
 use util::{transaction_utils,rng};
 use util::ser::{Readable, ReadableArgs, Writeable, Writer, WriterWriteAdaptor};
-use util::sha2::Sha256;
 use util::logger::Logger;
 use util::errors::APIError;
 use util::config::{UserConfig,ChannelConfig};
@@ -314,6 +315,9 @@ pub(super) struct Channel {
        funding_tx_confirmations: u64,
 
        their_dust_limit_satoshis: u64,
+       #[cfg(test)]
+       pub(super) our_dust_limit_satoshis: u64,
+       #[cfg(not(test))]
        our_dust_limit_satoshis: u64,
        their_max_htlc_value_in_flight_msat: u64,
        //get_our_max_htlc_value_in_flight_msat(): u64,
@@ -345,7 +349,7 @@ pub(super) struct Channel {
        logger: Arc<Logger>,
 }
 
-const OUR_MAX_HTLCS: u16 = 5; //TODO
+const OUR_MAX_HTLCS: u16 = 50; //TODO
 /// Confirmation count threshold at which we close a channel. Ideally we'd keep the channel around
 /// on ice until the funding transaction gets more confirmations, but the LN protocol doesn't
 /// really allow for this, so instead we're stuck closing it out at that point.
@@ -722,7 +726,7 @@ impl Channel {
        // Utilities to build transactions:
 
        fn get_commitment_transaction_number_obscure_factor(&self) -> u64 {
-               let mut sha = Sha256::new();
+               let mut sha = Sha256::engine();
                let our_payment_basepoint = PublicKey::from_secret_key(&self.secp_ctx, &self.local_keys.payment_base_key);
 
                if self.channel_outbound {
@@ -732,8 +736,7 @@ impl Channel {
                        sha.input(&self.their_payment_basepoint.unwrap().serialize());
                        sha.input(&our_payment_basepoint.serialize());
                }
-               let mut res = [0; 32];
-               sha.result(&mut res);
+               let res = Sha256::from_engine(sha).into_inner();
 
                ((res[26] as u64) << 5*8) |
                ((res[27] as u64) << 4*8) |
@@ -907,7 +910,7 @@ impl Channel {
                if value_to_b >= (dust_limit_satoshis as i64) {
                        txouts.push((TxOut {
                                script_pubkey: Builder::new().push_opcode(opcodes::All::OP_PUSHBYTES_0)
-                                                            .push_slice(&Hash160::from_data(&keys.b_payment_key.serialize())[..])
+                                                            .push_slice(&Hash160::hash(&keys.b_payment_key.serialize())[..])
                                                             .into_script(),
                                value: value_to_b as u64
                        }, None));
@@ -940,7 +943,7 @@ impl Channel {
 
        #[inline]
        fn get_closing_scriptpubkey(&self) -> Script {
-               let our_channel_close_key_hash = Hash160::from_data(&self.shutdown_pubkey.serialize());
+               let our_channel_close_key_hash = Hash160::hash(&self.shutdown_pubkey.serialize());
                Builder::new().push_opcode(opcodes::All::OP_PUSHBYTES_0).push_slice(&our_channel_close_key_hash[..]).into_script()
        }
 
@@ -1151,10 +1154,7 @@ impl Channel {
                }
                assert_eq!(self.channel_state & ChannelState::ShutdownComplete as u32, 0);
 
-               let mut sha = Sha256::new();
-               sha.input(&payment_preimage_arg.0[..]);
-               let mut payment_hash_calc = PaymentHash([0; 32]);
-               sha.result(&mut payment_hash_calc.0[..]);
+               let payment_hash_calc = PaymentHash(Sha256::hash(&payment_preimage_arg.0[..]).into_inner());
 
                // ChannelManager may generate duplicate claims/fails due to HTLC update events from
                // on-chain ChannelsMonitors during block rescan. Ideally we'd figure out a way to drop
@@ -1314,16 +1314,6 @@ impl Channel {
                }))
        }
 
-       pub fn get_update_fail_htlc_and_commit(&mut self, htlc_id: u64, err_packet: msgs::OnionErrorPacket) -> Result<Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned, ChannelMonitor)>, ChannelError> {
-               match self.get_update_fail_htlc(htlc_id, err_packet)? {
-                       Some(update_fail_htlc) => {
-                               let (commitment, monitor_update) = self.send_commitment_no_status_check()?;
-                               Ok(Some((update_fail_htlc, commitment, monitor_update)))
-                       },
-                       None => Ok(None)
-               }
-       }
-
        // Message handlers:
 
        pub fn accept_channel(&mut self, msg: &msgs::AcceptChannel, config: &UserConfig) -> Result<(), ChannelError> {
@@ -1650,11 +1640,7 @@ impl Channel {
                        return Err(ChannelError::Close("Peer sent update_fulfill_htlc when we needed a channel_reestablish"));
                }
 
-               let mut sha = Sha256::new();
-               sha.input(&msg.payment_preimage.0[..]);
-               let mut payment_hash = PaymentHash([0; 32]);
-               sha.result(&mut payment_hash.0[..]);
-
+               let payment_hash = PaymentHash(Sha256::hash(&msg.payment_preimage.0[..]).into_inner());
                self.mark_outbound_htlc_removed(msg.htlc_id, Some(payment_hash), None).map(|source| source.clone())
        }
 
@@ -3132,6 +3118,7 @@ impl Channel {
        /// waiting on the remote peer to send us a revoke_and_ack during which time we cannot add new
        /// HTLCs on the wire or we wouldn't be able to determine what they actually ACK'ed.
        /// You MUST call send_commitment prior to any other calls on this Channel
+       /// If an Err is returned, its a ChannelError::Ignore!
        pub fn send_htlc(&mut self, amount_msat: u64, payment_hash: PaymentHash, cltv_expiry: u32, source: HTLCSource, onion_routing_packet: msgs::OnionPacket) -> Result<Option<msgs::UpdateAddHTLC>, ChannelError> {
                if (self.channel_state & (ChannelState::ChannelFunded as u32 | BOTH_SIDES_SHUTDOWN_MASK)) != (ChannelState::ChannelFunded as u32) {
                        return Err(ChannelError::Ignore("Cannot send HTLC until channel is fully established and we haven't started shutting down"));
@@ -3243,6 +3230,12 @@ impl Channel {
                        }
                        if have_updates { break; }
                }
+               for htlc in self.pending_inbound_htlcs.iter() {
+                       if let InboundHTLCState::LocalRemoved(_) = htlc.state {
+                               have_updates = true;
+                       }
+                       if have_updates { break; }
+               }
                if !have_updates {
                        panic!("Cannot create commitment tx until we have some updates to send");
                }
@@ -3927,8 +3920,8 @@ mod tests {
        use util::logger::Logger;
        use secp256k1::{Secp256k1,Message,Signature};
        use secp256k1::key::{SecretKey,PublicKey};
-       use crypto::sha2::Sha256;
-       use crypto::digest::Digest;
+       use bitcoin_hashes::sha256::Hash as Sha256;
+       use bitcoin_hashes::Hash;
        use std::sync::Arc;
 
        struct TestFeeEstimator {
@@ -4054,12 +4047,7 @@ mod tests {
                                let mut preimage: Option<PaymentPreimage> = None;
                                if !htlc.offered {
                                        for i in 0..5 {
-                                               let mut sha = Sha256::new();
-                                               sha.input(&[i; 32]);
-
-                                               let mut out = PaymentHash([0; 32]);
-                                               sha.result(&mut out.0[..]);
-
+                                               let out = PaymentHash(Sha256::hash(&[i; 32]).into_inner());
                                                if out == htlc.payment_hash {
                                                        preimage = Some(PaymentPreimage([i; 32]));
                                                }
@@ -4091,9 +4079,7 @@ mod tests {
                                payment_hash: PaymentHash([0; 32]),
                                state: InboundHTLCState::Committed,
                        };
-                       let mut sha = Sha256::new();
-                       sha.input(&hex::decode("0000000000000000000000000000000000000000000000000000000000000000").unwrap());
-                       sha.result(&mut out.payment_hash.0[..]);
+                       out.payment_hash.0 = Sha256::hash(&hex::decode("0000000000000000000000000000000000000000000000000000000000000000").unwrap()).into_inner();
                        out
                });
                chan.pending_inbound_htlcs.push({
@@ -4104,9 +4090,7 @@ mod tests {
                                payment_hash: PaymentHash([0; 32]),
                                state: InboundHTLCState::Committed,
                        };
-                       let mut sha = Sha256::new();
-                       sha.input(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap());
-                       sha.result(&mut out.payment_hash.0[..]);
+                       out.payment_hash.0 = Sha256::hash(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()).into_inner();
                        out
                });
                chan.pending_outbound_htlcs.push({
@@ -4119,9 +4103,7 @@ mod tests {
                                source: HTLCSource::dummy(),
                                fail_reason: None,
                        };
-                       let mut sha = Sha256::new();
-                       sha.input(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap());
-                       sha.result(&mut out.payment_hash.0[..]);
+                       out.payment_hash.0 = Sha256::hash(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()).into_inner();
                        out
                });
                chan.pending_outbound_htlcs.push({
@@ -4134,9 +4116,7 @@ mod tests {
                                source: HTLCSource::dummy(),
                                fail_reason: None,
                        };
-                       let mut sha = Sha256::new();
-                       sha.input(&hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap());
-                       sha.result(&mut out.payment_hash.0[..]);
+                       out.payment_hash.0 = Sha256::hash(&hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()).into_inner();
                        out
                });
                chan.pending_inbound_htlcs.push({
@@ -4147,9 +4127,7 @@ mod tests {
                                payment_hash: PaymentHash([0; 32]),
                                state: InboundHTLCState::Committed,
                        };
-                       let mut sha = Sha256::new();
-                       sha.input(&hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap());
-                       sha.result(&mut out.payment_hash.0[..]);
+                       out.payment_hash.0 = Sha256::hash(&hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()).into_inner();
                        out
                });