Skip to content

Commit ab3d2fd

Browse files
committed
Require option_static_remotekey in channel/channelmonitor.
This simplifies channelmonitor quite nicely (as expected) as we never have to be concerned with learning data in a DataLossProtect which is require for us to claim our funds from the latest remote commitment transaction.
1 parent 9488ca4 commit ab3d2fd

9 files changed

+192
-266
lines changed

lightning/src/chain/keysinterface.rs

+2
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,8 @@ pub enum SpendableOutputDescriptor {
7373
/// The output which is referenced by the given outpoint
7474
output: TxOut,
7575
},
76+
// TODO: Note that because key is now static and exactly what is provided by us, we should drop
77+
// this in favor of StaticOutput:
7678
/// An output to a P2WPKH, spendable exclusively by the given private key.
7779
/// The witness in the spending input, is, thus, simply:
7880
/// <BIP 143 signature generated with the given key> <public key derived from the given key>

lightning/src/ln/chan_utils.rs

+2-5
Original file line numberDiff line numberDiff line change
@@ -259,11 +259,9 @@ pub struct TxCreationKeys {
259259
pub(crate) b_htlc_key: PublicKey,
260260
/// A's Payment Key (which isn't allowed to be spent from for some delay)
261261
pub(crate) a_delayed_payment_key: PublicKey,
262-
/// B's Payment Key
263-
pub(crate) b_payment_key: PublicKey,
264262
}
265263
impl_writeable!(TxCreationKeys, 33*6,
266-
{ per_commitment_point, revocation_key, a_htlc_key, b_htlc_key, a_delayed_payment_key, b_payment_key });
264+
{ per_commitment_point, revocation_key, a_htlc_key, b_htlc_key, a_delayed_payment_key });
267265

268266
/// One counterparty's public keys which do not change over the life of a channel.
269267
#[derive(Clone, PartialEq)]
@@ -298,14 +296,13 @@ impl_writeable!(ChannelPublicKeys, 33*5, {
298296

299297

300298
impl TxCreationKeys {
301-
pub(crate) fn new<T: secp256k1::Signing + secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, a_delayed_payment_base: &PublicKey, a_htlc_base: &PublicKey, b_revocation_base: &PublicKey, b_payment_base: &PublicKey, b_htlc_base: &PublicKey) -> Result<TxCreationKeys, secp256k1::Error> {
299+
pub(crate) fn new<T: secp256k1::Signing + secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, a_delayed_payment_base: &PublicKey, a_htlc_base: &PublicKey, b_revocation_base: &PublicKey, b_htlc_base: &PublicKey) -> Result<TxCreationKeys, secp256k1::Error> {
302300
Ok(TxCreationKeys {
303301
per_commitment_point: per_commitment_point.clone(),
304302
revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &b_revocation_base)?,
305303
a_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &a_htlc_base)?,
306304
b_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &b_htlc_base)?,
307305
a_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &a_delayed_payment_base)?,
308-
b_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &b_payment_base)?,
309306
})
310307
}
311308
}

lightning/src/ln/channel.rs

+150-160
Large diffs are not rendered by default.

lightning/src/ln/channelmanager.rs

