@@ -666,6 +666,13 @@ pub(super) struct ChannelContext<Signer: ChannelSigner> {
666666 // cost of others, but should really just be changed.
667667
668668 cur_holder_commitment_transaction_number: u64,
669+
670+ // The commitment point corresponding to `cur_holder_commitment_transaction_number`, which is the
671+ // *next* state. We recompute it each time the state changes because the state changes in places
672+ // that might be fallible: in particular, if the commitment point must be fetched from a remote
673+ // source, we want to ensure it happens at a point where we can actually fail somewhat gracefully;
674+ // i.e., force-closing a channel is better than a panic!
675+ next_per_commitment_point: PublicKey,
669676 cur_counterparty_commitment_transaction_number: u64,
670677 value_to_self_msat: u64, // Excluding all pending_htlcs, excluding fees
671678 pending_inbound_htlcs: Vec<InboundHTLCOutput>,
@@ -1441,13 +1448,14 @@ impl<Signer: ChannelSigner> ChannelContext<Signer> {
14411448 /// our counterparty!)
14421449 /// The result is a transaction which we can revoke broadcastership of (ie a "local" transaction)
14431450 /// TODO Some magic rust shit to compile-time check this?
1444- fn build_holder_transaction_keys(&self, commitment_number: u64) -> TxCreationKeys {
1445- let per_commitment_point = self.holder_signer.get_per_commitment_point(commitment_number, &self.secp_ctx);
1451+ fn build_holder_transaction_keys(&self) -> TxCreationKeys {
14461452 let delayed_payment_base = &self.get_holder_pubkeys().delayed_payment_basepoint;
14471453 let htlc_basepoint = &self.get_holder_pubkeys().htlc_basepoint;
14481454 let counterparty_pubkeys = self.get_counterparty_pubkeys();
14491455
1450- TxCreationKeys::derive_new(&self.secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint)
1456+ TxCreationKeys::derive_new(
1457+ &self.secp_ctx, &self.next_per_commitment_point, delayed_payment_base, htlc_basepoint,
1458+ &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint)
14511459 }
14521460
14531461 #[inline]
@@ -2492,7 +2500,12 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
24922500 log_trace!(logger, "Initial counterparty tx for channel {} is: txid {} tx {}",
24932501 log_bytes!(self.context.channel_id()), counterparty_initial_bitcoin_tx.txid, encode::serialize_hex(&counterparty_initial_bitcoin_tx.transaction));
24942502
2495- let holder_signer = self.context.build_holder_transaction_keys(self.context.cur_holder_commitment_transaction_number);
2503+ self.context.next_per_commitment_point =
2504+ self.context.holder_signer.get_per_commitment_point(
2505+ self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx
2506+ ).map_err(|_| ChannelError::Close("Unable to generate commitment point".to_owned()))?;
2507+
2508+ let holder_signer = self.context.build_holder_transaction_keys();
24962509 let initial_commitment_tx = self.context.build_commitment_transaction(self.context.cur_holder_commitment_transaction_number, &holder_signer, true, false, logger).tx;
24972510 {
24982511 let trusted_tx = initial_commitment_tx.trust();
@@ -2536,6 +2549,11 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
25362549 assert_eq!(self.context.channel_state & (ChannelState::MonitorUpdateInProgress as u32), 0); // We have no had any monitor(s) yet to fail update!
25372550 self.context.channel_state = ChannelState::FundingSent as u32;
25382551 self.context.cur_holder_commitment_transaction_number -= 1;
2552+ self.context.next_per_commitment_point =
2553+ self.context.holder_signer.get_per_commitment_point(
2554+ self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx
2555+ ).map_err(|_| ChannelError::Close("Unable to generate commitment point".to_owned()))?;
2556+
25392557 self.context.cur_counterparty_commitment_transaction_number -= 1;
25402558
25412559 log_info!(logger, "Received funding_signed from peer for channel {}", log_bytes!(self.context.channel_id()));
@@ -2857,7 +2875,7 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
28572875
28582876 let funding_script = self.context.get_funding_redeemscript();
28592877
2860- let keys = self.context.build_holder_transaction_keys(self.context.cur_holder_commitment_transaction_number );
2878+ let keys = self.context.build_holder_transaction_keys();
28612879
28622880 let commitment_stats = self.context.build_commitment_transaction(self.context.cur_holder_commitment_transaction_number, &keys, true, false, logger);
28632881 let commitment_txid = {
@@ -3021,6 +3039,11 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
30213039 };
30223040
30233041 self.context.cur_holder_commitment_transaction_number -= 1;
3042+ self.context.next_per_commitment_point =
3043+ self.context.holder_signer.get_per_commitment_point(
3044+ self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx
3045+ ).map_err(|_| ChannelError::Close("Unable to generate commitment point".to_owned()))?;
3046+
30243047 // Note that if we need_commitment & !AwaitingRemoteRevoke we'll call
30253048 // build_commitment_no_status_check() next which will reset this to RAAFirst.
30263049 self.context.resend_order = RAACommitmentOrder::CommitmentFirst;
@@ -3472,7 +3495,7 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
34723495 // Before proposing a feerate update, check that we can actually afford the new fee.
34733496 let inbound_stats = self.context.get_inbound_pending_htlc_stats(Some(feerate_per_kw));
34743497 let outbound_stats = self.context.get_outbound_pending_htlc_stats(Some(feerate_per_kw));
3475- let keys = self.context.build_holder_transaction_keys(self.context.cur_holder_commitment_transaction_number );
3498+ let keys = self.context.build_holder_transaction_keys();
34763499 let commitment_stats = self.context.build_commitment_transaction(self.context.cur_holder_commitment_transaction_number, &keys, true, true, logger);
34773500 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;
34783501 let holder_balance_msat = commitment_stats.local_balance_msat - outbound_stats.holding_cell_msat;
@@ -3653,10 +3676,9 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
36533676 assert!(!self.context.is_outbound() || self.context.minimum_depth == Some(0),
36543677 "Funding transaction broadcast by the local client before it should have - LDK didn't do it!");
36553678 self.context.monitor_pending_channel_ready = false;
3656- let next_per_commitment_point = self.context.holder_signer.get_per_commitment_point(self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx);
36573679 Some(msgs::ChannelReady {
36583680 channel_id: self.context.channel_id(),
3659- next_per_commitment_point,
3681+ next_per_commitment_point: self.context.next_per_commitment_point ,
36603682 short_channel_id_alias: Some(self.context.outbound_scid_alias),
36613683 })
36623684 } else { None };
@@ -3735,12 +3757,11 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
37353757 }
37363758
37373759 fn get_last_revoke_and_ack(&self) -> msgs::RevokeAndACK {
3738- let next_per_commitment_point = self.context.holder_signer.get_per_commitment_point(self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx);
37393760 let per_commitment_secret = self.context.holder_signer.release_commitment_secret(self.context.cur_holder_commitment_transaction_number + 2);
37403761 msgs::RevokeAndACK {
37413762 channel_id: self.context.channel_id,
37423763 per_commitment_secret,
3743- next_per_commitment_point,
3764+ next_per_commitment_point: self.context.next_per_commitment_point ,
37443765 #[cfg(taproot)]
37453766 next_local_nonce: None,
37463767 }
@@ -3839,7 +3860,9 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
38393860 }
38403861
38413862 if msg.next_remote_commitment_number > 0 {
3842- let expected_point = self.context.holder_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - msg.next_remote_commitment_number + 1, &self.context.secp_ctx);
3863+ let state_index = INITIAL_COMMITMENT_NUMBER - msg.next_remote_commitment_number + 1;
3864+ let expected_point = self.context.holder_signer.get_per_commitment_point(state_index, &self.context.secp_ctx)
3865+ .map_err(|_| ChannelError::Close(format!("Unable to retrieve per-commitment point for state {state_index}")))?;
38433866 let given_secret = SecretKey::from_slice(&msg.your_last_per_commitment_secret)
38443867 .map_err(|_| ChannelError::Close("Peer sent a garbage channel_reestablish with unparseable secret key".to_owned()))?;
38453868 if expected_point != PublicKey::from_secret_key(&self.context.secp_ctx, &given_secret) {
@@ -3904,11 +3927,10 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
39043927 }
39053928
39063929 // We have OurChannelReady set!
3907- let next_per_commitment_point = self.context.holder_signer.get_per_commitment_point(self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx);
39083930 return Ok(ReestablishResponses {
39093931 channel_ready: Some(msgs::ChannelReady {
39103932 channel_id: self.context.channel_id(),
3911- next_per_commitment_point,
3933+ next_per_commitment_point: self.context.next_per_commitment_point ,
39123934 short_channel_id_alias: Some(self.context.outbound_scid_alias),
39133935 }),
39143936 raa: None, commitment_update: None,
@@ -3944,10 +3966,9 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
39443966
39453967 let channel_ready = if msg.next_local_commitment_number == 1 && INITIAL_COMMITMENT_NUMBER - self.context.cur_holder_commitment_transaction_number == 1 {
39463968 // We should never have to worry about MonitorUpdateInProgress resending ChannelReady
3947- let next_per_commitment_point = self.context.holder_signer.get_per_commitment_point(self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx);
39483969 Some(msgs::ChannelReady {
39493970 channel_id: self.context.channel_id(),
3950- next_per_commitment_point,
3971+ next_per_commitment_point: self.context.next_per_commitment_point ,
39513972 short_channel_id_alias: Some(self.context.outbound_scid_alias),
39523973 })
39533974 } else { None };
@@ -4633,13 +4654,13 @@ impl<Signer: WriteableEcdsaChannelSigner> Channel<Signer> {
46334654 if need_commitment_update {
46344655 if self.context.channel_state & (ChannelState::MonitorUpdateInProgress as u32) == 0 {
46354656 if self.context.channel_state & (ChannelState::PeerDisconnected as u32) == 0 {
4636- let next_per_commitment_point =
4637- self.context.holder_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &self.context.secp_ctx);
4638- return Some(msgs::ChannelReady {
4639- channel_id: self.context.channel_id ,
4640- next_per_commitment_point ,
4641- short_channel_id_alias: Some(self.context.outbound_scid_alias),
4642- });
4657+ if let Ok( next_per_commitment_point) = self.context.holder_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &self.context.secp_ctx) {
4658+ return Some(msgs::ChannelReady {
4659+ channel_id: self.context.channel_id,
4660+ next_per_commitment_point ,
4661+ short_channel_id_alias: Some(self.context.outbound_scid_alias) ,
4662+ });
4663+ }
46434664 }
46444665 } else {
46454666 self.context.monitor_pending_channel_ready = true;
@@ -5568,6 +5589,9 @@ impl<Signer: WriteableEcdsaChannelSigner> OutboundV1Channel<Signer> {
55685589
55695590 let temporary_channel_id = entropy_source.get_secure_random_bytes();
55705591
5592+ let next_per_commitment_point = holder_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER, &secp_ctx)
5593+ .map_err(|_| APIError::ChannelUnavailable { err: "Unable to generate initial commitment point".to_owned()})?;
5594+
55715595 Ok(Self {
55725596 context: ChannelContext {
55735597 user_id,
@@ -5596,6 +5620,7 @@ impl<Signer: WriteableEcdsaChannelSigner> OutboundV1Channel<Signer> {
55965620 destination_script,
55975621
55985622 cur_holder_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
5623+ next_per_commitment_point,
55995624 cur_counterparty_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
56005625 value_to_self_msat,
56015626
@@ -5832,7 +5857,6 @@ impl<Signer: WriteableEcdsaChannelSigner> OutboundV1Channel<Signer> {
58325857 panic!("Tried to send an open_channel for a channel that has already advanced");
58335858 }
58345859
5835- let first_per_commitment_point = self.context.holder_signer.get_per_commitment_point(self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx);
58365860 let keys = self.context.get_holder_pubkeys();
58375861
58385862 msgs::OpenChannel {
@@ -5852,7 +5876,7 @@ impl<Signer: WriteableEcdsaChannelSigner> OutboundV1Channel<Signer> {
58525876 payment_point: keys.payment_point,
58535877 delayed_payment_basepoint: keys.delayed_payment_basepoint,
58545878 htlc_basepoint: keys.htlc_basepoint,
5855- first_per_commitment_point,
5879+ first_per_commitment_point: self.context.next_per_commitment_point ,
58565880 channel_flags: if self.context.config.announced_channel {1} else {0},
58575881 shutdown_scriptpubkey: Some(match &self.context.shutdown_scriptpubkey {
58585882 Some(script) => script.clone().into_inner(),
@@ -6202,6 +6226,8 @@ impl<Signer: WriteableEcdsaChannelSigner> InboundV1Channel<Signer> {
62026226 } else {
62036227 Some(cmp::max(config.channel_handshake_config.minimum_depth, 1))
62046228 };
6229+ let next_per_commitment_point = holder_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER, &secp_ctx)
6230+ .map_err(|_| ChannelError::Close("Unable to generate initial commitment point".to_owned()))?;
62056231
62066232 let chan = Self {
62076233 context: ChannelContext {
@@ -6230,6 +6256,7 @@ impl<Signer: WriteableEcdsaChannelSigner> InboundV1Channel<Signer> {
62306256 destination_script,
62316257
62326258 cur_holder_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
6259+ next_per_commitment_point,
62336260 cur_counterparty_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
62346261 value_to_self_msat: msg.push_msat,
62356262
@@ -6360,7 +6387,6 @@ impl<Signer: WriteableEcdsaChannelSigner> InboundV1Channel<Signer> {
63606387 ///
63616388 /// [`msgs::AcceptChannel`]: crate::ln::msgs::AcceptChannel
63626389 fn generate_accept_channel_message(&self) -> msgs::AcceptChannel {
6363- let first_per_commitment_point = self.context.holder_signer.get_per_commitment_point(self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx);
63646390 let keys = self.context.get_holder_pubkeys();
63656391
63666392 msgs::AcceptChannel {
@@ -6377,7 +6403,7 @@ impl<Signer: WriteableEcdsaChannelSigner> InboundV1Channel<Signer> {
63776403 payment_point: keys.payment_point,
63786404 delayed_payment_basepoint: keys.delayed_payment_basepoint,
63796405 htlc_basepoint: keys.htlc_basepoint,
6380- first_per_commitment_point,
6406+ first_per_commitment_point: self.context.next_per_commitment_point ,
63816407 shutdown_scriptpubkey: Some(match &self.context.shutdown_scriptpubkey {
63826408 Some(script) => script.clone().into_inner(),
63836409 None => Builder::new().into_script(),
@@ -6400,7 +6426,7 @@ impl<Signer: WriteableEcdsaChannelSigner> InboundV1Channel<Signer> {
64006426 fn funding_created_signature<L: Deref>(&mut self, sig: &Signature, logger: &L) -> Result<(Txid, CommitmentTransaction, Signature), ChannelError> where L::Target: Logger {
64016427 let funding_script = self.context.get_funding_redeemscript();
64026428
6403- let keys = self.context.build_holder_transaction_keys(self.context.cur_holder_commitment_transaction_number );
6429+ let keys = self.context.build_holder_transaction_keys();
64046430 let initial_commitment_tx = self.context.build_commitment_transaction(self.context.cur_holder_commitment_transaction_number, &keys, true, false, logger).tx;
64056431 {
64066432 let trusted_tx = initial_commitment_tx.trust();
@@ -6505,6 +6531,13 @@ impl<Signer: WriteableEcdsaChannelSigner> InboundV1Channel<Signer> {
65056531 self.context.cur_counterparty_commitment_transaction_number -= 1;
65066532 self.context.cur_holder_commitment_transaction_number -= 1;
65076533
6534+ let next_per_commitment_point_result = self.context.holder_signer.get_per_commitment_point(
6535+ self.context.cur_holder_commitment_transaction_number, &self.context.secp_ctx);
6536+ if next_per_commitment_point_result.is_err() {
6537+ return Err((self, ChannelError::Close("Unable to generate commitment point".to_owned())));
6538+ }
6539+ self.context.next_per_commitment_point = next_per_commitment_point_result.unwrap();
6540+
65086541 log_info!(logger, "Generated funding_signed for peer for channel {}", log_bytes!(self.context.channel_id()));
65096542
65106543 // Promote the channel to a full-fledged one now that we have updated the state and have a
@@ -7258,6 +7291,11 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
72587291 let mut secp_ctx = Secp256k1::new();
72597292 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
72607293
7294+ // If we weren't able to load the next_per_commitment_point, ask the signer for it now.
7295+ let next_per_commitment_point = holder_signer.get_per_commitment_point(
7296+ cur_holder_commitment_transaction_number, &secp_ctx
7297+ ).map_err(|_| DecodeError::Io(io::ErrorKind::Other))?;
7298+
72617299 // `user_id` used to be a single u64 value. In order to remain backwards
72627300 // compatible with versions prior to 0.0.113, the u128 is serialized as two
72637301 // separate u64 values.
@@ -7310,6 +7348,7 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
73107348 destination_script,
73117349
73127350 cur_holder_commitment_transaction_number,
7351+ next_per_commitment_point,
73137352 cur_counterparty_commitment_transaction_number,
73147353 value_to_self_msat,
73157354
0 commit comments