@@ -668,6 +668,13 @@ pub(super) struct ChannelContext<Signer: ChannelSigner> {
668668 // cost of others, but should really just be changed.
669669
670670 cur_holder_commitment_transaction_number: u64,
671+
672+ // The commitment point corresponding to `cur_holder_commitment_transaction_number`, which is the
673+ // *next* state. We recompute it each time the state changes because the state changes in places
674+ // that might be fallible: in particular, if the commitment point must be fetched from a remote
675+ // source, we want to ensure it happens at a point where we can actually fail somewhat gracefully;
676+ // i.e., force-closing a channel is better than a panic!
677+ next_per_commitment_point: PublicKey,
671678 cur_counterparty_commitment_transaction_number: u64,
672679 value_to_self_msat: u64, // Excluding all pending_htlcs, excluding fees
673680 pending_inbound_htlcs: Vec<InboundHTLCOutput>,
@@ -1455,13 +1462,14 @@ impl<Signer: ChannelSigner> ChannelContext<Signer> {
14551462 /// our counterparty!)
14561463 /// The result is a transaction which we can revoke broadcastership of (ie a "local" transaction)
14571464 /// TODO Some magic rust shit to compile-time check this?
1458- fn build_holder_transaction_keys(&self, commitment_number: u64) -> TxCreationKeys {
1459- let per_commitment_point = self.holder_signer.get_per_commitment_point(commitment_number, &self.secp_ctx);
1465+ fn build_holder_transaction_keys(&self) -> TxCreationKeys {
14601466 let delayed_payment_base = &self.get_holder_pubkeys().delayed_payment_basepoint;
14611467 let htlc_basepoint = &self.get_holder_pubkeys().htlc_basepoint;
14621468 let counterparty_pubkeys = self.get_counterparty_pubkeys();
14631469
1464- TxCreationKeys::derive_new(&self.secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint)
1470+ TxCreationKeys::derive_new(
1471+ &self.secp_ctx, &self.next_per_commitment_point, delayed_payment_base, htlc_basepoint,
1472+ &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint)
14651473 }
14661474
14671475 #[inline]
@@ -2515,7 +2523,12 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
25152523 log_trace!(logger, "Initial counterparty tx for channel {} is: txid {} tx {}",
25162524 log_bytes!(self.context.channel_id()), counterparty_initial_bitcoin_tx.txid, encode::serialize_hex(&counterparty_initial_bitcoin_tx.transaction));
25172525
2518- let holder_signer = self.context.build_holder_transaction_keys(self.context.cur_holder_commitment_transaction_number);
2526+ self.context.next_per_commitment_point =
2527+ self.context.holder_signer.get_per_commitment_point(
2528+ self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx
2529+ ).map_err(|_| ChannelError::Close("Unable to generate commitment point".to_owned()))?;
2530+
2531+ let holder_signer = self.context.build_holder_transaction_keys();
25192532 let initial_commitment_tx = self.context.build_commitment_transaction(self.context.cur_holder_commitment_transaction_number, &holder_signer, true, false, logger).tx;
25202533 {
25212534 let trusted_tx = initial_commitment_tx.trust();
@@ -2559,6 +2572,11 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
25592572 assert_eq!(self.context.channel_state & (ChannelState::MonitorUpdateInProgress as u32), 0); // We have no had any monitor(s) yet to fail update!
25602573 self.context.channel_state = ChannelState::FundingSent as u32;
25612574 self.context.cur_holder_commitment_transaction_number -= 1;
2575+ self.context.next_per_commitment_point =
2576+ self.context.holder_signer.get_per_commitment_point(
2577+ self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx
2578+ ).map_err(|_| ChannelError::Close("Unable to generate commitment point".to_owned()))?;
2579+
25622580 self.context.cur_counterparty_commitment_transaction_number -= 1;
25632581
25642582 log_info!(logger, "Received funding_signed from peer for channel {}", log_bytes!(self.context.channel_id()));
@@ -2880,7 +2898,7 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
28802898
28812899 let funding_script = self.context.get_funding_redeemscript();
28822900
2883- let keys = self.context.build_holder_transaction_keys(self.context.cur_holder_commitment_transaction_number );
2901+ let keys = self.context.build_holder_transaction_keys();
28842902
28852903 let commitment_stats = self.context.build_commitment_transaction(self.context.cur_holder_commitment_transaction_number, &keys, true, false, logger);
28862904 let commitment_txid = {
@@ -3044,6 +3062,11 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
30443062 };
30453063
30463064 self.context.cur_holder_commitment_transaction_number -= 1;
3065+ self.context.next_per_commitment_point =
3066+ self.context.holder_signer.get_per_commitment_point(
3067+ self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx
3068+ ).map_err(|_| ChannelError::Close("Unable to generate commitment point".to_owned()))?;
3069+
30473070 // Note that if we need_commitment & !AwaitingRemoteRevoke we'll call
30483071 // build_commitment_no_status_check() next which will reset this to RAAFirst.
30493072 self.context.resend_order = RAACommitmentOrder::CommitmentFirst;
@@ -3495,7 +3518,7 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
34953518 // Before proposing a feerate update, check that we can actually afford the new fee.
34963519 let inbound_stats = self.context.get_inbound_pending_htlc_stats(Some(feerate_per_kw));
34973520 let outbound_stats = self.context.get_outbound_pending_htlc_stats(Some(feerate_per_kw));
3498- let keys = self.context.build_holder_transaction_keys(self.context.cur_holder_commitment_transaction_number );
3521+ let keys = self.context.build_holder_transaction_keys();
34993522 let commitment_stats = self.context.build_commitment_transaction(self.context.cur_holder_commitment_transaction_number, &keys, true, true, logger);
35003523 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;
35013524 let holder_balance_msat = commitment_stats.local_balance_msat - outbound_stats.holding_cell_msat;
@@ -3676,10 +3699,9 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
36763699 assert!(!self.context.is_outbound() || self.context.minimum_depth == Some(0),
36773700 "Funding transaction broadcast by the local client before it should have - LDK didn't do it!");
36783701 self.context.monitor_pending_channel_ready = false;
3679- let next_per_commitment_point = self.context.holder_signer.get_per_commitment_point(self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx);
36803702 Some(msgs::ChannelReady {
36813703 channel_id: self.context.channel_id(),
3682- next_per_commitment_point,
3704+ next_per_commitment_point: self.context.next_per_commitment_point ,
36833705 short_channel_id_alias: Some(self.context.outbound_scid_alias),
36843706 })
36853707 } else { None };
@@ -3758,12 +3780,11 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
37583780 }
37593781
37603782 fn get_last_revoke_and_ack(&self) -> msgs::RevokeAndACK {
3761- let next_per_commitment_point = self.context.holder_signer.get_per_commitment_point(self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx);
37623783 let per_commitment_secret = self.context.holder_signer.release_commitment_secret(self.context.cur_holder_commitment_transaction_number + 2);
37633784 msgs::RevokeAndACK {
37643785 channel_id: self.context.channel_id,
37653786 per_commitment_secret,
3766- next_per_commitment_point,
3787+ next_per_commitment_point: self.context.next_per_commitment_point ,
37673788 #[cfg(taproot)]
37683789 next_local_nonce: None,
37693790 }
@@ -3862,7 +3883,9 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
38623883 }
38633884
38643885 if msg.next_remote_commitment_number > 0 {
3865- let expected_point = self.context.holder_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - msg.next_remote_commitment_number + 1, &self.context.secp_ctx);
3886+ let state_index = INITIAL_COMMITMENT_NUMBER - msg.next_remote_commitment_number + 1;
3887+ let expected_point = self.context.holder_signer.get_per_commitment_point(state_index, &self.context.secp_ctx)
3888+ .map_err(|_| ChannelError::Close(format!("Unable to retrieve per-commitment point for state {state_index}")))?;
38663889 let given_secret = SecretKey::from_slice(&msg.your_last_per_commitment_secret)
38673890 .map_err(|_| ChannelError::Close("Peer sent a garbage channel_reestablish with unparseable secret key".to_owned()))?;
38683891 if expected_point != PublicKey::from_secret_key(&self.context.secp_ctx, &given_secret) {
@@ -3927,11 +3950,10 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
39273950 }
39283951
39293952 // We have OurChannelReady set!
3930- let next_per_commitment_point = self.context.holder_signer.get_per_commitment_point(self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx);
39313953 return Ok(ReestablishResponses {
39323954 channel_ready: Some(msgs::ChannelReady {
39333955 channel_id: self.context.channel_id(),
3934- next_per_commitment_point,
3956+ next_per_commitment_point: self.context.next_per_commitment_point ,
39353957 short_channel_id_alias: Some(self.context.outbound_scid_alias),
39363958 }),
39373959 raa: None, commitment_update: None,
@@ -3967,10 +3989,9 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
39673989
39683990 let channel_ready = if msg.next_local_commitment_number == 1 && INITIAL_COMMITMENT_NUMBER - self.context.cur_holder_commitment_transaction_number == 1 {
39693991 // We should never have to worry about MonitorUpdateInProgress resending ChannelReady
3970- let next_per_commitment_point = self.context.holder_signer.get_per_commitment_point(self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx);
39713992 Some(msgs::ChannelReady {
39723993 channel_id: self.context.channel_id(),
3973- next_per_commitment_point,
3994+ next_per_commitment_point: self.context.next_per_commitment_point ,
39743995 short_channel_id_alias: Some(self.context.outbound_scid_alias),
39753996 })
39763997 } else { None };
@@ -4656,13 +4677,13 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
46564677 if need_commitment_update {
46574678 if self.context.channel_state & (ChannelState::MonitorUpdateInProgress as u32) == 0 {
46584679 if self.context.channel_state & (ChannelState::PeerDisconnected as u32) == 0 {
4659- let next_per_commitment_point =
4660- self.context.holder_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &self.context.secp_ctx);
4661- return Some(msgs::ChannelReady {
4662- channel_id: self.context.channel_id ,
4663- next_per_commitment_point ,
4664- short_channel_id_alias: Some(self.context.outbound_scid_alias),
4665- });
4680+ if let Ok( next_per_commitment_point) = self.context.holder_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &self.context.secp_ctx) {
4681+ return Some(msgs::ChannelReady {
4682+ channel_id: self.context.channel_id,
4683+ next_per_commitment_point ,
4684+ short_channel_id_alias: Some(self.context.outbound_scid_alias) ,
4685+ });
4686+ }
46664687 }
46674688 } else {
46684689 self.context.monitor_pending_channel_ready = true;
@@ -5591,6 +5612,9 @@ impl<Signer: WriteableEcdsaChannelSigner> OutboundV1Channel<Signer> {
55915612
55925613 let temporary_channel_id = entropy_source.get_secure_random_bytes();
55935614
5615+ let next_per_commitment_point = holder_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER, &secp_ctx)
5616+ .map_err(|_| APIError::ChannelUnavailable { err: "Unable to generate initial commitment point".to_owned()})?;
5617+
55945618 Ok(Self {
55955619 context: ChannelContext {
55965620 user_id,
@@ -5619,6 +5643,7 @@ impl<Signer: WriteableEcdsaChannelSigner> OutboundV1Channel<Signer> {
56195643 destination_script,
56205644
56215645 cur_holder_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
5646+ next_per_commitment_point,
56225647 cur_counterparty_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
56235648 value_to_self_msat,
56245649
@@ -5857,7 +5882,6 @@ impl<Signer: WriteableEcdsaChannelSigner> OutboundV1Channel<Signer> {
58575882 panic!("Tried to send an open_channel for a channel that has already advanced");
58585883 }
58595884
5860- let first_per_commitment_point = self.context.holder_signer.get_per_commitment_point(self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx);
58615885 let keys = self.context.get_holder_pubkeys();
58625886
58635887 msgs::OpenChannel {
@@ -5877,7 +5901,7 @@ impl<Signer: WriteableEcdsaChannelSigner> OutboundV1Channel<Signer> {
58775901 payment_point: keys.payment_point,
58785902 delayed_payment_basepoint: keys.delayed_payment_basepoint,
58795903 htlc_basepoint: keys.htlc_basepoint,
5880- first_per_commitment_point,
5904+ first_per_commitment_point: self.context.next_per_commitment_point ,
58815905 channel_flags: if self.context.config.announced_channel {1} else {0},
58825906 shutdown_scriptpubkey: Some(match &self.context.shutdown_scriptpubkey {
58835907 Some(script) => script.clone().into_inner(),
@@ -6222,6 +6246,9 @@ impl<Signer: WriteableEcdsaChannelSigner> InboundV1Channel<Signer> {
62226246 let mut secp_ctx = Secp256k1::new();
62236247 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
62246248
6249+ let next_per_commitment_point = holder_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER, &secp_ctx)
6250+ .map_err(|_| ChannelError::Close("Unable to generate initial commitment point".to_owned()))?;
6251+
62256252 let chan = Self {
62266253 context: ChannelContext {
62276254 user_id,
@@ -6249,6 +6276,7 @@ impl<Signer: WriteableEcdsaChannelSigner> InboundV1Channel<Signer> {
62496276 destination_script,
62506277
62516278 cur_holder_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
6279+ next_per_commitment_point,
62526280 cur_counterparty_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
62536281 value_to_self_msat: msg.push_msat,
62546282
@@ -6397,7 +6425,6 @@ impl<Signer: WriteableEcdsaChannelSigner> InboundV1Channel<Signer> {
63976425 ///
63986426 /// [`msgs::AcceptChannel`]: crate::ln::msgs::AcceptChannel
63996427 fn generate_accept_channel_message(&self) -> msgs::AcceptChannel {
6400- let first_per_commitment_point = self.context.holder_signer.get_per_commitment_point(self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx);
64016428 let keys = self.context.get_holder_pubkeys();
64026429
64036430 msgs::AcceptChannel {
@@ -6414,7 +6441,7 @@ impl<Signer: WriteableEcdsaChannelSigner> InboundV1Channel<Signer> {
64146441 payment_point: keys.payment_point,
64156442 delayed_payment_basepoint: keys.delayed_payment_basepoint,
64166443 htlc_basepoint: keys.htlc_basepoint,
6417- first_per_commitment_point,
6444+ first_per_commitment_point: self.context.next_per_commitment_point ,
64186445 shutdown_scriptpubkey: Some(match &self.context.shutdown_scriptpubkey {
64196446 Some(script) => script.clone().into_inner(),
64206447 None => Builder::new().into_script(),
@@ -6437,7 +6464,7 @@ impl<Signer: WriteableEcdsaChannelSigner> InboundV1Channel<Signer> {
64376464 fn funding_created_signature<L: Deref>(&mut self, sig: &Signature, logger: &L) -> Result<(Txid, CommitmentTransaction, Signature), ChannelError> where L::Target: Logger {
64386465 let funding_script = self.context.get_funding_redeemscript();
64396466
6440- let keys = self.context.build_holder_transaction_keys(self.context.cur_holder_commitment_transaction_number );
6467+ let keys = self.context.build_holder_transaction_keys();
64416468 let initial_commitment_tx = self.context.build_commitment_transaction(self.context.cur_holder_commitment_transaction_number, &keys, true, false, logger).tx;
64426469 {
64436470 let trusted_tx = initial_commitment_tx.trust();
@@ -6545,6 +6572,13 @@ impl<Signer: WriteableEcdsaChannelSigner> InboundV1Channel<Signer> {
65456572 self.context.cur_counterparty_commitment_transaction_number -= 1;
65466573 self.context.cur_holder_commitment_transaction_number -= 1;
65476574
6575+ let next_per_commitment_point_result = self.context.holder_signer.get_per_commitment_point(
6576+ self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx);
6577+ if next_per_commitment_point_result.is_err() {
6578+ return Err((self, ChannelError::Close("Unable to generate commitment point".to_owned())));
6579+ }
6580+ self.context.next_per_commitment_point = next_per_commitment_point_result.unwrap();
6581+
65486582 log_info!(logger, "Generated funding_signed for peer for channel {}", log_bytes!(self.context.channel_id()));
65496583
65506584 // Promote the channel to a full-fledged one now that we have updated the state and have a
@@ -7298,6 +7332,11 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
72987332 let mut secp_ctx = Secp256k1::new();
72997333 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
73007334
7335+ // If we weren't able to load the next_per_commitment_point, ask the signer for it now.
7336+ let next_per_commitment_point = holder_signer.get_per_commitment_point(
7337+ cur_holder_commitment_transaction_number, &secp_ctx
7338+ ).map_err(|_| DecodeError::Io(io::ErrorKind::Other))?;
7339+
73017340 // `user_id` used to be a single u64 value. In order to remain backwards
73027341 // compatible with versions prior to 0.0.113, the u128 is serialized as two
73037342 // separate u64 values.
@@ -7350,6 +7389,7 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
73507389 destination_script,
73517390
73527391 cur_holder_commitment_transaction_number,
7392+ next_per_commitment_point,
73537393 cur_counterparty_commitment_transaction_number,
73547394 value_to_self_msat,
73557395
0 commit comments