Skip to content

Commit abd78bd

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 468819d commit abd78bd

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;
@@ -1490,7 +1490,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
14901490
// Now that we're past error-generating stuff, update our local state:
14911491

14921492
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());
1493-
self.channel_monitor.provide_latest_local_commitment_tx_info(local_initial_commitment_tx, local_keys, self.feerate_per_kw, Vec::new());
1493+
self.channel_monitor.provide_latest_local_commitment_tx_info(local_initial_commitment_tx, local_keys, self.feerate_per_kw, Vec::new()).unwrap();
14941494
self.channel_state = ChannelState::FundingSent as u32;
14951495
self.channel_id = funding_txo.to_channel_id();
14961496
self.cur_remote_commitment_transaction_number -= 1;
@@ -1504,7 +1504,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
15041504

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

1531-
self.channel_monitor.provide_latest_local_commitment_tx_info(
1532-
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, self.feerate_per_kw, Vec::new());
1531+
self.latest_monitor_update_id += 1;
1532+
let monitor_update = ChannelMonitorUpdate {
1533+
update_id: self.latest_monitor_update_id,
1534+
updates: vec![ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo {
1535+
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),
1536+
local_keys, feerate_per_kw: self.feerate_per_kw, htlc_outputs: Vec::new(),
1537+
}]
1538+
};
1539+
self.channel_monitor.update_monitor(monitor_update.clone()).unwrap();
15341540
self.channel_state = ChannelState::FundingSent as u32 | (self.channel_state & (ChannelState::MonitorUpdateFailed as u32));
15351541
self.cur_local_commitment_transaction_number -= 1;
15361542

15371543
if self.channel_state & (ChannelState::MonitorUpdateFailed as u32) == 0 {
1538-
Ok(self.channel_monitor.clone())
1544+
Ok(monitor_update)
15391545
} else {
15401546
Err(ChannelError::Ignore("Previous monitor update failure prevented funding_signed from allowing funding broadcast"))
15411547
}
@@ -1830,7 +1836,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
18301836

18311837
self.channel_monitor.provide_latest_local_commitment_tx_info(
18321838
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),
1833-
local_keys, self.feerate_per_kw, htlcs_and_sigs);
1839+
local_keys, self.feerate_per_kw, htlcs_and_sigs).unwrap();
18341840

18351841
for htlc in self.pending_inbound_htlcs.iter_mut() {
18361842
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
@@ -2301,8 +2301,8 @@ impl<ChanSigner: ChannelKeys, M: Deref> ChannelManager<ChanSigner, M> where M::T
23012301
if chan.get().get_their_node_id() != *their_node_id {
23022302
return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
23032303
}
2304-
let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
2305-
if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2304+
let monitor_update = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
2305+
if let Err(e) = self.monitor.update_monitor(chan.get().get_funding_txo().unwrap(), monitor_update) {
23062306
return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, false, false);
23072307
}
23082308
(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
@@ -634,16 +634,53 @@ const MIN_SERIALIZATION_VERSION: u8 = 1;
634634
#[cfg_attr(test, derive(PartialEq))]
635635
#[derive(Clone)]
636636
pub(super) enum ChannelMonitorUpdateStep {
637+
LatestLocalCommitmentTXInfo {
638+
commitment_tx: LocalCommitmentTransaction,
639+
local_keys: chan_utils::TxCreationKeys,
640+
feerate_per_kw: u64,
641+
htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
642+
},
637643
}
638644

639645
impl Writeable for ChannelMonitorUpdateStep {
640-
fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::std::io::Error> {
646+
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
647+
match self {
648+
&ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { ref commitment_tx, ref local_keys, ref feerate_per_kw, ref htlc_outputs } => {
649+
0u8.write(w)?;
650+
commitment_tx.write(w)?;
651+
local_keys.write(w)?;
652+
feerate_per_kw.write(w)?;
653+
(htlc_outputs.len() as u64).write(w)?;
654+
for &(ref output, ref signature, ref source) in htlc_outputs.iter() {
655+
output.write(w)?;
656+
signature.write(w)?;
657+
source.write(w)?;
658+
}
659+
}
660+
}
641661
Ok(())
642662
}
643663
}
644664
impl<R: ::std::io::Read> Readable<R> for ChannelMonitorUpdateStep {
645-
fn read(_r: &mut R) -> Result<Self, DecodeError> {
646-
unimplemented!() // We don't have any enum variants to read (and never provide Monitor Updates)
665+
fn read(r: &mut R) -> Result<Self, DecodeError> {
666+
match Readable::read(r)? {
667+
0u8 => {
668+
Ok(ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo {
669+
commitment_tx: Readable::read(r)?,
670+
local_keys: Readable::read(r)?,
671+
feerate_per_kw: Readable::read(r)?,
672+
htlc_outputs: {
673+
let len: u64 = Readable::read(r)?;
674+
let mut res = Vec::new();
675+
for _ in 0..len {
676+
res.push((Readable::read(r)?, Readable::read(r)?, Readable::read(r)?));
677+
}
678+
res
679+
},
680+
})
681+
},
682+
_ => Err(DecodeError::InvalidValue),
683+
}
647684
}
648685
}
649686

@@ -1295,8 +1332,10 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
12951332
/// is important that any clones of this channel monitor (including remote clones) by kept
12961333
/// up-to-date as our local commitment transaction is updated.
12971334
/// Panics if set_their_to_self_delay has never been called.
1298-
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>)>) {
1299-
assert!(self.their_to_self_delay.is_some());
1335+
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> {
1336+
if self.their_to_self_delay.is_none() {
1337+
return Err(MonitorUpdateError("Got a local commitment tx info update before we'd set basic information about the channel"));
1338+
}
13001339
self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
13011340
self.current_local_signed_commitment_tx = Some(LocalSignedTx {
13021341
txid: commitment_tx.txid(),
@@ -1309,6 +1348,7 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
13091348
feerate_per_kw,
13101349
htlc_outputs,
13111350
});
1351+
Ok(())
13121352
}
13131353

13141354
/// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
@@ -1327,6 +1367,8 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
13271367
}
13281368
for update in updates.updates.drain(..) {
13291369
match update {
1370+
ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { commitment_tx, local_keys, feerate_per_kw, htlc_outputs } =>
1371+
self.provide_latest_local_commitment_tx_info(commitment_tx, local_keys, feerate_per_kw, htlc_outputs)?,
13301372
}
13311373
}
13321374
self.latest_update_id = updates.update_id;
@@ -3533,7 +3575,7 @@ mod tests {
35333575
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());
35343576
monitor.their_to_self_delay = Some(10);
35353577

3536-
monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10]));
3578+
monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10])).unwrap();
35373579
monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key);
35383580
monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key);
35393581
monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key);
@@ -3559,15 +3601,15 @@ mod tests {
35593601

35603602
// Now update local commitment tx info, pruning only element 18 as we still care about the
35613603
// previous commitment tx's preimages too
3562-
monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5]));
3604+
monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5])).unwrap();
35633605
secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
35643606
monitor.provide_secret(281474976710653, secret.clone()).unwrap();
35653607
assert_eq!(monitor.payment_preimages.len(), 12);
35663608
test_preimages_exist!(&preimages[0..10], monitor);
35673609
test_preimages_exist!(&preimages[18..20], monitor);
35683610

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

0 commit comments

Comments
 (0)