+4-14
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,7 @@ impl MsgHandleErrInternal {
244244
},
245245
},
246246
},
247-
ChannelError::CloseDelayBroadcast { msg, .. } => LightningError {
247+
ChannelError::CloseDelayBroadcast(msg) => LightningError {
248248
err: msg,
249249
action: msgs::ErrorAction::SendErrorMessage {
250250
msg: msgs::ErrorMessage {
@@ -541,7 +541,7 @@ macro_rules! break_chan_entry {
541541
}
542542
break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
543543
},
544-
Err(ChannelError::CloseDelayBroadcast { .. }) => { panic!("Wait is only generated on receipt of channel_reestablish, which is handled by try_chan_entry, we don't bother to support it here"); }
544+
Err(ChannelError::CloseDelayBroadcast(_)) => { panic!("Wait is only generated on receipt of channel_reestablish, which is handled by try_chan_entry, we don't bother to support it here"); }
545545
}
546546
}
547547
}
@@ -561,22 +561,12 @@ macro_rules! try_chan_entry {
561561
}
562562
return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
563563
},
564-
Err(ChannelError::CloseDelayBroadcast { msg, update }) => {
564+
Err(ChannelError::CloseDelayBroadcast(msg)) => {
565565
log_error!($self, "Channel {} need to be shutdown but closing transactions not broadcast due to {}", log_bytes!($entry.key()[..]), msg);
566566
let (channel_id, mut chan) = $entry.remove_entry();
567567
if let Some(short_id) = chan.get_short_channel_id() {
568568
$channel_state.short_to_id.remove(&short_id);
569569
}
570-
if let Err(e) = $self.monitor.update_monitor(chan.get_funding_txo().unwrap(), update) {
571-
match e {
572-
// Upstream channel is dead, but we want at least to fail backward HTLCs to save
573-
// downstream channels. In case of PermanentFailure, we are not going to be able
574-
// to claim back to_remote output on remote commitment transaction. Doesn't
575-
// make a difference here, we are concern about HTLCs circuit, not onchain funds.
576-
ChannelMonitorUpdateErr::PermanentFailure => {},
577-
ChannelMonitorUpdateErr::TemporaryFailure => {},
578-
}
579-
}
580570
let mut shutdown_res = chan.force_shutdown();
581571
if shutdown_res.0.len() >= 1 {
582572
log_error!($self, "You have a toxic local commitment transaction {} avaible in channel monitor, read comment in ChannelMonitor::get_latest_local_commitment_txn to be informed of manual action to take", shutdown_res.0[0].txid());
@@ -1635,7 +1625,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
16351625
}
16361626
Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, channel.force_shutdown(), self.get_channel_update(&channel).ok()))
16371627
},
1638-
ChannelError::CloseDelayBroadcast { .. } => { panic!("Wait is only generated on receipt of channel_reestablish, which is handled by try_chan_entry, we don't bother to support it here"); }
1628+
ChannelError::CloseDelayBroadcast(_) => { panic!("Wait is only generated on receipt of channel_reestablish, which is handled by try_chan_entry, we don't bother to support it here"); }
16391629
};
16401630
match handle_error!(self, err, their_node_id, channel_state) {
16411631
Ok(_) => unreachable!(),

lightning/src/ln/channelmonitor.rs

+25-79
Original file line numberDiff line numberDiff line change
@@ -616,11 +616,6 @@ pub(super) enum ChannelMonitorUpdateStep {
616616
idx: u64,
617617
secret: [u8; 32],
618618
},
619-
/// Indicates our channel is likely a stale version, we're closing, but this update should
620-
/// allow us to spend what is ours if our counterparty broadcasts their latest state.
621-
RescueRemoteCommitmentTXInfo {
622-
their_current_per_commitment_point: PublicKey,
623-
},
624619
}
625620

