Skip to content

Commit f52b477

Browse files
committed
Update Channel::funding_signed to use ChannelMonitorUpdate
This is the first of several steps to update ChannelMonitor updates to use the new ChannelMonitorUpdate objects, demonstrating how the new flow works in Channel.
1 parent ba4856e commit f52b477

File tree

4 files changed

+77
-19
lines changed

4 files changed

+77
-19
lines changed

lightning/src/ln/chan_utils.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,7 @@ pub(super) fn derive_public_revocation_key<T: secp256k1::Verification>(secp_ctx:
241241

242242
/// The set of public keys which are used in the creation of one commitment transaction.
243243
/// These are derived from the channel base keys and per-commitment data.
244-
#[derive(PartialEq)]
244+
#[derive(PartialEq, Clone)]
245245
pub struct TxCreationKeys {
246246
/// The per-commitment public key which was used to derive the other keys.
247247
pub per_commitment_point: PublicKey,
@@ -257,6 +257,8 @@ pub struct TxCreationKeys {
257257
/// B's Payment Key
258258
pub(crate) b_payment_key: PublicKey,
259259
}
260+
impl_writeable!(TxCreationKeys, 33*6,
261+
{ per_commitment_point, revocation_key, a_htlc_key, b_htlc_key, a_delayed_payment_key, b_payment_key });
260262

261263
/// One counterparty's public keys which do not change over the life of a channel.
262264
#[derive(Clone, PartialEq)]
@@ -339,6 +341,14 @@ pub struct HTLCOutputInCommitment {
339341
pub transaction_output_index: Option<u32>,
340342
}
341343

344+
impl_writeable!(HTLCOutputInCommitment, 1 + 8 + 4 + 32 + 5, {
345+
offered,
346+
amount_msat,
347+
cltv_expiry,
348+
payment_hash,
349+
transaction_output_index
350+
});
351+
342352
#[inline]
343353
pub(super) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, a_htlc_key: &PublicKey, b_htlc_key: &PublicKey, revocation_key: &PublicKey) -> Script {
344354
let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).into_inner();

lightning/src/ln/channel.rs

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use secp256k1;
1818
use ln::features::{ChannelFeatures, InitFeatures};
1919
use ln::msgs;
2020
use ln::msgs::{DecodeError, OptionalField, DataLossProtect};
21-
use ln::channelmonitor::ChannelMonitor;
21+
use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep};
2222
use ln::channelmanager::{PendingHTLCStatus, HTLCSource, HTLCFailReason, HTLCFailureMsg, PendingHTLCInfo, RAACommitmentOrder, PaymentPreimage, PaymentHash, BREAKDOWN_TIMEOUT, MAX_LOCAL_BREAKDOWN_TIMEOUT};
2323
use ln::chan_utils::{CounterpartyCommitmentSecrets, LocalCommitmentTransaction, TxCreationKeys, HTLCOutputInCommitment, HTLC_SUCCESS_TX_WEIGHT, HTLC_TIMEOUT_TX_WEIGHT, make_funding_redeemscript, ChannelPublicKeys};
2424
use ln::chan_utils;
@@ -1487,7 +1487,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
14871487
// Now that we're past error-generating stuff, update our local state:
14881488

14891489
self.channel_monitor.provide_latest_remote_commitment_tx_info(&remote_initial_commitment_tx, Vec::new(), self.cur_remote_commitment_transaction_number, self.their_cur_commitment_point.unwrap());
1490-
self.channel_monitor.provide_latest_local_commitment_tx_info(local_initial_commitment_tx, local_keys, self.feerate_per_kw, Vec::new());
1490+
self.channel_monitor.provide_latest_local_commitment_tx_info(local_initial_commitment_tx, local_keys, self.feerate_per_kw, Vec::new()).unwrap();
14911491
self.channel_state = ChannelState::FundingSent as u32;
14921492
self.channel_id = funding_txo.to_channel_id();
14931493
self.cur_remote_commitment_transaction_number -= 1;
@@ -1501,7 +1501,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
15011501

