Skip to content

Commit 4ebe64f

Browse files
committed
Use external key signer to generate closing transaction signatures
1 parent b1ed0ee commit 4ebe64f

File tree

3 files changed

+68
-18
lines changed

3 files changed

+68
-18
lines changed

lightning/src/chain/keysinterface.rs

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,13 @@ pub trait ChannelKeys : Send {
142142
/// TODO: Document the things someone using this interface should enforce before signing.
143143
/// TODO: Add more input vars to enable better checking (preferably removing commitment_tx and
144144
/// making the callee generate it via some util function we expose)!
145-
fn sign_remote_commitment<T: secp256k1::Signing>(&self, channel_value_satoshis: u64, channel_funding_script: &Script, feerate_per_kw: u64, commitment_tx: &Transaction, keys: &TxCreationKeys, htlcs: &[&HTLCOutputInCommitment], to_self_delay: u16, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()>;
145+
fn sign_remote_commitment<T: secp256k1::Signing>(&self, channel_value_satoshis: u64, channel_funding_redeemscript: &Script, absolute_fee: u64, commitment_tx: &Transaction, keys: &TxCreationKeys, htlcs: &[&HTLCOutputInCommitment], to_self_delay: u16, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()>;
146+
147+
/// Create a signature for a (proposed) closing transaction.
148+
///
149+
/// Note that, due to rounding, there may be one "missing" satoshi, and either party may have
150+
/// chosen to forgo their output as dust.
151+
fn sign_closing_transaction<T: secp256k1::Signing>(&self, channel_value_satoshis: u64, channel_funding_redeemscript: &Script, closing_tx: &Transaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()>;
146152

147153
/// Signs a channel announcement message with our funding key, proving it comes from one
148154
/// of the channel participants.
@@ -178,9 +184,9 @@ impl ChannelKeys for InMemoryChannelKeys {
178184
fn htlc_base_key(&self) -> &SecretKey { &self.htlc_base_key }
179185
fn commitment_seed(&self) -> &[u8; 32] { &self.commitment_seed }
180186

181-
fn sign_remote_commitment<T: secp256k1::Signing>(&self, channel_value_satoshis: u64, channel_funding_script: &Script, feerate_per_kw: u64, commitment_tx: &Transaction, keys: &TxCreationKeys, htlcs: &[&HTLCOutputInCommitment], to_self_delay: u16, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()> {
187+
fn sign_remote_commitment<T: secp256k1::Signing>(&self, channel_value_satoshis: u64, channel_funding_redeemscript: &Script, feerate_per_kw: u64, commitment_tx: &Transaction, keys: &TxCreationKeys, htlcs: &[&HTLCOutputInCommitment], to_self_delay: u16, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Vec<Signature>), ()> {
182188
if commitment_tx.input.len() != 1 { return Err(()); }
183-
let commitment_sighash = hash_to_message!(&bip143::SighashComponents::new(&commitment_tx).sighash_all(&commitment_tx.input[0], &channel_funding_script, channel_value_satoshis)[..]);
189+
let commitment_sighash = hash_to_message!(&bip143::SighashComponents::new(&commitment_tx).sighash_all(&commitment_tx.input[0], &channel_funding_redeemscript, channel_value_satoshis)[..]);
184190
let commitment_sig = secp_ctx.sign(&commitment_sighash, &self.funding_key);
185191

186192
let commitment_txid = commitment_tx.txid();
@@ -202,6 +208,16 @@ impl ChannelKeys for InMemoryChannelKeys {
202208
Ok((commitment_sig, htlc_sigs))
203209
}
204210

211+
fn sign_closing_transaction<T: secp256k1::Signing>(&self, channel_value_satoshis: u64, channel_funding_redeemscript: &Script, closing_tx: &Transaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
212+
if closing_tx.input.len() != 1 { return Err(()); }
213+
if closing_tx.input[0].witness.len() != 0 { return Err(()); }
214+
if closing_tx.output.len() > 2 { return Err(()); }
215+
216+
let sighash = hash_to_message!(&bip143::SighashComponents::new(closing_tx)
217+
.sighash_all(&closing_tx.input[0], &channel_funding_redeemscript, channel_value_satoshis)[..]);
218+
Ok(secp_ctx.sign(&sighash, &self.funding_key))
219+
}
220+
205221
fn sign_channel_announcement<T: secp256k1::Signing>(&self, msg: &msgs::UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
206222
let msghash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
207223
Ok(secp_ctx.sign(&msghash, &self.funding_key))

lightning/src/ln/channel.rs

Lines changed: 45 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -303,7 +303,7 @@ pub(super) struct Channel<ChanSigner: ChannelKeys> {
303303
#[cfg(not(test))]
304304
last_local_commitment_txn: Vec<Transaction>,
305305

306-
last_sent_closing_fee: Option<(u64, u64)>, // (feerate, fee)
306+
last_sent_closing_fee: Option<(u64, u64, Signature)>, // (feerate, fee, our_sig)
307307

308308
/// The hash of the block in which the funding transaction reached our CONF_TARGET. We use this
309309
/// to detect unconfirmation after a serialize-unserialize roundtrip where we may not see a full
@@ -2665,14 +2665,16 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
26652665
let proposed_total_fee_satoshis = proposed_feerate * tx_weight / 1000;
26662666

26672667
let (closing_tx, total_fee_satoshis) = self.build_closing_transaction(proposed_total_fee_satoshis, false);
2668-
let funding_redeemscript = self.get_funding_redeemscript();
2669-
let sighash = hash_to_message!(&bip143::SighashComponents::new(&closing_tx).sighash_all(&closing_tx.input[0], &funding_redeemscript, self.channel_value_satoshis)[..]);
2668+
let our_sig = self.local_keys
2669+
.sign_closing_transaction(self.channel_value_satoshis, &self.get_funding_redeemscript(), &closing_tx, &self.secp_ctx)
2670+
.ok();
2671+
if our_sig.is_none() { return None; }
26702672

2671-
self.last_sent_closing_fee = Some((proposed_feerate, total_fee_satoshis));
2673+
self.last_sent_closing_fee = Some((proposed_feerate, total_fee_satoshis, our_sig.clone().unwrap()));
26722674
Some(msgs::ClosingSigned {
26732675
channel_id: self.channel_id,
26742676
fee_satoshis: total_fee_satoshis,
2675-
signature: self.secp_ctx.sign(&sighash, &self.local_keys.funding_key()),
2677+
signature: our_sig.unwrap(),
26762678
})
26772679
}
26782680

@@ -2749,6 +2751,28 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
27492751
Ok((our_shutdown, self.maybe_propose_first_closing_signed(fee_estimator), dropped_outbound_htlcs))
27502752
}
27512753

2754+
fn build_signed_closing_transaction(&self, tx: &mut Transaction, their_sig: &Signature, our_sig: &Signature) {
2755+
if tx.input.len() != 1 { panic!("Tried to sign closing transaction that had input count != 1!"); }
2756+
if tx.input[0].witness.len() != 0 { panic!("Tried to re-sign closing transaction"); }
2757+
if tx.output.len() > 2 { panic!("Tried to sign bogus closing transaction"); }
2758+
2759+
tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
2760+
2761+
let our_funding_key = PublicKey::from_secret_key(&self.secp_ctx, self.local_keys.funding_key()).serialize();
2762+
let their_funding_key = self.their_funding_pubkey.unwrap().serialize();
2763+
if our_funding_key[..] < their_funding_key[..] {
2764+
tx.input[0].witness.push(our_sig.serialize_der().to_vec());
2765+
tx.input[0].witness.push(their_sig.serialize_der().to_vec());
2766+
} else {
2767+
tx.input[0].witness.push(their_sig.serialize_der().to_vec());
2768+
tx.input[0].witness.push(our_sig.serialize_der().to_vec());
2769+
}
2770+
tx.input[0].witness[1].push(SigHashType::All as u8);
2771+
tx.input[0].witness[2].push(SigHashType::All as u8);
2772+
2773+
tx.input[0].witness.push(self.get_funding_redeemscript().into_bytes());
2774+
}
2775+
27522776
pub fn closing_signed(&mut self, fee_estimator: &FeeEstimator, msg: &msgs::ClosingSigned) -> Result<(Option<msgs::ClosingSigned>, Option<Transaction>), ChannelError> {
27532777
if self.channel_state & BOTH_SIDES_SHUTDOWN_MASK != BOTH_SIDES_SHUTDOWN_MASK {
27542778
return Err(ChannelError::Close("Remote end sent us a closing_signed before both sides provided a shutdown"));
@@ -2781,9 +2805,9 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
27812805
},
27822806
};
27832807

2784-
if let Some((_, last_fee)) = self.last_sent_closing_fee {
2808+
if let Some((_, last_fee, our_sig)) = self.last_sent_closing_fee {
27852809
if last_fee == msg.fee_satoshis {
2786-
self.sign_commitment_transaction(&mut closing_tx, &msg.signature);
2810+
self.build_signed_closing_transaction(&mut closing_tx, &msg.signature, &our_sig);
27872811
self.channel_state = ChannelState::ShutdownComplete as u32;
27882812
self.channel_update_count += 1;
27892813
return Ok((None, Some(closing_tx)));
@@ -2794,9 +2818,10 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
27942818
($new_feerate: expr) => {
27952819
let closing_tx_max_weight = Self::get_closing_transaction_weight(&self.get_closing_scriptpubkey(), self.their_shutdown_scriptpubkey.as_ref().unwrap());
27962820
let (closing_tx, used_total_fee) = self.build_closing_transaction($new_feerate * closing_tx_max_weight / 1000, false);
2797-
sighash = hash_to_message!(&bip143::SighashComponents::new(&closing_tx).sighash_all(&closing_tx.input[0], &funding_redeemscript, self.channel_value_satoshis)[..]);
2798-
let our_sig = self.secp_ctx.sign(&sighash, &self.local_keys.funding_key());
2799-
self.last_sent_closing_fee = Some(($new_feerate, used_total_fee));
2821+
let our_sig = self.local_keys
2822+
.sign_closing_transaction(self.channel_value_satoshis, &funding_redeemscript, &closing_tx, &self.secp_ctx)
2823+
.map_err(|_| ChannelError::Close("External signer refused to sign closing transaction"))?;
2824+
self.last_sent_closing_fee = Some(($new_feerate, used_total_fee, our_sig.clone()));
28002825
return Ok((Some(msgs::ClosingSigned {
28012826
channel_id: self.channel_id,
28022827
fee_satoshis: used_total_fee,
@@ -2809,7 +2834,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
28092834
if self.channel_outbound {
28102835
let our_max_feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Normal);
28112836
if proposed_sat_per_kw > our_max_feerate {
2812-
if let Some((last_feerate, _)) = self.last_sent_closing_fee {
2837+
if let Some((last_feerate, _, _)) = self.last_sent_closing_fee {
28132838
if our_max_feerate <= last_feerate {
28142839
return Err(ChannelError::Close("Unable to come to consensus about closing feerate, remote wanted something higher than our Normal feerate"));
28152840
}
@@ -2819,7 +2844,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
28192844
} else {
28202845
let our_min_feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background);
28212846
if proposed_sat_per_kw < our_min_feerate {
2822-
if let Some((last_feerate, _)) = self.last_sent_closing_fee {
2847+
if let Some((last_feerate, _, _)) = self.last_sent_closing_fee {
28232848
if our_min_feerate >= last_feerate {
28242849
return Err(ChannelError::Close("Unable to come to consensus about closing feerate, remote wanted something lower than our Background feerate"));
28252850
}
@@ -2828,7 +2853,11 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
28282853
}
28292854
}
28302855

2831-
let our_sig = self.sign_commitment_transaction(&mut closing_tx, &msg.signature);
2856+
let our_sig = self.local_keys
2857+
.sign_closing_transaction(self.channel_value_satoshis, &funding_redeemscript, &closing_tx, &self.secp_ctx)
2858+
.map_err(|_| ChannelError::Close("External signer refused to sign closing transaction"))?;
2859+
self.build_signed_closing_transaction(&mut closing_tx, &msg.signature, &our_sig);
2860+
28322861
self.channel_state = ChannelState::ShutdownComplete as u32;
28332862
self.channel_update_count += 1;
28342863

@@ -3855,10 +3884,11 @@ impl<ChanSigner: ChannelKeys + Writeable> Writeable for Channel<ChanSigner> {
38553884
}
38563885

38573886
match self.last_sent_closing_fee {
3858-
Some((feerate, fee)) => {
3887+
Some((feerate, fee, sig)) => {
38593888
1u8.write(writer)?;
38603889
feerate.write(writer)?;
38613890
fee.write(writer)?;
3891+
sig.write(writer)?;
38623892
},
38633893
None => 0u8.write(writer)?,
38643894
}
@@ -4022,7 +4052,7 @@ impl<R : ::std::io::Read, ChanSigner: ChannelKeys + Readable<R>> ReadableArgs<R,
40224052

40234053
let last_sent_closing_fee = match <u8 as Readable<R>>::read(reader)? {
40244054
0 => None,
4025-
1 => Some((Readable::read(reader)?, Readable::read(reader)?)),
4055+
1 => Some((Readable::read(reader)?, Readable::read(reader)?, Readable::read(reader)?)),
40264056
_ => return Err(DecodeError::InvalidValue),
40274057
};
40284058

lightning/src/util/enforcing_trait_impls.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,10 @@ impl ChannelKeys for EnforcingChannelKeys {
5252
Ok(self.inner.sign_remote_commitment(channel_value_satoshis, channel_funding_script, feerate_per_kw, commitment_tx, keys, htlcs, to_self_delay, secp_ctx).unwrap())
5353
}
5454

55+
fn sign_closing_transaction<T: secp256k1::Signing>(&self, channel_value_satoshis: u64, channel_funding_redeemscript: &Script, closing_tx: &Transaction, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
56+
Ok(self.inner.sign_closing_transaction(channel_value_satoshis, channel_funding_redeemscript, closing_tx, secp_ctx).unwrap())
57+
}
58+
5559
fn sign_channel_announcement<T: secp256k1::Signing>(&self, msg: &msgs::UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<Signature, ()> {
5660
self.inner.sign_channel_announcement(msg, secp_ctx)
5761
}

0 commit comments

Comments
 (0)