626621
impl Writeable for ChannelMonitorUpdateStep {
@@ -658,10 +653,6 @@ impl Writeable for ChannelMonitorUpdateStep {
658653
idx.write(w)?;
659654
secret.write(w)?;
660655
},
661-
&ChannelMonitorUpdateStep::RescueRemoteCommitmentTXInfo { ref their_current_per_commitment_point } => {
662-
4u8.write(w)?;
663-
their_current_per_commitment_point.write(w)?;
664-
},
665656
}
666657
Ok(())
667658
}
@@ -710,11 +701,6 @@ impl Readable for ChannelMonitorUpdateStep {
710701
secret: Readable::read(r)?,
711702
})
712703
},
713-
4u8 => {
714-
Ok(ChannelMonitorUpdateStep::RescueRemoteCommitmentTXInfo {
715-
their_current_per_commitment_point: Readable::read(r)?,
716-
})
717-
},
718704
_ => Err(DecodeError::InvalidValue),
719705
}
720706
}
@@ -775,11 +761,6 @@ pub struct ChannelMonitor<ChanSigner: ChannelKeys> {
775761
pending_htlcs_updated: Vec<HTLCUpdate>,
776762
pending_events: Vec<events::Event>,
777763

778-
// Thanks to data loss protection, we may be able to claim our non-htlc funds
779-
// back, this is the script we have to spend from but we need to
780-
// scan every commitment transaction for that
781-
to_remote_rescue: Option<(Script, SecretKey)>,
782-
783764
// Used to track onchain events, i.e transactions parts of channels confirmed on chain, on which
784765
// we have to take actions once they reach enough confs. Key is a block height timer, i.e we enforce
785766
// actions when we receive a block with given height. Actions depend on OnchainEvent type.
@@ -831,7 +812,6 @@ impl<ChanSigner: ChannelKeys> PartialEq for ChannelMonitor<ChanSigner> {
831812
self.payment_preimages != other.payment_preimages ||
832813
self.pending_htlcs_updated != other.pending_htlcs_updated ||
833814
self.pending_events.len() != other.pending_events.len() || // We trust events to round-trip properly
834-
self.to_remote_rescue != other.to_remote_rescue ||
835815
self.onchain_events_waiting_threshold_conf != other.onchain_events_waiting_threshold_conf ||
836816
self.outputs_to_watch != other.outputs_to_watch
837817
{
@@ -1009,13 +989,6 @@ impl<ChanSigner: ChannelKeys + Writeable> ChannelMonitor<ChanSigner> {
1009989
}
1010990

1011991
self.last_block_hash.write(writer)?;
1012-
if let Some((ref to_remote_script, ref local_key)) = self.to_remote_rescue {
1013-
writer.write_all(&[1; 1])?;
1014-
to_remote_script.write(writer)?;
1015-
local_key.write(writer)?;
1016-
} else {
1017-
writer.write_all(&[0; 1])?;
1018-
}
1019992

1020993
writer.write_all(&byte_utils::be64_to_array(self.onchain_events_waiting_threshold_conf.len() as u64))?;
1021994
for (ref target, ref events) in self.onchain_events_waiting_threshold_conf.iter() {
@@ -1120,8 +1093,6 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
11201093
pending_htlcs_updated: Vec::new(),
11211094
pending_events: Vec::new(),
11221095

1123-
to_remote_rescue: None,
1124-
11251096
onchain_events_waiting_threshold_conf: HashMap::new(),
11261097
outputs_to_watch: HashMap::new(),
11271098

@@ -1229,22 +1200,6 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
12291200
}
12301201
}
12311202

1232-
pub(super) fn provide_rescue_remote_commitment_tx_info(&mut self, their_revocation_point: PublicKey) {
1233-
match self.key_storage {
1234-
Storage::Local { ref payment_base_key, ref keys, .. } => {
1235-
if let Ok(payment_key) = chan_utils::derive_public_key(&self.secp_ctx, &their_revocation_point, &keys.pubkeys().payment_basepoint) {
1236-
let to_remote_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1237-
.push_slice(&Hash160::hash(&payment_key.serialize())[..])
1238-
.into_script();
1239-
if let Ok(to_remote_key) = chan_utils::derive_private_key(&self.secp_ctx, &their_revocation_point, &payment_base_key) {
1240-
self.to_remote_rescue = Some((to_remote_script, to_remote_key));
1241-
}
1242-
}
1243-
},
1244-
Storage::Watchtower { .. } => {}
1245-
}
1246-
}
1247-
12481203
/// Informs this monitor of the latest local (ie broadcastable) commitment transaction. The
12491204
/// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
12501205
/// is important that any clones of this channel monitor (including remote clones) by kept
@@ -1287,8 +1242,6 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
12871242
self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage),
12881243
ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } =>
12891244
self.provide_secret(idx, secret)?,
1290-
ChannelMonitorUpdateStep::RescueRemoteCommitmentTXInfo { their_current_per_commitment_point } =>
1291-
self.provide_rescue_remote_commitment_tx_info(their_current_per_commitment_point),
12921245
}
12931246
}
12941247
self.latest_update_id = updates.update_id;
@@ -1313,8 +1266,6 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
13131266
self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage),
13141267
ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } =>
13151268
self.provide_secret(idx, secret)?,
1316-
ChannelMonitorUpdateStep::RescueRemoteCommitmentTXInfo { their_current_per_commitment_point } =>
1317-
self.provide_rescue_remote_commitment_tx_info(their_current_per_commitment_point),
13181269
}
13191270
}
13201271
self.latest_update_id = updates.update_id;
@@ -1436,7 +1387,7 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
14361387
(ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &keys.pubkeys().revocation_basepoint)),
14371388
ignore_error!(chan_utils::derive_private_revocation_key(&self.secp_ctx, &per_commitment_key, &revocation_base_key)),
14381389
ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &per_commitment_point, &keys.pubkeys().htlc_basepoint)),
1439-
Some(ignore_error!(chan_utils::derive_private_key(&self.secp_ctx, &per_commitment_point, &payment_base_key))))
1390+
Some(payment_base_key))
14401391
},
14411392
Storage::Watchtower { .. } => {
14421393
unimplemented!()
@@ -1466,7 +1417,7 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
14661417
} else if Some(&outp.script_pubkey) == local_payment_p2wpkh.as_ref() {
14671418
spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
14681419
outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1469-
key: local_payment_key.unwrap(),
1420+
key: local_payment_key.unwrap().clone(),
14701421
output: outp.clone(),
14711422
});
14721423
}
@@ -1620,13 +1571,11 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
16201571
if outp.script_pubkey.is_v0_p2wpkh() {
16211572
match self.key_storage {
16221573
Storage::Local { ref payment_base_key, .. } => {
1623-
if let Ok(local_key) = chan_utils::derive_private_key(&self.secp_ctx, &revocation_point, &payment_base_key) {
1624-
spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1625-
outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1626-
key: local_key,
1627-
output: outp.clone(),
1628-
});
1629-
}
1574+
spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1575+
outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1576+
key: payment_base_key.clone(),
1577+
output: outp.clone(),
1578+
});
16301579
},
16311580
Storage::Watchtower { .. } => {}
16321581
}
@@ -1653,15 +1602,24 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
16531602
}
16541603
}
16551604
}
1656-
} else if let Some((ref to_remote_rescue, ref local_key)) = self.to_remote_rescue {
1657-
for (idx, outp) in tx.output.iter().enumerate() {
1658-
if to_remote_rescue == &outp.script_pubkey {
1659-
spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1660-
outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1661-
key: local_key.clone(),
1662-
output: outp.clone(),
1663-
});
1664-
}
1605+
} else {
1606+
match self.key_storage {
1607+
Storage::Local { ref payment_base_key, .. } => {
1608+
let payment_hash160 = Hash160::hash(&PublicKey::from_secret_key(&self.secp_ctx, &payment_base_key).serialize());
1609+
let our_payment_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1610+
.push_slice(&payment_hash160)
1611+
.into_script();
1612+
for (idx, outp) in tx.output.iter().enumerate() {
1613+
if our_payment_script == outp.script_pubkey {
1614+
spendable_outputs.push(SpendableOutputDescriptor::DynamicOutputP2WPKH {
1615+
outpoint: BitcoinOutPoint { txid: commitment_txid, vout: idx as u32 },
1616+
key: payment_base_key.clone(),
1617+
output: outp.clone(),
1618+
});
1619+
}
1620+
}
1621+
},
1622+
Storage::Watchtower { .. } => unimplemented!(),
16651623
}
16661624
}
16671625
(claimable_outpoints, (commitment_txid, watch_outputs), spendable_outputs)
@@ -2524,15 +2482,6 @@ impl<ChanSigner: ChannelKeys + Readable> ReadableArgs<Arc<Logger>> for (Sha256dH
25242482
}
25252483

