Skip to content

Commit b4d14ae

Browse files
Make channel req response only require channel_id
Make the only information the respond_to_open_channel_request function require about the channel be the the temporary channel ID. This removes the need to pass excessive amounts of data with the OpenChannelRequest event.
1 parent 3606429 commit b4d14ae

File tree

3 files changed

+111
-74
lines changed

3 files changed

+111
-74
lines changed

lightning/src/ln/channel.rs

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -536,6 +536,17 @@ pub(super) struct Channel<Signer: Sign> {
536536
#[cfg(not(test))]
537537
closing_fee_limits: Option<(u64, u64)>,
538538

539+
/// Flag that ensures that the `get_accept_channel` function must be called before the
540+
/// `funding_created` function is executed successfully. The reason for need of this flag is
541+
/// that when the util::config::UserConfig.manually_accept_inbound_channels is set to true,
542+
/// inbound channels are required to be manually accepted by the node operator before the
543+
/// `SendAcceptChannel` message is created and sent out. The `get_accept_channel` function is
544+
/// called during that process.
545+
/// A counterparty node could theoretically send a `FundingCreated` message before the node
546+
/// operator has accepted the inbound channel. That would would execute the `funding_created`
547+
/// function before the `get_accept_channel` function, and should therefore be rejected.
548+
inbound_awaiting_accept: bool,
549+
539550
/// The hash of the block in which the funding transaction was included.
540551
funding_tx_confirmed_in: Option<BlockHash>,
541552
funding_tx_confirmation_height: u32,
@@ -833,6 +844,8 @@ impl<Signer: Sign> Channel<Signer> {
833844
closing_fee_limits: None,
834845
target_closing_feerate_sats_per_kw: None,
835846

847+
inbound_awaiting_accept: false,
848+
836849
funding_tx_confirmed_in: None,
837850
funding_tx_confirmation_height: 0,
838851
short_channel_id: None,
@@ -1130,6 +1143,8 @@ impl<Signer: Sign> Channel<Signer> {
11301143
closing_fee_limits: None,
11311144
target_closing_feerate_sats_per_kw: None,
11321145

1146+
inbound_awaiting_accept: true,
1147+
11331148
funding_tx_confirmed_in: None,
11341149
funding_tx_confirmation_height: 0,
11351150
short_channel_id: None,
@@ -1918,6 +1933,10 @@ impl<Signer: Sign> Channel<Signer> {
19181933
// channel.
19191934
return Err(ChannelError::Close("Received funding_created after we got the channel!".to_owned()));
19201935
}
1936+
if self.inbound_awaiting_accept {
1937+
// The Channel must manually accepted before the FundingCreated is received.
1938+
return Err(ChannelError::Close("FundingCreated message received before the channel was accepted".to_owned()));
1939+
}
19211940
if self.commitment_secrets.get_min_seen_secret() != (1 << 48) ||
19221941
self.cur_counterparty_commitment_transaction_number != INITIAL_COMMITMENT_NUMBER ||
19231942
self.cur_holder_commitment_transaction_number != INITIAL_COMMITMENT_NUMBER {
@@ -4504,7 +4523,11 @@ impl<Signer: Sign> Channel<Signer> {
45044523
}
45054524
}
45064525

4507-
pub fn get_accept_channel(&self) -> msgs::AcceptChannel {
4526+
pub fn inbound_is_awaiting_accept(&self) -> bool {
4527+
self.inbound_awaiting_accept
4528+
}
4529+
4530+
pub fn get_accept_channel(&mut self) -> msgs::AcceptChannel {
45084531
if self.is_outbound() {
45094532
panic!("Tried to send accept_channel for an outbound channel?");
45104533
}
@@ -4515,6 +4538,8 @@ impl<Signer: Sign> Channel<Signer> {
45154538
panic!("Tried to send an accept_channel for a channel that has already advanced");
45164539
}
45174540

4541+
self.inbound_awaiting_accept = false;
4542+
45184543
let first_per_commitment_point = self.holder_signer.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
45194544
let keys = self.get_holder_pubkeys();
45204545

@@ -5840,6 +5865,8 @@ impl<'a, Signer: Sign, K: Deref> ReadableArgs<(&'a K, u32)> for Channel<Signer>
58405865
closing_fee_limits: None,
58415866
target_closing_feerate_sats_per_kw,
58425867

5868+
inbound_awaiting_accept: false,
5869+
58435870
funding_tx_confirmed_in,
58445871
funding_tx_confirmation_height,
58455872
short_channel_id,
@@ -6050,7 +6077,7 @@ mod tests {
60506077
// Make sure A's dust limit is as we expect.
60516078
let open_channel_msg = node_a_chan.get_open_channel(genesis_block(network).header.block_hash());
60526079
let node_b_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[7; 32]).unwrap());
6053-
let node_b_chan = Channel::<EnforcingSigner>::new_from_req(&&feeest, &&keys_provider, node_b_node_id, &InitFeatures::known(), &open_channel_msg, 7, &config, 0, &&logger).unwrap();
6080+
let mut node_b_chan = Channel::<EnforcingSigner>::new_from_req(&&feeest, &&keys_provider, node_b_node_id, &InitFeatures::known(), &open_channel_msg, 7, &config, 0, &&logger).unwrap();
60546081

60556082
// Node B --> Node A: accept channel, explicitly setting B's dust limit.
60566083
let mut accept_channel_msg = node_b_chan.get_accept_channel();

lightning/src/ln/channelmanager.rs

Lines changed: 65 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -688,30 +688,6 @@ pub(super) struct ChannelHolder<Signer: Sign> {
688688
pub(super) pending_msg_events: Vec<MessageSendEvent>,
689689
}
690690

691-
/// Holds the information required for a user to respond to an open channel request, when the
692-
/// manually_accept_inbound_channels config flag is set to true.
693-
#[derive(Clone, Debug)]
694-
pub struct OpenChannelRequestInfo {
695-
/// The public key of the peer node which is requesting to open a channel.
696-
pub counterparty_node_id: PublicKey,
697-
/// The init features sent in the init message.
698-
pub their_features: InitFeatures,
699-
/// The Open channel message sent by the peer when requesting to open the channel.
700-
pub msg: msgs::OpenChannel
701-
}
702-
703-
impl Writeable for OpenChannelRequestInfo {
704-
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
705-
11u8.write(writer)?;
706-
write_tlv_fields!(writer, {
707-
(0, self.counterparty_node_id, required),
708-
(2, self.their_features, required),
709-
(4, self.msg, required),
710-
});
711-
Ok(())
712-
}
713-
}
714-
715691
/// Events which we process internally but cannot be procsesed immediately at the generation site
716692
/// for some reason. They are handled in timer_tick_occurred, so may be processed with
717693
/// quite some time lag.
@@ -4128,24 +4104,27 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
41284104
/// Called to respond to a request to open a channel after the
41294105
/// [`events::Event::OpenChannelRequest`] has been triggered.
41304106
///
4131-
/// If 'accept_channel' is set to true, the requested channel will be opened. If
4132-
/// 'accept_channel' is false, the open channel request will be rejected.
4107+
/// If `accept_channel` is set to true, the requested channel will be opened. If
4108+
/// `accept_channel` is false, the open channel request will be rejected.
41334109
///
4134-
/// The 'open_channel_request_info' parameter in the [`events::Event::OpenChannelRequest`]
4135-
/// event, should be directly passed as input to this function.
4110+
/// The `temporary_channel_id` parameter indicates which channel the reponse is for.
41364111
///
41374112
/// [`events::Event::OpenChannelRequest`]: crate::util::events::Event::OpenChannelRequest
4138-
pub fn respond_to_open_channel_request(&self, accept_channel: bool, open_channel_request_info: OpenChannelRequestInfo) {
4113+
pub fn respond_to_open_channel_request(&self, accept_channel: bool, temporary_channel_id: [u8; 32]) -> Result<(), APIError> {
41394114
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
4140-
match accept_channel {
4141-
true => {
4142-
let _ = handle_error!(self, self.internal_create_requested_channel(&open_channel_request_info.counterparty_node_id, open_channel_request_info.their_features, &open_channel_request_info.msg), open_channel_request_info.counterparty_node_id);
4143-
}
4144-
false => {
4145-
let err_res: Result<(), MsgHandleErrInternal> = Err(MsgHandleErrInternal::send_err_msg_no_close("The peer rejected the request to open the channel".to_owned(), open_channel_request_info.msg.temporary_channel_id.clone()));
4146-
let _ = handle_error!(self, err_res, open_channel_request_info.counterparty_node_id);
4115+
4116+
if let Some(counterparty_node_id) = self.internal_get_counterparty_node_id(temporary_channel_id) {
4117+
match accept_channel {
4118+
true => {
4119+
return self.accept_requested_channel(temporary_channel_id);
4120+
}
4121+
false => {
4122+
let err_res: Result<(), MsgHandleErrInternal> = Err(MsgHandleErrInternal::send_err_msg_no_close("The peer rejected the request to open the channel".to_owned(), temporary_channel_id));
4123+
let _ = handle_error!(self, err_res, counterparty_node_id);
4124+
return Ok(());
4125+
}
41474126
}
4148-
}
4127+
} else { return Err(APIError::ChannelUnavailable { err: "No channel with the inputted temporary_channel_id found".to_owned() }); }
41494128
}
41504129

41514130
fn internal_open_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
@@ -4157,42 +4136,69 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
41574136
return Err(MsgHandleErrInternal::send_err_msg_no_close("No inbound channels accepted".to_owned(), msg.temporary_channel_id.clone()));
41584137
}
41594138

4160-
if self.default_configuration.manually_accept_inbound_channels {
4161-
let mut pending_events = self.pending_events.lock().unwrap();
4162-
pending_events.push(
4163-
events::Event::OpenChannelRequest {
4164-
open_channel_request_info: OpenChannelRequestInfo {
4165-
counterparty_node_id: counterparty_node_id.clone(),
4166-
their_features: their_features.clone(),
4167-
msg: msg.clone()
4168-
},
4169-
}
4170-
);
4171-
return Ok(())
4172-
}
4173-
4174-
return self.internal_create_requested_channel(counterparty_node_id, their_features, msg);
4175-
}
4176-
4177-
fn internal_create_requested_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal>{
4178-
let channel = Channel::new_from_req(&self.fee_estimator, &self.keys_manager, counterparty_node_id.clone(),
4139+
let mut channel = Channel::new_from_req(&self.fee_estimator, &self.keys_manager, counterparty_node_id.clone(),
41794140
&their_features, msg, 0, &self.default_configuration, self.best_block.read().unwrap().height(), &self.logger)
41804141
.map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
41814142
let mut channel_state_lock = self.channel_state.lock().unwrap();
41824143
let channel_state = &mut *channel_state_lock;
41834144
match channel_state.by_id.entry(channel.channel_id()) {
41844145
hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!".to_owned(), msg.temporary_channel_id.clone())),
41854146
hash_map::Entry::Vacant(entry) => {
4147+
if !self.default_configuration.manually_accept_inbound_channels {
4148+
channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
4149+
node_id: counterparty_node_id.clone(),
4150+
msg: channel.get_accept_channel(),
4151+
});
4152+
} else {
4153+
let mut pending_events = self.pending_events.lock().unwrap();
4154+
pending_events.push(
4155+
events::Event::OpenChannelRequest {
4156+
temporary_channel_id: msg.temporary_channel_id.clone(),
4157+
counterparty_node_id: counterparty_node_id.clone(),
4158+
chain_hash: msg.chain_hash.clone(),
4159+
funding_satoshis: msg.funding_satoshis,
4160+
push_msat: msg.push_msat,
4161+
}
4162+
);
4163+
}
4164+
4165+
entry.insert(channel);
4166+
}
4167+
}
4168+
Ok(())
4169+
}
4170+
4171+
fn accept_requested_channel(&self, temporary_channel_id: [u8; 32]) -> Result<(), APIError> {
4172+
let mut channel_state_lock = self.channel_state.lock().unwrap();
4173+
let channel_state = &mut *channel_state_lock;
4174+
match channel_state.by_id.entry(temporary_channel_id) {
4175+
hash_map::Entry::Occupied(mut channel) => {
4176+
if !channel.get().inbound_is_awaiting_accept() {
4177+
return Err(APIError::APIMisuseError { err: "The channel isn't currently awaiting to be accepted.".to_owned() });
4178+
}
41864179
channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
4187-
node_id: counterparty_node_id.clone(),
4188-
msg: channel.get_accept_channel(),
4180+
node_id: channel.get().get_counterparty_node_id(),
4181+
msg: channel.get_mut().get_accept_channel(),
41894182
});
4190-
entry.insert(channel);
4183+
}
4184+
hash_map::Entry::Vacant(_) => {
4185+
return Err(APIError::ChannelUnavailable { err: "Can't accept a channel that doesn't exist".to_owned() });
41914186
}
41924187
}
41934188
Ok(())
41944189
}
41954190

