]> git.bitcoin.ninja Git - rust-lightning/commitdiff
Move remote htlc transaction signature behind ChanSigner
authorAntoine Riard <ariard@student.42.fr>
Tue, 24 Mar 2020 19:04:36 +0000 (15:04 -0400)
committerAntoine Riard <ariard@student.42.fr>
Mon, 18 May 2020 08:49:45 +0000 (04:49 -0400)
lightning/src/chain/keysinterface.rs
lightning/src/ln/channelmonitor.rs
lightning/src/ln/onchaintx.rs
lightning/src/util/enforcing_trait_impls.rs

index 2dc42abad3ae4cb92bd6284de47c816b4a801d1f..e6255da9ef98b5ed2ecc27ee7b4a9e78701211bd 100644 (file)
@@ -25,6 +25,7 @@ use util::ser::{Writeable, Writer, Readable};
 use ln::chan_utils;
 use ln::chan_utils::{TxCreationKeys, HTLCOutputInCommitment, make_funding_redeemscript, ChannelPublicKeys, LocalCommitmentTransaction};
 use ln::msgs;
+use ln::channelmanager::PaymentPreimage;
 
 use std::sync::atomic::{AtomicUsize, Ordering};
 use std::io::Error;
@@ -267,6 +268,25 @@ pub trait ChannelKeys : Send+Clone {
        //TODO: dry-up witness_script and pass pubkeys
        fn sign_justice_transaction<T: secp256k1::Signing>(&self, justice_tx: &Transaction, input: usize, witness_script: &Script, amount: u64, per_commitment_key: &SecretKey, revocation_pubkey: &PublicKey, is_htlc: bool, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
 
+       /// Create a signature for a claiming transaction for a HTLC output on a remote commitment
+       /// transaction, either offered or received.
+       ///
+       /// HTLC transaction may claim multiples offered outputs at same time if we know preimage
+       /// for each at detection. It may be called multtiples time for same output(s) if a fee-bump
+       /// is needed with regards to an upcoming timelock expiration.
+       ///
+       /// Witness_script is either a offered or received script as defined in BOLT3 for HTLC
+       /// outputs.
+       ///
+       /// Input index is a pointer towards outpoint spent, commited by sigs (BIP 143).
+       ///
+       /// Amount is value of the output spent by this input, committed by sigs (BIP 143).
+       ///
+       /// Preimage is solution for an offered HTLC haslock. A preimage sets to None hints this
+       /// htlc_tx as timing-out funds back to us on a received output.
+       //TODO: dry-up witness_script and pass pubkeys
+       fn sign_remote_htlc_transaction<T: secp256k1::Signing>(&self, htlc_tx: &Transaction, input: usize, witness_script: &Script, amount: u64, per_commitment_point: &PublicKey, preimage: &Option<PaymentPreimage>, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
+
        /// Create a signature for a (proposed) closing transaction.
        ///
        /// Note that, due to rounding, there may be one "missing" satoshi, and either party may have
@@ -424,6 +444,15 @@ impl ChannelKeys for InMemoryChannelKeys {
                Err(())
        }
 
+       fn sign_remote_htlc_transaction<T: secp256k1::Signing>(&self, htlc_tx: &Transaction, input: usize, witness_script: &Script, amount: u64, per_commitment_point: &PublicKey, preimage: &Option<PaymentPreimage>, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
+               if let Ok(htlc_key) = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &self.htlc_base_key) {
+                       let sighash_parts = bip143::SighashComponents::new(&htlc_tx);
+                       let sighash = hash_to_message!(&sighash_parts.sighash_all(&htlc_tx.input[input], &witness_script, amount)[..]);
+                       return Ok(secp_ctx.sign(&sighash, &htlc_key))
+               }
+               Err(())
+       }
+
        fn sign_closing_transaction<T: secp256k1::Signing>(&self, closing_tx: &Transaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
                if closing_tx.input.len() != 1 { return Err(()); }
                if closing_tx.input[0].witness.len() != 0 { return Err(()); }
index 8cfbe4ee882eaada7adaf45bcad8f08d58b58a7f..8a05ed4fb8c107fd64ae1d95e12f627800e7503c 100644 (file)
@@ -441,7 +441,6 @@ pub(crate) enum InputMaterial {
        },
        RemoteHTLC {
                per_commitment_point: PublicKey,
-               key: SecretKey,
                preimage: Option<PaymentPreimage>,
                amount: u64,
                locktime: u32,
@@ -465,10 +464,9 @@ impl Writeable for InputMaterial  {
                                input_descriptor.write(writer)?;
                                writer.write_all(&byte_utils::be64_to_array(*amount))?;
                        },
-                       &InputMaterial::RemoteHTLC { ref per_commitment_point, ref key, ref preimage, ref amount, ref locktime } => {
+                       &InputMaterial::RemoteHTLC { ref per_commitment_point, ref preimage, ref amount, ref locktime } => {
                                writer.write_all(&[1; 1])?;
                                per_commitment_point.write(writer)?;
-                               key.write(writer)?;
                                preimage.write(writer)?;
                                writer.write_all(&byte_utils::be64_to_array(*amount))?;
                                writer.write_all(&byte_utils::be32_to_array(*locktime))?;
@@ -504,13 +502,11 @@ impl Readable for InputMaterial {
                        },
                        1 => {
                                let per_commitment_point = Readable::read(reader)?;
-                               let key = Readable::read(reader)?;
                                let preimage = Readable::read(reader)?;
                                let amount = Readable::read(reader)?;
                                let locktime = Readable::read(reader)?;
                                InputMaterial::RemoteHTLC {
                                        per_commitment_point,
-                                       key,
                                        preimage,
                                        amount,
                                        locktime
@@ -1565,8 +1561,6 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
                                                if revocation_points.0 == commitment_number + 1 { Some(point) } else { None }
                                        } else { None };
                                if let Some(revocation_point) = revocation_point_option {
-                                       let htlc_privkey = ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, revocation_point, &self.keys.htlc_base_key()));
-
                                        self.remote_payment_script = {
                                                // Note that the Network here is ignored as we immediately drop the address for the
                                                // script_pubkey version
@@ -1584,7 +1578,7 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
                                                        let preimage = if htlc.offered { if let Some(p) = self.payment_preimages.get(&htlc.payment_hash) { Some(*p) } else { None } } else { None };
                                                        let aggregable = if !htlc.offered { false } else { true };
                                                        if preimage.is_some() || !htlc.offered {
-                                                               let witness_data = InputMaterial::RemoteHTLC { per_commitment_point: *revocation_point, key: htlc_privkey, preimage, amount: htlc.amount_msat / 1000, locktime: htlc.cltv_expiry };
+                                                               let witness_data = InputMaterial::RemoteHTLC { per_commitment_point: *revocation_point, preimage, amount: htlc.amount_msat / 1000, locktime: htlc.cltv_expiry };
                                                                claimable_outpoints.push(ClaimRequest { absolute_timelock: htlc.cltv_expiry, aggregable, outpoint: BitcoinOutPoint { txid: commitment_txid, vout: transaction_output_index }, witness_data });
                                                        }
                                                }
index 202079ee61b0bbb706b6ab23ee51f963f8f91285..7698fa421a5eafff3910e62d1b1d592dc241c0a2 100644 (file)
@@ -6,7 +6,6 @@
 use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, SigHashType};
 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
 use bitcoin::blockdata::script::Script;
-use bitcoin::util::bip143;
 
 use bitcoin::hash_types::Txid;
 
@@ -670,7 +669,7 @@ impl<ChanSigner: ChannelKeys> OnchainTxHandler<ChanSigner> {
                                                        log_trace!(logger, "Going to broadcast Penalty Transaction {} claiming revoked {} output {} from {} with new feerate {}...", bumped_tx.txid(), if *input_descriptor == InputDescriptors::RevokedOutput { "to_local" } else if *input_descriptor == InputDescriptors::RevokedOfferedHTLC { "offered" } else if *input_descriptor == InputDescriptors::RevokedReceivedHTLC { "received" } else { "" }, outp.vout, outp.txid, new_feerate);
                                                }
                                        },
-                                       &InputMaterial::RemoteHTLC { ref per_commitment_point, ref key, ref preimage, ref amount, ref locktime } => {
+                                       &InputMaterial::RemoteHTLC { ref per_commitment_point, ref preimage, ref amount, ref locktime } => {
                                                if let Ok(chan_keys) = TxCreationKeys::new(&self.secp_ctx, &per_commitment_point, &self.remote_tx_cache.remote_delayed_payment_base_key, &self.remote_tx_cache.remote_htlc_base_key, &self.key_storage.pubkeys().revocation_basepoint, &self.key_storage.pubkeys().htlc_basepoint) {
                                                        let mut this_htlc = None;
                                                        if let Some(htlcs) = self.remote_tx_cache.per_htlc.get(&outp.txid) {
@@ -684,18 +683,17 @@ impl<ChanSigner: ChannelKeys> OnchainTxHandler<ChanSigner> {
                                                        let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&this_htlc.unwrap(), &chan_keys.a_htlc_key, &chan_keys.b_htlc_key, &chan_keys.revocation_key);
 
                                                        if !preimage.is_some() { bumped_tx.lock_time = *locktime }; // Right now we don't aggregate time-locked transaction, if we do we should set lock_time before to avoid breaking hash computation
-                                                       let sighash_parts = bip143::SighashComponents::new(&bumped_tx);
-                                                       let sighash = hash_to_message!(&sighash_parts.sighash_all(&bumped_tx.input[i], &witness_script, *amount)[..]);
-                                                       let sig = self.secp_ctx.sign(&sighash, &key);
-                                                       bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
-                                                       bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
-                                                       if let &Some(preimage) = preimage {
-                                                               bumped_tx.input[i].witness.push(preimage.clone().0.to_vec());
-                                                       } else {
-                                                               // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
-                                                               bumped_tx.input[i].witness.push(vec![]);
+                                                       if let Ok(sig) = self.key_storage.sign_remote_htlc_transaction(&bumped_tx, i, &witness_script, *amount, &per_commitment_point, preimage, &self.secp_ctx) {
+                                                               bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
+                                                               bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
+                                                               if let &Some(preimage) = preimage {
+                                                                       bumped_tx.input[i].witness.push(preimage.0.to_vec());
+                                                               } else {
+                                                                       // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
+                                                                       bumped_tx.input[i].witness.push(vec![]);
+                                                               }
+                                                               bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
                                                        }
-                                                       bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
                                                        log_trace!(logger, "Going to broadcast Claim Transaction {} claiming remote {} htlc output {} from {} with new feerate {}...", bumped_tx.txid(), if preimage.is_some() { "offered" } else { "received" }, outp.vout, outp.txid, new_feerate);
                                                }
                                        },
index c9c503d9ae5646ff54c50fa07838f0bc99ee9791..dacec1a936adcc9e33c711dc5977f2f96c1b5a4f 100644 (file)
@@ -1,5 +1,6 @@
 use ln::chan_utils::{HTLCOutputInCommitment, TxCreationKeys, ChannelPublicKeys, LocalCommitmentTransaction};
 use ln::{chan_utils, msgs};
+use ln::channelmanager::PaymentPreimage;
 use chain::keysinterface::{ChannelKeys, InMemoryChannelKeys};
 
 use std::cmp;
@@ -108,6 +109,10 @@ impl ChannelKeys for EnforcingChannelKeys {
                Ok(self.inner.sign_justice_transaction(justice_tx, input, witness_script, amount, per_commitment_key, revocation_pubkey, is_htlc, secp_ctx).unwrap())
        }
 
+       fn sign_remote_htlc_transaction<T: secp256k1::Signing>(&self, htlc_tx: &Transaction, input: usize, witness_script: &Script, amount: u64, per_commitment_point: &PublicKey, preimage: &Option<PaymentPreimage>, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
+               Ok(self.inner.sign_remote_htlc_transaction(htlc_tx, input, witness_script, amount, per_commitment_point, preimage, secp_ctx).unwrap())
+       }
+
        fn sign_closing_transaction<T: secp256k1::Signing>(&self, closing_tx: &Transaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
                Ok(self.inner.sign_closing_transaction(closing_tx, secp_ctx).unwrap())
        }