25262484
let last_block_hash: Sha256dHash = Readable::read(reader)?;
2527-
let to_remote_rescue = match <u8 as Readable>::read(reader)? {
2528-
0 => None,
2529-
1 => {
2530-
let to_remote_script = Readable::read(reader)?;
2531-
let local_key = Readable::read(reader)?;
2532-
Some((to_remote_script, local_key))
2533-
}
2534-
_ => return Err(DecodeError::InvalidValue),
2535-
};
25362485

25372486
let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
25382487
let mut onchain_events_waiting_threshold_conf = HashMap::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
@@ -2598,8 +2547,6 @@ impl<ChanSigner: ChannelKeys + Readable> ReadableArgs<Arc<Logger>> for (Sha256dH
25982547
pending_htlcs_updated,
25992548
pending_events,
26002549

2601-
to_remote_rescue,
2602-
26032550
onchain_events_waiting_threshold_conf,
26042551
outputs_to_watch,
26052552

@@ -2652,7 +2599,6 @@ mod tests {
26522599
a_htlc_key: dummy_key.clone(),
26532600
b_htlc_key: dummy_key.clone(),
26542601
a_delayed_payment_key: dummy_key.clone(),
2655-
b_payment_key: dummy_key.clone(),
26562602
}
26572603
}
26582604
}