4191+
fn internal_get_counterparty_node_id(&self, channel_id: [u8; 32]) -> Option<PublicKey> {
4192+
match self.channel_state.lock().unwrap().by_id.entry(channel_id) {
4193+
hash_map::Entry::Occupied(channel) => {
4194+
return Some(channel.get().get_counterparty_node_id());
4195+
}
4196+
hash_map::Entry::Vacant(_) => {
4197+
return None;
4198+
}
4199+
}
4200+
}
4201+
41964202
fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
41974203
let (value, output_script, user_id) = {
41984204
let mut channel_lock = self.channel_state.lock().unwrap();

lightning/src/util/events.rs

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
//! few other things.
1616
1717
use chain::keysinterface::SpendableOutputDescriptor;
18-
use ln::channelmanager::{PaymentId, OpenChannelRequestInfo};
18+
use ln::channelmanager::{PaymentId};
1919
use ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
2020
use ln::msgs;
2121
use ln::msgs::DecodeError;
@@ -29,7 +29,7 @@ use bitcoin::blockdata::script::Script;
2929
use bitcoin::hashes::Hash;
3030
use bitcoin::hashes::sha256::Hash as Sha256;
3131
use bitcoin::secp256k1::key::PublicKey;
32-
32+
use bitcoin::hash_types::{BlockHash};
3333
use io;
3434
use prelude::*;
3535
use core::time::Duration;
@@ -412,16 +412,21 @@ pub enum Event {
412412
/// [`ChannelManager::respond_to_open_channel_request`]: crate::ln::channelmanager::ChannelManager::respond_to_open_channel_request
413413
/// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
414414
OpenChannelRequest {
415-
/// The OpenChannelRequestInfo holds the information required to handle an open channel request.
416-
/// The struct includes the [`msgs::OpenChannel`] message, which holds the information that may be relevant to
417-
/// the user in order to decide whether the request should be accepted or rejected.
415+
/// The temporary channel ID of the channel requested to be opened.
418416
///
419-
/// When accepting or rejecting to the request, the entire stuct should be passed back to the ChannelManager
417+
/// When accepting or rejecting to the request, the `temporary_channel_id` should be passed back to the ChannelManager
420418
/// with [`ChannelManager::respond_to_open_channel_request`].
421419
///
422-
/// [`msgs::OpenChannel`]: crate::ln::msgs::OpenChannel
423420
/// [`ChannelManager::respond_to_open_channel_request`]: crate::ln::channelmanager::ChannelManager::respond_to_open_channel_request
424-
open_channel_request_info: OpenChannelRequestInfo,
421+
temporary_channel_id: [u8; 32],
422+
/// The node_id of the counterparty requesting to open the channel.
423+
counterparty_node_id: PublicKey,
424+
/// The genesis hash of the blockchain where the channel is requested to be opened.
425+
chain_hash: BlockHash,
426+
/// The channel value of the requested channel.
427+
funding_satoshis: u64,
428+
/// The amount to push to the counterparty if the channel request is accepted, in milli-satoshi.
429+
push_msat: u64,
425430
},
426431
}
427432

@@ -535,11 +540,10 @@ impl Writeable for Event {
535540
(2, payment_hash, required),
536541
})
537542
},
538-
&Event::OpenChannelRequest { ref open_channel_request_info } => {
539-
11u8.write(writer)?;
540-
write_tlv_fields!(writer, {
541-
(0, open_channel_request_info, required),
542-
})
543+
&Event::OpenChannelRequest { .. } => {
544+
16u8.write(writer)?;
545+
// We never write the OpenChannelRequest events as, upon disconnection, peers
546+
// drop any channels which have not yet exchanged funding_signed.
543547
},
544548
// Note that, going forward, all new events must only write data inside of
545549
// `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write

0 commit comments

Comments
 (0)