Fix fuzzing issue with revocation
[rust-lightning] / lightning / src / util / enforcing_trait_impls.rs
index 92cf178c8c5d912a61e21a6e0d24f778ece99e7c..af497cbbe5bf2c65675873cd83c2ff96adcbef09 100644 (file)
@@ -24,6 +24,9 @@ use util::ser::{Writeable, Writer, Readable};
 use std::io::Error;
 use ln::msgs::DecodeError;
 
+/// Initial value for revoked commitment downward counter
+pub const INITIAL_REVOKED_COMMITMENT_NUMBER: u64 = 1 << 48;
+
 /// An implementation of ChannelKeys that enforces some policy checks.
 ///
 /// Eventually we will probably want to expose a variant of this which would essentially
@@ -31,7 +34,8 @@ use ln::msgs::DecodeError;
 #[derive(Clone)]
 pub struct EnforcingChannelKeys {
        pub inner: InMemoryChannelKeys,
-       last_commitment_number: Arc<Mutex<Option<u64>>>,
+       pub last_commitment_number: Arc<Mutex<Option<u64>>>,
+       pub revoked_commitment: Arc<Mutex<u64>>,
 }
 
 impl EnforcingChannelKeys {
@@ -39,6 +43,15 @@ impl EnforcingChannelKeys {
                Self {
                        inner,
                        last_commitment_number: Arc::new(Mutex::new(None)),
+                       revoked_commitment: Arc::new(Mutex::new(INITIAL_REVOKED_COMMITMENT_NUMBER))
+               }
+       }
+
+       pub fn new_with_revoked(inner: InMemoryChannelKeys, revoked_commitment: Arc<Mutex<u64>>) -> Self {
+               Self {
+                       inner,
+                       last_commitment_number: Arc::new(Mutex::new(None)),
+                       revoked_commitment
                }
        }
 }
@@ -49,7 +62,13 @@ impl ChannelKeys for EnforcingChannelKeys {
        }
 
        fn release_commitment_secret(&self, idx: u64) -> [u8; 32] {
-               // TODO: enforce the ChannelKeys contract - error here if we already signed this commitment
+               println!("XXX revoke {} for {}", idx, self.inner.commitment_seed[0]);
+
+               {
+                       let mut revoked = self.revoked_commitment.lock().unwrap();
+                       assert!(idx == *revoked || idx == *revoked - 1, "can only revoke the current or next unrevoked commitment - trying {}, revoked {}", idx, *revoked);
+                       *revoked = idx;
+               }
                self.inner.release_commitment_secret(idx)
        }
 
@@ -72,24 +91,20 @@ impl ChannelKeys for EnforcingChannelKeys {
                Ok(self.inner.sign_counterparty_commitment(commitment_tx, secp_ctx).unwrap())
        }
 
-       fn sign_holder_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
-               self.verify_holder_commitment_tx(commitment_tx, secp_ctx);
-
-               // TODO: enforce the ChannelKeys contract - error if this commitment was already revoked
-               // TODO: need the commitment number
-               Ok(self.inner.sign_holder_commitment(commitment_tx, secp_ctx).unwrap())
-       }
-
-       #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
-       fn unsafe_sign_holder_commitment<T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
-               Ok(self.inner.unsafe_sign_holder_commitment(commitment_tx, secp_ctx).unwrap())
-       }
-
-       fn sign_holder_commitment_htlc_transactions<T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<Vec<Signature>, ()> {
+       fn sign_holder_commitment_and_htlcs<T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()> {
                let trusted_tx = self.verify_holder_commitment_tx(commitment_tx, secp_ctx);
                let commitment_txid = trusted_tx.txid();
                let holder_csv = self.inner.counterparty_selected_contest_delay();
 
+               let revoked = self.revoked_commitment.lock().unwrap();
+               let commitment_number = trusted_tx.commitment_number();
+               println!("XXX sign {} for {}", commitment_number, self.inner.commitment_seed[0]);
+               if *revoked - 1 != commitment_number && *revoked - 2 != commitment_number {
+                       println!("can only sign the next two unrevoked commitment numbers, revoked={} vs requested={} for {}",
+                                *revoked, commitment_number, self.inner.commitment_seed[0]);
+                       return Err(());
+               }
+
                for (this_htlc, sig) in trusted_tx.htlcs().iter().zip(&commitment_tx.counterparty_htlc_sigs) {
                        assert!(this_htlc.transaction_output_index.is_some());
                        let keys = trusted_tx.keys();
@@ -101,7 +116,14 @@ impl ChannelKeys for EnforcingChannelKeys {
                        secp_ctx.verify(&sighash, sig, &keys.countersignatory_htlc_key).unwrap();
                }
 
-               Ok(self.inner.sign_holder_commitment_htlc_transactions(commitment_tx, secp_ctx).unwrap())
+               // TODO: enforce the ChannelKeys contract - error if this commitment was already revoked
+               // TODO: need the commitment number
+               Ok(self.inner.sign_holder_commitment_and_htlcs(commitment_tx, secp_ctx).unwrap())
+       }
+
+       #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
+       fn unsafe_sign_holder_commitment_and_htlcs<T: secp256k1::Signing + secp256k1::Verification>(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()> {
+               Ok(self.inner.unsafe_sign_holder_commitment_and_htlcs(commitment_tx, secp_ctx).unwrap())
        }
 
        fn sign_justice_transaction<T: secp256k1::Signing + secp256k1::Verification>(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, htlc: &Option<HTLCOutputInCommitment>, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
@@ -137,11 +159,12 @@ impl Writeable for EnforcingChannelKeys {
 
 impl Readable for EnforcingChannelKeys {
        fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
-               let inner = Readable::read(reader)?;
+               let inner: InMemoryChannelKeys = Readable::read(reader)?;
                let last_commitment_number = Readable::read(reader)?;
                Ok(EnforcingChannelKeys {
                        inner,
-                       last_commitment_number: Arc::new(Mutex::new(last_commitment_number))
+                       last_commitment_number: Arc::new(Mutex::new(last_commitment_number)),
+                       revoked_commitment: Arc::new(Mutex::new(INITIAL_REVOKED_COMMITMENT_NUMBER)),
                })
        }
 }