lightning/src/ln/features.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ impl InitFeatures {
8989
1 << 1 | // data_loss_protect supported
9090
1 << 5, // upfront_shutdown_script supported
9191
1 << (9 - 8*1) | // variable_length_onion supported
92+
1 << (12 - 8*1) | // static_remotekey required
9293
1 << (15 - 8*1), // basic_mpp supportedyment_secret supported
9394
1 << (17 - 8*2) // basic_mpp supported
9495
],
@@ -210,8 +211,8 @@ impl<T: sealed::Context> Features<T> {
210211
// unknown, upfront_shutdown_script, unknown (actually initial_routing_sync, but it
211212
// is only valid as an optional feature), and data_loss_protect:
212213
0 => (byte & 0b01000100),
213-
// payment_secret, unknown, unknown, var_onion_optin:
214-
1 => (byte & 0b00010100),
214+
// payment_secret, static_remotekey, unknown, var_onion_optin:
215+
1 => (byte & 0b00000100),
215216
// unknown, unknown, unknown, basic_mpp:
216217
2 => (byte & 0b01010100),
217218
// fallback, all even bits set:

lightning/src/ln/functional_tests.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -6553,7 +6553,7 @@ fn test_data_loss_protect() {
65536553
// We want to be sure that :
65546554
// * we don't broadcast our Local Commitment Tx in case of fallen behind
65556555
// * we close channel in case of detecting other being fallen behind
6556-
// * we are able to claim our own outputs thanks to remote my_current_per_commitment_point
6556+
// * we are able to claim our own outputs thanks to to_remote being static
65576557
let keys_manager;
65586558
let fee_estimator;
65596559
let tx_broadcaster;
@@ -6614,10 +6614,8 @@ fn test_data_loss_protect() {
66146614

66156615
let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
66166616

6617-
// Check we update monitor following learning of per_commitment_point from B
6617+
// Check we don't broadcast any transactions following learning of per_commitment_point from B
66186618
nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
6619-
check_added_monitors!(nodes[0], 1);
6620-
66216619
{
66226620
let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
66236621
assert_eq!(node_txn.len(), 0);

lightning/src/ln/peer_handler.rs

+4
Original file line numberDiff line numberDiff line change
@@ -637,6 +637,10 @@ impl<Descriptor: SocketDescriptor, CM: Deref> PeerManager<Descriptor, CM> where
637637
peer.sync_status = InitSyncTracker::ChannelsSyncing(0);
638638
peers.peers_needing_send.insert(peer_descriptor.clone());
639639
}
640+
if !msg.features.supports_static_remote_key() {
641+
log_debug!(self, "Peer {} does not support static remote key, disconnecting with no_connection_possible", log_pubkey!(peer.their_node_id.unwrap()));
642+
return Err(PeerHandleError{ no_connection_possible: true });
643+
}
640644

641645
if !peer.outbound {
642646
let mut features = InitFeatures::supported();

lightning/src/util/enforcing_trait_impls.rs

-2
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@ impl EnforcingChannelKeys {
3535
fn check_keys<T: secp256k1::Signing + secp256k1::Verification>(&self, secp_ctx: &Secp256k1<T>,
3636
keys: &TxCreationKeys) {
3737
let revocation_base = PublicKey::from_secret_key(secp_ctx, &self.inner.revocation_base_key());
38-
let payment_base = PublicKey::from_secret_key(secp_ctx, &self.inner.payment_base_key());
3938
let htlc_base = PublicKey::from_secret_key(secp_ctx, &self.inner.htlc_base_key());
4039

4140
let remote_points = self.inner.remote_channel_pubkeys.as_ref().unwrap();
@@ -45,7 +44,6 @@ impl EnforcingChannelKeys {
4544
&remote_points.delayed_payment_basepoint,
4645
&remote_points.htlc_basepoint,
4746
&revocation_base,
48-
&payment_base,
4947
&htlc_base).unwrap();
5048
if keys != &keys_expected { panic!("derived different per-tx keys") }
5149
}

0 commit comments

Comments
 (0)