Skip to content

Commit 745be58

Browse files
committed
Allow get_per_commitment_point to fail.
This changes `ChannelSigner::get_per_commitment_point` to return a `Result<PublicKey, ()`, which means that it can fail. Similarly, it changes `ChannelSigner::release_commitment_secret`. In order to accomodate failure at the callsites that otherwise assumed it was infallible, we cache the next per-commitment point each time the state advances in the `ChannelContext` and change the callsites to instead use the cached value.
1 parent 3dffe54 commit 745be58

File tree

6 files changed

+102
-49
lines changed

6 files changed

+102
-49
lines changed

lightning/src/chain/channelmonitor.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2752,9 +2752,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
27522752
},
27532753
commitment_txid: htlc.commitment_txid,
27542754
per_commitment_number: htlc.per_commitment_number,
2755-
per_commitment_point: self.onchain_tx_handler.signer.get_per_commitment_point(
2756-
htlc.per_commitment_number, &self.onchain_tx_handler.secp_ctx,
2757-
),
2755+
per_commitment_point: htlc.per_commitment_point,
27582756
htlc: htlc.htlc,
27592757
preimage: htlc.preimage,
27602758
counterparty_sig: htlc.counterparty_sig,

lightning/src/chain/onchaintx.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,7 @@ pub(crate) struct ExternalHTLCClaim {
179179
pub(crate) htlc: HTLCOutputInCommitment,
180180
pub(crate) preimage: Option<PaymentPreimage>,
181181
pub(crate) counterparty_sig: Signature,
182+
pub(crate) per_commitment_point: bitcoin::secp256k1::PublicKey,
182183
}
183184

