Skip to content

Commit beef1e7

Browse files
author
Antoine Riard
committed
Build witness_script for justice tx inside OnchainTxHandler
By moving script generation inside OnchainTxHandler, we may dry-up further ChannelMonitor in next commits.
1 parent 65130cb commit beef1e7

File tree

2 files changed

+45
-33
lines changed

2 files changed

+45
-33
lines changed

lightning/src/ln/channelmonitor.rs

Lines changed: 9 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -425,8 +425,7 @@ struct LocalSignedTx {
425425
#[derive(Clone, PartialEq)]
426426
pub(crate) enum InputMaterial {
427427
Revoked {
428-
witness_script: Script,
429-
pubkey: Option<PublicKey>,
428+
per_commitment_point: PublicKey,
430429
key: SecretKey,
431430
input_descriptor: InputDescriptors,
432431
amount: u64,
@@ -450,10 +449,9 @@ pub(crate) enum InputMaterial {
450449
impl Writeable for InputMaterial {
451450
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
452451
match self {
453-
&InputMaterial::Revoked { ref witness_script, ref pubkey, ref key, ref input_descriptor, ref amount} => {
452+
&InputMaterial::Revoked { ref per_commitment_point, ref key, ref input_descriptor, ref amount} => {
454453
writer.write_all(&[0; 1])?;
455-
witness_script.write(writer)?;
456-
pubkey.write(writer)?;
454+
per_commitment_point.write(writer)?;
457455
writer.write_all(&key[..])?;
458456
input_descriptor.write(writer)?;
459457
writer.write_all(&byte_utils::be64_to_array(*amount))?;
@@ -484,14 +482,12 @@ impl Readable for InputMaterial {
484482
fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
485483
let input_material = match <u8 as Readable>::read(reader)? {
486484
0 => {
487-
let witness_script = Readable::read(reader)?;
488-
let pubkey = Readable::read(reader)?;
485+
let per_commitment_point = Readable::read(reader)?;
489486
let key = Readable::read(reader)?;
490487
let input_descriptor = Readable::read(reader)?;
491488
let amount = Readable::read(reader)?;
492489
InputMaterial::Revoked {
493-
witness_script,
494-
pubkey,
490+
per_commitment_point,
495491
key,
496492
input_descriptor,
497493
amount
@@ -1456,10 +1452,8 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
14561452
let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
14571453
let revocation_pubkey = ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &self.keys.pubkeys().revocation_basepoint));
14581454
let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &self.keys.revocation_base_key()));
1459-
let b_htlc_key = ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &self.keys.pubkeys().htlc_basepoint));
14601455
let local_payment_key = ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, &per_commitment_point, &self.keys.payment_base_key()));
14611456
let delayed_key = ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key), &self.their_delayed_payment_base_key));
1462-
let a_htlc_key = ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key), &self.their_htlc_base_key));
14631457

14641458
let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
14651459
let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
@@ -1474,7 +1468,7 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
14741468
// First, process non-htlc outputs (to_local & to_remote)
14751469
for (idx, outp) in tx.output.iter().enumerate() {
14761470
if outp.script_pubkey == revokeable_p2wsh {
1477-
let witness_data = InputMaterial::Revoked { witness_script: revokeable_redeemscript.clone(), pubkey: Some(revocation_pubkey), key: revocation_key, input_descriptor: InputDescriptors::RevokedOutput, amount: outp.value };
1471+
let witness_data = InputMaterial::Revoked { per_commitment_point, key: revocation_key, input_descriptor: InputDescriptors::RevokedOutput, amount: outp.value };
14781472
claimable_outpoints.push(ClaimRequest { absolute_timelock: height + self.our_to_self_delay as u32, aggregable: true, outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 }, witness_data});
14791473
}
14801474
}
@@ -1483,13 +1477,11 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
14831477
if let Some(ref per_commitment_data) = per_commitment_option {
14841478
for (_, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
14851479
if let Some(transaction_output_index) = htlc.transaction_output_index {
1486-
let expected_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &a_htlc_key, &b_htlc_key, &revocation_pubkey);
14871480
if transaction_output_index as usize >= tx.output.len() ||
1488-
tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
1489-
tx.output[transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1481+
tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
14901482
return (claimable_outpoints, (commitment_txid, watch_outputs)); // Corrupted per_commitment_data, fuck this user
14911483
}
1492-
let witness_data = InputMaterial::Revoked { witness_script: expected_script, pubkey: Some(revocation_pubkey), key: revocation_key, input_descriptor: if htlc.offered { InputDescriptors::RevokedOfferedHTLC } else { InputDescriptors::RevokedReceivedHTLC }, amount: tx.output[transaction_output_index as usize].value };
1484+
let witness_data = InputMaterial::Revoked { per_commitment_point, key: revocation_key, input_descriptor: if htlc.offered { InputDescriptors::RevokedOfferedHTLC } else { InputDescriptors::RevokedReceivedHTLC }, amount: tx.output[transaction_output_index as usize].value };
14931485
claimable_outpoints.push(ClaimRequest { absolute_timelock: htlc.cltv_expiry, aggregable: true, outpoint: BitcoinOutPoint { txid: commitment_txid, vout: transaction_output_index }, witness_data });
14941486
}
14951487
}
@@ -1662,13 +1654,10 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
16621654
let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
16631655
let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
16641656
let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
1665-
let revocation_pubkey = ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &self.keys.pubkeys().revocation_basepoint));
16661657
let revocation_key = ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &self.keys.revocation_base_key()));
1667-
let delayed_key = ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &self.their_delayed_payment_base_key));
1668-
let redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.our_to_self_delay, &delayed_key);
16691658

