Skip to content

Commit ac55bfa

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 8e42037 commit ac55bfa

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
@@ -246,7 +246,7 @@ pub(super) fn derive_public_revocation_key<T: secp256k1::Verification>(secp_ctx:
246246

247247
/// The set of public keys which are used in the creation of one commitment transaction.
248248
/// These are derived from the channel base keys and per-commitment data.
249-
#[derive(PartialEq)]
249+
#[derive(PartialEq, Clone)]
250250
pub struct TxCreationKeys {
251251
/// The per-commitment public key which was used to derive the other keys.
252252
pub per_commitment_point: PublicKey,
@@ -262,6 +262,8 @@ pub struct TxCreationKeys {
262262
/// B's Payment Key
263263
pub(crate) b_payment_key: PublicKey,
264264
}
265+
impl_writeable!(TxCreationKeys, 33*6,
266+
{ per_commitment_point, revocation_key, a_htlc_key, b_htlc_key, a_delayed_payment_key, b_payment_key });
265267

266268
/// One counterparty's public keys which do not change over the life of a channel.
267269
#[derive(Clone, PartialEq)]
@@ -344,6 +346,14 @@ pub struct HTLCOutputInCommitment {
344346
pub transaction_output_index: Option<u32>,
345347
}
346348

349+
impl_writeable!(HTLCOutputInCommitment, 1 + 8 + 4 + 32 + 5, {
350+
offered,
351+
amount_msat,
352+
cltv_expiry,
353+
payment_hash,
354+
transaction_output_index
355+
});
356+
347357
#[inline]
348358
pub(super) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, a_htlc_key: &PublicKey, b_htlc_key: &PublicKey, revocation_key: &PublicKey) -> Script {
349359
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
@@ -2098,8 +2098,8 @@ impl<ChanSigner: ChannelKeys, M: Deref> ChannelManager<ChanSigner, M> where M::T
20982098
if chan.get().get_their_node_id() != *their_node_id {
20992099
return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
21002100
}
2101-
let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
2102-
if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2101+
let monitor_update = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
2102+
if let Err(e) = self.monitor.update_monitor(chan.get().get_funding_txo().unwrap(), monitor_update) {
21032103
return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, false, false);
21042104
}
21052105
(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
@@ -643,16 +643,53 @@ const MIN_SERIALIZATION_VERSION: u8 = 1;
643643
#[cfg_attr(test, derive(PartialEq))]
644644
#[derive(Clone)]
645645
pub(super) enum ChannelMonitorUpdateStep {
646+
LatestLocalCommitmentTXInfo {
647+
commitment_tx: LocalCommitmentTransaction,
648+
local_keys: chan_utils::TxCreationKeys,
649+
feerate_per_kw: u64,
650+
htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
651+
},
646652
}
647653

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

@@ -1299,8 +1336,10 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
12991336
/// is important that any clones of this channel monitor (including remote clones) by kept
13001337
/// up-to-date as our local commitment transaction is updated.
13011338
/// Panics if set_their_to_self_delay has never been called.
1302-
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>)>) {
1303-
assert!(self.their_to_self_delay.is_some());
1339+
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> {
1340+
if self.their_to_self_delay.is_none() {
1341+
return Err(MonitorUpdateError("Got a local commitment tx info update before we'd set basic information about the channel"));
1342+
}
13041343
self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
13051344
self.current_local_signed_commitment_tx = Some(LocalSignedTx {
13061345
txid: commitment_tx.txid(),
@@ -1313,6 +1352,7 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
13131352
feerate_per_kw,
13141353
htlc_outputs,
13151354
});
1355+
Ok(())
13161356
}
13171357

13181358
/// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
@@ -1331,6 +1371,8 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
13311371
}
13321372
for update in updates.updates.drain(..) {
13331373
match update {
1374+
ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { commitment_tx, local_keys, feerate_per_kw, htlc_outputs } =>
1375+
self.provide_latest_local_commitment_tx_info(commitment_tx, local_keys, feerate_per_kw, htlc_outputs)?,
13341376
}
13351377
}
13361378
self.latest_update_id = updates.update_id;
@@ -3502,7 +3544,7 @@ mod tests {
35023544
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());
35033545
monitor.their_to_self_delay = Some(10);
35043546

3505-
monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10]));
3547+
monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10])).unwrap();
35063548
monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key);
35073549
monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key);
35083550
monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key);
@@ -3528,15 +3570,15 @@ mod tests {
35283570

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

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

0 commit comments

Comments
 (0)