Skip to content

Commit 7a66886

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 4985587 commit 7a66886

File tree

4 files changed

+80
-19
lines changed

4 files changed

+80
-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
@@ -2104,8 +2104,8 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref> ChannelManager<ChanSigner, M,
21042104
if chan.get().get_their_node_id() != *their_node_id {
21052105
return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
21062106
}
2107-
let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
2108-
if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2107+
let monitor_update = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
2108+
if let Err(e) = self.monitor.update_monitor(chan.get().get_funding_txo().unwrap(), monitor_update) {
21092109
return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, false, false);
21102110
}
21112111
(chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())

lightning/src/ln/channelmonitor.rs

Lines changed: 53 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -651,16 +651,56 @@ const MIN_SERIALIZATION_VERSION: u8 = 1;
651651
#[cfg_attr(test, derive(PartialEq))]
652652
#[derive(Clone)]
653653
pub(super) enum ChannelMonitorUpdateStep {
654+
LatestLocalCommitmentTXInfo {
655+
// TODO: We really need to not be generating a fully-signed transaction in Channel and
656+
// passing it here, we need to hold off so that the ChanSigner can enforce a
657+
// only-sign-local-state-for-broadcast once invariant:
658+
commitment_tx: LocalCommitmentTransaction,
659+
local_keys: chan_utils::TxCreationKeys,
660+
feerate_per_kw: u64,
661+
htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
662+
},
654663
}
655664

656665
impl Writeable for ChannelMonitorUpdateStep {
657-
fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::std::io::Error> {
666+
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
667+
match self {
668+
&ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { ref commitment_tx, ref local_keys, ref feerate_per_kw, ref htlc_outputs } => {
669+
0u8.write(w)?;
670+
commitment_tx.write(w)?;
671+
local_keys.write(w)?;
672+
feerate_per_kw.write(w)?;
673+
(htlc_outputs.len() as u64).write(w)?;
674+
for &(ref output, ref signature, ref source) in htlc_outputs.iter() {
675+
output.write(w)?;
676+
signature.write(w)?;
677+
source.write(w)?;
678+
}
679+
}
680+
}
658681
Ok(())
659682
}
660683
}
661684
impl<R: ::std::io::Read> Readable<R> for ChannelMonitorUpdateStep {
662-
fn read(_r: &mut R) -> Result<Self, DecodeError> {
663-
unimplemented!() // We don't have any enum variants to read (and never provide Monitor Updates)
685+
fn read(r: &mut R) -> Result<Self, DecodeError> {
686+
match Readable::read(r)? {
687+
0u8 => {
688+
Ok(ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo {
689+
commitment_tx: Readable::read(r)?,
690+
local_keys: Readable::read(r)?,
691+
feerate_per_kw: Readable::read(r)?,
692+
htlc_outputs: {
693+
let len: u64 = Readable::read(r)?;
694+
let mut res = Vec::new();
695+
for _ in 0..len {
696+
res.push((Readable::read(r)?, Readable::read(r)?, Readable::read(r)?));
697+
}
698+
res
699+
},
700+
})
701+
},
702+
_ => Err(DecodeError::InvalidValue),
703+
}
664704
}
665705
}
666706

@@ -1307,8 +1347,10 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
13071347
/// is important that any clones of this channel monitor (including remote clones) by kept
13081348
/// up-to-date as our local commitment transaction is updated.
13091349
/// Panics if set_their_to_self_delay has never been called.
1310-
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>)>) {
1311-
assert!(self.their_to_self_delay.is_some());
1350+
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> {
1351+
if self.their_to_self_delay.is_none() {
1352+
return Err(MonitorUpdateError("Got a local commitment tx info update before we'd set basic information about the channel"));
1353+
}
13121354
self.prev_local_signed_commitment_tx = self.current_local_signed_commitment_tx.take();
13131355
self.current_local_signed_commitment_tx = Some(LocalSignedTx {
13141356
txid: commitment_tx.txid(),
@@ -1321,6 +1363,7 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
13211363
feerate_per_kw,
13221364
htlc_outputs,
13231365
});
1366+
Ok(())
13241367
}
13251368

13261369
/// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
@@ -1339,6 +1382,8 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
13391382
}
13401383
for update in updates.updates.drain(..) {
13411384
match update {
1385+
ChannelMonitorUpdateStep::LatestLocalCommitmentTXInfo { commitment_tx, local_keys, feerate_per_kw, htlc_outputs } =>
1386+
self.provide_latest_local_commitment_tx_info(commitment_tx, local_keys, feerate_per_kw, htlc_outputs)?,
13421387
}
13431388
}
13441389
self.latest_update_id = updates.update_id;
@@ -3514,7 +3559,7 @@ mod tests {
35143559
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());
35153560
monitor.their_to_self_delay = Some(10);
35163561

3517-
monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10]));
3562+
monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..10])).unwrap();
35183563
monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key);
35193564
monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key);
35203565
monitor.provide_latest_remote_commitment_tx_info(&dummy_tx, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key);
@@ -3540,15 +3585,15 @@ mod tests {
35403585

35413586
// Now update local commitment tx info, pruning only element 18 as we still care about the
35423587
// previous commitment tx's preimages too
3543-
monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5]));
3588+
monitor.provide_latest_local_commitment_tx_info(LocalCommitmentTransaction::dummy(), dummy_keys!(), 0, preimages_to_local_htlcs!(preimages[0..5])).unwrap();
35443589
secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
35453590
monitor.provide_secret(281474976710653, secret.clone()).unwrap();
35463591
assert_eq!(monitor.payment_preimages.len(), 12);
35473592
test_preimages_exist!(&preimages[0..10], monitor);
35483593
test_preimages_exist!(&preimages[18..20], monitor);
35493594

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

0 commit comments

Comments
 (0)