]> 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>
Sat, 9 May 2020 00:48:50 +0000 (20:48 -0400)
lightning/src/chain/keysinterface.rs
lightning/src/ln/channelmonitor.rs
lightning/src/ln/onchaintx.rs
lightning/src/util/enforcing_trait_impls.rs

index 415fb420ac6b5d418b277872aae91477f654c27f..f7b907358c4adade3127171d7b3e489d95a46108 100644 (file)
@@ -26,6 +26,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::Arc;
 use std::sync::atomic::{AtomicUsize, Ordering};
@@ -269,6 +270,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
@@ -426,6 +446,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 d35dbdab9d45ffcb5eca2862daa70b0977f435f1..9324437dc7370ba45c0bfe25a90f72e35897ce31 100644 (file)
@@ -431,7 +431,6 @@ pub(crate) enum InputMaterial {
        },
        RemoteHTLC {
                per_commitment_point: PublicKey,
-               key: SecretKey,
                preimage: Option<PaymentPreimage>,
                amount: u64,
                locktime: u32,
@@ -455,10 +454,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))?;
@@ -494,13 +492,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
@@ -1556,8 +1552,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
@@ -1575,7 +1569,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 aee25ef6d27c6cf7a8f0647c6e86b4748ca7595a..6af53c73e43dba56684f3383800ec0fb1e10381c 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;
 
@@ -673,7 +672,7 @@ impl<ChanSigner: ChannelKeys> OnchainTxHandler<ChanSigner> {
                                                        log_trace!(self, "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) {
@@ -687,18 +686,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!(self, "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())
        }