184185
// Represents the different types of claims for which events are yielded externally to satisfy said
@@ -1188,9 +1189,16 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
11881189
})
11891190
.map(|(htlc_idx, htlc)| {
11901191
let counterparty_htlc_sig = holder_commitment.counterparty_htlc_sigs[htlc_idx];
1192+
1193+
// TODO(waterson) fallible: move this somewhere!
1194+
let per_commitment_point = self.signer.get_per_commitment_point(
1195+
trusted_tx.commitment_number(), &self.secp_ctx,
1196+
).unwrap();
1197+
11911198
ExternalHTLCClaim {
11921199
commitment_txid: trusted_tx.txid(),
11931200
per_commitment_number: trusted_tx.commitment_number(),
1201+
per_commitment_point: per_commitment_point,
11941202
htlc: htlc.clone(),
11951203
preimage: *preimage,
11961204
counterparty_sig: counterparty_htlc_sig,

lightning/src/ln/channel.rs

Lines changed: 70 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ use crate::chain::BestBlock;
3535
use crate::chain::chaininterface::{FeeEstimator, ConfirmationTarget, LowerBoundedFeeEstimator};
3636
use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, LATENCY_GRACE_PERIOD_BLOCKS, CLOSED_CHANNEL_UPDATE_ID};
3737
use crate::chain::transaction::{OutPoint, TransactionData};
38-
use crate::sign::{EcdsaChannelSigner, WriteableEcdsaChannelSigner, EntropySource, ChannelSigner, SignerProvider, NodeSigner, Recipient};
38+
use crate::sign::{EcdsaChannelSigner, WriteableEcdsaChannelSigner, EntropySource, ChannelSigner, SignerProvider, NodeSigner, Recipient, SignerError};
3939
use crate::events::ClosureReason;
4040
use crate::routing::gossip::NodeId;
4141
use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer, VecWriter};
@@ -667,6 +667,13 @@ pub(super) struct ChannelContext<SP: Deref> where SP::Target: SignerProvider {
667667
// cost of others, but should really just be changed.
668668

669669
cur_holder_commitment_transaction_number: u64,
670+
671+
// The commitment point corresponding to `cur_holder_commitment_transaction_number`, which is the
672+
// *next* state. We recompute it each time the state changes because the state changes in places
673+
// that might be fallible: in particular, if the commitment point must be fetched from a remote
674+
// source, we want to ensure it happens at a point where we can actually fail somewhat gracefully;
675+
// i.e., force-closing a channel is better than a panic!
676+
next_per_commitment_point: PublicKey,
670677
cur_counterparty_commitment_transaction_number: u64,
671678
value_to_self_msat: u64, // Excluding all pending_htlcs, excluding fees
672679
pending_inbound_htlcs: Vec<InboundHTLCOutput>,
@@ -1442,13 +1449,14 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
14421449
/// our counterparty!)
14431450
/// The result is a transaction which we can revoke broadcastership of (ie a "local" transaction)
14441451
/// TODO Some magic rust shit to compile-time check this?
1445-
fn build_holder_transaction_keys(&self, commitment_number: u64) -> TxCreationKeys {
1446-
let per_commitment_point = self.holder_signer.as_ref().get_per_commitment_point(commitment_number, &self.secp_ctx);
1452+
fn build_holder_transaction_keys(&self) -> TxCreationKeys {
14471453
let delayed_payment_base = &self.get_holder_pubkeys().delayed_payment_basepoint;
14481454
let htlc_basepoint = &self.get_holder_pubkeys().htlc_basepoint;
14491455
let counterparty_pubkeys = self.get_counterparty_pubkeys();
14501456

1451-
TxCreationKeys::derive_new(&self.secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint)
1457+
TxCreationKeys::derive_new(
1458+
&self.secp_ctx, &self.next_per_commitment_point, delayed_payment_base, htlc_basepoint,
1459+
&counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint)
14521460
}
14531461

14541462
#[inline]
@@ -2495,7 +2503,12 @@ impl<SP: Deref> Channel<SP> where
24952503
log_trace!(logger, "Initial counterparty tx for channel {} is: txid {} tx {}",
24962504
log_bytes!(self.context.channel_id()), counterparty_initial_bitcoin_tx.txid, encode::serialize_hex(&counterparty_initial_bitcoin_tx.transaction));
24972505

2498-
let holder_signer = self.context.build_holder_transaction_keys(self.context.cur_holder_commitment_transaction_number);
2506+
self.context.next_per_commitment_point =
2507+
self.context.holder_signer.as_ref().get_per_commitment_point(
2508+
self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx
2509+
).map_err(|_| ChannelError::Close("Unable to generate commitment point".to_owned()))?;
2510+
2511+
let holder_signer = self.context.build_holder_transaction_keys();
24992512
let initial_commitment_tx = self.context.build_commitment_transaction(self.context.cur_holder_commitment_transaction_number, &holder_signer, true, false, logger).tx;
25002513
{
25012514
let trusted_tx = initial_commitment_tx.trust();
@@ -2545,6 +2558,11 @@ impl<SP: Deref> Channel<SP> where
25452558
assert_eq!(self.context.channel_state & (ChannelState::MonitorUpdateInProgress as u32), 0); // We have no had any monitor(s) yet to fail update!
25462559
self.context.channel_state = ChannelState::FundingSent as u32;
25472560
self.context.cur_holder_commitment_transaction_number -= 1;
2561+
self.context.next_per_commitment_point =
2562+
self.context.holder_signer.as_ref().get_per_commitment_point(
2563+
self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx
2564+
).map_err(|_| ChannelError::Close("Unable to generate commitment point".to_owned()))?;
2565+
25482566
self.context.cur_counterparty_commitment_transaction_number -= 1;
25492567

25502568
log_info!(logger, "Received funding_signed from peer for channel {}", log_bytes!(self.context.channel_id()));
@@ -2866,7 +2884,7 @@ impl<SP: Deref> Channel<SP> where
28662884

28672885
let funding_script = self.context.get_funding_redeemscript();
28682886

2869-
let keys = self.context.build_holder_transaction_keys(self.context.cur_holder_commitment_transaction_number);
2887+
let keys = self.context.build_holder_transaction_keys();
28702888

28712889
let commitment_stats = self.context.build_commitment_transaction(self.context.cur_holder_commitment_transaction_number, &keys, true, false, logger);
28722890
let commitment_txid = {
@@ -3030,6 +3048,11 @@ impl<SP: Deref> Channel<SP> where
30303048
};
30313049

30323050
self.context.cur_holder_commitment_transaction_number -= 1;
3051+
self.context.next_per_commitment_point =
3052+
self.context.holder_signer.as_ref().get_per_commitment_point(
3053+
self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx
3054+
).map_err(|_| ChannelError::Close("Unable to generate commitment point".to_owned()))?;
3055+
30333056
// Note that if we need_commitment & !AwaitingRemoteRevoke we'll call
30343057
// build_commitment_no_status_check() next which will reset this to RAAFirst.
30353058
self.context.resend_order = RAACommitmentOrder::CommitmentFirst;
@@ -3509,7 +3532,7 @@ impl<SP: Deref> Channel<SP> where
35093532
// Before proposing a feerate update, check that we can actually afford the new fee.
35103533
let inbound_stats = self.context.get_inbound_pending_htlc_stats(Some(feerate_per_kw));
35113534
let outbound_stats = self.context.get_outbound_pending_htlc_stats(Some(feerate_per_kw));
3512-
let keys = self.context.build_holder_transaction_keys(self.context.cur_holder_commitment_transaction_number);
3535+
let keys = self.context.build_holder_transaction_keys();
35133536
let commitment_stats = self.context.build_commitment_transaction(self.context.cur_holder_commitment_transaction_number, &keys, true, true, logger);
35143537
let buffer_fee_msat = commit_tx_fee_sat(feerate_per_kw, commitment_stats.num_nondust_htlcs + outbound_stats.on_holder_tx_holding_cell_htlcs_count as usize + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as usize, self.context.get_channel_type()) * 1000;
35153538
let holder_balance_msat = commitment_stats.local_balance_msat - outbound_stats.holding_cell_msat;
@@ -3690,10 +3713,9 @@ impl<SP: Deref> Channel<SP> where
36903713
assert!(!self.context.is_outbound() || self.context.minimum_depth == Some(0),
36913714
"Funding transaction broadcast by the local client before it should have - LDK didn't do it!");
36923715
self.context.monitor_pending_channel_ready = false;
3693-
let next_per_commitment_point = self.context.holder_signer.as_ref().get_per_commitment_point(self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx);
36943716
Some(msgs::ChannelReady {
36953717
channel_id: self.context.channel_id(),
3696-
next_per_commitment_point,
3718+
next_per_commitment_point: self.context.next_per_commitment_point,
36973719
short_channel_id_alias: Some(self.context.outbound_scid_alias),
36983720
})
36993721
} else { None };
@@ -3772,12 +3794,13 @@ impl<SP: Deref> Channel<SP> where
37723794
}
37733795

37743796
fn get_last_revoke_and_ack(&self) -> msgs::RevokeAndACK {
3775-
let next_per_commitment_point = self.context.holder_signer.as_ref().get_per_commitment_point(self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx);
3776-
let per_commitment_secret = self.context.holder_signer.as_ref().release_commitment_secret(self.context.cur_holder_commitment_transaction_number + 2);
3797+
// TODO(waterson): fallible!
3798+
let per_commitment_secret = self.context.holder_signer.as_ref().release_commitment_secret(self.context.cur_holder_commitment_transaction_number + 2)
3799+
.expect("release_per_commitment failed");
37773800
msgs::RevokeAndACK {
37783801
channel_id: self.context.channel_id,
37793802
per_commitment_secret,
3780-
next_per_commitment_point,
3803+
next_per_commitment_point: self.context.next_per_commitment_point,
37813804
#[cfg(taproot)]
37823805
next_local_nonce: None,
37833806
}
@@ -3887,7 +3910,9 @@ impl<SP: Deref> Channel<SP> where
38873910
}
38883911

38893912
if msg.next_remote_commitment_number > 0 {
3890-
let expected_point = self.context.holder_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - msg.next_remote_commitment_number + 1, &self.context.secp_ctx);
3913+
let state_index = INITIAL_COMMITMENT_NUMBER - msg.next_remote_commitment_number + 1;
3914+
let expected_point = self.context.holder_signer.as_ref().get_per_commitment_point(state_index, &self.context.secp_ctx)
3915+
.map_err(|_| ChannelError::Close(format!("Unable to retrieve per-commitment point for state {state_index}")))?;
38913916
let given_secret = SecretKey::from_slice(&msg.your_last_per_commitment_secret)
38923917
.map_err(|_| ChannelError::Close("Peer sent a garbage channel_reestablish with unparseable secret key".to_owned()))?;
38933918
if expected_point != PublicKey::from_secret_key(&self.context.secp_ctx, &given_secret) {
@@ -3946,11 +3971,10 @@ impl<SP: Deref> Channel<SP> where
39463971
}
39473972

39483973
// We have OurChannelReady set!
3949-
let next_per_commitment_point = self.context.holder_signer.as_ref().get_per_commitment_point(self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx);
39503974
return Ok(ReestablishResponses {
39513975
channel_ready: Some(msgs::ChannelReady {
39523976
channel_id: self.context.channel_id(),
3953-
next_per_commitment_point,
3977+
next_per_commitment_point: self.context.next_per_commitment_point,
39543978
short_channel_id_alias: Some(self.context.outbound_scid_alias),
39553979
}),
39563980
raa: None, commitment_update: None,
@@ -3986,10 +4010,9 @@ impl<SP: Deref> Channel<SP> where
39864010

39874011
let channel_ready = if msg.next_local_commitment_number == 1 && INITIAL_COMMITMENT_NUMBER - self.context.cur_holder_commitment_transaction_number == 1 {
39884012
// We should never have to worry about MonitorUpdateInProgress resending ChannelReady
3989-
let next_per_commitment_point = self.context.holder_signer.as_ref().get_per_commitment_point(self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx);
39904013
Some(msgs::ChannelReady {
39914014
channel_id: self.context.channel_id(),
3992-
next_per_commitment_point,
4015+
next_per_commitment_point: self.context.next_per_commitment_point,
39934016
short_channel_id_alias: Some(self.context.outbound_scid_alias),
39944017
})
39954018
} else { None };
@@ -4682,13 +4705,13 @@ impl<SP: Deref> Channel<SP> where
46824705
if need_commitment_update {
46834706
if self.context.channel_state & (ChannelState::MonitorUpdateInProgress as u32) == 0 {
46844707
if self.context.channel_state & (ChannelState::PeerDisconnected as u32) == 0 {
4685-
let next_per_commitment_point =
4686-
self.context.holder_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &self.context.secp_ctx);
4687-
return Some(msgs::ChannelReady {
4688-
channel_id: self.context.channel_id,
4689-
next_per_commitment_point,
4690-
short_channel_id_alias: Some(self.context.outbound_scid_alias),
4691-
});
4708+
if let Ok(next_per_commitment_point) = self.context.holder_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &self.context.secp_ctx) {
4709+
return Some(msgs::ChannelReady {
4710+
channel_id: self.context.channel_id,
4711+
next_per_commitment_point,
4712+
short_channel_id_alias: Some(self.context.outbound_scid_alias),
4713+
});
4714+
}
46924715
}
46934716
} else {
46944717
self.context.monitor_pending_channel_ready = true;
@@ -5638,6 +5661,9 @@ impl<SP: Deref> OutboundV1Channel<SP> where SP::Target: SignerProvider {
56385661

56395662
let temporary_channel_id = entropy_source.get_secure_random_bytes();
56405663

5664+
let next_per_commitment_point = holder_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER, &secp_ctx)
5665+
.map_err(|_| APIError::ChannelUnavailable { err: "Unable to generate initial commitment point".to_owned()})?;
5666+
56415667
Ok(Self {
56425668
context: ChannelContext {
56435669
user_id,
@@ -5666,6 +5692,7 @@ impl<SP: Deref> OutboundV1Channel<SP> where SP::Target: SignerProvider {
56665692
destination_script,
56675693

56685694
cur_holder_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
5695+
next_per_commitment_point,
56695696
cur_counterparty_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
56705697
value_to_self_msat,
56715698

@@ -5907,7 +5934,6 @@ impl<SP: Deref> OutboundV1Channel<SP> where SP::Target: SignerProvider {
59075934
panic!("Tried to send an open_channel for a channel that has already advanced");
59085935
}
59095936

5910-
let first_per_commitment_point = self.context.holder_signer.as_ref().get_per_commitment_point(self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx);
59115937
let keys = self.context.get_holder_pubkeys();
59125938

59135939
msgs::OpenChannel {
@@ -5927,7 +5953,7 @@ impl<SP: Deref> OutboundV1Channel<SP> where SP::Target: SignerProvider {
59275953
payment_point: keys.payment_point,
59285954
delayed_payment_basepoint: keys.delayed_payment_basepoint,
59295955
htlc_basepoint: keys.htlc_basepoint,
5930-
first_per_commitment_point,
5956+
first_per_commitment_point: self.context.next_per_commitment_point,
59315957
channel_flags: if self.context.config.announced_channel {1} else {0},
59325958
shutdown_scriptpubkey: Some(match &self.context.shutdown_scriptpubkey {
59335959
Some(script) => script.clone().into_inner(),
@@ -6276,6 +6302,8 @@ impl<SP: Deref> InboundV1Channel<SP> where SP::Target: SignerProvider {
62766302
} else {
62776303
Some(cmp::max(config.channel_handshake_config.minimum_depth, 1))
62786304
};
6305+
let next_per_commitment_point = holder_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER, &secp_ctx)
6306+
.map_err(|_| ChannelError::Close("Unable to generate initial commitment point".to_owned()))?;
62796307

62806308
let chan = Self {
62816309
context: ChannelContext {
@@ -6304,6 +6332,7 @@ impl<SP: Deref> InboundV1Channel<SP> where SP::Target: SignerProvider {
63046332
destination_script,
63056333

63066334
cur_holder_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
6335+
next_per_commitment_point,
63076336
cur_counterparty_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
63086337
value_to_self_msat: msg.push_msat,
63096338

@@ -6434,7 +6463,6 @@ impl<SP: Deref> InboundV1Channel<SP> where SP::Target: SignerProvider {
64346463
///
64356464
/// [`msgs::AcceptChannel`]: crate::ln::msgs::AcceptChannel
64366465
fn generate_accept_channel_message(&self) -> msgs::AcceptChannel {
6437-
let first_per_commitment_point = self.context.holder_signer.as_ref().get_per_commitment_point(self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx);
64386466
let keys = self.context.get_holder_pubkeys();
64396467

64406468
msgs::AcceptChannel {
@@ -6451,7 +6479,7 @@ impl<SP: Deref> InboundV1Channel<SP> where SP::Target: SignerProvider {
64516479
payment_point: keys.payment_point,
64526480
delayed_payment_basepoint: keys.delayed_payment_basepoint,
64536481
htlc_basepoint: keys.htlc_basepoint,
6454-
first_per_commitment_point,
6482+
first_per_commitment_point: self.context.next_per_commitment_point,
64556483
shutdown_scriptpubkey: Some(match &self.context.shutdown_scriptpubkey {
64566484
Some(script) => script.clone().into_inner(),
64576485
None => Builder::new().into_script(),
@@ -6474,7 +6502,7 @@ impl<SP: Deref> InboundV1Channel<SP> where SP::Target: SignerProvider {
64746502
fn funding_created_signature<L: Deref>(&mut self, sig: &Signature, logger: &L) -> Result<(CommitmentTransaction, CommitmentTransaction, Signature), ChannelError> where L::Target: Logger {
64756503
let funding_script = self.context.get_funding_redeemscript();
64766504

6477-
let keys = self.context.build_holder_transaction_keys(self.context.cur_holder_commitment_transaction_number);
6505+
let keys = self.context.build_holder_transaction_keys();
64786506
let initial_commitment_tx = self.context.build_commitment_transaction(self.context.cur_holder_commitment_transaction_number, &keys, true, false, logger).tx;
64796507
{
64806508
let trusted_tx = initial_commitment_tx.trust();
@@ -6588,6 +6616,13 @@ impl<SP: Deref> InboundV1Channel<SP> where SP::Target: SignerProvider {
65886616
self.context.cur_counterparty_commitment_transaction_number -= 1;
65896617
self.context.cur_holder_commitment_transaction_number -= 1;
65906618

6619+
let next_per_commitment_point_result = self.context.holder_signer.as_ref().get_per_commitment_point(
6620+
self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx);
6621+
if next_per_commitment_point_result.is_err() {
6622+
return Err((self, ChannelError::Close("Unable to generate commitment point".to_owned())));
6623+
}
6624+
self.context.next_per_commitment_point = next_per_commitment_point_result.unwrap();
6625+
65916626
log_info!(logger, "Generated funding_signed for peer for channel {}", log_bytes!(self.context.channel_id()));
65926627

65936628
// Promote the channel to a full-fledged one now that we have updated the state and have a
@@ -7342,6 +7377,11 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
73427377
let mut secp_ctx = Secp256k1::new();
73437378
secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
73447379

7380+
// If we weren't able to load the next_per_commitment_point, ask the signer for it now.
7381+
let next_per_commitment_point = holder_signer.get_per_commitment_point(
7382+
cur_holder_commitment_transaction_number, &secp_ctx
7383+
).map_err(|_| DecodeError::Io(io::ErrorKind::Other))?;
7384+
73457385
// `user_id` used to be a single u64 value. In order to remain backwards
73467386
// compatible with versions prior to 0.0.113, the u128 is serialized as two
73477387
// separate u64 values.
@@ -7394,6 +7434,7 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
73947434
destination_script,
73957435

73967436
cur_holder_commitment_transaction_number,
7437+
next_per_commitment_point,
73977438
cur_counterparty_commitment_transaction_number,
73987439
value_to_self_msat,
73997440

0 commit comments

Comments
 (0)