16701659
log_trace!(self, "Remote HTLC broadcast {}:{}", htlc_txid, 0);
1671-
let witness_data = InputMaterial::Revoked { witness_script: redeemscript, pubkey: Some(revocation_pubkey), key: revocation_key, input_descriptor: InputDescriptors::RevokedOutput, amount: tx.output[0].value };
1660+
let witness_data = InputMaterial::Revoked { per_commitment_point, key: revocation_key, input_descriptor: InputDescriptors::RevokedOutput, amount: tx.output[0].value };
16721661
let claimable_outpoints = vec!(ClaimRequest { absolute_timelock: height + self.our_to_self_delay as u32, aggregable: true, outpoint: BitcoinOutPoint { txid: htlc_txid, vout: 0}, witness_data });
16731662
(claimable_outpoints, Some((htlc_txid, tx.output.clone())))
16741663
}

lightning/src/ln/onchaintx.rs

Lines changed: 36 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ use secp256k1;
1717
use ln::msgs::DecodeError;
1818
use ln::channelmonitor::{ANTI_REORG_DELAY, CLTV_SHARED_CLAIM_BUFFER, InputMaterial, ClaimRequest};
1919
use ln::channelmanager::PaymentPreimage;
20-
use ln::chan_utils::{LocalCommitmentTransaction, HTLCOutputInCommitment};
20+
use ln::chan_utils;
21+
use ln::chan_utils::{TxCreationKeys, LocalCommitmentTransaction, HTLCOutputInCommitment};
2122
use chain::chaininterface::{FeeEstimator, BroadcasterInterface, ConfirmationTarget, MIN_RELAY_FEE_SAT_PER_1000_WEIGHT};
2223
use chain::keysinterface::ChannelKeys;
2324
use util::logger::Logger;
@@ -634,19 +635,41 @@ impl<ChanSigner: ChannelKeys> OnchainTxHandler<ChanSigner> {
634635

635636
for (i, (outp, per_outp_material)) in cached_claim_datas.per_input_material.iter().enumerate() {
636637
match per_outp_material {
637-
&InputMaterial::Revoked { ref witness_script, ref pubkey, ref key, ref input_descriptor, ref amount } => {
638-
let sighash_parts = bip143::SighashComponents::new(&bumped_tx);
639-
let sighash = hash_to_message!(&sighash_parts.sighash_all(&bumped_tx.input[i], &witness_script, *amount)[..]);
640-
let sig = self.secp_ctx.sign(&sighash, &key);
641-
bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
642-
bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
643-
if *input_descriptor != InputDescriptors::RevokedOutput {
644-
bumped_tx.input[i].witness.push(pubkey.unwrap().clone().serialize().to_vec());
645-
} else {
646-
bumped_tx.input[i].witness.push(vec!(1));
638+
&InputMaterial::Revoked { ref per_commitment_point, ref key, ref input_descriptor, ref amount } => {
639+
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().payment_basepoint, &self.key_storage.pubkeys().htlc_basepoint) {
640+
641+
let mut this_htlc = None;
642+
if *input_descriptor != InputDescriptors::RevokedOutput {
643+
if let Some(htlcs) = self.remote_tx_cache.per_htlc.get(&outp.txid) {
644+
for htlc in htlcs {
645+
if htlc.transaction_output_index.unwrap() == outp.vout {
646+
this_htlc = Some(htlc);
647+
}
648+
}
649+
}
650+
}
651+
652+
let witness_script = if *input_descriptor != InputDescriptors::RevokedOutput && this_htlc.is_some() {
653+
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)
654+
} else if *input_descriptor != InputDescriptors::RevokedOutput {
655+
return None;
656+
} else {
657+
chan_utils::get_revokeable_redeemscript(&chan_keys.revocation_key, self.remote_csv, &chan_keys.a_delayed_payment_key)
658+
};
659+
660+
let sighash_parts = bip143::SighashComponents::new(&bumped_tx);
661+
let sighash = hash_to_message!(&sighash_parts.sighash_all(&bumped_tx.input[i], &witness_script, *amount)[..]);
662+
let sig = self.secp_ctx.sign(&sighash, &key);
663+
bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
664+
bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
665+
if *input_descriptor != InputDescriptors::RevokedOutput {
666+
bumped_tx.input[i].witness.push(chan_keys.revocation_key.clone().serialize().to_vec());
667+
} else {
668+
bumped_tx.input[i].witness.push(vec!(1));
669+
}
670+
bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
671+
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);
647672
}
648-
bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
649-
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);
650673
},
651674
&InputMaterial::RemoteHTLC { ref witness_script, ref key, ref preimage, ref amount, ref locktime } => {
652675
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

0 commit comments

Comments
 (0)