diff --git a/lightning/src/ln/channel.rs b/lightning/src/ln/channel.rs index 7d4ce2ddb57..eb5d8b35758 100644 --- a/lightning/src/ln/channel.rs +++ b/lightning/src/ln/channel.rs @@ -6833,6 +6833,21 @@ impl OutboundV2Channel { require_confirmed_inputs: if self.context.we_require_confirmed_inputs { Some(()) } else { None }, } } + + pub fn accept_channel_v2(&mut self, msg: &msgs::AcceptChannelV2, default_limits: &ChannelHandshakeLimits, + their_features: &InitFeatures) -> Result<(), ChannelError> { + self.context.common.do_accept_channel_checks( + default_limits, their_features, msg.dust_limit_satoshis, get_v2_channel_reserve_satoshis( + msg.funding_satoshis + self.context.our_funding_satoshis, msg.dust_limit_satoshis), + msg.to_self_delay, msg.max_accepted_htlcs, msg.htlc_minimum_msat, + msg.max_htlc_value_in_flight_msat, msg.minimum_depth, &msg.channel_type, + &msg.shutdown_scriptpubkey, msg.funding_pubkey, msg.revocation_basepoint, msg.payment_basepoint, + msg.delayed_payment_basepoint, msg.htlc_basepoint, msg.first_per_commitment_point)?; + + // TODO(dual_funding): V2 Establishment Checks + + Ok(()) + } } // A not-yet-funded inbound (from counterparty) channel using V2 channel establishment. diff --git a/lightning/src/ln/channelmanager.rs b/lightning/src/ln/channelmanager.rs index 217871ffd73..976e0e7a1ca 100644 --- a/lightning/src/ln/channelmanager.rs +++ b/lightning/src/ln/channelmanager.rs @@ -28,7 +28,7 @@ use bitcoin::hash_types::{BlockHash, Txid}; use bitcoin::secp256k1::{SecretKey,PublicKey}; use bitcoin::secp256k1::Secp256k1; -use bitcoin::{LockTime, secp256k1, Sequence}; +use bitcoin::{LockTime, secp256k1, Sequence, Script}; use crate::chain; use crate::chain::{Confirm, ChannelMonitorUpdateStatus, Watch, BestBlock}; @@ -80,6 +80,9 @@ use core::ops::Deref; pub use crate::ln::outbound_payment::{PaymentSendFailure, Retry, RetryableSendFailure, RecipientOnionFields}; use crate::ln::script::ShutdownScript; +// Re-export this for use in the public API. +pub use super::channel::DualFundingUtxo; + // We hold various information about HTLC relay in the HTLC objects in Channel itself: // // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should @@ -2250,6 +2253,106 @@ where Ok(temporary_channel_id) } + + /// Creates a new outbound dual-funded channel to the given remote node and with the given value + /// contributed by us. + /// + /// `user_channel_id` will be provided back as in + /// [`Event::FundingGenerationReady::user_channel_id`] to allow tracking of which events + /// correspond with which `create_channel` call. Note that the `user_channel_id` defaults to a + /// randomized value for inbound channels. `user_channel_id` has no meaning inside of LDK, it + /// is simply copied to events and otherwise ignored. + /// + /// `funnding_satoshis` is the amount we are contributing to the channel. + /// Raises [`APIError::APIMisuseError`] when `funding_satoshis` > 2**24. + /// + /// The `funding_inputs` parameter accepts UTXOs in the form of [`DualFundingUtxo`] which will + /// be used to contribute `funding_satoshis` towards the channel (minus any mining fees due). + /// Raises [`APIError::APIMisuseError`] if the total value of the provided `funding_inputs` is + /// less than `funding_satoshis`. + // TODO(dual_funding): Describe error relating to inputs not being able to cover fees payable by us. + /// + /// The `change_script_pubkey` parameter provides a destination for the change output if any value + /// is remaining (greater than dust) after `funding_satoshis` and fees payable are satisfied by + /// `funding_inputs` + // TODO(dual_funding): We could allow a list of such outputs to be provided so that the user may + /// be able to do some more interesting things at the same time as funding a channel, like making + /// some low priority on-chain payment. + /// + /// The `funding_conf_target` parameter sets the priority of the funding transaction for appropriate + /// fee estimation. If `None`, then [`ConfirmationTarget::Normal`] is used. + /// + /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be opened due to failing to + /// generate a shutdown scriptpubkey or destination script set by + /// [`SignerProvider::get_shutdown_scriptpubkey`] or [`SignerProvider::get_destination_script`]. + /// + /// Note that we do not check if you are currently connected to the given peer. If no + /// connection is available, the outbound `open_channel` message may fail to send, resulting in + /// the channel eventually being silently forgotten (dropped on reload). + /// + /// Returns the new Channel's temporary `channel_id`. This ID will appear as + /// [`Event::FundingGenerationReady::temporary_channel_id`] and in + /// [`ChannelDetails::channel_id`] until after + /// [`ChannelManager::funding_transaction_generated`] is called, swapping the Channel's ID for + /// one derived from the funding transaction's TXID. If the counterparty rejects the channel + /// immediately, this temporary ID will appear in [`Event::ChannelClosed::channel_id`]. + /// + /// [`Event::FundingGenerationReady::user_channel_id`]: events::Event::FundingGenerationReady::user_channel_id + /// [`Event::FundingGenerationReady::temporary_channel_id`]: events::Event::FundingGenerationReady::temporary_channel_id + /// [`Event::ChannelClosed::channel_id`]: events::Event::ChannelClosed::channel_id + /// [`ConfirmationTarget::Normal`]: chain::chaininterface::ConfirmationTarget + pub fn create_dual_funded_channel(&self, their_network_key: PublicKey, funding_satoshis: u64, + funding_inputs: Vec, change_script_pubkey: Script, funding_conf_target: Option, + user_channel_id: u128, override_config: Option) -> Result<[u8; 32], APIError> + { + Self::dual_funding_amount_checks(funding_satoshis, &funding_inputs)?; + + let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); + // We want to make sure the lock is actually acquired by PersistenceNotifierGuard. + debug_assert!(&self.total_consistency_lock.try_write().is_err()); + + let per_peer_state = self.per_peer_state.read().unwrap(); + + let peer_state_mutex = per_peer_state.get(&their_network_key) + .ok_or_else(|| APIError::APIMisuseError{ err: format!("Not connected to node: {}", their_network_key) })?; + + let mut peer_state = peer_state_mutex.lock().unwrap(); + let channel = { + let outbound_scid_alias = self.create_and_insert_outbound_scid_alias(); + let their_features = &peer_state.latest_features; + let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration }; + match OutboundV2Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider, their_network_key, + their_features, funding_satoshis, funding_inputs, change_script_pubkey, user_channel_id, config, + self.best_block.read().unwrap().height(), outbound_scid_alias, true, funding_conf_target) + { + Ok(res) => res, + Err(e) => { + self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias); + return Err(e); + }, + } + }; + let res = channel.get_open_channel_v2(self.genesis_hash.clone()); + + let temporary_channel_id = channel.context.common.channel_id(); + match peer_state.outbound_v2_channel_by_id.entry(temporary_channel_id) { + hash_map::Entry::Occupied(_) => { + if cfg!(fuzzing) { + return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() }); + } else { + panic!("RNG is bad???"); + } + }, + hash_map::Entry::Vacant(entry) => { entry.insert(channel); } + } + + peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannelV2 { + node_id: their_network_key, + msg: res, + }); + Ok(temporary_channel_id) + } + fn list_funded_channels_with_filter::Signer>)) -> bool + Copy>(&self, f: Fn) -> Vec { // Allocate our best estimate of the number of channels we have in the `res` // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without @@ -5172,6 +5275,130 @@ where Ok(()) } + /// Accepts a request to open a dual-funded channel after an [`Event::OpenChannelV2Request`]. + /// + /// The `temporary_channel_id` parameter indicates which inbound channel should be accepted, + /// and the `counterparty_node_id` parameter is the id of the peer which has requested to open + /// the channel. + /// + /// The `user_channel_id` parameter will be provided back in + /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond + /// with which `accept_inbound_dual_funded_channel`/`accept_inbound_dual_funded_channel_from_trusted_peer_0conf` call. + /// + /// `funnding_satoshis` is the amount we are contributing to the channel. + /// Raises [`APIError::APIMisuseError`] when `funding_satoshis` > 2**24. + /// + /// The `funding_inputs` parameter accepts UTXOs in the form of [`DualFundingUtxo`] which will + /// be used to contribute `funding_satoshis` towards the channel (minus any mining fees due). + /// Raises [`APIError::APIMisuseError`] if the total value of the provided `funding_inputs` is + /// less than `funding_satoshis`. + // TODO(dual_funding): Describe error relating to inputs not being able to cover fees payable by us. + /// + /// The `change_script_pubkey` parameter provides a destination for the change output if any value + /// is remaining (greater than dust) after `funding_satoshis` and fees payable are satisfied by + /// `funding_inputs` + // TODO(dual_funding): We could allow a list of such outputs to be provided so that the user may + /// be able to do some more interesting things at the same time as funding. + + /// Note that this method will return an error and reject the channel, if it requires support + /// for zero confirmations. + // TODO(dual_funding): Discussion on complications with 0conf dual-funded channels where "locking" + // of UTXOs used for funding would be required and other issues. + // See: https://lists.linuxfoundation.org/pipermail/lightning-dev/2023-May/003920.html + /// + /// + /// [`Event::OpenChannelV2Request`]: events::Event::OpenChannelV2Request + /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id + pub fn accept_inbound_dual_funded_channel(&self, temporary_channel_id: &[u8; 32], + counterparty_node_id: &PublicKey, user_channel_id: u128, funding_satoshis: u64, + funding_inputs: Vec, change_script_pubkey: Script) -> Result<(), APIError> { + self.do_accept_inbound_dual_funded_channel(temporary_channel_id, counterparty_node_id, + user_channel_id, funding_satoshis, funding_inputs, change_script_pubkey) + } + + fn do_accept_inbound_dual_funded_channel(&self, temporary_channel_id: &[u8; 32], + counterparty_node_id: &PublicKey, user_channel_id: u128, funding_satoshis: u64, + funding_inputs: Vec, change_script_pubkey: Script, + ) -> Result<(), APIError> { + Self::dual_funding_amount_checks(funding_satoshis, &funding_inputs)?; + + let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); + + let peers_without_funded_channels = + self.peers_without_funded_channels(|peer| { peer.total_channel_count() > 0 }); + let per_peer_state = self.per_peer_state.read().unwrap(); + let peer_state_mutex = per_peer_state.get(counterparty_node_id) + .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?; + let mut peer_state_lock = peer_state_mutex.lock().unwrap(); + let peer_state = &mut *peer_state_lock; + let is_only_peer_channel = peer_state.total_channel_count() == 1; + match peer_state.inbound_v2_channel_by_id.entry(temporary_channel_id.clone()) { + hash_map::Entry::Occupied(mut channel) => { + if !channel.get().is_awaiting_accept() { + return Err(APIError::APIMisuseError { err: "The channel isn't currently awaiting to be accepted.".to_owned() }); + } + // TODO(dual_funding): Accept zero-conf dual-funded channels. + // See: https://lists.linuxfoundation.org/pipermail/lightning-dev/2023-May/003920.html + if channel.get().context.common.get_channel_type().requires_zero_conf() { + let send_msg_err_event = events::MessageSendEvent::HandleError { + node_id: channel.get().context.common.get_counterparty_node_id(), + action: msgs::ErrorAction::SendErrorMessage{ + msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "No zero confirmation channels accepted".to_owned(), } + } + }; + peer_state.pending_msg_events.push(send_msg_err_event); + let _ = remove_channel!(self, channel); + return Err(APIError::APIMisuseError { err: "Zero-conf dual-funded channels are not yet accepted.".to_owned() }); + } else { + // If this peer already has some channels, a new channel won't increase our number of peers + // with unfunded channels, so as long as we aren't over the maximum number of unfunded + // channels per-peer we can accept channels from a peer with existing ones. + if is_only_peer_channel && peers_without_funded_channels >= MAX_UNFUNDED_CHANNEL_PEERS { + let send_msg_err_event = events::MessageSendEvent::HandleError { + node_id: channel.get().context.common.get_counterparty_node_id(), + action: msgs::ErrorAction::SendErrorMessage{ + msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "Have too many peers with unfunded channels, not accepting new ones".to_owned(), } + } + }; + peer_state.pending_msg_events.push(send_msg_err_event); + let _ = remove_channel!(self, channel); + return Err(APIError::APIMisuseError { err: "Too many peers with unfunded channels, refusing to accept new ones".to_owned() }); + } + } + + channel.get_mut().context.our_change_script_pubkey = change_script_pubkey; + + peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannelV2 { + node_id: channel.get().context.common.get_counterparty_node_id(), + msg: channel.get_mut().accept_inbound_dual_funded_channel(user_channel_id), + }); + } + hash_map::Entry::Vacant(_) => { + return Err(APIError::ChannelUnavailable { err: format!("Channel with id {} not found for the passed counterparty node_id {}", log_bytes!(*temporary_channel_id), counterparty_node_id) }); + } + } + Ok(()) + } + + /// Checks related to inputs and their amounts related to establishing dual-funded channels. + fn dual_funding_amount_checks(funding_satoshis: u64, funding_inputs: &Vec) + -> Result<(), APIError> { + if funding_satoshis < 1000 { + return Err(APIError::APIMisuseError { + err: format!("Funding amount must be at least 1000 satoshis. It was {} sats", funding_satoshis), + }); + } + + let total_input_satoshis: u64 = funding_inputs.iter().map(|input| input.output.value).sum(); + if total_input_satoshis < funding_satoshis { + Err(APIError::APIMisuseError { + err: format!("Total value of funding inputs must be at least funding amount. It was {} sats", + total_input_satoshis) }) + } else { + Ok(()) + } + } + /// Gets the number of peers which match the given filter and do not have any funded, outbound, /// or 0-conf channels. /// @@ -5341,6 +5568,38 @@ where Ok(()) } + fn internal_accept_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) -> Result<(), MsgHandleErrInternal> { + let per_peer_state = self.per_peer_state.read().unwrap(); + let peer_state_mutex = per_peer_state.get(counterparty_node_id) + .ok_or_else(|| { + debug_assert!(false); + MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.temporary_channel_id) + })?; + let mut peer_state_lock = peer_state_mutex.lock().unwrap(); + let peer_state = &mut *peer_state_lock; + match peer_state.outbound_v2_channel_by_id.entry(msg.temporary_channel_id) { + hash_map::Entry::Occupied(mut chan) => { + let res = chan.get_mut().accept_channel_v2(&msg, &self.default_configuration.channel_handshake_limits, &peer_state.latest_features); + if let Err(err) = res { + // If we get an error at this point, the outbound channel should just be discarded and + // removed from maps as it's safe to do so. + update_maps_on_chan_removal!(self, &chan.get().context()); + let user_id = chan.get().context.common.get_user_id(); + let shutdown_res = chan.get_mut().context.common.force_shutdown(false); + chan.remove_entry(); + return Err(MsgHandleErrInternal::from_finish_shutdown(format!("{}", err), + msg.temporary_channel_id, user_id, shutdown_res, None)); + }; + // TODO(dual_funding): Begin Interactive Transaction Construction + // Here we will initialize the `InteractiveTxConstructor` and delegate + // the actual message handling for the interactive transaction protocol + // to its state machine. + Ok(()) + }, + hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.temporary_channel_id)), + } + } + fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> { let best_block = *self.best_block.read().unwrap(); @@ -7012,9 +7271,8 @@ where } fn handle_accept_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) { - let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close( - "Dual-funded channels not supported".to_owned(), - msg.temporary_channel_id.clone())), *counterparty_node_id); + let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self); + let _ = handle_error!(self, self.internal_accept_channel_v2(counterparty_node_id, msg), *counterparty_node_id); } fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) { @@ -10201,6 +10459,9 @@ mod tests { _ => panic!("expected BroadcastChannelUpdate event"), } } + + // Dual-funding: V2 Channel Establishment Tests + // TODO(dual_funding): Complete these. } #[cfg(ldk_bench)]