15021502
/// Handles a funding_signed message from the remote end.
15031503
/// If this call is successful, broadcast the funding transaction (and not before!)
1504-
pub fn funding_signed(&mut self, msg: &msgs::FundingSigned) -> Result<ChannelMonitor<ChanSigner>, ChannelError<ChanSigner>> {
1504+
pub fn funding_signed(&mut self, msg: &msgs::FundingSigned) -> Result<ChannelMonitorUpdate, ChannelError<ChanSigner>> {
15051505
if !self.channel_outbound {
15061506
return Err(ChannelError::Close("Received funding_signed for an inbound channel?"));
15071507
}
@@ -1525,14 +1525,20 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
15251525
// They sign the "local" commitment transaction, allowing us to broadcast the tx if we wish.
15261526
secp_check!(self.secp_ctx.verify(&local_sighash, &msg.signature, their_funding_pubkey), "Invalid funding_signed signature from peer");
15271527

1528-
self.channel_monitor.provide_latest_local_commitment_tx_info(
1529-
LocalCommitmentTransaction::new_missing_local_sig(local_initial_commitment_tx, &msg.signature, &PublicKey::from_secret_key(&self.secp_ctx, self.local_keys.funding_key()), their_funding_pubkey),
1530-
local_keys, self.feerate_per_kw, Vec::new());
1528+
self.latest_monitor_update_id += 1;
1529+
let monitor_update = ChannelMonitorUpdate {
1530+
update_id: self.latest_monitor_update_id,
1531+
updates: vec![ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo {
1532+
commitment_tx: LocalCommitmentTransaction::new_missing_local_sig(local_initial_commitment_tx, &msg.signature, &PublicKey::from_secret_key(&self.secp_ctx, self.local_keys.funding_key()), their_funding_pubkey),
1533+
local_keys, feerate_per_kw: self.feerate_per_kw, htlc_outputs: Vec::new(),
1534+
}]
1535+
};
1536+
self.channel_monitor.update_monitor(monitor_update.clone()).unwrap();
15311537
self.channel_state = ChannelState::FundingSent as u32 | (self.channel_state & (ChannelState::MonitorUpdateFailed as u32));
15321538
self.cur_local_commitment_transaction_number -= 1;
15331539

15341540
if self.channel_state & (ChannelState::MonitorUpdateFailed as u32) == 0 {
1535-
Ok(self.channel_monitor.clone())
1541+
Ok(monitor_update)
15361542
} else {
15371543
Err(ChannelError::Ignore("Previous monitor update failure prevented funding_signed from allowing funding broadcast"))
15381544
}
@@ -1827,7 +1833,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
18271833

18281834
self.channel_monitor.provide_latest_local_commitment_tx_info(
18291835
LocalCommitmentTransaction::new_missing_local_sig(local_commitment_tx.0, &msg.signature, &PublicKey::from_secret_key(&self.secp_ctx, self.local_keys.funding_key()), &their_funding_pubkey),
1830-
local_keys, self.feerate_per_kw, htlcs_and_sigs);
1836+
local_keys, self.feerate_per_kw, htlcs_and_sigs).unwrap();
18311837

18321838
for htlc in self.pending_inbound_htlcs.iter_mut() {
18331839
let new_forward = if let &InboundHTLCState::RemoteAnnounced(ref forward_info) = &htlc.state {

lightning/src/ln/channelmanager.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2090,8 +2090,8 @@ impl<ChanSigner: ChannelKeys, M: Deref> ChannelManager<ChanSigner, M> where M::T
20902090
if chan.get().get_their_node_id() != *their_node_id {
20912091
return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
20922092
}
2093-
let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
2094-
if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2093+
let monitor_update = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
2094+
if let Err(e) = self.monitor.update_monitor(chan.get().get_funding_txo().unwrap(), monitor_update) {
20952095
return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, false, false);
20962096
}
20972097
(chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())

lightning/src/ln/channelmonitor.rs

Lines changed: 50 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -642,16 +642,53 @@ const MIN_SERIALIZATION_VERSION: u8 = 1;
642642
#[cfg_attr(test, derive(PartialEq))]
643643
#[derive(Clone)]
644644
pub(super) enum ChannelMonitorUpdateStep {
645+
LatestLocalCommitmentTXInfo {
646+
commitment_tx: LocalCommitmentTransaction,
647+
local_keys: chan_utils::TxCreationKeys,
648+
feerate_per_kw: u64,
649+
htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
650+
},
645651
}
646652

647653
impl Writeable for ChannelMonitorUpdateStep {
648-
fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::std::io::Error> {
654+
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
655+
match self {
656+
&ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { ref commitment_tx, ref local_keys, ref feerate_per_kw, ref htlc_outputs } => {
657+
0u8.write(w)?;
658+
commitment_tx.write(w)?;
659+
local_keys.write(w)?;
660+
feerate_per_kw.write(w)?;
661+
(htlc_outputs.len() as u64).write(w)?;
662+
for &(ref output, ref signature, ref source) in htlc_outputs.iter() {
663+
output.write(w)?;
664+
signature.write(w)?;
665+
source.write(w)?;
666+
}
667+
}
668+
}
649669
Ok(())
650670
}
651671
}
652672
impl<R: ::std::io::Read> Readable<R> for ChannelMonitorUpdateStep {
653-
fn read(_r: &mut R) -> Result<Self, DecodeError> {
654-
unimplemented!() // We don't have any enum variants to read (and never provide Monitor Updates)
673+
fn read(r: &mut R) -> Result<Self, DecodeError> {
674+
match Readable::read(r)? {
675+
0u8 => {
676+
Ok(ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo {
677+
commitment_tx: Readable::read(r)?,
678+
local_keys: Readable::read(r)?,
679+
feerate_per_kw: Readable::read(r)?,
680+
htlc_outputs: {
681+
let len: u64 = Readable::read(r)?;
682+
let mut res = Vec::new();
683+
for _ in 0..len {
684+
res.push((Readable::read(r)?, Readable::read(r)?, Readable::read(r)?));
685+
}
686+
res
687+
},
688+
})
689+
},
690+
_ => Err(DecodeError::InvalidValue),
691+
}
655692
}
656693
}
657694

@@ -1298,8 +1335,10 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
12981335
/// is important that any clones of this channel monitor (including remote clones) by kept
12991336
/// up-to-date as our local commitment transaction is updated.
13001337
/// Panics if set_their_to_self_delay has never been called.
1301-
pub(super) fn provide_latest_local_commitment_tx_info(&mut self, commitment_tx: LocalCommitmentTransaction, local_keys: chan_utils::TxCreationKeys, feerate_per_kw: u64, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>) {
1302-
assert!(self.their_to_self_delay.is_some());
1338+
pub(super) fn provide_latest_local_commitment_tx_info(&mut self, commitment_tx: LocalCommitmentTransaction, local_keys: chan_utils::TxCreationKeys, feerate_per_kw: u64, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>) -> Result<(), MonitorUpdateError> {
1339+
if self.their_to_self_delay.is_none() {
1340+
return Err(MonitorUpdateError("Got a local commitment tx info update before we'd set basic information about the channel"));
1341+
}
13031342
self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
13041343
self.current_local_signed_commitment_tx = Some(LocalSignedTx {
13051344
txid: commitment_tx.txid(),
@@ -1312,6 +1351,7 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
13121351
feerate_per_kw,
13131352
htlc_outputs,
13141353
});
1354+
Ok(())
13151355
}
13161356

13171357
/// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
@@ -1330,6 +1370,8 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
13301370
}
13311371
for update in updates.updates.drain(..) {
13321372
match update {
1373+
ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { commitment_tx, local_keys, feerate_per_kw, htlc_outputs } =>
1374+
self.provide_latest_local_commitment_tx_info(commitment_tx, local_keys, feerate_per_kw, htlc_outputs)?,
13331375
}
13341376
}
13351377
self.latest_update_id = updates.update_id;
@@ -3501,7 +3543,7 @@ mod tests {
35013543
let mut monitor = ChannelMonitor::new(keys, &SecretKey::from_slice(&[41; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[43; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &SecretKey::from_slice(&[44; 32]).unwrap(), &PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), 0, Script::new(), logger.clone());
35023544
monitor.their_to_self_delay = Some(10);
35033545

3504-
monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10]));
3546+
monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10])).unwrap();
35053547
monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key);
35063548
monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key);
35073549
monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key);
@@ -3527,15 +3569,15 @@ mod tests {
35273569

35283570
// Now update local commitment tx info, pruning only element 18 as we still care about the
35293571
// previous commitment tx's preimages too
3530-
monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5]));
3572+
monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5])).unwrap();
35313573
secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
35323574
monitor.provide_secret(281474976710653, secret.clone()).unwrap();
35333575
assert_eq!(monitor.payment_preimages.len(), 12);
35343576
test_preimages_exist!(&preimages[0..10], monitor);
35353577
test_preimages_exist!(&preimages[18..20], monitor);
35363578

35373579
// But if we do it again, we'll prune 5-10
3538-
monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3]));
3580+
monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..3])).unwrap();
35393581
secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
35403582
monitor.provide_secret(281474976710652, secret.clone()).unwrap();
35413583
assert_eq!(monitor.payment_preimages.len(), 5);

0 commit comments

Comments
 (0)